text
stringlengths
10
2.72M
/* * Copyright (c) 2003-2004, Jadabs project * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * - Neither the name of the Jadabs project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Created on Apr 2, 2004 * */ package ch.ethz.jadabs.im.testgui.impl; import java.util.Hashtable; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import ch.ethz.jadabs.im.testgui.SwtManager; import ch.ethz.jadabs.remotefw.FrameworkManager; import ch.ethz.jadabs.im.api.IMException; import ch.ethz.jadabs.im.api.IMListener; import ch.ethz.jadabs.im.api.IMService; import ch.ethz.jadabs.im.jxme.IMServiceImpl; import ch.ethz.jadabs.jxme.services.GroupService; import ch.ethz.jadabs.sip.cons.MessageCons; /** * @author andfrei * */ public class Activator implements BundleActivator { static BundleContext bc; static SwtManagerImpl ui; static TestGUI testgui; //< static String test1sipaddress = "sip:test1@wlab.ethz.ch"; static String test2sipaddress = "sip:test2@wlab.ethz.ch"; static GroupService groupsvc = null; static IMService imservice = null; //> /* RemoteFramework */ static FrameworkManager rmanager; static String peername; /* * */ public void start(BundleContext bc) throws Exception { // add context Activator.bc = bc; peername = bc.getProperty("ch.ethz.jadabs.jxme.peeralias"); // instantiate the service ui = new SwtManagerImpl(); ui.start(); // FrameworkManager ServiceReference srefrm = Activator.bc.getServiceReference(FrameworkManager.class.getName()); rmanager = (FrameworkManager) bc.getService(srefrm); //register service bc.registerService(SwtManager.class.getName(), ui, new Hashtable()); //register service as a singleton... need a PID? //< peername = bc.getProperty("ch.ethz.jadabs.jxme.peeralias"); // get GroupService ServiceReference sref = bc.getServiceReference( "ch.ethz.jadabs.jxme.services.GroupService"); if (sref == null) throw new Exception("could not properly initialize IM, GroupService is missing"); groupsvc = (GroupService)bc.getService(sref); // create IMServiceImpl and do testrun if (peername.equals("peer1")) { imservice = new IMServiceImpl(groupsvc, test1sipaddress); testrunPeer1(); } else { imservice = new IMServiceImpl(groupsvc, test2sipaddress); testrunPeer2(); } // register IMService //bc.registerService("ch.ethz.jadabs.jxme.im.IMService", imservice, null); //> testgui = new TestGUI(); ui.exec(testgui, false); } /* * */ public void stop(BundleContext context) throws Exception { bc = null; ui.dispose(); ui = null; } public void testrunPeer1() { // try // { // first subscribe imservice.register(new Peer1IMListener(), MessageCons.IM_STATUS_ONLINE); // send IM-Message // imservice.sendMessage(test2sipaddress, "testmessage"); // // // // } catch (IMException e) // { // // TODO Auto-generated catch block // e.printStackTrace(); // } } public void testrunPeer2() { try { // first subscribe imservice.register(new Peer2IMListener(), MessageCons.IM_STATUS_ONLINE); // send IM-Message imservice.sendMessage(test1sipaddress, "testmessage"); } catch (IMException e) { // TODO Auto-generated catch block e.printStackTrace(); } } class Peer1IMListener implements IMListener { public void imRegistered(String sipaddress, int status) { System.out.println("IM joined: "+sipaddress); } public void imUnregistered(String sipaddress) { System.out.println("IM left: "+sipaddress); } public void process(String sipaddress, String msg) { System.out.println("IM sent: "+sipaddress+":"+msg); } } class Peer2IMListener implements IMListener { public void imRegistered(String sipaddress, int status) { System.out.println("IM joined: "+sipaddress); } public void imUnregistered(String sipaddress) { System.out.println("IM left: "+sipaddress); } public void process(String sipaddress, String msg) { System.out.println("IM sent: "+sipaddress+":"+msg); } } }
package com.zhaoyan.ladderball.service.event.handler; import com.zhaoyan.ladderball.dao.eventofmatch.EventOfMatchDao; import com.zhaoyan.ladderball.dao.player.PlayerOfMatchDao; import com.zhaoyan.ladderball.domain.eventofmatch.db.EventOfMatch; import com.zhaoyan.ladderball.domain.player.db.PlayerOfMatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * | 乌龙球 | 10027 | | */ public class EventWuLongQiuHandler extends EventHandler { Logger logger = LoggerFactory.getLogger(EventWuLongQiuHandler.class); @Override public boolean handleAddEvent(EventOfMatch event) { if (event.playerOfMatch != null) { // 更新球员数据 updateplayerOfMatch(event.eventCode, event.playerOfMatch.id); // 更新对面球队得分 updateOppositeTeamScore(event.matchId, event.teamId); } return true; } @Override public boolean handleDeleteEvent(EventOfMatch event) { if (event.playerOfMatch != null) { // 更新球员数据 updateplayerOfMatch(event.eventCode, event.playerOfMatch.id); // 更新对面球队得分 updateOppositeTeamScore(event.matchId, event.teamId); } return true; } /** * 更新球员数据 */ private void updateplayerOfMatch(int eventCode, long playerId) { // 事件总数 EventOfMatchDao eventOfMatchDao = getEventOfMatchDao(); int eventCount = eventOfMatchDao.getEventCountByPlayer(eventCode, playerId); // 更新个人事件个数 PlayerOfMatchDao playerOfMatchDao = getPlayerOfMatchDao(); PlayerOfMatch playerOfMatch = playerOfMatchDao.getPlayerById(playerId); playerOfMatch.event10027 = eventCount; playerOfMatchDao.modifyPlayer(playerOfMatch); } /** * 更新对面球队的比分 */ private void updateOppositeTeamScore(long matchId, long teamId) { long oppositeTeamId = TeamScoreUtil.getOppositeTeamId(getMatchDao(), matchId, teamId); TeamScoreUtil.updateTeamScore(getTeamOfMatchDao(), getPlayerOfMatchDao(), oppositeTeamId, teamId); } }
package src.modulo6.complementos; /** * * @author uel */ public class Point3 { private float x; private float y; private float z; public Point3() { } public Point3(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } public void setPoint3(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } public void setPoint3(Point3 point3) { this.x = point3.getX(); this.y = point3.getY(); this.z = point3.getZ(); } public float getX() { return x; } public void setX(float x) { this.x = x; } public float getY() { return y; } public void setY(float y) { this.y = y; } public float getZ() { return z; } public void setZ(float z) { this.z = z; } }
package com.github.bot.curiosone.core.knowledge; import com.ibm.icu.impl.Relation; import java.util.List; import java.util.Objects; /** * Resumes a semantic query parameters. * */ public class SemanticQuery { private SemanticRelationType relation; private String subject; private String object; private List<String> objAdjectives; private String verb; /** * Constructor. * @param relation {@link Relation} * @param subject Affirmation subject. * @param object Question/affirmation object * @param adjectives Object adjectives * @param verb Sentence verb. */ public SemanticQuery(SemanticRelationType relation, String subject,String object, List<String> adjectives, String verb) { this.relation = relation; this.subject = subject; this.object = object; this.objAdjectives = adjectives; this.verb = verb; } public SemanticQuery(SemanticRelationType relation,String subject, String object, String verb) { this(relation, subject, object, null, verb); } public SemanticQuery(SemanticRelationType relation, String object, List<String> adjectives, String verb) { this(relation, null, object, adjectives, verb); } public SemanticQuery(SemanticRelationType relation, String object, String verb) { this(relation, null, object, null, verb); } public String getObject() { return object; } public String getSubject() { return subject; } public List<String> getAdjectives() { return objAdjectives; } public SemanticRelationType getRelation() { return relation; } public String getVerb() { return verb; } @Override public boolean equals(Object other) { if (other == this) { return true; } if (other == null || other.getClass() != this.getClass()) { return false; } SemanticQuery that = (SemanticQuery) other; return this.relation.equals(that.relation) && this.subject.equals(that.subject) && this.object.equals(that.object) && this.verb.equals(that.verb); } @Override public int hashCode() { return Objects.hash(relation, subject, object, verb); } }
package com.xx.base.org.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.List; /** * 对象处理工具类 * @author Lixingxing */ public class BaseObjectUtils { // 深拷贝(拷贝的对象要实现 Serializable) @SuppressWarnings("unchecked") public static <T extends Serializable> T clone(T obj){ T cloneObj = null; try { //写入字节流 ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream obs = new ObjectOutputStream(out); obs.writeObject(obj); obs.close(); //分配内存,写入原始对象,生成新对象 ByteArrayInputStream ios = new ByteArrayInputStream(out.toByteArray()); ObjectInputStream ois = new ObjectInputStream(ios); //返回生成的新对象 cloneObj = (T) ois.readObject(); ois.close(); } catch (Exception e) { e.printStackTrace(); } return cloneObj; } // 深拷贝 @SuppressWarnings("unchecked") public static <T> List<T> cloneList(List<T> obj) { List<T> dest = null; try { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream obs = new ObjectOutputStream(out); obs.writeObject(obj); obs.close(); ByteArrayInputStream ios = new ByteArrayInputStream(out.toByteArray()); ObjectInputStream ois = new ObjectInputStream(ios); dest = (List<T>) ois.readObject(); ois.close(); }catch (Exception e){ e.printStackTrace(); } return dest; } }
package uk.gov.digital.ho.pttg.api; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Pageable; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import uk.gov.digital.ho.pttg.AuditService; import java.util.List; import static net.logstash.logback.argument.StructuredArguments.value; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static uk.gov.digital.ho.pttg.api.RequestData.REQUEST_DURATION_MS; import static uk.gov.digital.ho.pttg.application.LogEvent.*; @RestController @Slf4j public class AuditResource { private final AuditService auditService; private final RequestData requestData; public AuditResource(AuditService auditService, RequestData requestData) { this.auditService = auditService; this.requestData = requestData; } @GetMapping(value = "/audit", produces = APPLICATION_JSON_VALUE) public List<AuditRecord> retrieveAllAuditData(Pageable pageable) { log.info("Audit records requested, {}", pageable, value(EVENT, PTTG_AUDIT_RETRIEVAL_REQUEST_RECEIVED)); List<AuditRecord> auditRecords = auditService.getAllAuditData(pageable); log.info("{} audit records found", auditRecords.size(), value(EVENT, PTTG_AUDIT_RETRIEVAL_RESPONSE_SUCCESS), value(REQUEST_DURATION_MS, requestData.calculateRequestDuration())); return auditRecords; } @PostMapping(value = "/audit", consumes = APPLICATION_JSON_VALUE) public void recordAuditEntry(@RequestBody AuditableData auditableData) { log.info("Audit request {} received for correlation id {}", auditableData.getEventType(), auditableData.getCorrelationId(), value(EVENT, PTTG_AUDIT_REQUEST_RECEIVED)); auditService.add(auditableData); log.info("Audit request {} completed for correlation id {}", auditableData.getEventType(), auditableData.getCorrelationId(), value(EVENT, PTTG_AUDIT_REQUEST_COMPLETED), value(REQUEST_DURATION_MS, requestData.calculateRequestDuration())); } }
package com.serenitybdd.jbehave.steps; import com.serenitybdd.jbehave.pages.MainPage; import com.serenitybdd.jbehave.pages.ShoppingCartPage; import net.thucydides.core.annotations.Step; import java.util.List; public class BuyerSteps { MainPage mainPage; ShoppingCartPage shoppingCartPage; @Step public void click_on_add_1984_to_shopping_cart(){ mainPage.clickOnAdd1984ToShoppingCart(); } @Step public void click_on_add_da_vinci_to_shopping_cart(){ mainPage.clickOnAddDaVinciToShoppingCart(); } @Step public void click_on_shopping_cart(){ mainPage.clickOnShoppingCart(); } @Step public void main_page_is_opened(){ mainPage.open(); } @Step public List<String> check_items_in_shopping_cart(){ return shoppingCartPage.getItemName(); } @Step public void go_to_the_shopping_cart(){ mainPage.clickOnShoppingCart(); } @Step public void click_on_reduce_by_one_code_da_vinci(){ shoppingCartPage.clickOnReduceByOne(); } @Step public void click_on_add_by_one_1984(){ shoppingCartPage.clickOnAdd(); } @Step public String get_quantity_of_reduced_book(){ return shoppingCartPage.getQuantityOfReducedBook(); } @Step public String get_quantity_of_added_book(){ return shoppingCartPage.getQuantityOfAddedBook(); } }
package com.soecode.lyf.dao; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.soecode.lyf.service.BookService; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.soecode.lyf.BaseTest; import com.soecode.lyf.entity.Book; public class BookDaoTest extends BaseTest { @Autowired private BookDao bookDao; @Autowired private BookService bookService; @Test public void testQueryById() throws Exception { long bookId = 1000; Book book = bookDao.queryById(bookId); System.out.println(book); } @Test public void testQueryAll() throws Exception { List<Book> books = bookDao.queryAll("数",0, 4); for (Book book : books) { System.out.println(book); } } @Test public void testReduceNumber() throws Exception { long bookId = 1000; int update = bookDao.reduceNumber(bookId); System.out.println("update=" + update); } @Test public void delectBook() throws Exception{ long bookId = 1000; int delect = bookDao.delectBook(bookId); System.out.println("delect= " + delect); } @Test public void insterBook() throws Exception{ Book book = new Book(1000,"Java从入门到放弃",1); int insert = bookDao.insertBook(book); System.out.println("insert=" + insert); } @Test public void updateBook() throws Exception{ Book book = new Book(1000,"Oracle从删库到跑路",8); int update = bookDao.updateBook(book); System.out.println("update" + update); } @Test public void PageBookCount()throws Exception{ Map map = bookService.getList(null,0,0); List<Book> books =(ArrayList<Book>) map.get("list"); for (Book book : books) { System.out.println(book); } System.out.println(map.get("html")); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.inbio.ara.eao.security.impl; import java.util.List; import org.inbio.ara.eao.security.*; import javax.ejb.Stateless; import javax.persistence.Query; import org.inbio.ara.eao.BaseEAOImpl; import org.inbio.ara.persistence.taxonomy.UserNomenclaturalGroup; /** * * @author esmata */ @Stateless public class UserNomenclaturalGroupEAOImpl extends BaseEAOImpl<UserNomenclaturalGroup,Long> implements UserNomenclaturalGroupEAOLocal { /** * Metodo para obtener la lista de user_nomenclatural_gruups para un * determinado usuario * @param userId * @return */ public List<UserNomenclaturalGroup> getNomenclaturalGroupList(Long userId){ String sql = "Select un "; sql += "from NomenclaturalGroup n, UserNomenclaturalGroup un "; sql += "where n.nomenclaturalGroupId = un.userNomenclaturalGroupPK.nomenclaturalGroupId" + " and un.userNomenclaturalGroupPK.userId = :userId"; Query q = em.createQuery(sql); q.setParameter("userId", userId); return (List<UserNomenclaturalGroup>)q.getResultList(); } }
package com.yuneec.flight_settings; import android.util.Xml; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlSerializer; public class WifiPasswordService { public static List<WifiPassword> getWifiPasswords(InputStream xml) throws Exception { List<WifiPassword> wifiPasswords = null; WifiPassword wifiPassword = null; XmlPullParser parser = Xml.newPullParser(); parser.setInput(xml, "UTF-8"); for (int eventType = parser.getEventType(); eventType != 1; eventType = parser.next()) { switch (eventType) { case 0: wifiPasswords = new ArrayList(); break; case 2: if (!parser.getName().equals("wifipassword")) { if (!parser.getName().equals("ssid")) { if (!parser.getName().equals("password")) { break; } eventType = parser.next(); wifiPassword.setPassword(parser.getText()); break; } eventType = parser.next(); wifiPassword.setSsid(parser.getText()); break; } wifiPassword = new WifiPassword(); break; case 3: if (!parser.getName().equals("wifipassword")) { break; } wifiPasswords.add(wifiPassword); wifiPassword = null; break; default: break; } } return wifiPasswords; } public static void save(List<WifiPassword> wifiPasswords, OutputStream out) throws Exception { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(out, "UTF-8"); serializer.startDocument("UTF-8", Boolean.valueOf(true)); serializer.startTag(null, "wifipasswords"); for (WifiPassword wifiPassword : wifiPasswords) { serializer.startTag(null, "wifipassword"); serializer.startTag(null, "ssid"); serializer.text(wifiPassword.getSsid()); serializer.endTag(null, "ssid"); serializer.startTag(null, "password"); serializer.text(wifiPassword.getPassword()); serializer.endTag(null, "password"); serializer.endTag(null, "wifipassword"); } serializer.endTag(null, "wifipasswords"); serializer.endDocument(); out.flush(); out.close(); } }
package ltd.getman.testjobproject.presentation.views; public interface IView { void showSnackbarMessage(String text); }
package com.universidadeafit.appeafit.Views; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.widget.CalendarView; import android.widget.Toast; import com.universidadeafit.appeafit.R; public class Calendario extends AppCompatActivity { CalendarView calendar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_calendario); verToolbar("Calendario",true); initializeCalendar(); } public void verToolbar(String titulo,Boolean UpButton){ Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle(titulo); getSupportActionBar().setDisplayHomeAsUpEnabled(UpButton); } public void initializeCalendar() { calendar = (CalendarView) findViewById(R.id.calendar); // sets whether to show the week number. calendar.setShowWeekNumber(false); // sets the first day of week according to Calendar. // here we set Monday as the first day of the Calendar calendar.setFirstDayOfWeek(2); //The background color for the selected week. calendar.setSelectedWeekBackgroundColor(getResources().getColor(R.color.green)); //sets the color for the dates of an unfocused month. calendar.setUnfocusedMonthDateColor(getResources().getColor(R.color.transparent)); //sets the color for the separator line between weeks. calendar.setWeekSeparatorLineColor(getResources().getColor(R.color.transparent)); //sets the color for the vertical bar shown at the beginning and at the end of the selected date. calendar.setSelectedDateVerticalBar(R.color.darkgreen); //sets the listener to be notified upon selected date change. calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() { //show the selected date as a toast @Override public void onSelectedDayChange(CalendarView view, int year, int month, int day) { Toast.makeText(getApplicationContext(), day + "/" + month + "/" + year, Toast.LENGTH_LONG).show(); } }); } }
package cn.routePlan; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class RoutePlanMaps { private Graph g = new Graph(); public RoutePlanMaps() { } private List<Route> routeList; public void init() { List<Vertex> vertexList = null; //初始化开始点的Vertex for (Route route : routeList) { Long startPointId = route.getStartPointId(); vertexList = g.getVertex(startPointId); if (vertexList == null) { vertexList = new ArrayList<>(); g.addVertex(startPointId, vertexList); } vertexList.add(new Vertex(route.getEndPointId(), route.getWeight())); } //初始化结束点的Vertex for (Route route : routeList) { Long endPointId = route.getEndPointId(); //已初始化过的点,不需要重复初始化 if (g.getVertex(endPointId) != null) { continue; } //结束点的边是空 g.addVertex(endPointId, Collections.emptyList()); } } /** * 获取最短路线点序列 * * @param startPointId * @param finishPointIdId * @return */ public RoutePlanResult getShortestPath(Long startPointId, Long finishPointIdId) { RoutePlanResult routePlanResult = g.getShortestPath(startPointId, finishPointIdId); routePlanResult.setTotalLength(calTotalLength(routePlanResult)); return routePlanResult; } /** * 计算路径总长度 * * @param routePlanResult * @return */ public Long calTotalLength(RoutePlanResult routePlanResult) { long totalLength = 0L; if (routePlanResult == null || routePlanResult.getPointIds() == null || routePlanResult.getPointIds().isEmpty()) { routePlanResult.setTotalLength(totalLength); return totalLength; } List<Long> pointIds = routePlanResult.getPointIds(); int size = pointIds.size(); if (size <= 1) { //只有一个点,说明就在这个点,返回0 return totalLength; } for (int i = 0; i < size - 1; i++) { Route route = getRouteByStartAndEndPointId(pointIds.get(i), pointIds.get(i + 1)); if (route != null) { totalLength += route.getLength(); } } return totalLength; } /** * 根据起点和终点ID查询路径 * * @param startPointId * @param endPointId * @return */ private Route getRouteByStartAndEndPointId(Long startPointId, Long endPointId) { if (startPointId == null || endPointId == null || routeList == null || routeList.isEmpty()) { return null; } for (Route route : routeList) { if (route.getStartPointId().equals(startPointId) && route.getEndPointId().equals(endPointId)) { return route; } } return null; } /** * 设置用于规划的路径序列 * * @param routeList */ public void setRouteList(List<Route> routeList) { this.routeList = routeList; } }
package net.dryuf.bigio.seekable; import lombok.AccessLevel; import lombok.AllArgsConstructor; import net.dryuf.bigio.FlatChannel; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SeekableByteChannel; @AllArgsConstructor(access = AccessLevel.PROTECTED) public class SeekableChannelFlatChannel implements FlatChannel { public static SeekableChannelFlatChannel from(SeekableByteChannel channel) { return new SeekableChannelFlatChannel(channel); } @Override public int read(ByteBuffer buffer, long position) throws IOException { synchronized (seekableChannel) { seekableChannel.position(position); return seekableChannel.read(buffer); } } @Override public int write(ByteBuffer buffer, long position) throws IOException { synchronized (seekableChannel) { seekableChannel.position(position); return seekableChannel.write(buffer); } } private final SeekableByteChannel seekableChannel; }
package com.userframe.flatlands.window; import com.userframe.flatlands.framework.GameObject; public class Camera { private static float x, y; public static int camX; public static int camY; public Camera(float x, float y){ this.x = x; this.y = y; } public void tick(GameObject Player){ if(!Game.isPaused){ x += ((-Player.getX() + Game.camWidth / 2) - x) * 0.0400; y += ((-Player.getY() + Game.camHeight / 2) - y) * 0.0700; } camX = (int) x; camY = (int) y; } public void setX(float x){ this.x = x; } public void setY(float y){ this.y = y; } public float getX(){ return x; } public float getY(){ return y; } }
//here DemoBox allowed one object to initilize anotehr. class DemoBox { double width; double height; double depth; //this constructor takes one object type DemoBOx DemoBox(DemoBox o) { width = o.width; height = o.height; depth = o.depth; } //constructor used when all dimensions spacified DemoBox(double w,double h,double d) { //System.out.println("parameterized constructor"); width = w; height = h; depth = d; } //constructor used when no dimensions spacified. DemoBox() { // System.out.println("no parameterized constructor"); width = -1; height = -1; depth = 1; } public double volume() { return width * height * depth; } } class BoxDemo10 { public static void main(String[]args) { DemoBox box1 = new DemoBox(10,7,3); DemoBox box2 = new DemoBox(); DemoBox box3 = new DemoBox(box1);//here object box1 passsed to constructor Demobox //get value from volume() System.out.println(box1.volume()); System.out.println(box2.volume()); System.out.println(box3.volume()); } }
package com.kool.restaurant.dto; import java.util.Date; import java.util.Set; import lombok.Builder; import lombok.Data; @Builder @Data public class Reservation { private Long reservationId; private String reservationCode; private ReservationStatus status; private Integer restaurantId; private Set<Plat> dishList; private Date reservationDate; private Boolean ongoingReservation; }
package com.github.andlyticsproject.db; import android.net.Uri; import android.provider.BaseColumns; import java.util.HashMap; public final class AppStatsTable implements BaseColumns { public static final String DATABASE_TABLE_NAME = "appstats"; public static final Uri CONTENT_URI = Uri.parse("content://" + AndlyticsContentProvider.AUTHORITY + "/" + DATABASE_TABLE_NAME); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.andlytics." + DATABASE_TABLE_NAME; public static final String KEY_ROWID = "_id"; public static final String KEY_STATS_PACKAGENAME = "packagename"; public static final String KEY_STATS_REQUESTDATE = "requestdate"; public static final String KEY_STATS_DOWNLOADS = "downloads"; public static final String KEY_STATS_INSTALLS = "installs"; public static final String KEY_STATS_COMMENTS = "comments"; public static final String KEY_STATS_MARKETERANKING = "marketranking"; public static final String KEY_STATS_CATEGORYRANKING = "categoryranking"; public static final String KEY_STATS_5STARS = "starsfive"; public static final String KEY_STATS_4STARS = "starsfour"; public static final String KEY_STATS_3STARS = "starsthree"; public static final String KEY_STATS_2STARS = "starstwo"; public static final String KEY_STATS_1STARS = "starsone"; public static final String KEY_STATS_VERSIONCODE = "versioncode"; public static final String TABLE_CREATE_STATS = "create table " + AppStatsTable.DATABASE_TABLE_NAME + " (_id integer primary key autoincrement, " + AppStatsTable.KEY_STATS_PACKAGENAME + " text not null," + AppStatsTable.KEY_STATS_REQUESTDATE + " date not null," + AppStatsTable.KEY_STATS_DOWNLOADS + " integer," + AppStatsTable.KEY_STATS_INSTALLS + " integer," + AppStatsTable.KEY_STATS_COMMENTS + " integer," + AppStatsTable.KEY_STATS_MARKETERANKING + " integer," + AppStatsTable.KEY_STATS_CATEGORYRANKING + " integer," + AppStatsTable.KEY_STATS_5STARS + " integer," + AppStatsTable.KEY_STATS_4STARS + " integer," + AppStatsTable.KEY_STATS_3STARS + " integer," + AppStatsTable.KEY_STATS_2STARS + " integer," + AppStatsTable.KEY_STATS_1STARS + " integer," + AppStatsTable.KEY_STATS_VERSIONCODE + " integer);"; public static HashMap<String, String> PROJECTION_MAP; static { PROJECTION_MAP = new HashMap<String, String>(); PROJECTION_MAP.put(AppStatsTable.KEY_ROWID, AppStatsTable.KEY_ROWID); PROJECTION_MAP .put(AppStatsTable.KEY_STATS_PACKAGENAME, AppStatsTable.KEY_STATS_PACKAGENAME); PROJECTION_MAP .put(AppStatsTable.KEY_STATS_REQUESTDATE, AppStatsTable.KEY_STATS_REQUESTDATE); PROJECTION_MAP.put(AppStatsTable.KEY_STATS_DOWNLOADS, AppStatsTable.KEY_STATS_DOWNLOADS); PROJECTION_MAP.put(AppStatsTable.KEY_STATS_INSTALLS, AppStatsTable.KEY_STATS_INSTALLS); PROJECTION_MAP.put(AppStatsTable.KEY_STATS_COMMENTS, AppStatsTable.KEY_STATS_COMMENTS); PROJECTION_MAP.put(AppStatsTable.KEY_STATS_MARKETERANKING, AppStatsTable.KEY_STATS_MARKETERANKING); PROJECTION_MAP.put(AppStatsTable.KEY_STATS_CATEGORYRANKING, AppStatsTable.KEY_STATS_CATEGORYRANKING); PROJECTION_MAP.put(AppStatsTable.KEY_STATS_5STARS, AppStatsTable.KEY_STATS_5STARS); PROJECTION_MAP.put(AppStatsTable.KEY_STATS_4STARS, AppStatsTable.KEY_STATS_4STARS); PROJECTION_MAP.put(AppStatsTable.KEY_STATS_3STARS, AppStatsTable.KEY_STATS_3STARS); PROJECTION_MAP.put(AppStatsTable.KEY_STATS_2STARS, AppStatsTable.KEY_STATS_2STARS); PROJECTION_MAP.put(AppStatsTable.KEY_STATS_1STARS, AppStatsTable.KEY_STATS_1STARS); PROJECTION_MAP .put(AppStatsTable.KEY_STATS_VERSIONCODE, AppStatsTable.KEY_STATS_VERSIONCODE); } }
/******************************************************************************* * Copyright 2014 See AUTHORS file. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package dk.sidereal.lumm.architecture; /** * Class used for handling events when certain actions are triggered by * {@link LummComponent} and {@link LummObject} implementations. * <p> * The class is abstract so as to prompt the user to create an anonymous inner * class, customising the {@link #runr(Object...)} and {@link #run(Object...)} * methods at will, without having to create additional classes. */ public abstract class AbstractEvent { // region constructors public AbstractEvent() { } // endregion // region methods /** * Runs an event with a varying number of arguments, returning a varying * number of arguments. If no values are to be returned use * {@link #run(Object...)}. * * @param objects * to pass to the method * @return an array of type {@link Object}. Can be null. */ public Object[] runr(Object... objects) { return null; } /** * Runs an event with a varying number of arguments. If values are to be * returned use {@link #runr(Object...)}. * * @param objects */ public void run(Object... objects) { } // endregion }
package com.example.kuno.intentobjectex02; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { Button btnParcelButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnParcelButton = (Button) findViewById(R.id.btnParcelable); btnParcelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, SecondActivity.class); DataParcel obj = new DataParcel("Kuno", 27, "Yaksu"); intent.putExtra("ObjectType", "오브젝트 Parcelable"); intent.putExtra("ObjectData", obj); startActivity(intent); } }); } }
package com.staniul.teamspeak.commands.validators; import com.staniul.util.validation.Validator; import java.util.regex.Pattern; public class TwoIntegerParamsValidator implements Validator<String> { public static Pattern getPattern () { return Pattern.compile("^(\\d+)[ \t]+(\\d+)$"); } @Override public boolean validate(String element) { return getPattern().matcher(element).matches(); } }
package vape.springmvc.services; import vape.springmvc.entity.TarjetasGraficas; public interface TarjetasGraficasServices { public TarjetasGraficas getTarjetaGrafica(String idtg); }
package skollur1.msse.asu.edu.graduatestudentassignment; /* * Copyright 2016 Supraj Kolluri, * * * The contents of the file can only be used for the purpose of grading and reviewing. * The instructor and the University have the right to build and evaluate the * software package for the purpose of determining the grade and program assessment. * * * @author Supraj Kolluri mailto:supraj.kolluri@asu.edu * Software Engineering, CIDSE, IAFSE, ASU Poly * @version April 28, 2016 */ import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.facebook.AccessToken; import com.facebook.AccessTokenTracker; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.FacebookSdk; import com.facebook.Profile; import com.facebook.ProfileTracker; import com.facebook.login.LoginManager; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; import java.util.Arrays; /* The goal of this application is to display Users Facebook information and perform various activities on Google maps that is embedded into the application. To access the application one must login into the application using Facebook. Once the user is Logged in, he/she will see 2 buttons, One to display facebook information and the other to open google maps. On hitting the 'Show FB DETAILS' button, the user will see a screen which displays the users Profile Picture, Name, Date of birth, email address, Location and their Gender. All this information is pulled from the Facebook's Graph API by making an async request to it. Please note this information will only be visible if it is specified in the users facebook profile and the visibility is set to public. On clicking the second button 'Open Google Maps', the user will see google maps that is embedded into the application. The screen will we consist a marker that is pointed to Tempe by default. The user will be able to switch between various Maps types(Normal, Satellite, Terrain, Hybrid), by selecting the grouped menu button on the top right section of the screen. The user can also view the latitude, longitude coordinates of any location on the map by clicking on the location. Additionally, the user will be able to add markers on the map in two ways. First, the user can click on the 'ADD MARKER' and specify the latitude, longitude for the location. Second, the user can add a marker by going to the location on the map and clicking on the Map for a long duration. */ public class MainActivity extends AppCompatActivity { private TextView info; private LoginButton loginButton; private Button showFBbutton; private Button openMapsbutton; private CallbackManager callbackManager; private ProfileTracker mProfileTracker; private String userid = ""; MainActivity mainActivity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mainActivity = this; FacebookSdk.sdkInitialize(getApplicationContext()); setContentView(R.layout.activity_main); callbackManager = CallbackManager.Factory.create(); showFBbutton = (Button) findViewById(R.id.fbdetailsbutton); openMapsbutton = (Button) findViewById(R.id.openMapsButton); info = (TextView)findViewById(R.id.info); loginButton = (LoginButton)findViewById(R.id.login_button); loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_birthday", "user_friends")); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { showContent(); userid = loginResult.getAccessToken().getUserId(); if (Profile.getCurrentProfile() == null) { mProfileTracker = new ProfileTracker() { @Override protected void onCurrentProfileChanged(Profile profile, Profile profile2) { Log.v("facebook - profile", profile2.getFirstName()); info.setText("Welcome " + profile2.getFirstName() + "!!!"); mProfileTracker.stopTracking(); } }; mProfileTracker.startTracking(); } else { Profile profile = Profile.getCurrentProfile(); Log.v("facebook - profile", profile.getFirstName()); String name = profile.getFirstName(); info.setText("Welcome " + name + "!!!"); } Toast.makeText(getApplicationContext(), "User logged in", Toast.LENGTH_LONG).show(); /*info.setText( "User ID: " + loginResult.getAccessToken().getUserId() + "\n" + "Auth Token: " + loginResult.getAccessToken().getToken() );*/ } @Override public void onCancel() { Toast.makeText(getApplicationContext(), "Login attempt canceled.", Toast.LENGTH_LONG).show(); } @Override public void onError(FacebookException e) { Toast.makeText(getApplicationContext(), "Login attempt failed.", Toast.LENGTH_LONG).show(); } }); AccessTokenTracker accessTokenTracker = new AccessTokenTracker() { @Override protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) { if (currentAccessToken == null) { clearContent(); } } }; clearContent(); } private void clearContent(){ LoginManager.getInstance().logOut(); if(info!=null) { info.setVisibility(View.GONE); } if(showFBbutton!=null) { showFBbutton.setVisibility(View.GONE); } if(openMapsbutton!=null) { openMapsbutton.setVisibility(View.GONE); } } private void showContent(){ info.setVisibility(View.VISIBLE); showFBbutton.setVisibility(View.VISIBLE); openMapsbutton.setVisibility(View.VISIBLE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { callbackManager.onActivityResult(requestCode, resultCode, data); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void showFBDetails(View view){ Intent fbDetails = new Intent(mainActivity, DisplayFBDetails.class); fbDetails.putExtra("userid", userid); mainActivity.startActivityForResult(fbDetails,1); } public void openGoogleMaps(View view){ Intent maps = new Intent(mainActivity, MapsActivity.class); mainActivity.startActivityForResult(maps,1); } }
package Sevlet; import error.HttpError; import models.ResponseHeader; import models.ResponseHeaderBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedWriter; import java.io.IOException; public class ErrorServlet extends Servlet { private Logger logger = LoggerFactory.getLogger(ErrorServlet.class); public void writeError(HttpError httpError, BufferedWriter out) throws IOException { logger.debug("returning " + httpError); StringBuilder html = new StringBuilder(); String title = new StringBuilder().append(httpError.getCode().getId()).append(" ").append(httpError.getCode().getDescription()).toString(); writeHtmlFront(html, title); html.append(String.format("<h1> %s %s</h1>",httpError.getCode().getId() ,httpError.getCode().getDescription())).append(CRLF); writeHtmlBack(html); ResponseHeaderBuilder builder = new ResponseHeaderBuilder(); builder.setErrorState(httpError); builder.setContextType(); if(httpError.getCode().getId()==304){ builder.setField("Cache-Control","max-age=120"); } builder.setField("Content-Length: ",Integer.toString(html.length())); builder.setConnection(false); ResponseHeader responseheaeder = builder.build();; out.write(responseheaeder.getHeader()); out.write(html.toString()); } }
package com.goldenasia.lottery.data; import java.io.Serializable; /** * Created by Sakura on 2017/12/8. */ public class RebateOptionsBean implements Serializable { /** * property_name : * rebate : */ private String property_name; private String method_name; private String rebate; public String getProperty_name() { return property_name;} public void setProperty_name(String property_name) { this.property_name = property_name;} public String getMethod_name() { return method_name; } public void setMethod_name(String method_name) { this.method_name = method_name; } public String getRebate() { return rebate;} public void setRebate(String rebate) { this.rebate = rebate;} }
/** * */ package com.rd.utils.rest; import java.nio.charset.StandardCharsets; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation.Builder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import org.apache.commons.codec.binary.Base64; import org.apache.http.entity.ContentType; import org.json.JSONObject; /** * @author David Caviedes * */ public class RestUtils implements IRestUtils { /* (non-Javadoc) * @see com.rd.utils.rest.IRestUtils#getWebtarget(java.lang.String) */ @Override public WebTarget getWebtarget(String targetPath) { Client client = ClientBuilder.newBuilder().build(); return client.target(targetPath); } /* (non-Javadoc) * @see com.rd.utils.rest.IRestUtils#getBase64Token(java.lang.String, java.lang.String) */ @Override public String getBase64Token(String user, String pwd) { String token = user + ":" + pwd; return Base64.encodeBase64String(token.getBytes(StandardCharsets.UTF_8)); } /* (non-Javadoc) * @see com.rd.utils.rest.IRestUtils#addBasicAuthorizationHeaderToBuilder(javax.ws.rs.client.Invocation.Builder, java.lang.String) */ @Override public Builder addBasicAuthorizationHeaderToBuilder(Builder builder, String base64Token) { return builder.header("Authorization", "Basic " + base64Token); } /* (non-Javadoc) * @see com.rd.utils.rest.IRestUtils#invokeHttpJsonPost(javax.ws.rs.client.Invocation.Builder, org.json.JSONObject) */ @Override public Response invokeHttpJsonPost(Builder builder, JSONObject jsonObject) { return builder.post(Entity.entity(jsonObject.toString(), ContentType.APPLICATION_JSON.toString())); } }
package com.nucpoop.covserver.service; import java.util.List; import javax.transaction.Transactional; import com.nucpoop.covserver.mapper.UserMapper; import com.nucpoop.covserver.model.User; import com.nucpoop.covserver.model.UserEmailCheck; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService { @Autowired UserMapper userMapper; @Autowired PasswordEncoder passwordEncoder; @Override public int insertUser(User user) throws Exception { int result = userMapper.insertUser(user); return result; } @Override public UserEmailCheck checkEmail(String email) throws Exception { User user = userMapper.findByEmail(email); UserEmailCheck result = new UserEmailCheck(false); if (user == null) { result.setCanEmailSignUp(true); } else { result.setCanEmailSignUp(false); } return result; } @Override @Transactional public int withdrawalUser(User user) throws Exception { User compare = userMapper.findByEmail(user.getEmail()); if(passwordEncoder.matches(user.getPassword(), compare.getPassword())){ return userMapper.deleteUser(user); }else{ return 0; } } @Override public int updatePassword(User password) throws Exception { return userMapper.updatePassword(password); } @Override @Transactional public int resetPassword(User user) throws Exception { User userObj = userMapper.findByEmail(user.getEmail()); int passwordTemp = (int) (Math.random() * 8999 + 1000); String password = passwordEncoder.encode(Integer.toString(passwordTemp)); if (userObj != null) { user.setPassword(password); userMapper.updatePassword(user); return passwordTemp; } else { return 0; } } @Override public List<User> selectUsersForNotify(String time) throws Exception { return userMapper.notifyEmail(time); } @Override public int updateLocation(User user) throws Exception { return userMapper.updateLocation(user); } @Override public int updateNotify(User user) throws Exception { return userMapper.updateNofity(user); } @Override @Transactional public int updateUserInfo(User user) throws Exception{ String password = passwordEncoder.encode(user.getPassword()); userMapper.updateLocation(user); user.setPassword(password); return userMapper.updatePassword(user); } }
package org.elasticsearch.plugin.zentity.exceptions; import org.elasticsearch.ElasticsearchStatusException; import org.elasticsearch.rest.RestStatus; public class BadRequestException extends ElasticsearchStatusException { public BadRequestException(String message, Throwable cause) { super(message, RestStatus.BAD_REQUEST, cause); } public BadRequestException(String message) { this(message, null); } }
package com.cxc.bottomnavigationbar.ui; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.ashokvarma.bottomnavigation.BadgeItem; import com.ashokvarma.bottomnavigation.BottomNavigationBar; import com.ashokvarma.bottomnavigation.BottomNavigationItem; import com.cxc.bottomnavigationbar.fragment.CasesFragment; import com.cxc.bottomnavigationbar.fragment.EnterpriseFragment; import com.cxc.bottomnavigationbar.fragment.LawFragment; import com.cxc.bottomnavigationbar.R; import com.cxc.bottomnavigationbar.fragment.UserFragment; public class MainActivity extends AppCompatActivity implements BottomNavigationBar.OnTabSelectedListener{ public static final int CASES = 0; public static final int LAW = 1; public static final int ENTERPRISE = 2; public static final int USER = 3; private BottomNavigationBar btm_bar; private CasesFragment casesFragment; private UserFragment userFragment; private LawFragment lawFragment; private EnterpriseFragment enterpriseFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView(){ //初始化底部导航栏 initBtmBar(); //设置默认Fragment setDefaultFragment(); } private void initBtmBar(){ btm_bar = (BottomNavigationBar)findViewById(R.id.btm_bar); BadgeItem badgeItem = new BadgeItem().setText("2"); btm_bar //切换时是否显示动画 .setMode(BottomNavigationBar.MODE_FIXED) //点击时是否有水波纹 .setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC) //设置背景颜色 .setBarBackgroundColor(R.color.btm_bar) //选中或未选中时图标和文字的颜色(全局设定,每个Item也可单独设定选中时的颜色) .setInActiveColor(R.color.white) .setActiveColor(R.color.colorPrimary) //添加导航按钮 .addItem(new BottomNavigationItem(R.mipmap.city_2,R.string.home)) .addItem(new BottomNavigationItem(R.mipmap.map_2,R.string.map)) .addItem(new BottomNavigationItem(R.mipmap.file,R.string.report).setBadgeItem(badgeItem)) .addItem(new BottomNavigationItem(R.mipmap.user_2,R.string.my)) .initialise(); btm_bar.setTabSelectedListener(this); } private void setDefaultFragment(){ FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); casesFragment = new CasesFragment(); transaction.add(R.id.ll_content,casesFragment); transaction.commit(); } private void hideFragment(FragmentTransaction fragmentTransaction){ if(casesFragment != null){ fragmentTransaction.hide(casesFragment); } if(userFragment != null){ fragmentTransaction.hide(userFragment); } if(enterpriseFragment != null){ fragmentTransaction.hide(enterpriseFragment); } if(lawFragment != null){ fragmentTransaction.hide(lawFragment); } } private void showFragment(int i,FragmentTransaction fragmentTransaction){ switch (i){ case CASES: if(casesFragment == null){ casesFragment = new CasesFragment(); fragmentTransaction.add(R.id.ll_content,casesFragment); }else{ fragmentTransaction.show(casesFragment); } break; case LAW: if(lawFragment == null){ lawFragment = new LawFragment(); fragmentTransaction.add(R.id.ll_content,lawFragment); }else{ fragmentTransaction.show(lawFragment); } break; case ENTERPRISE: if(enterpriseFragment == null){ enterpriseFragment = new EnterpriseFragment(); fragmentTransaction.add(R.id.ll_content,enterpriseFragment); }else{ fragmentTransaction.show(enterpriseFragment); } break; case USER: if(userFragment == null){ userFragment = new UserFragment(); fragmentTransaction.add(R.id.ll_content,userFragment); }else{ fragmentTransaction.show(userFragment); } break; default: break; } } @Override public void onTabSelected(int position) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); hideFragment(fragmentTransaction); showFragment(position,fragmentTransaction); fragmentTransaction.commit(); } @Override public void onTabReselected(int position) { } @Override public void onTabUnselected(int position) { } }
package dk.webbies.tscreate.analysis.declarations; import dk.webbies.tscreate.analysis.declarations.types.*; import fj.data.Set; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * Created by Erik Krogh Kristensen on 21-12-2015. */ public final class ClassNameFinder implements DeclarationTypeVisitorWithArgument<Void, ClassNameFinder.Arg> { private final java.util.Set<DeclarationType> printsAsInterface; private Map<DeclarationType, String> declarationNames = new HashMap<>(); public ClassNameFinder(Map<String, DeclarationType> declarations, Map<DeclarationType, InterfaceDeclarationType> printsAsInterface) { this.printsAsInterface = printsAsInterface.keySet(); for (Map.Entry<String, DeclarationType> entry : declarations.entrySet()) { String name = entry.getKey(); DeclarationType type = entry.getValue(); type.accept(this, new Arg(name, DeclarationPrinter.emptySet())); } } @Override public Void visit(FunctionType functionType, Arg arg) { putNamedType(functionType, arg.path); return null; } @Override public Void visit(PrimitiveDeclarationType primitive, Arg argument) { return null; } @Override public Void visit(UnnamedObjectType object, Arg arg) { putNamedType(object, arg.path); if (arg.seen.member(object)) { return null; } if (printsAsInterface.contains(object)) { return null; } for (Map.Entry<String, DeclarationType> entry : object.getDeclarations().entrySet()) { String name = entry.getKey(); DeclarationType type = entry.getValue(); type.accept(this, arg.cons(name, object)); } return null; } @Override public Void visit(InterfaceDeclarationType interfaceType, Arg argument) { return null; } @Override public Void visit(UnionDeclarationType union, Arg argument) { return null; } @Override public Void visit(NamedObjectType namedObjectType, Arg argument) { return null; } @Override public Void visit(ClassType classType, Arg arg) { putNamedType(classType, arg.path); return null; } private void putNamedType(DeclarationType type, String path) { if (declarationNames.containsKey(type)) { String prevName = declarationNames.get(type); if (type instanceof ClassType && path.endsWith(((ClassType)type).getName()) && !prevName.endsWith(((ClassType)type).getName())) { declarationNames.put(type, path); return; } int prevDots = StringUtils.countMatches(prevName, "."); int newDots = StringUtils.countMatches(path, "."); if (newDots < prevDots) { declarationNames.put(type, path); return; } } else { declarationNames.put(type, path); } } @Override public Void visit(ClassInstanceType instanceType, Arg argument) { return null; } Map<DeclarationType, String> getDeclarationNames() { // Making sure that also the super-classes have names. Map<DeclarationType, String> result = new HashMap<>(declarationNames); boolean change = true; while (change) { change = false; for (DeclarationType type : new ArrayList<>(result.keySet())) { if (!(type instanceof ClassType)) { continue; } ClassType clazz = (ClassType) type; //noinspection SuspiciousMethodCalls if (clazz.getSuperClass() != null && !result.containsKey(clazz.getSuperClass())) { result.remove(clazz); change = true; } } } return result; } static final class Arg { final String path; final Set<DeclarationType> seen; Arg(String path, Set<DeclarationType> seen) { this.path = path; this.seen = seen; } Arg cons(String path, DeclarationType type) { return new Arg(this.path + "." + path, this.seen.insert(type)); } } }
package com.junzhao.shanfen.model; import com.google.gson.annotations.Expose; import java.io.Serializable; /** * Created by Administrator on 2018/3/20 0020. * * 抽奖--奖品类 */ public class PHRaffleResultData implements Serializable{ @Expose public String awardId; @Expose public String awardName; @Expose public String awardImg; @Expose public String startTime; @Expose public String invalidTime; @Expose public String addTime; public double awardValue; }
package com.shishal.myappportfolio; import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Toast toast = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } public void launchSpotifyStreamerApp(View view) { showToast("This Button will launch my Spotify Streamer App!"); } public void launchScoresApp(View view) { showToast("This Button will launch my Scores App!"); } public void launchLibraryApp(View view) { showToast("This Button will launch my Library App!"); } public void launchBuildItBiggerApp(View view) { showToast("This Button will launch my Build It Bigger App!"); } public void launchXYZReaderApp(View view) { showToast("This Button will launch my XYZ Reader App!"); } public void launchMyOwnApp(View view) { showToast("This Button will launch my Own App!"); } public void showToast(CharSequence text){ Context context = getApplicationContext(); if(toast != null) toast.cancel(); toast = Toast.makeText(context, text, Toast.LENGTH_SHORT); toast.show(); } }
package com.jgw.supercodeplatform.trace.dto; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * 溯源功能-配置字段表 * @author czm * */ @ApiModel(value = "注意前面带**-字段,溯源功能-配置字段表,") public class TraceFunFieldConfigParam implements Comparable<TraceFunFieldConfigParam>{ @ApiModelProperty(value = "**-主键id--编辑功能或节点时必传") private Long id; //主键id @ApiModelProperty(value = "**-动态生成的表名,在编辑时必传") private String enTableName; //动态生成的表名 @ApiModelProperty(value = "**-功能id,新增及编辑定制功能时必传,新增模板节点时使用节点功能id",notes="新增定制功能时必传,新增模板节点时使用节点功能id") private String functionId; //功能ID号 @ApiModelProperty(value = "**-功能名称,新增及编辑定制功能时必传,新增模板节点时使用节点功能名",notes="新增定制功能时必传,新增模板节点时使用节点功能名") private String functionName; //功能名称 @NotEmpty @ApiModelProperty(value = "**-字段类型,1、表示文本,2、多行文本,3 表示单选 4、多选 5、表示金额,6 表示日期,7表示时间,8表示日期和时间,9 表示图片,10 表示附件,11 表示邮箱,12 表示网址,13_表示对象,14表示手机,15数字,16操作人,17操作时间,18设备,19物料,20对象显示字段",notes="注意如果选择的是13对象类型传递的字段类型为13_具体类型,如:13_varchar(10)", required=true) private String fieldType; //字段类型 1、表示文本,2、多行文本,3 表示单选 4、多选 5、表示金额,6 表示日期,7表示时间,8表示日期和时间,8表示手机,9 表示图片,10 表示附件,11 表示邮箱,12 表示网址,13 表示对象 @NotNull @ApiModelProperty(value = "字段排序权重,数字越小排在前面",required=true) private Integer fieldWeight;//字段权重用于字段排序 @NotEmpty @ApiModelProperty(value = "字段名称",required=true) private String fieldName; //字段名称 @NotEmpty @ApiModelProperty(value = "字段英文名称",required=true) private String fieldCode; //字段Code @ApiModelProperty(value = "选择的对象codeId",required=false) private String objectType; //对象类型 @NotNull @ApiModelProperty(value = "1表示新增功能字段,2表示新增节点",required=true) private Integer typeClass; @ApiModelProperty(value = "默认值",required=false) private String defaultValue; //默认值 @ApiModelProperty(value = "是否必填,1必填,0非必填",example="1") private Integer isRequired; //是否必填 @ApiModelProperty(value = "验证格式") private String validateFormat; //验证格式 @ApiModelProperty(value = "最少长度") private Integer minSize; //最少长度 @ApiModelProperty(value = "**-除时间及金额其它类型默认为字符类型,字符类型必传--最大长度") private Integer maxSize; //最多长度 @ApiModelProperty(value = "默认张数") private Integer requiredNumber; //默认张数 @ApiModelProperty(value = "最少张数") private Integer minNumber; //最少张数 @ApiModelProperty(value = "最多张数") private Integer maxNumber; //最多张数 @ApiModelProperty(value = "选项值") private String dataValue; //选项值 @ApiModelProperty(value = "字段表id主键") private String objectFieldId; @ApiModelProperty(value = "启用") private Integer isRemarkEnable; //启用说明 @ApiModelProperty(value = "显示隐藏,1显示 0隐藏 不传默认显示") private Integer showHidden; //显示隐藏 private String componentId; @ApiModelProperty(value = "筛选字段") private String filterField; @ApiModelProperty(value = "筛选来源") private String filterSource; public Integer getReadOnly() { return readOnly; } public void setReadOnly(Integer readOnly) { this.readOnly = readOnly; } @ApiModelProperty(value = "只读") private Integer readOnly; public String getFilterField() { return filterField; } public void setFilterField(String filterField) { this.filterField = filterField; } public String getFilterSource() { return filterSource; } public void setFilterSource(String filterSource) { this.filterSource = filterSource; } public String getComponentId() { return componentId; } public void setComponentId(String componentId) { this.componentId = componentId; } public TraceFunFieldConfigParam(){} public TraceFunFieldConfigParam(String fieldCode,String fieldName,String fieldType, Integer fieldWeight,Integer isRequired,Integer maxSize,Integer minSize,Integer typeClass,String objectType,String objectFieldId){ this.fieldCode=fieldCode; this.fieldName=fieldName; this.fieldType=fieldType; this.fieldWeight=fieldWeight; this.isRequired=isRequired; this.maxSize=maxSize; this.minSize=minSize; this.typeClass=typeClass; this.objectType=objectType; this.objectFieldId=objectFieldId; } public String getFunctionId() { return functionId; } public void setFunctionId(String functionId) { this.functionId = functionId; } public String getFieldType() { return fieldType; } public void setFieldType(String fieldType) { this.fieldType = fieldType; } public Integer getFieldWeight() { return fieldWeight; } public String getObjectFieldId() { return objectFieldId; } public void setObjectFieldId(String objectFieldId) { this.objectFieldId = objectFieldId; } public void setFieldWeight(Integer fieldWeight) { this.fieldWeight = fieldWeight; } public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public String getFieldCode() { return fieldCode; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getEnTableName() { return enTableName; } public String getObjectType() { return objectType; } public void setObjectType(String objectType) { this.objectType = objectType; } public Integer getTypeClass() { return typeClass; } public void setTypeClass(Integer typeClass) { this.typeClass = typeClass; } public void setEnTableName(String enTableName) { this.enTableName = enTableName; } public void setFieldCode(String fieldCode) { this.fieldCode = fieldCode; } public String getDefaultValue() { return defaultValue; } public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } public Integer getIsRequired() { return isRequired; } public void setIsRequired(Integer isRequired) { this.isRequired = isRequired; } public String getValidateFormat() { return validateFormat; } public void setValidateFormat(String validateFormat) { this.validateFormat = validateFormat; } public Integer getMinSize() { return minSize; } public void setMinSize(Integer minSize) { this.minSize = minSize; } public Integer getMaxSize() { return maxSize; } public void setMaxSize(Integer maxSize) { this.maxSize = maxSize; } public String getFunctionName() { return functionName; } public void setFunctionName(String functionName) { this.functionName = functionName; } public Integer getRequiredNumber() { return requiredNumber; } public void setRequiredNumber(Integer requiredNumber) { this.requiredNumber = requiredNumber; } public Integer getMinNumber() { return minNumber; } public void setMinNumber(Integer minNumber) { this.minNumber = minNumber; } public Integer getMaxNumber() { return maxNumber; } public void setMaxNumber(Integer maxNumber) { this.maxNumber = maxNumber; } public String getDataValue() { return dataValue; } public void setDataValue(String dataValue) { this.dataValue = dataValue; } public Integer getIsRemarkEnable() { return isRemarkEnable; } public void setIsRemarkEnable(Integer isRemarkEnable) { this.isRemarkEnable = isRemarkEnable; } public Integer getShowHidden() { return showHidden; } public void setShowHidden(Integer showHidden) { this.showHidden = showHidden; } @Override public int compareTo(TraceFunFieldConfigParam o) { if (null==o ||null== o.getFieldWeight()) { return 1; } if (null==this.fieldWeight) { return 0; } if (this.fieldWeight>o.fieldWeight) { return 0; } return 1; } @Override public int hashCode() { return new HashCodeBuilder(17, 37). append(fieldCode). append(fieldName). toHashCode(); } @Override public boolean equals(Object obj) { if (obj == null) { return false;} if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } TraceFunFieldConfigParam rhs = (TraceFunFieldConfigParam) obj; return new EqualsBuilder() //这里调用父类的equals()方法,一般情况下不需要使用 .appendSuper(super.equals(obj)) .append("fieldCode", rhs.fieldCode) .append("fieldName", rhs.fieldName) .isEquals(); } }
/** * Copyright 2015 零志愿工作室 (http://www.0will.com). All rights reserved. * File Name: SysCommentServiceImpl.java * Author: chenlong * Encoding UTF-8 * Version: 1.0 * Date: 2015年3月9日 * History: */ package com.Owill.web.system.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.Owill.web.base.dao.BaseDao; import com.Owill.web.base.entity.QueryParam; import com.Owill.web.base.service.BaseServiceImpl; import com.Owill.web.system.dao.SysCommentDao; import com.Owill.web.system.entity.SysComment; /** * @author chenlong(chenlongwill@163.com) * @version Revision: 1.0.0 Date: 2015年3月9日 */ @Service("SysCommentService") public class SysCommentServiceImpl extends BaseServiceImpl<SysComment, Long> implements SysCommentService { @Autowired private SysCommentDao dao; @Override public List<SysComment> query(QueryParam param) { // TODO Auto-generated method stub return dao.query(param); } @Override public List<SysComment> query(QueryParam param, Long id) { // TODO Auto-generated method stub return dao.query(param, id); } @Override public BaseDao<SysComment, Long> getDao() { // TODO Auto-generated method stub return dao; } @Override public List<SysComment> query(String tag, Long id) { // TODO Auto-generated method stub return dao.query(tag, id); } }
package cn.edu.ncu.collegesecondhand.entity; /** * Created by ren lingyun on 2020/4/29 2:01 */ public class Refund { private int id; private int orderId; private String reason; public Refund(int orderId, String reason) { this.orderId = orderId; this.reason = reason; } public Refund() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getOrderId() { return orderId; } public void setOrderId(int orderId) { this.orderId = orderId; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } }
package com.grocery.codenicely.vegworld_new.contact_us.view; import com.grocery.codenicely.vegworld_new.contact_us.model.data.ContactUsData; /** * Created by meghal on 15/10/16. */ public interface ContactUsView { void showLoader(boolean show); void showMessage(String message); void setData(ContactUsData contactUsData); }
package com.cy.web.action.news; import java.util.LinkedHashMap; import javax.annotation.Resource; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.cy.bean.Paging; import com.cy.bean.news.News; import com.cy.service.news.NewsService; import com.cy.web.action.BaseAction; import com.opensymphony.xwork2.ActionContext; /** * 新闻列表控制器<br/> * 用于处理后台的新闻列表查询 * @author CY * */ @Controller @Scope("prototype") public class NewsAction extends BaseAction { @Resource private NewsService newsService; /** * 新闻列表 * @return */ public String execute() { // 分页 Paging<News> paging = new Paging<>(getPage()); // 用于存放排序的条件 LinkedHashMap<String, String> orderby = new LinkedHashMap<>(); // 按照id降序排列 orderby.put("id", "desc"); // 将查询的结果放到分页类中 paging.setQueryResult(newsService.getScrollData(paging.getfirstResult(),paging.getMaxResult(),orderby)); // 将分页对象存放到request域对象中 ActionContext.getContext().put("paging", paging); return "success"; } }
package com.redhat.service.bridge.manager.models; import java.util.Map; import java.util.UUID; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.MapKeyColumn; import com.redhat.service.bridge.infra.models.actions.BaseAction; @Entity public class Action { @Id private String id = UUID.randomUUID().toString(); private String name; private String type; @ElementCollection(fetch = FetchType.LAZY) @CollectionTable( name = "ACTION_PARAMETER", joinColumns = @JoinColumn(name = "action_id")) @MapKeyColumn(name = "name") @Column(name = "value", nullable = false, updatable = false) private Map<String, String> parameters; public String getId() { return id; } public Map<String, String> getParameters() { return parameters; } public void setParameters(Map<String, String> parameters) { this.parameters = parameters; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public BaseAction toActionRequest() { BaseAction ar = new BaseAction(); ar.setName(this.name); ar.setType(this.type); ar.setParameters(this.parameters); return ar; } }
package de.wiltherr.ws2812fx.serial.communication.exception; public class SendingPacketTimeout extends SendingPacketFailed { public SendingPacketTimeout(int timeoutMs) { super(String.format("Writing bytes to serial device timed out after %d ms.", timeoutMs)); } }
package Matriz; import Vetor.Vet2; public class Mat2 { //Atributos de classe do tipo float para cada posição da matriz: m00, m01, m10, m11; float m00, m01, m10, m11; //Método que define os valores da matriz de modo que ela se torne uma matriz identidade; public void setIdentidade(){ this.m00 = 1; this.m01 = 0; this.m10 = 0; this.m11 = 1; } //Método construtor padrão, sem parâmetros, que invoca o método acima, tornando a mesma uma matriz identidade. public Mat2(){ setIdentidade(); } //Método construtor que recebe dois parâmetros do tipo vet2, e estes são atribuídos as colunas da matriz; public Mat2(Vet2 col0, Vet2 col1){ this.m00 = col0.x; this.m01 = col1.x; this.m10 = col0.y; this.m11 = col1.y; } /*Métodos para adição de outra mat2. Estes métodos deverão receber por parâmetro uma outra mat2 que deverá ser somada a uma cópia da matriz atual e a matriz resultante da operação deve ser retornada.*/ public Mat2 adiciona(Mat2 outra){ Mat2 nova = new Mat2(); nova.m00 = this.m00 + outra.m00; nova.m01 = this.m01 + outra.m01; nova.m10 = this.m10 + outra.m10; nova.m11 = this.m11 + outra.m11; return nova; } /*Métodos para subtração de outra mat2. Estes métodos deverão receber por parâmetro uma outra mat2 que deverá ser subtraida a uma cópia da matriz atual e a matriz resultante da operação deve ser retornada.*/ public Mat2 subtrai(Mat2 outra){ Mat2 nova = new Mat2(); nova.m00 = this.m00 - outra.m00; nova.m01 = this.m01 - outra.m01; nova.m10 = this.m10 - outra.m10; nova.m11 = this.m11 - outra.m11; return nova; } //Método que retorna uma cópia da matriz com os valores multiplicados por um escalar recebido por parâmetro; public Mat2 multiplicaEscalar(float escalar){ Mat2 nova = new Mat2(); nova.m00 = this.m00 * escalar; nova.m01 = this.m01 * escalar; nova.m10 = this.m10 * escalar; nova.m11 = this.m11 * escalar; return nova; } //Método que retorna uma cópia da matriz com os valores divididos por um escalar recebido por parâmetro; public Mat2 divideEscalar(float escalar){ Mat2 nova = multiplicaEscalar(1/escalar); return nova; } //Método para multiplicação/produto da matriz por um vet2, este recebido por parâmetro, cujo retorno é um novo vet2 com o resultado da multiplicação; public Vet2 multiplicaVetor(Vet2 vetor){ Vet2 novo = new Vet2(); novo.x = this.m00 * vetor.x + this.m01 * vetor.y; novo.y = this.m10 * vetor.x + this.m11 * vetor.y; return novo; } //Método para multiplicação/produto da matriz por outra matriz mat2, esta recebida por parâmetro, cujo retorno é uma nova mat2 com o resultado da multiplicação; public Mat2 multiplicaMatriz(Mat2 outra){ Mat2 nova = new Mat2(); //primeira linha nova.m00 = this.m00 * outra.m00 + this.m01 * outra.m10; nova.m01 = this.m00 * outra.m01 + this.m01 * outra.m11; //segunda linha nova.m10 = this.m10 * outra.m00 + this.m11 * outra.m10; nova.m11 = this.m10 * outra.m01 + this.m11 * outra.m11; return nova; } //Método que retorna uma cópia da matriz atual transposta; public Mat2 getTransposta(){ Mat2 nova = new Mat2(); nova.m00 = this.m00; nova.m01 = this.m10; nova.m10 = this.m01; nova.m11 = this.m11; return nova; } //Método que simplesmente retorna uma nova cópia da matriz atual. public Mat2 getCopia(){ Mat2 nova = new Mat2(); nova.m00 = this.m00; nova.m01 = this.m01; nova.m10 = this.m10; nova.m11 = this.m11; return nova; } //Método que retorna uma matriz do tipo float de dimensões 2x2, esta com os valores dos atributos de classe desta matriz. public float[][] getMatriz(){ float m[][] = new float[3][3]; m[0][0] = this.m00; m[0][1] = this.m01; m[1][0] = this.m10; m[1][1] = this.m11; return m; } /*Método de translação, que recebe por parâmetro os valores de translação tx e ty, e então aplica a uma cópia da matriz uma translação de (tx,ty), e então retorna a nova matriz transladada.*/ public Mat2 translacao(float tx, float ty){ Mat2 nova = getCopia(); Mat2 translacao = new Mat2(); translacao.m01 = tx; translacao.m11 = ty; Mat2 resultado = translacao.multiplicaMatriz(nova); return resultado; } /*Método de rotação, que recebe por parâmetro o valor referente ao ângulo de rotação, e então aplica a uma cópia da matriz uma matriz tal rotação, e então retorna a nova matriz rotacionada.*/ public Mat2 escala(float sx, float sy){ Mat2 nova = getCopia(); Mat2 escala = new Mat2(); escala.m00 = sx; escala.m11 = sy; Mat2 resultado = escala.multiplicaMatriz(nova); return resultado; } /*Método de escala, que recebe por parâmetro os fatores de escala sx e sy, e então aplica a uma cópia da matriz uma escala de sx em x e sy em y, e então retorna a nova matriz escalada.*/ public Mat2 rotacao(float angulo){ Mat2 nova = getCopia(); Mat2 rotacao = new Mat2(); rotacao.m00 = (float) Math.cos(Math.toRadians(angulo)); rotacao.m01 = (float) - Math.sin(Math.toRadians(angulo)); rotacao.m10 = (float) Math.sin(Math.toRadians(angulo)); rotacao.m11 = (float) Math.cos(Math.toRadians(angulo)); Mat2 resultado = rotacao.multiplicaMatriz(nova); return resultado; } }
package com.bytest.autotest.innerService.impl; import com.bytest.autotest.aspect.DynamicSource; import com.bytest.autotest.dao.BreEventParamDao; import com.bytest.autotest.domain.BreEventParam; import com.bytest.autotest.enums.DateSourceType; import com.bytest.autotest.innerService.BreEventParamService; import org.apache.commons.lang.time.DateUtils; import org.apache.commons.lang3.time.DateFormatUtils; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.Date; import java.util.List; /** * 策略引擎事件请求和响应参数表(BreEventParam01)表服务实现类 * * @author makejava * @since 2020-08-20 16:09:08 */ @Service("breEventParamService") @DynamicSource(dasource = DateSourceType.bre) public class BreEventParamServiceImpl implements BreEventParamService { @Resource private BreEventParamDao breEventParamDao; /** * 通过ID查询单条数据 * * @param requestId 主键 * @return 实例对象 */ @Override public BreEventParam queryById(String requestId,String day) { return this.breEventParamDao.queryById(requestId,day); } /** * * @param eventId * @param * @return */ @Override public List<BreEventParam> queryByIdAndDay(String eventId,String day) { return this.breEventParamDao.queryByIdAndDay(eventId,day); } /** * 查询多条数据 * * @param offset 查询起始位置 * @param limit 查询条数 * @return 对象列表 */ @Override public List<BreEventParam> queryAllByLimit(int offset, int limit,String day) { return this.breEventParamDao.queryAllByLimit(offset, limit,day); } /** * 新增数据 * * @param breEventParam 实例对象 * @return 实例对象 */ @Override public BreEventParam insert(BreEventParam breEventParam,String day) { this.breEventParamDao.insert(breEventParam,day); return breEventParam; } /** * 修改数据 * * @param breEventParam 实例对象 * @return 实例对象 */ @Override public BreEventParam update(BreEventParam breEventParam,String day) { this.breEventParamDao.update(breEventParam,day); return this.queryById(breEventParam.getRequestId(),day); } /** * 通过主键删除数据 * * @param requestId 主键 * @return 是否成功 */ @Override public boolean deleteById(String requestId,String day) { return this.breEventParamDao.deleteById(requestId,day) > 0; } }
package com.roundarch.controller; import java.net.URLConnection; import java.util.Map; import org.apache.commons.io.IOUtils; import org.junit.Assert; import org.junit.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockMultipartFile; import org.springframework.mock.web.MockMultipartHttpServletRequest; public class RecruitControllerIntegrationTest extends AbstractControllerIntegrationTest { @Test public void createRecruitWithJson() throws Exception { MockHttpServletRequest request = createJsonRequest(); request.setMethod("POST"); request.setContentType("application/json"); request.setRequestURI("/recruit"); request.setContent("{'firstName' : 'Adam', \"lastName\" : \"Test\", \"school\" : \"Duke University\"}".getBytes()); MockHttpServletResponse response = handleRequest(request); Map<String, Object> json = toJson(response); Assert.assertEquals(200, response.getStatus()); Assert.assertNotNull(json.get("id")); } @Test public void createRecruitWithSingleQuotedJson() throws Exception { MockHttpServletRequest request = createJsonRequest(); request.setMethod("POST"); request.setContentType("application/json"); request.setRequestURI("/recruit"); request.setContent("{'firstName' : 'Adam', 'lastName' : 'Test', 'school' : \"Duke University\"}".getBytes()); MockHttpServletResponse response = handleRequest(request); Map<String, Object> json = toJson(response); Assert.assertEquals(200, response.getStatus()); Assert.assertNotNull(json.get("id")); } @Test public void createRecruitWithForm() throws Exception { MockHttpServletRequest request = createJsonRequest(); request.setMethod("POST"); request.setContentType("application/x-www-form-urlencoded"); request.setRequestURI("/recruit"); request.addParameter("firstName", "Adam"); request.addParameter("lastName", "Scherer"); request.addParameter("school", "Drake University"); MockHttpServletResponse response = handleRequest(request); Map<String, Object> json = toJson(response); Assert.assertEquals(200, response.getStatus()); Assert.assertNotNull(json.get("id")); } @Test public void get() throws Exception { MockHttpServletRequest request = createJsonRequest(); request.setMethod("GET"); request.setRequestURI("/recruit/1234"); MockHttpServletResponse response = handleRequest(request); Map<String, Object> json = toJson(response); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals(json.get("id"), "1234"); Assert.assertNull(json.get("reviews")); } @Test public void getComposite() throws Exception { MockHttpServletRequest request = createJsonRequest(); request.setMethod("GET"); request.setRequestURI("/recruit/composite/1234"); MockHttpServletResponse response = handleRequest(request); Map<String, Object> json = toJson(response); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals(json.get("id"), "1234"); Assert.assertNotNull(json.get("reviews")); } @Test public void createOrUpdate() throws Exception { MockHttpServletRequest request = createJsonRequest(); request.setMethod("POST"); request.setContentType("application/x-www-form-urlencoded"); request.setRequestURI("/recruit/1234"); request.addParameter("firstName", "TESTUPDATE"); MockHttpServletResponse response = handleRequest(request); Map<String, Object> json = toJson(response); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals(json.get("firstName"), "TESTUPDATE"); Assert.assertEquals(json.get("lastName"), "USER"); } @Test public void createOrUpdateWithJson() throws Exception { MockHttpServletRequest request = createJsonRequest(); request.setMethod("POST"); request.setRequestURI("/recruit/1234"); request.setContent("{\"firstName\" : \"TESTUPDATEJSON\"}".getBytes()); MockHttpServletResponse response = handleRequest(request); Map<String, Object> json = toJson(response); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals(json.get("firstName"), "TESTUPDATEJSON"); Assert.assertEquals(json.get("lastName"), "USER"); } @Test public void createOrUpdateSchoolListWithJson() throws Exception { MockHttpServletRequest request = createJsonRequest(); request.setMethod("POST"); request.setRequestURI("/recruit/1234"); request.setContent("{'firstName' : 'TESTUPDATEJSON', 'education' : [{'name' : 'Yale University'}, {'name' : 'Harvard University'}]}".getBytes()); MockHttpServletResponse response = handleRequest(request); Map<String, Object> json = toJson(response); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals(json.get("firstName"), "TESTUPDATEJSON"); Assert.assertEquals(json.get("lastName"), "USER"); } @Test public void delete() throws Exception { MockHttpServletRequest request = createJsonRequest(); request.setMethod("POST"); request.setRequestURI("/recruit/delete/1234"); MockHttpServletResponse response = handleRequest(request); Map<String, Object> json = toJson(response); Assert.assertEquals(204, response.getStatus()); Assert.assertEquals(true, json.isEmpty()); } @Test public void createRecruitAndResumeWithPost() throws Exception { MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(); request.setRequestURI("/recruit"); request.addParameter("resume", "true"); request.addParameter("firstName", "TEST"); request.addParameter("lastName", "WITHRESUME"); String filename = "sample_resume.docx"; byte[] content = IOUtils.toByteArray(new ClassPathResource("/sample_resume.docx").getInputStream()); MockMultipartFile mockMultipartFile = new MockMultipartFile("file", filename, URLConnection.guessContentTypeFromName(filename), content); request.addFile(mockMultipartFile); MockHttpServletResponse response = handleRequest(request); Assert.assertEquals(200, response.getStatus()); } }
package edu.upenn.cis350.androidapp.DataInteraction.Management.ItemManagement; import java.net.URL; import java.util.*; import org.json.simple.parser.*; import org.json.simple.*; import java.text.*; import edu.upenn.cis350.androidapp.AccessWebTask; import edu.upenn.cis350.androidapp.DataInteraction.Data.*; public class FoundJSONReader { private FoundJSONReader() {} private static FoundJSONReader instance = new FoundJSONReader(); public static FoundJSONReader getInstance() { return instance; } public Collection<FoundItem> getAllFoundItems() { Collection<FoundItem> foundItems = new HashSet<FoundItem>(); JSONParser parser = new JSONParser(); try { URL url = new URL("http://10.0.2.2:3000/all-found-items"); AccessWebTask task = new AccessWebTask(); task.execute(url); JSONObject jo = (JSONObject) parser.parse(task.get()); JSONArray items = (JSONArray) jo.get("items"); Iterator iter = items.iterator(); while (iter.hasNext()) { JSONObject item = (JSONObject) iter.next(); long id = (long) item.get("id"); long posterId = ((long) item.get("posterId")); String category = (String) item.get("category"); String rawDate = (String) item.get("date"); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); Date date = null; date = dateFormat.parse(rawDate); double latitude = Double.valueOf(item.get("latitude").toString()); double longitude = Double.valueOf(item.get("longitude").toString()); String around = (String) item.get("around"); FoundItem f = new FoundItem(id, posterId, category, date, latitude, longitude, around); foundItems.add(f); } } catch (Exception e) { System.out.println(e); } return foundItems; } }
package com.thinkdevs.cryptomarket.model; /** * Created by ABC on 8/3/2017. */ public class Users { private String un; private String ue; private String ui; private long uc; private long ul; private int us; private String ur; public Users() { } public Users(String un, String ue, String ui, long uc, long ul, int us, String ur) { this.un = un; this.ue = ue; this.ui = ui; this.uc = uc; this.ul = ul; this.us = us; this.ur=ur; } public String getUn() { return un; } public void setUn(String un) { this.un = un; } public String getUe() { return ue; } public void setUe(String ue) { this.ue = ue; } public String getUi() { return ui; } public void setUi(String ui) { this.ui = ui; } public long getUc() { return uc; } public void setUc(long uc) { this.uc = uc; } public long getUl() { return ul; } public void setUl(long ul) { this.ul = ul; } public int getUs() { return us; } public void setUs(int us) { this.us = us; } public String getUr() { return ur; } public void setUr(String ur) { this.ur = ur; } }
/* * Created on 09/12/2008 * */ package com.citibank.ods.persistence.pl.dao; import com.citibank.ods.common.dataset.DataSet; import com.citibank.ods.entity.pl.TplErEntity; /** * @author lfabiano * @since 09/12/2008 */ public interface TplErDAO extends BaseTplErDAO { public TplErEntity insert( TplErEntity erEntity_ ); public void deleteRelations( String erNbr_ ); public TplErEntity update( TplErEntity tplErEntity_ ); public boolean existsRelationActive( String erNbr_ ); public boolean existsRelation( String erNbr_, String emNbr_ ); //Combo de ER. public DataSet loadErNbr(); }
/* * 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 com.ut.healthelink.model; import java.util.Date; import java.util.List; /** * * @author chadmccue */ public class Transaction { private int orgId; private int sourceSubOrgId; private int userId; private int configId; private String batchName = null; private int transportMethodId; private String originalFileName = null; private int statusId; private String statusValue; private int messageTypeId; private int transactionStatusId; private int targetOrgId; private int targetSubOrgId = 0; private List<Integer> targetConfigId; private boolean autoRelease = true; private Date dateSubmitted = null; private String messageTypeName = null; private int batchId = 0; private int transactionId = 0; private int transactionRecordId = 0; private int transactionTargetId = 0; private int sourceType = 1; private int internalStatusId = 0; private int orginialTransactionId = 0; private String reportableField1 = null; private String reportableField2 = null; private String reportableField3 = null; private String reportableField4 = null; private String reportableFieldHeading1 = null; private String reportableFieldHeading2 = null; private String reportableFieldHeading3 = null; private String reportableFieldHeading4 = null; private List<transactionRecords> sourceOrgFields = null; private List<transactionRecords> sourceProviderFields = null; private List<transactionRecords> targetOrgFields = null; private List<transactionRecords> targetProviderFields = null; private List<transactionRecords> patientFields = null; private List<transactionRecords> detailFields = null; private Integer attachmentLimit; private Boolean attachmentRequired = false; private String attachmentNote = ""; private int messageStatus = 1; private String srcConfigName; private String srcOrgName; private String targetConfigName; private String targetOrgName; private Integer targetConfigId1; private String srcSiteName; private Integer parentOrgId = 0; public int getorgId() { return orgId; } public void setorgId(int orgId) { this.orgId = orgId; } public int getuserId() { return userId; } public void setuserId(int userId) { this.userId = userId; } public int getconfigId() { return configId; } public void setconfigId(int configId) { this.configId = configId; } public String getbatchName() { return batchName; } public void setbatchName(String batchName) { this.batchName = batchName; } public int gettransportMethodId() { return transportMethodId; } public void settransportMethodId(int transportMethodId) { this.transportMethodId = transportMethodId; } public String getoriginalFileName() { return originalFileName; } public void setoriginalFileName(String originalFileName) { this.originalFileName = originalFileName; } public int getstatusId() { return statusId; } public void setstatusId(int statusId) { this.statusId = statusId; } public String getstatusValue() { return statusValue; } public void setstatusValue(String statusValue) { this.statusValue = statusValue; } public int getmessageTypeId() { return messageTypeId; } public void setmessageTypeId(int messageTypeId) { this.messageTypeId = messageTypeId; } public int gettransactionStatusId() { return transactionStatusId; } public void settransactionStatusId(int transactionStatusId) { this.transactionStatusId = transactionStatusId; } public int gettargetOrgId() { return targetOrgId; } public void settargetOrgId(int targetOrgId) { this.targetOrgId = targetOrgId; } public List<Integer> gettargetConfigId() { return targetConfigId; } public void settargetConfigId(List<Integer> targetConfigId) { this.targetConfigId = targetConfigId; } public List<transactionRecords> getsourceOrgFields() { return sourceOrgFields; } public void setsourceOrgFields(List<transactionRecords> sourceOrgFields) { this.sourceOrgFields = sourceOrgFields; } public List<transactionRecords> getsourceProviderFields() { return sourceProviderFields; } public void setsourceProviderFields(List<transactionRecords> sourceProviderFields) { this.sourceProviderFields = sourceProviderFields; } public List<transactionRecords> gettargetOrgFields() { return targetOrgFields; } public void settargetOrgFields(List<transactionRecords> targetOrgFields) { this.targetOrgFields = targetOrgFields; } public List<transactionRecords> gettargetProviderFields() { return targetProviderFields; } public void settargetProviderFields(List<transactionRecords> targetProviderFields) { this.targetProviderFields = targetProviderFields; } public List<transactionRecords> getpatientFields() { return patientFields; } public void setpatientFields(List<transactionRecords> patientFields) { this.patientFields = patientFields; } public List<transactionRecords> getdetailFields() { return detailFields; } public void setdetailFields(List<transactionRecords> detailFields) { this.detailFields = detailFields; } public boolean getautoRelease() { return autoRelease; } public void setautoRelease(boolean autoRelease) { this.autoRelease = autoRelease; } public Date getdateSubmitted() { return dateSubmitted; } public void setdateSubmitted(Date dateSubmitted) { this.dateSubmitted = dateSubmitted; } public String getmessageTypeName() { return messageTypeName; } public void setmessageTypeName(String messageTypeName) { this.messageTypeName = messageTypeName; } public int gettransactionRecordId() { return transactionRecordId; } public void settransactionRecordId(int transactionRecordId) { this.transactionRecordId = transactionRecordId; } public int getbatchId() { return batchId; } public void setbatchId(int batchId) { this.batchId = batchId; } public int gettransactionId() { return transactionId; } public void settransactionId(int transactionId) { this.transactionId = transactionId; } public int gettransactionTargetId() { return transactionTargetId; } public void settransactionTargetId(int transactionTargetId) { this.transactionTargetId = transactionTargetId; } public int getsourceType() { return sourceType; } public void setsourceType(int sourceType) { this.sourceType = sourceType; } public int getinternalStatusId() { return internalStatusId; } public void setinternalStatusId(int internalStatusId) { this.internalStatusId = internalStatusId; } public int getorginialTransactionId() { return orginialTransactionId; } public void setorginialTransactionId(int orginialTransactionId) { this.orginialTransactionId = orginialTransactionId; } public String getreportableField1() { return reportableField1; } public void setreportableField1(String reportableField1) { this.reportableField1 = reportableField1; } public String getreportableField2() { return reportableField2; } public void setreportableField2(String reportableField2) { this.reportableField2 = reportableField2; } public String getreportableField3() { return reportableField3; } public void setreportableField3(String reportableField3) { this.reportableField3 = reportableField3; } public String getreportableField4() { return reportableField4; } public void setreportableField4(String reportableField4) { this.reportableField4 = reportableField4; } public String getreportableFieldHeading1() { return reportableFieldHeading1; } public void setreportableFieldHeading1(String reportableFieldHeading1) { this.reportableFieldHeading1 = reportableFieldHeading1; } public String getreportableFieldHeading2() { return reportableFieldHeading2; } public void setreportableFieldHeading2(String reportableFieldHeading2) { this.reportableFieldHeading2 = reportableFieldHeading2; } public String getreportableFieldHeading3() { return reportableFieldHeading3; } public void setreportableFieldHeading3(String reportableFieldHeading3) { this.reportableFieldHeading3 = reportableFieldHeading3; } public String getreportableFieldHeading4() { return reportableFieldHeading4; } public void setreportableFieldHeading4(String reportableFieldHeading4) { this.reportableFieldHeading4 = reportableFieldHeading4; } public int getmessageStatus() { return messageStatus; } public void setmessageStatus(int messageStatus) { this.messageStatus = messageStatus; } public int getTargetSubOrgId() { return targetSubOrgId; } public void setTargetSubOrgId(int targetSubOrgId) { this.targetSubOrgId = targetSubOrgId; } public int getSourceSubOrgId() { return sourceSubOrgId; } public void setSourceSubOrgId(int sourceSubOrgId) { this.sourceSubOrgId = sourceSubOrgId; } public Integer getAttachmentLimit() { return attachmentLimit; } public void setAttachmentLimit(Integer attachmentLimit) { this.attachmentLimit = attachmentLimit; } public Boolean getAttachmentRequired() { return attachmentRequired; } public void setAttachmentRequired(Boolean attachmentRequired) { this.attachmentRequired = attachmentRequired; } public String getAttachmentNote() { return attachmentNote; } public void setAttachmentNote(String attachmentNote) { this.attachmentNote = attachmentNote; } public List<Integer> getTargetConfigId() { return targetConfigId; } public void setTargetConfigId(List<Integer> targetConfigId) { this.targetConfigId = targetConfigId; } public String getSrcConfigName() { return srcConfigName; } public void setSrcConfigName(String srcConfigName) { this.srcConfigName = srcConfigName; } public String getSrcOrgName() { return srcOrgName; } public void setSrcOrgName(String srcOrgName) { this.srcOrgName = srcOrgName; } public String getTargetConfigName() { return targetConfigName; } public void setTargetConfigName(String targetConfigName) { this.targetConfigName = targetConfigName; } public String getTargetOrgName() { return targetOrgName; } public void setTargetOrgName(String targetOrgName) { this.targetOrgName = targetOrgName; } public Integer getTargetConfigId1() { return targetConfigId1; } public void setTargetConfigId1(Integer targetConfigId1) { this.targetConfigId1 = targetConfigId1; } public int getOrgId() { return orgId; } public void setOrgId(int orgId) { this.orgId = orgId; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public int getConfigId() { return configId; } public void setConfigId(int configId) { this.configId = configId; } public String getBatchName() { return batchName; } public void setBatchName(String batchName) { this.batchName = batchName; } public int getTransportMethodId() { return transportMethodId; } public void setTransportMethodId(int transportMethodId) { this.transportMethodId = transportMethodId; } public String getOriginalFileName() { return originalFileName; } public void setOriginalFileName(String originalFileName) { this.originalFileName = originalFileName; } public int getStatusId() { return statusId; } public void setStatusId(int statusId) { this.statusId = statusId; } public String getStatusValue() { return statusValue; } public void setStatusValue(String statusValue) { this.statusValue = statusValue; } public int getMessageTypeId() { return messageTypeId; } public void setMessageTypeId(int messageTypeId) { this.messageTypeId = messageTypeId; } public int getTransactionStatusId() { return transactionStatusId; } public void setTransactionStatusId(int transactionStatusId) { this.transactionStatusId = transactionStatusId; } public int getTargetOrgId() { return targetOrgId; } public void setTargetOrgId(int targetOrgId) { this.targetOrgId = targetOrgId; } public boolean isAutoRelease() { return autoRelease; } public void setAutoRelease(boolean autoRelease) { this.autoRelease = autoRelease; } public Date getDateSubmitted() { return dateSubmitted; } public void setDateSubmitted(Date dateSubmitted) { this.dateSubmitted = dateSubmitted; } public String getMessageTypeName() { return messageTypeName; } public void setMessageTypeName(String messageTypeName) { this.messageTypeName = messageTypeName; } public int getBatchId() { return batchId; } public void setBatchId(int batchId) { this.batchId = batchId; } public int getTransactionId() { return transactionId; } public void setTransactionId(int transactionId) { this.transactionId = transactionId; } public int getTransactionRecordId() { return transactionRecordId; } public void setTransactionRecordId(int transactionRecordId) { this.transactionRecordId = transactionRecordId; } public int getTransactionTargetId() { return transactionTargetId; } public void setTransactionTargetId(int transactionTargetId) { this.transactionTargetId = transactionTargetId; } public int getSourceType() { return sourceType; } public void setSourceType(int sourceType) { this.sourceType = sourceType; } public int getInternalStatusId() { return internalStatusId; } public void setInternalStatusId(int internalStatusId) { this.internalStatusId = internalStatusId; } public int getOrginialTransactionId() { return orginialTransactionId; } public void setOrginialTransactionId(int orginialTransactionId) { this.orginialTransactionId = orginialTransactionId; } public String getReportableField1() { return reportableField1; } public void setReportableField1(String reportableField1) { this.reportableField1 = reportableField1; } public String getReportableField2() { return reportableField2; } public void setReportableField2(String reportableField2) { this.reportableField2 = reportableField2; } public String getReportableField3() { return reportableField3; } public void setReportableField3(String reportableField3) { this.reportableField3 = reportableField3; } public String getReportableField4() { return reportableField4; } public void setReportableField4(String reportableField4) { this.reportableField4 = reportableField4; } public String getReportableFieldHeading1() { return reportableFieldHeading1; } public void setReportableFieldHeading1(String reportableFieldHeading1) { this.reportableFieldHeading1 = reportableFieldHeading1; } public String getReportableFieldHeading2() { return reportableFieldHeading2; } public void setReportableFieldHeading2(String reportableFieldHeading2) { this.reportableFieldHeading2 = reportableFieldHeading2; } public String getReportableFieldHeading3() { return reportableFieldHeading3; } public void setReportableFieldHeading3(String reportableFieldHeading3) { this.reportableFieldHeading3 = reportableFieldHeading3; } public String getReportableFieldHeading4() { return reportableFieldHeading4; } public void setReportableFieldHeading4(String reportableFieldHeading4) { this.reportableFieldHeading4 = reportableFieldHeading4; } public List<transactionRecords> getSourceOrgFields() { return sourceOrgFields; } public void setSourceOrgFields(List<transactionRecords> sourceOrgFields) { this.sourceOrgFields = sourceOrgFields; } public List<transactionRecords> getSourceProviderFields() { return sourceProviderFields; } public void setSourceProviderFields( List<transactionRecords> sourceProviderFields) { this.sourceProviderFields = sourceProviderFields; } public List<transactionRecords> getTargetOrgFields() { return targetOrgFields; } public void setTargetOrgFields(List<transactionRecords> targetOrgFields) { this.targetOrgFields = targetOrgFields; } public List<transactionRecords> getTargetProviderFields() { return targetProviderFields; } public void setTargetProviderFields( List<transactionRecords> targetProviderFields) { this.targetProviderFields = targetProviderFields; } public List<transactionRecords> getPatientFields() { return patientFields; } public void setPatientFields(List<transactionRecords> patientFields) { this.patientFields = patientFields; } public List<transactionRecords> getDetailFields() { return detailFields; } public void setDetailFields(List<transactionRecords> detailFields) { this.detailFields = detailFields; } public int getMessageStatus() { return messageStatus; } public void setMessageStatus(int messageStatus) { this.messageStatus = messageStatus; } public String getSrcSiteName() { return srcSiteName; } public void setSrcSiteName(String srcSiteName) { this.srcSiteName = srcSiteName; } public Integer getParentOrgId() { return parentOrgId; } public void setParentOrgId(Integer parentOrgId) { this.parentOrgId = parentOrgId; } }
package com.Exam.Entity; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.apache.lucene.analysis.core.KeywordAnalyzer; import org.hibernate.search.annotations.Analyzer; import org.hibernate.search.annotations.DocumentId; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.Indexed; import org.hibernate.search.annotations.TermVector; @Entity @Table(name = "customer") @Indexed public class Customer { @Id @GeneratedValue(strategy = GenerationType.AUTO) @DocumentId int maKH; @Field String tenKH; String diaChi; String phone; Date ngaySinh; @Field(termVector = TermVector.YES) String email; String cmnd; public String getCmnd() { return cmnd; } public void setCmnd(String cmnd) { this.cmnd = cmnd; } public int getMaKH() { return maKH; } public void setMaKH(int maKH) { this.maKH = maKH; } public String getTenKH() { return tenKH; } public void setTenKH(String tenKH) { this.tenKH = tenKH; } public String getDiaChi() { return diaChi; } public void setDiaChi(String diaChi) { this.diaChi = diaChi; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Date getNgaySinh() { return ngaySinh; } public void setNgaySinh(Date ngaySinh) { this.ngaySinh = ngaySinh; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Customer(int maKH, String tenKH, String diaChi, String phone, Date ngaySinh, String email, String cmnd) { super(); this.maKH = maKH; this.tenKH = tenKH; this.diaChi = diaChi; this.phone = phone; this.ngaySinh = ngaySinh; this.email = email; this.cmnd = cmnd; } public Customer() { super(); } }
package br.mg.puc.sica.security.server.entities; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; @Entity @Table(name = "user", schema="security") public class User implements Serializable { /** * */ private static final long serialVersionUID = -4691892066212174511L; @Id @Column(name = "email") private String email; @Column(name = "name") private String name; @Column(name = "picture") private String picture; @Transient private String authorization; protected User() { } public static User of (String email, String name, String urlPicture, String jsessionid) { User user = new User (); user.setEmail(email); user.setName(name); user.setPicture(urlPicture); user.setAuthorization(jsessionid); return user; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the email */ public String getEmail() { return email; } /** * @param email the email to set */ public void setEmail(String email) { this.email = email; } /** * @return the picture */ public String getPicture() { return picture; } /** * @param picture the picture to set */ public void setPicture(String picture) { this.picture = picture; } /** * @return the authorization */ public String getAuthorization() { return authorization; } /** * @param authorization the authorization to set */ public void setAuthorization(String authorization) { this.authorization = authorization; } }
package edu.oregonstate.cs361.battleship; /** * Created by williamstribyjr on 3/14/17. */ public class EasyComputer extends Computer{ public EasyComputer(){ } }
package com.timewarp.games.onedroidcode.vsl.nodes.robot.sensors; import com.timewarp.engine.Direction; import com.timewarp.engine.Vector2D; import com.timewarp.games.onedroidcode.objects.Player; import com.timewarp.games.onedroidcode.vsl.CodeRunner; import com.timewarp.games.onedroidcode.vsl.Node; import com.timewarp.games.onedroidcode.vsl.Value; public class BlockSensorNode extends Node { @Override public Node execute(CodeRunner runner) { final Player player = runner.grid.player; final Direction dir = player.direction; final Vector2D position = player.getXY(); final Vector2D target = position.add(dir.getVector()).add(0.5f); final boolean isSolid = runner.grid.isObjectSolid((int) target.x, (int) target.y); runner.setFlag("boolean", new Value(Value.TYPE_BOOLEAN, isSolid)); return next; } @Override public void reset() { } }
package ma.adria.banque.repository; import ma.adria.banque.entities.Test; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface TestRepository extends JpaRepository<Test, Long> { }
package com.esum.comp.etx; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.comp.etx.process.ETXMessageListener; import com.esum.comp.etx.table.TPRoutInfoTable; import com.esum.framework.core.component.DefaultComponent; import com.esum.framework.core.component.table.InfoTableManager; import com.esum.framework.core.exception.SystemException; public class ETXAdapter extends DefaultComponent { private Logger log = LoggerFactory.getLogger(ETXAdapter.class); public void onInit() throws SystemException { initComponentConfig(new ETXConfig(getId())); log.debug("Initializing TPRoutInfo..."); initInfoTable(ETXConfig.ETX_INFO_TABLE_ID, TPRoutInfoTable.class); log.info("Initialized TPRoutInfo."); setInputChannelListener(ETXMessageListener.class); } public void onReload(String[] reloadIds, boolean inBound, boolean outBound) throws SystemException { TPRoutInfoTable tpInfoTable = (TPRoutInfoTable)InfoTableManager.getInstance().getInfoTable(ETXConfig.ETX_INFO_TABLE_ID); if(reloadIds==null || reloadIds.length==0) tpInfoTable.reloadAllInfoRecord(); else tpInfoTable.reloadInfoRecord(reloadIds); } }
/* * 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 Turnieje.Servlets; import email.GoogleMail; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.mail.MessagingException; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; 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 org.json.JSONObject; import pl.polsl.aei.io.turnieje.model.datamodel.User; import pl.polsl.aei.io.turnieje.model.datamodel.UserId; import pl.polsl.aei.io.turnieje.model.repository.ITeamRepository; import pl.polsl.aei.io.turnieje.model.repository.IUserRepository; import pl.polsl.aei.io.turnieje.model.repository.RepositoryProvider; /** * * @author mariu */ @WebServlet(name = "RegistrationServlet", urlPatterns = {"/Registration"}) public class RegistrationServlet extends HttpServlet { ITeamRepository teamRepository; //<editor-fold defaultstate="expanded" desc="init()"> RepositoryProvider repositoryProvider; IUserRepository userRepository; @Override public void init() { repositoryProvider = RepositoryProvider.getInstance(); userRepository = repositoryProvider.getUserRepository(); } //wykorzystanie klasy InternetAddress do sprawdzenia emaila public static boolean isValidEmailAddress(String email) { boolean result = true; try { InternetAddress emailAddr = new InternetAddress(email); emailAddr.validate(); } catch (AddressException ex) { result = false; } return result; } public static boolean validateFirstName(String firstName) { return firstName.matches("[A-Z][a-zA-Z]*"); } public static boolean validateLastName(String lastName) { return lastName.matches("[a-zA-z]+(['-][a-zA-Z]+)*"); } //</editor-fold> /** * 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, MessagingException { response.setContentType("text/html;charset=UTF-8"); String JSONString = request.getParameter("JSONFromRegistration"); JSONObject JSON = new JSONObject(JSONString); String name = JSON.getString("name"); String surname = JSON.getString("surname"); String email = JSON.getString("email"); String password1 = JSON.getString("password1"); String password2 = JSON.getString("password2"); String checkBox= JSON.getString("checkBox"); String statement =""; if ("".equals(name)) {statement="Imie jest puste!"; } if(name.length()<3) { statement="Imie jest zbyt krotkie!"; } if(!validateFirstName(name)) { statement="Imie jest niepoprawne!"; } if(!validateLastName(surname)) { statement="Nazwisko jest niepoprawne!"; } if ("".equals(surname)) {statement="Nazwisko jest puste!"; } if(surname.length()<3) { statement="Nazwisko jest zbyt krotkie!"; } if (!(password1.equals(password2))) { statement="Hasla są rozne!"; } if (("".equals(password1)) || ("".equals(password2))) {statement="Haslo jest puste!"; } if(password1.length()<8) { statement="Haslo jest zbyt krotkie!"; } if(!isValidEmailAddress(email)) { statement="Niepoprawny email!"; } if ("false".equals(checkBox)) { statement="Brak akceptacji regulaminu!"; } if("".equals(statement)) { User user = new User(); user.setEmail(email); user.setFirstName(name); user.setActive(false); user.setLastName(surname); user.setPassHash(password1); UserId userid = userRepository.add(user); if (userid == null) { statement ="Email ktory podales juz istnieje w bazie!"; response.sendRedirect("BadRegistration.jsp?statement="+statement); } else { int id=userid.id; GoogleMail.Send("turniejeserwis","Aligator33",email, email,"Link Aktywacyjny","Jeśli się rejestrowałeś skopiuj ten link aktywacyjny: " + "http://localhost:15406/Turnieje/RegistrationActivate.jsp?id="+id); if(statement.isEmpty()) { response.sendRedirect("GoodRegistration.jsp"); } else { response.sendRedirect("BadRegistration.jsp?statement="+statement); } } } else { response.sendRedirect("BadRegistration.jsp?statement="+statement); } } // <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 { try { processRequest(request, response); } catch (MessagingException ex) { Logger.getLogger(RegistrationServlet.class.getName()).log(Level.SEVERE, null, ex); } } /** * 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 { try { processRequest(request, response); } catch (MessagingException ex) { Logger.getLogger(RegistrationServlet.class.getName()).log(Level.SEVERE, null, ex); } } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
package com.gmail.filoghost.holographicdisplays.disk; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import com.gmail.filoghost.holographicdisplays.exception.InvalidFormatException; import com.gmail.filoghost.holographicdisplays.exception.WorldNotFoundException; public class LocationSerializer { private static DecimalFormat decimalFormat; static { // More precision is not needed at all. decimalFormat = new DecimalFormat("0.000"); DecimalFormatSymbols formatSymbols = decimalFormat.getDecimalFormatSymbols(); formatSymbols.setDecimalSeparator('.'); decimalFormat.setDecimalFormatSymbols(formatSymbols); } public static Location locationFromString(String input) throws WorldNotFoundException, InvalidFormatException { if (input == null) { throw new InvalidFormatException(); } String[] parts = input.split(","); if (parts.length != 4) { throw new InvalidFormatException(); } try { double x = Double.parseDouble(parts[1].replace(" ", "")); double y = Double.parseDouble(parts[2].replace(" ", "")); double z = Double.parseDouble(parts[3].replace(" ", "")); World world = Bukkit.getWorld(parts[0].trim()); if (world == null) { throw new WorldNotFoundException(parts[0].trim()); } return new Location(world, x, y, z); } catch (NumberFormatException ex) { throw new InvalidFormatException(); } } public static String locationToString(Location loc) { return (loc.getWorld().getName() + ", " + decimalFormat.format(loc.getX()) + ", " + decimalFormat.format(loc.getY()) + ", " + decimalFormat.format(loc.getZ())); } }
package cc.ipotato.multithread; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class ThreadUseCallableTest { public static void main(String[] args) throws ExecutionException, InterruptedException { FutureTask<String> task = new FutureTask<String>(new ThreadUseCallable()); new Thread(task).start(); System.out.println(task.get()); } }
package model; import contract.IMove; /** * The Classe Spell * @author Victor Zimmermann */ public class Spell extends Entity implements IMove { /** The Direction of Spell. */ private int dirS; /** * Instantiates a new spell. * * @param x * the pos x * @param y * the pos y * @param id * the id */ public Spell(int x, int y, char id) { super(x, y, id); State=true; Image = "fireball_1.png"; } /** * Sets the next pos x,y. * * @param DirS * the next pos x,y */ public void move(int dirS){ switch (dirS){ case 1 : setX(getX()); setY(getY()-1); case 2 : setX(getX()+1); setY(getY()-1); case 3 : setX(getX()+1); setY(getY()); case 4 : setX(getX()+1); setY(getY()+1); case 5 : setX(getX()); setY(getY()+1); case 6 : setX(getX()-1); setY(getY()+1); case 7 : setX(getX()-1); setY(getY()); case 8 : setX(getX()-1); setY(getY()-1); } } /** * change dirS when the spell need it. * * @param dirS * the new dirS */ public void changedirS(){ switch(dirS){ case 1 : dirS=5; break; case 2 : dirS= 6; break; case 3 : dirS= 7; break; case 4 : dirS= 8; break; case 5 : dirS= 1; break; case 6 : dirS= 2; break; case 7 : dirS= 3; break; case 8 : dirS= 4; break; } } // GETTERS // SETTERS // /** * Gets the dirS. * * @return dirS */ public int getDirS() { return dirS; } /** * Sets the dirS. * * @param dirS * the new dirS */ public void setDirS(int dirS) { this.dirS = dirS; } public void setSprite(String Image) { // TODO Auto-generated method stub } }
package lab5; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class ContaTest { @Test void adicionaCompra() { } @Test void getDebito() { } @Test void getCliente() { } @Test void testToString() { } @Test void testHashCode() { } @Test void testEquals() { } }
package pl.artursienkowski.service.stock; import org.springframework.stereotype.Service; import pl.artursienkowski.model.Car; import pl.artursienkowski.model.Customer; import pl.artursienkowski.repository.CarRepository; import pl.artursienkowski.repository.CustomerRepository; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; @Service public class CarsStockService { private CarRepository carRepository; private CustomerRepository customerRepository; public CarsStockService(CarRepository carRepository, CustomerRepository customerRepository) { this.carRepository = carRepository; this.customerRepository = customerRepository; } public void carsStockQuantityUpdate () { List<Car> carList = carRepository.findAll(); for (Car car : carList) { List<Customer> quantityUpdate = new ArrayList<>(); List<Customer> customers = customerRepository.findCustomerByCarAndStatus(car, "SELL"); for(Customer c : customers) { if (car.getUpdateOn().isBefore(c.getUpdateOn())) { quantityUpdate.add(c); } } car.setQuantity(car.getQuantity() - quantityUpdate.size()); car.setUpdateOn(LocalDateTime.now()); carRepository.save(car); } } }
package com.houzhi.retrofitdemo.fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.houzhi.retrofitdemo.R; import com.houzhi.retrofitdemo.model.Args; import com.houzhi.retrofitdemo.model.HttpbinRequest; import butterknife.Bind; import butterknife.OnClick; import retrofit.Call; /** * @author houzhi */ public class ExampleBodyFragment extends BaseRequestExampleFragment { @Bind(R.id.et_value1) TextView etValue1; @Bind(R.id.et_value2) TextView etValue2; @Bind(R.id.et_value3) TextView etValue3; @OnClick(R.id.bt_request) void request() { Args args = new Args(); args.setArg1(etValue1.getText().toString()); args.setArg2(etValue2.getText().toString()); args.setArg3(etValue3.getText().toString()); Call<HttpbinRequest> call = httpbinService.postBody(args); processCall(call); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_example_body, container, false); return view; } }
/* TODO Реализуйте Калькулятор, который должен уметь выполнять математические операции (+, -, *, /, ^, %) над целыми положительными числами. Для проверки знака математической операции воспользуйтесь оператором switch(). Выведите на результат на экран Используйте ввод с клавиатуры (класс Scanner) Для продолжения/завершения работы программы выводите сообщение "Хотите продолжить? [да/нет]:". Если пользователь ввел ни "да" ни "нет", а что-то другое — снова выведите сообщение "Хотите продолжить? [да/нет]:". (Реализуйте эту логику в Test-классах) */ package com.lesson02.calculator; import java.util.Scanner; public class CalculatorTest { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Calculator myCalc = new Calculator(); String choice; do { System.out.print("Введите первое число (целое, положительное): "); int a = sc.nextInt(); System.out.print("Введите операцию из перечня (+, -, *, /, ^, %): "); //char operator = sc.next(); // не прокатило. разные типы. придется sc.next().charAt(0); // этого не было ни в видео, ни в ссылке на урок со Сканером char operator = sc.next().charAt(0); System.out.print("Введите второе число (целое, положительное): "); int b = sc.nextInt(); myCalc.calculate(a, operator, b); // Ввод кириллицей не понимает, поэтому вынужден запрашивать латинский ввод yes/no System.out.println("Хотите продолжить? [yes/no]: "); choice = sc.next(); while (!choice.equals("yes") && !choice.equals("no")) { System.out.println("!!!Ошибка при вводе!!! Попробуйте еще раз [yes/no]: "); choice = sc.next(); } } while (choice.equals("yes")); } }
import java.util.*; class Lucky_Substring { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int sum4 = 0, sum7 = 0; System.out.println("Enter string"); String str = sc.nextLine(); for(int i =0 ; i<str.length(); i++) { if(str.charAt(i)=='4') sum4++; if(str.charAt(i)=='7') sum7++; } if(sum4==0 && sum7==0) System.out.println(-1); else if(sum4>=sum7) System.out.println(4); else System.out.println(7); } }
package pl.weakpoint.library.controller; public interface ReservationRequestMapping { String RESERVATION_ROOT = "/reservation"; String GET_ALL = "/getAll.do"; }
package common.android; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import common.android.contentprovider.ContentProviderApi; public class BootReceiver extends BroadcastReceiver { private static final String TAG = BootReceiver.class.getSimpleName() + "------"; @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "BootReceiver starting ..."); try { if(ContentProviderApi.getBooleanConf(context.getContentResolver(), ConfKeyList.EnableLocationReport.name(), false)) { GenericApplication.startLocationReportService(context); } } catch (Exception e) { Log.e(this.getClass().getName(), "", e); } try { GenericApplication.startNotificationPollerService(context); } catch (Exception e) { Log.e(this.getClass().getName(), "", e); } try { GenericApplication.startLogSenderService(context); } catch (Exception e) { Log.e(this.getClass().getName(), "", e); } try { GenericApplication.setupWidgetUpdateTimer(context); } catch (Exception e) { Log.e(this.getClass().getName(), "", e); } } }
/* * Created on Mar 1, 2007 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.citibank.ods.entity.pl.valueobject; import java.util.Date; /** * @author fernando.salgado * * Tabela Historica de Agrupador de Produtos Private */ public class TplAggrProdPrvtHistEntityVO extends BaseTplAggrProdPrvtEntityVO { /** * Data de Referencia do registro no historico */ private Date m_prvtProdAggrRefDate; /** * @return Returns the prvtProdAggrRefDate. */ public Date getPrvtProdAggrRefDate() { return m_prvtProdAggrRefDate; } /** * @param prvtProdAggrRefDate_ The prvtProdAggrRefDate to set. */ public void setPrvtProdAggrRefDate( Date prvtProdAggrRefDate_ ) { m_prvtProdAggrRefDate = prvtProdAggrRefDate_; } }
package com.example.spacepictures.retrofit; import com.example.spacepictures.pojo.Object; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; public interface RetrofitInterface { @GET("apod?api_key=L4juwY6U70NI1errn1qV0OTkPwWMzwPNj2cVHFw4&thumbs=false") Call<List<Object>> someResponse(@Query("count") Integer count); }
package f.star.iota.milk.ui.girlsky.girl; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import java.util.ArrayList; import java.util.List; import f.star.iota.milk.Menus; import f.star.iota.milk.Net; import f.star.iota.milk.base.PagerFragment; import f.star.iota.milk.base.TitlePagerAdapter; public class GirlSkyPagerFragment extends PagerFragment { @Override protected TitlePagerAdapter getPagerAdapter() { List<String> titles = new ArrayList<>(); titles.add("美女图片"); titles.add("性感美女"); titles.add("丝袜美女"); titles.add("外国美女"); titles.add("街拍美女"); titles.add("自拍美女"); titles.add("美女写真"); titles.add("古装美女"); titles.add("人体艺术"); List<Fragment> fragments = new ArrayList<>(); fragments.add(GirlSkyFragment.newInstance(Net.GIRLSKY_MNTP)); fragments.add(GirlSkyFragment.newInstance(Net.GIRLSKY_XGMN)); fragments.add(GirlSkyFragment.newInstance(Net.GIRLSKY_SWMN)); fragments.add(GirlSkyFragment.newInstance(Net.GIRLSKY_WGMN)); fragments.add(GirlSkyFragment.newInstance(Net.GIRLSKY_JPMN)); fragments.add(GirlSkyFragment.newInstance(Net.GIRLSKY_ZPMN)); fragments.add(GirlSkyFragment.newInstance(Net.GIRLSKY_MNXZ)); fragments.add(GirlSkyFragment.newInstance(Net.GIRLSKY_GZMN)); fragments.add(GirlSkyFragment.newInstance(Net.GIRLSKY_RTYS)); return new TitlePagerAdapter(getChildFragmentManager(), fragments, titles); } @Override protected int setTabMode() { return TabLayout.MODE_SCROLLABLE; } @Override public int getFragmentMenuID() { return Menus.MENU_GIRLSKY_ID; } }
package com.sirma.itt.javacourse.networkingAndGui.task3.serverClientTalk.client; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; import com.sirma.itt.javacourse.networkingAndGui.task3.serverClientTalk.server.DateServer; /** * User interface for the {@link DateServer} client {@link DateClient}. * * @author Simeon Iliev */ public class DateClientGui extends JFrame { private static final long serialVersionUID = 3497964934272245742L; private JTextArea messageWingow; private DateClient client; private JButton connectButton; /** * Start the window frame and opens the connection to the server. */ public DateClientGui() { setUp(); } /** * Sets up the window elements. */ private void setUp() { JFrame mainWindow = this; messageWingow = new JTextArea(); connectButton = new JButton("Connect"); messageWingow.setEditable(false); JPanel labelPanel = new JPanel(); labelPanel.setPreferredSize(new Dimension(300, 30)); labelPanel.add(connectButton); mainWindow.setLayout(new BorderLayout()); mainWindow.setTitle("Date Client"); mainWindow.add(labelPanel, BorderLayout.NORTH); mainWindow.add(messageWingow); mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainWindow.setSize(300, 200); mainWindow.setVisible(true); connectButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { startConnection(); } }); } /** * Opens the connection to the server and extracts the message data and * closes the connection. */ private void startConnection() { client = new DateClient(messageWingow); client.start(); } }
package kr.or.ddit.member.main; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import kr.or.ddit.member.service.IMemberService; import kr.or.ddit.member.service.MemberServiceImpl; import kr.or.ddit.member.vo.MemberVO; import org.apache.log4j.Logger; import com.ibatis.sqlmap.client.SqlMapClient; /* * 이 클래스는 Controller역할과 View역할을 같이 한다. */ public class MemberInfoMain { private static Logger logger = Logger.getLogger(MemberInfoMain.class); private IMemberService service; //service 객체가 저장될 변수 선언 private Scanner scan =new Scanner(System.in); //생성자 public MemberInfoMain() { //service = new MemberServiceImpl(); //service 객체 생성 service = MemberServiceImpl.getInstance(); //service 객체 생성 } public static void main(String[] args) { new MemberInfoMain().memberStart(); } public int displayMenu(){ logger.info("전체출력메세지 기록 "); System.out.println("--------------------------------"); System.out.println("\t==작업 선택 =="); System.out.println("\t1.자료 입력 "); System.out.println("\t2.자료 삭제 "); System.out.println("\t3.자료 수정 "); System.out.println("\t4.자료 수정2 "); System.out.println("\t5.자료 검색 "); System.out.println("\t6.전체 자료 출력 "); System.out.println("\t0.작업 끝 "); System.out.println("-------------------------------"); System.out.print("작업선택>> "); int num=Integer.parseInt(scan.nextLine()); return num; } public void memberStart(){ logger.info("전체출력에서 선택값"); while(true){ int choice=displayMenu(); logger.info("전체출력에서 선택값"); switch(choice){ case 1 : //입력 (추가) memberInsert(); break; case 2 : //삭제 memberDelete(); break; case 3 : //수정 memberUpdate(); break; case 4 : //수정2 memberUpdate2(); break; case 5 : //검색 memberSearch(); break; case 6 : //전체자료 출력 displayMember(); break; case 0 : System.out.println("작업을 종료합니다."); return; default : System.out.println("작업 선택이 잘못되었습니다."); System.out.println("다시입력하세요"); } } } //회원 정보를 검색하는 메서드 public void memberSearch(){ logger.info("자료 검색"); // 검색할 필드를 보여주고 사용자가 선택하게 한다음 // 검색할 내용을 입력 받아서 // 사용자가 선택한 필드에 입력받은 내용이 포함되는 모든 자료를 출력한다. //Map의 구조 // key value // field 검색할 컬럼명 // search 검색할 내용 System.out.println(); logger.info("회원(자료) 상세 검색 "); String fieldName = ""; String searchData = ""; System.out.println(); System.out.println("검색할 정보를 입력하세요."); System.out.println("1.회원번호 2.회원이름 3.전화번호 4.주소"); System.out.println("------------------------------"); System.out.print(" 항목 선택 >>"); logger.info("회원(자료)상세검색 선택"); int num = scan.nextInt(); switch(num){ case 1 : fieldName = "mem_id"; break; case 2 : fieldName = "mem_name"; break; case 3 : fieldName = "mem_tel"; break; case 4 : fieldName = "mem_addr"; break; default: System.out.println("검색할 데이터를 잘못 선택했습니다."); System.out.println("검색작업을 마칩니다."); return; } scan.nextLine(); // 버퍼 비우기 nextLine을 사용하기 전에 nextInt ,nextFlot 등이 있으면 버퍼비우기를 해주어야 한다. System.out.println(); System.out.print("검색할 내용>>"); searchData = scan.nextLine(); Map<String, String> searchMap = new HashMap<>(); searchMap.put("field", fieldName); searchMap.put("search", searchData); List<MemberVO> memList = service.getSearchMember(searchMap); System.out.println(); System.out.println("--------------------------------"); System.out.println(" ID 이름 전화번호 주소"); System.out.println("--------------------------------"); if(memList == null ||memList.size()==0){ System.out.println("출력할 데이터가 없습니다."); }else{ for(MemberVO memVO : memList){ //List 개수만큼 반복 //반복문에서 각각의 MemberVO에 저장된 데이터를 출력한다. String memId=memVO.getMem_id(); String memName=memVO.getMem_name(); String memTel=memVO.getMem_tel(); String memAddr=memVO.getMem_addr(); System.out.println(" " + memId +" "+memName+" "+memTel+" "+memAddr); } } System.out.println("-------------------------------"); System.out.println("출력끝"); } // 회원 정보를 수정하는 메서드2 public void memberUpdate2(){ System.out.println(); System.out.println("수정할 회원 정보를 입력하세요."); System.out.print("수정할 회원ID >> "); String memId = scan.nextLine(); int count = service.getMemberCount(memId); if(count==0){ System.out.println(memId + "은 없는 회원ID입니다. 수정작업을 종료합니다."); return; } int num = 0; // 선택한 항목 번호가 저장될 변수 String selField = ""; // 선택한 항목의 컬럼명이 저장될 변수 String msg = ""; do{ System.out.println(); System.out.println("수정할 항목을 선택하세요"); System.out.println(" 1.회원이름 2.전화번호 3.주소 "); System.out.println("---------------------------"); System.out.print(" 항목선택 >> "); num = Integer.parseInt(scan.nextLine()); switch(num){ case 1 : selField = "mem_name"; msg = "새로운 회원 이름"; break; case 2 : selField = "mem_tel"; msg = "새로운 전화번호"; break; case 3 : selField = "mem_addr"; msg = "새로운 주소"; break; default : System.out.println("항목선택을 잘못했습니다. 다시 선택하세요"); } }while(num<1 || num>3); System.out.print(msg + " >> "); String data = ""; if(selField.equals("mem_addr")){ //scan.nextLine(); // 버퍼 비우기 data = scan.nextLine(); }else{ data = scan.nextLine(); } // 매개변수로 사용할 Map객체 생성 // 매개변수 paramMap의 구조 // key value // field 수정할 필드명 // data 수정할 값 // memId 수정할 회원ID Map<String, String> paramMap = new HashMap<>(); paramMap.put("field", selField); paramMap.put("data", data); paramMap.put("memId", memId); int cnt = service.updateMember(paramMap); if(cnt>0){ System.out.println(memId + "회원의 " + selField + " 정보가 수정되었습니다."); }else{ System.out.println("수정 작업 실패"); } } //회원정보를 수정하는 메서드 public void memberUpdate(){ System.out.println(); System.out.println("수정할 회원 정보를 입력하세요"); System.out.println("수정할 회원ID >> "); String memId=scan.nextLine(); int count = service.getMemberCount(memId); if(count==0){ System.out.print(memId + "은 없는 회원ID입니다. 수정작업을 종료합니다."); return; } System.out.print("새로운 회원이름 >>"); String memName=scan.nextLine(); System.out.print("새로운 회원전화번호 >>"); String memTel=scan.nextLine(); //scan.nextLine(); //버퍼비우기 System.out.print("새로운 회원주소 >>"); String memAddr=scan.nextLine(); MemberVO memVO = new MemberVO(); memVO.setMem_id(memId); memVO.setMem_name(memName); memVO.setMem_tel(memTel); memVO.setMem_addr(memAddr); int cnt=service.updateMember(memVO); if(cnt>0){ System.out.println(memId+ "회원의 정보가 수정되었습니다."); }else{ System.out.println("수정작업실패"); } } //회원 정보를 삭제하는 메서드 public void memberDelete(){ System.out.println(); System.out.println("삭제할 회원 정보를 입력하세요"); System.out.println("삭제할 회원ID"); String memId=scan.next(); int count=service.getMemberCount(memId); if(count==0){ System.out.println(memId + "는 없는 회원ID입니다."); return; } int cnt = service.deleteMember(memId); if(cnt>0){ System.out.println(memId + "회원의 정보가 삭제되었습니다."); }else{ System.out.println("삭제 작업 실패!!"); } } //새로운 회원 정보를 추가하는 메서드 public void memberInsert(){ System.out.println(); System.out.println("추가할 회원 정보를 입력하세요"); System.out.println("회원ID >> "); String memId = scan.nextLine(); int count = service.getMemberCount(memId); if(count>0){ System.out.println(memId+"는 이미 가입된 회원ID입니다."); //System.out.println("다른 ID로 다시 입력하세요 "); return; } System.out.println("회원이름 >> "); String memName=scan.nextLine(); System.out.println("회원전화번호 >> "); String memTel=scan.nextLine(); //scan.nextLine(); //입력 버퍼 비우기 System.out.println("회원주소 >> "); String memAddr=scan.nextLine(); MemberVO memVO = new MemberVO(); //입력한 추가할 데이터를 저장할 MemberVO 객체 생성 //setter를 이용해서 입력한 값들을 vo 객체에 저장한다. memVO.setMem_id(memId); memVO.setMem_name(memName); memVO.setMem_tel(memTel); memVO.setMem_addr(memAddr); //vo객체를 이용해서 추가해주는 service 객체 쪽의 메서드를 호출한다. int cnt = service.insertMember(memVO); if(cnt>0){ System.out.println(memId + "회원이 추가 되었습니다."); }else { System.out.println("추가 작업 실패 ㅜㅜ"); } } //회원 전체 자료를 출력하는 메서드 public void displayMember(){ //service에 있는 getAllMember()메서드를 호출해서 전체 회원정보를 가져온다. List <MemberVO> memList = service.getAllMember(); System.out.println(); System.out.println("--------------------------------"); System.out.println(" ID 이름 전화번호 주소"); System.out.println("--------------------------------"); for(MemberVO memVO : memList){ //List 개수만큼 반복 //반복문에서 각각의 MemberVO에 저장된 데이터를 출력한다. String memId=memVO.getMem_id(); String memName=memVO.getMem_name(); String memTel=memVO.getMem_tel(); String memAddr=memVO.getMem_addr(); System.out.println(" " + memId +" "+memName+" "+memTel+" "+memAddr); } System.out.println("-------------------------------"); System.out.println("출력끝"); } }
package view; import model.FileLetterLezer; import model.HoofdletterDecorator; import model.LetterLezer; import model.SpatieToevoegenDecorator; public class FileLetterLezerLauncher { public static void main(String[] args) { LetterLezer fl = new FileLetterLezer("letters.txt"); fl = new HoofdletterDecorator(fl); fl = new SpatieToevoegenDecorator(fl); char letter = fl.leesLetter(); while (letter != '*') { System.out.print(letter); letter = fl.leesLetter(); } } }
package com.company; public class ImageMap { int[][] kep;//értéke a szín ImageMap(int x_meret,int y_meret) { kep = new int[x_meret][y_meret]; } public void setRGB(int x, int y, int c) { kep[x][y] = c; } public int getRGB(int x, int y) { return kep[x][y]; } }
package com.esum.router; import org.apache.commons.lang.StringUtils; import com.esum.framework.common.util.ClassUtil; import com.esum.framework.common.util.DateUtil; import com.esum.framework.core.component.ComponentManager; import com.esum.framework.core.component.ComponentManagerFactory; import com.esum.framework.core.component.mbean.Component; import com.esum.framework.core.config.Configurator; import com.esum.framework.core.exception.FrameworkException; import com.esum.framework.core.h2db.H2DBServer; import com.esum.framework.core.management.ManagementException; import com.esum.framework.core.management.manager.XTrusManager; import com.esum.framework.core.route.ShutdownListener; import com.esum.framework.net.queue.HornetQServer; /** * xTrus Shutdown Listener. */ public class RouterShutdownListener extends Thread { private String traceId = ""; private Component main; public RouterShutdownListener(Component main){ this.traceId = "[ROUTER] "; this.main = main; } public void run() { System.out.println("===================================================================="); traceId = traceId + "["+DateUtil.getCYMDHMSS()+"] "; String shutdownClass = null; try { shutdownClass = Configurator.getInstance().getString("shutdown.listener.class", null); } catch (FrameworkException e) { } if(StringUtils.isNotEmpty(shutdownClass)) { System.out.println(traceId+"Calling Shutdown Listener class."); ShutdownListener listener = null; try { listener = (ShutdownListener)ClassUtil.forName(shutdownClass).newInstance(); listener.shutdown(); if(this.main!=null) this.main.shutdown(); } catch (Exception e) { System.out.println(traceId+"Can not processing shutdown listener class."); e.printStackTrace(); } } try { H2DBServer.getInstance().stopServer(); } catch (Exception e) { System.out.println("H2DB Server shutdown failed."); e.printStackTrace(); } ComponentManager cm = null; try { cm = ComponentManagerFactory.currentComponentManager(); if(cm.isMainNodeType()) { try { HornetQServer.getInstance().stop(); } catch (Exception e) { System.out.println("HornetQ Server shutdown failed."); e.printStackTrace(); } } } catch (Exception e){ e.printStackTrace(); } try { XTrusManager.getInstance().shutdown(); } catch (ManagementException e) { System.out.println("xTrus Manager shutdown failed."); e.printStackTrace(); } System.out.println(traceId+"xTrus Engine shutdowned."); System.out.println("===================================================================="); } }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class csv { private String fileName; private Double val; protected ArrayList<ArrayList<Double>> recoverLog; protected ArrayList<ArrayList<Double>> readLog; private BufferedReader br; private String line; public csv(String fileName) throws IOException { this.fileName = fileName; File f = new File(fileName); if(!f.exists()) { FileWriter fw = new FileWriter(fileName,false); fw.write("Deposit 0.0"); fw.close(); } } protected ArrayList<ArrayList<Double>> readLog() { recoverLog = new ArrayList<ArrayList<Double>>(); try { br = new BufferedReader(new FileReader(fileName)); while ((line = br.readLine()) != null) { String[] contents = line.split(" "); ArrayList<Double> tempList = new ArrayList<Double>(); if (contents[0].compareTo("Deposit") == 0) { String[] deposits = contents[1].split(","); for(int i=0;i<deposits.length;++i) { tempList.add(Double.valueOf(deposits[i])); } recoverLog.add(tempList); } else { val = Double.valueOf(contents[1]); val = -val; tempList.add(val); recoverLog.add(tempList); } } return recoverLog; } catch (IOException e) { e.printStackTrace(); return null; } } protected void printLog() { readLog = new ArrayList<ArrayList<Double>> (); try { br = new BufferedReader(new FileReader(fileName)); while((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } protected void generateLog(ArrayList <ArrayList<Double>> log) { try { FileWriter fw = new FileWriter(fileName,false); StringBuilder file = new StringBuilder(); for (int i = 0; i < log.size(); ++i) { String temp=""; val = (double) 0; for(int j = 0; j<log.get(i).size();++j) { val = val + log.get(i).get(j); temp+= String.valueOf(Math.abs(log.get(i).get(j)))+","; } temp=temp.substring(0,temp.length()-2); if (val >= 0) { file.append("Deposit "+temp); } else { file.append("Withdraw "+temp); } file.append("\r\n"); } fw.write(file.toString()); fw.flush(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } }
package com.gxtc.huchuan.ui.live.intro; import android.app.Activity; import android.text.TextUtils; import com.alibaba.fastjson.JSONObject; import com.gxtc.commlibrary.utils.ErrorCodeUtil; import com.gxtc.commlibrary.utils.GotoUtil; import com.gxtc.huchuan.Constant; import com.gxtc.huchuan.bean.ChatInFoStatusBean; import com.gxtc.huchuan.bean.ChatInfosBean; import com.gxtc.huchuan.bean.pay.OrdersRequestBean; import com.gxtc.huchuan.bean.pay.OrdersResultBean; import com.gxtc.huchuan.data.UserManager; import com.gxtc.huchuan.data.deal.DealRepository; import com.gxtc.huchuan.data.deal.DealSource; import com.gxtc.huchuan.helper.RxTaskHelper; import com.gxtc.huchuan.http.ApiCallBack; import com.gxtc.huchuan.http.ApiObserver; import com.gxtc.huchuan.http.ApiResponseBean; import com.gxtc.huchuan.http.service.LiveApi; import com.gxtc.huchuan.http.service.PayApi; import com.gxtc.huchuan.ui.pay.PayActivity; import java.math.BigDecimal; import java.util.HashMap; import rx.Observable; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * 来自 伍玉南 的装逼小尾巴 on 17/12/8. */ public class LiveIntroPresenter implements LiveIntroContract.Presenter { private LiveIntroContract.View mView; private DealSource dealData; public LiveIntroPresenter(LiveIntroContract.View view) { mView = view; mView.setPresenter(this); dealData = new DealRepository(); } @Override public void getData(String id) { mView.showLoad(); String token = null; if (UserManager.getInstance().isLogin()) { token = UserManager.getInstance().getToken(); } HashMap<String, String> map = new HashMap<>(); if(!TextUtils.isEmpty(token)) map.put("token", token); map.put("chatInfoId", id); Observable<ApiResponseBean<ChatInfosBean>> infoObs = LiveApi.getInstance().getChatInfosBean(token, id); //获取课程信息 Observable<ApiResponseBean<ChatInFoStatusBean>> statusObs = LiveApi.getInstance().getChatInfoStatus(map); //获取用户在课程中的状态信息等 //获取课堂的禁言状态 Subscription sub = Observable.concat(infoObs,statusObs) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new ApiObserver<ApiResponseBean<?>>(new ApiCallBack() { @Override public void onSuccess(Object data) { if(mView == null) return; if(data instanceof ChatInfosBean){ mView.showLoadFinish(); mView.showChatInfoData((ChatInfosBean) data); } if(data instanceof ChatInFoStatusBean){ mView.showChatInFoStatusBean((ChatInFoStatusBean) data); } } @Override public void onError(String errorCode, String message) { if(mView == null) return; mView.showLoadFinish(); if(!String.valueOf(ErrorCodeUtil.NO_TOKEN_10002).equals(errorCode)){ mView.showError(message); } } @Override public void onCompleted() { } })); RxTaskHelper.getInstance().addTask(this,sub); } @Override public void collect(String classId) { mView.showLoad(); HashMap<String, String> map = new HashMap<>(); map.put("token", UserManager.getInstance().getToken()); map.put("bizType", "2"); map.put("bizId", classId); dealData.saveCollect(map, new ApiCallBack<Object>() { @Override public void onSuccess(Object data) { if(mView == null) return; mView.showLoadFinish(); mView.showCollectResult(); } @Override public void onError(String errorCode, String message) { if(mView == null) return; mView.showLoadFinish(); mView.showError(message); } }); } @Override public void follow(String id) { mView.showLoad(); Subscription sub = LiveApi.getInstance() .setUserFollow(UserManager.getInstance().getToken(), "2", id) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( new ApiObserver<ApiResponseBean<Void>>(new ApiCallBack() { @Override public void onSuccess(Object data) { if(mView != null){ mView.showLoadFinish(); mView.showFollowSuccess(); } } @Override public void onError(String errorCode, String message) { if(mView != null){ mView.showLoadFinish(); mView.showError(message); } } })); RxTaskHelper.getInstance().addTask(this,sub); } //报名系列课 @Override public void enrollSeries(Activity activity, ChatInfosBean bean, String shareUserCode, String freeSign) { String token = UserManager.getInstance().getToken(); String seriesId = bean.getChatSeries(); //圈内成员免费报名 if("1".equals(bean.getJoinGroup())){ mView.showLoad(); Subscription sub = LiveApi.getInstance() .saveFreeChatSeriesBuy(token, seriesId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new ApiObserver<ApiResponseBean<Void>>(new ApiCallBack<Void>() { @Override public void onSuccess(Void data) { if(mView != null){ mView.showLoadFinish(); mView.showEnrollSeriesSuccess(); } } @Override public void onError(String errorCode, String message) { if(mView != null){ mView.showLoadFinish(); mView.showError(message); } } })); RxTaskHelper.getInstance().addTask(this, sub); return; } //免费邀请 if(!TextUtils.isEmpty(shareUserCode) && !TextUtils.isEmpty(freeSign)){ freeInviteJoinSeries(seriesId, shareUserCode, freeSign); return; } //普通的购买 double fee = 0; try { fee = Double.valueOf(bean.getFee()); }catch (Exception e){ fee = 0; } BigDecimal moneyB = new BigDecimal(fee); //计算总价 double total = moneyB.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100; JSONObject jsonObject = new JSONObject(); jsonObject.put("chatSeriesId", seriesId); if (!TextUtils.isEmpty(shareUserCode)) { jsonObject.put("userCode", shareUserCode); jsonObject.put("joinType", 0); jsonObject.put("type", 1); } String extra = jsonObject.toJSONString(); OrdersRequestBean requestBean = new OrdersRequestBean(); requestBean.setToken(UserManager.getInstance().getToken()); requestBean.setTransType("CS"); requestBean.setTotalPrice(total + ""); requestBean.setExtra(extra); requestBean.setGoodsName("系列课购买"); if (fee == 0) { mView.showLoad(); requestBean.setPayType("ALIPAY"); HashMap<String, String> map = new HashMap<>(); map.put("token", requestBean.getToken()); map.put("transType", requestBean.getTransType()); map.put("payType", requestBean.getPayType()); map.put("totalPrice", requestBean.getTotalPrice()); map.put("extra", requestBean.getExtra()); Subscription sub = PayApi.getInstance().getOrder(map).subscribeOn( Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe( new ApiObserver<ApiResponseBean<OrdersResultBean>>( new ApiCallBack<OrdersResultBean>() { @Override public void onSuccess(OrdersResultBean data) { if (mView != null) { mView.showLoadFinish(); mView.showEnrollSeriesSuccess(); } } @Override public void onError(String errorCode, String message) { if (mView != null) { mView.showLoadFinish(); mView.showError(message); } } })); RxTaskHelper.getInstance().addTask(this, sub); } else { GotoUtil.goToActivity(activity, PayActivity.class, Constant.INTENT_PAY_RESULT, requestBean); } } //报名课堂 @Override public void enrollClassroom(String id, String joinGroup, String shareUserCode) { if (UserManager.getInstance().isLogin()) { //这里不走支付接口 if(TextUtils.isEmpty(shareUserCode) || "1".equals(joinGroup)){ freeEnroll(id); //这里走支付接口 要生成订单 }else{ freeEnrollByPay(id, shareUserCode); } } else { mView.tokenOverdue(); } } @Override public void payEnrollClassroom(Activity activity, ChatInfosBean bean, String shareUserCode, String freeSign) { if (!UserManager.getInstance().isLogin()) { mView.tokenOverdue(); return; } //圈内成员 免费入场 if(bean != null && "1".equals(bean.getJoinGroup())){ enrollClassroom(bean.getId(), bean.getJoinGroup(), null); return; } String fee = bean.getFee(); String chatRoomName = bean.getChatRoomName(); double money = 0; try { money = Double.valueOf(bean.getFee()); }catch (Exception e){ e.printStackTrace(); } //课程收费,跳去支付界面 if(TextUtils.isEmpty(shareUserCode) && money != 0){ BigDecimal moneyB = new BigDecimal(fee); double total = moneyB.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100; JSONObject jsonObject = new JSONObject(); jsonObject.put("chatInfoId", bean.getId()); String extra = jsonObject.toJSONString(); OrdersRequestBean requestBean = new OrdersRequestBean(); requestBean.setToken(UserManager.getInstance().getToken()); requestBean.setTransType("CI"); requestBean.setTotalPrice(total + ""); requestBean.setExtra(extra); requestBean.setGoodsName("课堂收费-" + chatRoomName); GotoUtil.goToActivity(activity, PayActivity.class, Constant.INTENT_PAY_RESULT, requestBean); //课程免费而且不是别人分享的 }else if( TextUtils.isEmpty(shareUserCode) && money == 0){ freeEnrollByPay(bean.getId(), null); //免费邀请进入课堂的 } else if(!TextUtils.isEmpty(freeSign) && !TextUtils.isEmpty(shareUserCode)) { freeInviteJoin(bean.getId(), shareUserCode, freeSign); //这里是走分销流程的 } else { OrdersRequestBean requestBean = new OrdersRequestBean(); BigDecimal moneyB = new BigDecimal(fee); double total = moneyB.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100; if(total == 0){ freeEnrollByPay(bean.getId(), null); }else{ String token = UserManager.getInstance().getToken(); String transType = "CI"; String extra = "{\"chatInfoId\":\"" + bean.getId() + "\",\"userCode\":\"" + shareUserCode + "\",\"joinType\":0,\"type\":1}"; requestBean.setTotalPrice(total + ""); requestBean.setToken(token); requestBean.setTransType(transType); requestBean.setExtra(extra); requestBean.setGoodsName("课堂收费-" + chatRoomName); GotoUtil.goToActivity(activity, PayActivity.class, 0, requestBean); } } } //免费报名,不走支付接口 @Override public void freeEnroll(String id) { mView.showLoad(); Subscription sub = LiveApi.getInstance() .saveChatSignup(UserManager.getInstance().getToken(), id) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new ApiObserver<ApiResponseBean<Void>>(new ApiCallBack<Void>() { @Override public void onSuccess(Void data) { if(mView == null) return; mView.showLoadFinish(); mView.showEnrollSuccess(); } @Override public void onError(String errorCode, String message) { if(mView == null) return; mView.showLoadFinish(); mView.showError(message); } })); RxTaskHelper.getInstance().addTask(this,sub); } //免费报名,走支付接口 @Override public void freeEnrollByPay(String id, String shareUserCode) { mView.showLoad(); JSONObject jObject = new JSONObject(); jObject.put("chatInfoId", id); jObject.put("joinType", 0); jObject.put("type", 1); if(!TextUtils.isEmpty(shareUserCode)){ jObject.put("userCode", shareUserCode); } String token = UserManager.getInstance().getToken(); String transType = "CI"; String payType = "WX"; String extra = jObject.toJSONString(); double total = 0; HashMap<String,String> map = new HashMap<>(); map.put("token",token); map.put("transType",transType); map.put("payType",payType); map.put("totalPrice",total + ""); map.put("extra",extra); Subscription sub = PayApi.getInstance() .getOrder(map) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new ApiObserver<ApiResponseBean<OrdersResultBean>>(new ApiCallBack() { @Override public void onSuccess(Object data) { if(mView == null) return; mView.showLoadFinish(); mView.showEnrollSuccess(); } @Override public void onError(String errorCode, String message) { if(mView == null) return; mView.showLoadFinish(); mView.showError(message); } })); RxTaskHelper.getInstance().addTask(this,sub); } //免费邀请加入课堂 @Override public void freeInviteJoin(String id, String shareUserCode, String freeSign) { mView.showLoad(); String token = UserManager.getInstance().getToken(); String transType = "CI"; String payType = "WX"; String totalPrice = "0"; JSONObject jobj = new JSONObject(); jobj.put("chatInfoId", id); jobj.put("freeSign", freeSign); jobj.put("userCode", shareUserCode); jobj.put("joinType", 3); String extra = jobj.toString(); HashMap<String,String> map = new HashMap<>(); map.put("token",token); map.put("transType",transType); map.put("payType",payType); map.put("totalPrice",totalPrice); map.put("extra",extra); Subscription sub = PayApi.getInstance() .getOrder(map) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new ApiObserver<ApiResponseBean<OrdersResultBean>>(new ApiCallBack() { @Override public void onSuccess(Object data) { if(mView == null) return; mView.showLoadFinish(); mView.showEnrollSuccess(); } @Override public void onError(String errorCode, String message) { if(mView != null){ mView.showLoadFinish(); mView.showError(message); } } })); RxTaskHelper.getInstance().addTask(this,sub); } //免费邀请系列课 private void freeInviteJoinSeries(String id, String shareUserCode, String freeSign){ mView.showLoad(); String token = UserManager.getInstance().getToken(); String transType = "CS"; String payType = "WX"; String totalPrice = "0"; JSONObject jobj = new JSONObject(); jobj.put("chatSeriesId", id); jobj.put("freeSign", freeSign); jobj.put("userCode", shareUserCode); jobj.put("joinType", 4); String extra = jobj.toString(); HashMap<String,String> map = new HashMap<>(); map.put("token",token); map.put("transType",transType); map.put("payType",payType); map.put("totalPrice",totalPrice); map.put("extra",extra); Subscription sub = PayApi.getInstance() .getOrder(map) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new ApiObserver<ApiResponseBean<OrdersResultBean>>(new ApiCallBack() { @Override public void onSuccess(Object data) { if (mView != null) { mView.showLoadFinish(); mView.showEnrollSeriesSuccess(); } } @Override public void onError(String errorCode, String message) { if(mView != null){ mView.showLoadFinish(); mView.showError(message); } } })); RxTaskHelper.getInstance().addTask(this,sub); } @Override public void start() { } @Override public void destroy() { mView = null; dealData.destroy(); RxTaskHelper.getInstance().cancelTask(this); } }
package com.oa.file.form; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.TableGenerator; import com.oa.user.form.UserInfo; @Entity @Table(name="file_cabinets") public class FileCabinets { @Id @GeneratedValue(strategy= GenerationType.TABLE,generator="ud") @TableGenerator(name = "ud", table = "hibernate_table", pkColumnName = "gen_pk", pkColumnValue = "1", valueColumnName = "gen_val", initialValue = 1, allocationSize = 1) @Column(name = "fileId") private int fileId; @Id @ManyToOne(fetch = FetchType.LAZY, cascade = { CascadeType.ALL }) @JoinColumn(name = "userId", referencedColumnName = "USER_ID") private UserInfo userInfo; @Column(name = "fullName") private String fullName; @Column(name = "extensionName") private String extensionName; @Column(name = "file_size") private int fileSize; @Column(name = "file_path") private String filePath; @ManyToOne(fetch = FetchType.LAZY, cascade = { CascadeType.ALL }) @JoinColumn(name = "file_type") private FileCabinetsType fileCabinetsType; public int getFileId() { return fileId; } public void setFileId(int fileId) { this.fileId = fileId; } public UserInfo getUserInfo() { return userInfo; } public void setUserInfo(UserInfo userInfo) { this.userInfo = userInfo; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getExtensionName() { return extensionName; } public void setExtensionName(String extensionName) { this.extensionName = extensionName; } public int getFileSize() { return fileSize; } public void setFileSize(int fileSize) { this.fileSize = fileSize; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public FileCabinetsType getFileCabinetsType() { return fileCabinetsType; } public void setFileCabinetsType(FileCabinetsType fileCabinetsType) { this.fileCabinetsType = fileCabinetsType; } }
package ALIXAR.U8_XML.U8_T3_USO_DE_STAX; public class Cachimba { private int id; private String nombre; private String marca; private String gama; private int ano_lanzamiento; public Cachimba(String nombre, String marca, String gama, int ano_lanzamiento, int id) { this.id = id; this.nombre = nombre; this.marca = marca; this.gama = gama; this.ano_lanzamiento = ano_lanzamiento; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getMarca() { return marca; } public void setMarca(String marca) { this.marca = marca; } public String getGama() { return gama; } public void setGama(String gama) { this.gama = gama; } public int getAno_lanzamiento() { return ano_lanzamiento; } public void setAno_lanzamiento(int ano_lanzamiento) { this.ano_lanzamiento = ano_lanzamiento; } }
package com.shwetansh.covid_19tracker; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.leo.simplearcloader.SimpleArcLoader; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.DateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class Vaccinated extends AppCompatActivity { EditText search; ListView listView; SimpleArcLoader simpleArcLoader; public static List<ModelVaccinated> modelVaccinatedList=new ArrayList<>(); ModelVaccinated modelVaccinated; MySecondAdapter mySecondAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_vaccinated); search=findViewById(R.id.edtVaccinatedSearch); listView=findViewById(R.id.listViewVaccinated); simpleArcLoader=findViewById(R.id.vacloader); getSupportActionBar().setTitle("Vaccinated Population"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); fetchData(); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { startActivity(new Intent(getApplicationContext(),Detail_Activity2.class).putExtra("position",i)); } }); search.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { mySecondAdapter.getFilter().filter(charSequence); mySecondAdapter.notifyDataSetChanged(); } @Override public void afterTextChanged(Editable editable) { } }); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if(item.getItemId()==android.R.id.home) { mySecondAdapter.clearData(); mySecondAdapter.notifyDataSetChanged(); finish(); } return super.onOptionsItemSelected(item); } private void fetchData() { String url= "https://disease.sh/v3/covid-19/vaccine/coverage/countries?lastdays"; simpleArcLoader.start(); StringRequest request= new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { try{ JSONArray jsonArray=new JSONArray(response); for (int i=0;i<jsonArray.length();i++){ JSONObject jsonObject=jsonArray.getJSONObject(i); String countryName=jsonObject.getString("country"); JSONObject object=jsonObject.getJSONObject("timeline"); String timeline=object.getString("7/24/21"); modelVaccinated =new ModelVaccinated(countryName,timeline); modelVaccinatedList.add(modelVaccinated); } mySecondAdapter=new MySecondAdapter(Vaccinated.this,modelVaccinatedList); listView.setAdapter(mySecondAdapter); simpleArcLoader.stop(); simpleArcLoader.setVisibility(View.GONE); }catch (JSONException e){ e.printStackTrace(); simpleArcLoader.stop(); simpleArcLoader.setVisibility(View.GONE); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { simpleArcLoader.stop(); simpleArcLoader.setVisibility(View.GONE); Toast.makeText(Vaccinated.this,error.getMessage(),Toast.LENGTH_SHORT).show(); } }); RequestQueue requestQueue= Volley.newRequestQueue(this); requestQueue.add(request); } }
import java.util.LinkedList; import java.util.Queue; /** * 岛屿数量 https://leetcode-cn.com/problems/number-of-islands/ */ public class 岛屿数量二刷 { public int numIslands_BFS(char[][] grid) { if(grid==null||grid.length==0) return 0; Queue<Integer> queue=new LinkedList<>(); int colLen=grid[0].length; int count=0; for(int i=0;i<grid.length;i++){ for(int j=0;j<grid[0].length;j++){ if(grid[i][j]=='1'){ grid[i][j]='0'; count++; queue.offer(i*colLen+j); while (!queue.isEmpty()){ int combine=queue.poll(); int ti=combine/colLen; int tj=combine%colLen; if(ti+1<grid.length&&grid[ti+1][tj]=='1') { queue.offer((ti+1)*colLen+tj); grid[ti+1][tj]='0'; } if(ti-1>=0&&grid[ti-1][tj]=='1') { queue.offer((ti-1)*colLen+tj); grid[ti-1][tj]='0'; } if(tj+1<colLen&&grid[ti][tj+1]=='1') { queue.offer(ti*colLen+tj+1); grid[ti][tj+1]='0'; } if(tj-1>=0&&grid[ti][tj-1]=='1') { queue.offer(ti*colLen+tj-1); grid[ti][tj-1]='0'; } } } } } return count; } public int numIslands(char[][] grid) { int count=0; for(int i=0;i<grid.length;i++){ for(int j=0;j<grid[0].length;j++){ if(grid[i][j]=='1'){ count++; dfs(grid,i,j); } } } return count; } private void dfs(char[][] grid, int i, int j) { if(i>=grid.length||i<0||j>=grid[0].length||j<0||grid[i][j]=='0'){ return; } grid[i][j]='0'; dfs(grid,i-1,j); dfs(grid,i+1,j); dfs(grid,i,j-1); dfs(grid,i,j+1); } }
package Greedy; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; public class QueueReconstruction { public int[][] reconstructQueue(int[][] people) { int[][] result = new int[people.length][]; Arrays.sort(people, new Comparator<int[]>(){ public int compare(int[] a1, int[] a2){ if(a1[0]!=a2[0]){ return a2[0]-a1[0]; }else{ return a1[1]-a2[1]; } } }); ArrayList<int[]> list = new ArrayList<int[]>(); for(int i=0; i<people.length; i++){ int[] arr = people[i]; list.add(arr[1],arr); } for(int i=0; i<people.length; i++){ result[i]=list.get(i); } return result; } public static void main(String[] args) { // TODO Auto-generated method stub int[][] people = { {7,0}, {4,4}, {7,1}, {5,0}, {6,1}, {5,2} }; QueueReconstruction qr = new QueueReconstruction(); int[][] result = qr.reconstructQueue(people); for(int[] arr : result) System.out.println(Arrays.toString(arr)); } }
package a1; import javax.swing.AbstractAction; import java.awt.event.ActionEvent; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; public class SizeCommand implements MouseWheelListener { Model m; public SizeCommand(Model m){ this.m = m; } public void mouseWheelMoved(MouseWheelEvent e){ m.changeSize(e.getWheelRotation()); } }
package com.project.smart6.model; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * IPL Player Entity * @author krish * */ @Entity @Table(name = "ipl_players") public class IPLPlayer { @Id private int player_id; private String player_name; private String player_type; private String player_credit; private String player_team; private String player_points; private int team_id; /** * @return the player_id */ public int getPlayer_id() { return player_id; } /** * @param player_id the player_id to set */ public void setPlayer_id(int player_id) { this.player_id = player_id; } /** * @return the player_name */ public String getPlayer_name() { return player_name; } /** * @param player_name the player_name to set */ public void setPlayer_name(String player_name) { this.player_name = player_name; } /** * @return the player_type */ public String getPlayer_type() { return player_type; } /** * @param player_type the player_type to set */ public void setPlayer_type(String player_type) { this.player_type = player_type; } /** * @return the player_credit */ public String getPlayer_credit() { return player_credit; } /** * @param player_credit the player_credit to set */ public void setPlayer_credit(String player_credit) { this.player_credit = player_credit; } /** * @return the player_team */ public String getPlayer_team() { return player_team; } /** * @param player_team the player_team to set */ public void setPlayer_team(String player_team) { this.player_team = player_team; } /** * @return the player_points */ public String getPlayer_points() { return player_points; } /** * @param player_points the player_points to set */ public void setPlayer_points(String player_points) { this.player_points = player_points; } /** * @return the team_id */ public int getTeam_id() { return team_id; } /** * @param team_id the team_id to set */ public void setTeam_id(int team_id) { this.team_id = team_id; } }
package pro.likada.service.serviceImpl; import org.hibernate.HibernateException; import pro.likada.dao.TelegramUserDAO; import pro.likada.model.TelegramUser; import pro.likada.model.User; import pro.likada.service.TelegramUserService; import javax.inject.Inject; import javax.inject.Named; import javax.transaction.Transactional; import java.util.List; /** * Created by bumur on 17.03.2017. */ @Named("telegramUserService") @Transactional public class TelegramUserServiceImpl implements TelegramUserService { @Inject private TelegramUserDAO telegramUserDAO; @Override public TelegramUser findById(Long id) throws HibernateException { return telegramUserDAO.findById(id); } @Override public TelegramUser findByTelegramUserId(Integer telegramUserId) throws HibernateException { return telegramUserDAO.findByTelegramUserId(telegramUserId); } @Override public TelegramUser findByTelegramUsername(String username) throws HibernateException { return telegramUserDAO.findByTelegramUsername(username); } @Override public List<TelegramUser> findByOwnerUser(User owner) { return telegramUserDAO.findByOwnerUser(owner); } @Override public List<TelegramUser> findAll() { return telegramUserDAO.findAll(); } @Override public void save(TelegramUser telegramUser) throws HibernateException { telegramUserDAO.save(telegramUser); } @Override public void delete(TelegramUser telegramUser) throws HibernateException { telegramUserDAO.delete(telegramUser); } @Override public void deleteByTelegramUserId(Long id) throws HibernateException { telegramUserDAO.deleteByTelegramUserId(id); } }
package com.g74.rollersplat.controller.command; import com.g74.rollersplat.controller.states.*; import com.g74.rollersplat.model.menu.Menu; import com.g74.rollersplat.viewer.gui.GUI; import java.io.IOException; public class StateController { private State state; private int levelNum = 1; private int modeNum = 0; private int chosenColor = 0; private final int levelCount = 3; // cuz we have 3 levels public StateController(GUI gui) { state = new MenuState(gui, new Menu()); } public void run(GUI gui) throws IOException, InterruptedException { int result; while (true) { this.levelNum = 1; result = state.run(this); if (result == -2) break; // menu exit button was pressed while (result >= 10) { //didnt choose a mode yet if (result < 20) //chose a color chosenColor = result; result = state.run(this); } if (result == -2) break; // menu exit button was pressed while ((levelNum < levelCount + 1) && result != -1) { result = state.run(this); } } gui.close(); } public void setState(State state) { this.state = state; } public int getLevelNum (){ return this.levelNum; } public int getChosenColor() { return this.chosenColor; } public void setModeNum(int num) { this.modeNum = num; } public void setLevelNum (int num) { this.levelNum = num; } public int getModeNum() { return this.modeNum; } public int getLevelCount(){ return this.levelCount; } public State getState() { return state; } }
package com.cpro.rxjavaretrofit.entity; /** * Created by lx on 2016/6/16. */ public class MemberBaseInfoEntity { private String memberRoleId; private String memberName; private String memberHeadUrl; public MemberBaseInfoEntity(String memberRoleId, String memberName, String memberHeadUrl) { this.memberRoleId = memberRoleId; this.memberName = memberName; this.memberHeadUrl = memberHeadUrl; } public String getMemberRoleId() { return memberRoleId; } public void setMemberRoleId(String memberRoleId) { this.memberRoleId = memberRoleId; } public String getMemberName() { return memberName; } public void setMemberName(String memberName) { this.memberName = memberName; } public String getMemberHeadUrl() { return memberHeadUrl; } public void setMemberHeadUrl(String memberHeadUrl) { this.memberHeadUrl = memberHeadUrl; } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.04.05 at 10:33:51 AM CST // package nbi.xsd.model; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for FilePatternType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="FilePatternType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="filePattern" type="{}FileDetailRecordType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "FilePatternType", propOrder = { "filePattern" }) public class FilePatternType { @XmlElement(required = true) protected List<FileDetailRecordType> filePattern; /** * Gets the value of the filePattern property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the filePattern property. * * <p> * For example, to add a new item, do as follows: * <pre> * getFilePattern().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link FileDetailRecordType } * * */ public List<FileDetailRecordType> getFilePattern() { if (filePattern == null) { filePattern = new ArrayList<FileDetailRecordType>(); } return this.filePattern; } }
package com.intentsg.service.tour.repository; import com.intentsg.service.tour.model.UserTour; import com.intentsg.service.tour.service.TourService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.*; @DataJpaTest @Transactional @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) class UserTourRepositoryTest { @Autowired UserTourRepository userTourRepository; @Test void findAllByUserId() { List<UserTour> testUserTour = new ArrayList<>(); UserTour ut1 = new UserTour(1L, "userid1", 100L, 10); UserTour ut2 = new UserTour(2L, "userid2", 101L, 10); UserTour ut3 = new UserTour(3L, "userid2", 102L, 10); testUserTour.add(ut1); testUserTour.add(ut2); testUserTour.add(ut3); userTourRepository.saveAll(testUserTour); List<UserTour> fromDbUserTour = userTourRepository.findAllByUserId("userid2"); assertEquals(fromDbUserTour.size(), 2); } }
package org.traccar.notificators; import org.traccar.Context; import org.traccar.model.Event; import org.traccar.model.Position; import org.traccar.model.User; import org.traccar.notification.FullMessage; import org.traccar.notification.MessageException; import org.traccar.notification.NotificationFormatter; import javax.ws.rs.client.AsyncInvoker; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation; public class NotificatorFcm extends Notificator { @Override public void sendSync(long userId, Event event, Position position) throws MessageException, InterruptedException { User user = Context.getPermissionsManager().getUser(userId); String serverKey = Context.getConfig().getString("notificator.fcm.serverkey", ""); String url = "https://fcm.googleapis.com/fcm/send"; Invocation.Builder requestBuilder = Context.getClient().target(url).request(); requestBuilder = requestBuilder.header("Authorization", "key=" + serverKey); requestBuilder = requestBuilder.header("Content-Type", "application/json"); AsyncInvoker invoker = requestBuilder.async(); FullMessage fullMessage = NotificationFormatter.formatFCMMessage(userId, event, position); invoker.post(Entity.json(new FCM(user.getFcm(), new FCM.Notification(fullMessage.getBody(), fullMessage.getSubject() + " Alert")))); } public static class FCM { private String to; private Notification notification; public FCM() { } public FCM(String to, Notification notification) { this.to = to; this.notification = notification; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public Notification getNotification() { return notification; } public void setNotification(Notification notification) { this.notification = notification; } public static class Notification { private String body, title; public Notification() { } public Notification(String body, String title) { this.body = body; this.title = title; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } } } }
package com.alibaba.druid.bvt.sql.mysql.select; import com.alibaba.druid.sql.MysqlTest; import com.alibaba.druid.sql.SQLUtils; import com.alibaba.druid.sql.ast.SQLStatement; import com.alibaba.druid.sql.ast.statement.SQLSelectStatement; import com.alibaba.druid.util.JdbcConstants; import java.util.List; public class MySqlSelectTest_127 extends MysqlTest { public void test_0() throws Exception { String sql = "/*+engine=mpp*/SELECT min(pay_byr_rate_90d) FROM (/*+engine=mpp*/SELECT pay_byr_rate_90d FROM caspian.ads_itm_hpcj_all_df WHERE item_pools_tags = '1116' AND pay_byr_rate_90d >= 0 ORDER BY pay_byr_rate_90d DESC LIMIT 49) LIMIT 500"; List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals(1, statementList.size()); assertEquals("/*+engine=mpp*/\n" + "SELECT min(pay_byr_rate_90d)\n" + "FROM (\n" + "\t/*+engine=mpp*/\n" + "\tSELECT pay_byr_rate_90d\n" + "\tFROM caspian.ads_itm_hpcj_all_df\n" + "\tWHERE item_pools_tags = '1116'\n" + "\t\tAND pay_byr_rate_90d >= 0\n" + "\tORDER BY pay_byr_rate_90d DESC\n" + "\tLIMIT 49\n" + ")\n" + "LIMIT 500", stmt.toString()); } }
package alien4cloud.it.topology; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.elasticsearch.common.collect.Maps; import org.junit.Assert; import alien4cloud.dao.model.FacetedSearchResult; import alien4cloud.it.Context; import alien4cloud.it.Entry; import alien4cloud.it.common.CommonStepDefinitions; import alien4cloud.it.utils.JsonTestUtil; import alien4cloud.model.templates.TopologyTemplate; import alien4cloud.model.templates.TopologyTemplateVersion; import alien4cloud.rest.component.SearchRequest; import alien4cloud.rest.model.RestResponse; import alien4cloud.rest.template.CreateTopologyTemplateRequest; import alien4cloud.rest.topology.NodeTemplateRequest; import alien4cloud.rest.utils.JsonUtil; import alien4cloud.topology.TopologyDTO; import alien4cloud.utils.ReflectionUtil; import cucumber.api.DataTable; import cucumber.api.java.en.And; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class TopologyTemplateStepDefinitions { private CommonStepDefinitions commonSteps = new CommonStepDefinitions(); @When("^I create a new topology template with name \"([^\"]*)\" and description \"([^\"]*)\"$") public void I_create_a_new_topology_template_with_name_and_description(String topologyTemplateName, String topologyTemplateDesc) throws Throwable { CreateTopologyTemplateRequest ttRequest = new CreateTopologyTemplateRequest(); ttRequest.setDescription(topologyTemplateDesc); ttRequest.setName(topologyTemplateName); Context.getInstance().registerRestResponse(Context.getRestClientInstance().postJSon("/rest/templates/topology", JsonUtil.toString(ttRequest))); String topologyTemplateId = JsonUtil.read(Context.getInstance().getRestResponse(), String.class).getData(); // assertNotNull(topologyTemplateId); // get the last version of this topology template // String templateVersionJson = Context.getRestClientInstance().get("/rest/templates/" + topologyTemplateId + "/versions/"); // TopologyTemplateVersion ttv = JsonUtil.read(templateVersionJson, TopologyTemplateVersion.class).getData(); // recover the created template to register it String templateTopologyJson = Context.getRestClientInstance().get("/rest/templates/topology/" + topologyTemplateId); TopologyTemplate template = JsonUtil.read(templateTopologyJson, TopologyTemplate.class).getData(); // assertNotNull(template); if (template != null) { Context.getInstance().registerTopologyTemplate(template); // Context.getInstance().registerTopologyId(ttv.getTopologyId()); } } public static TopologyTemplateVersion getLatestTopologyTemplateVersion(String topologyTemplateId) throws IOException { String templateVersionJson = Context.getRestClientInstance().get("/rest/templates/" + topologyTemplateId + "/versions/"); TopologyTemplateVersion ttv = JsonUtil.read(templateVersionJson, TopologyTemplateVersion.class).getData(); return ttv; } @Then("^I can get and register the topology for the last version of the registered topology template$") public void I_can_get_the_last_version_for_the_registered_topology_template() throws Throwable { TopologyTemplate topologyTemplate = Context.getInstance().getTopologyTemplate(); TopologyTemplateVersion ttv = getLatestTopologyTemplateVersion(topologyTemplate.getId()); assertNotNull(ttv); assertNotNull(ttv.getTopologyId()); Context.getInstance().registerTopologyId(ttv.getTopologyId()); } @Given("^I create a new topology template with name \"([^\"]*)\" and description \"([^\"]*)\" and node templates$") public void I_create_a_new_topology_template_with_name_and_description_and_node_templates(String topologyTemplateName, String topologyTemplateDesc, DataTable nodeTemplates) throws Throwable { // create the topology I_create_a_new_topology_template_with_name_and_description(topologyTemplateName, topologyTemplateDesc); I_can_get_the_last_version_for_the_registered_topology_template(); // add all specified nodetemplate to a specific topology (from Application or Topology template) for (List<String> row : nodeTemplates.raw()) { NodeTemplateRequest req = new NodeTemplateRequest(row.get(0), row.get(1)); String nodeTypeJson = Context.getInstance().getJsonMapper().writeValueAsString(req); String topologyId = Context.getInstance().getTopologyId(); Context.getInstance().registerRestResponse( Context.getRestClientInstance().postJSon("/rest/topologies/" + topologyId + "/nodetemplates", nodeTypeJson)); } // Created topology should have a node template count == count(nodeTemplates) Context.getInstance().registerRestResponse(Context.getRestClientInstance().get("/rest/topologies/" + Context.getInstance().getTopologyId())); TopologyDTO topologyTemplateBase = JsonTestUtil.read(Context.getInstance().getRestResponse(), TopologyDTO.class).getData(); assertEquals(topologyTemplateBase.getTopology().getNodeTemplates().size(), nodeTemplates.raw().size()); } @Then("^The RestResponse should contain a topology template id$") public void The_RestResponse_should_contain_a_topology_template_id() throws Throwable { String topologyTemplateId = JsonUtil.read(Context.getInstance().getRestResponse(), String.class).getData(); assertNotNull(topologyTemplateId); } @Then("^I can get this newly created topology template$") public void I_can_get_this_newly_created_topology_template() throws Throwable { TopologyTemplate topologyTemplate = Context.getInstance().getTopologyTemplate(); assertNotNull(topologyTemplate); } @Given("^I have created a new topology template with name \"([^\"]*)\" and description \"([^\"]*)\"$") public void I_have_created_a_new_topology_template_with_name_and_description(String topologyTemplateName, String topologyTemplateDesc) throws Throwable { I_create_a_new_topology_template_with_name_and_description(topologyTemplateName, topologyTemplateDesc); commonSteps.I_should_receive_a_RestResponse_with_no_error(); } @When("^I delete the newly created topology template$") public void I_delete_the_newly_created_topology_template() throws Throwable { TopologyTemplate topologyTemplate = Context.getInstance().getTopologyTemplate(); assertNotNull(topologyTemplate); Context.getInstance().registerRestResponse(Context.getRestClientInstance().delete("/rest/templates/topology/" + topologyTemplate.getId())); } @When("^I delete the topology template with name \"([^\"]*)\"$") public void I_delete_topology_template(String topologyTemplateName) throws Throwable { String topologyTemplateId = getTopologyTemplateIdFromName(topologyTemplateName); assertNotNull(topologyTemplateId); Context.getInstance().registerRestResponse(Context.getRestClientInstance().delete("/rest/templates/topology/" + topologyTemplateId)); } public static String getTopologyTemplateIdFromName(String topologyTemplateName) throws Throwable { SearchRequest templateWithNameSearchRequest = new SearchRequest(); Map<String, String[]> filters = Maps.newHashMap(); filters.put("name", new String[] { topologyTemplateName }); templateWithNameSearchRequest.setFilters(filters); templateWithNameSearchRequest.setFrom(0); templateWithNameSearchRequest.setSize(1); String response = Context.getRestClientInstance().postJSon("/rest/templates/topology/search", JsonUtil.toString(templateWithNameSearchRequest)); RestResponse<FacetedSearchResult> restResponse = JsonUtil.read(response, FacetedSearchResult.class); Assert.assertEquals(1, restResponse.getData().getData().length); Map<String, Object> singleResult = (Map<String, Object>) restResponse.getData().getData()[0]; String templateId = (String) singleResult.get("id"); return templateId; } @Then("^The related topology shouldn't exist anymore$") public void The_related_topology_shouldn_t_exist_anymore() throws Throwable { Context.getInstance().registerRestResponse(Context.getRestClientInstance().get("/rest/topologies/" + Context.getInstance().getTopologyId())); commonSteps.I_should_receive_a_RestResponse_with_an_error_code(504); } @When("^I update the topology template \"([^\"]*)\" fields:$") public void I_update_the_topology_template_fields(String name, List<Entry> fileds) throws Throwable { Map<String, String> fieldsMap = Maps.newHashMap(); for (Entry field : fileds) { fieldsMap.put(field.getName(), field.getValue()); } TopologyTemplate topologyTemplate = Context.getInstance().getTopologyTemplate(); assertNotNull(topologyTemplate); Context.getInstance().registerRestResponse( Context.getRestClientInstance().putJSon("/rest/templates/topology/" + topologyTemplate.getId(), JsonUtil.toString(fieldsMap))); } @And("^The topology template should have its \"([^\"]*)\" set to \"([^\"]*)\"$") public void The_topology_template_should_have_its_set_to(String fieldName, String fieldValue) throws Throwable { TopologyTemplate topologyTemplate = Context.getInstance().getTopologyTemplate(); String response = Context.getRestClientInstance().get("/rest/templates/topology/" + topologyTemplate.getId()); TopologyTemplate topologyTemplateUpdated = JsonUtil.read(response, TopologyTemplate.class).getData(); assertNotNull(topologyTemplateUpdated); assertEquals(fieldValue, ReflectionUtil.getPropertyValue(topologyTemplateUpdated, fieldName).toString()); } @Given("^I expose the template as type \"([^\"]*)\"$") public void I_expose_the_template_as_type(String type) throws Throwable { String topologyId = Context.getInstance().getTopologyId(); assertNotNull(topologyId); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("elementId", type)); Context.getInstance().registerRestResponse( Context.getRestClientInstance().putUrlEncoded("/rest/topologies/" + topologyId + "/substitutions/type", nvps)); } @Given("^I expose the capability \"([^\"]*)\" for the node \"([^\"]*)\"$") public void I_expose_the_capability_for_the_node(String capabilityName, String nodeName) throws Throwable { String topologyId = Context.getInstance().getTopologyId(); assertNotNull(topologyId); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("nodeTemplateName", nodeName)); nvps.add(new BasicNameValuePair("capabilityId", capabilityName)); Context.getInstance().registerRestResponse( Context.getRestClientInstance().putUrlEncoded("/rest/topologies/" + topologyId + "/substitutions/capabilities/" + capabilityName, nvps)); } @Given("^I rename the exposed capability \"([^\"]*)\" to \"([^\"]*)\"$") public void I_rename_the_exposed_capability_to(String capabilityName, String newName) throws Throwable { String topologyId = Context.getInstance().getTopologyId(); assertNotNull(topologyId); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("newCapabilityId", newName)); Context.getInstance().registerRestResponse( Context.getRestClientInstance().postUrlEncoded("/rest/topologies/" + topologyId + "/substitutions/capabilities/" + capabilityName, nvps)); } @Given("^I expose the requirement \"([^\"]*)\" for the node \"([^\"]*)\"$") public void I_expose_the_requirement_for_the_node(String requirementName, String nodeName) throws Throwable { String topologyId = Context.getInstance().getTopologyId(); assertNotNull(topologyId); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("nodeTemplateName", nodeName)); nvps.add(new BasicNameValuePair("requirementId", requirementName)); Context.getInstance().registerRestResponse( Context.getRestClientInstance().putUrlEncoded("/rest/topologies/" + topologyId + "/substitutions/requirements/" + requirementName, nvps)); } @Given("^I rename the exposed requirement \"([^\"]*)\" to \"([^\"]*)\"$") public void I_rename_the_exposed_requirement_to(String requirementName, String newName) throws Throwable { String topologyId = Context.getInstance().getTopologyId(); assertNotNull(topologyId); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("newRequirementId", newName)); Context.getInstance().registerRestResponse( Context.getRestClientInstance().postUrlEncoded("/rest/topologies/" + topologyId + "/substitutions/requirements/" + requirementName, nvps)); } }
package tn.esprit.spring.repository; import org.springframework.data.repository.CrudRepository; import tn.esprit.spring.entity.Projet; public interface IProjetRepository extends CrudRepository<Projet, Integer> { }
package com.example.android.citylistview; /** * Created by Shereen on 10/10/2017. */ public class City { private String Name; private int Population; private int image; private String Longitude; private String Latitude; public City(String name, int population, int image) { setName(name); setPopulation(population); this.setImage(image); } public String getName() { return Name; } public void setName(String name) { Name = name; } public int getPopulation() { return Population; } public void setPopulation(int population) { Population = population; } public int getImage() { return image; } public void setImage(int image) { this.image = image; } public String getLongitude() { return Longitude; } public void setLongitude(String longitude) { Longitude = longitude; } public String getLatitude() { return Latitude; } public void setLatitude(String latitude) { Latitude = latitude; } }
package com.myvodafone.android.business.managers; import android.app.Activity; import android.content.Context; import android.os.AsyncTask; import com.myvodafone.android.model.service.ClaimedCouponResult; import com.myvodafone.android.model.service.CouponResult; import com.myvodafone.android.model.service.CouponsResponse; import com.myvodafone.android.model.service.UserHistoryResult; import com.myvodafone.android.model.service.fixed.ClaimedCoupon; import com.myvodafone.android.model.service.fixed.Coupon; import com.myvodafone.android.model.service.fixed.UserHistory; import com.myvodafone.android.model.service.handlers.CouponResultHandler; import com.myvodafone.android.model.service.handlers.UserHistoryResultHandler; import com.myvodafone.android.service.DataHandler; import com.myvodafone.android.service.FXLDataParser; import com.myvodafone.android.service.FXLWLResponseListenerImpl; import com.myvodafone.android.service.WorklightClientManager; import com.myvodafone.android.utils.StaticTools; import com.worklight.wlclient.api.WLFailResponse; import com.worklight.wlclient.api.WLResponse; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; /** * Created by d.alexandrakis on 15/4/2016. */ public class ThankYouManager { private static ArrayList<CouponResult> cachedThankYouAllItems; private static ArrayList<UserHistoryResult> cachedThankYouCodeItems; private static int previousListPosition = 0; public interface ThankYouCouponListener { void onSuccessfulCouponsRetrieval(ArrayList<CouponResult> result); void onErrorCouponsRetrieval(String msg); void onEmptyCouponRetrieval(); } public interface ThankYouUserHistoryListener { void OnSuccessfulUserHistoryRetrieval(ArrayList<UserHistoryResult> response); void onErrorUserHistoryRetrieval(String msg); void onEmptyUserHistoryRetrieval(); } public interface ThankYouFxdCouponListener extends FixedLineManager.FixedLineServiceListener { void onSuccessfulFxdCouponsRetrieval(ArrayList<CouponResult> result); void onEmptyFxdCouponsRetrieval(); void onErrorFxdCouponsRetrieval(String msg); } public interface ThankYouFxdUserHistoryListener extends FixedLineManager.FixedLineServiceListener { void OnSuccessfulFxdUserHistoryRetrieval(ArrayList<UserHistoryResult> response); void onEmptyFxdUserHistoryRetrieval(); void onErrorFxdUserHistoryRetrieval(String msg); } public interface ThankYouClaimCouponListener { void onSuccessfulCouponClaimed(ClaimedCouponResult result); void onErrorCouponClaimed(String msg); } public interface ThankYouFxdClaimCouponListener extends FixedLineManager.FixedLineServiceListener { void onSuccessfulFxdCouponClaimed(ClaimedCouponResult result); void onEmptyFxdFxdCouponClaimed(); void onErrorFxdCouponClaimed(String msg); } public static void getThankYouUserHistory(Context context, final String username, final String password, final String langCode, final String number, final String afm, final String limit, final String offset, WeakReference<ThankYouUserHistoryListener> listener) { new GetThankYouUserHistory(context, username, password, langCode, number, afm, limit, offset, listener).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } public static void getThankYouCoupons(Context context, final String username, final String password, final String langCode, final String number, final String afm, final String orderBy, WeakReference<ThankYouCouponListener> listener) { new GetThankYouCoupons(context, username, password, langCode, number, afm, orderBy, listener).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } public static void getClaimedCoupon(Context context, final String username, final String password, final String langCode, final String number, final String afm, final String couponId, WeakReference<ThankYouClaimCouponListener> listener) { new GetClaimedCoupon(context, username, password, langCode, number, afm, couponId, listener).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } public static class GetThankYouUserHistory extends AsyncTask<Void, Void, Void> { String username, password, langCode, number, afm, limit, offset; ArrayList<UserHistoryResult> results; ThankYouUserHistoryListener callback; Context context; public GetThankYouUserHistory(Context context, final String username, final String password, final String langCode, final String number, final String afm, final String limit, final String offset, WeakReference<ThankYouUserHistoryListener> listener) { this.username = username; this.password = password; this.langCode = langCode; this.number = number; this.afm = afm; this.limit = limit; this.offset = offset; this.context = context; callback = listener != null ? listener.get() : null; } @Override protected Void doInBackground(Void... params) { results = DataHandler.wb_get_user_history(context, username, password, langCode, number, afm, limit, offset); return null; } @Override protected void onPostExecute(Void aVoid) { if (callback != null) { if (results == null) { callback.onErrorUserHistoryRetrieval("null"); } else { if (results.size() < 1) { callback.onEmptyUserHistoryRetrieval(); } else { callback.OnSuccessfulUserHistoryRetrieval(results); } } } } } public static class GetThankYouCoupons extends AsyncTask<Void, Void, Void> { String username, password, langCode, number, afm, orderBy; CouponsResponse response; ArrayList<CouponResult> results; ThankYouCouponListener callback; Context context; public GetThankYouCoupons(Context context, final String username, final String password, final String langCode, final String number, final String afm, final String orderBy, WeakReference<ThankYouCouponListener> listener) { this.username = username; this.password = password; this.langCode = langCode; this.number = number; this.afm = afm; this.orderBy = orderBy; this.context = context; callback = listener != null ? listener.get() : null; } @Override protected Void doInBackground(Void... params) { response = DataHandler.wb_get_coupons(context, username, password, langCode, number, afm, orderBy); return null; } @Override protected void onPostExecute(Void aVoid) { results = response!=null? response.getCoupons():null; if (callback != null) { if (results == null) { callback.onErrorCouponsRetrieval("null"); } else { if (results.size() < 1) { callback.onEmptyCouponRetrieval(); } else { callback.onSuccessfulCouponsRetrieval(results); } } } } } public static void getFxdThankYouUserHistory(Activity activity, String[] params, final WeakReference<ThankYouFxdUserHistoryListener> listener) { final ArrayList<UserHistoryResult> response = new ArrayList<UserHistoryResult>(); WorklightClientManager.getUserHistory(params, activity, new FXLWLResponseListenerImpl() { @Override public void onSuccess(WLResponse wlResponse) { StaticTools.Log("GetFxdThankYouUserHistory :" + wlResponse.getResponseText()); final ThankYouFxdUserHistoryListener callback = listener!=null?listener.get():null; UserHistory userHistory = FXLDataParser.parseUserHistory(wlResponse.getResponseJSON().toString()); if (userHistory != null && userHistory.getIsSuccessful() && userHistory.getResponseData() != null && userHistory.getResponseData().getData() != null && userHistory.getResponseData().getData().size() > 0) { List<UserHistory.Datum> items = userHistory.getResponseData().getData(); UserHistoryResultHandler handler = new UserHistoryResultHandler(); for (int i = 0; i <= items.size() - 1; i++) { UserHistory.Datum data = items.get(i); response.add(handler.fromDatumToUserHistoryResult(data)); } if (callback != null) { callback.OnSuccessfulFxdUserHistoryRetrieval(response); } } else { if (callback != null) { callback.onEmptyFxdUserHistoryRetrieval(); } } } @Override public void onFailure(WLFailResponse wlFailResponse) { StaticTools.Log("GetFxdThankYouUserHistory :" + wlFailResponse.toString()); final ThankYouFxdUserHistoryListener callback = listener!=null?listener.get():null; if (callback != null) { callback.onErrorFxdUserHistoryRetrieval("empty"); } } @Override public void onSessionTimeout() { final FixedLineManager.FixedLineServiceListener callback = listener != null ? listener.get() : null; if (callback != null) { callback.onAuthError(); } } }); } public static void getFxdThankYouCoupons(Activity activity, String[] params, final WeakReference<ThankYouFxdCouponListener> listener){ final ArrayList<CouponResult> response = new ArrayList<CouponResult>(); WorklightClientManager.getCoupons(params,activity , new FXLWLResponseListenerImpl() { @Override public void onSuccess(WLResponse wlResponse) { StaticTools.Log("GetFxdThankYouCoupons :" + wlResponse.getResponseText()); final ThankYouFxdCouponListener callback = listener!=null?listener.get():null; Coupon coupon = FXLDataParser.parseCoupons(wlResponse.getResponseJSON().toString()); if(coupon != null && coupon.getIsSuccessful() && coupon.getResponseData() != null && coupon.getResponseData().getOffers() != null && coupon.getResponseData().getOffers().size() > 1){ List<Coupon.Offer> items = coupon.getResponseData().getOffers(); CouponResultHandler handler = new CouponResultHandler(); for(int i =0; i <= items.size() -1; i ++){ Coupon.Offer offer = items.get(i); response.add(handler.fromOfferToCouponResult(offer)); } if(callback != null){ callback.onSuccessfulFxdCouponsRetrieval(response); } } else{ if(callback != null){ callback.onEmptyFxdCouponsRetrieval(); } } } @Override public void onFailure(WLFailResponse wlFailResponse) { StaticTools.Log("GetFxdThankYouCoupons :" + wlFailResponse.toString()); final ThankYouFxdCouponListener callback = listener!=null?listener.get():null; if(callback != null){ callback.onErrorFxdCouponsRetrieval("empty"); } } @Override public void onSessionTimeout() { final FixedLineManager.FixedLineServiceListener callback = listener != null ? listener.get() : null; if (callback != null) { callback.onAuthError(); } } }); } public static class GetClaimedCoupon extends AsyncTask<Void,Void,Void>{ private Context context; private String username,password,langCode,number,afm,couponId; private ThankYouClaimCouponListener callback; private ClaimedCouponResult result; public GetClaimedCoupon(Context context, final String username, final String password, final String langCode, final String number, final String afm,final String couponId, WeakReference<ThankYouClaimCouponListener> listener){ this.context = context; this.username = username; this.password = password; this.langCode = langCode; this.number = number; this.afm = afm; this.couponId = couponId; callback = listener!=null?listener.get():null; } @Override protected Void doInBackground(Void... params) { result = DataHandler.wb_get_claimed_coupon(context,username,password,langCode,number,afm,couponId); return null; } @Override protected void onPostExecute(Void aVoid) { if(callback != null){ if(result == null){ callback.onErrorCouponClaimed("null"); } else { callback.onSuccessfulCouponClaimed(result); } } } } public static void getFxdClaimedCoupon(Activity activity, String[] params, final WeakReference<ThankYouFxdClaimCouponListener> listener){ final ClaimedCouponResult response = new ClaimedCouponResult(); WorklightClientManager.getClaimedCoupon(params,activity , new FXLWLResponseListenerImpl() { @Override public void onSuccess(WLResponse wlResponse) { StaticTools.Log("GetFxdClaimedCoupon :" + wlResponse.getResponseText()); final ThankYouFxdClaimCouponListener callback = listener!=null?listener.get():null; ClaimedCoupon coupon = FXLDataParser.parseClaimedCoupon(wlResponse.getResponseJSON().toString()); if(coupon.getIsSuccessful() && coupon.getResponseData() != null){ response.setGiftCode(coupon.getResponseData().getGiftcode().getCDATA()); response.setGiftCodeValidUntil(coupon.getResponseData().getGiftcodeValidUntil().getCDATA()); response.setMsisdn(coupon.getResponseData().getMsisdn().getXmlns()); response.setOfferTaken(coupon.getResponseData().getOfferTaken().getCDATA()); response.setResponse(coupon.getResponseData().getResponse().getCDATA()); response.setSmsSent(coupon.getResponseData().getSmssent().getCDATA()); if(callback != null){ callback.onSuccessfulFxdCouponClaimed(response); } } else { if(callback != null){ callback.onEmptyFxdFxdCouponClaimed(); } } } @Override public void onFailure(WLFailResponse wlFailResponse) { StaticTools.Log("GetFxdClaimedCoupon :" + wlFailResponse.toString()); final ThankYouFxdClaimCouponListener callback = listener!=null?listener.get():null; if(callback != null){ callback.onErrorFxdCouponClaimed("empty"); } } @Override public void onSessionTimeout() { final FixedLineManager.FixedLineServiceListener callback = listener != null ? listener.get() : null; if (callback != null) { callback.onAuthError(); } } }); } public static void setCachedThankYouAllItems(ArrayList<CouponResult> thankYouAllItems) { if(cachedThankYouAllItems == null) { cachedThankYouAllItems = new ArrayList<>(); } cachedThankYouAllItems = thankYouAllItems; } public static ArrayList<CouponResult> getCachedThankYouAllItems() { if(cachedThankYouAllItems == null) { return new ArrayList<>(); } else { return cachedThankYouAllItems; } } public static void setCachedThankYouCodeItems(ArrayList<UserHistoryResult> thankYouCodeItems) { if(cachedThankYouCodeItems == null) { cachedThankYouCodeItems = new ArrayList<>(); } cachedThankYouCodeItems = thankYouCodeItems; } public static ArrayList<UserHistoryResult> getCachedThankYouCodeItems() { if(cachedThankYouCodeItems == null) { return new ArrayList<>(); } else { return cachedThankYouCodeItems; } } public static int getPreviousListPosition() { return previousListPosition; } public static void setPreviousListPosition(int previousListPosition) { ThankYouManager.previousListPosition = previousListPosition; } }
package com.gaoshin.beans; import java.util.Calendar; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class UserFile { private Long id; private User user; private String mimetype; private UserFileType type; private String name; private String path; private Calendar createTime; public void setCreateTime(Calendar createTime) { this.createTime = createTime; } public Calendar getCreateTime() { return createTime; } public void setMimetype(String mimetype) { this.mimetype = mimetype; } public String getMimetype() { return mimetype; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setPath(String path) { this.path = path; } public String getPath() { return path; } public void setUser(User user) { this.user = user; } public User getUser() { return user; } public void setId(Long id) { this.id = id; } public Long getId() { return id; } public void setType(UserFileType type) { this.type = type; } public UserFileType getType() { return type; } }
package project.core.groupPage; import org.openqa.selenium.By; import project.BasePage; public class GroupProfilePage extends BasePage { private static final By participantBtnLocator = By.xpath(".//*[contains(@data-l,'t,join')]/div"); private static final By leaveGroupBtnLocator = By.xpath(".//*[contains(@data-l,'t,join')]//a[contains(@class, 'dropdown_i')]"); public GroupProfilePage() { } @Override protected void check() { clickable(participantBtnLocator); } public void leaveGroup() { click(participantBtnLocator); click(leaveGroupBtnLocator); } }
package express.product.pt.cn.fishepress.utils; import android.support.annotation.RestrictTo; import express.product.pt.cn.fishepress.bean.CookingBean; import express.product.pt.cn.fishepress.http.httpinterface.CookService; import retrofit2.Call; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.plugins.RxJavaObservableExecutionHook; import rx.schedulers.Schedulers; /** * 网络请求工具类 */ public class HttpUtils { private static HttpUtils instance; private final static String API_COOK_IO = "https://apis.juhe.cn/"; //单例 public static HttpUtils getInstance() { if(instance==null){ synchronized (HttpUtils.class){ if(instance==null){ instance = new HttpUtils(); } } } return instance; } public Observable<CookingBean> getApiCookIo(String name,String apiId,String rn) { Retrofit retrofit=new Retrofit.Builder() .baseUrl(API_COOK_IO) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); CookService cookService=retrofit.create(CookService.class); // cookService.listNameCook(name,apiId,rn) // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(new Subscriber<CookingBean>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // // } // // @Override // public void onNext(CookingBean cookingBean) { // // } // }); Observable<CookingBean> observable=cookService.listNameCook(name,apiId,rn); return observable; } public Retrofit.Builder getBuilder(String StringApi){ Retrofit.Builder retrofit=new Retrofit.Builder(); retrofit.baseUrl(StringApi); retrofit.addConverterFactory(GsonConverterFactory.create()); retrofit.addCallAdapterFactory(RxJavaCallAdapterFactory.create()); return retrofit; } }
package com.example.music; import androidx.appcompat.app.AppCompatActivity; import de.hdodenhof.circleimageview.CircleImageView; import android.animation.ObjectAnimator; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.util.Log; import android.view.View; import android.view.animation.LinearInterpolator; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.example.music.Service.MusicService; import java.text.SimpleDateFormat; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private int count = 3; private boolean isEnd = false; private Handler mHandler = new Handler(); private static final String TAG = "MainActivity"; private MusicService.MyBinder mMyBinder; private TextView play; private CircleImageView img; private boolean isImg = false; private ObjectAnimator mCircleAnimator; private TextView reset; private SeekBar seekBar; //进度条下面的当前进度文字,将毫秒化为m:ss格式 private SimpleDateFormat time = new SimpleDateFormat("m:ss"); //“绑定”服务的intent Intent MediaServiceIntent; private TextView nowTime; private TextView allTime; private TextView timer; private TextView speed; private static Handler handler; private Thread myThread = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); mCircleAnimator = ObjectAnimator.ofFloat(img, "rotation", 0.0f, 360.0f); mCircleAnimator.setDuration(3000);//转一圈的时间 mCircleAnimator.setInterpolator(new LinearInterpolator());//插入器,可控制加速、减速 mCircleAnimator.setRepeatCount(-1);//重复次数,-1为不停止 mCircleAnimator.setRepeatMode(ObjectAnimator.RESTART);//重复模式 在重复次数>=0时生效 MediaServiceIntent = new Intent(this, MusicService.class); MediaServiceIntent.putExtra("aaa","qwer");//可以传一些数据 bindService(MediaServiceIntent, mServiceConnection, BIND_AUTO_CREATE); handler = new Handler(){ public void handleMessage(Message message){ switch (message.what){ case 0: if (count == 0){ mMyBinder.stop(); mCircleAnimator.end(); isImg = false; play.setText("播放"); timer.setText("3s定时已结束"); count = 3; }else { timer.setText(String.valueOf(count)+"s后停止"); } break; default: break; } } }; } private void init() { play = findViewById(R.id.play); img = findViewById(R.id.img); reset = findViewById(R.id.reset); timer = findViewById(R.id.timer); speed = findViewById(R.id.speed); nowTime = findViewById(R.id.now_time); allTime = findViewById(R.id.all_time); //监听滚动条事件 seekBar = (SeekBar) findViewById(R.id.seek_bar); play.setOnClickListener(this); reset.setOnClickListener(this); timer.setOnClickListener(this); speed.setOnClickListener(this); } private ServiceConnection mServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mMyBinder = (MusicService.MyBinder) service; seekBar.setMax(mMyBinder.getProgress()); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { //这里很重要,如果不判断是否来自用户操作进度条,会不断执行下面语句块里面的逻辑,然后就会卡顿卡顿 if(fromUser){ mMyBinder.seekToPositon(seekBar.getProgress()); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); mHandler.post(mRunnable); Log.d(TAG, "Service与Activity已连接"); } @Override public void onServiceDisconnected(ComponentName name) { } }; @Override public void onClick(View v) { //创建Intent对象向service传参 Intent intent = new Intent(); //设置class intent.setClass(MainActivity.this, MusicService.class); switch (v.getId()){ case R.id.play: if (!isImg ){ if (mCircleAnimator.isPaused()){ mCircleAnimator.resume(); }else { mCircleAnimator.start(); } isImg = true; play.setText("暂停"); mMyBinder.play(); // //设置携带的数据 // intent.putExtra("flg","start"); // //启动服务 // startService(intent); }else { mCircleAnimator.pause(); isImg = false; play.setText("继续"); mMyBinder.pause(); // //设置携带的数据 // intent.putExtra("flg","pause"); // //启动服务 // startService(intent); } break; case R.id.reset: mCircleAnimator.end(); isImg = false; play.setText("播放"); mMyBinder.stop(); // //设置携带的数据 // intent.putExtra("flg","reset"); // //启动服务 // startService(intent); break; case R.id.timer: myThread = new Thread(new Runnable() { @Override public void run() { while (!isEnd) { try { Thread.sleep(1000); count--; if (count < 1) { isEnd = true; } Message msg = new Message(); msg.what = 0; handler.sendMessage(msg); } catch (Exception e) { e.printStackTrace(); } } } }); myThread.start(); // mMyBinder.timer(); // mCircleAnimator.end(); // isImg = false; // play.setText("播放"); break; case R.id.speed: mMyBinder.speed(); break; } } @Override protected void onDestroy() { super.onDestroy(); //我们的handler发送是定时1000s发送的,如果不关闭,MediaPlayer release掉了还在获取getCurrentPosition就会爆IllegalStateException错误 mHandler.removeCallbacks(mRunnable); mMyBinder.stop(); unbindService(mServiceConnection); } /** * 更新ui的runnable */ private Runnable mRunnable = new Runnable() { @Override public void run() { seekBar.setProgress(mMyBinder.getPlayPosition()); nowTime.setText(time.format(mMyBinder.getPlayPosition()) + "s"); allTime.setText(time.format(mMyBinder.getProgress()) + "s"); mHandler.postDelayed(mRunnable, 1000); } }; }
package edu.uha.miage.core.repository; import edu.uha.miage.core.entity.Departement; import edu.uha.miage.core.entity.Fonction; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; /** * * @author victo */ public interface FonctionRepository extends JpaRepository<Fonction, Long> { Fonction findByLibelle(String libelle); Optional<Fonction> findById(Long id); List<Fonction> findAllByOrderByLibelle(); List<Fonction> findAllByOrderByDepartementAscLibelleAsc(); public List<Fonction> findByDepartementOrderByLibelle(Departement departement); }
package RAUDT.RoundRobinJCDT_Throughput; import genDevs.modeling.*; import GenCol.*; import simView.*; public class JobAllocator extends ViewableAtomic { protected Queue q; protected int vm_count; protected char[] vm_type; protected boolean[] vm_available; protected int[] vm_queue_length; protected Queue Queue_CPU, Queue_RAM, Queue_NetResponse; protected Job job; protected Info info; protected int current_V, current_I, current_A; protected double processing_time; public JobAllocator() { this("JobAllocator", 10, 1); } public JobAllocator(String name, double Processing_time, int _vm_count) { super(name); addInport("in"); addInport("vm_info"); addInport("done"); for (int i = 0; i < _vm_count; i++) addOutport("out" + i); vm_count = _vm_count; processing_time = Processing_time; } public void initialize() { q = new Queue(); Queue_CPU = new Queue(); Queue_RAM = new Queue(); Queue_NetResponse = new Queue(); vm_type = new char [vm_count]; vm_available = new boolean [vm_count]; vm_queue_length = new int [vm_count]; for (int i = 0; i < vm_count; i++) { vm_type[i] = ' '; vm_available[i] = true; vm_queue_length[i] = 0; } job = new Job(""); current_V = 0; current_I = 1; current_A = 2; holdIn("passive", INFINITY); } public void deltext(double e, message x) { Continue(e); if (phaseIs("passive")) { for (int i = 0; i < x.getLength(); i++) { if (messageOnPort(x, "in", i)) { job = (Job)x.getValOnPort("in", i); holdIn("busy", processing_time); } } } else { for (int i = 0; i < x.getLength(); i++) { if (messageOnPort(x, "in", i)) { q.add(x.getValOnPort("in", i)); } } } } public void deltint() { if (phaseIs("busy")) { if (q.size() > 0) { job = (Job)q.removeFirst(); holdIn("busy", processing_time); } else { holdIn("passive", INFINITY); } } } public message out() { message m = new message(); if (phaseIs("busy")) { switch (job.type) { case 'V': m.add(makeContent("out" + current_V, job)); current_V = (current_V == 0)? 3 : 0; break; case 'I': m.add(makeContent("out" + current_I, job)); current_I = (current_I == 1)? 4 : 1; break; case 'A': m.add(makeContent("out" + current_A, job)); current_A = (current_A == 2)? 5 : 2; break; default: break; } } return m; } public String getTooltipText() { return super.getTooltipText() + "\n" + "job: " + job.getName() + "\n" + "queue: " + q.toString() + "\n" + "Queue_CPU: " + Queue_CPU.toString() + "\n" + "Queue_RAM: " + Queue_RAM.toString() + "\n" + "Queue_NetResponse: " + Queue_NetResponse.toString(); } }
package com.hazelcast.jet.impl; import com.hazelcast.client.impl.clientside.DefaultClientExtension; import com.hazelcast.client.impl.clientside.HazelcastClientInstanceImpl; import com.hazelcast.jet.JetInstance; public class JetClientExtension extends DefaultClientExtension { private JetClientInstanceImpl jetClientInstance; @Override public void afterStart(HazelcastClientInstanceImpl client) { super.afterStart(client); jetClientInstance = new JetClientInstanceImpl(client); } @Override public JetInstance getJetInstance() { return jetClientInstance; } }
package com.jaiaxn.design.pattern.behavioral.template; /** * @author: wang.jiaxin * @date: 2019年08月27日 * @description: **/ public class Basketball extends Game { @Override void initialize() { System.out.println("Basketball Game initialized!"); } @Override void startPlay() { System.out.println("Basketball Game started!"); } @Override void endPlay() { System.out.println("Basketball Game Finished!"); } }
package algorithms.graph.practice; import java.util.Collections; import algorithms.graph.Digraph; import algorithms.graph.process.CycleDetection; import algorithms.graph.process.TopologicalSort; public class ReversePostTopoSort implements TopologicalSort { private boolean hasCycle; private Iterable<Integer> topoOrder; public void init(Digraph digraph) { CycleDetection cycleDetection = new DepthFirstDirectedCycleDetection(); cycleDetection.init(digraph); hasCycle = cycleDetection.hasCycle(); if (hasCycle) { topoOrder = Collections.emptyList(); return; } DepthFirstOrder order = new DepthFirstOrder(); order.init(digraph); topoOrder = order.reversePost(); } public boolean isDAG() { return !hasCycle; } public Iterable<Integer> sort() { return topoOrder; } }