text
stringlengths
10
2.72M
public class MethodCall { public static void main(String[] args) { System.out.println("Called before 1"); method1(); System.out.println("called after 1"); } public static void method1() { System.out.println("called before 2 from 1"); method2(); System.out.println("called after 2 from 1"); } public static void method2() { System.out.println("Executing 2 from 1"); } }
import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.text.DateFormat; public class ContradoService { private PagamentoOnline pagamentoOnline; public ContradoService(PagamentoOnline pagamentoOnline){ this.pagamentoOnline = pagamentoOnline; } public void processaContrato(Contrato contrato, int meses){ //valor de cada parcela double parcela = contrato.getValor_total() / meses; for(int i = 1; i <= meses; i++){ double valorJuros = parcela + pagamentoOnline.juros(parcela, i); double valorTotal = valorJuros + pagamentoOnline.taxaDePagamento(valorJuros); Date data = addMounths(contrato.getData_contrato(), i); Locale brasil = new Locale("pt", "BR"); DateFormat f2 = DateFormat.getDateInstance(DateFormat.FULL, brasil); System.out.println("Parcela: "+valorTotal); System.out.println("Vencimento: "+f2.format(data)); } } private Date addMounths(Date data, int n) { Calendar cal = Calendar.getInstance(); cal.setTime(data); cal.add(Calendar.MONTH, n); return cal.getTime(); } }
package com.csc214.rebeccavandyke.socialnetworkingproject2.database; /* * Rebecca Van Dyke * rvandyke@u.rochester.edu * CSC 214 Project 2 * TA: Julian Weiss */ public class SocialNetworkDBSchema { public static final int VERSION = 1; public static final String DATABASE_NAME = "social_network.db"; public static final class UserTable { public static final String NAME = "users"; public static final class Cols { public static final String ID = "id"; public static final String USERNAME = "username"; public static final String PASSWORD = "password"; public static final String FULLNAME = "full_name"; public static final String EMAIL = "email"; public static final String BIRTHDATE = "birthdate"; public static final String HOMETOWN = "hometown"; public static final String PHOTO = "photo"; public static final String BIO = "bio"; public static final String USERS_FAVORITED = "users_favorited"; } //end class Cols } //end class UserTable public static final class PostTable { public static final String NAME = "posts"; public static final class Cols { public static final String ID = "id"; public static final String TIMESTAMP = "timestamp"; public static final String USER = "user"; public static final String POST_TEXT ="post_text"; public static final String POST_PHOTO = "post_photo"; } //end class Cols } //end class PostTable } //end class SocialNetworkDBSchema
package org.example.config; import lombok.SneakyThrows; import org.example.ApplicationContext; import org.example.annotation.InjectByType; import java.lang.reflect.Field; public class InjectByTypeAnnontaionObjectConfigurator implements ObjectConfigurator { @SneakyThrows @Override public void configure(Object object, ApplicationContext context) { for (Field field : object.getClass().getDeclaredFields()) { if (field.isAnnotationPresent(InjectByType.class)) { field.setAccessible(true); Object value = context.getObject(field.getType()); field.set(object, value); } } } }
public class Eje8 { public static void main(String[] args) { int inc = 0; for (int i=0;i<=100;i++){ if (i%3 == 0){ System.out.println(i); inc++; } } System.out.println(inc); } }
package algo_ad.day1; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class KnapscakTest { //static int [][] goods = {{25,10},{10,9},{10,5}}; //static int [][] goods = {{25,10},{10,9},{10,5}}; static int [][] goods = {{5,50},{10,60},{20,140}}; private static List<int[]> list = new ArrayList<>(); public static void main(String[] args) { // 위 조건을 0-1 Knapsack문제를 처리하시오 //subSet(0,0); int weight = 30; int max =0; for (int i = 0; i < (1<<goods.length); i++) { List<Good> subset = new ArrayList<>(); int sumw =0; int sump =0; for (int j = 0; j < goods.length; j++) { if((i& (1<<j))>0) { if(sumw + goods[j][0] >weight) { break; }else { Good good = new Good(goods[j][0], goods[j][1]); subset.add(good); sumw += good.w; sump += good.p; } } } System.out.println(subset); max =Math.max(max, sump); } System.out.println(max); } public static class Good { int w, p; public Good(int w, int p) { this.w = w; this.p = p; } @Override public String toString() { return "Good [w=" + w + ", p=" + p + "]"; } } /*public static void subSet(int r , int k) { int sum =0; for (int i = 0; i < list.size(); i++) { sum+=list.get(i)[0]; if(sum>) } System.out.println(); if(r == goods.length) { return; } for (int i = k; i < goods.length; i++) { list.add(goods[i]); subSet(r+1,i+1); list.remove(list.size()-1); } }*/ }
package com.tencent.mm.protocal.c; import com.tencent.mm.bk.a; public final class cgg extends a { public int otY; public int rRb; public int rUA; public int rUB; public String rUC; public int riv; protected final int a(int i, Object... objArr) { int fQ; if (i == 0) { f.a.a.c.a aVar = (f.a.a.c.a) objArr[0]; aVar.fT(1, this.rRb); aVar.fT(2, this.riv); aVar.fT(3, this.otY); if (this.rUC != null) { aVar.g(4, this.rUC); } aVar.fT(5, this.rUB); aVar.fT(6, this.rUA); return 0; } else if (i == 1) { fQ = ((f.a.a.a.fQ(1, this.rRb) + 0) + f.a.a.a.fQ(2, this.riv)) + f.a.a.a.fQ(3, this.otY); if (this.rUC != null) { fQ += f.a.a.b.b.a.h(4, this.rUC); } return (fQ + f.a.a.a.fQ(5, this.rUB)) + f.a.a.a.fQ(6, this.rUA); } else if (i == 2) { f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler); for (fQ = a.a(aVar2); fQ > 0; fQ = a.a(aVar2)) { if (!super.a(aVar2, this, fQ)) { aVar2.cJS(); } } return 0; } else if (i != 3) { return -1; } else { f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0]; cgg cgg = (cgg) objArr[1]; switch (((Integer) objArr[2]).intValue()) { case 1: cgg.rRb = aVar3.vHC.rY(); return 0; case 2: cgg.riv = aVar3.vHC.rY(); return 0; case 3: cgg.otY = aVar3.vHC.rY(); return 0; case 4: cgg.rUC = aVar3.vHC.readString(); return 0; case 5: cgg.rUB = aVar3.vHC.rY(); return 0; case 6: cgg.rUA = aVar3.vHC.rY(); return 0; default: return -1; } } } }
package com.kodilla.restaurantfrontend.service; import com.kodilla.restaurantfrontend.ProductType; import com.kodilla.restaurantfrontend.domain.Product; import java.math.BigDecimal; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; public class ProductService { private Set<Product> products; private static ProductService productService; private ProductService() { this.products = exampleData(); } public static ProductService getInstance() { if (productService == null) { productService = new ProductService(); } return productService; } public Set getProducts() { return products; } public void addProduct(Product product) { this.products.add(product); } private Set exampleData() { Set<Product> products = new HashSet<>(); products.add(new Product("Pizza", "32", "true", "1", ProductType.MAIN_COURSE)); products.add(new Product("Pomodoro", "12", "true", "1", ProductType.SOUP)); products.add(new Product("Ice", "22", "true", "2", ProductType.DESSERT)); products.add(new Product("Coca-cola", "6", "true", "2", ProductType.DRINKS)); return products; } public Set findByProductName(String productName) { return products.stream() .filter(product -> product.getProductName().contains(productName)) .collect(Collectors.toSet()); } public Set findByProductPrice(String price) { return products.stream() .filter(product -> product.getPrice().contains(price)) .collect(Collectors.toSet()); } public void save(Product product) { this.products.add(product); } public void delete(Product product) { this.products.remove(product); } public Integer addQuantity(Integer m) { products.stream().map(n -> n.getQuantity()).map(n -> n + 1).collect(Collectors.toList()); return getProducts().size(); } }
/* * 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 boletin10; /** * * @author Brian */ public class subiendo { // ahora parriba // ahora pabajo }
/* * William Orozco, 13386 * Dulce Chacon, 13463 * Luis Gomez, 13135 * Programa para contar diferentes tipos de palabras en un archivo de texto. * * HOJA DE TRABAJO 8 * * Se uso codigo de referencia adjuntado con la hoja de trabajo */ /* * Clase que sirve para instanciar. */ //package HT8; /*Se importan las clases necesarias de java*/ import java.util.TreeMap; import java.util.Hashtable; /*Esta clase implementa la interfaz wordSet, proporcionada con la hoja*/ public class SelectSet implements WordSet { /* Se usan las implementaciones de: * 1. RedBlackTree * 2. SplayTree * 3. HashTable * 4. TreeMap de JCF */ int tipoSet =0; Integer llave = 0; /*llave para el hash table*/ private SimpleSet estructura1; private RedBlackTree estructura2; private SplayTree estructura3; private Hashtable<Integer, Word> estructura4; private TreeMap estructura5; private Word palabra; /*Constructor, que instancia de acuerdo con el tipo de set*/ public SelectSet(int tipo) { tipoSet = tipo; if (tipo == 1) { estructura1 = new SimpleSet(); } else if (tipo == 2) { estructura2 = new RedBlackTree(new Word()); } else if (tipo == 3) { estructura3 = new SplayTree(); } else if (tipo == 4) { estructura4 = new Hashtable<Integer, Word>(); } else if (tipo == 5) { estructura5 = new TreeMap(); } } /* Método para agregar palabras*/ public void add(Word wordObject) throws NullPointerException { if (tipoSet == 1) { estructura1.add(wordObject); } else if (tipoSet == 2) { estructura2.insert(wordObject); } else if (tipoSet == 3) { estructura3.insert(wordObject); } else if (tipoSet == 4) { if (estructura4.isEmpty()) llave=0; else llave=estructura4.size(); estructura4.put(llave, wordObject); //llave++; } else if (tipoSet == 5) { if (estructura5.isEmpty()) llave=0; else llave=estructura5.size(); estructura5.put(llave, wordObject); //llave++; } } /*Método para obtener palabras, retornando segun el tipo de estructura*/ public Word get(Word word) { //llave=0; if (tipoSet == 1) { palabra = estructura1.get(word); } else if (tipoSet == 2) { palabra=(Word)estructura2.find(word); } else if (tipoSet == 3) { palabra=(Word)estructura3.find(word); } else if (tipoSet == 4) { if (estructura4.contains(word)){ palabra=word; //palabra=(Word)estructura4.get(llave); //llave++; } } else if (tipoSet == 5) { if (estructura5.containsValue(word)){ palabra=word; //palabra=(Word)estructura5.get(llave); //llave++; } } return palabra; } }
/******************************************************************************* * Copyright (c) 2012 Jens Kristian Villadsen. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * Jens Kristian Villadsen - initial API and implementation ******************************************************************************/ package gmusic.api.impl; import gmusic.api.comm.FormBuilder; import gmusic.api.comm.HttpUrlConnector; import gmusic.api.comm.JSON; import gmusic.api.interfaces.IGoogleHttpClient; import gmusic.api.interfaces.IGoogleMusicAPI; import gmusic.api.interfaces.IJsonDeserializer; import gmusic.api.model.AddPlaylist; import gmusic.api.model.DeletePlaylist; import gmusic.api.model.Playlist; import gmusic.api.model.Playlists; import gmusic.api.model.QueryResponse; import gmusic.api.model.Song; import gmusic.api.model.SongUrl; import gmusic.model.Tune; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import com.google.common.base.Strings; import com.google.common.io.Files; import com.google.common.io.Resources; public class GoogleMusicAPI implements IGoogleMusicAPI { protected final IGoogleHttpClient client; protected final IJsonDeserializer deserializer; protected final File storageDirectory; public GoogleMusicAPI() { this(new HttpUrlConnector(), new JSON(), new File(".")); } public GoogleMusicAPI(IGoogleHttpClient httpClient, IJsonDeserializer jsonDeserializer, File file) { client = httpClient; deserializer = jsonDeserializer; storageDirectory = file; } @Override public final void login(String email, String password) throws IOException, URISyntaxException, InvalidCredentialsException { Map<String, String> fields = new HashMap<String, String>(); fields.put("service", "sj"); fields.put("Email", email); fields.put("Passwd", password); FormBuilder form = new FormBuilder(); form.addFields(fields); form.close(); try { client.dispatchPost(new URI(HTTPS_WWW_GOOGLE_COM_ACCOUNTS_CLIENT_LOGIN), form); } catch(IllegalStateException ise) { throw new InvalidCredentialsException(ise, "Provided credentials: '" + email + "' and '" + password + "' where insufficient"); } } @Override public final Collection<Song> getAllSongs() throws IOException, URISyntaxException { return getSongs(""); } @Override public final AddPlaylist addPlaylist(String playlistName) throws Exception { Map<String, String> fields = new HashMap<String, String>(); fields.put("json", "{\"title\":\"" + playlistName + "\"}"); FormBuilder form = new FormBuilder(); form.addFields(fields); form.close(); return deserializer.deserialize(client.dispatchPost(new URI(HTTPS_PLAY_GOOGLE_COM_MUSIC_SERVICES_ADDPLAYLIST), form), AddPlaylist.class); } @Override public final Playlists getAllPlaylists() throws IOException, URISyntaxException { return deserializer.deserialize(getPlaylistAssist("{}"), Playlists.class); } @Override public final Playlist getPlaylist(String plID) throws IOException, URISyntaxException { return deserializer.deserialize(getPlaylistAssist("{\"id\":\"" + plID + "\"}"), Playlist.class); } protected final URI getTuneURL(Tune tune) throws URISyntaxException, IOException { return new URI(deserializer.deserialize(client.dispatchGet(new URI(String.format(HTTPS_PLAY_GOOGLE_COM_MUSIC_PLAY_SONGID, tune.getId()))), SongUrl.class).getUrl()); } @Override public URI getSongURL(Song song) throws URISyntaxException, IOException { return getTuneURL(song); } @Override public final DeletePlaylist deletePlaylist(String id) throws Exception { Map<String, String> fields = new HashMap<String, String>(); fields.put("json", "{\"id\":\"" + id + "\"}"); FormBuilder form = new FormBuilder(); form.addFields(fields); form.close(); return deserializer.deserialize(client.dispatchPost(new URI(HTTPS_PLAY_GOOGLE_COM_MUSIC_SERVICES_DELETEPLAYLIST), form), DeletePlaylist.class); } private final String getPlaylistAssist(String jsonString) throws IOException, URISyntaxException { Map<String, String> fields = new HashMap<String, String>(); fields.put("json", jsonString); FormBuilder builder = new FormBuilder(); builder.addFields(fields); builder.close(); return client.dispatchPost(new URI(HTTPS_PLAY_GOOGLE_COM_MUSIC_SERVICES_LOADPLAYLIST), builder); } private final Collection<Song> getSongs(String continuationToken) throws IOException, URISyntaxException { Collection<Song> chunkedCollection = new ArrayList<Song>(); // Map<String, String> fields = new HashMap<String, String>(); // fields.put("json", "{\"continuationToken\":\"" + continuationToken + "\"}"); FormBuilder form = new FormBuilder(); // form.addFields(fields); form.close(); String response = client.dispatchPost(new URI(HTTPS_PLAY_GOOGLE_COM_MUSIC_SERVICES_LOADALLTRACKS), form); int start = response.indexOf("([[") + 4; int end = response.indexOf("window.parent['slat_progress'](1.0);"); response = response.substring(start, end); String[] responses = response.split("\\]\\r?\\n,\\["); for(String r : responses) { String[] values = splitNotInQuotes(r); Song s = new Song(); s.setId(values[0]); s.setTitle(values[1]); s.setName(values[1]); if(!Strings.isNullOrEmpty(values[2])) { s.setAlbumArtUrl("https:" + values[2]); } s.setArtist(values[3]); s.setAlbum(values[4]); s.setAlbumArtist(values[5]); s.setGenre(values[11]); s.setDurationMillis(toLong(values[13])); s.setType(toInt(values[16])); s.setYear(toInt(values[18])); s.setPlaycount(toInt(values[22])); s.setRating(values[23]); if(!Strings.isNullOrEmpty(values[24])) { s.setCreationDate(Float.valueOf(values[24]) / 1000); } if(!Strings.isNullOrEmpty(values[36])) { s.setUrl("https:" + values[36]); } chunkedCollection.add(s); } return chunkedCollection; } private String[] splitNotInQuotes(String r) { return r.replace("\"", "").split(","); } private int toInt(String str) { int retInt; try { retInt = Integer.valueOf(str); } catch(NumberFormatException e) { retInt = 0; } return retInt; } private long toLong(String str) { long retLong; try { retLong = Long.valueOf(str); } catch(NumberFormatException e) { retLong = 0; } return retLong; } @Override public Collection<File> downloadSongs(Collection<Song> songs) throws MalformedURLException, IOException, URISyntaxException { Collection<File> files = new ArrayList<File>(); for(Song song : songs) { files.add(downloadSong(song)); } return files; } @Override public File downloadSong(Song song) throws MalformedURLException, IOException, URISyntaxException { return downloadTune(song); } @Override public QueryResponse search(String query) throws IOException, URISyntaxException { if(Strings.isNullOrEmpty(query)) { throw new IllegalArgumentException("query is null or empty"); } Map<String, String> fields = new HashMap<String, String>(); fields.put("json", "{\"q\":\"" + query + "\"}"); FormBuilder form = new FormBuilder(); form.addFields(fields); form.close(); String response = client.dispatchPost(new URI(HTTPS_PLAY_GOOGLE_COM_MUSIC_SERVICES_SEARCH), form); return deserializer.deserialize(response, QueryResponse.class); } protected File downloadTune(Tune song) throws MalformedURLException, IOException, URISyntaxException { File file = new File(storageDirectory.getAbsolutePath() + System.getProperty("path.separator") + song.getId() + ".mp3"); if(!file.exists()) { Files.write(Resources.toByteArray(getTuneURL(song).toURL()), file); } return file; } @Override public void uploadSong(File song) { } }
package com.example.dell.capston; /** * Created by dell on 2016-04-02. */ public class Server { }
package com.mideas.rpg.v2.game.item; public enum ItemType { STUFF, ITEM, POTION }
/******************************************************************************* * Copyright (c) 2015 - 2018 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. *******************************************************************************/ package jsettlers.logic.movable; import jsettlers.algorithms.fogofwar.FoWTask; import jsettlers.algorithms.path.Path; import jsettlers.algorithms.simplebehaviortree.BehaviorTreeHelper; import jsettlers.algorithms.simplebehaviortree.IBooleanConditionFunction; import jsettlers.algorithms.simplebehaviortree.IEDirectionSupplier; import jsettlers.algorithms.simplebehaviortree.IEMaterialTypeSupplier; import jsettlers.algorithms.simplebehaviortree.INodeStatusActionConsumer; import jsettlers.algorithms.simplebehaviortree.IShortPoint2DSupplier; import jsettlers.algorithms.simplebehaviortree.IShortSupplier; import jsettlers.algorithms.simplebehaviortree.Node; import jsettlers.algorithms.simplebehaviortree.NodeStatus; import jsettlers.algorithms.simplebehaviortree.Root; import jsettlers.algorithms.simplebehaviortree.Tick; import jsettlers.algorithms.simplebehaviortree.nodes.Guard; import jsettlers.common.action.EMoveToType; import jsettlers.common.map.shapes.HexGridArea; import jsettlers.common.mapobject.EMapObjectType; import jsettlers.common.material.EMaterialType; import jsettlers.common.material.ESearchType; import jsettlers.common.movable.EDirection; import jsettlers.common.movable.EEffectType; import jsettlers.common.movable.EMovableAction; import jsettlers.common.movable.EMovableType; import jsettlers.common.position.ShortPoint2D; import jsettlers.common.selectable.ESelectionType; import jsettlers.logic.constants.Constants; import jsettlers.logic.constants.MatchConstants; import jsettlers.logic.movable.civilian.BearerMovable; import jsettlers.logic.movable.civilian.BricklayerMovable; import jsettlers.logic.movable.civilian.DiggerMovable; import jsettlers.logic.movable.civilian.SimpleBuildingWorkerMovable; import jsettlers.logic.movable.civilian.HealerMovable; import jsettlers.logic.movable.cargo.CargoShipMovable; import jsettlers.logic.movable.cargo.DonkeyMovable; import jsettlers.logic.movable.civilian.LegacyBuildingWorkerMovable; import jsettlers.logic.movable.interfaces.AbstractMovableGrid; import jsettlers.logic.movable.interfaces.IAttackableHumanMovable; import jsettlers.logic.movable.interfaces.IFerryMovable; import jsettlers.logic.movable.interfaces.ILogicMovable; import jsettlers.logic.movable.military.BowmanMovable; import jsettlers.logic.movable.military.InfantryMovable; import jsettlers.logic.movable.military.MageMovable; import jsettlers.logic.movable.other.FerryMovable; import jsettlers.logic.movable.specialist.GeologistMovable; import jsettlers.logic.movable.specialist.PioneerMovable; import jsettlers.logic.movable.specialist.ThiefMovable; import jsettlers.logic.player.Player; import java.util.EnumMap; import java.util.LinkedList; import java.util.Map; import static jsettlers.algorithms.simplebehaviortree.BehaviorTreeHelper.*; /** * Central Movable class of JSettlers. * * @author Andreas Eberle */ public abstract class Movable implements ILogicMovable, FoWTask { private static final long serialVersionUID = -705947810059935866L; private static final int SHIP_PUSH_DISTANCE = 10; protected final AbstractMovableGrid grid; private final int id; protected final Player player; private EMovableState state = EMovableState.DOING_NOTHING; private final EMovableType movableType; private EMaterialType materialType = EMaterialType.NO_MATERIAL; private EMovableAction movableAction = EMovableAction.NO_ACTION; private EDirection direction; private final Map<EEffectType, Integer> effectEnd = new EnumMap<>(EEffectType.class); private int animationStartTime; private short animationDuration; public transient ShortPoint2D oldFowPosition = null; protected ShortPoint2D position; protected Path path; protected float health; private boolean visible = true; private ILogicMovable pushedFrom; private boolean isRightstep = false; protected int flockDelay = 700; private transient boolean selected = false; private transient boolean soundPlayed = false; // the following data only for ship passengers protected IFerryMovable ferryToEnter = null; protected boolean playerControlled; private boolean leavePosition = false; private Tick<? extends Movable> tick;//TODO fix behaviour tree serialisation protected Movable(AbstractMovableGrid grid, EMovableType movableType, ShortPoint2D position, Player player, Movable replace, Root<? extends Movable> behaviour) { this.grid = grid; this.position = position; this.player = player; this.movableType = movableType; this.tick = behaviour != null? new Tick<>(this, (Root<Movable>)behaviour) : null; if(replace != null) { this.health = replace.getHealth()/replace.getMovableType().getHealth()*movableType.getHealth(); this.direction = replace.getDirection(); if(movableType == replace.movableType) { this.materialType = replace.materialType; } } else { this.health = movableType.getHealth(); this.direction = EDirection.VALUES[MatchConstants.random().nextInt(EDirection.NUMBER_OF_DIRECTIONS)]; } playerControlled = movableType.playerControllable; this.id = MovableManager.requestId(this, replace); } /** * Tests if this movable can receive moveTo requests and if so, directs it to go to the given position. * * @param targetPosition * Desired position the movable should move to */ @Override public void moveTo(ShortPoint2D targetPosition, EMoveToType moveToType) { } public void leavePosition() { if (isBusy()) { return; } leavePosition = true; } protected boolean checkPathStepPreconditions() { if(pathStep != null && !pathStep.test(this)) { aborted = true; return false; } return true; } protected boolean aborted; protected IBooleanConditionFunction<Movable> pathStep; //TODO remove so that tests will continue working in the future protected void pathAborted(ShortPoint2D pathTarget) { aborted = true; } protected static <T extends Movable> Node<T> setDirectionNode(EDirection direction) { return action(mov -> {mov.setDirection(direction);}); } protected static <T extends Movable> Node<T> setDirectionNode(IEDirectionSupplier<T> direction) { return action(mov -> {mov.setDirection(direction.apply(mov));}); } protected static <T extends Movable> Node<T> setMaterialNode(EMaterialType material) { return action(mov -> {mov.setMaterial(material);}); } protected static <T extends Movable> Node<T> hide() { return action(mov -> {mov.setVisible(false);}); } protected static <T extends Movable> Node<T> show() { return action(mov -> {mov.setVisible(true);}); } protected static <T extends Movable> Node<T> drop(IEMaterialTypeSupplier<T> materialType, IBooleanConditionFunction<T> offerMaterial) { return sequence( playAction(EMovableAction.BEND_DOWN, Constants.MOVABLE_BEND_DURATION), action(mov -> { EMaterialType takeDropMaterial = materialType.apply(mov); if (takeDropMaterial == null || !takeDropMaterial.isDroppable()) return; mov.setMaterial(EMaterialType.NO_MATERIAL); mov.grid.dropMaterial(mov.position, takeDropMaterial, offerMaterial.test(mov), false); }), playAction(EMovableAction.RAISE_UP, Constants.MOVABLE_BEND_DURATION) ); } protected static <T extends Movable> Node<T> take(IEMaterialTypeSupplier<T> materialType, IBooleanConditionFunction<T> fromMap, INodeStatusActionConsumer<T> tookMaterial) { return sequence( condition(mov -> !fromMap.test(mov) || mov.grid.canTakeMaterial(mov.position, materialType.apply(mov))), playAction(EMovableAction.BEND_DOWN, Constants.MOVABLE_BEND_DURATION), action(mov -> { EMaterialType material = materialType.apply(mov); mov.grid.takeMaterial(mov.position, material); mov.setMaterial(material); tookMaterial.accept(mov); }), playAction(EMovableAction.RAISE_UP, Constants.MOVABLE_BEND_DURATION) ); } protected static <T extends Movable> Node<T> goInDirectionIfAllowedAndFree(IEDirectionSupplier<T> direction) { return sequence( condition(mov -> mov.goInDirection(direction.apply(mov), EGoInDirectionMode.GO_IF_ALLOWED_AND_FREE)), waitFor(condition(mov -> ((Movable)mov).state == EMovableState.DOING_NOTHING)) ); } protected static <T extends Movable> Node<T> goInDirectionIfFree(IEDirectionSupplier<T> direction) { return sequence( condition(mov -> { ShortPoint2D targetPosition = direction.apply(mov).getNextHexPoint(mov.position); if(mov.grid.isFreePosition(targetPosition.x, targetPosition.y)) { ((Movable)mov).initGoingSingleStep(targetPosition); mov.setState(EMovableState.GOING_SINGLE_STEP); return true; } else { return false; } }), waitFor(condition(mov -> ((Movable)mov).state == EMovableState.DOING_NOTHING)) ); } protected static <T extends Movable> Node<T> goInDirectionWaitFree(EDirection direction, IBooleanConditionFunction<T> pathStep) { return goInDirectionWaitFree(mov -> direction, pathStep); } protected static <T extends Movable> Node<T> goInDirectionWaitFree(IEDirectionSupplier<T> direction, IBooleanConditionFunction<T> pathStep) { return sequence( action(mov -> { mov.aborted = false; mov.pathStep = (IBooleanConditionFunction<Movable>)pathStep; mov.goInDirection(direction.apply(mov), EGoInDirectionMode.GO_IF_ALLOWED_WAIT_TILL_FREE); }), waitFor(condition(mov -> mov.path == null)), condition(mov -> !mov.aborted) ); } private ShortPoint2D markedTarget = null; protected static <T extends Movable> Node<T> followPresearchedPathMarkTarget(IBooleanConditionFunction<T> pathStep) { return resetAfter(mov -> { Movable mmov = mov; mmov.grid.setMarked(mmov.markedTarget, false); mmov.markedTarget = null; }, sequence( action(mov -> { Movable mmov = mov; mmov.markedTarget = mmov.path.getTargetPosition(); mmov.grid.setMarked(mmov.markedTarget, true); }), followPresearchedPath(pathStep) ) ); } protected static <T extends Movable> Node<T> followPresearchedPath(IBooleanConditionFunction<T> pathStep) { return sequence( action(mov -> { Movable realMov = mov; mov.aborted = false; mov.pathStep = (IBooleanConditionFunction<Movable>)pathStep; assert mov.path != null : "path must be non-null to be able to followPresearchedPath()!"; realMov.followPath(mov.path); }), waitFor(condition(mov -> mov.path == null)), condition(mov -> !mov.aborted) ); } /** * * @param duration * duration in milliseconds */ protected static <T extends Movable> Node<T> playAction(EMovableAction action, short duration) { return playAction(action, mov -> duration); } /** * * @param duration * duration in milliseconds */ protected static <T extends Movable> Node<T> playAction(EMovableAction action, IShortSupplier<T> duration) { return sequence( action(mov -> { Movable realMov = mov; realMov.playAnimation(action, duration.apply(mov)); realMov.setState(EMovableState.WAITING); realMov.soundPlayed = false; }), waitFor(condition(mov -> ((Movable)mov).state == EMovableState.DOING_NOTHING)) ); } protected static <T extends Movable> Node<T> goToPos(IShortPoint2DSupplier<T> target, IBooleanConditionFunction<T> pathStep) { return sequence( condition(mov -> { Movable realMov = mov; mov.aborted = false; mov.pathStep = (IBooleanConditionFunction<Movable>)pathStep; Path path = mov.grid.calculatePathTo(mov, target.apply(mov)); realMov.followPath(path); return mov.path != null; }), waitFor(condition(mov -> mov.path == null)), condition(mov -> !mov.aborted) ); } protected Path findWayAroundObstacle(ShortPoint2D position, Path path) { if (!path.hasOverNextStep()) { // if path has no position left return path; } EDirection direction = EDirection.getApproxDirection(position, path.getOverNextPos()); EDirection rightDir = direction.getNeighbor(-1); EDirection leftDir = direction.getNeighbor(1); ShortPoint2D straightPos = direction.getNextHexPoint(position); ShortPoint2D twoStraightPos = direction.getNextHexPoint(position, 2); ShortPoint2D rightPos = rightDir.getNextHexPoint(position); ShortPoint2D rightStraightPos = direction.getNextHexPoint(rightPos); ShortPoint2D straightRightPos = rightDir.getNextHexPoint(straightPos); ShortPoint2D leftPos = leftDir.getNextHexPoint(position); ShortPoint2D leftStraightPos = direction.getNextHexPoint(leftPos); ShortPoint2D straightLeftPos = leftDir.getNextHexPoint(straightPos); ShortPoint2D overNextPos = path.getOverNextPos(); LinkedList<ShortPoint2D[]> possiblePaths = new LinkedList<>(); if (twoStraightPos.equals(overNextPos)) { if (grid.isValidPosition(this, rightPos.x, rightPos.y) && grid.isValidPosition(this, rightStraightPos.x, rightStraightPos.y)) { possiblePaths.add(new ShortPoint2D[]{ rightPos, rightStraightPos}); } else if (grid.isValidPosition(this, leftPos.x, leftPos.y) && grid.isValidPosition(this, leftStraightPos.x, leftStraightPos.y)) { possiblePaths.add(new ShortPoint2D[]{ leftPos, leftStraightPos}); } else { // TODO @Andreas Eberle maybe calculate a new path } } if (rightStraightPos.equals(overNextPos) && grid.isValidPosition(this, rightPos.x, rightPos.y)) { possiblePaths.add(new ShortPoint2D[]{rightPos}); } if (leftStraightPos.equals(overNextPos) && grid.isValidPosition(this, leftPos.x, leftPos.y)) { possiblePaths.add(new ShortPoint2D[]{leftPos}); } if ((straightRightPos.equals(overNextPos) || straightLeftPos.equals(overNextPos)) && grid.isValidPosition(this, straightPos.x, straightPos.y) && grid.hasNoMovableAt(straightPos.x, straightPos.y)) { possiblePaths.add(new ShortPoint2D[]{straightPos}); } else { // TODO @Andreas Eberle maybe calculate a new path } // try to find a way without a movable or with a pushable movable. for (ShortPoint2D[] pathPrefix : possiblePaths) { // check if any of the paths is free of movables ShortPoint2D firstPosition = pathPrefix[0]; ILogicMovable movable = grid.getMovableAt(firstPosition.x, firstPosition.y); if (movable == null || movable.isProbablyPushable(this)) { path.goToNextStep(); return new Path(path, pathPrefix); } } return path; } @Override public int timerEvent() { if (!isAlive()) { return -1; } switch (state) { // ensure animation is finished, if not, reschedule case GOING_SINGLE_STEP: case PATHING: case WAITING: int remainingAnimationTime = animationStartTime + animationDuration - MatchConstants.clock().getTime(); if (remainingAnimationTime > 0) { return remainingAnimationTime; } break; default: break; } switch (state) { case WAITING: case GOING_SINGLE_STEP: setState(EMovableState.DOING_NOTHING); // the action is finished, as the time passed movableAction = EMovableAction.NO_ACTION; break; case PATHING: pathingAction(); break; default: break; } if (state == EMovableState.DOING_NOTHING) { // if movable is currently doing nothing if(tick != null) { NodeStatus status = NodeStatus.SUCCESS; // continue behaviour if the previous run was successful for(int i = 0; i < 2 && status == NodeStatus.SUCCESS && isAlive(); i++) { status = tick.tick(); } } } leavePosition = false; if (state == EMovableState.DOING_NOTHING) { return Constants.MOVABLE_INTERRUPT_PERIOD; } return animationDuration; } private void pathingAction() { if (path == null || !path.hasNextStep() || ferryToEnter == null && !checkPathStepPreconditions()) { // if path is finished, or canceled by strategy return from here setState(EMovableState.DOING_NOTHING); movableAction = EMovableAction.NO_ACTION; path = null; if (ferryToEnter != null) { enterFerry(); } return; } ILogicMovable blockingMovable = grid.getMovableAt(path.nextX(), path.nextY()); if (blockingMovable == null) { // if we can go on to the next step if (grid.isValidNextPathPosition(this, path.getNextPos(), path.getTargetPosition())) { // next position is valid goSinglePathStep(); } else { // next position is invalid movableAction = EMovableAction.NO_ACTION; animationDuration = Constants.MOVABLE_INTERRUPT_PERIOD; // recheck shortly Path newPath = grid.calculatePathTo(this, path.getTargetPosition()); // try to find a new path if (newPath == null) { // no path found setState(EMovableState.DOING_NOTHING); pathAborted(path.getTargetPosition()); // inform strategy path = null; } else { this.path = newPath; // continue with new path if (grid.hasNoMovableAt(path.nextX(), path.nextY())) { // path is valid, but maybe blocked (leaving blocked area) goSinglePathStep(); } } } } else { // step not possible, so try it next time movableAction = EMovableAction.NO_ACTION; boolean pushedSuccessfully = blockingMovable.push(this); if (!pushedSuccessfully) { path = findWayAroundObstacle(position, path); animationDuration = Constants.MOVABLE_INTERRUPT_PERIOD; // recheck shortly } else if (movableAction == EMovableAction.NO_ACTION) { animationDuration = Constants.MOVABLE_INTERRUPT_PERIOD; // recheck shortly } // else: push initiated our next step } if (this.isShip()) { // ships need more space pushShips(); } } private void enterFerry() { int distanceToFerry = this.getPosition().getOnGridDistTo(ferryToEnter.getPosition()); if (distanceToFerry <= Constants.MAX_FERRY_ENTRANCE_DISTANCE) { if (ferryToEnter.addPassenger((IAttackableHumanMovable)this)) { grid.leavePosition(this.getPosition(), this); setState(EMovableState.ON_FERRY); } } ferryToEnter = null; } private void pushShips() { HexGridArea.stream(position.x, position.y, 1, SHIP_PUSH_DISTANCE) .filterBounds(grid.getWidth(), grid.getHeight()) .forEach((x, y) -> { ILogicMovable blockingMovable = grid.getMovableAt(x, y); if (blockingMovable != null && blockingMovable.isShip()) { blockingMovable.push(this); } }); } @Override public void goSinglePathStep() { initGoingSingleStep(path.getNextPos()); path.goToNextStep(); } @Override public ShortPoint2D getPosition() { return this.position; } @Override public int getViewDistance() { return movableType.getViewDistance(); } @Override public ShortPoint2D getFoWPosition() { return position; } @Override public ShortPoint2D getOldFoWPosition() { return oldFowPosition; } @Override public void setOldFoWPosition(ShortPoint2D position) { oldFowPosition = position; } @Override public ILogicMovable getPushedFrom() { return pushedFrom; } private void initGoingSingleStep(ShortPoint2D position) { direction = EDirection.getDirection(this.position, position); playAnimation(EMovableAction.WALKING, movableType.getStepDurationMs()); grid.leavePosition(this.position, this); grid.enterPosition(position, this, false); this.position = position; isRightstep = !isRightstep; } protected static <T extends Movable> Guard<T> doingNothingGuard() { return guard(mov -> true, doingNothingAction()); } protected static <T extends Movable> Node<T> doingNothingAction() { return selector( sequence( condition(mov -> ((Movable) mov).leavePosition), selector( goInDirectionIfAllowedAndFree(mov -> EDirection.VALUES[0]), goInDirectionIfAllowedAndFree(mov -> EDirection.VALUES[1]), goInDirectionIfAllowedAndFree(mov -> EDirection.VALUES[2]), goInDirectionIfAllowedAndFree(mov -> EDirection.VALUES[3]), goInDirectionIfAllowedAndFree(mov -> EDirection.VALUES[4]), goInDirectionIfAllowedAndFree(mov -> EDirection.VALUES[5]) ) ), sequence( condition(Movable::isShip), action(Movable::pushShips), sleep(mov -> mov.flockDelay) ), sequence( condition(mov -> mov.grid.isBlockedOrProtected(mov.position.x, mov.position.y)), selector( sequence( condition(mov -> mov.preSearchPath(true, mov.position.x, mov.position.y, (short) 50, ESearchType.NON_BLOCKED_OR_PROTECTED)), followPresearchedPath(mov -> true) ), // just "succeed" after dying action(Movable::kill) ) ), // flock to decentralize sequence( condition(mov -> { ShortPoint2D decentVector = mov.grid.calcDecentralizeVector(mov.position.x, mov.position.y); EDirection randomDirection = mov.getDirection().getNeighbor(MatchConstants.random().nextInt(-1, 1)); int dx = randomDirection.gridDeltaX + decentVector.x; int dy = randomDirection.gridDeltaY + decentVector.y; if (ShortPoint2D.getOnGridDist(dx, dy) >= 2) { mov.flockDelay = Math.max(mov.flockDelay - 100, 500); mov.flockDirection = EDirection.getApproxDirection(0, 0, dx, dy); return true; } else { mov.flockDelay = Math.min(mov.flockDelay + 100, 1000); return false; } }), goInDirectionIfAllowedAndFree(mov -> mov.flockDirection) ), sequence( action(mov -> { int turnDirection = MatchConstants.random().nextInt(-8, 8); if (Math.abs(turnDirection) <= 1) { mov.lookInDirection(mov.getDirection().getNeighbor(turnDirection)); } }), sleep(mov -> mov.flockDelay) ) ); } protected EDirection flockDirection; /** * A call to this method indicates this movable that it shall leave it's position to free the position for another movable. * * @param pushingMovable * The movable pushing at this movable. This should be the movable that want's to get the position! * @return true if this movable will move out of it's way in the near future <br> * false if this movable doesn't move. */ @Override public boolean push(ILogicMovable pushingMovable) { if (!isAlive()) { return false; } switch (state) { case DOING_NOTHING: if (isBusy()) { // don't go to random direction if movable shouldn't do something in DOING_NOTHING return false; } if (goToRandomDirection(pushingMovable)) { // try to find free direction return true; // if we found a free direction, go there and tell the pushing one we'll move } else { // if we didn't find a direction, check if it's possible to exchange positions if (pushingMovable.getPath() == null || !pushingMovable.getPath().hasNextStep()) { return false; // the other movable just pushed to get space, we can't do anything for it here. } else if (pushingMovable.getMovableType().isPlayerControllable() || grid.isValidPosition(this, position.x, position.y)) { // exchange positions EDirection directionToPushing = EDirection.getApproxDirection(this.position, pushingMovable.getPosition()); pushingMovable.goSinglePathStep(); // if no free direction found, exchange the positions of the movables pathStep = null; goInDirection(directionToPushing, EGoInDirectionMode.GO_IF_ALLOWED_WAIT_TILL_FREE); return true; } else { // exchange not possible, as the location is not valid. return false; } } case PATHING: if (path == null || pushingMovable.getPath() == null || !pushingMovable.getPath().hasNextStep()) { return false; // the other movable just pushed to get space, so we can't do anything for it in this state. } if (animationStartTime + animationDuration <= MatchConstants.clock().getTime() && this.path.hasNextStep()) { ShortPoint2D nextPos = path.getNextPos(); if (pushingMovable.getPosition() == nextPos) { // two movables going in opposite direction and wanting to exchange positions pushingMovable.goSinglePathStep(); this.goSinglePathStep(); } else { if (grid.hasNoMovableAt(nextPos.x, nextPos.y)) { // this movable isn't blocked, so just let it's pathingAction() handle this } else if (pushedFrom == null) { try { this.pushedFrom = pushingMovable; return grid.getMovableAt(nextPos.x, nextPos.y).push(this); } finally { this.pushedFrom = null; } } else { while (pushingMovable != this) { pushingMovable.goSinglePathStep(); pushingMovable = pushingMovable.getPushedFrom(); } this.goSinglePathStep(); } } } return true; case GOING_SINGLE_STEP: case WAITING: return false; // we can't do anything case DEBUG_STATE: return false; default: assert false : "got pushed in unhandled state: " + state; return false; } } @Override public Path getPath() { return path; } public boolean isProbablyPushable(ILogicMovable pushingMovable) { switch (state) { case DOING_NOTHING: return true; case PATHING: return path != null && pushingMovable.getPath() != null && pushingMovable.getPath().hasNextStep(); default: return false; } } private boolean goToRandomDirection(ILogicMovable pushingMovable) { int offset = MatchConstants.random().nextInt(EDirection.NUMBER_OF_DIRECTIONS); EDirection pushedFromDir = EDirection.getApproxDirection(this.getPosition(), pushingMovable.getPosition()); if (pushedFromDir == null) { return false; } for (int i = 0; i < EDirection.NUMBER_OF_DIRECTIONS; i++) { EDirection currDir = EDirection.VALUES[(i + offset) % EDirection.NUMBER_OF_DIRECTIONS]; if (currDir != pushedFromDir && currDir != pushedFromDir.rotateRight(1) && currDir != pushedFromDir.rotateRight(EDirection.NUMBER_OF_DIRECTIONS - 1) && goInDirection(currDir, EGoInDirectionMode.GO_IF_ALLOWED_AND_FREE)) { return true; } } return false; } /** * Sets the material this movable is carrying to the given one. * * @param materialType * The material type to be set * @return {@link EMaterialType} that has been set before. */ public final EMaterialType setMaterial(EMaterialType materialType) { assert materialType != null : "MaterialType may not be null"; EMaterialType former = this.materialType; this.materialType = materialType; return former; } private void playAnimation(EMovableAction movableAction, short duration) { this.animationStartTime = MatchConstants.clock().getTime(); this.animationDuration = duration; this.movableAction = movableAction; } /** * Lets this movable look in the given direction. * * @param direction * The direction to look. */ public final void lookInDirection(EDirection direction) { this.direction = direction; } /** * Tries to go a step in the given direction. * * @param direction * direction to go * @param mode * Use the given mode to go.<br> * @return true if the step can and will immediately be executed. <br> * false if the target position is generally blocked or a movable occupies that position. */ public final boolean goInDirection(EDirection direction, EGoInDirectionMode mode) { ShortPoint2D targetPosition = direction.getNextHexPoint(position); switch (mode) { case GO_IF_ALLOWED_WAIT_TILL_FREE: { this.direction = direction; setState(EMovableState.PATHING); this.followPath(new Path(targetPosition)); return true; } case GO_IF_ALLOWED_AND_FREE: if ((grid.isValidPosition(this, targetPosition.x, targetPosition.y) && grid.hasNoMovableAt(targetPosition.x, targetPosition.y))) { initGoingSingleStep(targetPosition); setState(EMovableState.GOING_SINGLE_STEP); return true; } else { break; } } return false; } @Override public final void setPosition(ShortPoint2D position) { if (visible) { grid.leavePosition(this.position, this); grid.enterPosition(position, this, true); } this.position = position; } public final void setVisible(boolean visible) { if (this.visible == visible) { // nothing to change } else if (this.visible) { // is visible and gets invisible grid.leavePosition(position, this); } else { grid.enterPosition(position, this, true); } this.visible = visible; } /** * @param dijkstra * if true, dijkstra algorithm is used<br> * if false, in area finder is used. * @param centerX * @param centerY * @param radius * @param searchType * @return true if a path has been found. */ public final boolean preSearchPath(boolean dijkstra, short centerX, short centerY, short radius, ESearchType searchType) { assert state == EMovableState.DOING_NOTHING : "this method can only be invoked in state DOING_NOTHING"; if (dijkstra) { this.path = grid.searchDijkstra(this, centerX, centerY, radius, searchType); } else { this.path = grid.searchInArea(this, centerX, centerY, radius, searchType); } return path != null; } protected boolean isBusy() { return state != EMovableState.DOING_NOTHING; } public boolean isOnOwnGround() { return grid.getPlayerAt(position) == player; } private void followPath(Path path) { this.path = path; setState(EMovableState.PATHING); this.movableAction = EMovableAction.NO_ACTION; pathingAction(); } /** * Sets the state to the given one and resets the movable to a clean start of this state. * * @param newState */ protected void setState(EMovableState newState) { this.state = newState; } /** * kills this movable. */ @Override public final void kill() { if(!isAlive()) return; decoupleMovable(); spawnGhost(); killMovable(); } private void spawnGhost() { ShortPoint2D ghostPosition = getGhostPosition(); if(ghostPosition != null) { grid.addSelfDeletingMapObject(position, EMapObjectType.GHOST, Constants.GHOST_PLAY_DURATION, player); } } protected ShortPoint2D getGhostPosition() { // position of the movable on a ferry is the position it loaded into the ferry => not correct => don't show ghost return isOnFerry()? null : position; } protected void decoupleMovable() { if (!isAlive()) { return; // this movable already died. } grid.leavePosition(this.position, this); MovableManager.remove(this); } protected void killMovable() { this.health = -200; this.state = EMovableState.DEAD; this.selected = false; position = null; } public boolean isOnFerry() { return state == EMovableState.ON_FERRY; } /** * Gets the player object of this movable. * * @return The player object of this movable. */ public final Player getPlayer() { return player; } @Override public final boolean isSelected() { return selected; } @Override public final boolean isWounded() { return health < movableType.health; } @Override public final void setSelected(boolean selected) { this.selected = selected; } @Override public void stopOrStartWorking(boolean stop) { } @Override public final ESelectionType getSelectionType() { return movableType.selectionType; } @Override public final void setSoundPlayed() { this.soundPlayed = true; } @Override public final boolean isSoundPlayed() { return soundPlayed; } @Override public final EMovableType getMovableType() { return movableType; } @Override public final EMovableAction getAction() { return movableAction; } @Override public final EDirection getDirection() { return direction; } @Override public final float getMoveProgress() { return ((float) (MatchConstants.clock().getTime() - animationStartTime)) / animationDuration; } @Override public final EMaterialType getMaterial() { return materialType; } @Override public final float getHealth() { return health; } @Override public final boolean isAlive() { return state != EMovableState.DEAD; } @Override public final boolean isRightstep() { return isRightstep; } @Override public final boolean needsPlayersGround() { return movableType.needsPlayersGround(); } @Override public final void debug() { System.out.println("debug: " + this); } @Override public final int getID() { return id; } @Override public String toString() { return "Movable: " + id + " position: " + position + " player: " + player.playerId + " movableType: " + movableType + " direction: " + direction + " material: " + materialType; } protected enum EMovableState { PATHING, DOING_NOTHING, GOING_SINGLE_STEP, WAITING, ON_FERRY, DEAD, /** * This state may only be used for debugging reasons! */ DEBUG_STATE } public boolean isShip() { return movableType.isShip(); } public final void setDirection(EDirection direction) { this.direction = direction; } public void addEffect(EEffectType effect) { effectEnd.put(effect, effect.getTime()*1000 + MatchConstants.clock().getTime()); } @Override public boolean hasEffect(EEffectType effect) { return getEffectTime(effect) > 0; } protected int getEffectTime(EEffectType effect) { if(!effectEnd.containsKey(effect)) return -MatchConstants.clock().getTime(); return effectEnd.get(effect) - MatchConstants.clock().getTime(); } protected static <T extends Movable> Guard<T> handleFrozenEffect() { return guard(mov -> mov.hasEffect(EEffectType.FROZEN), BehaviorTreeHelper.sleep(mov -> mov.getEffectTime(EEffectType.FROZEN)) ); } public static Movable createMovable(EMovableType movableType, Player player, ShortPoint2D position, AbstractMovableGrid grid) { return createMovable(movableType, player, position, grid, null); } protected static Movable createMovable(EMovableType movableType, Player player, ShortPoint2D position, AbstractMovableGrid grid, Movable replaceMovable) { if(replaceMovable != null) replaceMovable.decoupleMovable(); Movable movable = chooseMovableClass(movableType, player, position, grid, replaceMovable); MovableManager.add(movable); grid.enterPosition(position, movable, true); if(replaceMovable != null) replaceMovable.killMovable(); return movable; } private static Movable chooseMovableClass(EMovableType movableType, Player player, ShortPoint2D position, AbstractMovableGrid grid, Movable movable) { switch (movableType) { case SWORDSMAN_L1: case SWORDSMAN_L2: case SWORDSMAN_L3: case PIKEMAN_L1: case PIKEMAN_L2: case PIKEMAN_L3: return new InfantryMovable(grid, movableType, position, player, movable); case BOWMAN_L1: case BOWMAN_L2: case BOWMAN_L3: return new BowmanMovable(grid, movableType, position, player, movable); case MAGE: return new MageMovable(grid, position, player, movable); case BEARER: return new BearerMovable(grid, position, player, movable); case DIGGER: return new DiggerMovable(grid, position, player, movable); case BRICKLAYER: return new BricklayerMovable(grid, position, player, movable); case THIEF: return new ThiefMovable(grid, position, player, movable); case PIONEER: return new PioneerMovable(grid, position, player, movable); case GEOLOGIST: return new GeologistMovable(grid, position, player, movable); case CARGO_SHIP: return new CargoShipMovable(grid, position, player, movable); case FERRY: return new FerryMovable(grid, position, player, movable); case DONKEY: return new DonkeyMovable(grid, movableType, position, player, movable); case BAKER: case CHARCOAL_BURNER: case MELTER: case MINER: case PIG_FARMER: case DONKEY_FARMER: case SAWMILLER: case SMITH: return new LegacyBuildingWorkerMovable(grid, movableType, position, player, movable); case FISHERMAN: case STONECUTTER: case WATERWORKER: case LUMBERJACK: case FORESTER: case WINEGROWER: case FARMER: case DOCKWORKER: case MILLER: case SLAUGHTERER: return new SimpleBuildingWorkerMovable(grid, movableType, position, player, movable); case HEALER: return new HealerMovable(grid, position, player, movable); default: throw new AssertionError("movable type " + movableType + " is not mapped to a movable class!"); } } }
package com.tencent.mm.plugin.setting.ui.setting; import com.tencent.mm.plugin.setting.a.h; import com.tencent.mm.plugin.setting.a.i; import com.tencent.mm.ui.base.l; import com.tencent.mm.ui.base.n$c; class SettingsUI$24 implements n$c { final /* synthetic */ SettingsUI mUx; SettingsUI$24(SettingsUI settingsUI) { this.mUx = settingsUI; } public final void a(l lVar) { if (lVar.crF()) { lVar.ak(1, i.logout_menu_logout, h.menu_logout_single); lVar.ak(2, i.logout_menu_exit, h.menu_close_wechat); } } }
package org.zqu.yiban.schedule.model.json; /** * Created by zqh on 2017/7/18. */ public class AuthorizeSuccResponse extends AuthorizeBaseResponse{ /** * visit_user : {"userid":"易班用户ID","username":"易班用户名","usernick":"易班用户昵称","usersex":"易班用户性别"} * visit_oauth : {"access_token":"授权凭证","token_expires":"有效unix时间戳"} */ private VisitUserBean visit_user; private VisitOauthBean visit_oauth; public VisitUserBean getVisit_user() { return visit_user; } public void setVisit_user(VisitUserBean visit_user) { this.visit_user = visit_user; } public VisitOauthBean getVisit_oauth() { return visit_oauth; } public void setVisit_oauth(VisitOauthBean visit_oauth) { this.visit_oauth = visit_oauth; } public static class VisitUserBean { /** * userid : 易班用户ID * username : 易班用户名 * usernick : 易班用户昵称 * usersex : 易班用户性别 */ private String userid; private String username; private String usernick; private String usersex; public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUsernick() { return usernick; } public void setUsernick(String usernick) { this.usernick = usernick; } public String getUsersex() { return usersex; } public void setUsersex(String usersex) { this.usersex = usersex; } } public static class VisitOauthBean { /** * access_token : 授权凭证 * token_expires : 有效unix时间戳 */ private String access_token; private String token_expires; public String getAccess_token() { return access_token; } public void setAccess_token(String access_token) { this.access_token = access_token; } public String getToken_expires() { return token_expires; } public void setToken_expires(String token_expires) { this.token_expires = token_expires; } } }
package leetcode; /** * @Author: Mr.M * @Date: 2019-03-22 15:34 * @Description: https://leetcode-cn.com/problems/palindrome-number/ **/ public class T9回文数 { public static boolean isPalindrome(int x) { return String.valueOf(x).equals(new StringBuilder(String.valueOf(x)).reverse().toString()); } public static void main(String[] args) { System.out.println(isPalindrome(123)); System.out.println(isPalindrome(121)); } }
abstract class Hitable { abstract public boolean hit(Ray r, float t_min, float t_max, HitRecord rec); }
package br.com.univag.logic; import br.com.univag.controller.Logica; import br.com.univag.dominio.TipoMsg; import br.com.univag.exception.DaoException; import br.com.univag.model.MovimentoVo; import br.com.univag.service.MovimentoVeiculoService; import br.com.univag.util.Mensagem; import java.io.IOException; import java.sql.Connection; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author CRISTIANO */ public class ConsultarUltimoRegistroMovimentoPlacaLogic implements Logica { Mensagem mensagem = new Mensagem(); MovimentoVeiculoService service = new MovimentoVeiculoService(); Connection con; @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String logica = request.getParameter("logica"); String placa = request.getParameter("placa"); mensagem.setRequest(request); con = (Connection) request.getAttribute("connection"); service.setCon(con); if(logica !=null){ if(logica.equals("registroMovimento")){ try { placa = placa.trim().toUpperCase(); List<MovimentoVo>list = service.listRegistroMov(removerMascara(placa)); if(list==null){ mensagem.message(TipoMsg.ALERTA, "Não foi encontrado registro do veiculo informado"); return "sistema/consultarVeiculoView.jsp"; } request.setAttribute("listMovimento",list); return "sistema/listRegistroMovimentoView.jsp"; } catch (DaoException ex) { ex.getMessage(); } } } return "sistema/consultarVeiculoView.jsp"; } public String removerMascara(String str) { str = str.trim(); return str.replaceAll("[^a-zA-Z0-9 ]", ""); } }
package tema12; import java.text.SimpleDateFormat; public class Main { public static void main(String[] args0) throws Exception { Pessoa pessoa = PessoaBuilder.construtor() .comNome("Isabella") .comDataDeNascimento(new SimpleDateFormat("dd/M/yyyy").parse("21/08/1995")) .comEndereco("Av. João XXIII", 768, "Uberlândia", "MG") .build(); System.out.println(pessoa.printPessoa()); } }
package mg.egg.eggc.compiler.egg.java; import mg.egg.eggc.runtime.libjava.*; import mg.egg.eggc.compiler.libegg.base.*; import mg.egg.eggc.compiler.libegg.java.*; import mg.egg.eggc.compiler.libegg.egg.*; import mg.egg.eggc.compiler.libegg.mig.*; import mg.egg.eggc.compiler.libegg.latex.*; import mg.egg.eggc.compiler.libegg.type.*; import mg.egg.eggc.runtime.libjava.lex.*; import java.util.*; import mg.egg.eggc.runtime.libjava.lex.*; import mg.egg.eggc.runtime.libjava.*; import mg.egg.eggc.runtime.libjava.messages.*; import mg.egg.eggc.runtime.libjava.problem.IProblem; import java.util.Vector; import java.util.List; import java.util.ArrayList; public class S_GLOBALES_EGG implements IDstNode { LEX_EGG scanner; S_GLOBALES_EGG() { } S_GLOBALES_EGG(LEX_EGG scanner, boolean eval) { this.scanner = scanner; this.att_eval = eval; offset = 0; length = 0; this.att_scanner = scanner; } int [] sync= new int[0]; REGLE att_reg; boolean att_eval; TDS att_table; LEX_EGG att_scanner; IVisiteurEgg att_vis; private void regle42() throws Exception { //declaration //appel length = 0; offset = scanner.getPreviousOffset()+ scanner.getPreviousLength(); } private void regle41() throws Exception { //declaration T_EGG x_2 = new T_EGG(scanner ) ; S_GLOBS_EGG x_3 = new S_GLOBS_EGG(scanner,att_eval) ; //appel if (att_eval) action_auto_inh_41(x_3); x_2.analyser(LEX_EGG.token_t_global); addChild(x_2); x_3.analyser() ; addChild(x_3); offset =x_2.getOffset(); length =x_3.getOffset() + x_3.getLength() - offset; } private void action_auto_inh_41(S_GLOBS_EGG x_3) throws Exception { try { // instructions x_3.att_table=this.att_table; x_3.att_reg=this.att_reg; x_3.att_vis=this.att_vis; }catch(RuntimeException e) { att_scanner._interrompre(IProblem.Internal,att_scanner.getBeginLine(),ICoreMessages.id_EGG_runtime_error, CoreMessages.EGG_runtime_error,new Object[] { "EGG", "#auto_inh","GLOBALES -> t_global GLOBS ;"}); } } public void analyser () throws Exception { scanner.lit ( 1 ) ; switch ( scanner.fenetre[0].code ) { case LEX_EGG.token_t_global : // 54 regle41 () ; break ; case LEX_EGG.token_t_action : // 60 regle42 () ; break ; default : scanner._interrompre(IProblem.Syntax, scanner.getBeginLine(), IEGGMessages.id_EGG_unexpected_token,EGGMessages.EGG_unexpected_token,new String[]{scanner.fenetre[0].getNom()}); } } private IDstNode parent; public void setParent( IDstNode p){parent = p;} public IDstNode getParent(){return parent;} private List<IDstNode> children = null ; public void addChild(IDstNode node){ if (children == null) { children = new ArrayList<IDstNode>() ;} children.add(node); node.setParent(this); } public List<IDstNode> getChildren(){return children;} public boolean isLeaf(){return children == null;} public void accept(IDstVisitor visitor) { boolean visitChildren = visitor.visit(this); if (visitChildren && children != null){ for(IDstNode node : children){ node.accept(visitor); } } visitor.endVisit(this); } private int offset; private int length; public int getOffset(){return offset;} public void setOffset(int o){offset = o;} public int getLength(){return length;} public void setLength(int l){length = l;} private boolean malformed = false; public void setMalformed(){malformed = true;} public boolean isMalformed(){return malformed;} }
/* La sentencia if: if (condicional){ Instruccion1; } else{ Intruccion2; } */ package condicionalessimples; import javax.swing.JOptionPane; /** * * @author jrodriguez */ public class CondicionalesSimples { private static Object interger; /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here //Variable int numero , dato =5; //Ingresar datos por ventanas emergentes con JOptionPane.showInputDialog("") //Hay que parseralo a Interger a entero "Integer.parseInt" numero = Integer.parseInt(JOptionPane.showInputDialog("Ingresar un numero: ")); /* == : Igualdad != : Diferente > : Mayor >= : Mayor o igual < : Menor <= : Menor o igual */ if(numero < dato){ JOptionPane.showMessageDialog(null,"El numero ingresado fue "+numero+" este es menor que: "+dato); } else{ JOptionPane.showMessageDialog(null,"El numero ingresado fue "+numero+" este es mayor que: "+dato); } } }
package com.website.views.pages; import java.io.Serializable; import javax.annotation.PostConstruct; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import org.primefaces.event.FileUploadEvent; import com.website.managers.file.Uploader; import com.website.models.entities.Author; import com.website.models.entities.Event; import com.website.persistence.AuthorService; import com.website.persistence.EventService; import com.website.tools.navigation.Redirector; import com.website.tools.navigation.SessionManager; import com.website.views.WebPages; /** * The event edition web page view.</br> * This {@link Named} class is bound with the same named xhtml file. * * @author Jérémy Pansier */ @Named @ViewScoped public class EventEdition implements Serializable { /** The serial version UID. */ private static final long serialVersionUID = -7682934518094297522L; /** The web page. */ public static final WebPages WEB_PAGE = WebPages.EVENT_EDITION; /** The service managing the event persistence. */ @Inject private EventService eventService; /** The service managing the author persistence. */ @Inject private AuthorService authorService; /** The event id HTTP request parameter. */ private Long id; /** The event. */ private transient Event event; /** The author. */ private transient Author author; /** The session user name. */ private String sessionUserName; /** * Initializes the session user name and the event just after the construction. */ @PostConstruct public void init() { sessionUserName = SessionManager.getSessionUserNameOrRedirect(); author = authorService.findAuthorByAuthorName(sessionUserName); } /** * Gets the web page. * * @return the web page */ public WebPages getWebPage() { return WEB_PAGE; } /** * Gets the event id HTTP request parameter. * * @return the event id HTTP request parameter */ public Long getId() { return id; } /** * Sets the event id HTTP request parameter. * * @param id the event id HTTP request parameter */ public void setId(final Long id) { this.id = id; } /** * Gets the author. * * @return the author */ public Author getAuthor() { return author; } /** * Gets the event. * * @return the event */ public Event getEvent() { return event; } /** * Sets the event on the web page loading, depending on the HTTP request parameter.</br> */ public void load() { try { if (id != null) { if (!eventService.isEventsAuthor(id, sessionUserName)) { return; } event = eventService.findEventByEventId(id); } } catch (final NullPointerException e) { Redirector.redirect(WebPages.EVENTS_LIST.createJsfUrl()); return; } } /** * Uploads the file corresponding to the specified file upload event.</br> * Updates the event filename only if it is not null in such a way to keep the old file if the file upload fails. * * @param fileUploadEvent the file upload event */ public void upload(final FileUploadEvent fileUploadEvent) { final String uploadedFilename = Uploader.uploadFile(fileUploadEvent); if (null != uploadedFilename) { event.setFilename(uploadedFilename); } } /** * Edits the event. */ public void editEvent() { if (!eventService.isEventsAuthor(id, sessionUserName)) { return; } eventService.updateEvent(event); Redirector.redirect(WebPages.EVENT_MANAGEMENT.createJsfUrl("eventId", id), false, "Évènement édité avec succès"); } }
package android.support.v7.widget; import android.content.res.ColorStateList; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Outline; import android.graphics.Paint; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffColorFilter; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; final class ae extends Drawable { float Tl; private final RectF Tm; private final Rect Tn; float To; boolean Tp = false; boolean Tq = true; final Paint cN; private PorterDuffColorFilter jM; private ColorStateList kI; private Mode kJ; public ae(int i, float f) { this.Tl = f; this.cN = new Paint(5); this.cN.setColor(i); this.Tm = new RectF(); this.Tn = new Rect(); } public final void draw(Canvas canvas) { Object obj; Paint paint = this.cN; if (this.jM == null || paint.getColorFilter() != null) { obj = null; } else { paint.setColorFilter(this.jM); obj = 1; } canvas.drawRoundRect(this.Tm, this.Tl, this.Tl, paint); if (obj != null) { paint.setColorFilter(null); } } final void h(Rect rect) { if (rect == null) { rect = getBounds(); } this.Tm.set((float) rect.left, (float) rect.top, (float) rect.right, (float) rect.bottom); this.Tn.set(rect); if (this.Tp) { float c = af.c(this.To, this.Tl, this.Tq); this.Tn.inset((int) Math.ceil((double) af.d(this.To, this.Tl, this.Tq)), (int) Math.ceil((double) c)); this.Tm.set(this.Tn); } } protected final void onBoundsChange(Rect rect) { super.onBoundsChange(rect); h(rect); } public final void getOutline(Outline outline) { outline.setRoundRect(this.Tn, this.Tl); } public final void setAlpha(int i) { this.cN.setAlpha(i); } public final void setColorFilter(ColorFilter colorFilter) { this.cN.setColorFilter(colorFilter); } public final int getOpacity() { return -3; } public final void setTintList(ColorStateList colorStateList) { this.kI = colorStateList; this.jM = b(this.kI, this.kJ); invalidateSelf(); } public final void setTintMode(Mode mode) { this.kJ = mode; this.jM = b(this.kI, this.kJ); invalidateSelf(); } protected final boolean onStateChange(int[] iArr) { if (this.kI == null || this.kJ == null) { return false; } this.jM = b(this.kI, this.kJ); return true; } public final boolean isStateful() { return (this.kI != null && this.kI.isStateful()) || super.isStateful(); } private PorterDuffColorFilter b(ColorStateList colorStateList, Mode mode) { if (colorStateList == null || mode == null) { return null; } return new PorterDuffColorFilter(colorStateList.getColorForState(getState(), 0), mode); } }
package zxingdemo.lyb.com.zxingdemo.utils; import android.app.AlertDialog; import android.content.Context; import android.os.Bundle; import android.view.View; public class CoinToJiFenDialog extends AlertDialog { @SuppressWarnings("unused") private View view; protected CoinToJiFenDialog(Context context) { super(context); } public CoinToJiFenDialog(Context context, boolean cancelable, OnCancelListener cancelListener) { super(context, cancelable, cancelListener); } public CoinToJiFenDialog(Context context, int theme, View view) { super(context, theme); this.view = view; setContentView(view); } @Override protected void onCreate(Bundle savedInstanceState) { /* requestWindowFeature(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE); requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); getWindow().setBackgroundDrawableResource(android.R.color.transparent);*/ } }
package com.spothero.challenge.bo; import java.util.List; public class Rates { private List<Rate> rates; public List<Rate> getRates() { return rates; } public void setRates(List<Rate> rateList) { this.rates = rateList; } }
package rontikeky.beraspakone.Fragment; import android.app.ProgressDialog; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import rontikeky.beraspakone.ProductAdapter; import rontikeky.beraspakone.R; import rontikeky.beraspakone.app.ApiService; import rontikeky.beraspakone.app.appControllerRetro; import rontikeky.beraspakone.products.Product; import rontikeky.beraspakone.products.ProductList; /** * A simple {@link Fragment} subclass. */ public class fragment_home extends Fragment { private RecyclerView rvProduct; private LinearLayoutManager mProductLayoutManager; private ProductAdapter mProductAdapter; protected Context mCtx; ProgressBar pBar; ProgressDialog pDialog; List<Product> productList = new ArrayList<>(); public fragment_home() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_home, container, false); pBar = view.findViewById(R.id.pCircle); getAllProduct(); rvProduct = view.findViewById(R.id.rvProduct); rvProduct.setHasFixedSize(true); mProductLayoutManager = new GridLayoutManager(mCtx, 2); rvProduct.setLayoutManager(mProductLayoutManager); return view; } @Override public void onAttach(Context mCtx) { super.onAttach(mCtx); this.mCtx = mCtx; } private void getAllProduct() { pBar.setVisibility(View.VISIBLE); ApiService client = appControllerRetro.createService(ApiService.class, "Basic ZGV2ZWxvcG1lbnQ6"); Call<ProductList> call = client.getMyJSON(); call.enqueue(new Callback<ProductList>() { @Override public void onResponse(Call<ProductList> call, Response<ProductList> response) { pBar.setVisibility(View.GONE); if(response.isSuccessful()) { int i = 0; while (i < response.body().getProducts().size()) { Product dataProduct = new Product(response.body().getProducts().get(i).getIdProduct(), response.body().getProducts().get(i).getProductName(), response.body().getProducts().get(i).getProductDescription()); productList.add(dataProduct); i++; // Log.d("VARDUMP", String.valueOf(dataProduct.getProductName())); } productList = response.body().getProducts(); ProductAdapter adapter = new ProductAdapter(mCtx, productList){ //this is the magic, abstraction do public void onClickAndCount(Integer GT){ //proses parameter yang didapet di sini, misal angka yang diinput user dari adapter tadi, atau apapun, //terus taruh hasilnya di view activity ini, misal kalau casenya situ di bottomSHIT yah // TextView valGT = (TextView) findViewById(R.id.valGrandTotal); // valGT.setText(String.valueOf(GT)); } }; rvProduct.setAdapter(adapter); } else { Log.d("Error Home", response.message()); } } @Override public void onFailure(Call<ProductList> call, Throwable t) { // dialog.dismiss(); } }); } }
package com.example.event; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.MotionEvent; import android.widget.TextView; /** * Created by ouyangshen on 2017/11/23. */ @SuppressLint("DefaultLocale") public class TouchSingleActivity extends AppCompatActivity { private TextView tv_touch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_touch_single); tv_touch = findViewById(R.id.tv_touch); } // 在发生触摸事件时触发 public boolean onTouchEvent(MotionEvent event) { // 从开机到现在的毫秒数 int seconds = (int) (event.getEventTime() / 1000); int hour = seconds / 3600; int minute = seconds % 3600 / 60; int second = seconds % 60; String desc = String.format("动作发生时间:开机距离现在%02d:%02d:%02d", hour, minute, second); desc = String.format("%s\n动作名称是:", desc); // 获得触摸事件的动作类型 int action = event.getAction(); if (action == MotionEvent.ACTION_DOWN) { // 手指按下 desc = String.format("%s按下", desc); } else if (action == MotionEvent.ACTION_MOVE) { // 手指移动 desc = String.format("%s移动", desc); } else if (action == MotionEvent.ACTION_UP) { // 手指提起 desc = String.format("%s提起", desc); } else if (action == MotionEvent.ACTION_CANCEL) { // 取消手势 desc = String.format("%s取消", desc); } desc = String.format("%s\n动作发生位置是:横坐标%f,纵坐标%f", desc, event.getX(), event.getY()); tv_touch.setText(desc); return super.onTouchEvent(event); } }
package com.revature.model; import java.sql.Timestamp; public class Reimbursement { private int rid; private int eid_fk; private int approvedBy; private int rejectedBy; private String status; private Timestamp approvateDate; private Timestamp rejectedDate; private double amount; private byte[] image; private String category; private Timestamp submitDate; public Reimbursement(int eid_fk, double amount, String category) { super(); System.out.println("inside reimb cnstr"); this.eid_fk = eid_fk; this.amount = amount; this.category = category; } public Reimbursement(int rid, String status, Double amount, Timestamp timestamp) { this.rid = rid; this.status = status; this.amount = amount; this.submitDate = timestamp; System.out.println("timestamp " + timestamp); } public int getRid() { return rid; } public void setRid(int rid) { this.rid = rid; } public int getEid_fk() { return eid_fk; } public void setEid_fk(int eid_fk) { this.eid_fk = eid_fk; } public int getApprovedBy() { return approvedBy; } public void setApprovedBy(int approvedBy) { this.approvedBy = approvedBy; } public int getRejectedBy() { return rejectedBy; } public void setRejectedBy(int rejectedBy) { this.rejectedBy = rejectedBy; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Timestamp getApprovateDate() { return approvateDate; } public void setApprovateDate(Timestamp approvateDate) { this.approvateDate = approvateDate; } public Timestamp getRejectedDate() { return rejectedDate; } public void setRejectedDate(Timestamp rejectedDate) { this.rejectedDate = rejectedDate; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public byte[] getImage() { return image; } public void setImage(byte[] image) { this.image = image; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public Timestamp getSubmitDate() { return submitDate; } public void setSubmitDate(Timestamp submitDate) { this.submitDate = submitDate; } }
package com.lukian.productmicroservice.controller; import com.lukian.productmicroservice.entity.Product; import com.lukian.productmicroservice.service.ProductService; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/product") @Slf4j public class ProductController { private final ProductService service; public ProductController(ProductService service) { this.service = service; } @GetMapping("/all") public List<Product> getAll() { return service.getAll(); } @PostMapping() public void create(@RequestBody Product product) { service.createProduct(product); } @GetMapping("/{id}") public Product get(@PathVariable("id") int id) { return service.getByCreditId(id); } }
package com.cyberdust.automation.tools; import com.cyberdust.automation.elements.IOSElements; import org.junit.*; public class IOSAutoBlast extends IOSElements { String blast_recipient = "bktest02"; String blast_type = "text, photo"; // Use photo, video, text, or a combination of the 3 String blast_text = "Test"; // Only works for text blasts int number_of_blasts = 50; // Number of blasts per type public void photo_blast() throws Exception { Thread.sleep(500); action_menu().click(); Thread.sleep(500); action_menu_media().click(); photo_gallery().click(); camera_roll().click(); camera_roll_photo1().click(); next_button().click(); blast_friends().click(); username(blast_recipient).click(); blast_Ok_button().perform(); } public void video_blast() throws Exception { action_menu().click(); action_menu_media().click(); video_button().click(); action().longPress(photo_button(), 5000).release().perform(); next_button().click(); blast_friends().click(); username(blast_recipient).click(); blast_Ok_button().perform(); } public void text_blast() throws Exception { action_menu().click(); action_menu_text().click(); driver.getKeyboard().sendKeys(blast_text); next_button().click(); blast_friends().click(); username(blast_recipient).click(); blast_Ok_button().perform(); } @Test public void autoblast() throws Exception { for (int i = 0; i < number_of_blasts;) { if (blast_type.toLowerCase().contains("text".toLowerCase())) { text_blast(); System.out.println("Sending blast: #" + (i+1)); i+=1; } if (blast_type.toLowerCase().contains("photo".toLowerCase())) { photo_blast(); System.out.println("Sending blast: #" + (i+1)); i+=1; } if (blast_type.toLowerCase().contains("video".toLowerCase())) { video_blast(); System.out.println("Sending blast: #" + (i+1)); i+=1; } } } }
package me.krstic.xml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "Printform") @XmlAccessorType(XmlAccessType.FIELD) public class PrintForm { private String ACC_N11; private String ACCGN11; private String ACT_DA1; private String ACT_DAT; private String ACT3DA2; private String ACT3DAT; private String AMOUNT; private String AMOUNT1; private String AMOUNT2; private String AMOUNT3; private String AMOUNT4; private String AMOUNT5; private String AMOUNT6; private String AUTPNAM; private String BNK_NAM; private String C_NAM1; private String C_NAM2; private String CASHDID; private String CNR_CO2; private String CNR_COD; private String COD_TP2; private String CODEC1; private String CODEN1; private String CUR_BUY; private String CUR_CO2; private String CUR_CO3; private String CUR_CO4; private String CUR_CO7; private String CUR_COD; private String CUR_DAT; private String CUR_HS1; private String CUR_HST; private String CUR_NU2; private String CUR_NU3; private String CUR_NU4; private String CUR_NU7; private String CUR_NUM; private String CUR_SEL; private String CUR_UN1; private String CUR_UNT; private String CUR2UNT; private String CUR3UNT; private String DEN_EM1; private String DEN_EM2; private String DEN_EM3; private String DEN_EM4; private String DEN_EM5; private String DEN_EM6; private String DEN_EM7; private String DEN_EM8; private String DEN_EM9; private String DEN_EMA; private String DEN_EMB; private String DEN_EMC; private String DEN_EMD; private String DEN_UN1; private String DEN_UN2; private String DEN_UN3; private String DEN_UN4; private String DEN_UN5; private String DEN_UN6; private String DEN_UN7; private String DEN_UN8; private String DEN_UN9; private String DEN_UNA; private String DEN_UNB; private String DEN_UNC; private String DEN_UND; private String FR_AMO; private String MESS; private String MESSSC2; private String MESSSC3; private String NEWBAL; private String OPU_CO1; private String OPU_COD; private String P_OFEE; private String PIECE1; private String PIECE2; private String PIECE3; private String PIECE4; private String PIECE5; private String PIECE6; private String PIECE7; private String PIECE8; private String PIECE9; private String PIECEA; private String PIECEB; private String PIECEC; private String PIECED; private String PRN_A11; private String PRN_AL8; private String PRN_AL9; private String PRN_ALB; private String PRN_CRE; private String PRN_DEP; private String PRN_EQU; private String PRN_FRA; private String PRN_PAI; private String PRV_AMO; private String RAT_DIF; private String RATE; private String RATE1; private String REF_CHK; private String REF_NUM; private String REFTNUM; private String SEC_ORD; private String SEN_SEQ; private String SEQ_NUM; private String SIGN_1; private String SIGNCHK; private String TXSHORT; private String U_DATE; public PrintForm() { } public String getACC_N11() { return ACC_N11; } public void setACC_N11(String aCC_N11) { ACC_N11 = aCC_N11; } public String getACCGN11() { return ACCGN11; } public void setACCGN11(String aCCGN11) { ACCGN11 = aCCGN11; } public String getACT_DA1() { return ACT_DA1; } public void setACT_DA1(String aCT_DA1) { ACT_DA1 = aCT_DA1; } public String getACT_DAT() { return ACT_DAT; } public void setACT_DAT(String aCT_DAT) { ACT_DAT = aCT_DAT; } public String getACT3DA2() { return ACT3DA2; } public void setACT3DA2(String aCT3DA2) { ACT3DA2 = aCT3DA2; } public String getACT3DAT() { return ACT3DAT; } public void setACT3DAT(String aCT3DAT) { ACT3DAT = aCT3DAT; } public String getAMOUNT() { return AMOUNT; } public void setAMOUNT(String aMOUNT) { AMOUNT = aMOUNT; } public String getAMOUNT1() { return AMOUNT1; } public void setAMOUNT1(String aMOUNT1) { AMOUNT1 = aMOUNT1; } public String getAMOUNT2() { return AMOUNT2; } public void setAMOUNT2(String aMOUNT2) { AMOUNT2 = aMOUNT2; } public String getAMOUNT3() { return AMOUNT3; } public void setAMOUNT3(String aMOUNT3) { AMOUNT3 = aMOUNT3; } public String getAMOUNT4() { return AMOUNT4; } public void setAMOUNT4(String aMOUNT4) { AMOUNT4 = aMOUNT4; } public String getAMOUNT5() { return AMOUNT5; } public void setAMOUNT5(String aMOUNT5) { AMOUNT5 = aMOUNT5; } public String getAMOUNT6() { return AMOUNT6; } public void setAMOUNT6(String aMOUNT6) { AMOUNT6 = aMOUNT6; } public String getAUTPNAM() { return AUTPNAM; } public void setAUTPNAM(String aUTPNAM) { AUTPNAM = aUTPNAM; } public String getBNK_NAM() { return BNK_NAM; } public void setBNK_NAM(String bNK_NAM) { BNK_NAM = bNK_NAM; } public String getC_NAM1() { return C_NAM1; } public void setC_NAM1(String c_NAM1) { C_NAM1 = c_NAM1; } public String getC_NAM2() { return C_NAM2; } public void setC_NAM2(String c_NAM2) { C_NAM2 = c_NAM2; } public String getCASHDID() { return CASHDID; } public void setCASHDID(String cASHDID) { CASHDID = cASHDID; } public String getCNR_CO2() { return CNR_CO2; } public void setCNR_CO2(String cNR_CO2) { CNR_CO2 = cNR_CO2; } public String getCNR_COD() { return CNR_COD; } public void setCNR_COD(String cNR_COD) { CNR_COD = cNR_COD; } public String getCOD_TP2() { return COD_TP2; } public void setCOD_TP2(String cOD_TP2) { COD_TP2 = cOD_TP2; } public String getCODEC1() { return CODEC1; } public void setCODEC1(String cODEC1) { CODEC1 = cODEC1; } public String getCODEN1() { return CODEN1; } public void setCODEN1(String cODEN1) { CODEN1 = cODEN1; } public String getCUR_BUY() { return CUR_BUY; } public void setCUR_BUY(String cUR_BUY) { CUR_BUY = cUR_BUY; } public String getCUR_CO2() { return CUR_CO2; } public void setCUR_CO2(String cUR_CO2) { CUR_CO2 = cUR_CO2; } public String getCUR_CO3() { return CUR_CO3; } public void setCUR_CO3(String cUR_CO3) { CUR_CO3 = cUR_CO3; } public String getCUR_CO4() { return CUR_CO4; } public void setCUR_CO4(String cUR_CO4) { CUR_CO4 = cUR_CO4; } public String getCUR_CO7() { return CUR_CO7; } public void setCUR_CO7(String cUR_CO7) { CUR_CO7 = cUR_CO7; } public String getCUR_COD() { return CUR_COD; } public void setCUR_COD(String cUR_COD) { CUR_COD = cUR_COD; } public String getCUR_DAT() { return CUR_DAT; } public void setCUR_DAT(String cUR_DAT) { CUR_DAT = cUR_DAT; } public String getCUR_HS1() { return CUR_HS1; } public void setCUR_HS1(String cUR_HS1) { CUR_HS1 = cUR_HS1; } public String getCUR_HST() { return CUR_HST; } public void setCUR_HST(String cUR_HST) { CUR_HST = cUR_HST; } public String getCUR_NU2() { return CUR_NU2; } public void setCUR_NU2(String cUR_NU2) { CUR_NU2 = cUR_NU2; } public String getCUR_NU3() { return CUR_NU3; } public void setCUR_NU3(String cUR_NU3) { CUR_NU3 = cUR_NU3; } public String getCUR_NU4() { return CUR_NU4; } public void setCUR_NU4(String cUR_NU4) { CUR_NU4 = cUR_NU4; } public String getCUR_NU7() { return CUR_NU7; } public void setCUR_NU7(String cUR_NU7) { CUR_NU7 = cUR_NU7; } public String getCUR_NUM() { return CUR_NUM; } public void setCUR_NUM(String cUR_NUM) { CUR_NUM = cUR_NUM; } public String getCUR_SEL() { return CUR_SEL; } public void setCUR_SEL(String cUR_SEL) { CUR_SEL = cUR_SEL; } public String getCUR_UN1() { return CUR_UN1; } public void setCUR_UN1(String cUR_UN1) { CUR_UN1 = cUR_UN1; } public String getCUR_UNT() { return CUR_UNT; } public void setCUR_UNT(String cUR_UNT) { CUR_UNT = cUR_UNT; } public String getCUR2UNT() { return CUR2UNT; } public void setCUR2UNT(String cUR2UNT) { CUR2UNT = cUR2UNT; } public String getCUR3UNT() { return CUR3UNT; } public void setCUR3UNT(String cUR3UNT) { CUR3UNT = cUR3UNT; } public String getDEN_EM1() { return DEN_EM1; } public void setDEN_EM1(String dEN_EM1) { DEN_EM1 = dEN_EM1; } public String getDEN_EM2() { return DEN_EM2; } public void setDEN_EM2(String dEN_EM2) { DEN_EM2 = dEN_EM2; } public String getDEN_EM3() { return DEN_EM3; } public void setDEN_EM3(String dEN_EM3) { DEN_EM3 = dEN_EM3; } public String getDEN_EM4() { return DEN_EM4; } public void setDEN_EM4(String dEN_EM4) { DEN_EM4 = dEN_EM4; } public String getDEN_EM5() { return DEN_EM5; } public void setDEN_EM5(String dEN_EM5) { DEN_EM5 = dEN_EM5; } public String getDEN_EM6() { return DEN_EM6; } public void setDEN_EM6(String dEN_EM6) { DEN_EM6 = dEN_EM6; } public String getDEN_EM7() { return DEN_EM7; } public void setDEN_EM7(String dEN_EM7) { DEN_EM7 = dEN_EM7; } public String getDEN_EM8() { return DEN_EM8; } public void setDEN_EM8(String dEN_EM8) { DEN_EM8 = dEN_EM8; } public String getDEN_EM9() { return DEN_EM9; } public void setDEN_EM9(String dEN_EM9) { DEN_EM9 = dEN_EM9; } public String getDEN_EMA() { return DEN_EMA; } public void setDEN_EMA(String dEN_EMA) { DEN_EMA = dEN_EMA; } public String getDEN_EMB() { return DEN_EMB; } public void setDEN_EMB(String dEN_EMB) { DEN_EMB = dEN_EMB; } public String getDEN_EMC() { return DEN_EMC; } public void setDEN_EMC(String dEN_EMC) { DEN_EMC = dEN_EMC; } public String getDEN_EMD() { return DEN_EMD; } public void setDEN_EMD(String dEN_EMD) { DEN_EMD = dEN_EMD; } public String getDEN_UN1() { return DEN_UN1; } public void setDEN_UN1(String dEN_UN1) { DEN_UN1 = dEN_UN1; } public String getDEN_UN2() { return DEN_UN2; } public void setDEN_UN2(String dEN_UN2) { DEN_UN2 = dEN_UN2; } public String getDEN_UN3() { return DEN_UN3; } public void setDEN_UN3(String dEN_UN3) { DEN_UN3 = dEN_UN3; } public String getDEN_UN4() { return DEN_UN4; } public void setDEN_UN4(String dEN_UN4) { DEN_UN4 = dEN_UN4; } public String getDEN_UN5() { return DEN_UN5; } public void setDEN_UN5(String dEN_UN5) { DEN_UN5 = dEN_UN5; } public String getDEN_UN6() { return DEN_UN6; } public void setDEN_UN6(String dEN_UN6) { DEN_UN6 = dEN_UN6; } public String getDEN_UN7() { return DEN_UN7; } public void setDEN_UN7(String dEN_UN7) { DEN_UN7 = dEN_UN7; } public String getDEN_UN8() { return DEN_UN8; } public void setDEN_UN8(String dEN_UN8) { DEN_UN8 = dEN_UN8; } public String getDEN_UN9() { return DEN_UN9; } public void setDEN_UN9(String dEN_UN9) { DEN_UN9 = dEN_UN9; } public String getDEN_UNA() { return DEN_UNA; } public void setDEN_UNA(String dEN_UNA) { DEN_UNA = dEN_UNA; } public String getDEN_UNB() { return DEN_UNB; } public void setDEN_UNB(String dEN_UNB) { DEN_UNB = dEN_UNB; } public String getDEN_UNC() { return DEN_UNC; } public void setDEN_UNC(String dEN_UNC) { DEN_UNC = dEN_UNC; } public String getDEN_UND() { return DEN_UND; } public void setDEN_UND(String dEN_UND) { DEN_UND = dEN_UND; } public String getFR_AMO() { return FR_AMO; } public void setFR_AMO(String fR_AMO) { FR_AMO = fR_AMO; } public String getMESS() { return MESS; } public void setMESS(String mESS) { MESS = mESS; } public String getMESSSC2() { return MESSSC2; } public void setMESSSC2(String mESSSC2) { MESSSC2 = mESSSC2; } public String getMESSSC3() { return MESSSC3; } public void setMESSSC3(String mESSSC3) { MESSSC3 = mESSSC3; } public String getNEWBAL() { return NEWBAL; } public void setNEWBAL(String nEWBAL) { NEWBAL = nEWBAL; } public String getOPU_CO1() { return OPU_CO1; } public void setOPU_CO1(String oPU_CO1) { OPU_CO1 = oPU_CO1; } public String getOPU_COD() { return OPU_COD; } public void setOPU_COD(String oPU_COD) { OPU_COD = oPU_COD; } public String getP_OFEE() { return P_OFEE; } public void setP_OFEE(String p_OFEE) { P_OFEE = p_OFEE; } public String getPIECE1() { return PIECE1; } public void setPIECE1(String pIECE1) { PIECE1 = pIECE1; } public String getPIECE2() { return PIECE2; } public void setPIECE2(String pIECE2) { PIECE2 = pIECE2; } public String getPIECE3() { return PIECE3; } public void setPIECE3(String pIECE3) { PIECE3 = pIECE3; } public String getPIECE4() { return PIECE4; } public void setPIECE4(String pIECE4) { PIECE4 = pIECE4; } public String getPIECE5() { return PIECE5; } public void setPIECE5(String pIECE5) { PIECE5 = pIECE5; } public String getPIECE6() { return PIECE6; } public void setPIECE6(String pIECE6) { PIECE6 = pIECE6; } public String getPIECE7() { return PIECE7; } public void setPIECE7(String pIECE7) { PIECE7 = pIECE7; } public String getPIECE8() { return PIECE8; } public void setPIECE8(String pIECE8) { PIECE8 = pIECE8; } public String getPIECE9() { return PIECE9; } public void setPIECE9(String pIECE9) { PIECE9 = pIECE9; } public String getPIECEA() { return PIECEA; } public void setPIECEA(String pIECEA) { PIECEA = pIECEA; } public String getPIECEB() { return PIECEB; } public void setPIECEB(String pIECEB) { PIECEB = pIECEB; } public String getPIECEC() { return PIECEC; } public void setPIECEC(String pIECEC) { PIECEC = pIECEC; } public String getPIECED() { return PIECED; } public void setPIECED(String pIECED) { PIECED = pIECED; } public String getPRN_A11() { return PRN_A11; } public void setPRN_A11(String pRN_A11) { PRN_A11 = pRN_A11; } public String getPRN_AL8() { return PRN_AL8; } public void setPRN_AL8(String pRN_AL8) { PRN_AL8 = pRN_AL8; } public String getPRN_AL9() { return PRN_AL9; } public void setPRN_AL9(String pRN_AL9) { PRN_AL9 = pRN_AL9; } public String getPRN_ALB() { return PRN_ALB; } public void setPRN_ALB(String pRN_ALB) { PRN_ALB = pRN_ALB; } public String getPRN_CRE() { return PRN_CRE; } public void setPRN_CRE(String pRN_CRE) { PRN_CRE = pRN_CRE; } public String getPRN_DEP() { return PRN_DEP; } public void setPRN_DEP(String pRN_DEP) { PRN_DEP = pRN_DEP; } public String getPRN_EQU() { return PRN_EQU; } public void setPRN_EQU(String pRN_EQU) { PRN_EQU = pRN_EQU; } public String getPRN_FRA() { return PRN_FRA; } public void setPRN_FRA(String pRN_FRA) { PRN_FRA = pRN_FRA; } public String getPRN_PAI() { return PRN_PAI; } public void setPRN_PAI(String pRN_PAI) { PRN_PAI = pRN_PAI; } public String getPRV_AMO() { return PRV_AMO; } public void setPRV_AMO(String pRV_AMO) { PRV_AMO = pRV_AMO; } public String getRAT_DIF() { return RAT_DIF; } public void setRAT_DIF(String rAT_DIF) { RAT_DIF = rAT_DIF; } public String getRATE() { return RATE; } public void setRATE(String rATE) { RATE = rATE; } public String getRATE1() { return RATE1; } public void setRATE1(String rATE1) { RATE1 = rATE1; } public String getREF_CHK() { return REF_CHK; } public void setREF_CHK(String rEF_CHK) { REF_CHK = rEF_CHK; } public String getREF_NUM() { return REF_NUM; } public void setREF_NUM(String rEF_NUM) { REF_NUM = rEF_NUM; } public String getREFTNUM() { return REFTNUM; } public void setREFTNUM(String rEFTNUM) { REFTNUM = rEFTNUM; } public String getSEC_ORD() { return SEC_ORD; } public void setSEC_ORD(String sEC_ORD) { SEC_ORD = sEC_ORD; } public String getSEN_SEQ() { return SEN_SEQ; } public void setSEN_SEQ(String sEN_SEQ) { SEN_SEQ = sEN_SEQ; } public String getSEQ_NUM() { return SEQ_NUM; } public void setSEQ_NUM(String sEQ_NUM) { SEQ_NUM = sEQ_NUM; } public String getSIGN_1() { return SIGN_1; } public void setSIGN_1(String sIGN_1) { SIGN_1 = sIGN_1; } public String getSIGNCHK() { return SIGNCHK; } public void setSIGNCHK(String sIGNCHK) { SIGNCHK = sIGNCHK; } public String getTXSHORT() { return TXSHORT; } public void setTXSHORT(String tXSHORT) { TXSHORT = tXSHORT; } public String getU_DATE() { return U_DATE; } public void setU_DATE(String u_DATE) { U_DATE = u_DATE; } @Override public String toString() { return "PrintForm [ACC_N11=" + ACC_N11 + ", ACCGN11=" + ACCGN11 + ", ACT_DA1=" + ACT_DA1 + ", ACT_DAT=" + ACT_DAT + ", ACT3DA2=" + ACT3DA2 + ", ACT3DAT=" + ACT3DAT + ", AMOUNT=" + AMOUNT + ", AMOUNT1=" + AMOUNT1 + ", AMOUNT2=" + AMOUNT2 + ", AMOUNT3=" + AMOUNT3 + ", AMOUNT4=" + AMOUNT4 + ", AMOUNT5=" + AMOUNT5 + ", AMOUNT6=" + AMOUNT6 + ", AUTPNAM=" + AUTPNAM + ", BNK_NAM=" + BNK_NAM + ", C_NAM1=" + C_NAM1 + ", C_NAM2=" + C_NAM2 + ", CASHDID=" + CASHDID + ", CNR_CO2=" + CNR_CO2 + ", CNR_COD=" + CNR_COD + ", COD_TP2=" + COD_TP2 + ", CODEC1=" + CODEC1 + ", CODEN1=" + CODEN1 + ", CUR_BUY=" + CUR_BUY + ", CUR_CO2=" + CUR_CO2 + ", CUR_CO3=" + CUR_CO3 + ", CUR_CO4=" + CUR_CO4 + ", CUR_CO7=" + CUR_CO7 + ", CUR_COD=" + CUR_COD + ", CUR_DAT=" + CUR_DAT + ", CUR_HS1=" + CUR_HS1 + ", CUR_HST=" + CUR_HST + ", CUR_NU2=" + CUR_NU2 + ", CUR_NU3=" + CUR_NU3 + ", CUR_NU4=" + CUR_NU4 + ", CUR_NU7=" + CUR_NU7 + ", CUR_NUM=" + CUR_NUM + ", CUR_SEL=" + CUR_SEL + ", CUR_UN1=" + CUR_UN1 + ", CUR_UNT=" + CUR_UNT + ", CUR2UNT=" + CUR2UNT + ", CUR3UNT=" + CUR3UNT + ", DEN_EM1=" + DEN_EM1 + ", DEN_EM2=" + DEN_EM2 + ", DEN_EM3=" + DEN_EM3 + ", DEN_EM4=" + DEN_EM4 + ", DEN_EM5=" + DEN_EM5 + ", DEN_EM6=" + DEN_EM6 + ", DEN_EM7=" + DEN_EM7 + ", DEN_EM8=" + DEN_EM8 + ", DEN_EM9=" + DEN_EM9 + ", DEN_EMA=" + DEN_EMA + ", DEN_EMB=" + DEN_EMB + ", DEN_EMC=" + DEN_EMC + ", DEN_EMD=" + DEN_EMD + ", DEN_UN1=" + DEN_UN1 + ", DEN_UN2=" + DEN_UN2 + ", DEN_UN3=" + DEN_UN3 + ", DEN_UN4=" + DEN_UN4 + ", DEN_UN5=" + DEN_UN5 + ", DEN_UN6=" + DEN_UN6 + ", DEN_UN7=" + DEN_UN7 + ", DEN_UN8=" + DEN_UN8 + ", DEN_UN9=" + DEN_UN9 + ", DEN_UNA=" + DEN_UNA + ", DEN_UNB=" + DEN_UNB + ", DEN_UNC=" + DEN_UNC + ", DEN_UND=" + DEN_UND + ", FR_AMO=" + FR_AMO + ", MESS=" + MESS + ", MESSSC2=" + MESSSC2 + ", MESSSC3=" + MESSSC3 + ", NEWBAL=" + NEWBAL + ", OPU_CO1=" + OPU_CO1 + ", OPU_COD=" + OPU_COD + ", P_OFEE=" + P_OFEE + ", PIECE1=" + PIECE1 + ", PIECE2=" + PIECE2 + ", PIECE3=" + PIECE3 + ", PIECE4=" + PIECE4 + ", PIECE5=" + PIECE5 + ", PIECE6=" + PIECE6 + ", PIECE7=" + PIECE7 + ", PIECE8=" + PIECE8 + ", PIECE9=" + PIECE9 + ", PIECEA=" + PIECEA + ", PIECEB=" + PIECEB + ", PIECEC=" + PIECEC + ", PIECED=" + PIECED + ", PRN_A11=" + PRN_A11 + ", PRN_AL8=" + PRN_AL8 + ", PRN_AL9=" + PRN_AL9 + ", PRN_ALB=" + PRN_ALB + ", PRN_CRE=" + PRN_CRE + ", PRN_DEP=" + PRN_DEP + ", PRN_EQU=" + PRN_EQU + ", PRN_FRA=" + PRN_FRA + ", PRN_PAI=" + PRN_PAI + ", PRV_AMO=" + PRV_AMO + ", RAT_DIF=" + RAT_DIF + ", RATE=" + RATE + ", RATE1=" + RATE1 + ", REF_CHK=" + REF_CHK + ", REF_NUM=" + REF_NUM + ", REFTNUM=" + REFTNUM + ", SEC_ORD=" + SEC_ORD + ", SEN_SEQ=" + SEN_SEQ + ", SEQ_NUM=" + SEQ_NUM + ", SIGN_1=" + SIGN_1 + ", SIGNCHK=" + SIGNCHK + ", TXSHORT=" + TXSHORT + ", U_DATE=" + U_DATE + "]"; } }
/* * 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.time; import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.util.Date; import org.apache.commons.net.DatagramSocketClient; /** * The TimeUDPClient class is a UDP implementation of a client for the Time protocol described in RFC 868. To use the class, merely open a local datagram socket * with {@link org.apache.commons.net.DatagramSocketClient#open open } and call {@link #getTime getTime } or {@link #getTime getDate } to retrieve the time. * Then call {@link org.apache.commons.net.DatagramSocketClient#close close } to close the connection properly. Unlike * {@link org.apache.commons.net.time.TimeTCPClient}, successive calls to {@link #getTime getTime } or {@link #getDate getDate } are permitted without * re-establishing a connection. That is because UDP is a connectionless protocol and the Time protocol is stateless. * * * @see TimeTCPClient */ public final class TimeUDPClient extends DatagramSocketClient { /** The default time port. It is set to 37 according to RFC 868. */ public static final int DEFAULT_PORT = 37; /** * The number of seconds between 00:00 1 January 1900 and 00:00 1 January 1970. This value can be useful for converting time values to other formats. */ public static final long SECONDS_1900_TO_1970 = 2208988800L; private final byte[] dummyData = new byte[1]; private final byte[] timeData = new byte[4]; /** * Same as <code> getTime(host, DEFAULT_PORT); </code> * * @param host the time-server * @return the date * @throws IOException on error */ public Date getDate(final InetAddress host) throws IOException { return new Date((getTime(host, DEFAULT_PORT) - SECONDS_1900_TO_1970) * 1000L); } /** * Retrieves the time from the server and returns a Java Date containing the time converted to the local time zone. * * @param host The address of the server. * @param port The port of the service. * @return A Date value containing the time retrieved from the server converted to the local time zone. * @throws IOException If an error occurs while fetching the time. */ public Date getDate(final InetAddress host, final int port) throws IOException { return new Date((getTime(host, port) - SECONDS_1900_TO_1970) * 1000L); } /** * Same as <code> getTime(host, DEFAULT_PORT); </code> * * @param host the time-server * @return the time returned from the server * @throws IOException on error */ public long getTime(final InetAddress host) throws IOException { return getTime(host, DEFAULT_PORT); } /** * Retrieves the time from the specified server and port and returns it. The time is the number of seconds since 00:00 (midnight) 1 January 1900 GMT, as * specified by RFC 868. This method reads the raw 32-bit big-endian unsigned integer from the server, converts it to a Java long, and returns the value. * * @param host The address of the server. * @param port The port of the service. * @return The time value retrieved from the server. * @throws IOException If an error occurs while retrieving the time. */ public long getTime(final InetAddress host, final int port) throws IOException { final DatagramPacket sendPacket = new DatagramPacket(dummyData, dummyData.length, host, port); final DatagramPacket receivePacket = new DatagramPacket(timeData, timeData.length); checkOpen().send(sendPacket); checkOpen().receive(receivePacket); long time = 0L; time |= (((timeData[0] & 0xff) << 24) & 0xffffffffL); time |= (((timeData[1] & 0xff) << 16) & 0xffffffffL); time |= (((timeData[2] & 0xff) << 8) & 0xffffffffL); time |= ((timeData[3] & 0xff) & 0xffffffffL); return time; } }
package pl.mgd.jdbc.listener; import java.sql.SQLException; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import pl.mgd.jdbc.db.DbUtil; /* *DbInitListener This class implements interface ServletContextListener, * and because is registered as a Listener her methods will be called during creation an app */ @WebListener public class DbInitListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent arg0) { DbUtil.getInstance().close(); System.out.println("Context Destroyed"); } @Override public void contextInitialized(ServletContextEvent arg0) { System.out.println("Context initialized"); try { DbUtil.getInstance().getConnection(); } catch(SQLException e) { e.printStackTrace(); } } }
/* * 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 de.projekt.controller; import de.projekt.model.Karteikarte; import de.projekt.model.Player; import de.projekt.model.Werte; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author Jonas */ @WebServlet(name = "SingleplayerController", urlPatterns = {"/SingleplayerController"}) public class SingleplayerController extends HttpServlet implements Werte{ public static int count; public Karteikarte single; public int setsize; public static int right=0; public static int wrong=0; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); //______________________________ Ausgabe der Karten count = (int) session.getAttribute("count"); single = (Karteikarte) session.getAttribute("single"); setsize = single.getPlaysetSize(); int answer = Integer.parseInt(request.getParameter("id")); // Wenn answer 1 dann wurde die Frage richtig beantwortet, wenn 0 dann falsch if(answer==1) right++; else wrong++; Player currentplayer = (Player) session.getAttribute("player"); currentplayer.setUserAnswer(answer,single.getPlayset(count),single.getPlayer()); count++; if(count>=setsize){ request.setAttribute("right",right); request.setAttribute("wrong",wrong); session.removeAttribute("count"); request.getRequestDispatcher("/WEB-INF/views/EndResult.jsp").forward(request, response); right = wrong = 0; } else{ //Gibt die jeweilige Frage aus String question= single.getQuestion(count); String correctAnswer= single.getCorrectAnswer(count); session.setAttribute("count", count); request.setAttribute("question",question); request.setAttribute("answer",correctAnswer); request.getRequestDispatcher("/WEB-INF/views/AusgabeSinglePlayer.jsp").forward(request, response); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
package graphics; import java.awt.Color; import java.awt.GridLayout; import javax.swing.JButton; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import game.Game; import _aux.CustomTypes; // Game controls public class Control extends graphics.Box { public Control(int w, int h, Game g) { super(w, h, new GridLayout(1, 2, 0, 0)); JButton turn = new JButton("Run turn"); JButton timestamp = new JButton("Autoplay"); // Button actions (triggers a flag in the game object) turn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (g.gm != CustomTypes.GameMode.TURN) { g.gm = CustomTypes.GameMode.TURN; System.out.println("[Control] - Game mode switched to \"TURN\""); } g.controlFeedback(CustomTypes.GameMode.TURN); } }); timestamp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (g.gm != CustomTypes.GameMode.TIMESTAMP) { g.gm = CustomTypes.GameMode.TIMESTAMP; System.out.println("[Control] - Game mode switched to \"TIMESTAMP\""); } g.controlFeedback(CustomTypes.GameMode.TIMESTAMP); } }); this.add(turn); this.add(timestamp); } }
package jc.sugar.JiaHui.jmeter.postprocessor; import jc.sugar.JiaHui.jmeter.*; import org.apache.jmeter.extractor.XPathExtractor; import java.util.HashMap; import java.util.Map; import static org.apache.jorphan.util.Converter.getBoolean; import static org.apache.jorphan.util.Converter.getString; @JMeterElementMapperFor(value = JMeterElementType.XPathExtractor, testGuiClass = JMeterElement.XPathExtractor) public class XPathExtractorMapper extends AbstractJMeterElementMapper<XPathExtractor> { public static final String WEB_TOLERANT = "tolerant"; public static final String WEB_QUIET = "quiet"; public static final String WEB_REPORT_ERRORS = "reportErrors"; public static final String WEB_SHOW_WARNINGS = "showWarnings"; public static final String WEB_FRAGMENT = "fragment"; public static final String WEB_NAMESPACE = "namespace"; public static final String WEB_VALIDATE = "validate"; public static final String WEB_WHITESPACE = "whitespace"; public static final String WEB_DOWNLOAD_DTDS = "downloadDtds"; public static final String WEB_REF_NAME = "refName"; public static final String WEB_XPATH_QUERY = "xpathQuery"; public static final String WEB_MATCH_NUMBER = "matchNumber"; public static final String WEB_DEFAULT = "default"; private XPathExtractorMapper(XPathExtractor element, Map<String, Object> attributes) { super(element, attributes); } public XPathExtractorMapper(Map<String, Object> attributes){ this(new XPathExtractor(), attributes); } public XPathExtractorMapper(XPathExtractor element){ this(element, new HashMap<>()); } @Override public XPathExtractor fromAttributes() { element.setTolerant(getBoolean(attributes.get(WEB_TOLERANT))); element.setQuiet(getBoolean(attributes.get(WEB_QUIET))); element.setReportErrors(getBoolean(attributes.get(WEB_REPORT_ERRORS))); element.setShowWarnings(getBoolean(attributes.get(WEB_SHOW_WARNINGS))); element.setFragment(getBoolean(attributes.get(WEB_FRAGMENT))); element.setNameSpace(getBoolean(attributes.get(WEB_NAMESPACE))); element.setValidating(getBoolean(attributes.get(WEB_VALIDATE))); element.setWhitespace(getBoolean(attributes.get(WEB_WHITESPACE))); element.setDownloadDTDs(getBoolean(attributes.get(WEB_DOWNLOAD_DTDS))); element.setRefName(getString(attributes.get(WEB_REF_NAME))); element.setXPathQuery(getString(attributes.get(WEB_XPATH_QUERY))); element.setMatchNumber(getString(attributes.get(WEB_MATCH_NUMBER))); element.setDefaultValue(getString(attributes.get(WEB_DEFAULT))); return element; } @Override public Map<String, Object> toAttributes() { attributes.put(WEB_CATEGORY, JMeterElementCategory.Postprocessor); attributes.put(WEB_TYPE, JMeterElementType.XPathExtractor); attributes.put(WEB_TOLERANT, element.isTolerant()); attributes.put(WEB_QUIET, element.isQuiet()); attributes.put(WEB_REPORT_ERRORS, element.reportErrors()); attributes.put(WEB_SHOW_WARNINGS, element.showWarnings()); attributes.put(WEB_FRAGMENT, element.getFragment()); attributes.put(WEB_NAMESPACE, element.useNameSpace()); attributes.put(WEB_VALIDATE, element.isValidating()); attributes.put(WEB_WHITESPACE, element.isWhitespace()); attributes.put(WEB_DOWNLOAD_DTDS, element.isDownloadDTDs()); attributes.put(WEB_REF_NAME, element.getRefName()); attributes.put(WEB_XPATH_QUERY, element.getXPathQuery()); attributes.put(WEB_MATCH_NUMBER, element.getMatchNumberAsString()); attributes.put(WEB_DEFAULT, element.getDefaultValue()); return attributes; } }
package com.jim.multipos.data.operations; import io.reactivex.Observable; /** * Created by user on 12.09.17. */ public interface JoinCustomerGroupWithCustomerOperations { Observable<Long> addCustomerToCustomerGroup(Long customerGroupId, Long customerId); Observable<Boolean> removeCustomerFromCustomerGroup(Long customerGroupId, Long customerId); Observable<Boolean> removeJoinCustomerGroupWithCustomer(Long customerId); }
package com.hesoyam.pharmacy.appointment.dto; import com.hesoyam.pharmacy.appointment.model.CheckUp; import com.hesoyam.pharmacy.util.DateTimeRange; public class FutureCheckupDTO { Long id; String pharmacyName; String dermatologistFullName; DateTimeRange range; Double price; public FutureCheckupDTO() { //Empty ctor for JSON serializer } public FutureCheckupDTO(CheckUp checkUp) { this.id = checkUp.getId(); this.pharmacyName = checkUp.getPharmacy().getName(); this.dermatologistFullName = checkUp.getDermatologist().getFirstName()+" "+checkUp.getDermatologist().getLastName(); this.range = checkUp.getDateTimeRange(); this.price = checkUp.getPrice(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getPharmacyName() { return pharmacyName; } public void setPharmacyName(String pharmacyName) { this.pharmacyName = pharmacyName; } public String getDermatologistFullName() { return dermatologistFullName; } public void setDermatologistFullName(String dermatologistFullName) { this.dermatologistFullName = dermatologistFullName; } public DateTimeRange getRange() { return range; } public void setRange(DateTimeRange range) { this.range = range; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } }
package semantics.model; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; import semantics.KnowBase; import static semantics.KnowBase.toTaggedArray; public class Inversion extends Roleish { private final Roleish r; public Inversion(Roleish r) { this.r = r; } @Override public void checkSignature(KnowBase kb) { r.checkSignature(kb); } @Override public JsonElement toJson() { return toTaggedArray("i", r.toJson()); } @Override public boolean containsUnknown() { return r.containsUnknown(); } @Override public Roleish stripUnknown() { return containsUnknown() ? new Full() : this; } @Override public String toString() { return String.format("%s⁻", r); } @Override public boolean equals(Object o) { if (o instanceof Inversion) { return r.equals(((Inversion) o).r); } return false; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package creationFichier; import au.com.bytecode.opencsv.CSVReader; import au.com.bytecode.opencsv.CSVWriter; import java.io.*; /** * * @author Administrateur */ public class NewClass { public static void main(String[] args) throws FileNotFoundException, IOException { CSVWriter writer = new CSVWriter(new OutputStreamWriter(new FileOutputStream("data/extract/extractMotMot/nbr/extractall1.csv"), "UTF-8"), '\t',CSVWriter.NO_QUOTE_CHARACTER); int i=1; while(i<18220){ CSVReader scanner1=new CSVReader(new FileReader("data/extract/extractMotMot/nbr/extract"+i+".csv"),'\t'); String[] line1; while((line1=scanner1.readNext())!=null){ writer.writeNext(line1); } i++; } writer.close(); } }
/* * Copyright (C) 2010-2012, Wan Lee, wan5332@gmail.com * Source can be obtained from git://github.com/wanclee/datashaper.git * BSD-style license. Please read license.txt that comes with source files */ /** * */ package com.psrtoolkit.datashaper.enumeration; /** * @author Wan * */ public enum PopulationMode { CREATE_NEW, USE_EXISTING; }
package algorithm.swea.D4; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class _3124_MST { static int v, e; static ArrayList<Edge> edges; static int[] nodes; static long answer; static class Edge implements Comparable<Edge> { int from; int to; long cost; Edge(int from, int to, long cost) { this.from = from; this.to = to; this.cost = cost; } @Override public int compareTo(Edge o) { return Long.compare(this.cost, o.cost); } } static int find(int x) { if (nodes[x] == x) return x; return nodes[x] = find(nodes[x]); } static boolean union(int x, int y) { int xRoot = find(x); int yRoot = find(y); if (xRoot == yRoot) return false; nodes[yRoot] = xRoot; return true; } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; StringBuilder sb = new StringBuilder(); int T = Integer.parseInt(br.readLine()); for (int tc = 1; tc <= T; tc++) { st = new StringTokenizer(br.readLine()); v = Integer.parseInt(st.nextToken()); e = Integer.parseInt(st.nextToken()); edges = new ArrayList<>(); nodes = new int[v + 1]; answer = 0; for (int i = 1; i <= v; i++) { nodes[i] = i; } for (int i = 0; i < e; i++) { st = new StringTokenizer(br.readLine()); int from = Integer.parseInt(st.nextToken()); int to = Integer.parseInt(st.nextToken()); long cost = Long.parseLong(st.nextToken()); edges.add(new Edge(from, to, cost)); } Collections.sort(edges); int cnt = 0; for (Edge edge : edges) { if (cnt == v - 1) break; if (union(edge.from, edge.to)) { answer += edge.cost; cnt++; } } sb.append("#").append(tc).append(" ").append(answer).append("\n"); } System.out.print(sb); } }
package ba.bitcamp.LaBS03D03; public class FunkUnosFunkNizaISabiranjeIIspisnajmanjeg { /** * Ubacuje integere u niz * @param num2 Unesena duzina niza * @return niz popunjen integerima */ public static int[] unosNiza(int num2) { int [] drugiNiz = new int [num2]; for(int i=0; i<drugiNiz.length; i++) { System.out.print("Unesite broj: "); int num = TextIO.getlnInt(); drugiNiz [i] = num; } return drugiNiz; } /** * Ispisuje niz * @param niz Uneseni niz */ public static void print(int[] niz) { for(int i = 0; i < niz.length; i++) { System.out.print("Clanovi niza su: "); System.out.print(niz[i] + " "); } System.out.println(); } /** * Sabira niz * @param niz Uneseni niz * @return sumu niza */ public static int sabiranje(int[] niz) { int suma = 0; for(int i=0; i < niz.length; i++) { suma = suma + niz[i]; } return suma; } /** * Funkcija najmanjeg clana niza * @param niz * @return Vraca najmanji clan niza */ public static int najmanjiClan(int[] niz) { int temp = niz[0]; for(int i=0; i < niz.length; i++) { if(temp > niz[i]) { temp = niz[i]; } } return temp; } /** * Funkcija najveceg clana niza * @param niz * @return Vraca najveci clan niza */ public static int najveciClan(int[] niz) { int temp = 0; for(int i=0; i < niz.length; i++) { if(temp < niz[i]) { temp = niz[i]; } } return temp; } public static void main(String[] args) { System.out.print("Unesite velicinu niza: "); int num2 = TextIO.getlnInt(); int[] niz = unosNiza(num2); print(niz); int suma = sabiranje(niz); System.out.println("Suma niza je: " + suma); int min = najmanjiClan(niz); System.out.println("Najmanji clan niza je: " + min); int max = najveciClan(niz); System.out.println("Najveci clan niza je: " + max); } }
package com.ecommerce.domain.categorias; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.OneToMany; import org.modelmapper.ModelMapper; import com.ecommerce.domain.carrinhos.CarrinhoProduto; import com.ecommerce.domain.categoriaproduto.CategoriaProduto; import com.ecommerce.domain.cortamproduto.CorTamProduto; import com.ecommerce.domain.favoritos.Favorito; import com.ecommerce.domain.fotos.FotoProduto; public class CategoriaDTO { private Long id; private String titulo; private byte[] foto; private List<CategoriaProduto> categoriaProdutos; public static CategoriaDTO create(Categoria categoria) { ModelMapper modelMapper = new ModelMapper(); return modelMapper.map(categoria, CategoriaDTO.class); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitulo() { return titulo; } public void setTitulo(String titulo) { this.titulo = titulo; } public byte[] getFoto() { return foto; } public void setFoto(byte[] foto) { this.foto = foto; } public List<CategoriaProduto> getCategoriaProdutos() { return categoriaProdutos; } public void setCategoriaProdutos(List<CategoriaProduto> categoriaProdutos) { this.categoriaProdutos = categoriaProdutos; } }
package com.gmail.khanhit100896.foody.account; import android.annotation.SuppressLint; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.gmail.khanhit100896.foody.R; import com.gmail.khanhit100896.foody.config.Config; import com.gmail.khanhit100896.foody.config.RoundedTransformation; import com.gmail.khanhit100896.foody.food.FoodActivity; import com.gmail.khanhit100896.foody.history.HistoryActivity; import com.gmail.khanhit100896.foody.home.HomRestaurantActivity; import com.gmail.khanhit100896.foody.like.LikeActivity; import com.gmail.khanhit100896.foody.main.LoginActivity; import com.google.firebase.auth.FirebaseUser; import com.squareup.picasso.Picasso; /** * A simple {@link Fragment} subclass. */ public class AccountFragment extends Fragment { protected View view; protected TextView txt_trang_chu, txt_nha_hang,txt_mon_an,txt_yeu_thich,txt_lich_su,txt_dang_nhap,txt_dang_xuat; protected int REQUEST_CODE = 1; // User info protected ImageView imgUser; protected TextView txtUserNameMain; protected TextView txtEmailMain; public AccountFragment() { // Required empty public constructor } @SuppressLint("ResourceAsColor") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment this.view = inflater.inflate(R.layout.fragment_account, container, false); init(); // Hàm lấy thông tin user khi đã đăng nhập rồi final FirebaseUser user = Config.getConfig().getmAuth().getInstance().getCurrentUser(); if (user != null) { this.txt_dang_nhap.setEnabled(false); this.txt_dang_nhap.setTextColor(Color.GRAY); txt_dang_xuat.setEnabled(true); txt_dang_xuat.setTextColor(Color.BLACK); // Name, email address, and profile photo Url String name = user.getDisplayName(); String email = user.getEmail(); String photoUrl = user.getPhotoUrl().toString(); Picasso.get().load(photoUrl) .transform(new RoundedTransformation(60, 0)) .into(this.imgUser); this.txtUserNameMain.setText(name); this.txtEmailMain.setText(email); } else{ txt_dang_xuat.setEnabled(false); txt_dang_xuat.setTextColor(Color.GRAY); } this.txt_trang_chu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().recreate(); } }); this.txt_nha_hang.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getContext(),HomRestaurantActivity.class)); } }); this.txt_mon_an.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getContext(),FoodActivity.class)); } }); this.txt_yeu_thich.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getContext(),LikeActivity.class)); } }); this.txt_lich_su.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getContext(),HistoryActivity.class)); } }); this.txt_dang_nhap.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(),LoginActivity.class); String context = AccountFragment.class.getSimpleName(); intent.putExtra("context",context); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } }); this.txt_dang_xuat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Config.getConfig().signOut(); imgUser.setImageResource(0); txtUserNameMain.setText(""); txtEmailMain.setText(""); txt_dang_nhap.setEnabled(true); txt_dang_nhap.setTextColor(Color.BLACK); Toast toast = Toast.makeText(getContext(),"Đăng xuất thành công",Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER,0,0); toast.show(); getActivity().recreate(); } }); return this.view; } private void init() { this.imgUser = this.view.findViewById(R.id.imgUser); this.txtUserNameMain = this.view.findViewById(R.id.txtUserNameMain); this.txtEmailMain = this.view.findViewById(R.id.txtEmailMain); this.txt_trang_chu = this.view.findViewById(R.id.txt_trang_chu); this.txt_nha_hang = this.view.findViewById(R.id.txt_nha_hang); this.txt_mon_an = this.view.findViewById(R.id.txt_mon_an); this.txt_yeu_thich = this.view.findViewById(R.id.txt_yeu_thich); this.txt_lich_su = this.view.findViewById(R.id.txt_lich_su); this.txt_dang_nhap = this.view.findViewById(R.id.txt_dang_nhap); this.txt_dang_xuat = this.view.findViewById(R.id.txt_dang_xuat); } }
package operations.commands; import graphana.MainControl; import graphana.operationsystem.Command; import graphana.operationsystem.OperationArguments; import graphana.operationsystem.OperationDescFile; import graphana.operationsystem.OperationGroup; import scriptinterface.execution.returnvalues.ExecutionReturn; public class CmdsProgress extends OperationGroup implements OperationDescFile { private Object progressSender = new Object(); public Command[] getOperations() { return new Command[]{new ExecEnableScriptProgress(), new ExecDisableScriptProgress(), new ExecSetProgress(), new ExecSetProgressMessage()}; } @Override public String getDescriptionFilename() { return CMDSDIR + "color.xml"; } private class ExecEnableScriptProgress extends Command { @Override protected ExecutionReturn execute(MainControl mainControl, OperationArguments args) { mainControl.getUserInterface().setProgressSender(progressSender); return ExecutionReturn.VOID; } @Override protected String getSignatureString() { return "enableScriptProgress () : void"; } } private class ExecDisableScriptProgress extends Command { @Override protected ExecutionReturn execute(MainControl mainControl, OperationArguments args) { mainControl.getUserInterface().setProgressSender(null); mainControl.getUserInterface().hideProgressOutput(); return ExecutionReturn.VOID; } @Override protected String getSignatureString() { return "disableScriptProgress () : void"; } } private class ExecSetProgress extends Command { @Override protected ExecutionReturn execute(MainControl mainControl, OperationArguments args) { mainControl.getUserInterface().setProgress(progressSender, args.getFloatArg(0)); return ExecutionReturn.VOID; } @Override protected String getSignatureString() { return "setProgress (progress:Float) : void"; } } private class ExecSetProgressMessage extends Command { @Override protected ExecutionReturn execute(MainControl mainControl, OperationArguments args) { mainControl.getUserInterface().setProgressMessage(progressSender, args.getStringArg(0)); return ExecutionReturn.VOID; } @Override protected String getSignatureString() { return "setProgressMessage (message:String) : void"; } } }
package com.tencent.mm.plugin.sns.ui.previewimageview; public interface DynamicGridView$f { void bEN(); }
//@@author A0139772U package seedu.whatnow.ui; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.control.TextArea; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Border; import javafx.scene.layout.GridPane; import javafx.scene.paint.Paint; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Stage; /** * A ui for the status bar that is displayed at the header of the application. */ public class StatusPanel extends UiPart { public static final String STATUS_DISPLAY_ID = "statusPanel"; private TextArea statusDisplayArea; private final StringProperty displayed = new SimpleStringProperty(""); private static final String FXML = "StatusPanel.fxml"; private AnchorPane placeHolder; private AnchorPane mainPane; private GridPane gridPane; public static StatusPanel load(Stage primaryStage, AnchorPane placeHolder, GridPane gridPane) { StatusPanel statusBar = UiPartLoader.loadUiPart(primaryStage, placeHolder, new StatusPanel()); statusBar.configure(gridPane); return statusBar; } public void configure(GridPane gridPane) { this.gridPane = gridPane; Image image = new Image("/images/WhatNowWhiteOnBlue.png"); ImageView iv1 = new ImageView(); iv1.setImage(image); iv1.setFitWidth(350); iv1.setFitHeight(178); TextArea statusDisplayArea = new TextArea(); statusDisplayArea.setEditable(false); statusDisplayArea.setId(STATUS_DISPLAY_ID); statusDisplayArea.textProperty().bind(displayed); statusDisplayArea.setMaxWidth(350); statusDisplayArea.setMinHeight(60); statusDisplayArea.setMaxHeight(60); statusDisplayArea.setPadding(Insets.EMPTY); statusDisplayArea.setFont(Font.font(15)); statusDisplayArea.setBorder(Border.EMPTY); Text pinHeader = new Text(); pinHeader.setText("Pinned Items"); pinHeader.setFont(Font.font(20)); pinHeader.setFill(Paint.valueOf("white")); gridPane.add(iv1, 0, 0, 1, 1); gridPane.add(statusDisplayArea, 0, 1, 1, 1); gridPane.add(pinHeader, 0, 2, 1, 1); GridPane.setHalignment(gridPane.getChildren().get(4), HPos.CENTER); } @Override public void setNode(Node node) { mainPane = (AnchorPane) node; } @Override public void setPlaceholder(AnchorPane placeholder) { this.placeHolder = placeholder; } @Override public String getFxmlPath() { return FXML; } public void postMessage(String message) { displayed.setValue(message); } }
package processingdraw; import de.fhpotsdam.unfolding.Map; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.marker.SimplePointMarker; import de.fhpotsdam.unfolding.providers.Google; import de.fhpotsdam.unfolding.utils.MapUtils; import processing.core.PApplet; public class EarthquakeCityMapM extends PApplet { private UnfoldingMap map; public void setup(){ size(950,600,OPENGL);//Specify OPENGL renderer map = new UnfoldingMap(this, 200, 50, 700, 500, new Google.GoogleMapProvider()); map.zoomToLevel(2); MapUtils.createDefaultEventDispatcher(this, map); } public void draw(){ Location jpLoc=new Location(-38.14f,-73.03f); SimplePointMarker jp= new SimplePointMarker(jpLoc); map.addMarker(jp); background(255,200,200); map.draw(); // addkey(); } }
package com.xhpower.qianmeng.dao; import com.xhpower.qianmeng.entity.User; import com.baomidou.mybatisplus.mapper.BaseMapper; /** * <p> * Mapper 接口 * </p> * * @author xc * @since 2018-07-25 */ public interface UserMapper extends BaseMapper<User> { }
package com.tencent.mm.g.a; import com.tencent.mm.sdk.b.b; public final class gh extends b { public a bPv; public gh() { this((byte) 0); } private gh(byte b) { this.bPv = new a(); this.sFm = false; this.bJX = null; } }
package eprudnikov.homebanking.citibank; import eprudnikov.homebanking.common.CategoryProvider; import org.junit.Before; import org.junit.Test; import java.util.*; import static org.junit.Assert.*; public class CitibankStatementProcessorTest { private CitibankStatementProcessor processor; private Map<String, String> categories; @Before public void setUp() { categories = new HashMap<>(); categories.put("S1", "C1"); categories.put("ig", CategoryProvider.IGNORE_CATEGORY); // TODO try mock in this case processor = new CitibankStatementProcessor(new CategoryProvider() { @Override public Set<String> getCategory(String source) { Set<String> result = new HashSet<>(); result.add(categories.containsKey(source) ? categories.get(source) : UNKNOWN_CATEGORY); return result; } }); } @Test public void testEmptyOrNullStatement() { Map<String, Double> result = processor.processStatement(null); assertNotNull(result); assertTrue(result.isEmpty()); result = processor.processStatement(new ArrayList<>()); assertNotNull(result); assertTrue(result.isEmpty()); } @Test public void testSimpleStatement() { List<String> data = new ArrayList<>(); data.add("\"25/02/2015\",\"S1\",\"-100\",\"'5256897087510003'\""); Map<String, Double> result = processor.processStatement(data); assertNotNull(result); assertEquals(1, result.size()); assertTrue(result.containsKey("C1")); assertTrue(result.containsValue(-100.)); data.add("\"25/02/2015\",\"S1\",\"-100\",\"'5256897087510003'\""); data.add("\"25/02/2015\",\"S2\",\"-10.123\",\"'5256897087510003'\""); result = processor.processStatement(data); assertNotNull(result); assertEquals(2, result.size()); assertTrue(result.containsKey("C1")); // TODO is it possible to replace it by lambda? assertTrue(result.containsValue(-200.)); assertTrue(result.containsKey(CategoryProvider.UNKNOWN_CATEGORY)); assertTrue(result.containsValue(-10.123)); } @Test public void testIgnoringOfIncome() { List<String> data = new ArrayList<>(); data.add("\"25/02/2015\",\"S1\",\"-100\",\"'5256897087510003'\""); data.add("\"25/02/2015\",\"S1\",\"10\",\"'5256897087510003'\""); data.add("\"25/02/2015\",\"S2\",\"10\",\"'5256897087510003'\""); Map<String, Double> result = processor.processStatement(data); assertNotNull(result); assertEquals(1, result.size()); assertTrue(result.containsKey("C1")); assertTrue(result.containsValue(-100.)); } @Test public void testIgnoreCategory() { List<String> data = new ArrayList<>(); data.add("\"25/02/2015\",\"S1\",\"-100\",\"'5256897087510003'\""); data.add("\"25/02/2015\",\"ig\",\"-100\",\"'5256897087510003'\""); Map<String, Double> result = processor.processStatement(data); assertNotNull(result); assertEquals(1, result.size()); assertTrue(result.containsKey("C1")); assertTrue(result.containsValue(-100.)); } }
package scriptinterface.defaulttypes; import scriptinterface.ScriptType; import java.io.File; /** * Script type wrapper for files. The file is assumed to exist. */ public class GExistingFile extends GFile implements TextHolder { private final static ScriptType TYPE = new ScriptType("ExistingFile", "File"); public GExistingFile(File value) { super(value); } public GExistingFile() { this(null); } @Override public ScriptType getType() { return TYPE; } @Override public GExistingFile clone() { return new GExistingFile(value); } }
import io.appium.java_client.MobileBy; import io.appium.java_client.android.AndroidDriver; import java.net.URL; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class Forgot_Password_Test { private static final String APP = "/Users/Gordon/Downloads/Twiga DMS v3.11.0-210317_0912(STAGING).apk"; private static final String APPIUM = "http://localhost:4723/wd/hub"; private AndroidDriver driver; @Before public void setUp() throws Exception { DesiredCapabilities caps = new DesiredCapabilities(); caps.setCapability("platformName", "Android"); caps.setCapability("platformVersion", "11"); caps.setCapability("deviceName", "Android Emulator"); caps.setCapability("automationName", "UiAutomator2"); caps.setCapability("app", APP); driver = new AndroidDriver(new URL(APPIUM), caps); try { Thread.sleep(3000); } catch (Exception ign) {} } @After public void tearDown() { if (driver != null) { driver.quit(); } } @Test public void test() { WebDriverWait wait = new WebDriverWait(driver, 30); WebElement forgot_password = driver.findElement(MobileBy.id("com.twigafoods.soko.staging:id/btnForgotPin")); forgot_password.click(); WebElement username_pass = wait.until(ExpectedConditions.presenceOfElementLocated(MobileBy.id("com.twigafoods.soko.staging:id/edtPhoneNumber"))); username_pass.sendKeys("0729055307"); } }
package com.walkerwang.algorithm.goldcode; /**高度最小的BST * * 题目描述 对于一个元素各不相同且按升序排列的有序序列,请编写一个算法,创建一棵高度最小的二叉查找树。 给定一个有序序列int[] vals,请返回创建的二叉查找树的高度。 * @author walkerwang * */ public class BSTofMinHigh { public static void main(String[] args) { int[] vals = {1,2,3,4,5,6,7,8}; System.out.println(buildMinimalBST(vals)); } public static int buildMinimalBST(int[] vals) { if(vals == null || vals.length < 1) return 0; return build(vals, 0, vals.length); } public static int build(int[] vals, int start, int end) { if(end <= start){ return 1; } int mid = (start+end)/2; int height1 = 1 + build(vals, start, mid-1); int height2 = 1 + build(vals, mid+1, end); return height1 > height2 ? height1 : height2; } }
package com.graduation.yearbook; import android.app.Activity; import android.content.Intent; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageButton; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.graduation.yearbook.Dialog.ChoseFunction; import com.graduation.yearbook.PhotoPage.PhotoStart; import com.graduation.yearbook.gcm.RegistrationIntentService; import java.net.URLEncoder; public class LoginAblumActivity extends Activity implements Animation.AnimationListener { private String TAG = "LoginAblumActivity"; private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; private ImageButton imgbu_add; private Animation toLargeAnimation; private Animation toSmallAnimation; private GoogleCloudMessaging gcm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imgbu_add = (ImageButton) findViewById(R.id.album_imgbu_add); toLargeAnimation = AnimationUtils.loadAnimation(LoginAblumActivity.this, R.anim.to_large); toSmallAnimation = AnimationUtils.loadAnimation(LoginAblumActivity.this, R.anim.to_small); toLargeAnimation.setAnimationListener(LoginAblumActivity.this); toSmallAnimation.setAnimationListener(LoginAblumActivity.this); imgbu_add.startAnimation(toSmallAnimation); addListenerOnButton(); //註冊GCM registerGCM(); } public void addListenerOnButton() { imgbu_add.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { switch (v.getId()) { case R.id.album_imgbu_add: { ChoseFunction m_ChoseFunction = new ChoseFunction(LoginAblumActivity.this, R.style.add_dialog); m_ChoseFunction.show(); Window dialogWindow = m_ChoseFunction.getWindow(); android.view.WindowManager.LayoutParams lp = dialogWindow.getAttributes(); lp.width = 500; lp.height = 500; dialogWindow.setBackgroundDrawable(new BitmapDrawable()); dialogWindow.setAttributes(lp); // Intent intent = new Intent(); // intent.setClass(MainActivity.this, PhotoPager.class); // startActivity(intent); // finish(); break; } } } }); } private void registerGCM() { if (checkPlayServices()) { Intent intent = new Intent(this, RegistrationIntentService.class); startService(intent); } else { } } private boolean checkPlayServices() { GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); int resultCode = apiAvailability.isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (apiAvailability.isUserResolvableError(resultCode)) { apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST).show(); } else { Log.i(TAG, "This device is not supported."); } return false; } return true; } @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { if (animation.hashCode() == toLargeAnimation.hashCode()) { imgbu_add.startAnimation(toSmallAnimation); } else { imgbu_add.startAnimation(toLargeAnimation); } } @Override public void onAnimationRepeat(Animation animation) { } // 接收 ZXing 掃描後回傳來的結果 public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == 1) { if (resultCode == RESULT_OK) { // ZXing回傳的內容 String contents = intent.getStringExtra("SCAN_RESULT"); Intent intentDownload = new Intent(); intentDownload.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intentDownload.setClass(LoginAblumActivity.this, PhotoStart.class); String strQueryURl = URLEncoder.encode("http://www.ilikeus.com.tw/static_file/ilikeus/zh_TW/album/4/20/4-20.zip"); intentDownload.putExtra("ScanInfo", "http://www.ilikeus.com.tw/static_file/ilikeus/zh_TW/album/4/20/4-20.zip"); startActivity(intentDownload); //這行一定要放在這函式的最後 } else if (resultCode == RESULT_CANCELED) { Toast.makeText(this, "取消掃描", Toast.LENGTH_LONG).show(); } } } }
package shivaji.scheduleapp; import android.graphics.Matrix; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import com.davemorrissey.labs.subscaleview.ImageSource; import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.appindexing.Thing; import com.google.android.gms.common.api.GoogleApiClient; import static android.R.attr.id; public class Main2Activity extends AppCompatActivity { ImageView imageView; /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ private GoogleApiClient client; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); SubsamplingScaleImageView imageView = (SubsamplingScaleImageView)findViewById(R.id.imageView); String string = getIntent().getStringExtra("section"); if (string.equals("a")) { imageView.setImage(ImageSource.resource(R.drawable.sa)); } else if (string.equals("b")) { imageView.setImage(ImageSource.resource(R.drawable.sb)); } else if (string.equals("c")) { imageView.setImage(ImageSource.resource(R.drawable.sc)); } else if (string.equals("d")) { imageView.setImage(ImageSource.resource(R.drawable.sd)); } else if (string.equals("e")) { imageView.setImage(ImageSource.resource(R.drawable.se)); } else if (string.equals("f")) { imageView.setImage(ImageSource.resource(R.drawable.sf)); } else if (string.equals("g")) { imageView.setImage(ImageSource.resource(R.drawable.sg)); } else if (string.equals("h")) { imageView.setImage(ImageSource.resource(R.drawable.sh)); } else if (string.equals("i")) { imageView.setImage(ImageSource.resource(R.drawable.si)); } else if (string.equals("j")) { imageView.setImage(ImageSource.resource(R.drawable.sj)); } else if (string.equals("k")) { imageView.setImage(ImageSource.resource(R.drawable.sk)); } else if (string.equals("l")) { imageView.setImage(ImageSource.resource(R.drawable.sl)); } else if (string.equals("m")) { imageView.setImage(ImageSource.resource(R.drawable.sm)); } else if (string.equals("n")) { imageView.setImage(ImageSource.resource(R.drawable.sn)); } else if (string.equals("o")) { imageView.setImage(ImageSource.resource(R.drawable.so)); } else if (string.equals("p")) { imageView.setImage(ImageSource.resource(R.drawable.sp)); } else if (string.equals("q")) { imageView.setImage(ImageSource.resource(R.drawable.sq)); } else if (string.equals("r")) { imageView.setImage(ImageSource.resource(R.drawable.sr)); } else if (string.equals("s")) { imageView.setImage(ImageSource.resource(R.drawable.ss)); } else if (string.equals("t")) { imageView.setImage(ImageSource.resource(R.drawable.st)); } else if (string.equals("u")) { imageView.setImage(ImageSource.resource(R.drawable.su)); } else if (string.equals("v")) { imageView.setImage(ImageSource.resource(R.drawable.sv)); } else if (string.equals("w")) { imageView.setImage(ImageSource.resource(R.drawable.sw)); } else if (string.equals("x")) { imageView.setImage(ImageSource.resource(R.drawable.sx)); } // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); } /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ public Action getIndexApiAction() { Thing object = new Thing.Builder() .setName("Main2 Page") // TODO: Define a title for the content shown. // TODO: Make sure this auto-generated URL is correct. .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]")) .build(); return new Action.Builder(Action.TYPE_VIEW) .setObject(object) .setActionStatus(Action.STATUS_TYPE_COMPLETED) .build(); } @Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); AppIndex.AppIndexApi.start(client, getIndexApiAction()); } @Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. AppIndex.AppIndexApi.end(client, getIndexApiAction()); client.disconnect(); } }
package com.example.v3.design.observer; import com.example.v3.design.observer.client.UserA; import com.example.v3.design.observer.server.RenmrbGongzh; public class App { public static void main(String[] args) { RenmrbGongzh r = new RenmrbGongzh(); UserA a = new UserA (r); r.product(); } }
package com.tatianadzn.factory; public enum PizzaType { MARGARITA, NAPOLETANA }
package com.tencent.mm.plugin.gif; import com.tencent.mm.a.f; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.emoji.PluginEmoji; import com.tencent.mm.sdk.platformtools.o; import com.tencent.mm.sdk.platformtools.x; import java.lang.ref.WeakReference; public class b { private static b khw; public f<String, WeakReference<d>> khx = new f(10); f<String, WeakReference<a>> khy = new f(10, new 1(this)); public static synchronized b aVQ() { b bVar; synchronized (b.class) { if (khw == null) { synchronized (b.class) { if (khw == null) { khw = new b(); } } } bVar = khw; } return bVar; } public final a EA(String str) { if (this.khy.get(str) != null) { return (a) ((WeakReference) this.khy.get(str)).get(); } return null; } public final a dj(String str, String str2) { a aVar = null; if (this.khy.get(str) != null) { aVar = (a) ((WeakReference) this.khy.get(str)).get(); } if (aVar == null) { long currentTimeMillis = System.currentTimeMillis(); if (o.Wg(str2)) { aVar = new f(str2); } else { aVar = new c(str2); } x.d("MicroMsg.GIF.MMAnimateDrawableCacheMgr", "new MMAnimateDrawable use time:%d", new Object[]{Long.valueOf(System.currentTimeMillis() - currentTimeMillis)}); this.khy.put(str, new WeakReference(aVar)); } return aVar; } public final a q(String str, byte[] bArr) { a aVar = null; if (bArr != null) { if (this.khy.get(str) != null) { aVar = (a) ((WeakReference) this.khy.get(str)).get(); } if (aVar == null) { if (o.bx(bArr) && ((PluginEmoji) g.n(PluginEmoji.class)).getEmojiMgr().aEa()) { aVar = new f(bArr); } else { aVar = new c(bArr); } this.khy.put(str, new WeakReference(aVar)); } if (!aVar.isRunning()) { aVar.reset(); } } return aVar; } }
package com.wlc.ds.sort; import java.util.Arrays; import org.junit.Test; public class InsertSortTest { int[] array = {3,5,4,2,1,7,9,8,0,-5,20}; @Test public void testSort() { new InsertSort().sort(array); System.out.println(Arrays.toString(array)); } }
package com.julio.gitsnews.activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.julio.gitsnews.R; import com.julio.gitsnews.model.DetailModel; import com.julio.gitsnews.rests.APIClient; import com.julio.gitsnews.rests.APIInterface; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class DetailActivity extends AppCompatActivity { private ImageView ivThumbnailD; private TextView tvJudulD, tvAuthorD, tvTanggalD, tvBeritaD; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); String id = getIntent().getStringExtra("id"); ivThumbnailD = findViewById(R.id.iv_thumbnail_d); tvJudulD = findViewById(R.id.tv_judul_d); tvAuthorD = findViewById(R.id.tv_author_d); tvTanggalD = findViewById(R.id.tv_tanggal_d); tvBeritaD = findViewById(R.id.tv_berita_d); final APIInterface apiService = APIClient.getClient().create(APIInterface.class); Call<DetailModel> call = apiService.getNewsDetail(id); call.enqueue(new Callback<DetailModel>() { @Override public void onResponse(Call<DetailModel> call, Response<DetailModel> response) { DetailModel detailModel = response.body(); Glide.with(getApplicationContext()) .load(detailModel.getThumbnail()) .into(ivThumbnailD); tvJudulD.setText(detailModel.getJudul()); tvAuthorD.setText(detailModel.getAuthor()); tvTanggalD.setText(detailModel.getTanggal()); tvBeritaD.setText(detailModel.getBerita()); Log.e("liat", detailModel.getBerita()); } @Override public void onFailure(Call<DetailModel> call, Throwable t) { Log.d("mamaku", "onFailure: "+t.toString()); } }); } }
package mine_mine; import java.util.Scanner; public class WholeLoop { public static void main(String[] args) { // int apple =1; // // while(apple <= 10){ // System.out.println("Eating applesssssssssssssss"); // apple++; // } // // System.out.println("No more apples:("); // System.out.println("***********************************************"); // // Scanner keyboard =new Scanner(System.in); // int number, count; // System.out.println("Enter a number"); // number= keyboard.nextInt(); // // count =5; // while(count <= number){ // System.out.println(count +", "); // count+=10; // } // // System.out.println("*************************"); Scanner keyboard =new Scanner (System.in); int total =0; System.out.println("Enter a positive number"); int nextNum= keyboard.nextInt(); while(nextNum >0){ total= total +nextNum; nextNum =keyboard.nextInt(); } System.out.println("Sum of all the number"+total); } }
//package net.cupmouse.minecraft.eplugin.bettercmd.mod; // //import com.google.common.base.Optional; //import net.cupmouse.minecraft.eplugin.EPluginSession; //import net.cupmouse.minecraft.eplugin.data.user.UserSession; //import org.spongepowered.api.block.BlockLoc; //import org.spongepowered.api.data.manipulator.mutable.item.DurabilityData; //import org.spongepowered.api.entity.living.player.Player; //import org.spongepowered.api.item.ItemType; //import org.spongepowered.api.item.ItemTypes; //import org.spongepowered.api.item.inventory.ItemStack; //import org.spongepowered.api.util.command.CommandException; //import org.spongepowered.api.util.command.CommandSource; // //import java.util.List; // //public class BetterInventoryEdit extends BetterCommandMod { // // public BetterInventoryEdit(EPluginSession plugin) { // super(plugin); // } // // @Override // public boolean call(CommandSource source, String arguments, List<String> parents) throws CommandException { // Player player = (Player) source; // UserSession sessionData = plugin.userManager.get(player).get().getUserSession().get(); // // if (arguments.equalsIgnoreCase("select")) { // if (cmd.length == 1) { // BlockLoc blockLocTarget = Utility.getBlockTarget(player, 16); // // Inventory inventory = Utility.getInventory(blockLocTarget); // if (inventory != null) { // sessionData.setInventoryEditSelected(inventory); // source.sendMessage(ChatColor.AQUA + Prefixes.OK + "インベントリを設定しました! : ブロック/" + Utility.materialToJapanese(blockLocTarget.getType())); // return true; // } else { // source.sendMessage(ChatColor.RED + Prefixes.ERROR + "インベントリがあるブロックをカーソルに当ててください!"); // return false; // } // } else if (cmd.length == 2) { // Player targetPlayer = plugin.game.getServer().get().getPlayer(cmd[1]); // // if (targetPlayer != null) { // sessionData.setInventoryEditSelected(targetPlayer.getInventory()); // source.sendMessage(ChatColor.AQUA + Prefixes.OK + "インベントリを設定しました! : プレイヤー/" + targetPlayer.getName()); // return true; // } else { // source.sendMessage(ChatColor.RED + Prefixes.ERROR + "プレイヤーが存在しません"); // return false; // } // } // } else { // Inventory inventory = sessionData.getInventoryEditSelected(); // if (inventory == null) { // source.sendMessage(ChatColor.RED + Prefixes.ERROR + "編集するインベントリが選択されていません!"); // return false; // } // // if (length == 2 && arguments.equalsIgnoreCase("fill")) { // try { // ItemStack deitemstack = getItemStack(player, cmd[1]); // // for (int i = 0; i < inventory.getSize(); i++) // inventory.setItem(i, deitemstack.clone()); // // player.sendMessage(ChatColor.AQUA + Prefixes.OK + Utility.materialToJapanese(deitemstack.getType()) + "で一杯まで埋めました"); // return true; // } catch (ItemStackSerializeException e) { // source.sendMessage(ChatColor.RED + Prefixes.ERROR + e.getLocalizedMessage()); // return false; // } // } else if (length == 2 && arguments.equalsIgnoreCase("add")) { // try { // ItemStack deitemstack = getItemStack(player, cmd[1]); // inventory.addItem(deitemstack); // player.sendMessage(ChatColor.AQUA + Prefixes.OK + Utility.materialToJapanese(deitemstack.getType()) + "を" + deitemstack.getAmount() + "こ追加しました"); // return true; // } catch (ItemStackSerializeException e) { // player.sendMessage(ChatColor.RED + Prefixes.ERROR + e.getLocalizedMessage()); // return false; // } // } else if (length == 1 && arguments.equalsIgnoreCase("showgui")) { // player.openInventory(inventory); // return true; //// } else if (length == 2 && arguments.equalsIgnoreCase("find")) { //// // } else if (length == 1 && arguments.equalsIgnoreCase("clear")) { // inventory.clear(); // player.sendMessage(ChatColor.AQUA + Prefixes.OK + "全アイテムを削除しました"); // return true; //// } else if (length == 2 && arguments.equalsIgnoreCase("showviewers")) { // } // } // return false; // } // // @Override // public Optional<String> getShortDescription() { // return null; // } // // @Override // public Optional<String> getHelp() { // return null; // } // // @Override // public String getUsage() { // return null; // } // // private ItemStack getItemStack(Player player, String request) throws ItemStackSerializeException { // if (request.equalsIgnoreCase("hand")) { // if (player.getInventory().getItemInHand() == null) // throw new ItemStackSerializeException("あなたの手にはアイテムがありません!"); // return player.getInventory().getItemInHand(); // } else if (request.equalsIgnoreCase("helmet")) { // if (player.getInventory().getHelmet() == null) // throw new ItemStackSerializeException("あなたの頭にはアイテムが装備されていません!"); // return player.getInventory().getHelmet(); // } else if (request.equalsIgnoreCase("chestplate")) { // if (player.getInventory().getChestplate() == null) // throw new ItemStackSerializeException("あなたの服にはアイテムが装備されていません!"); // return player.getInventory().getChestplate(); // } else if (request.equalsIgnoreCase("leggins")) { // if (player.getInventory().getLeggings() == null) // throw new ItemStackSerializeException("あなたのスボンにはアイテムが装備されていません!"); // return player.getInventory().getLeggings(); // } else if (request.equalsIgnoreCase("boots")) { // if (player.getInventory().getBoots() == null) // throw new ItemStackSerializeException("あなたの足にはアイテムが装備されていません!"); // return player.getInventory().getBoots(); // } else { // return deserializeItemStack(request); // } // } // // private ItemStack deserializeItemStack(String string) throws ItemStackSerializeException { // int hasData = string.indexOf(':'); // int hasAmount = string.indexOf('*'); // String sIdOrName, sAmount = null, sData = null; // // if (hasData == -1) { // if (hasAmount == -1) { // // データなし、数なし // sIdOrName = string; // } else { // // データなし、数あり // sIdOrName = string.substring(0, hasAmount); // sAmount = string.substring(hasAmount + 1); // } // } else { // if (hasAmount == -1) { // // データあり、数なし // sIdOrName = string.substring(0, hasData); // sData = string.substring(hasData + 1); // } else { // // データあり、数あり // if (hasData < hasAmount) { // //データのほうが先 // sIdOrName = string.substring(0, hasData); // sData = string.substring(hasData + 1, hasAmount); // sAmount = string.substring(hasAmount + 1); // } else { // //数のほうが先 // sIdOrName = string.substring(0, hasAmount); // sAmount = string.substring(hasAmount + 1, hasData); // sData = string.substring(hasData + 1); // } // } // } // // ItemType material; // int amount = 1; // short data = 0; // // try { // // TODO 名前でItemTypeを取得 // material = ItemTypes.getByName(Integer.parseInt(sIdOrName)); // } catch (NumberFormatException e) { // material = ItemTypes.getByName(sIdOrName); // // if (material == null) // throw new ItemStackSerializeException("アイテム名またはアイテムIDが正しくありません!"); // } // if (sAmount != null) { // try { // amount = Integer.parseInt(sAmount); // } catch (NumberFormatException e) { // throw new ItemStackSerializeException("数が不正です!", e); // } // } // // if (sData != null) { // try { // data = Short.parseShort(sData); // } catch (NumberFormatException e) { // throw new ItemStackSerializeException("データ値が不正です!", e); // } // } // // return plugin.registry.createItemBuilder() // .itemType(material) // .quantity(amount) // .itemData(DurabilityData) // .build(); // } // // @Override // public List<String> getSuggestions(CommandSource source, String arguments) throws CommandException { // if (length == 1) { // return pickSuggestions(arguments, "select", "showgui", "fill", "add", "remove", "find", "clear", "showviewers"); // } else if (length == 2 && (arguments.equalsIgnoreCase("fill") || arguments.equalsIgnoreCase("add") || arguments.equalsIgnoreCase("remove"))) { // List<String> tabCompleteReturn = pickSuggestions(arguments, "MaterialNameOrId:Data*Amount", "hand", "helmet", "chestplate", "leggins", "boots", "clear"); // tabCompleteReturn.addAll(pickSuggestions(arguments, ItemTypes.values())); // return tabCompleteReturn; // } // return null; // } // // public static class ItemStackSerializeException extends Exception { // // /** // * // */ // private static final long serialVersionUID = 2815843684804019796L; // // public ItemStackSerializeException(String arg0) { // super(arg0); // } // // public ItemStackSerializeException(Throwable arg0) { // super(arg0); // } // // public ItemStackSerializeException(String arg0, Throwable arg1) { // super(arg0, arg1); // } // } // //}
package com.cli.tool; import com.cli.tool.operations.CSVFile; import com.cli.tool.operations.FormatString; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class CLITest { private String testString = "Hello World"; private CSVFile createCSVFile; private CSVFile readCSVFile; private FormatString formatString; @Before public void setUpTestData(){ formatString = new FormatString(testString); String fileName = "store_string.csv"; createCSVFile = new CSVFile(testString, fileName); readCSVFile = new CSVFile(fileName); } @Test public void testUpperCase(){ String expectedUpperCaseString = "HELLO WORLD"; assertEquals(expectedUpperCaseString, formatString.toUpperCase()); } @Test public void testAlternateCase(){ String expectedAlternateCaseString = "hElLo wOrLd"; assertEquals(expectedAlternateCaseString, formatString.toAlternateCase()); } @Test public void testCSVFileCreation(){ createCSVFile.createCSVFile(); assertEquals(testString, readCSVFile.readCSVFile().trim()); } @Test public void testReadCSVFileNotExist(){ String fileNameNotExist = "not_exist.csv"; readCSVFile = new CSVFile(fileNameNotExist); String NO_DATA = ""; assertEquals(NO_DATA, readCSVFile.readCSVFile().trim()); } }
package edu.oregonstate.cs361.battleship; import com.google.gson.Gson; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import spark.Request; import spark.Spark; import spark.utils.IOUtils; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; import static org.junit.jupiter.api.Assertions.*; import static spark.Spark.awaitInitialization; /** * Created by michaelhilton on 1/26/17. */ class MainTest { @BeforeAll public static void beforeClass() { Main.main(null); awaitInitialization(); } @AfterAll public static void afterClass() { Spark.stop(); } @Test public void testGetModel() { TestResponse res = request("GET", "/model", null); assertEquals(200, res.status); //assertEquals("MODEL",res.body); } @Test public void testPlaceShip() { BattleshipModel test = new BattleshipModel(); Gson gson = new Gson(); String model = gson.toJson(test); TestResponse res = request("POST", "/placeShip/battleShip/1/1/horizontal", model); assertEquals(res.status, 200); } @Test public void testBadPlacement(){ BattleshipModel test = new BattleshipModel(); Gson gson = new Gson(); String model = gson.toJson(test); TestResponse res = request("POST", "/placeShip/battleShip/11/11/horizontal", model); assertEquals(res,null); } @Test public void testFireAtInvalidRow() { //Fire attempt at (0,3) //Location is off board and should return error // creates an object to send to the server BattleshipModel test = new BattleshipModel(); Gson gson = new Gson(); String model = gson.toJson(test); TestResponse res = request( "POST", "/fire/0/3", model); assertEquals(res, null); //assertEquals( "Invalid fire location! That shot was off the board.", res.body); } @Test public void testFireAtInvalidCol() { //Fire attempt at (4,0) //Location is off board and should return error //creates a model to send to the server. BattleshipModel test = new BattleshipModel(); Gson gson = new Gson(); String model = gson.toJson(test); TestResponse res = request( "POST", "/fire/4/0", model); assertEquals( res, null); //assertEquals( "Invalid fire location! That shot was off the board.", res.body); } @Test public void testValidFire(){ BattleshipModel test = new BattleshipModel(); Gson gson = new Gson(); String model = gson.toJson(test); TestResponse res = request( "POST", "/fire/4/1", model); assertEquals( 200, res.status); } private TestResponse request(String method, String path, String body) { try { URL url = new URL("http://localhost:4567" + path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); connection.setDoOutput(true); if(body != null) { connection.setDoInput(true); byte[] outputInBytes = body.getBytes("UTF-8"); OutputStream os = connection.getOutputStream(); os.write(outputInBytes); } connection.connect(); body = IOUtils.toString(connection.getInputStream()); return new TestResponse(connection.getResponseCode(), body); } catch (IOException e) { return null; } } private static class TestResponse { public final String body; public final int status; public TestResponse(int status, String body) { this.status = status; this.body = body; } public Map<String,String> json() { return new Gson().fromJson(body, HashMap.class); } } }
package monopoly.model.player; public enum State { InGame, InJail, InBankruptcy }
/* * 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 view; import classes.ContaBancaria; import classes.ContaCorrente; import exerciciocontasbancarias.ExercicioContasBancarias; /** * * @author Mateus Bernini */ public class DigitarInformacoes2 extends javax.swing.JFrame { /** * Creates new form DigitarInformacoes2 */ public DigitarInformacoes2() { initComponents(); this.setLocationRelativeTo(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { txtnumero = new javax.swing.JTextField(); txtsaldo = new javax.swing.JTextField(); txtlimite = new javax.swing.JTextField(); btcriar = new javax.swing.JButton(); btvoltar = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); btcriar.setText("Criar"); btcriar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btcriarActionPerformed(evt); } }); btvoltar.setText("Voltar"); btvoltar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btvoltarActionPerformed(evt); } }); jLabel1.setText("Digite a Taxa de Operação"); jLabel2.setText("Digite o Saldo"); jLabel3.setText("Digite o Número da Conta"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(225, 225, 225) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btcriar, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btvoltar, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGap(94, 94, 94) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel2) .addComponent(txtlimite) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE) .addComponent(txtsaldo) .addComponent(txtnumero))))) .addContainerGap(124, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap(45, Short.MAX_VALUE) .addComponent(jLabel3) .addGap(18, 18, 18) .addComponent(txtnumero, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(txtsaldo, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(27, 27, 27) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(txtlimite, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(30, 30, 30) .addComponent(btcriar) .addGap(50, 50, 50) .addComponent(btvoltar) .addGap(84, 84, 84)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btcriarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btcriarActionPerformed // TODO add your handling code here: int numConta = Integer.parseInt(txtnumero.getText()); double saldo = Double.parseDouble(txtsaldo.getText()); double taxaDeOperacao = Double.parseDouble(txtlimite.getText()); ContaBancaria cb = new ContaCorrente(numConta, saldo, taxaDeOperacao); // TODO add your handling code here: ExercicioContasBancarias.banco.inserir(cb); }//GEN-LAST:event_btcriarActionPerformed private void btvoltarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btvoltarActionPerformed // TODO add your handling code here: new Tela2().setVisible(true); this.dispose(); }//GEN-LAST:event_btvoltarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(DigitarInformacoes2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(DigitarInformacoes2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(DigitarInformacoes2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(DigitarInformacoes2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new DigitarInformacoes2().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btcriar; private javax.swing.JButton btvoltar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JTextField txtlimite; private javax.swing.JTextField txtnumero; private javax.swing.JTextField txtsaldo; // End of variables declaration//GEN-END:variables }
package com.tencent.mm.plugin.appbrand.app; import com.tencent.mm.g.a.o; import com.tencent.mm.sdk.b.b; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.x; class e$18 extends c<o> { final /* synthetic */ e ffn; e$18(e eVar) { this.ffn = eVar; this.sFo = o.class.getName().hashCode(); } public final /* synthetic */ boolean a(b bVar) { boolean fV = e.abf().fgu.fV("AppBrandCommonKVData", "update AppBrandCommonKVData set value = '0' where key like '%_unreadCount'"); x.i("MicroMsg.AppBrandCommonKVDataStorage", "sql:%s, updateRet : %b", new Object[]{"update AppBrandCommonKVData set value = '0' where key like '%_unreadCount'", Boolean.valueOf(fV)}); return true; } }
package com.lc.exstreetseller.base; import com.xjl.elibrary.app.EPreferences; public class BasePreference extends EPreferences { public BasePreference() { super("exstreetseller"); } }
/* * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.test.lib.dcmd; import jdk.test.lib.process.OutputAnalyzer; import javax.management.*; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.management.ManagementFactory; import java.util.HashMap; /** * Executes Diagnostic Commands on the target VM (specified by a host/port combination or a full JMX Service URL) using * the JMX interface. If the target is not the current VM, the JMX Remote interface must be enabled beforehand. */ public class JMXExecutor extends CommandExecutor { private final MBeanServerConnection mbs; /** * Instantiates a new JMXExecutor targeting the current VM */ public JMXExecutor() { super(); mbs = ManagementFactory.getPlatformMBeanServer(); } /** * Instantiates a new JMXExecutor targeting the VM indicated by the given host/port combination or a full JMX * Service URL * * @param target a host/port combination on the format "host:port" or a full JMX Service URL of the target VM */ public JMXExecutor(String target) { String urlStr; if (target.matches("^\\w[\\w\\-]*(\\.[\\w\\-]+)*:\\d+$")) { /* Matches "hostname:port" */ urlStr = String.format("service:jmx:rmi:///jndi/rmi://%s/jmxrmi", target); } else if (target.startsWith("service:")) { urlStr = target; } else { throw new IllegalArgumentException("Could not recognize target string: " + target); } try { JMXServiceURL url = new JMXServiceURL(urlStr); JMXConnector c = JMXConnectorFactory.connect(url, new HashMap<>()); mbs = c.getMBeanServerConnection(); } catch (IOException e) { throw new CommandExecutorException("Could not initiate connection to target: " + target, e); } } protected OutputAnalyzer executeImpl(String cmd) throws CommandExecutorException { String stdout = ""; String stderr = ""; String[] cmdParts = cmd.split(" ", 2); String operation = commandToMethodName(cmdParts[0]); Object[] dcmdArgs = produceArguments(cmdParts); String[] signature = {String[].class.getName()}; ObjectName beanName = getMBeanName(); try { stdout = (String) mbs.invoke(beanName, operation, dcmdArgs, signature); } /* Failures on the "local" side, the one invoking the command. */ catch (ReflectionException e) { Throwable cause = e.getCause(); if (cause instanceof NoSuchMethodException) { /* We want JMXExecutor to match the behavior of the other CommandExecutors */ String message = "Unknown diagnostic command: " + operation; stderr = exceptionTraceAsString(new IllegalArgumentException(message, e)); } else { rethrowExecutorException(operation, dcmdArgs, e); } } /* Failures on the "local" side, the one invoking the command. */ catch (InstanceNotFoundException | IOException e) { rethrowExecutorException(operation, dcmdArgs, e); } /* Failures on the remote side, the one executing the invoked command. */ catch (MBeanException e) { stdout = exceptionTraceAsString(e); } return new OutputAnalyzer(stdout, stderr); } private void rethrowExecutorException(String operation, Object[] dcmdArgs, Exception e) throws CommandExecutorException { String message = String.format("Could not invoke: %s %s", operation, String.join(" ", (String[]) dcmdArgs[0])); throw new CommandExecutorException(message, e); } private ObjectName getMBeanName() throws CommandExecutorException { String MBeanName = "com.sun.management:type=DiagnosticCommand"; try { return new ObjectName(MBeanName); } catch (MalformedObjectNameException e) { String message = "MBean not found: " + MBeanName; throw new CommandExecutorException(message, e); } } private Object[] produceArguments(String[] cmdParts) { Object[] dcmdArgs = {new String[0]}; /* Default: No arguments */ if (cmdParts.length == 2) { dcmdArgs[0] = cmdParts[1].split(" "); } return dcmdArgs; } /** * Convert from diagnostic command to MBean method name * * Examples: * help --> help * VM.version --> vmVersion * VM.command_line --> vmCommandLine */ private static String commandToMethodName(String cmd) { String operation = ""; boolean up = false; /* First letter is to be lower case */ /* * If a '.' or '_' is encountered it is not copied, * instead the next character will be converted to upper case */ for (char c : cmd.toCharArray()) { if (('.' == c) || ('_' == c)) { up = true; } else if (up) { operation = operation.concat(Character.toString(c).toUpperCase()); up = false; } else { operation = operation.concat(Character.toString(c).toLowerCase()); } } return operation; } private static String exceptionTraceAsString(Throwable cause) { StringWriter sw = new StringWriter(); cause.printStackTrace(new PrintWriter(sw)); return sw.toString(); } }
package com.rc.portal.vo; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.rc.app.framework.webapp.model.BaseModel; public class TBrandExample extends BaseModel{ protected String orderByClause; protected List oredCriteria; public TBrandExample() { oredCriteria = new ArrayList(); } protected TBrandExample(TBrandExample example) { this.orderByClause = example.orderByClause; this.oredCriteria = example.oredCriteria; } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public List getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); } public static class Criteria { protected List criteriaWithoutValue; protected List criteriaWithSingleValue; protected List criteriaWithListValue; protected List criteriaWithBetweenValue; protected Criteria() { super(); criteriaWithoutValue = new ArrayList(); criteriaWithSingleValue = new ArrayList(); criteriaWithListValue = new ArrayList(); criteriaWithBetweenValue = new ArrayList(); } public boolean isValid() { return criteriaWithoutValue.size() > 0 || criteriaWithSingleValue.size() > 0 || criteriaWithListValue.size() > 0 || criteriaWithBetweenValue.size() > 0; } public List getCriteriaWithoutValue() { return criteriaWithoutValue; } public List getCriteriaWithSingleValue() { return criteriaWithSingleValue; } public List getCriteriaWithListValue() { return criteriaWithListValue; } public List getCriteriaWithBetweenValue() { return criteriaWithBetweenValue; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteriaWithoutValue.add(condition); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } Map map = new HashMap(); map.put("condition", condition); map.put("value", value); criteriaWithSingleValue.add(map); } protected void addCriterion(String condition, List values, String property) { if (values == null || values.size() == 0) { throw new RuntimeException("Value list for " + property + " cannot be null or empty"); } Map map = new HashMap(); map.put("condition", condition); map.put("values", values); criteriaWithListValue.add(map); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } List list = new ArrayList(); list.add(value1); list.add(value2); Map map = new HashMap(); map.put("condition", condition); map.put("values", list); criteriaWithBetweenValue.add(map); } public Criteria andIdIsNull() { addCriterion("id is null"); return this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return this; } public Criteria andIdEqualTo(Long value) { addCriterion("id =", value, "id"); return this; } public Criteria andIdNotEqualTo(Long value) { addCriterion("id <>", value, "id"); return this; } public Criteria andIdGreaterThan(Long value) { addCriterion("id >", value, "id"); return this; } public Criteria andIdGreaterThanOrEqualTo(Long value) { addCriterion("id >=", value, "id"); return this; } public Criteria andIdLessThan(Long value) { addCriterion("id <", value, "id"); return this; } public Criteria andIdLessThanOrEqualTo(Long value) { addCriterion("id <=", value, "id"); return this; } public Criteria andIdIn(List values) { addCriterion("id in", values, "id"); return this; } public Criteria andIdNotIn(List values) { addCriterion("id not in", values, "id"); return this; } public Criteria andIdBetween(Long value1, Long value2) { addCriterion("id between", value1, value2, "id"); return this; } public Criteria andIdNotBetween(Long value1, Long value2) { addCriterion("id not between", value1, value2, "id"); return this; } public Criteria andBrandNameIsNull() { addCriterion("brand_name is null"); return this; } public Criteria andBrandNameIsNotNull() { addCriterion("brand_name is not null"); return this; } public Criteria andBrandNameEqualTo(String value) { addCriterion("brand_name =", value, "brandName"); return this; } public Criteria andBrandNameNotEqualTo(String value) { addCriterion("brand_name <>", value, "brandName"); return this; } public Criteria andBrandNameGreaterThan(String value) { addCriterion("brand_name >", value, "brandName"); return this; } public Criteria andBrandNameGreaterThanOrEqualTo(String value) { addCriterion("brand_name >=", value, "brandName"); return this; } public Criteria andBrandNameLessThan(String value) { addCriterion("brand_name <", value, "brandName"); return this; } public Criteria andBrandNameLessThanOrEqualTo(String value) { addCriterion("brand_name <=", value, "brandName"); return this; } public Criteria andBrandNameLike(String value) { addCriterion("brand_name like", value, "brandName"); return this; } public Criteria andBrandNameNotLike(String value) { addCriterion("brand_name not like", value, "brandName"); return this; } public Criteria andBrandNameIn(List values) { addCriterion("brand_name in", values, "brandName"); return this; } public Criteria andBrandNameNotIn(List values) { addCriterion("brand_name not in", values, "brandName"); return this; } public Criteria andBrandNameBetween(String value1, String value2) { addCriterion("brand_name between", value1, value2, "brandName"); return this; } public Criteria andBrandNameNotBetween(String value1, String value2) { addCriterion("brand_name not between", value1, value2, "brandName"); return this; } public Criteria andBrandTypeIsNull() { addCriterion("brand_type is null"); return this; } public Criteria andBrandTypeIsNotNull() { addCriterion("brand_type is not null"); return this; } public Criteria andBrandTypeEqualTo(Integer value) { addCriterion("brand_type =", value, "brandType"); return this; } public Criteria andBrandTypeNotEqualTo(Integer value) { addCriterion("brand_type <>", value, "brandType"); return this; } public Criteria andBrandTypeGreaterThan(Integer value) { addCriterion("brand_type >", value, "brandType"); return this; } public Criteria andBrandTypeGreaterThanOrEqualTo(Integer value) { addCriterion("brand_type >=", value, "brandType"); return this; } public Criteria andBrandTypeLessThan(Integer value) { addCriterion("brand_type <", value, "brandType"); return this; } public Criteria andBrandTypeLessThanOrEqualTo(Integer value) { addCriterion("brand_type <=", value, "brandType"); return this; } public Criteria andBrandTypeIn(List values) { addCriterion("brand_type in", values, "brandType"); return this; } public Criteria andBrandTypeNotIn(List values) { addCriterion("brand_type not in", values, "brandType"); return this; } public Criteria andBrandTypeBetween(Integer value1, Integer value2) { addCriterion("brand_type between", value1, value2, "brandType"); return this; } public Criteria andBrandTypeNotBetween(Integer value1, Integer value2) { addCriterion("brand_type not between", value1, value2, "brandType"); return this; } public Criteria andLogoIsNull() { addCriterion("logo is null"); return this; } public Criteria andLogoIsNotNull() { addCriterion("logo is not null"); return this; } public Criteria andLogoEqualTo(String value) { addCriterion("logo =", value, "logo"); return this; } public Criteria andLogoNotEqualTo(String value) { addCriterion("logo <>", value, "logo"); return this; } public Criteria andLogoGreaterThan(String value) { addCriterion("logo >", value, "logo"); return this; } public Criteria andLogoGreaterThanOrEqualTo(String value) { addCriterion("logo >=", value, "logo"); return this; } public Criteria andLogoLessThan(String value) { addCriterion("logo <", value, "logo"); return this; } public Criteria andLogoLessThanOrEqualTo(String value) { addCriterion("logo <=", value, "logo"); return this; } public Criteria andLogoLike(String value) { addCriterion("logo like", value, "logo"); return this; } public Criteria andLogoNotLike(String value) { addCriterion("logo not like", value, "logo"); return this; } public Criteria andLogoIn(List values) { addCriterion("logo in", values, "logo"); return this; } public Criteria andLogoNotIn(List values) { addCriterion("logo not in", values, "logo"); return this; } public Criteria andLogoBetween(String value1, String value2) { addCriterion("logo between", value1, value2, "logo"); return this; } public Criteria andLogoNotBetween(String value1, String value2) { addCriterion("logo not between", value1, value2, "logo"); return this; } public Criteria andBrandUrlIsNull() { addCriterion("brand_url is null"); return this; } public Criteria andBrandUrlIsNotNull() { addCriterion("brand_url is not null"); return this; } public Criteria andBrandUrlEqualTo(String value) { addCriterion("brand_url =", value, "brandUrl"); return this; } public Criteria andBrandUrlNotEqualTo(String value) { addCriterion("brand_url <>", value, "brandUrl"); return this; } public Criteria andBrandUrlGreaterThan(String value) { addCriterion("brand_url >", value, "brandUrl"); return this; } public Criteria andBrandUrlGreaterThanOrEqualTo(String value) { addCriterion("brand_url >=", value, "brandUrl"); return this; } public Criteria andBrandUrlLessThan(String value) { addCriterion("brand_url <", value, "brandUrl"); return this; } public Criteria andBrandUrlLessThanOrEqualTo(String value) { addCriterion("brand_url <=", value, "brandUrl"); return this; } public Criteria andBrandUrlLike(String value) { addCriterion("brand_url like", value, "brandUrl"); return this; } public Criteria andBrandUrlNotLike(String value) { addCriterion("brand_url not like", value, "brandUrl"); return this; } public Criteria andBrandUrlIn(List values) { addCriterion("brand_url in", values, "brandUrl"); return this; } public Criteria andBrandUrlNotIn(List values) { addCriterion("brand_url not in", values, "brandUrl"); return this; } public Criteria andBrandUrlBetween(String value1, String value2) { addCriterion("brand_url between", value1, value2, "brandUrl"); return this; } public Criteria andBrandUrlNotBetween(String value1, String value2) { addCriterion("brand_url not between", value1, value2, "brandUrl"); return this; } public Criteria andBrandInfoIsNull() { addCriterion("brand_info is null"); return this; } public Criteria andBrandInfoIsNotNull() { addCriterion("brand_info is not null"); return this; } public Criteria andBrandInfoEqualTo(String value) { addCriterion("brand_info =", value, "brandInfo"); return this; } public Criteria andBrandInfoNotEqualTo(String value) { addCriterion("brand_info <>", value, "brandInfo"); return this; } public Criteria andBrandInfoGreaterThan(String value) { addCriterion("brand_info >", value, "brandInfo"); return this; } public Criteria andBrandInfoGreaterThanOrEqualTo(String value) { addCriterion("brand_info >=", value, "brandInfo"); return this; } public Criteria andBrandInfoLessThan(String value) { addCriterion("brand_info <", value, "brandInfo"); return this; } public Criteria andBrandInfoLessThanOrEqualTo(String value) { addCriterion("brand_info <=", value, "brandInfo"); return this; } public Criteria andBrandInfoLike(String value) { addCriterion("brand_info like", value, "brandInfo"); return this; } public Criteria andBrandInfoNotLike(String value) { addCriterion("brand_info not like", value, "brandInfo"); return this; } public Criteria andBrandInfoIn(List values) { addCriterion("brand_info in", values, "brandInfo"); return this; } public Criteria andBrandInfoNotIn(List values) { addCriterion("brand_info not in", values, "brandInfo"); return this; } public Criteria andBrandInfoBetween(String value1, String value2) { addCriterion("brand_info between", value1, value2, "brandInfo"); return this; } public Criteria andBrandInfoNotBetween(String value1, String value2) { addCriterion("brand_info not between", value1, value2, "brandInfo"); return this; } public Criteria andPinyinIsNull() { addCriterion("pinyin is null"); return this; } public Criteria andPinyinIsNotNull() { addCriterion("pinyin is not null"); return this; } public Criteria andPinyinEqualTo(String value) { addCriterion("pinyin =", value, "pinyin"); return this; } public Criteria andPinyinNotEqualTo(String value) { addCriterion("pinyin <>", value, "pinyin"); return this; } public Criteria andPinyinGreaterThan(String value) { addCriterion("pinyin >", value, "pinyin"); return this; } public Criteria andPinyinGreaterThanOrEqualTo(String value) { addCriterion("pinyin >=", value, "pinyin"); return this; } public Criteria andPinyinLessThan(String value) { addCriterion("pinyin <", value, "pinyin"); return this; } public Criteria andPinyinLessThanOrEqualTo(String value) { addCriterion("pinyin <=", value, "pinyin"); return this; } public Criteria andPinyinLike(String value) { addCriterion("pinyin like", value, "pinyin"); return this; } public Criteria andPinyinNotLike(String value) { addCriterion("pinyin not like", value, "pinyin"); return this; } public Criteria andPinyinIn(List values) { addCriterion("pinyin in", values, "pinyin"); return this; } public Criteria andPinyinNotIn(List values) { addCriterion("pinyin not in", values, "pinyin"); return this; } public Criteria andPinyinBetween(String value1, String value2) { addCriterion("pinyin between", value1, value2, "pinyin"); return this; } public Criteria andPinyinNotBetween(String value1, String value2) { addCriterion("pinyin not between", value1, value2, "pinyin"); return this; } public Criteria andIsWapIsNull() { addCriterion("is_wap is null"); return this; } public Criteria andIsWapIsNotNull() { addCriterion("is_wap is not null"); return this; } public Criteria andIsWapEqualTo(Integer value) { addCriterion("is_wap =", value, "isWap"); return this; } public Criteria andIsWapNotEqualTo(Integer value) { addCriterion("is_wap <>", value, "isWap"); return this; } public Criteria andIsWapGreaterThan(Integer value) { addCriterion("is_wap >", value, "isWap"); return this; } public Criteria andIsWapGreaterThanOrEqualTo(Integer value) { addCriterion("is_wap >=", value, "isWap"); return this; } public Criteria andIsWapLessThan(Integer value) { addCriterion("is_wap <", value, "isWap"); return this; } public Criteria andIsWapLessThanOrEqualTo(Integer value) { addCriterion("is_wap <=", value, "isWap"); return this; } public Criteria andIsWapIn(List values) { addCriterion("is_wap in", values, "isWap"); return this; } public Criteria andIsWapNotIn(List values) { addCriterion("is_wap not in", values, "isWap"); return this; } public Criteria andIsWapBetween(Integer value1, Integer value2) { addCriterion("is_wap between", value1, value2, "isWap"); return this; } public Criteria andIsWapNotBetween(Integer value1, Integer value2) { addCriterion("is_wap not between", value1, value2, "isWap"); return this; } public Criteria andIsAppIsNull() { addCriterion("is_app is null"); return this; } public Criteria andIsAppIsNotNull() { addCriterion("is_app is not null"); return this; } public Criteria andIsAppEqualTo(Integer value) { addCriterion("is_app =", value, "isApp"); return this; } public Criteria andIsAppNotEqualTo(Integer value) { addCriterion("is_app <>", value, "isApp"); return this; } public Criteria andIsAppGreaterThan(Integer value) { addCriterion("is_app >", value, "isApp"); return this; } public Criteria andIsAppGreaterThanOrEqualTo(Integer value) { addCriterion("is_app >=", value, "isApp"); return this; } public Criteria andIsAppLessThan(Integer value) { addCriterion("is_app <", value, "isApp"); return this; } public Criteria andIsAppLessThanOrEqualTo(Integer value) { addCriterion("is_app <=", value, "isApp"); return this; } public Criteria andIsAppIn(List values) { addCriterion("is_app in", values, "isApp"); return this; } public Criteria andIsAppNotIn(List values) { addCriterion("is_app not in", values, "isApp"); return this; } public Criteria andIsAppBetween(Integer value1, Integer value2) { addCriterion("is_app between", value1, value2, "isApp"); return this; } public Criteria andIsAppNotBetween(Integer value1, Integer value2) { addCriterion("is_app not between", value1, value2, "isApp"); return this; } public Criteria andIsPcIsNull() { addCriterion("is_pc is null"); return this; } public Criteria andIsPcIsNotNull() { addCriterion("is_pc is not null"); return this; } public Criteria andIsPcEqualTo(Integer value) { addCriterion("is_pc =", value, "isPc"); return this; } public Criteria andIsPcNotEqualTo(Integer value) { addCriterion("is_pc <>", value, "isPc"); return this; } public Criteria andIsPcGreaterThan(Integer value) { addCriterion("is_pc >", value, "isPc"); return this; } public Criteria andIsPcGreaterThanOrEqualTo(Integer value) { addCriterion("is_pc >=", value, "isPc"); return this; } public Criteria andIsPcLessThan(Integer value) { addCriterion("is_pc <", value, "isPc"); return this; } public Criteria andIsPcLessThanOrEqualTo(Integer value) { addCriterion("is_pc <=", value, "isPc"); return this; } public Criteria andIsPcIn(List values) { addCriterion("is_pc in", values, "isPc"); return this; } public Criteria andIsPcNotIn(List values) { addCriterion("is_pc not in", values, "isPc"); return this; } public Criteria andIsPcBetween(Integer value1, Integer value2) { addCriterion("is_pc between", value1, value2, "isPc"); return this; } public Criteria andIsPcNotBetween(Integer value1, Integer value2) { addCriterion("is_pc not between", value1, value2, "isPc"); return this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return this; } public Criteria andCreateTimeIn(List values) { addCriterion("create_time in", values, "createTime"); return this; } public Criteria andCreateTimeNotIn(List values) { addCriterion("create_time not in", values, "createTime"); return this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return this; } public Criteria andRemarkIsNull() { addCriterion("remark is null"); return this; } public Criteria andRemarkIsNotNull() { addCriterion("remark is not null"); return this; } public Criteria andRemarkEqualTo(String value) { addCriterion("remark =", value, "remark"); return this; } public Criteria andRemarkNotEqualTo(String value) { addCriterion("remark <>", value, "remark"); return this; } public Criteria andRemarkGreaterThan(String value) { addCriterion("remark >", value, "remark"); return this; } public Criteria andRemarkGreaterThanOrEqualTo(String value) { addCriterion("remark >=", value, "remark"); return this; } public Criteria andRemarkLessThan(String value) { addCriterion("remark <", value, "remark"); return this; } public Criteria andRemarkLessThanOrEqualTo(String value) { addCriterion("remark <=", value, "remark"); return this; } public Criteria andRemarkLike(String value) { addCriterion("remark like", value, "remark"); return this; } public Criteria andRemarkNotLike(String value) { addCriterion("remark not like", value, "remark"); return this; } public Criteria andRemarkIn(List values) { addCriterion("remark in", values, "remark"); return this; } public Criteria andRemarkNotIn(List values) { addCriterion("remark not in", values, "remark"); return this; } public Criteria andRemarkBetween(String value1, String value2) { addCriterion("remark between", value1, value2, "remark"); return this; } public Criteria andRemarkNotBetween(String value1, String value2) { addCriterion("remark not between", value1, value2, "remark"); return this; } public Criteria andSeoTitleIsNull() { addCriterion("seo_title is null"); return this; } public Criteria andSeoTitleIsNotNull() { addCriterion("seo_title is not null"); return this; } public Criteria andSeoTitleEqualTo(String value) { addCriterion("seo_title =", value, "seoTitle"); return this; } public Criteria andSeoTitleNotEqualTo(String value) { addCriterion("seo_title <>", value, "seoTitle"); return this; } public Criteria andSeoTitleGreaterThan(String value) { addCriterion("seo_title >", value, "seoTitle"); return this; } public Criteria andSeoTitleGreaterThanOrEqualTo(String value) { addCriterion("seo_title >=", value, "seoTitle"); return this; } public Criteria andSeoTitleLessThan(String value) { addCriterion("seo_title <", value, "seoTitle"); return this; } public Criteria andSeoTitleLessThanOrEqualTo(String value) { addCriterion("seo_title <=", value, "seoTitle"); return this; } public Criteria andSeoTitleLike(String value) { addCriterion("seo_title like", value, "seoTitle"); return this; } public Criteria andSeoTitleNotLike(String value) { addCriterion("seo_title not like", value, "seoTitle"); return this; } public Criteria andSeoTitleIn(List values) { addCriterion("seo_title in", values, "seoTitle"); return this; } public Criteria andSeoTitleNotIn(List values) { addCriterion("seo_title not in", values, "seoTitle"); return this; } public Criteria andSeoTitleBetween(String value1, String value2) { addCriterion("seo_title between", value1, value2, "seoTitle"); return this; } public Criteria andSeoTitleNotBetween(String value1, String value2) { addCriterion("seo_title not between", value1, value2, "seoTitle"); return this; } public Criteria andSeoKeywordIsNull() { addCriterion("seo_keyword is null"); return this; } public Criteria andSeoKeywordIsNotNull() { addCriterion("seo_keyword is not null"); return this; } public Criteria andSeoKeywordEqualTo(String value) { addCriterion("seo_keyword =", value, "seoKeyword"); return this; } public Criteria andSeoKeywordNotEqualTo(String value) { addCriterion("seo_keyword <>", value, "seoKeyword"); return this; } public Criteria andSeoKeywordGreaterThan(String value) { addCriterion("seo_keyword >", value, "seoKeyword"); return this; } public Criteria andSeoKeywordGreaterThanOrEqualTo(String value) { addCriterion("seo_keyword >=", value, "seoKeyword"); return this; } public Criteria andSeoKeywordLessThan(String value) { addCriterion("seo_keyword <", value, "seoKeyword"); return this; } public Criteria andSeoKeywordLessThanOrEqualTo(String value) { addCriterion("seo_keyword <=", value, "seoKeyword"); return this; } public Criteria andSeoKeywordLike(String value) { addCriterion("seo_keyword like", value, "seoKeyword"); return this; } public Criteria andSeoKeywordNotLike(String value) { addCriterion("seo_keyword not like", value, "seoKeyword"); return this; } public Criteria andSeoKeywordIn(List values) { addCriterion("seo_keyword in", values, "seoKeyword"); return this; } public Criteria andSeoKeywordNotIn(List values) { addCriterion("seo_keyword not in", values, "seoKeyword"); return this; } public Criteria andSeoKeywordBetween(String value1, String value2) { addCriterion("seo_keyword between", value1, value2, "seoKeyword"); return this; } public Criteria andSeoKeywordNotBetween(String value1, String value2) { addCriterion("seo_keyword not between", value1, value2, "seoKeyword"); return this; } public Criteria andSeoDescribeIsNull() { addCriterion("seo_describe is null"); return this; } public Criteria andSeoDescribeIsNotNull() { addCriterion("seo_describe is not null"); return this; } public Criteria andSeoDescribeEqualTo(String value) { addCriterion("seo_describe =", value, "seoDescribe"); return this; } public Criteria andSeoDescribeNotEqualTo(String value) { addCriterion("seo_describe <>", value, "seoDescribe"); return this; } public Criteria andSeoDescribeGreaterThan(String value) { addCriterion("seo_describe >", value, "seoDescribe"); return this; } public Criteria andSeoDescribeGreaterThanOrEqualTo(String value) { addCriterion("seo_describe >=", value, "seoDescribe"); return this; } public Criteria andSeoDescribeLessThan(String value) { addCriterion("seo_describe <", value, "seoDescribe"); return this; } public Criteria andSeoDescribeLessThanOrEqualTo(String value) { addCriterion("seo_describe <=", value, "seoDescribe"); return this; } public Criteria andSeoDescribeLike(String value) { addCriterion("seo_describe like", value, "seoDescribe"); return this; } public Criteria andSeoDescribeNotLike(String value) { addCriterion("seo_describe not like", value, "seoDescribe"); return this; } public Criteria andSeoDescribeIn(List values) { addCriterion("seo_describe in", values, "seoDescribe"); return this; } public Criteria andSeoDescribeNotIn(List values) { addCriterion("seo_describe not in", values, "seoDescribe"); return this; } public Criteria andSeoDescribeBetween(String value1, String value2) { addCriterion("seo_describe between", value1, value2, "seoDescribe"); return this; } public Criteria andSeoDescribeNotBetween(String value1, String value2) { addCriterion("seo_describe not between", value1, value2, "seoDescribe"); return this; } } }
package net.iz44kpvp.kitpvp.Kits2; import java.util.Random; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import net.iz44kpvp.kitpvp.Sistemas.Habilidade; public class Viper_Snail implements Listener { @EventHandler public void onviper(final EntityDamageByEntityEvent e) { if (e.getDamager() instanceof Player && e.getEntity() instanceof Player) { final Player p = (Player) e.getEntity(); final Player d = (Player) e.getDamager(); if (Habilidade.getAbility(d).equalsIgnoreCase("Viper")) { final Random r = new Random(); final int rand = r.nextInt(100); if (rand >= 67) { p.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 80, 1)); } } } } @EventHandler public void onsnail(final EntityDamageByEntityEvent e) { if (e.getDamager() instanceof Player && e.getEntity() instanceof Player) { final Player p = (Player) e.getEntity(); final Player d = (Player) e.getDamager(); if (Habilidade.getAbility(d).equalsIgnoreCase("Snail")) { final Random r = new Random(); final int rand = r.nextInt(100); if (rand >= 67) { p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 80, 1)); } } } } }
package com.spring.spring.locator; public class CoVaxin implements IVaccination { public CoVaxin() { } @Override public void vaccinate(String name) { System.out.println("Opt For:" + name); } }
package com.tencent.mm.plugin.appbrand.ui.autofill; import com.tencent.mm.plugin.appbrand.ui.autofill.b.2; import com.tencent.mm.protocal.c.ej; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.base.l; import com.tencent.mm.ui.base.n.c; import java.util.Iterator; class b$2$1 implements c { final /* synthetic */ 2 gxJ; b$2$1(2 2) { this.gxJ = 2; } public final void a(l lVar) { x.i("MicroMsg.AppBrandIDCardVerifyPwdFrag", "phone_list.size %d", new Object[]{Integer.valueOf(this.gxJ.gxI.gxx.reO.size())}); Iterator it = this.gxJ.gxI.gxx.reO.iterator(); while (it.hasNext()) { ej ejVar = (ej) it.next(); if (bi.oW(ejVar.reM) || bi.oW(ejVar.reN)) { x.e("MicroMsg.AppBrandIDCardVerifyPwdFrag", "phone_id or show_phone is empty, continue"); } else { lVar.e(this.gxJ.gxI.gxx.reO.indexOf(ejVar), ejVar.reN); } } } }
package com.example.myoga.ui.yoga; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; import com.example.myoga.AsanaRecyclerViewAdapter; import com.example.myoga.R; public class PosturesFragment extends Fragment { RecyclerView.Adapter rvAdapter; RecyclerView rvAsanas; PosturesViewModel posturesViewModel; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { posturesViewModel = new ViewModelProvider(this).get(PosturesViewModel.class); View root = inflater.inflate(R.layout.fragment_yoga_postures, container, false); rvAsanas = root.findViewById(R.id.AsanasRv); rvAsanas.setHasFixedSize(true); rvAsanas.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false)); Toast.makeText(getContext(), "Loading postures..", Toast.LENGTH_SHORT).show(); posturesViewModel.getAllAsanas().observe(getViewLifecycleOwner(), yogaAsanas -> { rvAdapter = new AsanaRecyclerViewAdapter(getContext(), yogaAsanas, AsanaRecyclerViewAdapter.RV_TYPE.ALL); rvAsanas.setAdapter(rvAdapter); }); declareFragmentTransactions(root); return root; } private void declareFragmentTransactions(View view) { new Thread(() -> { Button breathingButton = view.findViewById(R.id.btnBreathing); Button posturesButton = view.findViewById(R.id.btnPostures); Button meditationButton = view.findViewById(R.id.btnMeditation); NavController navController = Navigation.findNavController(getActivity(), R.id.nav_host_fragment); posturesButton.setOnClickListener(v -> { navController.navigate(R.id.navigation_yoga_postures); }); breathingButton.setOnClickListener(v -> { navController.navigate(R.id.navigation_yoga_breathing); }); meditationButton.setOnClickListener(v -> { navController.navigate(R.id.navigation_yoga_meditation); }); }).start(); } }
package KeywordObjectDetectionPackage; public class Detector { OpenCVTools cvTools; public Detector(OpenCVTools CVTools) { cvTools = CVTools; } public int Find(String arg) { return 0; } }
package com.thelagg.skylounge.namehourschecker.commands; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.DyeColor; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.json.simple.parser.ParseException; import com.google.common.collect.Lists; import com.thelagg.skylounge.namehourschecker.Main; import net.md_5.bungee.api.ChatColor; public class UsernameCommand implements CommandExecutor { public static List<Inventory> openInventories; public UsernameCommand() { openInventories = new ArrayList<Inventory>(); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { String username = args[0]; try { Player player = (Player) sender; List<Object[]> names = Main.nameGrabber.getNames(username); Inventory inv = Bukkit.getServer().createInventory(player, getNextMultipleOf9(names.size()-1), username + "'s History.."); for(int i = 0; i<names.size()-1; i++) { String name = (String) names.get(i)[0]; long time = (Long) names.get(i)[1]; ItemStack item = new ItemStack(Material.STAINED_CLAY,1); item.setDurability((short)(i==0?5:14)); ItemMeta meta = item.getItemMeta(); meta.setDisplayName(ChatColor.RESET + (i==0?(ChatColor.GREEN + "Currently: "):(ChatColor.RED + "Name: ")) + ChatColor.GRAY + name); if(time!=0) meta.setLore(Arrays.asList(ChatColor.RESET + "" + ChatColor.GOLD + "Changed: " + ChatColor.GRAY + formatDate(time))); item.setItemMeta(meta); inv.setItem(i, item); } openInventories.add(inv); player.openInventory(inv); } catch (InterruptedException | IOException | ParseException e) { e.printStackTrace(); sender.sendMessage(ChatColor.DARK_RED + "We couldn't find a player by that name"); return false; } return false; } private int getNextMultipleOf9(int i) { while(i%9!=0) { i++; } return i; } public String formatDate(long time) { Date d = new Date(time); SimpleDateFormat dt = new SimpleDateFormat("MMM dd, yyyy"); return dt.format(d); } }
package com.kodilla.stream.beautifier; public class PoemBeautifier { public String beautify(String text, PoemDecorator poemDecorator) { String beautifierText = poemDecorator.decorate(text); return beautifierText ; } }
package com.ece6133.model.timing; import java.util.ArrayList; /** * A wrapper for {@link Block} that contains references to upstream and downstream Blocks and downstream paths * Useful for constructing a DAG for the paths */ public class BlockNode { private Block block; private ArrayList<BlockNode> immediateUpstreamBlocks = new ArrayList<>(); private ArrayList<BlockNode> immediateDownstreamBlocks = new ArrayList<>(); private ArrayList<CoarsePath> downstreamPaths = new ArrayList<>(); private int arrivalTime = 0; private int requiredArrivalTime = Integer.MAX_VALUE; private int slack = 0; private int delay = 0; /** * creates a blocknode from a block * @param b contained block */ public BlockNode(Block b) { setBlock(b); } /** * gets the backing block * @return backing block */ public Block getBlock() { return block; } /** * sets the backing block * @param block backing block */ public void setBlock(Block block) { this.block = block; } /** * * @return */ public ArrayList<BlockNode> getImmediateUpstreamBlocks() { return immediateUpstreamBlocks; } /** * * @param immediateUpstreamBlocks */ public void setImmediateUpstreamBlocks(ArrayList<BlockNode> immediateUpstreamBlocks) { this.immediateUpstreamBlocks = immediateUpstreamBlocks; } /** * * @return */ public ArrayList<BlockNode> getImmediateDownstreamBlocks() { return immediateDownstreamBlocks; } /** * * @param immediateDownstreamBlocks */ public void setImmediateDownstreamBlocks(ArrayList<BlockNode> immediateDownstreamBlocks) { this.immediateDownstreamBlocks = immediateDownstreamBlocks; } /** * * @return */ public ArrayList<CoarsePath> getDownstreamPaths() { return downstreamPaths; } /** * * @param downstreamPaths */ public void setDownstreamPaths(ArrayList<CoarsePath> downstreamPaths) { this.downstreamPaths = downstreamPaths; } public int getRequiredArrivalTime() { return requiredArrivalTime; } public void setRequiredArrivalTime(int requiredArrivalTime) { this.requiredArrivalTime = requiredArrivalTime; setSlack(this.requiredArrivalTime - this.arrivalTime); } public int getArrivalTime() { return arrivalTime; } public void setArrivalTime(int arrivalTime) { this.arrivalTime = arrivalTime; setSlack(this.requiredArrivalTime - this.arrivalTime); } public int getSlack() { return slack; } public void setSlack(int slack) { this.slack = slack; } public int getDelay() { return delay; } public void setDelay(int delay) { this.delay = delay; } public boolean isSource() { return this.immediateUpstreamBlocks.isEmpty(); } public boolean isSink() { return this.immediateDownstreamBlocks.isEmpty(); } }
package com.example.currencyrestfulservice.model; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.AllArgsConstructor; import lombok.Getter; import java.io.IOException; import java.net.URL; @Getter @AllArgsConstructor @JsonDeserialize(using = Gif.GifDeserializer.class) public class Gif { private URL url; static class GifDeserializer extends JsonDeserializer<Gif> { @Override public Gif deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(p); URL url = new URL("https://i.giphy.com/media/" + node.get("data").get("id").textValue() + "/giphy.gif"); return new Gif(url); } } }
package servlet; import bean.RegisterDao; import bean.User; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/EditServlet") public class EditServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.println("<h1>Update Customer</h1>"); String sid=request.getParameter("userid"); int id=Integer.parseInt(sid); User e=RegisterDao.getEmployeeById(id); out.print("<form action='EditServlet2' method='post'>"); out.print("<table>"); out.print("<tr><td>userid:</td><td><input type='text' name='userid' value='"+e.getUserid()+"'/></td></tr>"); out.print("<tr><td>Password:</td><td><input type='password' name='passid' value='"+e.getPassid()+"'/></td></tr>"); out.print("<tr><td>Name:</td><td><input type='text' name='username' value='"+e.getUsername()+"'/></td></tr>"); out.print("<tr><td>Address:</td><td><input type='text' name='address' value='"+e.getAddress()+"'/></td></tr>"); out.print("<tr><td>Country:</td><td>"); out.print("<select name='country' style='width:150px'>"); out.print("<option>India</option>"); out.print("<option>USA</option>"); out.print("<option>UK</option>"); out.print("<option>Other</option>"); out.print("</select>"); out.print("</td></tr>"); out.print("<tr><td>zipcode</td><td><input type='text' name='zip' value='"+e.getZip()+"'/></td></tr>"); out.print("<tr><td>Email:</td><td><input type='email' name='email' value='"+e.getEmail()+"'/></td></tr>"); out.print("<tr><td colspan='2'><input type='submit' value='Edit & Save '/></td></tr>"); out.print("</table>"); out.print("</form>"); out.close(); } }
package com.differencer.pi.viewers; import java.io.File; import java.util.HashMap; import java.util.Iterator; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.eclipse.compare.CompareConfiguration; import org.eclipse.compare.ITypedElement; import org.eclipse.compare.structuremergeviewer.DiffNode; import org.eclipse.compare.structuremergeviewer.IDiffElement; import org.eclipse.compare.structuremergeviewer.StructureDiffViewer; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.preferences.IPreferencesService; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.ActionContributionItem; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.FileDialog; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.differencer.pi.Activator; import com.differencer.pi.actions.ExportToClientTransportAction; import com.differencer.pi.actions.ExportToServerTransportAction; import com.differencer.pi.editors.Server; import com.differencer.pi.nodes.ConfigurationNode; import com.differencer.pi.preferences.PreferenceConstants; public class ConfigurationStructureMergeViewer extends StructureDiffViewer { public ConfigurationStructureMergeViewer(Composite parent, CompareConfiguration configuration) { super(parent, configuration); } @Override protected void fillContextMenu(IMenuManager manager) { boolean enable = false; ISelection selection = getSelection(); HashMap<ConfigurationNode, ConfigurationNode> nodes = new HashMap<ConfigurationNode, ConfigurationNode>(); if (selection instanceof IStructuredSelection) { Iterator<IStructuredSelection> elements = ((IStructuredSelection) selection).iterator(); while (elements.hasNext()) { Object element = elements.next(); if (element instanceof DiffNode) { DiffNode container = (DiffNode) element; ITypedElement typed = container.getLeft(); if (typed instanceof ConfigurationNode) { enable = true; ConfigurationNode leaf = (ConfigurationNode) typed; if (leaf.getChildren().length != 0) { enable = true; Object[] children = leaf.getChildren(); for (int i = 0; i < children.length;i++){ ConfigurationNode child = (ConfigurationNode) children[i]; nodes.put(child, child); } } nodes.put(leaf, leaf); } } } } IPreferencesService service = Platform.getPreferencesService(); String transportDirectory = service.getString(Activator.PLUGIN_ID, PreferenceConstants.P_TRANSPORT_PATH, "not found transport directory preference!", null); String transportArchiveDirectory = service.getString(Activator.PLUGIN_ID, PreferenceConstants.P_TRANSPORT_ARCHIVE_PATH, "not found transport archive directory preference!", null); ExportToClientTransportAction exportToClientTransportAction = new ExportToClientTransportAction(nodes, transportDirectory, transportArchiveDirectory); ActionContributionItem actionToClientContributionItem = new ActionContributionItem(exportToClientTransportAction); actionToClientContributionItem.setVisible(true); exportToClientTransportAction.setEnabled(enable); Server left = null; if (getRoot() instanceof DiffNode) { DiffNode container = (DiffNode) getRoot(); ITypedElement right = container.getRight(); if (right instanceof ConfigurationNode) { left = ((ConfigurationNode) right).getServer(); } } ExportToServerTransportAction exportToServerTransportAction = new ExportToServerTransportAction(nodes, transportDirectory, transportArchiveDirectory, left); ActionContributionItem actionToServerContributionItem = new ActionContributionItem(exportToServerTransportAction); actionToServerContributionItem.setVisible(true); exportToServerTransportAction.setEnabled(enable); manager.add(actionToClientContributionItem); manager.add(actionToServerContributionItem); super.fillContextMenu(manager); } @Override protected void createToolItems(ToolBarManager tbm) { Action a = new Action() { public void run() { exportDifference(); } }; a.setText("Export"); a.setToolTipText("Export difference"); a.setDescription("Export difference to file"); // ImageDescriptor id = Activator.getImageDescriptor("icons/sample.gif"); // if (id != null) a.setDisabledImageDescriptor(id); // id = Activator.getImageDescriptor("icons/sample.gif"); // if (id != null) { // a.setImageDescriptor(id); // a.setHoverImageDescriptor(id); // } ActionContributionItem exportAction = new ActionContributionItem(a); exportAction.setVisible(true); tbm.add(exportAction); super.createToolItems(tbm); } private void exportDifference() { FileDialog fd = new FileDialog(getControl().getShell(), SWT.SAVE); fd.setText("Save"); fd.setFilterPath("C:/tmp"); String[] filterExt = { "*.txt", "*.xml", "*.*" }; fd.setFilterExtensions(filterExt); String selected = fd.open(); if (selected != null) exportTree(selected); } private void exportTree(String path) { ConfigurationNode confnodeLeft = null; ConfigurationNode confnodeRight = null; DiffNode rootnode = (DiffNode) getRoot(); try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document document = docBuilder.newDocument(); if (rootnode.getLeft() != null) confnodeLeft = (ConfigurationNode) rootnode.getLeft(); if (confnodeLeft == null) return; Element root = document.createElement(confnodeLeft.getElementName()); root.setAttribute("name", confnodeLeft.getName()); root.setAttribute("side", "left"); document.appendChild(root); addElements(document, root, rootnode); if (rootnode.getRight() != null) confnodeRight = (ConfigurationNode) rootnode.getRight(); if (confnodeRight == null) return; root = document.createElement(confnodeRight.getElementName()); root.setAttribute("name", confnodeRight.getName()); root.setAttribute("side", "right"); document.appendChild(root); addElements(document, root, rootnode); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(new File(path)); transformer.transform(source, result); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } } public static Document addElements(Document document, Element element, DiffNode diffnode) { IDiffElement[] nodes = diffnode.getChildren(); for (int i = 0; i < nodes.length; i++) { DiffNode subdiffnode = (DiffNode) nodes[i]; ConfigurationNode subconfnodeLeft = null; ConfigurationNode subconfnodeRight = null; if (diffnode.getLeft() != null) subconfnodeLeft = (ConfigurationNode) subdiffnode.getLeft(); if (subconfnodeLeft == null) continue; Element subelement = document.createElement(subconfnodeLeft.getElementName()); subelement.setAttribute("name", subconfnodeLeft.getName()); subelement.setAttribute("side", "left"); element.appendChild(subelement); addElements(document, subelement, subdiffnode); if (diffnode.getRight() != null) subconfnodeRight = (ConfigurationNode) subdiffnode.getRight(); if (subconfnodeRight == null) continue; subelement = document.createElement(subconfnodeRight.getElementName()); subelement.setAttribute("name", subconfnodeRight.getName()); subelement.setAttribute("side", "right"); element.appendChild(subelement); addElements(document, subelement, subdiffnode); } return document; } }
package br.com.zup.edu.nossositedeviagens.model.dto; import br.com.zup.edu.nossositedeviagens.model.Pais; import com.fasterxml.jackson.annotation.JsonProperty; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; public class PaisDto { @NotBlank private String nome; public PaisDto() { } public PaisDto(@JsonProperty("nome") String nome) { this.nome = nome; } public Pais converter(){ return new Pais( nome); } public String getNome() { return nome; } }
public class Onions extends ManushDec { public Onions(Manush m) { super(m); } public String makeManush() { // super.makeManush(); return super.makeManush() +"with Onions"; } }
package com.tencent.mm.plugin.game.gamewebview.jsapi.biz; import android.content.Intent; import com.tencent.mm.plugin.game.gamewebview.jsapi.a; import com.tencent.mm.plugin.game.gamewebview.ui.GameWebViewUI; import com.tencent.mm.plugin.game.gamewebview.ui.d; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.MMActivity; import com.tencent.mm.ui.tools.k; import org.json.JSONObject; public final class i extends a { public static final int CTRL_BYTE = 254; public static final String NAME = "chooseMedia"; private MMActivity.a fEk = new 4(this); int fFw; GameWebViewUI jGT; d jGU; public final void a(d dVar, JSONObject jSONObject, int i) { x.i("MicroMsg.GameJsApiChooseMedia", "invoke"); if (jSONObject == null) { x.i("MicroMsg.GameJsApiChooseMedia", "data is null"); dVar.E(i, a.f("doChooseMedia:fail_invalid_data", null)); return; } this.jGU = dVar; this.fFw = i; this.jGT = dVar.getPageActivity(); x.i("MicroMsg.GameJsApiChooseMedia", " checkPermission checkcamera[%b]", new Object[]{Boolean.valueOf(com.tencent.mm.pluginsdk.permission.a.a(this.jGT, "android.permission.CAMERA", 119, "", ""))}); x.i("MicroMsg.GameJsApiChooseMedia", " checkPermission checkMicroPhone[%b]", new Object[]{Boolean.valueOf(com.tencent.mm.pluginsdk.permission.a.a(this.jGT, "android.permission.RECORD_AUDIO", 120, "", ""))}); if (com.tencent.mm.pluginsdk.permission.a.a(this.jGT, "android.permission.RECORD_AUDIO", 120, "", "") && r0) { String str; String oV = bi.oV(jSONObject.optString("sourceType")); String optString = jSONObject.optString("mediaType", ""); int min = Math.min(jSONObject.optInt("maxDuration", 10), 10); String optString2 = jSONObject.optString("camera", ""); int optInt = jSONObject.optInt("count", 1); String optString3 = jSONObject.optString("sizeType", ""); x.i("MicroMsg.GameJsApiChooseMedia", "doChooseMedia sourceType:%s, mediaType:%s, maxDuration:%d, camera:%s, count:%d, sizeType:%s", new Object[]{oV, optString, Integer.valueOf(min), optString2, Integer.valueOf(optInt), optString3}); Intent intent = new Intent(); intent.putExtra("key_pick_local_pic_count", optInt); if (min <= 0) { min = 10; } intent.putExtra("key_pick_local_media_duration", min); intent.putExtra("query_media_type", 3); intent.putExtra("key_pick_local_media_video_type", 2); intent.putExtra("key_pick_local_media_sight_type", optString); intent.putExtra("key_pick_local_pic_query_source_type", (optString3.contains("original") ^ optString3.contains("compressed")) != 0 ? 7 : 8); intent.putExtra("key_pick_local_pic_send_raw", Boolean.valueOf(optString3.contains("compressed"))); if (bi.oW(oV)) { str = "album|camera"; } else { str = oV; } if (str.contains("album") && str.contains("camera")) { k kVar = new k(this.jGT); kVar.b(null, new 1(this), new 2(this, optString2, intent)); kVar.d(new 3(this, dVar, i)); kVar.bEo(); return; } else if (str.contains("album")) { K(intent); return; } else if (str.contains("camera")) { a(optString2, intent); return; } else { dVar.E(i, a.f("chooseMedia:fail_sourceType_error", null)); return; } } dVar.E(i, a.f("doChooseMedia:fail_no_user_permission", null)); } final void a(String str, Intent intent) { int i; x.i("MicroMsg.GameJsApiChooseMedia", "chooseMediaFromCamera"); if (str.equals("front")) { i = 16; } else { i = 256; } intent.putExtra("key_pick_local_pic_capture", i); this.jGT.geJ = this.fEk; com.tencent.mm.bg.d.a(this.jGT, "webview", ".ui.tools.OpenFileChooserUI", intent, 65535 & hashCode(), false); } final void K(Intent intent) { x.i("MicroMsg.GameJsApiChooseMedia", "chooseMediaFromAlbum"); intent.putExtra("key_pick_local_pic_capture", 4096); this.jGT.geJ = this.fEk; com.tencent.mm.bg.d.a(this.jGT, "webview", ".ui.tools.OpenFileChooserUI", intent, 65535 & hashCode(), false); } }
package leetcode; /** * @author kangkang lou */ public class Main_149 { public int maxPoints(Point[] points) { return 0; } public static void main(String[] args) { } }
package com.example.emrapplication.ui; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.location.Location; import android.os.Bundle; import android.speech.RecognizerIntent; 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 com.example.emrapplication.R; import com.example.emrapplication.managers.Constants; import com.example.emrapplication.model.Caller; import com.example.emrapplication.model.Emergency; import com.example.emrapplication.model.EmergencyStatus; import com.example.emrapplication.presenters.LocationPresenter; import com.example.emrapplication.presenters.SosPresenter; import com.example.emrapplication.presenters.UserInfoPresenter; import com.google.android.gms.location.LocationResult; import com.google.firebase.auth.FirebaseAuth; import java.util.Locale; public class SosActivity extends AppCompatActivity implements SosPresenter.View, UserInfoPresenter.View, LocationPresenter.LocationListener, ActivityCompat.OnRequestPermissionsResultCallback { // MARK: - Class Properties - UI Elements Button buttonEditProfile; ImageButton imageButtonSOS; Dialog confirmDialog; Button buttonConfirm; Button signoutButton; Button registerButton; TextView userNameTextView; EditText descriptionEditText; // MARK: - Objects SosPresenter sosPresenter; UserInfoPresenter userInfoPresenter; LocationPresenter locationPresenter; Location lastLocation = null; private static final String TAG = "MDB:SosActivity"; // MARK: - Listeners View.OnClickListener sigout = new View.OnClickListener() { @Override public void onClick(View v) { FirebaseAuth.getInstance().signOut(); Intent intent = new Intent(SosActivity.this, LoginActivity.class); startActivity(intent); } }; View.OnClickListener goToProfileActivity = new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(SosActivity.this, EditProfileActivity.class); startActivity(i); } }; View.OnClickListener goToRegistrationActivity = new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(SosActivity.this, RegistrationActivity.class); startActivity(intent); } }; View.OnLongClickListener longClickSosButtonListener = new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startVoiceRecognitionIntent(Constants.VOICE_RECOGNITION_REQUEST_CODE); return false; } }; // MARK: - Override Default Methods @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sos); checkLoginStatus(); sosPresenter = new SosPresenter(this); userInfoPresenter = new UserInfoPresenter(this); sosPresenter.checkIfEmergencyExistsForCurrentUser(); descriptionEditText = findViewById(R.id.editTextEmergencyDiscription); signoutButton = findViewById(R.id.signout_button); signoutButton.setOnClickListener(sigout); buttonEditProfile = findViewById(R.id.buttonEditProfile); buttonEditProfile.setOnClickListener(goToProfileActivity); registerButton = findViewById(R.id.register_button); registerButton.setOnClickListener(goToRegistrationActivity); userNameTextView = findViewById(R.id.firstname_textView); confirmDialog = new Dialog(SosActivity.this); imageButtonSOS = findViewById(R.id.imageButtonSOS); imageButtonSOS.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showConfirmPopup(); } }); imageButtonSOS.setOnLongClickListener(longClickSosButtonListener); requestLocationPermission(); locationPresenter = new LocationPresenter(this, this); locationPresenter.getLastLocation(); setTitle("SOS"); } @Override protected void onStart() { super.onStart(); setButtonVisibility(); userInfoPresenter.getCurrentUser(); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); // Check which request we're responding to if (requestCode == Constants.REQUEST_CHECK_SETTINGS) { // Make sure the request was successful if (resultCode == RESULT_OK) { Log.d(TAG, "onActivityResult: intent data for request check settings: " + data.getDataString()); } else { Log.d(TAG, "onActivityResult: result code not ok! intent data for request check settings: " + data.getDataString()); } } if(requestCode == Constants.VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) { String bestResult = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS).get(0); descriptionEditText.setText(bestResult); Log.d(TAG, "onActivityResult: voice recognition intent:best Result: " + bestResult); } } @Override public void onBackPressed() { //super.onBackPressed(); Log.d(TAG, "onBackPressed: Override this to do nothing."); } // MARK: - Class Methods private void setButtonVisibility() { if(FirebaseAuth.getInstance().getCurrentUser() != null) { if(FirebaseAuth.getInstance().getCurrentUser().isAnonymous()) { signoutButton.setVisibility(View.VISIBLE); buttonEditProfile.setVisibility(View.GONE); registerButton.setVisibility(View.VISIBLE); } else { signoutButton.setVisibility(View.VISIBLE); buttonEditProfile.setVisibility(View.VISIBLE); registerButton.setVisibility(View.GONE); } } } public void showConfirmPopup(){ confirmDialog.setContentView(R.layout.confirm_emergency); buttonConfirm = confirmDialog.findViewById(R.id.buttonConfirm); confirmDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); confirmDialog.show(); try{ buttonConfirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //this is where the application will proceed with sending the data to the database //for now it will just simply close the dialog/popup. confirmDialog.dismiss(); //test code to simply move to the next activity. // Intent i = new Intent(SosActivity.this, EmergencyActivity.class); // startActivity(i); //goToEmergencyActivity(); sosPresenter.createNewEmergency(lastLocation, descriptionEditText.getText().toString()); } }); } catch (Exception e){ Toast.makeText(this,e.getMessage(), Toast.LENGTH_LONG).show(); } } private void showPermissionAlert() { // create an alert dialogue builder AlertDialog.Builder builder = new AlertDialog.Builder(this); // configure title and message for the alert builder.setTitle("Location Access Permission"); builder.setMessage("The app requires your permission to access your location in order to allow emergency personnel to find you."); // add cancel button builder.setNegativeButton("Do not Allow", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); // add grant access button builder.setPositiveButton("Grant Access", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ActivityCompat.requestPermissions(SosActivity.this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION}, Constants.PERMISSIONS_REQUEST_ACCESS_LOCATION); } }); // create and show alert builder.create().show(); } private void goToEmergencyActivity(Emergency emergency) { Intent intent = new Intent(SosActivity.this, EmergencyActivity.class); intent.putExtra("emergencyId", emergency.id); startActivity(intent); } private void checkLoginStatus() { if(FirebaseAuth.getInstance().getCurrentUser() == null) { Intent intent = new Intent(SosActivity.this, LoginActivity.class); startActivity(intent); } } private void startVoiceRecognitionIntent(int requestCode) { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.ENGLISH); startActivityForResult(intent, requestCode); } // MARK: - Implement ActivityCompat.OnRequestPermissionsResultCallback Methods @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); Log.d(TAG, "onRequestPermissionsResult: request code:" + requestCode); for(int result: grantResults) { Log.d(TAG, "onRequestPermissionsResult: GrantResult: " + result); } if(requestCode == Constants.PERMISSIONS_REQUEST_ACCESS_LOCATION) { if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.d(TAG, "onRequestPermissionsResult: permission granted, get location."); locationPresenter.getLastLocation(); } else { Log.d(TAG, "onRequestPermissionsResult: permission not granted, showing alert. grant results: " + grantResults ); //showPermissionAlert(); } } else if(requestCode == Constants.PERMISSIONS_REQUEST_ACCESS_BACKGROUND_LOCATION) { if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.d(TAG, "onRequestPermissionsResult: permission granted for background location."); locationPresenter.getLastLocation(); } else { Log.d(TAG, "onRequestPermissionsResult: background permission not granted, showing alert."); //showPermissionAlert(); } } } // MARK: - Implement LocationPresenter.LocationListener Methods @Override public void didGetLastLocation(Location location) { this.lastLocation = location; } @Override public void didFailToGetLastLocation(String message) { } @Override public void requestLocationPermission() { // check if permission has already been given if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // permission not granted // check if you need to show rational behind asking for permission if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { Log.d(TAG, "requestPermission: show permission alert"); showPermissionAlert(); } else { ActivityCompat.requestPermissions(SosActivity.this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION}, Constants.PERMISSIONS_REQUEST_ACCESS_LOCATION); } } else { if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) != PackageManager.PERMISSION_GRANTED) { // check if you need to show rational behind asking for permission if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION)) { Log.d(TAG, "requestPermission: show permission alert"); showPermissionAlert(); } else { ActivityCompat.requestPermissions(SosActivity.this, new String[] {Manifest.permission.ACCESS_BACKGROUND_LOCATION}, Constants.PERMISSIONS_REQUEST_ACCESS_LOCATION); } } } } @Override public void didUpdateLocation(LocationResult locationResult) { } // MARK: - Implement SosPresenter Methods @Override public void didCreateEmergency(Emergency emergency) { goToEmergencyActivity(emergency); } @Override public void errorCreatingEmergency(String message) { Toast.makeText(this, "Error creating emergency, please try again!\n\n error:" + message, Toast.LENGTH_LONG).show(); } @Override public void emergencyExistsForCurrentUser(Emergency emergency) { if(emergency.status.equals(EmergencyStatus.CREATED) || emergency.status.equals(EmergencyStatus.INPROGRESS)) { if(emergency.id != null) { goToEmergencyActivity(emergency); } } } // MARK: - Implement UerInfoPresenter Methods @Override public void onUserChanged(Caller caller) { if(caller.firstName != null && !caller.firstName.isEmpty()) { userNameTextView.setText(caller.firstName); } else { userNameTextView.setText("Guest"); } } // MARK: Test public void test() { sosPresenter.createNewEmergency(lastLocation, "testing"); // Emergency emergency = new Emergency("1",(new Date()).getTime(),"2", null,"test","testing",lastLocation); // // FirebaseManager.getInstance().DATABASE_REFERENCE.child("emergency_test").setValue(emergency).addOnSuccessListener(new OnSuccessListener<Void>() { // @Override // public void onSuccess(Void aVoid) { // Log.d(TAG, "onSuccess: test successfull!"); // } // }).addOnFailureListener(new OnFailureListener() { // @Override // public void onFailure(@NonNull Exception e) { // Log.d(TAG, "onFailure: test failed!!"); // } // }); // // // Map<String, Object> map = new HashMap<>(); // map.put("test", "ok then"); } }
/** * BreadWallet * <p/> * Created by byfieldj on <jade@breadwallet.com> 1/17/18. * Copyright (c) 2019 breadwallet LLC * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.breadwallet.presenter.activities; import android.arch.lifecycle.ViewModelProviders; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.constraint.ConstraintLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.breadwallet.BuildConfig; import com.breadwallet.R; import com.breadwallet.model.Experiments; import com.breadwallet.presenter.activities.settings.SettingsActivity; import com.breadwallet.presenter.activities.util.BRActivity; import com.breadwallet.presenter.customviews.BRNotificationBar; import com.breadwallet.presenter.customviews.BaseTextView; import com.breadwallet.presenter.entities.CryptoRequest; import com.breadwallet.presenter.fragments.FragmentSend; import com.breadwallet.presenter.viewmodels.HomeViewModel; import com.breadwallet.repository.ExperimentsRepositoryImpl; import com.breadwallet.tools.adapter.WalletListAdapter; import com.breadwallet.tools.animation.UiUtils; import com.breadwallet.tools.listeners.RecyclerItemClickListener; import com.breadwallet.tools.manager.AppEntryPointHandler; import com.breadwallet.tools.manager.BRSharedPrefs; import com.breadwallet.tools.manager.InternetManager; import com.breadwallet.tools.manager.PromptManager; import com.breadwallet.tools.util.BRConstants; import com.breadwallet.tools.util.CurrencyUtils; import com.breadwallet.tools.util.EventUtils; import com.breadwallet.tools.util.Utils; import com.breadwallet.ui.notification.InAppNotificationActivity; import com.breadwallet.ui.wallet.WalletActivity; import com.breadwallet.wallet.wallets.bitcoin.WalletBitcoinManager; import com.breadwallet.wallet.wallets.ethereum.WalletTokenManager; import com.platform.HTTPServer; import java.util.HashMap; import java.util.Map; /** * Created by byfieldj on 1/17/18. * <p> * Home activity that will show a list of a user's wallets */ public class HomeActivity extends BRActivity implements InternetManager.ConnectionReceiverListener { private static final String TAG = HomeActivity.class.getSimpleName(); public static final String EXTRA_DATA = "com.breadwallet.presenter.activities.HomeActivity.EXTRA_DATA"; public static final String EXTRA_PUSH_NOTIFICATION_CAMPAIGN_ID = "com.breadwallet.presenter.activities.HomeActivity.EXTRA_PUSH_CAMPAIGN_ID"; private static final String NETWORK_TESTNET = "TESTNET"; private static final String NETWORK_MAINNET = "MAINNET"; private RecyclerView mWalletRecycler; private WalletListAdapter mAdapter; private BaseTextView mFiatTotal; private BRNotificationBar mNotificationBar; private ConstraintLayout mBuyLayout; private LinearLayout mTradeLayout; private LinearLayout mMenuLayout; private LinearLayout mListGroupLayout; private HomeViewModel mViewModel; private BaseTextView mBuyMenuLabel; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); // Show build info as a watermark on non prod builds like: TESTNET 3.10.1 build 1 setUpBuildInfoLabel(); mWalletRecycler = findViewById(R.id.rv_wallet_list); mFiatTotal = findViewById(R.id.total_assets_usd); mNotificationBar = findViewById(R.id.notification_bar); mBuyLayout = findViewById(R.id.buy_layout); mTradeLayout = findViewById(R.id.trade_layout); mMenuLayout = findViewById(R.id.menu_layout); mListGroupLayout = findViewById(R.id.list_group_layout); mBuyMenuLabel = findViewById(R.id.buy_text_view); boolean showBuyAndSell = BRConstants.USD.equals(BRSharedPrefs.getPreferredFiatIso(this)) && ExperimentsRepositoryImpl.INSTANCE.isExperimentActive(Experiments.BUY_SELL_MENU_BUTTON); //mBuyMenuLabel.setText(showBuyAndSell ? R.string.HomeScreen_buyAndSell : R.string.HomeScreen_buy); Map<String, String> eventAttributes = new HashMap<>(); eventAttributes.put(EventUtils.EVENT_ATTRIBUTE_SHOW, Boolean.toString(showBuyAndSell)); EventUtils.pushEvent(EventUtils.EVENT_EXPERIMENT_BUY_SELL_MENU_BUTTON, eventAttributes); //buy button bitkanda mTradeLayout.setOnClickListener(view -> showSendFragment(null)); // mBuyLayout.setOnClickListener(view -> { //bitkanda // Map<String, String> clickAttributes = new HashMap<>(); // eventAttributes.put(EventUtils.EVENT_ATTRIBUTE_BUY_AND_SELL, Boolean.toString(showBuyAndSell)); // EventUtils.pushEvent(EventUtils.EVENT_HOME_DID_TAP_BUY, clickAttributes); // String url = String.format(BRConstants.CURRENCY_PARAMETER_STRING_FORMAT, // HTTPServer.getPlatformUrl(HTTPServer.URL_BUY), // WalletBitcoinManager.getInstance(HomeActivity.this).getCurrencyCode()); // UiUtils.startPlatformBrowser(HomeActivity.this, url); // }); mBuyLayout.setOnClickListener(view -> UiUtils.showReceiveFragment(HomeActivity.this, true)); //mTradeLayout.setOnClickListener(view -> UiUtils.startPlatformBrowser(HomeActivity.this, HTTPServer.getPlatformUrl(HTTPServer.URL_TRADE))); mMenuLayout.setOnClickListener(view -> { Intent intent = new Intent(HomeActivity.this, SettingsActivity.class); intent.putExtra(SettingsActivity.EXTRA_MODE, SettingsActivity.MODE_SETTINGS); startActivity(intent); overridePendingTransition(R.anim.enter_from_bottom, R.anim.empty_300); }); mWalletRecycler.setLayoutManager(new LinearLayoutManager(this)); mWalletRecycler.addOnItemTouchListener(new RecyclerItemClickListener(this, mWalletRecycler, new RecyclerItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position, float x, float y) { if (position >= mAdapter.getItemCount() || position < 0) { return; } if (mAdapter.getItemViewType(position) == 0) { String currencyCode = mAdapter.getItemAt(position).getCurrencyCode(); BRSharedPrefs.putCurrentWalletCurrencyCode(HomeActivity.this, currencyCode); // Use BrdWalletActivity to show rewards view and animation if BRD and not shown yet. if (WalletTokenManager.BRD_CURRENCY_CODE.equalsIgnoreCase(currencyCode)) { if (!BRSharedPrefs.getRewardsAnimationShown(HomeActivity.this)) { Map<String, String> attributes = new HashMap<>(); attributes.put(EventUtils.EVENT_ATTRIBUTE_CURRENCY, WalletTokenManager.BRD_CURRENCY_CODE); EventUtils.pushEvent(EventUtils.EVENT_REWARDS_OPEN_WALLET, attributes); } BrdWalletActivity.start(HomeActivity.this, currencyCode); } else { WalletActivity.start(HomeActivity.this, currencyCode); } overridePendingTransition(R.anim.enter_from_right, R.anim.exit_to_left); } else { //bitkanda delete add wallets // Intent intent = new Intent(HomeActivity.this, AddWalletsActivity.class); // startActivity(intent); // overridePendingTransition(R.anim.enter_from_right, R.anim.exit_to_left); } } @Override public void onLongItemClick(View view, int position) { } })); processIntentData(getIntent()); ImageView buyBell = findViewById(R.id.buy_bell); boolean isBellNeeded = ExperimentsRepositoryImpl.INSTANCE.isExperimentActive(Experiments.BUY_NOTIFICATION) && CurrencyUtils.isBuyNotificationNeeded(this); buyBell.setVisibility(isBellNeeded ? View.VISIBLE : View.INVISIBLE); mAdapter = new WalletListAdapter(this); mWalletRecycler.setAdapter(mAdapter); // Get ViewModel, observe updates to Wallet and aggregated balance data mViewModel = ViewModelProviders.of(this).get(HomeViewModel.class); mViewModel.getWallets().observe(this, wallets -> mAdapter.setWallets(wallets)); mViewModel.getAggregatedFiatBalance().observe(this, aggregatedFiatBalance -> { if (aggregatedFiatBalance == null) { Log.e(TAG, "fiatTotalAmount is null"); return; } mFiatTotal.setText(CurrencyUtils.getFormattedAmount(HomeActivity.this, BRSharedPrefs.getPreferredFiatIso(HomeActivity.this), aggregatedFiatBalance)); }); mViewModel.getNotificationLiveData().observe(this, notification -> { if (notification != null) { InAppNotificationActivity.Companion.start(HomeActivity.this, notification); } }); mViewModel.checkForInAppNotification(); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); processIntentData(intent); } //send public void showSendFragment(final CryptoRequest request) { // TODO: Find a better solution. if (FragmentSend.isIsSendShown()) { return; } FragmentSend.setIsSendShown(true); new Handler().postDelayed(() -> { FragmentSend fragmentSend = (FragmentSend) getSupportFragmentManager() .findFragmentByTag(FragmentSend.class.getName()); if (fragmentSend == null) { fragmentSend = new FragmentSend(); } Bundle arguments = new Bundle(); arguments.putSerializable(WalletActivity.EXTRA_CRYPTO_REQUEST, request); fragmentSend.setArguments(arguments); if (!fragmentSend.isAdded()) { getSupportFragmentManager().beginTransaction() .setCustomAnimations(0, 0, 0, R.animator.plain_300) .add(android.R.id.content, fragmentSend, FragmentSend.class.getName()) .addToBackStack(FragmentSend.class.getName()).commit(); } }, WalletActivity.SEND_SHOW_DELAY); } private synchronized void processIntentData(Intent intent) { if (intent.hasExtra(EXTRA_PUSH_NOTIFICATION_CAMPAIGN_ID)) { Map<String, String> attributes = new HashMap<>(); attributes.put(EventUtils.EVENT_ATTRIBUTE_CAMPAIGN_ID, intent.getStringExtra(EXTRA_PUSH_NOTIFICATION_CAMPAIGN_ID)); EventUtils.pushEvent(EventUtils.EVENT_MIXPANEL_APP_OPEN, attributes); EventUtils.pushEvent(EventUtils.EVENT_PUSH_NOTIFICATION_OPEN); } String data = intent.getStringExtra(EXTRA_DATA); if (Utils.isNullOrEmpty(data)) { data = intent.getDataString(); } if (data != null) { AppEntryPointHandler.processDeepLink(this, data); } } private void showNextPromptIfNeeded() { PromptManager.PromptItem toShow = PromptManager.nextPrompt(this); if (toShow != null) { View promptView = PromptManager.promptInfo(this, toShow); if (mListGroupLayout.getChildCount() > 0) { mListGroupLayout.removeAllViews(); } mListGroupLayout.addView(promptView, 0); EventUtils.pushEvent(EventUtils.EVENT_PROMPT_PREFIX + PromptManager.getPromptName(toShow) + EventUtils.EVENT_PROMPT_SUFFIX_DISPLAYED); } else { Log.i(TAG, "showNextPrompt: nothing to show"); } } @Override protected void onResume() { super.onResume(); showNextPromptIfNeeded(); InternetManager.registerConnectionReceiver(this, this); onConnectionChanged(InternetManager.getInstance().isConnected(this)); mViewModel.refreshWallets(); } @Override protected void onPause() { super.onPause(); InternetManager.unregisterConnectionReceiver(this, this); } @Override public void onConnectionChanged(boolean isConnected) { Log.d(TAG, "onConnectionChanged: isConnected: " + isConnected); if (isConnected) { if (mNotificationBar != null) { mNotificationBar.setVisibility(View.GONE); } } else { if (mNotificationBar != null) { mNotificationBar.setVisibility(View.VISIBLE); mNotificationBar.bringToFront(); } } } public void closeNotificationBar() { mNotificationBar.setVisibility(View.INVISIBLE); } private void setUpBuildInfoLabel() { TextView buildInfoTextView = findViewById(R.id.testnet_label); String network = BuildConfig.BITCOIN_TESTNET ? NETWORK_TESTNET : NETWORK_MAINNET; String buildInfo = network + " " + BuildConfig.VERSION_NAME + " build " + BuildConfig.BUILD_VERSION; buildInfoTextView.setText(buildInfo); buildInfoTextView.setVisibility(BuildConfig.BITCOIN_TESTNET || BuildConfig.DEBUG ? View.VISIBLE : View.GONE); } }
package Collections.Sets.Challenge; import java.util.HashSet; import java.util.Set; public class Planet extends HeavenlyBody<Moon> { private final Set<Moon> satellites; public Planet(String name, double orbitalPeriod, Set<Moon> satellites) { super(name, orbitalPeriod); this.satellites = new HashSet<>(satellites); } @Override public boolean addSatellites(Moon satellite) { return this.satellites.add(satellite); } @Override public Set<? extends HeavenlyBody<Moon>> getSatellites() { return new HashSet<>(this.satellites); } }
package xframe.example.pattern.factory.factorymethod; public class BydFactory extends CarFactory{ private BydFactory(){ } private static BydFactory instance = new BydFactory(); public static BydFactory getInstance(){ return instance; } @Override public Car createCar() { // TODO Auto-generated method stub return new Byd(); } }
package com.dao; import com.entity.Attence; import com.hibernate.HibernateSessionFactory; import java.util.ArrayList; import org.hibernate.Query; import org.hibernate.Session; public class QueryDao { private ArrayList<Attence> attenceList; public ArrayList<Attence> Query() { Session session = HibernateSessionFactory.getSession(); String hql = "from Attence"; Query query = session.createQuery(hql); this.attenceList = ((ArrayList)query.list()); session.close(); return this.attenceList; } public static void main(String[] args) { QueryDao dao = new QueryDao(); dao.Query(); } public ArrayList<Attence> getAttenceList() { return this.attenceList; } public void setAttenceList(ArrayList<Attence> attenceList) { this.attenceList = attenceList; } }
package IO; import java.io.*; public class Copy { public static void main(String[] args) throws IOException { //创建输入流 FileReader fr = new FileReader("C:\\Users\\HJQ\\Desktop\\新建文本文档.txt"); //创建输出流 FileWriter fw = new FileWriter("C:\\Users\\HJQ\\Desktop\\copy.txt"); // //方法一: // // //定义变量,记录读取的内容 // int len; // // //循环读取,并将读取的内容赋值给变量 // while ((len = fr.read()) != -1){ // // //写入本地文件 // fw.write(len); // } // //方法二: // // //定义字符数组 // char[] chs = new char[2048]; // // //记录读取到的有效字符 // int len; // // //循环读取,并将读取的内容赋值给变量 // while ((len = fr.read(chs)) != -1){ // fw.write(chs,0,len); // } // //方法三: // // BufferedReader br = new BufferedReader(fr); // BufferedWriter bw = new BufferedWriter(fw); // // int len; // // //Buffered不必使用char方法 // while ((len = br.read()) != -1){ // bw.write(len); // } // // br.close(); // bw.close(); //方法四: BufferedReader br = new BufferedReader(fr); BufferedWriter bw = new BufferedWriter(fw); String str; //按行读取 while ((str = br.readLine()) != null){ bw.write(str); //换行 bw.newLine(); } br.close(); bw.close(); //关闭流 fr.close(); fw.close(); } }
package com.guptas.android.model; /** * Created by sakshiagarwal on 09/04/16. */ public class Users { private String name; private Long points; // Required default constructor for Firebase object mapping @SuppressWarnings("unused") public Users() { } public Users(String name, Long points) { this.name = name; this.points = points; } public String getName() { return name; } public Long getPoints() { return points; } }
package com.decrypt.beeglejobsearch.ui.screens.auth; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Log; import com.decrypt.beeglejobsearch.flow.Screen; import com.decrypt.beeglejobsearch.mvp.models.AuthModel; import com.decrypt.beeglejobsearch.mvp.presenters.IAuthPresenter; import com.decrypt.beeglejobsearch.mvp.presenters.RootPresenter; import com.decrypt.beeglejobsearch.mvp.views.IRootView; import com.decrypt.beeglejobsearch.ui.activities.RootActivity; import com.decrypt.beeglejobsearch.ui.activities.SplashActivity; import com.decrypt.beeglejobsearch.utils.ConstantManager; import com.decrypt.beeglejobsearch.utils.NetworkStatusChecker; import javax.inject.Inject; import dagger.Provides; import com.decrypt.beeglejobsearch.di.DaggerService; import com.decrypt.beeglejobsearch.di.scopes.AuthScope; import com.decrypt.beeglejobsearch.flow.AbstractScreen; import com.decrypt.beeglejobsearch.mvp.models.IAuthModel; import com.decrypt.beeglejobsearch.mvp.presenters.IAuthPresenter; import com.decrypt.beeglejobsearch.mvp.views.IRootView; import com.decrypt.beeglejobsearch.utils.ConstantManager; import mortar.MortarScope; import mortar.ViewPresenter; import static android.content.ContentValues.TAG; @Screen(com.decrypt.beeglejobsearch.R.layout.screen_auth) public class AuthScreen extends AbstractScreen<RootActivity.RootComponent> { private boolean mIsCatalogLoading=false; private int mCustomState = 1; @Override public Object createScreenComponent(RootActivity.RootComponent parentComponent) { return DaggerAuthScreen_Component.builder() .rootComponent(parentComponent) .module(new Module()) .build(); } public int getCustomState() { return mCustomState; } public void setCustomState(int mCustomState) { this.mCustomState = mCustomState; } //region ============================= DI ============================= @dagger.Module public class Module { @Provides @AuthScope AuthScreen.AuthPresenter provideAuthPresenter() { return new AuthScreen.AuthPresenter(); } @Provides @AuthScope IAuthModel provideAuthModel() { return new AuthModel(); } } @dagger.Component(dependencies = RootActivity.RootComponent.class, modules = Module.class) @AuthScope public interface Component { void inject(AuthPresenter authPresenter); void inject(AuthView authView); } //endregion //region ============================= Presenter ============================= public class AuthPresenter extends ViewPresenter<AuthView> implements IAuthPresenter { @Inject RootPresenter mRootPresenter; @Inject IAuthModel mAuthModel; @Override protected void onEnterScope(MortarScope scope) { Log.e("AuthScreen", "onEnterScope: "); super.onEnterScope(scope); ((Component)scope.getService(DaggerService.SERVICE_NAME)).inject(this); } @Override protected void onLoad(Bundle savedInstanceState) { super.onLoad(savedInstanceState); if(getView() != null) { if(checkUserAuth() && getRootView() != null) { getView().hideLoginBtn(); } else { getView().showLoginBtn(); } } } @Nullable private IRootView getRootView() { return mRootPresenter.getView(); } @Override public void clickOnLogin() { if (getView()!=null && getRootView() != null) { if (getView().isIdle()) { getView().setCustomState(AuthView.LOGIN_STATE); } else { boolean emailOk = getView().getEmail().matches(ConstantManager.PATTERN_EMAIL); boolean passwordOk = getView().getPassword().matches(ConstantManager.PATTERN_PASSWORD); if (emailOk && passwordOk) { getRootView().showMessage(getView().getContext().getString(com.decrypt.beeglejobsearch.R.string.user_authenticating_message)); loginUser(getView().getUserEmail(), getView().getUserPassword()); // mAuthModel.loginUser(getView().getAuthPanel().getUserEmail(), getView().getAuthPanel().getUserPassword()); } else { getView().errorAuthForm(); if (!emailOk) getView().setWrongEmailError(); if (!passwordOk) getView().setWrongPasswordError(); getRootView().showMessage(getView().getContext().getString(com.decrypt.beeglejobsearch.R.string.email_or_password_wrong_format)); } } } } private void loginUser(String userEmail, String userPassword) { if (NetworkStatusChecker.isNetworkAvailable(getView().getContext())) { mAuthModel.saveAuthToken("authenticated"); onLoginSuccess(); } else { onLoginError(String.valueOf(String.valueOf(com.decrypt.beeglejobsearch.R.string.error_network_failure))); } } @Override public void clickOnFb() { if (getRootView()!=null) { getRootView().showMessage("clickOnFb"); } } @Override public void clickOnVk() { if (getRootView()!=null) { getRootView().showMessage("clickOnVk"); } } @Override public void clickOnTwitter() { if (getRootView()!=null) { getRootView().showMessage("clickOnTwitter"); } } @Override public void clickOnShowCatalog() { mIsCatalogLoading = true; if (getView() != null && getRootView()!=null) { getRootView().showMessage(getView().getContext().getString(com.decrypt.beeglejobsearch.R.string.catalog_loading_message)); getRootView().showLoad(); class WaitSplash extends AsyncTask<Void, Void, Void> { protected Void doInBackground(Void... params) { try { Thread.currentThread(); Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } return null; } protected void onPostExecute(Void result) { super.onPostExecute(result); mIsCatalogLoading = false; if (getView()!=null) { getRootView().hideLoad(); getRootView().showMessage(getView().getContext().getString(com.decrypt.beeglejobsearch.R.string.catalog_loaded_message)); if(getRootView() instanceof RootActivity) { ((RootActivity) getRootView()).onBackPressed(); } } } } WaitSplash waitSplash = new WaitSplash(); waitSplash.execute(); Log.e("AuthScreen", "clickOnShowCatalog: "+getRootView()); if(getRootView() instanceof SplashActivity) { ((SplashActivity) getRootView()).startRootActivity(); ((SplashActivity) getRootView()).overridePendingTransition(com.decrypt.beeglejobsearch.R.anim.enter_pull_in, com.decrypt.beeglejobsearch.R.anim.exit_fade_out); } } } @Override public void onPasswordChanged() { // Log.d(TAG, "onPasswordChanged: "+getView() + getView().getPassword().toString()); if (getView()!=null) { if (getView().getPassword().matches(ConstantManager.PATTERN_PASSWORD)) { getView().setAcceptablePassword(); } else { getView().setNonAcceptablePassword(); } } } @Override public void onEmailChanged() { Log.d(TAG, "onEmailChanged: "+getView()); if (getView()!=null) { if (getView().getEmail().matches(ConstantManager.PATTERN_EMAIL)) getView().setAcceptableEmail(); else getView().setNonAcceptableEmail(); } } @Override public boolean checkUserAuth() { return mAuthModel.isAuthUser(); } @Override public void onLoginSuccess() { if (getView()!=null && getRootView()!=null) { getRootView().showMessage(getView().getContext().getString(com.decrypt.beeglejobsearch.R.string.authentificate_successful)); getView().hideLoginBtn(); getView().setCustomState(AuthView.IDLE_STATE); } } @Override public void onLoginError(String message) { if (getRootView()!=null) { getRootView ().showMessage(message); } } } //endregion }
package il.ac.huji.todolist; import java.util.List; import android.content.Context; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class CustomListAdapter extends ArrayAdapter<ToDoItem> { public CustomListAdapter(Context context, int textViewResourceId , List<ToDoItem> list ) { super(context, textViewResourceId, list); } @Override public View getView(int position, View cv, ViewGroup parent) { ToDoItem item = getItem(position); LayoutInflater inf = LayoutInflater.from(getContext()); View v = inf.inflate(R.layout.todo_layout, null); TextView todoItem = (TextView)v.findViewById(R.id.txtTodoTitle); TextView todoDate = (TextView)v.findViewById(R.id.txtTodoDueDate); todoItem.setText(item.todo); todoDate.setText(item.dueDateRepr()); todoDate.setTextColor(Color.BLACK); todoItem.setTextColor(Color.BLACK); if (item.isOverdue()){ todoDate.setTextColor(Color.RED); todoItem.setTextColor(Color.RED); } else { todoDate.setTextColor(Color.BLACK); todoItem.setTextColor(Color.BLACK); } String vals = todoItem.getText() + " " + String.valueOf(item.isOverdue()) + " " + todoDate.getText(); return v; } }
package com.xinruke.user.dto; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.NotBlank; @ApiModel("用户添加信息") public class UserInfoAddVO { @ApiModelProperty("用户名") @NotBlank(message = "用户名不能为空") private String name; @ApiModelProperty("登录密码") @Length(min = 6,message = "最少6个字符") private String password; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
package com.msir.web; import com.msir.pojo.UserDO; import com.msir.service.ITestService; import org.apache.log4j.Logger; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.authz.annotation.RequiresRoles; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest; @Controller @RequestMapping("test") public class TestController { private static Logger logger = Logger.getLogger(TestController.class); @Autowired private ITestService testService; @RequestMapping(value="/login",method= RequestMethod.POST) public String login(UserDO user, HttpServletRequest request){ Subject currentUser = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),user.getUserPassword()); try { currentUser.login(token); } catch (UnknownAccountException e) { logger.error("用户名不存在",e); return "test/error"; } catch (IncorrectCredentialsException e) { logger.error("密码错误",e); return "test/error"; } catch (LockedAccountException e) { logger.error("您的账号在另一个地方登陆",e); return "test/error"; }catch (AuthenticationException e){ logger.error("error",e); return "test/error"; } return "test/index"; } @RequestMapping(value="/login",method=RequestMethod.GET) public String toLogin(){ return "test/login"; } @RequestMapping("success") public String success(){ return "test/index"; } @RequestMapping("unauthorized") public String unauthorized(){ return "test/unauthorized"; } @RequestMapping("admin") @RequiresRoles("admin") public String admin () { return "test/admin"; } @RequestMapping({"admin","user"}) public String user () { return "test/user"; } }
package com.jpa.orm.controller; import com.jpa.orm.domain.Find; import com.jpa.orm.domain.Provinsi; import com.jpa.orm.service.impl.ProvinsiServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Map; @RestController @RequestMapping(value = "/api/prov") public class ProvinsiController { @Autowired ProvinsiServiceImpl provinsiService; @GetMapping(value = "") public Map findAll() { return provinsiService.findAll(); } @PostMapping(value = "/save") public Map create(@RequestBody Provinsi prov) { if (prov.getId() == null) { return provinsiService.create(prov); } else { return provinsiService.update(prov); } } @PostMapping(value = "/find") public Map find(@RequestBody Find find) { if (find.getKey().equals("id")) { return provinsiService.findOne(find); } else { return null; } } @DeleteMapping(value = "/delete") public Map delete(@RequestBody Find find) { if (find.getId() == null) { return null; } else { return provinsiService.delete(find.getId()); } } }