text
stringlengths
10
2.72M
package pat.test; import pat.decorator.*; import pat.factory.*; import pat.observer.*; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub //Decorator pattern Computer com = new Computer(); com = new Disc(com); //add disc to com com = new Monitor(com); //add monitor to com com = new LiquidCooling(com); //add liquid cooling to com com = new LiquidCooling(com); //add liquid cooling to com System.out.println("You have purchased " + com.description() + "."); //Factory pattern FirstFactory factory = new FirstFactory("Oracle"); Connection con = factory.createConnection(); System.out.println("You are connected to : " + con.description()); FirstFactory factory2 = new FirstFactory("sql server"); con = factory2.createConnection(); System.out.println("You are connected to : " + con.description()); //Observer pattern Database database = new Database(); Archiver archiver = new Archiver(); Client client = new Client(); Boss boss = new Boss(); database.registerObserver(archiver); database.registerObserver(client); database.registerObserver(boss); database.editRecord("delete", "record 1"); } }
package listExamples; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.concurrent.CopyOnWriteArrayList; public class ArrayListExample { /** List(I) is the Child of Collection(I). * ArrayList (C) is one of the classes provides implementation for the List(I). * In list duplicate values are allowed and the insertion order is maintained. * The underlying DS is resizeable Array or Growable Array. We can insert Heterogeneous objects as well. * NOTE: All the collections can store Heterogeneous objects can be stored except TREE SET and TREE MAP. * ArraList and vector implements RandomAccess, Serializable and Cloneable Interfaces * Synchronized-> No * Thread safe-> NO * Default capacity-10 * Fill Ratio or Load factor:1 or 100% * Growth Rate: current_size + current_size/2 */ public void arrayListExample(){ //add() used to add the specified element at the end of the List List<String> arrayList= new ArrayList<String>(); arrayList.add("Audi"); arrayList.add("Benz"); arrayList.add("Bugatti"); arrayList.add("Aston martin"); System.out.println(arrayList); //add(int index, Object element) method will add at specified index position arrayList.add(0,"Mustang"); System.out.println(arrayList); //to check the indexof any element System.out.println("Index position of Audi is :"+arrayList.indexOf("Audi")); //-1 is returned if the element is not there System.out.println("Index position of Ambassador is :"+arrayList.indexOf("Ambassador")); //List allows duplicate elements arrayList.add("Mustang"); System.out.println(arrayList); //indexof always returns the first occurrence System.out.println("Index position of Mustang is :"+arrayList.indexOf("Mustang")); //last index of is used to check the last occurence position System.out.println("Last Index position of Mustang is :"+arrayList.lastIndexOf("Mustang")); // add a list to another list List<String> anotherList=new ArrayList<String>(); anotherList.addAll(arrayList); System.out.println("New List copied :"+ anotherList); //clear to delete all the elements anotherList.clear(); System.out.println("List after clearing "+anotherList); //we can even insert null anotherList.add(null); System.out.println("After adding null "+anotherList); anotherList.add("mango"); anotherList.add("Banana"); //adding list to a list at specified position. anotherList.addAll(0,arrayList); System.out.println("New list after adding the old list at 0th position :"+anotherList); //set() is used to update the element based on index anotherList.set(6, "Tata"); anotherList.set(7,"Civic"); System.out.println("List after updating the last two elements : "+anotherList); //remove(int position) removes the value at the specified position anotherList.remove(6); System.out.println("After removing :"+anotherList); //remove using object value anotherList.remove("Civic"); System.out.println("After removing Civic: "+ anotherList); /*get an element based on index position. If the index is not there we will get index out of bound exception*/ System.out.println("Element at 5th Position "+anotherList.get(5)); //isEmpty() method to check the list is empty or not System.out.println("This list is empty. True or False? "+ anotherList.isEmpty()); System.out.println(anotherList); //get all the elements in the list using for loop for(int size=0; size<anotherList.size();size++){ System.out.println("element at "+size+"th position " +anotherList.get(size)); } //fetch using advanced for loop for (String string : anotherList) { System.out.println("List elements "+string); } //forward traversing using ListIterator ListIterator<String> listIterator= anotherList.listIterator(); while(listIterator.hasNext()){ System.out.println("Forward Iteration : "+listIterator.next()); } // reverse Iteration using ListIterator while(listIterator.hasPrevious()){ System.out.println("Reverse Iteration : "+listIterator.previous()); } /*Iteration with Iterator (NOTE: Not ListIterator) Iterator can only traverse forward but not on reverse. Hence we are using ListIterator for better usages.*/ Iterator< String> iterator=anotherList.iterator(); while(iterator.hasNext()){ System.out.println("Forward Only:"+iterator.next()); } /* ArrayList is non-synchronized.It should not be used in multi-threaded * environment without explicit synchronization.Hence, * adding an element to the list when traversing through it * will give concurrent modification exception. * This is happening because when a thread is trying to read the elements * from the list another thread is trying to add or remove an element from the same. */ try{ for (String string : anotherList) { System.out.println("Reading the list values"+ string); anotherList.add("Mustang"); } } catch(Exception e){ System.out.println("Dude! You are trying to modify a list while a read operation is happening"); } } /* CopyOnWriteArrayList allows us to modify * the list while reading it */ public void syncArrayListExample(){ CopyOnWriteArrayList<String> syncal = new CopyOnWriteArrayList<String>(); //Adding elements to synchronized ArrayList syncal.add("Pen"); syncal.add("NoteBook"); syncal.add("Ink"); System.out.println("Iterating synchronized ArrayList:"); Iterator<String> syncIterator = syncal.iterator(); while (syncIterator.hasNext()){ System.out.println(syncIterator.next()); syncal.add("Eraser"); syncal.remove("Eraser"); } System.out.println("Final List: "+syncal); } public static void main(String[] args) { // TODO Auto-generated method stub ArrayListExample example= new ArrayListExample(); example.arrayListExample(); //example.syncArrayListExample(); } }
/* * 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 FORM; /** * * @author D4ve */ public class Usuario { private int PIDM; private String nombreUsuario; private String estLn; private int aux; public String getEstLn() { return estLn; } public void setEstLn(String estLn) { this.estLn = estLn; } /** * @return the PIDM */ public int getPIDM() { return PIDM; } /** * @param PIDM the PIDM to set */ public void setPIDM(int PIDM) { this.PIDM = PIDM; } public String getNombreUsuario() { return nombreUsuario; } public void setNombreUsuario(String nombreUsuario) { this.nombreUsuario = nombreUsuario; } }
package com.google.android.gms.analytics.internal; class m$1 implements Runnable { final /* synthetic */ boolean aFK; final /* synthetic */ m aFL; m$1(m mVar, boolean z) { this.aFL = mVar; this.aFK = z; } public final void run() { this.aFL.aFJ.nK(); } }
package com.bat.commoncode.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 响应结构体注解 * * @author ZhengYu * @version 1.0 2019/10/30 11:53 **/ @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface CodeEntity { boolean success(); int errCode() default 0; String msg(); }
package locks; import csc2227proj.Platform; import java.util.concurrent.atomic.AtomicIntegerArray; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; /** * * @author trbot */ public class Lock3 implements AbstractLock { private static final int HAS_LOCK = 1; private static final int MUST_WAIT = 0; // updater to perform CAS on ``next_slot'' private final static AtomicIntegerFieldUpdater<Lock3> up = AtomicIntegerFieldUpdater.newUpdater(Lock3.class, "next_slot"); // represents the process that currently has the right to hold the lock private volatile int next_slot = 0; private AtomicIntegerArray slots; private int my_place; private int nprocs; public Lock3(final int _nprocs) { assert(_nprocs > 0); nprocs = _nprocs; // note: following has the side-effect of initializing entries to MUST_WAIT slots = new AtomicIntegerArray(nprocs*Platform.SLOT_STEP_BOOL); slots.set(0, HAS_LOCK); } @Override public void acquire() throws Exception { int _my_place = up.getAndIncrement(this); if ((_my_place % nprocs) == 0) { up.getAndAdd(this, -nprocs); } _my_place %= nprocs; while (slots.get(_my_place) == MUST_WAIT); slots.set(_my_place, MUST_WAIT); // now that we've obtained the lock, we can use var. my_place safely my_place = _my_place; } @Override public void release() { // precondition: the calling process must hold the lock // note: this "my_place" must be the same as the last one obtained // in acquire(), by anderson's algorithm, since only // a process holding the lock can call release(). slots.set((my_place+1) % nprocs, HAS_LOCK); } }
package com.penzias.service; import com.penzias.core.interfaces.BasicService; import com.penzias.entity.SysUserModular; import com.penzias.entity.SysUserModularExample; public interface SysUserModularService extends BasicService<SysUserModularExample, SysUserModular> { }
package com.example.zealience.oneiromancy.entity; import android.os.Parcel; import android.os.Parcelable; /** * @user steven * @createDate 2019/3/20 15:16 * @description 首页数据正常的实体 */ public class HomeNormalEntity implements Parcelable { private String userName; private String userImage; private String photoUrl; private String content; public HomeNormalEntity() { } public HomeNormalEntity(String photoUrl, String userImage, String userName, String content) { this.photoUrl = photoUrl; this.userImage = userImage; this.userName = userName; this.content = content; } public String getPhotoUrl() { return photoUrl; } public void setPhotoUrl(String photoUrl) { this.photoUrl = photoUrl; } public String getUserImage() { return userImage; } public void setUserImage(String userImage) { this.userImage = userImage; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { } }
package com.tencent.mm.ui; import android.app.Activity; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import com.tencent.mm.platformtools.x; import com.tencent.mm.ui.base.b; class w$10 implements OnCancelListener { final /* synthetic */ Activity ews; final /* synthetic */ Intent tnx; w$10(Intent intent, Activity activity) { this.tnx = intent; this.ews = activity; } public final void onCancel(DialogInterface dialogInterface) { if (this.tnx != null) { if (!(this.ews instanceof LauncherUI)) { this.ews.finish(); } this.ews.startActivity(this.tnx); b.E(this.ews, this.tnx); x.ca(this.ews); } } }
package com.yida.design.command.demo.command; /** ********************* * 删除页面的命令 * * @author yangke * @version 1.0 * @created 2018年5月12日 上午10:32:20 *********************** */ public class DeletePageCommand extends AbstractCommand { @Override public void execute() { // 找到美工组 super.pageGroup.find(); // 删除页面 super.pageGroup.delete(); // 给出计划 super.pageGroup.plan(); } }
package com.home.closematch.mapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.home.closematch.entity.Message; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.home.closematch.entity.dto.BaseMessageDTO; import org.springframework.stereotype.Repository; import java.util.List; /** * @Entity com.home.closematch.entity.Message */ @Repository public interface MessageMapper extends BaseMapper<Message> { IPage<BaseMessageDTO> getGlobalMessage(Page<BaseMessageDTO> page); IPage<BaseMessageDTO> getUserSelfMessageByAccountId(Page<BaseMessageDTO> page, Long accountId); }
package JavaFX.Calendar; import javafx.fxml.Initializable; import javafx.geometry.Pos; import javafx.scene.control.ComboBox; import javafx.scene.control.DateCell; import javafx.scene.control.Label; import javafx.scene.effect.*; import javafx.scene.layout.*; import javafx.scene.paint.Color; import java.net.URL; import java.time.LocalDate; import java.time.Month; import java.util.ResourceBundle; import java.util.function.Supplier; public class formController implements Initializable { public GridPane grid; public ComboBox<Month> monthList; public Supplier<DateCell> dateCellSupplier; public Pane panelCalendar; @Override public void initialize(URL url, ResourceBundle resourceBundle) { cellInit(); monthListInit(); labelInit(); gridInit(); gridClear(); gridFill(LocalDate.now()); } private void labelInit() { panelCalendar.getChildren().stream() .filter(node -> node.getClass().getSimpleName().equals("Label")) .map(node -> (Label) node) .forEach(label -> { label.setAlignment(Pos.CENTER); label.setOnMouseClicked(event -> { if (label.getBackground() == null) { label.setStyle("-fx-background-color: #1b6cd7;" + "-fx-text-fill: #ffffff;" + "-fx-border-radius: 3;" + "-fx-background-radius: 3"); } else { label.setBackground(null); label.setStyle("-fx-text-fill: #898383"); } }); }); } private void cellInit() { dateCellSupplier = () -> { var cell = new DateCell(); cell.setStyle("-fx-font-weight: bold"); cell.setAlignment(Pos.CENTER); cell.setOnMouseEntered(event -> cell.setEffect(new DropShadow(15, Color.BLUE))); cell.setOnMouseExited(event -> cell.setEffect(null)); return cell; }; } private void gridInit() { for (int row = 0; row < grid.getRowCount(); row++) { for (int column = 0; column < grid.getColumnCount(); column++) { grid.add(dateCellSupplier.get(), column, row); } } grid.setGridLinesVisible(true); } private void gridClear() { for (int i = 1; i < grid.getChildren().size(); i++) { var newDate = (DateCell) grid.getChildren().get(i); newDate.setText(""); } } private void gridFill(LocalDate currentDate) { gridClear(); int currentYear = currentDate.getYear(); int currentMonth = currentDate.getMonthValue(); int currentMonthLength = currentDate.lengthOfMonth(); int index = LocalDate.of(currentYear, currentMonth, 1).getDayOfWeek().getValue(); int count = 1; for (int i = 0; i < currentMonthLength; i++) { var newDate = (DateCell) grid.getChildren().get(i + index); newDate.setText(String.valueOf(LocalDate.of(currentYear, currentMonth, count++).getDayOfMonth())); } } private void monthListInit() { monthList.getItems().addAll(Month.values()); monthList.setValue(LocalDate.now().getMonth()); monthList.setOnAction(event -> { Month selectedMonth = monthList.getSelectionModel().getSelectedItem(); gridFill(LocalDate.of(2021, selectedMonth, 1)); }); } }
package com.example.user.mychat; import android.app.Activity; import android.widget.Toast; import com.example.user.mychat.network.NetworkStateMonitor; import com.example.user.mychat.utils.ResourceUtil; public abstract class BaseActivity extends Activity implements NetworkStateMonitor.OnNetworkStateChangedListener{ protected abstract void networkSateChanged(boolean isConnected); @Override protected void onStart() { super.onStart(); NetworkStateMonitor.getInstance(this).registerListener(this); } @Override protected void onPause() { super.onPause(); NetworkStateMonitor.getInstance(this).unregisterListener(this); } @Override public void onNetworkStateChanged(NetworkStateMonitor networkStateMonitor) { if(networkStateMonitor.isConnected()){ networkSateChanged(true); }else{ networkSateChanged(false); } Toast.makeText(this, ResourceUtil.getString(this, R.string.alert_network_changed), Toast.LENGTH_LONG).show(); } }
package android.support.v7.widget; import android.support.v4.a.a; import android.support.v4.view.ai; import android.support.v4.view.z; import android.support.v7.widget.RecyclerView.t; import android.view.View; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class v extends aj { private ArrayList<t> NN = new ArrayList(); private ArrayList<t> NO = new ArrayList(); private ArrayList<b> NP = new ArrayList(); private ArrayList<a> NQ = new ArrayList(); ArrayList<ArrayList<t>> NR = new ArrayList(); ArrayList<ArrayList<b>> NS = new ArrayList(); ArrayList<ArrayList<a>> NT = new ArrayList(); ArrayList<t> NU = new ArrayList(); ArrayList<t> NV = new ArrayList(); ArrayList<t> NW = new ArrayList(); ArrayList<t> NX = new ArrayList(); public void eR() { int i; int i2; int i3; int i4 = !this.NN.isEmpty() ? 1 : 0; if (this.NP.isEmpty()) { i = 0; } else { i = 1; } if (this.NQ.isEmpty()) { i2 = 0; } else { i2 = 1; } if (this.NO.isEmpty()) { i3 = 0; } else { i3 = 1; } if (i4 != 0 || i != 0 || i3 != 0 || i2 != 0) { ArrayList arrayList; Runnable 1; Iterator it = this.NN.iterator(); while (it.hasNext()) { t tVar = (t) it.next(); ai U = z.U(tVar.SU); this.NW.add(tVar); U.h(this.RW).t(0.0f).a(new 4(this, tVar, U)).start(); } this.NN.clear(); if (i != 0) { arrayList = new ArrayList(); arrayList.addAll(this.NP); this.NS.add(arrayList); this.NP.clear(); 1 = new 1(this, arrayList); if (i4 != 0) { z.a(((b) arrayList.get(0)).Oq.SU, 1, this.RW); } else { 1.run(); } } if (i2 != 0) { arrayList = new ArrayList(); arrayList.addAll(this.NQ); this.NT.add(arrayList); this.NQ.clear(); 1 = new 2(this, arrayList); if (i4 != 0) { z.a(((a) arrayList.get(0)).Ok.SU, 1, this.RW); } else { 1.run(); } } if (i3 != 0) { ArrayList arrayList2 = new ArrayList(); arrayList2.addAll(this.NO); this.NR.add(arrayList2); this.NO.clear(); Runnable 3 = new 3(this, arrayList2); if (i4 == 0 && i == 0 && i2 == 0) { 3.run(); return; } long j; long j2; long j3 = i4 != 0 ? this.RW : 0; if (i != 0) { j = this.RX; } else { j = 0; } if (i2 != 0) { j2 = this.RY; } else { j2 = 0; } z.a(((t) arrayList2.get(0)).SU, 3, j3 + Math.max(j, j2)); } } } public boolean b(t tVar) { e(tVar); this.NN.add(tVar); return true; } public boolean c(t tVar) { e(tVar); z.d(tVar.SU, 0.0f); this.NO.add(tVar); return true; } public boolean a(t tVar, int i, int i2, int i3, int i4) { View view = tVar.SU; int Q = (int) (((float) i) + z.Q(tVar.SU)); int R = (int) (((float) i2) + z.R(tVar.SU)); e(tVar); int i5 = i3 - Q; int i6 = i4 - R; if (i5 == 0 && i6 == 0) { y(tVar); return false; } if (i5 != 0) { z.b(view, (float) (-i5)); } if (i6 != 0) { z.c(view, (float) (-i6)); } this.NP.add(new b(tVar, Q, R, i3, i4, (byte) 0)); return true; } public boolean a(t tVar, t tVar2, int i, int i2, int i3, int i4) { if (tVar == tVar2) { return a(tVar, i, i2, i3, i4); } float Q = z.Q(tVar.SU); float R = z.R(tVar.SU); float G = z.G(tVar.SU); e(tVar); int i5 = (int) (((float) (i3 - i)) - Q); int i6 = (int) (((float) (i4 - i2)) - R); z.b(tVar.SU, Q); z.c(tVar.SU, R); z.d(tVar.SU, G); if (tVar2 != null) { e(tVar2); z.b(tVar2.SU, (float) (-i5)); z.c(tVar2.SU, (float) (-i6)); z.d(tVar2.SU, 0.0f); } this.NQ.add(new a(tVar, tVar2, i, i2, i3, i4, (byte) 0)); return true; } private void a(List<a> list, t tVar) { for (int size = list.size() - 1; size >= 0; size--) { a aVar = (a) list.get(size); if (a(aVar, tVar) && aVar.Ok == null && aVar.Ol == null) { list.remove(aVar); } } } private void a(a aVar) { if (aVar.Ok != null) { a(aVar, aVar.Ok); } if (aVar.Ol != null) { a(aVar, aVar.Ol); } } private boolean a(a aVar, t tVar) { if (aVar.Ol == tVar) { aVar.Ol = null; } else if (aVar.Ok != tVar) { return false; } else { aVar.Ok = null; } z.d(tVar.SU, 1.0f); z.b(tVar.SU, 0.0f); z.c(tVar.SU, 0.0f); k(tVar); return true; } public void d(t tVar) { int size; ArrayList arrayList; View view = tVar.SU; z.U(view).cancel(); for (size = this.NP.size() - 1; size >= 0; size--) { if (((b) this.NP.get(size)).Oq == tVar) { z.c(view, 0.0f); z.b(view, 0.0f); y(tVar); this.NP.remove(size); } } a(this.NQ, tVar); if (this.NN.remove(tVar)) { z.d(view, 1.0f); k(tVar); } if (this.NO.remove(tVar)) { z.d(view, 1.0f); k(tVar); } for (size = this.NT.size() - 1; size >= 0; size--) { List list = (ArrayList) this.NT.get(size); a(list, tVar); if (list.isEmpty()) { this.NT.remove(size); } } for (int size2 = this.NS.size() - 1; size2 >= 0; size2--) { arrayList = (ArrayList) this.NS.get(size2); int size3 = arrayList.size() - 1; while (size3 >= 0) { if (((b) arrayList.get(size3)).Oq == tVar) { z.c(view, 0.0f); z.b(view, 0.0f); y(tVar); arrayList.remove(size3); if (arrayList.isEmpty()) { this.NS.remove(size2); } } else { size3--; } } } for (size = this.NR.size() - 1; size >= 0; size--) { arrayList = (ArrayList) this.NR.get(size); if (arrayList.remove(tVar)) { z.d(view, 1.0f); k(tVar); if (arrayList.isEmpty()) { this.NR.remove(size); } } } this.NW.remove(tVar); this.NU.remove(tVar); this.NX.remove(tVar); this.NV.remove(tVar); eS(); } private void e(t tVar) { a.v(tVar.SU); d(tVar); } public boolean isRunning() { return (this.NO.isEmpty() && this.NQ.isEmpty() && this.NP.isEmpty() && this.NN.isEmpty() && this.NV.isEmpty() && this.NW.isEmpty() && this.NU.isEmpty() && this.NX.isEmpty() && this.NS.isEmpty() && this.NR.isEmpty() && this.NT.isEmpty()) ? false : true; } final void eS() { if (!isRunning()) { fZ(); } } public final void eT() { int size; for (size = this.NP.size() - 1; size >= 0; size--) { b bVar = (b) this.NP.get(size); View view = bVar.Oq.SU; z.c(view, 0.0f); z.b(view, 0.0f); y(bVar.Oq); this.NP.remove(size); } for (size = this.NN.size() - 1; size >= 0; size--) { k((t) this.NN.get(size)); this.NN.remove(size); } for (size = this.NO.size() - 1; size >= 0; size--) { t tVar = (t) this.NO.get(size); z.d(tVar.SU, 1.0f); k(tVar); this.NO.remove(size); } for (size = this.NQ.size() - 1; size >= 0; size--) { a((a) this.NQ.get(size)); } this.NQ.clear(); if (isRunning()) { int size2; ArrayList arrayList; int size3; for (size2 = this.NS.size() - 1; size2 >= 0; size2--) { arrayList = (ArrayList) this.NS.get(size2); for (size3 = arrayList.size() - 1; size3 >= 0; size3--) { b bVar2 = (b) arrayList.get(size3); View view2 = bVar2.Oq.SU; z.c(view2, 0.0f); z.b(view2, 0.0f); y(bVar2.Oq); arrayList.remove(size3); if (arrayList.isEmpty()) { this.NS.remove(arrayList); } } } for (size2 = this.NR.size() - 1; size2 >= 0; size2--) { arrayList = (ArrayList) this.NR.get(size2); for (size3 = arrayList.size() - 1; size3 >= 0; size3--) { t tVar2 = (t) arrayList.get(size3); z.d(tVar2.SU, 1.0f); k(tVar2); arrayList.remove(size3); if (arrayList.isEmpty()) { this.NR.remove(arrayList); } } } for (size2 = this.NT.size() - 1; size2 >= 0; size2--) { arrayList = (ArrayList) this.NT.get(size2); for (size3 = arrayList.size() - 1; size3 >= 0; size3--) { a((a) arrayList.get(size3)); if (arrayList.isEmpty()) { this.NT.remove(arrayList); } } } j(this.NW); j(this.NV); j(this.NU); j(this.NX); fZ(); } } private static void j(List<t> list) { for (int size = list.size() - 1; size >= 0; size--) { z.U(((t) list.get(size)).SU).cancel(); } } public boolean a(t tVar, List<Object> list) { return !list.isEmpty() || super.a(tVar, list); } }
package com.lyq.model; import javax.persistence.*; //章管理 @Entity @Table(name="t_zhang") public class Zhang { @Id @GeneratedValue(strategy= GenerationType.AUTO) private Integer zid; //主键Id private String zname;//章名称 private Integer mid; //对应目录id // @Transient private String mname;//目录名称 public String getMname() { return mname; } public void setMname(String mname) { this.mname = mname; } public Integer getZid() { return zid; } public void setZid(Integer zid) { this.zid = zid; } public String getZname() { return zname; } public void setZname(String zname) { this.zname = zname; } public Integer getMid() { return mid; } public void setMid(Integer mid) { this.mid = mid; } }
package com.example.user.simplelife; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.CheckBox; import android.widget.ExpandableListView; import android.widget.ImageButton; import android.widget.Toast; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class AddFavoriteActivity extends Activity { ExpandListAdapter listAdapter; ExpandableListView listView; ArrayList<Expandable_Parent> expListItems; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_favorite); listView = (ExpandableListView) findViewById(R.id.expandableListView); expListItems = prepareListData(); if(expListItems!=null) listAdapter = new ExpandListAdapter (AddFavoriteActivity.this, expListItems); if(listAdapter!=null) listView.setAdapter(listAdapter); ImageButton btnBack = (ImageButton) findViewById(R.id.ibtnBack_addfavorite); btnBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(AddFavoriteActivity.this, ApplianceActivity.class); Bundle bundle = new Bundle(); bundle.putInt("type", 1); ArrayList<String> temp = new ArrayList<>(); for(int i=0;i<expListItems.size();i++) { ArrayList<Expandable_Child> childs = expListItems.get(i).getItems(); for(int j=0;j<childs.size();j++) { Expandable_Child child = childs.get(j); if(child.isChecked())temp.add(child.getName()); } } //bundle.putSerializable("Favorite",temp); ObjectWriter.WriteObject(temp,"FAVORITE.fav"); intent.putExtras(bundle); startActivity(intent); } }); } private ArrayList<Expandable_Parent> prepareListData() { String parentNames[] = { "Light", "Air Conditioner", "Television", "Other" }; int images[] = { R.drawable.light_icon, R.drawable.air_icon, R.drawable.tv_icon, R.drawable.other_icon_white }; //String childNames[] = { // "living room","kitchen" //}; //ArrayList<String> childNames = new ArrayList<>(); ArrayList<Expandable_Parent> list = new ArrayList<>(); ArrayList<String> mclist=null; if(new File("sdcard/MC_ID").exists()) { mclist = ObjectReader.loadMC("MC_ID"); ArrayList<Appliance> appliances = new ArrayList<>(); for (int i = 0; i < mclist.size(); i++) { String mcName = mclist.get(i); MainController mc = ObjectReader.loadMainController(mcName); ArrayList<Appliance> temp = mc.getAppliances(); for (int j = 0; j < temp.size(); j++) appliances.add(j, temp.get(j)); } for (int i = 0; i < parentNames.length; i++) { Expandable_Parent parent = new Expandable_Parent(); ArrayList<Expandable_Child> chList; parent.setImage(images[i]); parent.setName(parentNames[i]); chList = new ArrayList<>(); String pName = parentNames[i]; ArrayList<String> childNames = null; if (pName.equals("Light")) { ArrayList<String> tempS = new ArrayList<>(); for (int k = 0; k < appliances.size(); k++) { Appliance app = appliances.get(k); if (app.getType().equals("Light")) tempS.add(app.getName()); } childNames = tempS; } else if (pName.equals("Air Conditioner")) { ArrayList<String> tempS = new ArrayList<>(); for (int k = 0; k < appliances.size(); k++) { Appliance app = appliances.get(k); if (app.getType().equals("AC")) tempS.add(app.getName()); } childNames = tempS; } else if (pName.equals("Television")) { ArrayList<String> tempS = new ArrayList<>(); for (int k = 0; k < appliances.size(); k++) { Appliance app = appliances.get(k); if (app.getType().equals("TV")) tempS.add(app.getName()); } childNames = tempS; } else if (pName.equals("Other")) { ArrayList<String> tempS = new ArrayList<>(); for (int k = 0; k < appliances.size(); k++) { Appliance app = appliances.get(k); if (app.getType().equals("Other")) tempS.add(app.getName()); } childNames = tempS; } for (int j = 0; j < childNames.size(); j++) { Expandable_Child child = new Expandable_Child(); child.setName(childNames.get(j)); chList.add(child); } parent.setItems(chList); list.add(parent); } } return list; } @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_add_favorite, 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); } }
/* * Copyright 2013 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.overlord.rtgov.ui.client.shared.services; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.overlord.rtgov.ui.client.model.ApplicationListBean; import org.overlord.rtgov.ui.client.model.ReferenceBean; import org.overlord.rtgov.ui.client.model.ServiceBean; import org.overlord.rtgov.ui.client.model.ServiceResultSetBean; import org.overlord.rtgov.ui.client.model.ServicesSearchBean; import org.overlord.rtgov.ui.client.model.UiException; /** * Provides a way to manage services. * * @author eric.wittmann@redhat.com */ @Path("/rest/services") public interface IServicesService { /** * Return a list of all application names. * @throws UiException */ @GET @Path("applications") @Produces(MediaType.APPLICATION_JSON) public ApplicationListBean getApplicationNames() throws UiException; /** * Search for services using the given search criteria. * @param search * @param page * @param sortColumn * @param ascending * @throws UiException */ @POST @Path("search") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public ServiceResultSetBean findServices(ServicesSearchBean search) throws UiException; /** * Fetches a full service by its id. * @param id * @throws UiException */ @GET @Path("service") @Produces(MediaType.APPLICATION_JSON) public ServiceBean getService(@QueryParam("id") String id) throws UiException; /** * Fetches a full reference by its id. * @param id * @throws UiException */ @GET @Path("reference") @Produces(MediaType.APPLICATION_JSON) public ReferenceBean getReference(@QueryParam("id") String id) throws UiException; }
package com.example.SBNZ.service; import java.util.ArrayList; import java.util.List; import com.example.SBNZ.model.Person; import com.example.SBNZ.model.User; import com.example.SBNZ.repository.DietRepository; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.QueryResults; import org.kie.api.runtime.rule.QueryResultsRow; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import com.example.SBNZ.enums.diet.MealType; import com.example.SBNZ.model.diet.Diet; import com.example.SBNZ.model.diet.InputDataDiet; import com.example.SBNZ.model.diet.Meal; import com.example.SBNZ.model.diet.SearchDiet; import com.example.SBNZ.repository.MealRepository; @Service public class DietService { @Autowired private KieService kieService; @Autowired private MealService mealService; @Autowired private DietRepository dietRepository; @Autowired private UserService userService; public Diet getDiet(InputDataDiet inputData) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Person person = (Person) authentication.getPrincipal(); User user = userService.findByUsername(person.getUsername()); String username = person.getUsername(); KieSession kieSession = kieService.getKieSession(username, "basic"); List<Meal> meals = mealService.findAll(); for (Meal meal: meals) { kieSession.insert(meal); } // inputData.setMeals(new ArrayList<>()); kieSession.insert(inputData); kieSession.getAgenda().getAgendaGroup("Ruleflow1").setFocus(); kieSession.fireAllRules(); kieService.clearWorkingMemory(username, "basic"); Diet saved = dietRepository.save(inputData.getDiet()); user.setDiet(saved); userService.update(user); return inputData.getDiet(); } public List<Meal> getMeals(SearchDiet input){ KieSession kieSession = kieService.generateQuerySession(); InputDataDiet mockInput = new InputDataDiet(); mockInput.setMeals(mealService.findAll()); kieSession.insert(mockInput); QueryResults results; input = checkSearchDietInput(input); if (!input.getMealType().equals("")) { results = kieSession.getQueryResults("Recommend meals with mealtype", MealType.valueOf(input.getMealType()),input.getKcalFrom(),input.getKcalTo() ,input.getProteinFrom(),input.getProteinTo(),input.getFatFrom(), input.getFatTo(), input.getCarbsFrom(),input.getCarbsTo()); } else { results = kieSession.getQueryResults("Recommend meals without mealtype", input.getKcalFrom(),input.getKcalTo() ,input.getProteinFrom(),input.getProteinTo(),input.getFatFrom(), input.getFatTo(), input.getCarbsFrom(),input.getCarbsTo()); } for(QueryResultsRow queryResult : results) { List<Meal> meals = (List<Meal>) queryResult.get("$filteredMeals"); kieSession.dispose(); return meals; } kieSession.dispose(); return null; } private SearchDiet checkSearchDietInput(SearchDiet input) { if (input.getCarbsTo() == 0) { input.setCarbsTo(1000000); } if (input.getFatTo() == 0) { input.setFatTo(10000000); } if (input.getKcalTo() == 0) { input.setKcalTo(10000000); } if (input.getProteinTo() == 0) { input.setProteinTo(10000000); } return input; } public Diet findByUser() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Person person = (Person) authentication.getPrincipal(); return userService.findByUsername(person.getUsername()).getDiet(); } }
package com.atgem.googleplay; import android.app.ActionBar; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import bean.FixBarber; import bean.OrderShop; import bean.ServcePrice; import bean.Url; import com.atgem.ailisidemo.WorksActivity; import com.atgem.ailisidemo.activity.ShopActivity; import com.atgem.lunbodemo.HomeActivity; import com.lidroid.xutils.HttpUtils; import com.lidroid.xutils.exception.HttpException; import com.lidroid.xutils.http.RequestParams; import com.lidroid.xutils.http.ResponseInfo; import com.lidroid.xutils.http.callback.RequestCallBack; import com.lidroid.xutils.http.client.HttpRequest; public class PaySucessActivity extends Activity { TextView tvOrderName; TextView yuyuema; TextView return_home; TextView continueshop; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.paysuccess); tvOrderName=(TextView) findViewById(R.id.tv_odername); yuyuema=(TextView) findViewById(R.id.yuyuema); FixBarber barber=(FixBarber)getIntent().getSerializableExtra("bar"); OrderShop shop= (OrderShop) getIntent().getSerializableExtra("shop"); final ServcePrice sPrice=(ServcePrice) getIntent().getSerializableExtra("price"); Bundle bundle=new Bundle(); bundle.putSerializable("bar", barber); bundle.putSerializable("shop",shop); bundle.putSerializable("price", sPrice); tvOrderName.setText(shop.getS_name()+"预约券"); showAcitonBar(); SharedPreferences sp = getSharedPreferences("orderId",MODE_PRIVATE); SharedPreferences sharedPreferences = getSharedPreferences("yuyuema", MODE_PRIVATE); SharedPreferences.Editor editor=sharedPreferences.edit(); int i=(int) (Math.random()*1000+10000); editor.putInt("res_num", i); editor.commit(); yuyuema.setText(i+""); RequestParams params = new RequestParams(); params.addHeader("name", "value"); params.addQueryStringParameter("name", "value"); // 只包含字符串参数时默认使用BodyParamsEntity, // 类似于UrlEncodedFormEntity("application/x-www-form-urlencoded")。 params.addBodyParameter("o_id",String.valueOf(sp.getInt("o_id",0))); params.addBodyParameter("res_num",String.valueOf(i)); // 加入文件参数后默认使用MultipartEntity("multipart/form-data"), // 如需"multipart/related",xUtils中提供的MultipartEntity支持设置subType为"related"。 // 使用params.setBodyEntity(httpEntity)可设置更多类型的HttpEntity(如: // MultipartEntity,BodyParamsEntity,FileUploadEntity,InputStreamUploadEntity,StringEntity)。 // 例如发送json参数:params.setBodyEntity(new StringEntity(jsonStr,charset)); HttpUtils http = new HttpUtils(); http.send(HttpRequest.HttpMethod.POST, Url.url+":8080/Alisi2/AddReservationServlet", params, new RequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String> responseInfo) { Toast.makeText(PaySucessActivity.this,"订阅成功...",Toast.LENGTH_SHORT).show(); } @Override public void onFailure(HttpException error, String msg) { Toast.makeText(PaySucessActivity.this,"订阅失败...",Toast.LENGTH_SHORT).show(); } }); return_home=(TextView) findViewById(R.id.tv_returnhome); return_home.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub Intent intent=new Intent(PaySucessActivity.this,HomeActivity.class); startActivity(intent); } }); continueshop=(TextView) findViewById(R.id.tv_continuebuy); continueshop.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub Intent intent2=new Intent(PaySucessActivity.this,ShopActivity.class); startActivity(intent2); } }); } public void showAcitonBar(){ ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); ActionBar.LayoutParams lp =new ActionBar.LayoutParams( ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER); LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View titleView = inflater.inflate(R.layout.action_bar_title, null); actionBar.setCustomView(titleView, lp); actionBar.setDisplayShowHomeEnabled(false);//去掉导航 actionBar.setDisplayShowTitleEnabled(false);//去掉标题 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); actionBar.setDisplayShowCustomEnabled(true); TextView tv_title=(TextView) actionBar.getCustomView().findViewById(R.id.title); tv_title.setText("支付成功"); ImageButton imageBtn = (ImageButton) actionBar.getCustomView().findViewById(R.id.image_btn); imageBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } }
package uw.cse.dineon.library; import java.util.ArrayList; import java.util.List; import uw.cse.dineon.library.image.DineOnImage; import uw.cse.dineon.library.util.ParseUtil; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseUser; /** * This class represents a Restaurant. Where internally * the class can tracks its profile representation and List of current * and old restaurant transactions. * @author zachr81, mhotan */ public class Restaurant extends Storable { // Parse used Keys public static final String RESERVATION_LIST = "reservationList"; public static final String INFO = "restaurantInfo"; public static final String PAST_ORDERS = "pastOrders"; public static final String PENDING_ORDERS = "pendingOrders"; public static final String PAST_USERS = "pastUsers"; public static final String SESSIONS = "restaurantDiningSessions"; public static final String CUSTOMER_REQUESTS = "customerRequests"; /** * Restaurant information. */ private final RestaurantInfo mRestInfo; /** * Past Orders placed at this restaurant. * Also includes any recently placed orders. */ private final List<Order> mPastOrders; /** * Past Orders placed at this restaurant. * Also includes any recently placed orders. */ private final List<Order> mPendingOrders; /** * Past users that have visited the restaurant. */ private final List<UserInfo> mPastUsers; /** * Currently pending reservations. */ private final List<Reservation> mReservations; /** * Currently Active Dining sessions. */ private final List<DiningSession> mSessions; /** * Customer request that is not associated with the restaurant. */ private final List<CustomerRequest> mCustomerRequests; /** * Temporary order used for persistent data references. */ private Order tempOrder; /** * Temporary request to store persistent reference. */ private CustomerRequest tempRequest; /** * Temporary dining session for a persistent reference. */ private DiningSession tempDiningSession; /** * Create a bare bones Restaurant with just a name. * TODO Add basic constraints to creating a restaurant * @param user of Restaurant * @throws ParseException */ public Restaurant(ParseUser user) throws ParseException { super(Restaurant.class); mRestInfo = new RestaurantInfo(user); mPastOrders = new ArrayList<Order>(); mPastUsers = new ArrayList<UserInfo>(); mPendingOrders = new ArrayList<Order>(); mReservations = new ArrayList<Reservation>(); mSessions = new ArrayList<DiningSession>(); mCustomerRequests = new ArrayList<CustomerRequest>(); } /** * Creates a Restaurant object from the given ParseObject. * * @param po Parse object to build from * @throws ParseException */ public Restaurant(ParseObject po) throws ParseException { super(po); mRestInfo = new RestaurantInfo(po.getParseObject(INFO)); mPastOrders = ParseUtil.toListOfStorables(Order.class, po.getList(PAST_ORDERS)); mPastUsers = ParseUtil.toListOfStorables(UserInfo.class, po.getList(PAST_USERS)); mPendingOrders = ParseUtil.toListOfStorables( Order.class, po.getList(PENDING_ORDERS)); mReservations = ParseUtil.toListOfStorables( Reservation.class, po.getList(RESERVATION_LIST)); mSessions = ParseUtil.toListOfStorables(DiningSession.class, po.getList(SESSIONS)); mCustomerRequests = ParseUtil.toListOfStorables( CustomerRequest.class, po.getList(CUSTOMER_REQUESTS)); } @Override public ParseObject packObject() { ParseObject po = super.packObject(); po.put(INFO, mRestInfo.packObject()); // Pack up old stuff po.put(PAST_ORDERS, ParseUtil.toListOfParseObjects(mPastOrders)); po.put(PAST_USERS, ParseUtil.toListOfParseObjects(mPastUsers)); // Pack current stuff po.put(PENDING_ORDERS, ParseUtil.toListOfParseObjects(mPendingOrders)); po.put(RESERVATION_LIST, ParseUtil.toListOfParseObjects(mReservations)); po.put(SESSIONS, ParseUtil.toListOfParseObjects(mSessions)); po.put(CUSTOMER_REQUESTS, ParseUtil.toListOfParseObjects(mCustomerRequests)); return po; } ///////////////////////////////////////////////////// //// Setter methods ///////////////////////////////////////////////////// /** * Returns the name of this restaurant. * @return Name */ public String getName() { return mRestInfo.getName(); } /** * Returns reference to Restaurant Info Object. * NOTE: Permissions to change Information is not protected * @return RestaurantInfo */ public RestaurantInfo getInfo() { return mRestInfo; } /** * Returns a list copy of Customer Requests. * @return the customerRequests that this restaurant is aware of */ public List<CustomerRequest> getCustomerRequests() { return new ArrayList<CustomerRequest>(mCustomerRequests); } /** * Returns a list of all current reservations that the Restaurant has tracked. * * @return List<Reservation> */ public List<Reservation> getReservationList() { return new ArrayList<Reservation>(mReservations); } /** * Returns the current list of past orders placed at the restaurant. * @return List<Order> of past orders placed at the restaurant. */ public List<Order> getPastOrders() { return new ArrayList<Order>(mPastOrders); } /** * Returns the current Dining Session which contains the user * or null if there is no dining session for that user. * @param user User to find in a dining session * @return null if no dining session has user, else dining session that contains user. */ public DiningSession getDiningSession(UserInfo user) { for (DiningSession d : getSessions()) { if (d.hasUser(user)) { return d; } } return null; } /** * Gets the dining session assocaited with tableID. * @param tableId Table ID of the dining session to find * @return null if no dining session has user, else dining session for tableID */ public DiningSession getDiningSession(int tableId) { for (DiningSession d: getSessions()) { if (d.getTableID() == tableId) { return d; } } return null; } /** * List of current running dining sessions. * @return List<DiningSession> */ public List<DiningSession> getSessions() { return new ArrayList<DiningSession>(mSessions); } /** * Each one of the restaurants have pending dining sessions. * Returns all the orders of all the pending dining sessions. * @return a list of all pending orders */ public List<Order> getPendingOrders() { return new ArrayList<Order>(mPendingOrders); } ///////////////////////////////////////////////////// //// Setter methods ///////////////////////////////////////////////////// /** * Add a new customer request. * @param newReq request to add */ public void addCustomerRequest(CustomerRequest newReq) { mCustomerRequests.add(newReq); } /** * Adds the given reservation to the reservation list. * @param newReservation to add */ public void addReservation(Reservation newReservation) { mReservations.add(newReservation); } /** * Marks this Order as complete. * @param order Order that has been completed. */ public void completeOrder(Order order) { if (order == null) { return; } // Move from list of pending orders to // list of past orders if (mPendingOrders.remove(order)) { mPastOrders.add(order); } } /** * Cancels current order if it exists. * @param order Order to cancel. */ public void cancelPendingOrder(Order order) { mPendingOrders.remove(order); } /** * Adds a pending order to a restaurant. * @param order Order to be added. cannot be null. */ public void addOrder(Order order) { if (order == null) { throw new NullPointerException("Order being added to restaurant is null"); } mPendingOrders.add(order); } /** * Adds given DiningSession to sessions. * @param session to add */ public void addDiningSession(DiningSession session) { if (session == null) { // Invalid input return; } if (mSessions.contains(session)) { // Already tracking this session return; } mSessions.add(session); } /** * Deletes this dining session from the cloud and the restaurant. * @param session */ public void removeDiningSession(DiningSession session) { if (session == null) { return; } //Remove pending orders List<Order> orders = session.getOrders(); for (Order o : orders) { mPendingOrders.remove(o); } //Remove customer requests List<CustomerRequest> requests = session.getRequests(); for (CustomerRequest r : requests) { mCustomerRequests.remove(r); } // If we found the session. if (mSessions.remove(session)) { mPastUsers.addAll(session.getUsers()); session.deleteFromCloud(); } } /** * Remove the specified CustomerRequest. * @param oldReq request to remove */ public void removeCustomerRequest(CustomerRequest oldReq) { mCustomerRequests.remove(oldReq); } /** * Remove the specified reservation. * @param removeReservation from restaurant */ public void removeReservation(Reservation removeReservation) { mReservations.remove(removeReservation); // TODO Delete the reservation from parse } /** * Clears all the past orders from this restaurant. */ public void clearPastOrders() { // TODO For each of the Orders delete from parse mPastOrders.clear(); } /** * Adds image associated to this image. * @param image Image to add. */ public synchronized void addImage(DineOnImage image) { mRestInfo.addImage(image); } /** * Remove image. * @param image Image to remove. */ public synchronized void removeImage(DineOnImage image) { mRestInfo.removeImage(image); } /** * Updates the current user if it exists in the restaurant. * @param user User to update */ public void updateUser(UserInfo user) { if (user == null) { return; } // NOTE (MH) Because we have to replace the old version // of this user with a current version. // We have to check for object ID equality to find the object to replace // Find the UserInfo to remove in past users UserInfo toRemove = null; for (UserInfo info : mPastUsers) { if (info.getObjId().equals(user.getObjId())) { toRemove = info; } } // Effectively replaces. if (toRemove != null) { mPastUsers.remove(toRemove); mPastUsers.add(user); } // Find the user if they exist in the past . for (DiningSession session: mSessions) { toRemove = null; for (UserInfo sessionUser: session.getUsers()) { // Find the user to remove. if (sessionUser.getObjId().equals(user.getObjId())) { toRemove = sessionUser; break; } } // Remove and replace new user if (toRemove != null) { session.removeUser(toRemove); session.addUser(user); } } } @Override public void deleteFromCloud() { for (Order order: mPastOrders) { order.deleteFromCloud(); } for (Order order: mPendingOrders) { order.deleteFromCloud(); } for (Reservation reservation: mReservations) { reservation.deleteFromCloud(); } for (CustomerRequest request: mCustomerRequests) { request.deleteFromCloud(); } mRestInfo.deleteFromCloud(); super.deleteFromCloud(); } /** * Permanently deletes the dining session of this. * @param session to remove */ public void delete(DiningSession session) { mSessions.remove(session); // Remove all references the the customer request to be removed. for (CustomerRequest req: session.getRequests()) { mCustomerRequests.remove(req); } session.deleteFromCloud(); // Save the restaurant immediately this.saveInBackGround(null); } /** * Sets the temporary order reference for this restaurant. * This temporary variable only survives as long as the user * is logged in and as long * @param order Temporary order to set. */ public void setTempOrder(Order order) { tempOrder = order; } /** * Temporary order set by setTempOrder. * @return temporary order reference, null if no reference is set */ public Order getTempOrder() { return tempOrder; } /** * Sets the temporary Customer request reference for this restaurant. * This temporary variable only survives as long as the user * is logged in and as long * @param request Temporary request, or null if you want to remove any temporary request. */ public void setTempRequest(CustomerRequest request) { tempRequest = request; } /** * Gets the temporary request set by setTempRequest. * @return Temporary request, or null if none is available */ public CustomerRequest getTempCustomerRequest() { return tempRequest; } /** * Sets the temporary dining Session reference for this restaurant. * This temporary variable only survives as long as the user * is logged in and as long * @param session Temporary Dining Session, or null if you want to remove any temporary request. */ public void setTempDiningSession(DiningSession session) { tempDiningSession = session; } /** * Gets the temporary dining session set by setTempDiningSession. * @return Temporary dining session, or null if none is available */ public DiningSession getTempDiningSession() { return tempDiningSession; } // /** // * Creates a restaurant from a parcel. // * @param source Source to build from // */ // public Restaurant(Parcel source) { // super(source); // mRestInfo = source.readParcelable(RestaurantInfo.class.getClassLoader()); // // mPastOrders = new ArrayList<Order>(); // mPendingOrders = new ArrayList<Order>(); // mPastUsers = new ArrayList<UserInfo>(); // mReservations = new ArrayList<Reservation>(); // mSessions = new ArrayList<DiningSession>(); // mCustomerRequests = new ArrayList<CustomerRequest>(); // // source.readTypedList(mPastOrders, Order.CREATOR); // source.readTypedList(mPendingOrders, Order.CREATOR); // source.readTypedList(mPastUsers, UserInfo.CREATOR); // source.readTypedList(mReservations, Reservation.CREATOR); // source.readTypedList(mSessions, DiningSession.CREATOR); // source.readTypedList(mCustomerRequests, CustomerRequest.CREATOR); // } // // /** // * Write the object to a parcel object. // * @param dest the Parcel to write to // * @param flags to set // */ // @Override // public void writeToParcel(Parcel dest, int flags) { // super.writeToParcel(dest, flags); // dest.writeParcelable(mRestInfo, flags); // dest.writeTypedList(mPastOrders); // dest.writeTypedList(mPendingOrders); // dest.writeTypedList(mPastUsers); // dest.writeTypedList(mReservations); // dest.writeTypedList(mSessions); // dest.writeTypedList(mCustomerRequests); // } // // /** // * Parcelable creator object of a Restaurant. // * Can create a Restaurant from a Parcel. // */ // public static final Parcelable.Creator<Restaurant> CREATOR = // new Parcelable.Creator<Restaurant>() { // // @Override // public Restaurant createFromParcel(Parcel source) { // return new Restaurant(source); // } // // @Override // public Restaurant[] newArray(int size) { // return new Restaurant[size]; // } // }; }
package com.tencent.mm.plugin.appbrand.jsapi.file; import com.tencent.mm.plugin.appbrand.appstorage.AppBrandLocalMediaObject; import com.tencent.mm.plugin.appbrand.appstorage.AppBrandLocalMediaObjectManager; import com.tencent.mm.plugin.appbrand.jsapi.a; import com.tencent.mm.plugin.appbrand.l; import com.tencent.mm.sdk.platformtools.bi; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.json.JSONArray; import org.json.JSONObject; public final class q extends a { private static final int CTRL_INDEX = 115; private static final String NAME = "getSavedFileList"; public final void a(l lVar, JSONObject jSONObject, int i) { List<AppBrandLocalMediaObject> listStoredFiles = AppBrandLocalMediaObjectManager.listStoredFiles(lVar.mAppId); JSONArray jSONArray = new JSONArray(); if (!bi.cX(listStoredFiles)) { for (AppBrandLocalMediaObject appBrandLocalMediaObject : listStoredFiles) { try { JSONObject jSONObject2 = new JSONObject(); jSONObject2.put("filePath", appBrandLocalMediaObject.bNH); jSONObject2.put("size", appBrandLocalMediaObject.eyz); jSONObject2.put("createTime", TimeUnit.MILLISECONDS.toSeconds(appBrandLocalMediaObject.fjU)); jSONArray.put(jSONObject2); } catch (Exception e) { } } } Map hashMap = new HashMap(1); hashMap.put("fileList", jSONArray); lVar.E(i, f("ok", hashMap)); } }
package testRouleTaBoule.elements; import testRouleTaBoule.graphics.ImagesSprites; public class ElementLimite extends Element { public ElementLimite(Coordonnees coord) { super(coord, ImagesSprites.limite); } public boolean isSolid() { return true; } }
package com.app.main.service; import java.util.List; import com.app.main.dto.User; public interface IuserService { List<User> getAllUsers(); User getUserById(String email); void addUser(User user); void deleteUser(String email); void updateUser(User user, String email); String validate(String email,String pwd); }
package com.linkedbook.configuration; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.util.Base64; import static java.nio.charset.StandardCharsets.UTF_8; public class AES128 { private final String ips; private final Key keySpec; public AES128(String key) { byte[] keyBytes = new byte[16]; byte[] b = key.getBytes(UTF_8); System.arraycopy(b, 0, keyBytes, 0, keyBytes.length); SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES"); this.ips = key.substring(0, 16); this.keySpec = keySpec; } public String encrypt(String value) throws NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(ips.getBytes())); byte[] encrypted = cipher.doFinal(value.getBytes(UTF_8)); return new String(Base64.getEncoder().encode(encrypted)); } public String decrypt(String value) throws NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(ips.getBytes(UTF_8))); byte[] decrypted = Base64.getDecoder().decode(value.getBytes()); return new String(cipher.doFinal(decrypted), UTF_8); } }
package com.jaisonbrooks.github.treehouse.crystalmagic.app; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.Typeface; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextSwitcher; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewSwitcher; import java.util.Random; public class MainActivity extends ActionBarActivity implements View.OnClickListener { private String answer; private TextSwitcher answerSwitcher; private TextView answerTextView; private int[] colors; private CrystalMagic crystalMagic = new CrystalMagic(); private Typeface robotoThin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewByIds(); initialize(); setupTextSwitcher(); } private void findViewByIds() { Button askCrystal = (Button) findViewById(R.id.btn_answer); askCrystal.setOnClickListener(this); } public void initialize() { answer = getString(R.string.title_answer); colors = getApplication().getResources().getIntArray(R.array.colors); } private void setupTextSwitcher() { String temp = "\"" + answer + "\""; answerSwitcher = (TextSwitcher) findViewById(R.id.textSwitcher); // Set the ViewFactory of the TextSwitcher that will create TextView object when asked answerSwitcher.setFactory(new ViewSwitcher.ViewFactory() { public View makeView() { answerTextView = new TextView(MainActivity.this); float textSize = getResources().getDimension(R.dimen.activity_answer_textsize); answerTextView.setTextSize(textSize); answerTextView.setTextColor(getResources().getColor(android.R.color.holo_purple)); answerTextView.setTypeface(Typeface.createFromAsset(getAssets(),"Roboto-Thin.ttf")); return answerTextView; } }); Animation in = AnimationUtils.loadAnimation(this, android.R.anim.fade_in); in.setDuration(350); Animation out = AnimationUtils.loadAnimation(this,android.R.anim.fade_out); out.setDuration(350); answerSwitcher.setInAnimation(in); // set the animation type of textSwitcher answerSwitcher.setOutAnimation(out); // set the animation type of textSwitcher answerSwitcher.setText(temp); } @Override public void onClick(View view) { // Set answer to UI String magicAnswer = crystalMagic.getAnswer(); answerSwitcher.setText("\"" + magicAnswer + "\""); Log.d("onClick", "Your Answer is " + "\"" + magicAnswer + "\""); int x = crystalMagic.getInt(); answerTextView.setTextColor(crystalMagic.getInt()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.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(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package com.ibeiliao.pay.api.enums; /** * 支付订单的状态列表 * @author linyi 2016/7/11. */ public enum PaymentStatus { /** * 支付成功 */ SUCCESS((byte)1, "支付成功"), /** * 支付失败 */ FAILURE((byte)2, "支付失败"), /** * 等待支付 */ WAITING_FOR_PAYMENT((byte)3, "等待支付"); /** * 状态值 */ private byte status; /** * 状态名 */ private String message; private PaymentStatus(byte status, String message) { this.status = status; this.message = message; } public byte getStatus() { return status; } public String getMessage() { return message; } }
package com.semester_project.smd_project.Activities; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.ContextCompat; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.semester_project.smd_project.R; import org.jetbrains.annotations.NotNull; public class SignIn extends AppCompatActivity { private Button signinbtnclicked; private TextView forgotpassclick, createnewaccount; private EditText user_email, user_password; private FirebaseAuth SigninMe; private FirebaseAuth.AuthStateListener mAuthListener; private ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_in); signinbtnclicked = findViewById(R.id.signbtn); forgotpassclick = findViewById(R.id.forgotpassword); createnewaccount = findViewById(R.id.createaccount); user_email = findViewById(R.id.useremail); user_password = findViewById(R.id.userpassword); progressBar = findViewById(R.id.progressbar1); SigninMe = FirebaseAuth.getInstance(); ShowPassowrd(user_password); signinbtnclicked.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String emailId = user_email.getText().toString(); String password = user_password.getText().toString(); HideKeyboard(getApplicationContext()); if(emailId.isEmpty()) { user_email.setError("Please, Enter Email ID"); user_email.requestFocus(); } else if (password.isEmpty()) {user_password.setError("Please, Enter Password"); user_password.requestFocus(); } else if (password.isEmpty() && emailId.isEmpty()) { Toast.makeText(getApplicationContext(), "Please, fill all the fields!", Toast.LENGTH_LONG).show(); } else if (!password.isEmpty() && !emailId.isEmpty()) { progressBar.setVisibility(View.VISIBLE); SigninMe.signInWithEmailAndPassword(emailId, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()) { Intent intohom = new Intent (SignIn.this, MainActivity.class); intohom.putExtra("UID", emailId); startActivity(intohom); progressBar.setVisibility(View.GONE); finish(); } else { Toast.makeText(getApplicationContext(), "Not Signed In !", Toast.LENGTH_LONG).show(); progressBar.setVisibility(View.GONE); } } }); } else { HideKeyboard(SignIn.this); } } }); forgotpassclick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent forgotpassclickedintent = new Intent (SignIn.this, PasswordRecovery.class); HideKeyboard(getApplicationContext()); startActivity(forgotpassclickedintent); finish(); } }); createnewaccount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent createaccountclickedintent = new Intent (SignIn.this, SignUp.class); HideKeyboard(getApplicationContext()); startActivity(createaccountclickedintent); } }); } @SuppressLint("ClickableViewAccessibility") public void ShowPassowrd(@NotNull final EditText pass) { pass.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { final int DRAWABLE_LEFT = 0; final int DRAWABLE_RIGHT = 2; final int DRAWABLE_BOTTOM = 3; if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getX() >= (pass.getRight() - pass.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { pass.setCompoundDrawables(ContextCompat.getDrawable(getApplicationContext(), R.drawable.password), null, ContextCompat.getDrawable(getApplicationContext(), R.drawable.invisible), null); pass.setInputType(1); return true; } } return false; } }); } public void HideKeyboard(Context c) { InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); View view = getCurrentFocus(); if (view == null) { view = new View(c); } imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } }
package interviews.facebook; import common.TrieNode; /** * Author: Meng Zhou * Code time: 23 minutes * Compile Error: 0 * Runtime Error: 1 * Time of Improvement: 2 * */ public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } // Inserts a word into the trie. public void insert(String word) { if(word == null || word.length() == 0) return; TrieNode head = root; for(char c : word.toCharArray()) { if(head.nodes[c - 'a'] == null) { head.nodes[c - 'a'] = new TrieNode(); } head = head.nodes[c - 'a']; } head.end = true; } // Returns if the word is in the trie. public boolean search(String word) { if(word == null || word.length() == 0) return false; TrieNode head = root; for(char c : word.toCharArray()) { if(head.nodes[c - 'a'] == null) return false; head = head.nodes[c - 'a']; } return head.end; } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { if(prefix == null || prefix.length() == 0) return false; TrieNode head = root; for(char c : prefix.toCharArray()) { if(head.nodes[c - 'a'] == null) return false; head = head.nodes[c - 'a']; } return true; } }
package com.connectis.programator.demo.dom.minecraft4; import java.util.ArrayList; import java.util.List; public class BlockIron extends Block { private List<Tool> strongEnoughToolList; public BlockIron() { strongEnoughToolList = new ArrayList<>(); strongEnoughToolList.add(new PickAxe(Tool.Material.STONE)); strongEnoughToolList.add(new PickAxe(Tool.Material.STEEL)); } public boolean isToolStrongEnough(Tool tool) { boolean result = false; for (Tool strongTool : strongEnoughToolList) { if (strongTool.equals(tool)) { result = true; } } return result; } @Override public List<Item> gather(Tool tool) { if (this.isToolStrongEnough(tool)) { return super.gather(tool); } return new ArrayList<>(); } }
package com.tencent.mm.plugin.voip.ui; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.tencent.mm.R; public class VoipSmallIconButton extends FrameLayout { private TextView ih; private ImageView isa; private Drawable oQK = null; private Drawable oQL = null; private OnTouchListener oQM = new 1(this); public void setOnClickListener(OnClickListener onClickListener) { this.isa.setOnClickListener(onClickListener); } public VoipSmallIconButton(Context context, AttributeSet attributeSet) { CharSequence charSequence = 0; super(context, attributeSet); LayoutInflater.from(context).inflate(R.i.layout_voip_small_icon_button, this); TypedArray obtainStyledAttributes = context.getTheme().obtainStyledAttributes(attributeSet, R.n.VoipButton, 0, 0); try { this.oQK = obtainStyledAttributes.getDrawable(R.n.VoipButton_iconRes); this.oQL = obtainStyledAttributes.getDrawable(R.n.VoipButton_iconResPressed); charSequence = obtainStyledAttributes.getString(R.n.VoipButton_iconTip); int resourceId = obtainStyledAttributes.getResourceId(R.n.VoipButton_iconTip, -1); this.isa = (ImageView) findViewById(R.h.small_icon_button); this.isa.setImageDrawable(this.oQK); this.isa.setOnTouchListener(this.oQM); this.isa.setContentDescription(charSequence); this.ih = (TextView) findViewById(R.h.small_icon_text); if (resourceId != -1) { this.ih.setText(getContext().getString(resourceId)); } } finally { obtainStyledAttributes.recycle(); } } public void setEnabled(boolean z) { this.isa.setEnabled(z); this.ih.setEnabled(z); } }
package edu.weber; public class Data { /** Computes the average of the measures of the given objects. @param objects an array of Measurable objects @return the average of the measures */ public static double average(Measurable[] objects) { double sum = 0; for (Measurable obj : objects) { sum = sum + obj.getMeasure(); } if (objects.length > 0) { return sum / objects.length; } else { return 0; } } public static Measurable max(Measurable[] objects) //method used to get the measure of a value in an object array { Measurable maxObject = objects[0]; //starts max object with the first for (int i = 0; i < objects.length; i++) //loops to the length of the array { if(i != objects.length - 1) //if NOT at the end of the array { if (objects[i].getMeasure() > objects[i + 1].getMeasure()) { //checks measure of current item with next maxObject = objects[i]; //if the new item is larger assign it to max } } else if(objects[i].getMeasure() > objects[i - 1].getMeasure()) //if end item is larger than previous { maxObject = objects[i]; //assign it to max object } } return maxObject; } }
package collections.optinal; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class SortList { public static ArrayList<String> sortList(String path) throws IOException { ArrayList<String> list = new ArrayList<>(); FileReader reader = new FileReader(path); Scanner scanner = new Scanner(reader); while (scanner.hasNextLine()) { list.add(scanner.nextLine()); } Collections.sort(list); scanner.close(); reader.close(); return list; } }
import java.util.ArrayList; public class Test { int a = 100; }
/* * Model Class containing the data structure for the model */ package finalproject; import java.util.ArrayList; /** * * @author Bart Kooijmans */ public class Model { private String modelType; private boolean elementPresent; private ArrayList<Element> elements; private ArrayList<String> linkedModels; /** * Constructor for an empty model of the given type. * * @param type String representing the type of the model to be created, values are limited to the list generated y the ModelController class */ protected Model(String type) { modelType = type; elementPresent = false; elements = new ArrayList<Element>(); linkedModels = new ArrayList<String>(); } /** * Contructor for the model class for an existing model * * @param type String representing the type of the model to be created, values are limited to the list generated y the ModelController class * @param present boolean representing if elements are present within the model (Would normally always be true for existing models) * @param existingE ArrayList of elements representing the models primary elements of the model (These contain all the connection and inner elements within it) * @param existingModels Arraylist of Stringa containing the relative path to linked models */ protected Model(String type, boolean present, ArrayList<Element> existingE, ArrayList<String> existingModels) { modelType = type; elementPresent = present; elements = existingE; linkedModels = existingModels; } /** * Standard get function for the boolean representing if elements are present within the model * * @return boolean elementPresent */ protected boolean getElementPresent() { return elementPresent; } /** * Returns the string containing/representing the type of the model. * * @return String modelType */ protected String getModelType() { return modelType; } /** * Returns an ArrayList of the Element object instance that make up the model, top level elements all other elements and connections are contained within these. * * @return ArrayList of Element instances elements */ protected ArrayList<Element> getElements() { return elements; } /** * Set method for elementPresent which is the boolean representing if elements are present (true) or not (false) * * @param updatedStatus */ protected void setElementPresent(boolean updatedStatus) { elementPresent = updatedStatus; } /** * Return an ArrayList of string containing the relative path to all models linked to this model as a whole * * @return ArryList of Strings linkedModels */ protected ArrayList<String> getLinkedModels() { return linkedModels; } }
package org.usfirst.frc.team4716.robot.subsystems; import org.usfirst.frc.team4716.robot.RobotMap; import org.usfirst.frc.team4716.robot.commands.drivetrain.ACSJoystickDrive; import edu.wpi.first.wpilibj.DoubleSolenoid; import edu.wpi.first.wpilibj.DoubleSolenoid.Value; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.Gyro; import edu.wpi.first.wpilibj.Talon; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * */ public class ACSDriveTrain extends Subsystem { public double iGainHG = .05; // a lower iGain for the public double iGainLG = .03; // low gear prevents jerky movements private double leftPower = 0, rightPower = 0; private boolean isHighGear; public final double RIGHT_ENCOCDER_TO_DISTANCE_RATIO = (6 * Math.PI) / (12.0 * 255.0); public final double LEFT_ENCOCDER_TO_DISTANCE_RATIO = (6 * Math.PI) / (12.0 * 255.0); // Speed controllers private Talon leftDriveA = new Talon(RobotMap.leftDrivePortA); private Talon leftDriveB = new Talon(RobotMap.leftDrivePortB); private Talon leftDriveC = new Talon(RobotMap.leftDrivePortC); private Talon rightDriveA = new Talon(RobotMap.rightDrivePortA); private Talon rightDriveB = new Talon(RobotMap.rightDrivePortB); private Talon rightDriveC = new Talon(RobotMap.rightDrivePortC); // Encoders private Encoder leftEncoder = new Encoder(RobotMap.leftEncoderPortA, RobotMap.leftEncoderPortB, false); private Encoder rightEncoder = new Encoder(RobotMap.rightEncoderPortA, RobotMap.rightEncoderPortB, true); // Solenoids private DoubleSolenoid shifter = new DoubleSolenoid(RobotMap.shifterPortHigh, RobotMap.shifterPortLow); // Gyro public Gyro gyro; public ACSDriveTrain() { super("Drivebase"); gyro = new Gyro(RobotMap.gyroPort); } // Default Command public void initDefaultCommand() { setDefaultCommand(new ACSJoystickDrive()); } //Set Speed of Drive Train public void setLeftRightPower(double leftPower, double rightPower) { leftDriveA.set(leftPower); leftDriveB.set(leftPower); leftDriveC.set(leftPower); rightDriveA.set(-rightPower); rightDriveB.set(-rightPower); rightDriveC.set(-rightPower); } //Set Gear of Drive Train regardless of prior position public void setGear(boolean isHigh) { if (isHigh == true) { shifter.set(DoubleSolenoid.Value.kForward); isHighGear = false; } else if (isHigh == false) { shifter.set(DoubleSolenoid.Value.kReverse); isHighGear = true; } else { if (getGearState() == DoubleSolenoid.Value.kForward) { isHigh = true; setGear(isHigh); } else { isHigh = false; setGear(isHigh); } } } //Set Speed for near Perfect Turns (Test before to find desired angle) public void setSpeedAngleTurn(double _speed, double _angle, boolean _isRight) { double leftpow, rightpow; if (_isRight == true && Math.abs(gyro.getAngle()) < _angle) { rightpow = _speed; setLeftRightPower(0, rightpow); } else if (_isRight == false && Math.abs(gyro.getAngle()) < _angle) { leftpow = _speed; setLeftRightPower(leftpow, 0); } } //Set Speed to Drive Straight, adjust kP for less jerky movements. public void setSpeedDriveStraight(double _speed) { double rightpow, leftpow; double angle = gyro.getAngle(); double kP = 0.02; if (2 < angle) { rightpow = _speed - kP * angle; setLeftRightPower(rightpow, _speed); } else if (-2 > angle) { leftpow = _speed + kP * angle; setLeftRightPower(_speed, leftpow); } else { setLeftRightPower(_speed, _speed); } } public void setRightSP(double rightPower) { this.rightPower = rightPower; } public void setLeftSP(double leftPower) { this.leftPower = leftPower; } // value is defined by either kReverse, kForward or kOff public Value getGearState() { return shifter.get(); } //The rest of the getters, straight forward// public Encoder getLeftEncoder() { return leftEncoder; } public double getLeftEncoderDistance() { // in feet return leftEncoder.get() * LEFT_ENCOCDER_TO_DISTANCE_RATIO; } public double getLeftEncoderDistanceInMeters() { return getLeftEncoderDistance() * 0.3048; } public Encoder getRightEncoder() { return rightEncoder; } public double getRightEncoderDistance() { return rightEncoder.get() * RIGHT_ENCOCDER_TO_DISTANCE_RATIO; } public double getRightEncoderDistanceInMeters() { return getRightEncoderDistance() * 0.3048; } public double getGyroAngle() { return -gyro.getAngle(); } public double getGyroAngleInRadians() { return (getGyroAngle() * Math.PI) / 180.0; } public double getAverageDistance() { return (getRightEncoderDistance() + getLeftEncoderDistance()) / 2.0; } public double getLeftSP() { return leftPower; } public double getRightSP() { return rightPower; } //Sensor Resets// public void resetEncoders() { leftEncoder.reset(); rightEncoder.reset(); } public void resetGyro() { gyro.reset(); } //Smart Dashboard Update// public void update() { SmartDashboard.putNumber("driveLeftEncoder", getLeftEncoderDistance()); SmartDashboard.putNumber("driveRightEncoder", getRightEncoderDistance()); SmartDashboard.putNumber("gyro", getGyroAngle()); // super.update(); } }
import java.util.*; import java.util.function.*; import java.util.stream.*; public class ExaggeratingList<T> implements List<T>{ private ArrayList<T> underlying = new ArrayList<>(); private final int SMALL_VALUE_SIZE; public static final int DEFAULT_SMALL_VALUE_SIZE = 5; public ExaggeratingList() { this(DEFAULT_SMALL_VALUE_SIZE); } public ExaggeratingList(Integer smallValueSize) { SMALL_VALUE_SIZE = smallValueSize; } public boolean add(T o) { return underlying.add(o); } public void add(int i, T o) { underlying.add(i, o); } public boolean addAll(Collection<? extends T> c) { return underlying.addAll(c); } public boolean addAll(int i, Collection<? extends T> c) { return underlying.addAll(i, c); } public void clear() { underlying.clear(); } public boolean contains(Object o) { return underlying.contains(o); } public boolean containsAll(Collection<?> o) { return underlying.contains(o); } public void forEach(Consumer<? super T> c) { underlying.forEach(c); } public T get(int i) { return underlying.get(i); } public int indexOf(Object o){ return underlying.indexOf(o); } public boolean isEmpty() { return underlying.isEmpty(); } public Iterator<T> iterator() { return underlying.iterator(); } public int lastIndexOf(Object o) { return underlying.lastIndexOf(o); } public ListIterator<T> listIterator() { return underlying.listIterator(); } public ListIterator<T> listIterator(int i) { return underlying.listIterator(i); } public Stream<T> parallelStream() { return underlying.parallelStream(); } public boolean remove(Object o) { return underlying.remove(o); } public T remove(int i) { return underlying.remove(i); } public boolean removeAll(Collection<?> c) { return underlying.removeAll(c); } public boolean removeIf(Predicate<? super T> p) { return underlying.removeIf(p); } public void replaceAll(UnaryOperator<T> u) { underlying.replaceAll(u); } public boolean retainAll(Collection<?> c) { return underlying.retainAll(c); } public T set(int i, T o) { return underlying.set(i, o); } public int size() { return 2 * underlying.size(); } public void sort(Comparator<? super T> c) { underlying.sort(c); } public Spliterator<T> spliterator() { return underlying.spliterator(); } public Stream<T> stream() { return underlying.stream(); } public List<T> subList(int i, int j) { return underlying.subList(i, j); } @SuppressWarnings("unchecked") public Object[] toArray() { return underlying.toArray(); } @SuppressWarnings("unchecked") public <T> T[] toArray(T[] array) { return underlying.toArray(array); } }
package com.yixin.kepler.enity;/** * Created by liushuai2 on 2018/6/9. */ import com.yixin.common.system.domain.BZBaseEntiy; import com.yixin.common.system.util.Label; import javax.persistence.Column; /** * Package : com.yixin.kepler.enity * * @author YixinCapital -- liushuai2 * 2018年06月09日 19:11 */ public class AssetRule extends BZBaseEntiy{ /** * 规则 */ @Label(name = "规则") @Column(name = "rule", length = 255) protected String rule; /** * 规则类型 */ @Label(name = "规则类型") @Column(name = "rule_type", length = 16) protected String ruleType; /** * 输出类脚本 */ @Label(name = "输出类脚本") @Column(name = "script", columnDefinition = "LONGTEXT") protected String script; /** * 规则依赖的字段,使用逗号分隔 */ @Label(name = "规则依赖的字段,使用逗号分隔") @Column(name = "fields", length=256) protected String fields; public String getRule() { return rule; } public void setRule(String rule) { this.rule = rule; } public String getRuleType() { return ruleType; } public void setRuleType(String ruleType) { this.ruleType = ruleType; } public String getScript() { return script; } public void setScript(String script) { this.script = script; } public String getFields() { return fields; } public void setFields(String fields) { this.fields = fields; } }
package com.rawls.ai; public abstract interface iPlayerAI extends iAI{ }
package br.com.desafio.models; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * Utilizado as anotações do Lombok para reduzir boilerplate na aplicação. * @author Windows * */ @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Entity(name= "sala_evento") public class SalaEventoEntity { @Id @Column private Integer id; @Column private String nome; @Column private Integer lotacao; }
/******************************************************************************* * Copyright 2020 Grégoire Martinetti * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package org.gmart.devtools.java.serdes.codeGen.javaGen.model.serialization.impls; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.stream.Collectors; import java.util.stream.Stream; import org.gmart.devtools.java.serdes.codeGen.javaGen.model.serialization.SerializableObjectBuilder; import org.gmart.devtools.java.serdes.codeGen.javaGen.model.serialization.SerializerProvider; public class YamlSerializerProvider implements SerializerProvider<Object> { public static class YamlSerializableObjectBuilder implements SerializableObjectBuilder<Object> { private final LinkedHashMap<String, Object> objectBuilder; public YamlSerializableObjectBuilder() { super(); this.objectBuilder = new LinkedHashMap<>(); } @Override public void addProperty(String name, Object value) { objectBuilder.put(name, value); } @Override public Object build() { return objectBuilder; } } @Override public SerializableObjectBuilder<Object> makeObjectSerializer() { return new YamlSerializableObjectBuilder(); } @Override public Object makeSerializablePrimitive(Object toSerialize, int primitiveIndex) { return toSerialize; } @Override public Object makeSerializableString(String str) { return str; } @Override public Object makeSerializableList(Stream<Object> toSerialize) { return toSerialize.collect(Collectors.toCollection(ArrayList::new)); } }
package com.ricex.cartracker.androidrequester.request.user; import com.ricex.cartracker.androidrequester.request.AbstractRequest; import com.ricex.cartracker.androidrequester.request.ApplicationPreferences; import com.ricex.cartracker.androidrequester.request.response.RequestResponse; import com.ricex.cartracker.androidrequester.request.exception.RequestException; import com.ricex.cartracker.androidrequester.request.type.BooleanResponseType; import com.ricex.cartracker.common.auth.AuthUser; /** A Server Request to login to the server to obtain a Session Token. * * The login is performed with a username and password * * @author Mitchell Caisse * */ public class LoginPasswordRequest extends AbstractRequest<Boolean> { /** The user's username */ private final String username; /** The user's password */ private final String password; /** Creates a new Instance of Password Request * * @param username The username to login with * @param password The password to login with */ public LoginPasswordRequest(ApplicationPreferences applicationPreferences, String username, String password) { super(applicationPreferences); this.username = username; this.password = password; } /** Executes the request * * @return The AFTResponse representing the results of the request * @throws RequestException If an error occurred while making the request */ protected RequestResponse<Boolean> executeRequest() throws RequestException { AuthUser user = new AuthUser(username, password); return postForObject(getPasswordLoginAddress(), user, new BooleanResponseType()); } }
/* * 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 lab_3_sd; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; /** * * @author Nelson */ public class ClientStart { public static int puerto_index; public static int puerto_cache; public static int puerto_front; public static int nParticiones; public static String stopwords; public static ArrayList<String> palabras = new ArrayList<>(); /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException, Exception { // Lectura de parametros FileReader fr = new FileReader("FrontConf.ini"); if(fr == null){ System.out.println("Archivo erroneo"); System.exit(1); } BufferedReader bf = new BufferedReader(fr); String parametro; int counter = 0; while( (parametro = bf.readLine() ) != null ){ if(parametro.charAt(0) != '/'){ switch (counter) { case 0: puerto_front = Integer.parseInt(parametro); System.out.println("parametro " + counter + ": " + puerto_front); break; case 1: nParticiones = Integer.parseInt(parametro); System.out.println("parametro " + counter + ": " + nParticiones); break; case 2: puerto_index = Integer.parseInt(parametro); System.out.println("parametro " + counter + ": " + puerto_index); break; case 3: puerto_cache = Integer.parseInt(parametro); System.out.println("parametro " + counter + ": " + puerto_cache); break; case 4: stopwords = parametro; System.out.println("parametro " + counter + ": " + stopwords); break; default: System.out.println("parametro " + counter + ": " + parametro + "no es usado"); break; } counter++; } } fr.close(); bf.close(); ServerSocket ssock = new ServerSocket(puerto_front); System.out.println("Listening..."); while (true) { Socket sock = ssock.accept(); System.out.println("Connected"); new Thread(new MultiThreadServer(sock, nParticiones)).start(); } } // public static String GET(String sentence) throws IOException{ // String fromServer; // //// FileReader fr = new FileReader("FrontConf.ini"); //// BufferedReader bf = new BufferedReader(fr); //// String parametro; //// parametro = bf.readLine(); //// parametro = bf.readLine(); //// int port = Integer.parseInt(parametro); // // System.out.println("el puerto es: " + 1324); // // // estructura improvisada // sentence = "GET /consulta/" + sentence; // String[] requests = {sentence}; // // for (String request : requests) { // //Buffer para enviar el dato al server // try ( //Socket para el cliente (host, puerto) // // Socket clientSocket = new Socket("localhost", 1324)) { // //Buffer para enviar el dato al server // DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); // //Buffer para recibir dato del servidor // BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // //Leemos del cliente y lo mandamos al servidor // outToServer.writeBytes(request + '\n'); // //Recibimos del servidor // fromServer = inFromServer.readLine(); // System.out.println("Server response: " + fromServer); // //Cerramos el socket // } // } // return sentence; // } public static String filtrarSW(String cadena) throws FileNotFoundException, IOException { try (FileReader xr = new FileReader("C:\\Users\\Nelson\\Documents\\NetBeansProjects\\LAB3_SD\\stop-words-spanish.txt")) { // try (FileReader xr = new FileReader("C:\\Users\\Amaranta Saball\\Documents\\NetBeansProjects\\LAB3_SD\\stop-words-spanish.txt")) { if(xr == null){ System.out.println("Archivo erroneo"); System.exit(1); } try (BufferedReader xf = new BufferedReader(xr)) { palabras = new ArrayList(); String aux1; while( (aux1 = xf.readLine() ) != null ){ palabras.add(aux1); } xf.close(); } xr.close(); System.out.println("lista de " + palabras.size() + " stopwords"); } // reemplazamos caracteres especiales cadena = cadena.replaceAll("[Ñ]","N"); cadena = cadena.replaceAll("[ñ]","n"); cadena = cadena.replaceAll("[èéêë]","e"); cadena = cadena.replaceAll("[ùúûü]","u"); cadena = cadena.replaceAll("[ìíîï]","i"); cadena = cadena.replaceAll("[àáâä]","a"); cadena = cadena.replaceAll("[òóôö]","o"); cadena = cadena.replaceAll("[ÈÉÊË]","E"); cadena = cadena.replaceAll("[ÙÚÛÜ]","U"); cadena = cadena.replaceAll("[ÌÍÎÏ]","I"); cadena = cadena.replaceAll("[ÀÁÂÄ]","A"); cadena = cadena.replaceAll("[ÒÓÔÖ]","O"); cadena = cadena.replaceAll("[|.,<>=/:;]"," "); cadena = cadena.replaceAll("[^a-z \\nA-Z]",""); cadena = cadena.replaceAll("\\s+", " "); cadena = cadena.toLowerCase(); cadena = cadena.trim(); // eliminamos las stopwords, los espacios aseguran no eliminar parte de palabras for (int i = 0; i < palabras.size(); i++) { String aux = "\\b"+palabras.get(i)+"\\b"; cadena = cadena.replaceAll( aux , ""); } return cadena; } }
package sqltojava; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.Date; /** * java变sql * @author gq * @time 2017年5月18日 */ public class JavaToSql { public static void main(String[] args) { File sql=new File("src/sqltojava/java.txt"); Date date=new Date(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd-HHmmss"); File history=new File("src/sqltojava/history/java-"+sdf.format(date)+".txt"); File historyJava=new File("src/sqltojava/history/sql-"+sdf.format(date)+".txt"); File sqlReult=new File("src/sqltojava/sqlResult.txt"); copyDeal(sql, history,historyJava,sqlReult); System.out.println("执行成功。"); } public static void copyDeal(File fromfile,File sourcefile,File tofile,File tofileCopy){ BufferedReader br = null; BufferedWriter bwCopy =null; BufferedWriter bw =null; BufferedWriter bw2 =null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream(fromfile),"utf-8")); bwCopy = new BufferedWriter(new FileWriter(sourcefile)); bw = new BufferedWriter(new FileWriter(tofile)); bw2 = new BufferedWriter(new FileWriter(tofileCopy)); String line=null; while( (line = br.readLine()) != null){ bwCopy.write(line); bwCopy.newLine(); //line="+ \" "+line+" \""; line=line.substring(3, line.length()-2); // System.out.println(line); bw.write(line); bw.newLine(); bw2.write(line); bw2.newLine(); } bw.flush(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (br != null) br.close(); if (bw != null) bw.close(); if (bwCopy != null) bwCopy.close(); if (bw2 != null) bw2.close(); } catch (IOException e) { e.printStackTrace(); } } } }
package com.ilp.innovations.myapplication.Fragments; import android.app.ProgressDialog; import android.app.SearchManager; import android.content.Context; import android.content.DialogInterface; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.SearchView; import android.widget.TextView; import android.widget.Toast; import com.github.kevinsawicki.http.HttpRequest; import com.ilp.innovations.myapplication.R; import com.ilp.innovations.myapplication.Beans.Slot; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Map; public class UnAllocatedSlotsFragment extends Fragment implements View.OnClickListener{ private final String ARG_SECTION_NUMBER = "section_number"; private CheckBox selectAll; private ListView slotList; private ProgressDialog pDialog; private ArrayList<Slot> slots; private SlotAdapter slotAdapter; private Drawable question; public boolean searchBySlot; private SearchManager searchManager; private SearchView searchView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); question = getResources().getDrawable(R.drawable.questionmark); } public UnAllocatedSlotsFragment newInstance() { UnAllocatedSlotsFragment fragment = new UnAllocatedSlotsFragment(); return fragment; } public UnAllocatedSlotsFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Toast.makeText(getActivity().getApplicationContext(),"in unallocatedslotsfragment",Toast.LENGTH_SHORT).show(); View rootView = inflater.inflate(R.layout.fragment_main, container, false); selectAll = (CheckBox) rootView.findViewById(R.id.selectAll); slotList = (ListView) rootView.findViewById(R.id.slotList); selectAll.setVisibility(View.GONE); slots = new ArrayList<Slot>(); slotAdapter = new SlotAdapter(slots); slotList.setAdapter(slotAdapter); Slot s1 = new Slot(1,"","A1"); Slot s2 = new Slot(2,"","A2"); Slot s3 = new Slot(3,"","A3"); slots.add(s1); slots.add(s2); slots.add(s3); slotAdapter.notifyDataSetChanged(); pDialog = new ProgressDialog(getActivity()); pDialog.setCancelable(false); slotList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); final EditText txtNewSlot = new EditText(getActivity()); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); txtNewSlot.setLayoutParams(lp); txtNewSlot.setHint(getResources().getString(R.string.txt_new_slot_num)); builder.setTitle("CHANGE VEHICLE"); builder.setMessage("Selected Slot : " +slots.get(position).getSlot()+"\n\n"); builder.setView(txtNewSlot); builder.setPositiveButton("CHANGE", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String regId = txtNewSlot.getText().toString(); slots.get(position).setRegId(regId); slotAdapter.notifyDataSetChanged(); //do something to update slot vehicle } }); builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); //builder.setView(inflater.inflate(R.layout.activity_dialogue, null)); AlertDialog confirmAlert = builder.create(); confirmAlert.show(); } }); return rootView; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // Inflate the menu items for use in the action bar inflater.inflate(R.menu.menu_main, menu); if(searchBySlot) { menu.findItem(R.id.search_slot).setIcon(getResources().getDrawable(R.drawable.check)); menu.findItem(R.id.search_reg_num).setIcon(null); } else { menu.findItem(R.id.search_reg_num).setIcon(getResources().getDrawable(R.drawable.check)); menu.findItem(R.id.search_slot).setIcon(null); } searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE); searchView = (SearchView) menu.findItem(R.id.action_search).getActionView(); searchView.setSearchableInfo( searchManager.getSearchableInfo(getActivity().getComponentName())); searchView.setBackgroundColor(getResources().getColor(R.color.bg_search)); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { if(slots!=null) { ArrayList<Slot> updatedSlots = new ArrayList<Slot>(); for(Slot eachSlot:slots) { if(searchBySlot && eachSlot.getSlot().contains(newText)) { updatedSlots.add(eachSlot); } else if(!searchBySlot && eachSlot.getRegId().contains(newText)) { updatedSlots.add(eachSlot); } } slotAdapter = new SlotAdapter(updatedSlots); slotList.setAdapter(slotAdapter); } return false; } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.search_slot: searchBySlot = true; getActivity().invalidateOptionsMenu(); break; case R.id.search_reg_num: searchBySlot = false; getActivity().invalidateOptionsMenu(); break; default: return super.onOptionsItemSelected(item); } return true; } @Override public void onClick(View v) { } private void showDialog() { if (!pDialog.isShowing()) pDialog.show(); } private void hideDialog() { if (pDialog.isShowing()) pDialog.dismiss(); } private class HttpRequestTask extends AsyncTask<String, String, String> { private Map<String,String> params; public HttpRequestTask(Map<String,String> data) { this.params = data; } protected String doInBackground(String... urls) { String response=null; try { String url = "http://" + urls[0] + "/index.php"; Log.d("myTag", url); response = HttpRequest.post(url) .accept("application/json") .form(params) .body(); Log.d("myTag","Response-->"+response); } catch (HttpRequest.HttpRequestException exception) { exception.printStackTrace(); return null; } catch (Exception e) { e.printStackTrace(); return null; } return response; } protected void onPostExecute(String response) { try { Log.d("myTag", response); JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); // Check for error node in json if (!error) { } else { // Error in login. Get the error message String errorMsg = jObj.getString("error_msg"); Toast.makeText(getActivity(), errorMsg, Toast.LENGTH_LONG).show(); } } catch(JSONException je) { je.printStackTrace(); Toast.makeText(getActivity(), "Error in response!", Toast.LENGTH_SHORT).show(); } catch (NullPointerException ne) { Toast.makeText(getActivity(), "Error in connection! Please check your connection", Toast.LENGTH_SHORT).show(); } finally { hideDialog(); } } } private class SlotAdapter extends BaseAdapter { private ArrayList<Slot> adpaterList = new ArrayList<Slot>(); public SlotAdapter(ArrayList<Slot> adapterList) { this.adpaterList = adapterList; } @Override public int getCount() { return this.adpaterList.size(); } @Override public Slot getItem(int position) { return this.adpaterList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { //setting the view with list item convertView = View.inflate(getActivity(), R.layout.slot_item, null); // This class is necessary to identify the list item, in case convertView!=null new ViewHolder(convertView); } ViewHolder holder = (ViewHolder) convertView.getTag(); //getting view elements value from ArrayList Slot currentSlot = getItem(position); String titleString = currentSlot.getRegId(); String allocatedSlot = "Slot: " + currentSlot.getSlot(); //setting the view element with corressponding value holder.regId.setText(titleString); holder.slot.setText(allocatedSlot); holder.img.setImageDrawable(question); return convertView; } class ViewHolder { private TextView regId; private TextView slot; private ImageView img; ViewHolder(View view) { regId = (TextView) view.findViewById(R.id.reg_id); slot = (TextView) view.findViewById(R.id.slot); img = (ImageView) view.findViewById(R.id.avtar); view.setTag(this); } } } }
package com.martian.andfix.base; import android.app.Application; import android.os.Environment; import com.alipay.euler.andfix.patch.PatchManager; import com.martian.andfix.util.AppInfoUtil; import java.io.IOException; /** * @author martian on 2017/12/26. */ public class MyApplication extends Application { private static final String APATCH_PACH = "/fix.apatch"; private PatchManager mPatchManager; private static MyApplication instance; public static MyApplication getInstance() { return instance; } @Override public void onCreate() { super.onCreate(); instance = this; initAndfix(); } /** * 初始化Andfix */ private void initAndfix() { // 初始化patch管理类 mPatchManager = new PatchManager(this); // 初始化patch版本 mPatchManager.init(String.valueOf(AppInfoUtil.getVersionCode(this))); mPatchManager.loadPatch(); } public void addPatch(){ try { String patchFileString = Environment.getExternalStorageDirectory().getAbsolutePath()+APATCH_PACH; mPatchManager.addPatch(patchFileString); } catch (IOException e) { e.printStackTrace(); } } public PatchManager getPatchManager(){ if(mPatchManager == null){ mPatchManager = new PatchManager(this); } return mPatchManager; } }
package edu.umn.cs.recsys.uu; import it.unimi.dsi.fastutil.longs.Long2DoubleMap; import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap; import org.grouplens.lenskit.vectors.MutableSparseVector; import org.grouplens.lenskit.vectors.similarity.CosineVectorSimilarity; import org.lenskit.api.Result; import org.lenskit.api.ResultMap; import org.lenskit.basic.AbstractItemScorer; import org.lenskit.data.dao.ItemEventDAO; import org.lenskit.data.dao.UserEventDAO; import org.lenskit.data.ratings.Rating; import org.lenskit.data.history.History; import org.lenskit.data.history.UserHistory; import org.lenskit.results.Results; import javax.annotation.Nonnull; import javax.inject.Inject; import java.util.*; /** * User-user item scorer. * @author <a href="http://www.grouplens.org">GroupLens Research</a> */ public class SimpleUserUserItemScorer extends AbstractItemScorer { private final UserEventDAO userDao; private final ItemEventDAO itemDao; private static final double NEIGHBOR_SIZE = 30; @Inject public SimpleUserUserItemScorer(UserEventDAO udao, ItemEventDAO idao) { userDao = udao; itemDao = idao; } @Override public ResultMap scoreWithDetails(long user, @Nonnull Collection<Long> items) { Long2DoubleMap userVector = getUserRatingVector(user); MutableSparseVector userVectorSv = MutableSparseVector.create(userVector); double userMean = userVectorSv.mean(); // This is a list where you can store the results of your user-user computations List<Result> results = new ArrayList<>(); // Score items for this user using user-user collaborative filtering // This is the loop structure to iterate over the items to score. for (Long item: items) { double score = 0; Long2DoubleMap userSimilarities = getUserSimilarities(userVectorSv, item); List<UserSimilarity> neighbors = getNeighbors(userSimilarities, user); double sum = 0; for (UserSimilarity userSimilarity : neighbors) { MutableSparseVector sv = getMeanCentered(getUserRatingVector(userSimilarity.user)); score += userSimilarity.similarity * sv.get(item); sum += Math.abs(userSimilarity.similarity); } score = userMean + score / sum; // HINT You can add Result objects to the results List using the following line: // results.add(Results.create(item, score)); results.add(Results.create(item, score)); } return Results.newResultMap(results); } /** * Get a user's rating vector. * @param user The user ID. * @return The rating vector. */ private Long2DoubleMap getUserRatingVector(long user) { UserHistory<Rating> history = userDao.getEventsForUser(user, Rating.class); if (history == null) { history = History.forUser(user); } Long2DoubleMap ratings = new Long2DoubleOpenHashMap(); for (Rating r: history) { if (r.hasValue()) { ratings.put(r.getItemId(), r.getValue()); } } return ratings; } /** * Compute vector of similarities for the input user's ratings vector. * In this vector for each element the key is the user and the value is the similarity. * Similarity implemented as a cosine similarity between mean-centered ratings vector. * @param userVector vector of ratings for input user. * @return vector of similarities. */ private Long2DoubleMap getUserSimilarities(MutableSparseVector userVector, Long item) { Long2DoubleMap result = new Long2DoubleOpenHashMap(); for (Long user: itemDao.getUsersForItem(item)) { MutableSparseVector sv = getMeanCentered(getUserRatingVector(user)); CosineVectorSimilarity cosineVectorSimilarity = new CosineVectorSimilarity(); Double sim = cosineVectorSimilarity.similarity(userVector, sv); result.put(user, sim); } return result; } /** * Create a new vector where the mean of the vector is subtracted from each element. * @param vec input vector. * @return mean-centered vector. */ private MutableSparseVector getMeanCentered(Long2DoubleMap userVector) { MutableSparseVector userVectorSv = MutableSparseVector.create(userVector); double userMean = userVectorSv.mean(); for (Map.Entry<Long, Double> e: userVector.entrySet()) { userVectorSv.set((long)e.getKey(), e.getValue() - userMean); } return userVectorSv; } class UserSimilarity { public long user; public double similarity; public UserSimilarity(long user, double similarity) { this.user = user; this.similarity = similarity; } @Override public String toString() { return String.format("%d: %.4f", user, similarity); } } /** * Retrieve the nearest neighbors who have rated the item. * @param userSimilarities vector of similarities between the input user * and all other users. * @param user the input user ID. * @return list of UserSimilarity objects (a pair of user ID and similarity value). */ private List<UserSimilarity> getNeighbors(Long2DoubleMap userSimilarities, Long user) { List<UserSimilarity> allResult = new ArrayList<>(); for (Map.Entry<Long, Double> e : userSimilarities.entrySet()) { UserSimilarity userSimilarity = new UserSimilarity(e.getKey(), e.getValue()); allResult.add(userSimilarity); } Collections.sort(allResult, new Comparator<UserSimilarity>() { @Override public int compare(UserSimilarity o1, UserSimilarity o2) { return (int)Math.signum(o2.similarity - o1.similarity); } }); List<UserSimilarity> result = new ArrayList<>(); for (UserSimilarity userSimilarity : allResult) { if (result.size() >= NEIGHBOR_SIZE) { break; } if (userSimilarity.user == user) { continue; } result.add(userSimilarity); } return result; } }
package web.dao; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import web.models.User; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import java.util.List; @Repository public class UserDaoImpl implements UserDao { @PersistenceContext private EntityManager entityManager; @Transactional @Override public void createNewUser(User user) { entityManager.persist(user); } @Transactional(readOnly = true) @Override public User getUserById(long id) { TypedQuery<User> query = entityManager.createQuery("SELECT u FROM User u WHERE u.id = :id", User.class); query.setParameter("id", id); return query.getResultList().stream().findAny().orElse(null); } @Transactional(readOnly = true) @Override public User getUserByName(String name) { TypedQuery<User> query = entityManager.createQuery("SELECT u FROM User u WHERE u.name = :name", User.class); query.setParameter("name", name); return query.getResultList().stream().findAny().orElse(null); } @Transactional(readOnly = true) @Override public List<User> getAllUsers() { return entityManager .createQuery("SELECT u FROM User u", User.class).getResultList(); } @Transactional @Override public void editUserById(long id, User user) { User updatedUser = getUserById(id); updatedUser.setFirstName(user.getFirstName()); updatedUser.setLastName(user.getLastName()); updatedUser.setAge(user.getAge()); updatedUser.setName(user.getName()); updatedUser.setRoles(user.getRoles()); } @Transactional @Override public void updatePassword(long id, String newPassword) { User updatedUser = getUserById(id); updatedUser.setPassword(newPassword); } @Transactional @Override public void deleteUserById(long id) { entityManager.remove(getUserById(id)); } }
package com.weekendproject.connectivly.controller; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.json.JSONException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.weekendproject.connectivly.model.MarketPlaceCategory; import com.weekendproject.connectivly.repository.MarketplaceRepository; @RestController @RequestMapping("/api/master") public class MarketplaceController { @Autowired private MarketplaceRepository repository; @GetMapping("/getMarketplace") public List<MarketPlaceCategory> getMarketplace(HttpServletRequest request) throws IOException, JSONException { // Principal principal = request.getUserPrincipal(); // String userName = principal.getName(); System.out.println(">>>>> " + repository.findAll()); return repository.findAll(); } }
package com.tencent.mm.plugin.qqmail.ui; import com.tencent.mm.plugin.qqmail.b.y; class b$7 implements Runnable { final /* synthetic */ b mgt; final /* synthetic */ y mgy; b$7(b bVar, y yVar) { this.mgt = bVar; this.mgy = yVar; } public final void run() { this.mgt.b(this.mgy); } }
public class Main { public static void main(String[] args) { MaxHeap heap = new MaxHeap(); heap.add(14); heap.add(19); heap.add(21); heap.add(29); heap.add(30); heap.add(17); heap.add(23); heap.add(25); heap.add(32); heap.remove(); heap.remove(); heap.add(55); System.out.println("size of the heap : " + heap.size); heap.printList(); } }
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.integration.kafka.support; import org.springframework.integration.kafka.core.ZookeeperConnectDefaults; /** * @author Soby Chacko * @since 0.5 */ public class ZookeeperConnect { private String zkConnect = ZookeeperConnectDefaults.ZK_CONNECT; private String zkConnectionTimeout = ZookeeperConnectDefaults.ZK_CONNECTION_TIMEOUT; private String zkSessionTimeout = ZookeeperConnectDefaults.ZK_SESSION_TIMEOUT; private String zkSyncTime = ZookeeperConnectDefaults.ZK_SYNC_TIME; public String getZkConnect() { return zkConnect; } public void setZkConnect(final String zkConnect) { this.zkConnect = zkConnect; } public String getZkConnectionTimeout() { return zkConnectionTimeout; } public void setZkConnectionTimeout(final String zkConnectionTimeout) { this.zkConnectionTimeout = zkConnectionTimeout; } public String getZkSessionTimeout() { return zkSessionTimeout; } public void setZkSessionTimeout(final String zkSessionTimeout) { this.zkSessionTimeout = zkSessionTimeout; } public String getZkSyncTime() { return zkSyncTime; } public void setZkSyncTime(final String zkSyncTime) { this.zkSyncTime = zkSyncTime; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.webbeans.test.specalization; import jakarta.enterprise.inject.Alternative; import jakarta.enterprise.inject.Produces; import jakarta.enterprise.inject.Specializes; import jakarta.enterprise.util.AnnotationLiteral; import jakarta.inject.Qualifier; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.apache.webbeans.test.AbstractUnitTest; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ProducerMethodSpecialisationTest extends AbstractUnitTest { @Test public void testProducerMethodSpecialisation() { startContainer(A.class, B.class); assertEquals("B-one", getInstance(String.class, new AnnotationLiteral<OneProducesMethod>(){})); assertEquals("B-two", getInstance(String.class, new AnnotationLiteral<TwoProducesMethod>(){})); assertEquals("A-three", getInstance(String.class, new AnnotationLiteral<ThreeProducesMethod>(){})); } @Test public void testProducerMethodSpecialisation_NotEnabledAlternative() { startContainer(A.class, C.class); assertEquals("A-one", getInstance(String.class, new AnnotationLiteral<OneProducesMethod>(){})); } public static class A { @Produces @OneProducesMethod public String getX() { return "A-one"; } @Produces @TwoProducesMethod public String getY() { return "A-two"; } @Produces @ThreeProducesMethod public String getZ() { return "A-three"; } } public static class B extends A { @Produces @Specializes @OneProducesMethod public String getX() { return "B-one"; } @Produces @Specializes @TwoProducesMethod public String getY() { return "B-two"; } } public static class C extends A { @Produces @Specializes @OneProducesMethod @Alternative // not enabled! public String getX() { return "C-one"; } } @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) @Qualifier public @interface OneProducesMethod { } @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) @Qualifier public @interface TwoProducesMethod { } @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) @Qualifier public @interface ThreeProducesMethod { } }
package edu.sjsu.fly5.services; public class JourneyServiceProxy implements edu.sjsu.fly5.services.JourneyService { private String _endpoint = null; private edu.sjsu.fly5.services.JourneyService journeyService = null; public JourneyServiceProxy() { _initJourneyServiceProxy(); } public JourneyServiceProxy(String endpoint) { _endpoint = endpoint; _initJourneyServiceProxy(); } private void _initJourneyServiceProxy() { try { journeyService = (new edu.sjsu.fly5.services.JourneyServiceServiceLocator()).getJourneyService(); if (journeyService != null) { if (_endpoint != null) ((javax.xml.rpc.Stub)journeyService)._setProperty("javax.xml.rpc.service.endpoint.address", _endpoint); else _endpoint = (String)((javax.xml.rpc.Stub)journeyService)._getProperty("javax.xml.rpc.service.endpoint.address"); } } catch (javax.xml.rpc.ServiceException serviceException) {} } public String getEndpoint() { return _endpoint; } public void setEndpoint(String endpoint) { _endpoint = endpoint; if (journeyService != null) ((javax.xml.rpc.Stub)journeyService)._setProperty("javax.xml.rpc.service.endpoint.address", _endpoint); } public edu.sjsu.fly5.services.JourneyService getJourneyService() { if (journeyService == null) _initJourneyServiceProxy(); return journeyService; } public boolean bookJourney(edu.sjsu.fly5.pojos.Traveller[] traveller, edu.sjsu.fly5.pojos.FlightInstance[] flightInstance, edu.sjsu.fly5.pojos.PaymentDetails paymentDetails, edu.sjsu.fly5.pojos.Person[] person) throws java.rmi.RemoteException{ if (journeyService == null) _initJourneyServiceProxy(); return journeyService.bookJourney(traveller, flightInstance, paymentDetails, person); } public boolean cancelJourney(int bookingId) throws java.rmi.RemoteException{ if (journeyService == null) _initJourneyServiceProxy(); return journeyService.cancelJourney(bookingId); } public edu.sjsu.fly5.pojos.Journey[] listAllJourneys() throws java.rmi.RemoteException{ if (journeyService == null) _initJourneyServiceProxy(); return journeyService.listAllJourneys(); } public boolean rescheduleJourney(java.lang.String bookingId, edu.sjsu.fly5.pojos.Journey journey) throws java.rmi.RemoteException{ if (journeyService == null) _initJourneyServiceProxy(); return journeyService.rescheduleJourney(bookingId, journey); } public edu.sjsu.fly5.pojos.Journey generateItinerary(long bookingReferenceNo, java.lang.String lastName) throws java.rmi.RemoteException{ if (journeyService == null) _initJourneyServiceProxy(); return journeyService.generateItinerary(bookingReferenceNo, lastName); } public edu.sjsu.fly5.pojos.Journey[] listAllJourney(java.lang.String userName) throws java.rmi.RemoteException{ if (journeyService == null) _initJourneyServiceProxy(); return journeyService.listAllJourney(userName); } }
package it.usi.xframe.xas.servlet; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; /** * Servlet implementation class VodafonePopSmsDeliver */ public class VodafonePopSmsDeliver extends HttpServlet { private static final long serialVersionUID = 1L; private static Logger log = Logger.getLogger(VodafonePopSmsDeliver.class); private static final String LOG_PREFIX = "VODAFONEPOPSOAPSMS"; private static final String LOG_LEVEL_NONE = "dbglevel=none"; private static final String LOG_LEVEL_DEFAULT = "dbglevel=default"; private static final String LOG_LEVEL_DEBUG = "dbglevel=full"; //public static final String PAGE_CHARSET = "iso-8859-1"; public static final String PAGE_CHARSET = "UTF-8"; class BufferedServletInputStream extends ServletInputStream { ByteArrayInputStream bais; public BufferedServletInputStream(ByteArrayInputStream bais) { this.bais = bais; } public int available() { return bais.available(); } public int read() { return bais.read(); } public int read(byte[] buf, int off, int len) { return bais.read(buf, off, len); } } class BufferedRequestWrapper extends HttpServletRequestWrapper { ByteArrayInputStream bais; ByteArrayOutputStream baos; BufferedServletInputStream bsis; byte[] buffer; public BufferedRequestWrapper(HttpServletRequest req) throws IOException { super(req); InputStream is = req.getInputStream(); baos = new ByteArrayOutputStream(); byte buf[] = new byte[1024]; int letti; while ((letti = is.read(buf)) > 0) { baos.write(buf, 0, letti); } buffer = baos.toByteArray(); } public ServletInputStream getInputStream() { try { bais = new ByteArrayInputStream(buffer); bsis = new BufferedServletInputStream(bais); } catch (Exception ex) { ex.printStackTrace(); } return bsis; } public byte[] getBuffer() { return buffer; } } /** * @see HttpServlet#HttpServlet() */ public VodafonePopSmsDeliver() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doAll(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doAll(request, response); } private void doAll (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String destinator = null; String messageId = null; String messageState = null; String status = null; String errCode = null; String errMsg = null; ParseDeliveryReport p = new ParseDeliveryReport(); try { BufferedRequestWrapper bufferedRequest= new BufferedRequestWrapper(request); String soapMessage = new String(bufferedRequest.getBuffer()); log.debug("REQUEST -> " + soapMessage); p.read(soapMessage); destinator = p.getDestinator(); messageId = p.getMessageId(); messageState = p.getMessageState(); } catch(Exception e) { log.error(e); e.printStackTrace(); destinator = null; messageId = null; messageState = null; } if(messageState==null) { errCode = messageState; errMsg = "Error during delivery processing"; status = "ERR"; } else if(messageState.equals("1")) { errCode = messageState; errMsg = "ENROUTE: The message is in enroute state"; status = "OK"; } else if(messageState.equals("2")) { errCode = messageState; errMsg = "DELIVERED: Message is delivered to destination"; status = "OK"; } else if(messageState.equals("3")) { errCode = messageState; errMsg = "EXPIRED: Message validity period has expired"; status = "ERR"; } else if(messageState.equals("4")) { errCode = messageState; errMsg = "DELETED: Message has been deleted"; status = "ERR"; } else if(messageState.equals("5")) { errCode = messageState; errMsg = "UNDELIVERABLE: Message is undeliverable"; status = "ERR"; } else if(messageState.equals("6")) { errCode = messageState; errMsg = "ACCEPTED: Message is in accepted state (i.e. has been manually read on behalf of the subscriber by customer service)"; status = "OK"; } else if(messageState.equals("7")) { errCode = messageState; errMsg = "UNKNOWN: Message is in invalid state"; status = "ERR"; } else if(messageState.equals("8")) { errCode = messageState; errMsg = "REJECTED: Message is in a rejected state"; status = "ERR"; } else { errCode = messageState; errMsg = "?"; status = "ERR"; } // log securityDeliveryLog(status, errMsg, errCode, destinator, messageId); response.setContentType("text/html;charset=" + PAGE_CHARSET); PrintWriter out = response.getWriter(); out.println("<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:SoapSmppGW\">"); out.println("<soapenv:Header/>"); out.println("<soapenv:Body>"); out.println("<urn:DeliverResponse soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"); out.println("<DeliverReturn xsi:type=\"urn:Deliver_resp\">"); out.println("<command_status xsi:type=\"xsd:int\">0</command_status>"); out.println("<error_code xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">OK</error_code>"); out.println("<message_id xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">EMPTY</message_id>"); out.println("</DeliverReturn>"); out.println("</urn:DeliverResponse>"); out.println("</soapenv:Body>"); out.println("</soapenv:Envelope>"); } // this log is used by Security Office private void securityDeliveryLog(String status, String description, String errCode, String destinatorPhoneNumber, String msgid) { String userid = null; // common logging utility StringBuffer sb = new StringBuffer(); sb.append(",smslogprefix=" + LOG_PREFIX); sb.append(",smsstatus=" + status); sb.append(",errormessage=" + description); sb.append("," + LOG_LEVEL_DEFAULT); sb.append(",dstphonenumber=" + destinatorPhoneNumber); sb.append(",smsgatewayresponse=" + errCode); sb.append(",smsid=" + msgid); log.info(sb); } }
package hirondelle.web4j.database; import static hirondelle.web4j.util.Consts.NEW_LINE; import hirondelle.web4j.BuildImpl; import hirondelle.web4j.model.AppException; import hirondelle.web4j.model.DateTime; import hirondelle.web4j.model.Decimal; import hirondelle.web4j.model.Id; import hirondelle.web4j.model.DateTime.Unit; import hirondelle.web4j.readconfig.ConfigReader; import hirondelle.web4j.security.SafeText; import hirondelle.web4j.util.Util; import java.math.BigDecimal; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TimeZone; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** Encapsulates an SQL statement used in the application. <P><span class='highlight'>See package overview for important information</span>. <P>This class hides details regarding all SQL statements used by the application. These items are hidden from the caller of this class : <ul> <li>the retrieval of SQL statements from an underlying textual <tt>.sql</tt> file or files <li>the textual content of SQL statements <li>the details of placing parameters into a {@link PreparedStatement} </ul> <P> Only {@link PreparedStatement} objects are used here, since they <a href="http://www.javapractices.com/Topic212.cjp">are usually preferable</a> to {@link Statement} objects. */ final class SqlStatement { /** Called by the framework upon startup, to read and validate all SQL statements from the underlying <tt>*.sql</tt> text file(s). <P>Verifies that there is no mismatch whatsoever between the <tt>public static final</tt> {@link SqlId} fields used in the application, and the keys of the corresponding <tt>*.sql</tt> file(s). If there is a mismatch, then an exception is thrown when this class loads, to ensure that errors are reported as soon as possible. <P> Upon startup, the framework can optionally attempt a test precompile of each SQL statement, by calling {@link Connection#prepareStatement(String)}. If the SQL text is not syntactically correct, then a call to <tt>Connection.prepareStatement()</tt> <em>might</em> throw an {@link SQLException}, according to the implementation of the driver/database. (For example, JavaDB/Derby will throw an {@link SQLException}, while MySql and Oracle will not.) If such an error is detected, then it is logged as <tt>SEVERE</tt>. <P>A setting in <tt>web.xml</tt> can disable this pre-compilation, if desired. */ static void readSqlFile() { readSqlText(); checkStoredProcedures(); checkSqlFilesVersusSqlIdFields(); precompileAll(); } /** SQL statement which takes parameters. <P>This class supports the same classes as parameters as {@link ConvertColumnImpl}. That is, only objects of the those classes can be present in the <tt>aSqlParams</tt> list. A parameter may also be <tt>null</tt>. <P> For <tt>Id</tt> objects, in particular, the underlying column must modeled as text, not a number. If the underlying column is numeric, then the caller must convert an {@link Id} into a numeric form using {@link Id#asInteger} or {@link Id#asLong}. @param aSqlId corresponds to a key in the underlying <tt>.sql</tt> file @param aSearchCriteria is possibly <tt>null</tt>, and represents the criteria input by the user during a search operation for a particular record (or records). If present, then {@link DynamicSql#toString()} is appended to the text of the underlying SQL statement from the <tt>.sql</tt> files. @param aSqlParams contains at least one object of the supported classes noted above; <span class="highlight">the number and order of these parameter objects matches the number and order of "?" parameters in the underlying SQL</span>. */ SqlStatement(SqlId aSqlId, DynamicSql aSearchCriteria, Object... aSqlParams) { fSqlId = aSqlId; fSqlText = getSqlTextFromId(aSqlId); if (aSearchCriteria != null) { fSqlText = fSqlText + aSearchCriteria.toString(); } checkNumParamsMatches(aSqlParams); checkParamsOfSupportedType(aSqlParams); fParams = aSqlParams; fLogger.finest(this.toString()); } /** Return a {@link PreparedStatement} whose parameters, if any, have been populated using the <tt>aSqlParams</tt> passed to the constructor. <P>If the underlying database auto-generates any keys by executing the returned <tt>PreparedStatement</tt>, they will be available from the returned value using {@link Statement#getGeneratedKeys}. <P>If the returned statement is a <tt>SELECT</tt>, then a limit, as configured in <tt>web.xml</tt>, is placed on the maximum number of rows which can be returned. This is meant as a defensive safety measure, to avoid returning an excessively large number of rows. */ PreparedStatement getPreparedStatement(Connection aConnection) throws SQLException { PreparedStatement result = null; result = getPS(fSqlText, aConnection, fSqlId); populateParamsUsingPS(result); result.setMaxRows(DbConfig.getMaxRows(fSqlId.getDatabaseName()).intValue()); result.setFetchSize(DbConfig.getFetchSize(fSqlId.getDatabaseName()).intValue()); return result; } /** Return the {@link SqlId} passed to the constructor. */ public SqlId getSqlId() { return fSqlId; } /** Return the number of <tt>'?'</tt> placeholders appearing in the underlying SQL statement. */ static int getNumParameters(SqlId aSqlId) { int result = 0; String sqlText = getSqlTextFromId(aSqlId); result = getNumParams(fQUESTION_MARK, sqlText); return result; } /** Intended for debugging only. */ @Override public String toString() { StringBuilder result = new StringBuilder(); result.append(fSqlId); result.append(" {"); result.append(NEW_LINE); result.append(" fSqlText = ").append(fSqlText).append(NEW_LINE); List<Object> params = Arrays.asList(fParams); result.append(" Params = ").append(params).append(NEW_LINE); result.append("}"); result.append(NEW_LINE); return result.toString(); } // PRIVATE /** The id of the SQL statement, as named in the underlying .sql file. */ private final SqlId fSqlId; /** Parameter values to be placed into a SQL statement. */ private final Object[] fParams; /** The raw text of the SQL statement, as retrieved from the underlying *.sql file(s) (for example "SELECT Name FROM Blah"). */ private String fSqlText; /** Contents of the underlying *.sql file(s). */ private static Properties fSqlProperties; private static final Pattern fQUESTION_MARK = Pattern.compile("\\?"); private static final Pattern fSQL_PROPERTIES_FILE_NAME_PATTERN = Pattern.compile("(?:.)*\\.sql"); private static final String fTESTING_SQL_PROPERTIES = "C:\\johanley\\Projects\\webappskeleton\\WEB-INF\\mysql.sql"; private static final String fSTORED_PROC = "{call"; private static final Pattern fSELECT_PATTERN = Pattern.compile("^SELECT", Pattern.CASE_INSENSITIVE); private static final String fUNSUPPORTED_STORED_PROC = "{?="; private static final Logger fLogger = Util.getLogger(SqlStatement.class); private static PreparedStatement getPS(String aSqlText, Connection aConnection, SqlId aSqlId) throws SQLException { PreparedStatement result = null; if (isStoredProcedure(aSqlText)) { result = aConnection.prepareCall(aSqlText); } else { if (isSelect(aSqlText)) { // allow scrolling of SELECT result sets; this is needed by ModelFromRow, to create lists with children result = aConnection.prepareStatement(aSqlText, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); } else { if (DbConfig.hasAutogeneratedKeys(aSqlId.getDatabaseName())) { result = aConnection.prepareStatement(aSqlText, Statement.RETURN_GENERATED_KEYS); } else { result = aConnection.prepareStatement(aSqlText); } } } return result; } private void populateParamsUsingPS(PreparedStatement aStatement) throws SQLException { // parameter indexes are 1-based, not 0-based. for (int idx = 1; idx <= fParams.length; ++idx) { Object param = fParams[idx - 1]; if (param == null) { fLogger.finest("Param" + idx + ": null"); // is there a better way of doing this? // setNull needs the type of the underlying column, which is not available aStatement.setString(idx, null); } else if (param instanceof String) { fLogger.finest("Param" + idx + ": String"); aStatement.setString(idx, (String)param); } else if (param instanceof Integer) { fLogger.finest("Param" + idx + ": Integer"); Integer paramVal = (Integer)param; aStatement.setInt(idx, paramVal.intValue()); } else if (param instanceof Boolean) { fLogger.finest("Param" + idx + ": Boolean"); Boolean paramVal = (Boolean)param; aStatement.setBoolean(idx, paramVal.booleanValue()); } else if (param instanceof hirondelle.web4j.model.DateTime) { fLogger.finest("Param" + idx + ": hirondelle.web4j.model.DateTime"); setDateTime(param, aStatement, idx); } else if (param instanceof java.util.Date) { fLogger.finest("Param" + idx + ": Date"); setDate(param, aStatement, idx); } else if (param instanceof java.math.BigDecimal) { fLogger.finest("Param" + idx + ": BigDecimal"); aStatement.setBigDecimal(idx, (BigDecimal)param); } else if (param instanceof Decimal) { fLogger.finest("Param" + idx + ": Decimal"); Decimal value = (Decimal)param; aStatement.setBigDecimal(idx, value.getAmount()); } else if (param instanceof Long) { fLogger.finest("Param" + idx + ": Long"); Long paramVal = (Long)param; aStatement.setLong(idx, paramVal.longValue()); } else if (param instanceof Id) { fLogger.finest("Param" + idx + ": Id"); Id paramId = (Id)param; aStatement.setString(idx, paramId.getRawString()); } else if (param instanceof SafeText) { fLogger.finest("Param" + idx + ": SafeText"); SafeText paramText = (SafeText)param; aStatement.setString(idx, paramText.getRawString()); } else if (param instanceof Locale){ fLogger.finest("Param" + idx + ": Locale"); Locale locale = (Locale)param; String nonLocalizedId = locale.toString(); //en_US_south; independent of any JRE locale aStatement.setString(idx, nonLocalizedId); } else if (param instanceof TimeZone){ fLogger.finest("Param" + idx + ": TimeZone"); TimeZone timeZone = (TimeZone)param; String nonLocalizedId = timeZone.getID(); //America/Montreal aStatement.setString(idx, nonLocalizedId); } else { throw new IllegalArgumentException("Unsupported type of parameter: " + param.getClass()); } } } private void setDate(Object aParam, PreparedStatement aStatement, int aIdx) throws SQLException { // java.sql.Date has date only, and java.sql.Time has time only java.util.Date dateUtil = (java.util.Date)aParam; java.sql.Timestamp timestampSql = new java.sql.Timestamp(dateUtil.getTime()); if (DbConfig.hasTimeZoneHint()) { aStatement.setTimestamp(aIdx, timestampSql, DbConfig.getTimeZoneHint()); } else { aStatement.setTimestamp(aIdx, timestampSql); } } private void setDateTime(Object aParam, PreparedStatement aStatement, int aIdx) throws SQLException { DateTime dateTime = (DateTime)aParam; String formattedDateTime = ""; if ( dateTime.unitsAllPresent(Unit.YEAR, Unit.MONTH, Unit.DAY) && dateTime.unitsAllAbsent(Unit.HOUR, Unit.MINUTE, Unit.SECOND) ){ fLogger.finest("Treating DateTime as a date (year-month-day)."); formattedDateTime = dateTime.format(DbConfig.getDateFormat(fSqlId.getDatabaseName())); } else if ( dateTime.unitsAllAbsent(Unit.YEAR, Unit.MONTH, Unit.DAY) && dateTime.unitsAllPresent(Unit.HOUR, Unit.MINUTE, Unit.SECOND) ){ fLogger.finest("Treating DateTime as a time (hour-minute-second)."); formattedDateTime = dateTime.format(DbConfig.getTimeFormat(fSqlId.getDatabaseName())); } else if ( dateTime.unitsAllPresent(Unit.YEAR, Unit.MONTH, Unit.DAY) && dateTime.unitsAllPresent(Unit.HOUR, Unit.MINUTE, Unit.SECOND) ) { fLogger.finest("Treating DateTime as a date+time (year-month-day-hour-minute-second)."); formattedDateTime = dateTime.format(DbConfig.getDateTimeFormat(fSqlId.getDatabaseName())); } else { String message = "Unable to format DateTime using the DateTimeFormatForPassingParamsToDb setting in web.xml." + " The units present in the DateTime object do not match any of the expected combinations. " + "If needed, you can always format the DateTime manually in your DAO, and pass a String to the database instead of a DateTime." ; fLogger.severe(message); throw new IllegalArgumentException(message); } aStatement.setString(aIdx, formattedDateTime); } private static String getSqlTextFromId(SqlId aSqlId) { return fSqlProperties.getProperty(aSqlId.toString()); } private void checkNumParamsMatches(Object[] aSqlParams) { checkNumParams(fQUESTION_MARK, aSqlParams); } private static boolean isStoredProcedure(String aSqlText) { return aSqlText.startsWith(fSTORED_PROC); } private static boolean isSelect(String aSqlText) { return Util.contains(fSELECT_PATTERN, aSqlText); } private void checkNumParams(Pattern aPattern, Object[] aParams) { Matcher matcher = aPattern.matcher(fSqlText); int numParams = 0; while (matcher.find()) { ++numParams; } if (numParams != aParams.length) { throw new IllegalArgumentException(aParams.length + " params should be " + numParams); } } private static int getNumParams(Pattern aPlaceholderPattern, String aSqlText) { int result = 0; Matcher matcher = aPlaceholderPattern.matcher(aSqlText); while (matcher.find()) { ++result; } return result; } private void checkParamsOfSupportedType(Object[] aSqlParams) { for (Object param : aSqlParams) { if (!isSupportedType(param)) { throw new IllegalArgumentException("Unsupported type of SQL parameter: " + param.getClass()); } } } private boolean isSupportedType(Object aParam) { return aParam == null || BuildImpl.forConvertParam().isSupported(aParam.getClass()); } private static void readSqlText() { if (fSqlProperties != null) { fSqlProperties.clear(); } if (!DbConfig.isTestingMode()) { fSqlProperties = ConfigReader.fetchMany(fSQL_PROPERTIES_FILE_NAME_PATTERN, ConfigReader.FileType.TEXT_BLOCK); } else { fSqlProperties = ConfigReader.fetchForTesting(fTESTING_SQL_PROPERTIES, ConfigReader.FileType.TEXT_BLOCK); } } private static void checkSqlFilesVersusSqlIdFields() { Map sqlIdFields = ConfigReader.fetchPublicStaticFinalFields(SqlId.class); Set<String> sqlIdStrings = convertToSetOfStrings(sqlIdFields); fLogger.config("SqlId fields " + Util.logOnePerLine(sqlIdStrings)); AppException mismatches = getMismatches(sqlIdStrings, fSqlProperties.keySet()); if (mismatches.isNotEmpty()) { fLogger.severe("MISMATCH found between .sql files and SqlId fields. " + Util.logOnePerLine(mismatches.getMessages())); throw new IllegalStateException(Util.logOnePerLine(mismatches.getMessages())); } fLogger.config("No mismatches found between .sql files and SqlId fields."); } /** Map <tt>aSqlIdFields</tt> contains KEY - containing Class VALUE - Set of SqlId Fields <P> In this case, we are interested only in the "global" set of SqlId fields, unrelated to any particular class. This method will doubly iterate through its argument, and return a Set of Strings extracted from the SqlId.toString() method. This is to allow comparison with the identifiers in the .sql files. */ private static Set<String> convertToSetOfStrings(Map<Class<?>, Set<SqlId>> aSqlIdFields) { Set<String> result = new LinkedHashSet<String>(); Set classes = aSqlIdFields.keySet(); Iterator classesIter = classes.iterator(); while (classesIter.hasNext()) { Class containingClass = (Class)classesIter.next(); Set<SqlId> fields = aSqlIdFields.get(containingClass); result.addAll(getSqlIdFieldsAsStrings(fields)); } return result; } private static Set<String> getSqlIdFieldsAsStrings(Set<SqlId> aSqlIds) { Set<String> result = new LinkedHashSet<String>(); for (SqlId sqlId : aSqlIds) { result.add(sqlId.toString()); } return result; } private static AppException getMismatches(Set<String> aSqlIdStrings, Collection<Object> aSqlTextFileKeys) { AppException result = new AppException(); for (String fieldValue : aSqlIdStrings) { if (!aSqlTextFileKeys.contains(fieldValue)) { result.add("SqlId field " + fieldValue + " is not present in any underlying .sql file."); } } for (Object sqlFileKey : aSqlTextFileKeys) { if (!aSqlIdStrings.contains(sqlFileKey)) { result.add("The key " + sqlFileKey + " in a .sql file does not match any corresponding public static final SqlId field in any class."); } } return result; } private static void checkStoredProcedures() { AppException errors = new AppException(); Enumeration allSqlIds = fSqlProperties.propertyNames(); while (allSqlIds.hasMoreElements()) { String sqlId = (String)allSqlIds.nextElement(); String sql = (String)fSqlProperties.get(sqlId); if (sql.startsWith(fUNSUPPORTED_STORED_PROC)) { errors.add( "The stored procedured called " + Util.quote(sqlId) + " has an explict return " + "value since it begins with " + fUNSUPPORTED_STORED_PROC + ". " + "A *.sql file can contain stored procedures, but only if they do not " + "have any OUT or INOUT parameters, including *explicit* return values (which " + "would need registration as an OUT parameter). See hirondelle.web4j.database " + "package overview for more information." ); } } if (errors.isNotEmpty()) { throw new IllegalStateException(errors.getMessages().toString()); } } /** Attempt a precompile of all statements. <P>Precompilation is not supported by some drivers/databases. */ private static void precompileAll() { fLogger.config("Attempting precompile of all SQL statements by calling Connection.prepareStatement(String). Precompilation is not supported by all drivers/databases. If not supported, then this checking is not useful. See web.xml."); ConnectionSource connSrc = BuildImpl.forConnectionSource(); Connection connection = null; PreparedStatement preparedStatement = null; String sqlText = null; SqlId sqlId = null; String sqlIdString = null; List<String> successIds = new ArrayList<String>(); List<String> failIds = new ArrayList<String>(); Set<Object> statementIds = fSqlProperties.keySet(); Iterator<Object> iter = statementIds.iterator(); while (iter.hasNext()) { sqlId = SqlId.fromStringId((String) iter.next()); sqlIdString = sqlId.toString(); sqlText = fSqlProperties.getProperty(sqlIdString); String dbName = sqlId.getDatabaseName(); if(DbConfig.isSqlPrecompilationAttempted(dbName)){ try { connection = (Util.textHasContent(dbName)) ? connSrc.getConnection(dbName) : connSrc.getConnection(); preparedStatement = getPS(sqlText, connection, sqlId); // SQLException depends on driver/db successIds.add(sqlIdString); } catch (SQLException ex) { failIds.add(sqlIdString); fLogger.severe("SQLException occurs for attempted precompile of " + sqlId + " " + ex.getMessage() + NEW_LINE + sqlText); } catch (DAOException ex) { fLogger.severe("Error encountered during attempts to precompile SQL statements : " + ex); } finally { try { DbUtil.close(preparedStatement, connection); } catch (DAOException ex) { fLogger.severe("Cannot close connection and/or statement : " + ex); } } } } fLogger.config("Attempted SQL precompile, and found no failure for : " + Util.logOnePerLine(successIds)); if (!failIds.isEmpty()) { fLogger.config("Attempted SQL precompile, and found *** FAILURE *** for : " + Util.logOnePerLine(failIds)); } } }
package com.dto; public class JianCe { private Integer j_id; //检测的id private Integer p_id; //外键 连接person表 private String img_path; //图片地址 private String p2; private String r_r; //RR间期 private String heart_rate;//心率 private String r_number; //R波的数量 public String getP2() { return p2; } public void setP2(String p2) { this.p2 = p2; } public Integer getJ_id() { return j_id; } public void setJ_id(Integer j_id) { this.j_id = j_id; } public Integer getP_id() { return p_id; } public void setP_id(Integer p_id) { this.p_id = p_id; } public String getImg_path() { return img_path; } public void setImg_path(String img_path) { this.img_path = img_path; } public String getR_r() { return r_r; } public void setR_r(String r_r) { this.r_r = r_r; } public String getHeart_rate() { return heart_rate; } public void setHeart_rate(String heart_rate) { this.heart_rate = heart_rate; } public String getR_number() { return r_number; } public void setR_number(String r_number) { this.r_number = r_number; } }
/* * Created on Oct 5, 2006 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ package com.ibm.jikesbt; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /** * * @author sfoley * * Used for reading lines of source from a source file */ public class BT_SourceFile { private static final String[] noLines = new String[0]; private String lines[]; public final String name; private BT_Class clazz; BT_SourceFile(BT_Class clazz, String name) { this.name = name; this.clazz = clazz; } public boolean equals(Object o) { if(!(o instanceof BT_SourceFile)) { return false; } BT_SourceFile other = (BT_SourceFile) o; return name.equals(other.name); } private void readLines() { if(lines != null) { return; } String dir = BT_Repository.getSourcePath() + File.separatorChar; dir += clazz.packageName().replace('.', File.separatorChar) + File.separatorChar; BufferedReader sourceLineReader = null; String resource = dir + name; try { sourceLineReader = new BufferedReader(new FileReader(resource)); StringVector lines = new StringVector(); try { String line = sourceLineReader.readLine(); while (line != null) { lines.addElement(line); line = sourceLineReader.readLine(); } } catch(IOException e) {} finally { if(sourceLineReader != null) { try { sourceLineReader.close(); } catch(IOException e) { clazz.getRepository().factory.noteFileCloseIOException(resource, e); } } } this.lines = lines.toArray(); } catch(FileNotFoundException e) { lines = noLines; } return; } String getLine(int number) { readLines(); if(number <= lines.length) { return lines[number - 1]; } return null; } }
package uk.co.mobsoc.MobsGames; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBurnEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.world.WorldLoadEvent; import uk.co.mobsoc.MobsGames.Data.BlockData; import uk.co.mobsoc.MobsGames.Data.SavedData; import uk.co.mobsoc.MobsGames.Game.AbstractGame; import uk.co.mobsoc.MobsGames.Player.AbstractPlayerClass; public class GenericListener implements Listener { /** * This is in the wrong place, but I didnt want to make a listener just for one measly function. * This captures players selecting a block (By right clicking with flint in hand) * @param event */ @EventHandler public void onInteract(PlayerInteractEvent event){ if(event.isCancelled()){ return; } if(!event.hasBlock()){ return; } if(!event.getPlayer().hasPermission("games.alter")){ return ; } if(event.getPlayer().getItemInHand().getType() == Material.FLINT){ event.setCancelled(true); Block b = event.getClickedBlock(); MobsGames.instance.blockSelected.put(event.getPlayer().getName().toLowerCase(), new BlockData(b)); event.getPlayer().sendMessage("Selected block : "+b.getX()+" "+b.getY()+" "+b.getZ()); } } @EventHandler public void onFireSet(BlockBurnEvent event){ event.setCancelled(true); } @EventHandler public void onLogout(PlayerQuitEvent event){ Player player = event.getPlayer(); AbstractGame game = MobsGames.getGame(); if(game!=null){ AbstractPlayerClass apc = game.getPlayerClass(player); if(apc!=null){ game.startLogOutTimer(apc); } } } @EventHandler public void onWorldLoad(WorldLoadEvent event){ SavedData.loadWorld(event.getWorld()); } }
package nl.kvtulder.friendsr; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.drawable.Drawable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; public class ProfileActivity extends AppCompatActivity { SharedPreferences.Editor editor; Friend retrievedFriend; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); Intent intent = getIntent(); retrievedFriend = (Friend) intent.getSerializableExtra("clicked_friend"); TextView friendName = findViewById(R.id.friendName); friendName.setText(retrievedFriend.getName()); TextView friendBio = findViewById(R.id.friendBio); friendBio.setText(retrievedFriend.getBio()); ImageView friendImage = findViewById(R.id.friendImage); Drawable picture = getResources().getDrawable(retrievedFriend.getDrawableID()); friendImage.setImageDrawable(picture); SharedPreferences prefs = getSharedPreferences("settings", MODE_PRIVATE); editor = prefs.edit(); RatingBar ratingBar = findViewById(R.id.friendRating); ratingBar.setOnRatingBarChangeListener(new ratingBarClickListener()); ratingBar.setRating(prefs.getFloat(retrievedFriend.getName() + "Rating",0)); } public class ratingBarClickListener implements RatingBar.OnRatingBarChangeListener { @Override public void onRatingChanged(RatingBar ratingBar, float v, boolean b) { editor.putFloat(retrievedFriend.getName() + "Rating",ratingBar.getRating()); editor.apply(); } } }
package com.wuyan.masteryi.mall.entity; import lombok.Data; /** * @Author: Zhao Shuqing * @Date: 2021/7/6 10:30 * @Description: */ @Data public class Category { private Integer categoryId; private Integer parentCategoryId; private String categoryName; }
/* * 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 calculadorarmi; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import Calculadora.*; /** * * @author Alexis */ public class Cliente { private Cliente() {} /** * @param args the command line arguments */ public static void main(String[] args) { String host = (args.length < 1) ? null : args[0]; try { Registry registry = LocateRegistry.getRegistry(host); //también puedes usar getRegistry(String host, int port) Calculadora stub = (Calculadora) registry.lookup("Calculadora"); int x=5,y=4; double a=5,b=4; int response = stub.suma(x,y); int respRest = stub.resta(x,y); int respMult = stub.mult(x,y); double respDiv = stub.division(a,b); System.out.println("Calculadora RMI"); System.out.println("Respuesta suma: "+x+" + "+y+" = " + response); System.out.println("Respuesta resta: "+x+" - "+y+" = " + respRest); System.out.println("Respuesta multiplicacion: "+x+" * "+y+" = " + respMult); System.out.println("Respuesta division: "+x+" / "+y+" = " + respDiv); } catch (Exception e) { System.err.println("Excepción del cliente: " + e.toString()); } } }
package space.lobanov.firstapp; import androidx.appcompat.app.AppCompatActivity; import android.app.Dialog; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.media.Image; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import java.text.BreakIterator; import java.text.StringCharacterIterator; import java.util.Random; public class Level1 extends AppCompatActivity { //вызываем диалоговое окно Dialog dialog; Dialog dialogEnd; public int numLeft; //переменная для левой картинки public int numRight; //переменная для правой картинки Array array = new Array();//создали новый объект из класса Array Random random = new Random();//для генерации случайных чисел public int count = 0;//счетчик правильных ответов @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.universal); //создаём переменную text_levels TextView textView = findViewById(R.id.text_levels);//установили текст //сообщаем о том, что разместили картинку с именем img_left final ImageView img_left = (ImageView)findViewById(R.id.img_left); //скругляем углы у левой картинки img_left.setClipToOutline(true); //сообщаем о том, что разместили картинку с именем img_right final ImageView img_right = (ImageView)findViewById(R.id.img_right); //скругляем углы у правой картинки img_right.setClipToOutline(true); //путь к левой TextView final TextView text_left =findViewById(R.id.text_left); //путь к правой TextView final TextView text_right = findViewById(R.id.text_right); //развернуть игру на весь экран начало Window window = getWindow(); window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); //развернуть игру на весь экран конец //вызов диалогового окга в начале игры dialog = new Dialog(this);//создаем новое диалоговое окно dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);//скрываем заголовок dialog.setContentView(R.layout.previewdialog);//путь к макету диалогового окна dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));//прозрачный фон диалогового окна dialog.setCancelable(false);//окно нельзя закрыть кнопкой назад //кнопка которая закрывает диалоговое окно начало TextView btnClose = (TextView) dialog.findViewById(R.id.btnclose); btnClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Обрабатываем нажатие кнопки начало try { //вернуться назад к выбору уровня начало Intent intent= new Intent(Level1.this,GameLevels.class);//создали намерение для перехода startActivity(intent);//запустили намерение finish();//закрыть класс //вернуться назад к выбору уровня конец }catch (Exception e){ } dialog.dismiss();//закрываем диалоговое окно //обрабатываем нажатие кнопки конец } }); //кнопка которая закрывает диалоговое окно конец //кнопка продолжить начало Button btncontinue =(Button)dialog.findViewById(R.id.btncontinue); btncontinue.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss();//закрываем диалоговое окно } }); //кнопка продолжить конец dialog.show();//показываем диалоговое окно //--------------------- //вызов диалогового окна в конце игры dialogEnd = new Dialog(this);//создаем новое диалоговое окно dialogEnd.requestWindowFeature(Window.FEATURE_NO_TITLE);//скрываем заголовок dialogEnd.setContentView(R.layout.dialogend);//путь к макету диалогового окна dialogEnd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));//прозрачный фон диалогового окна dialogEnd.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);//разворачивает окно на весь экран dialogEnd.setCancelable(false);//окно нельзя закрыть кнопкой назад //кнопка которая закрывает диалоговое окно начало TextView btnClose2 = (TextView) dialogEnd.findViewById(R.id.btnclose); btnClose2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Обрабатываем нажатие кнопки начало try { //вернуться назад к выбору уровня начало Intent intent= new Intent(Level1.this,GameLevels.class);//создали намерение для перехода startActivity(intent);//запустили намерение finish();//закрыть класс //вернуться назад к выбору уровня конец }catch (Exception e){ } dialogEnd.dismiss();//закрываем диалоговое окно //обрабатываем нажатие кнопки конец } }); //кнопка которая закрывает диалоговое окно конец //кнопка продолжить начало Button btncontinue2 =(Button)dialogEnd.findViewById(R.id.btncontinue); btncontinue2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { Intent intent = new Intent(Level1.this, Level2.class); startActivity(intent); finish(); }catch (Exception e){ } dialogEnd.dismiss();//закрываем диалоговое окно } }); //кнопка продолжить конец //--------------------- //Кнопака "назад" начало Button btn_back = (Button)findViewById(R.id.button_back); btn_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //обрабатываем нажатие кнопки -начало try { //вернуться назад к выбору уровня начало Intent intent = new Intent(Level1.this,GameLevels.class); //создали намерение для перехода startActivity(intent);//старт намерения finish();//закрыть этот класс //вернуться назад к выбору уровня крнец }catch (Exception e){ } //обрабатываем нажатие кнопки -конец } }); //Кнопка назад-конец //массив для прогресса игры начало final int [] progress = { R.id.point1, R.id.point2, R.id.point3, R.id.point4, R.id.point5, R.id.point6, R.id.point7, R.id.point8, R.id.point9, R.id.point10, R.id.point11, R.id.point12, R.id.point13, R.id.point14, R.id.point15, R.id.point16, R.id.point17, R.id.point18, R.id.point19, R.id.point20, }; //массив для прогресса игры конец //Поключаем анимацию начало final Animation animation = AnimationUtils.loadAnimation(Level1.this,R.anim.alpha); //Поключаем анимацию конец numLeft = random.nextInt(10);//генерирум случайное число от 0 до 9 img_left.setImageResource(array.images1[numLeft]);//достаем из массива картинку text_left.setText(array.texts1[numLeft]);//достаем из массива текст numRight = random.nextInt(10);//генерируем случайное число от 0-9 //цикл с предусловием, проверяющие равенство чисел начало while (numLeft==numRight){ numRight = random.nextInt(10); } //цикл с предусловием, проверяющие равенство чисел конец img_right.setImageResource(array.images1[numRight]);//достаем из массива картинку text_right.setText(array.texts1[numRight]);//достаем из массива текст //обрабатываем нажатие на левую картинку начало img_left.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { //условие касания картинки начало if (event.getAction()==MotionEvent.ACTION_DOWN){ //если коснулся картинки начало img_right.setEnabled(false);//блокируем правую картинку if (numLeft>numRight) { img_left.setImageResource(R.drawable.true_otv); } else{ img_left.setImageResource(R.drawable.false_otv); } //если коснулся картинки конец }else if (event.getAction()==MotionEvent.ACTION_UP){ //если отпустил палец начало if (numLeft>numRight){ //если левая картинка больше if (count<20){ count=count+1; } //закрашиваем прогресс серым цветом начало for (int i =0;i<20;i++){ TextView tv = findViewById(progress[i]); tv.setBackgroundResource(R.drawable.style_points); } //закрашиваем прогресс серым цветом конец //определяем правильные ответы и закрашиваем зеленым цветом начало for (int i=0;i<count;i++){ TextView tv = findViewById(progress[i]); tv.setBackgroundResource(R.drawable.style_points_green); } //определяем правильные ответы и закрашиваем зеленым цветом конец }else{ //если левая картинка меньше if (count>0){ if(count==1){ count=0; }else{ count= count-2; } } //закрашиваем прогресс серым цветом начало for (int i =0;i<19;i++){ TextView tv = findViewById(progress[i]); tv.setBackgroundResource(R.drawable.style_points); } //закрашиваем прогресс серым цветом конец //определяем правильные ответы и закрашиваем зеленым цветом начало for (int i=0;i<count;i++){ TextView tv = findViewById(progress[i]); tv.setBackgroundResource(R.drawable.style_points_green); } //определяем правильные ответы и закрашиваем зеленым цветом конец } //если отпустил палец конец if (count==20){ //ВЫХОД ИЗ УРОВНЯ //параметр level будет запоминать и передавать цифры на каждом уровне в переменную level SharedPreferences save = getSharedPreferences("Save",MODE_PRIVATE); final int level = save.getInt("Level",1); if(level >1 ){ }else { SharedPreferences.Editor editor = save.edit(); editor.putInt("Level",2);//уровень пройден и мы пишем цифру следующего уровня editor.commit(); } dialogEnd.show(); }else { numLeft = random.nextInt(10);//генерирум случайное число от 0 до 9 img_left.setImageResource(array.images1[numLeft]);//достаем из массива картинку img_left.startAnimation(animation); text_left.setText(array.texts1[numLeft]);//достаем из массива текст numRight = random.nextInt(10);//генерируем случайное число от 0-9 //цикл с предусловием, проверяющие равенство чисел начало while (numLeft==numRight){ numRight = random.nextInt(10); } //цикл с предусловием, проверяющие равенство чисел конец img_right.setImageResource(array.images1[numRight]);//достаем из массива картинку img_right.startAnimation(animation); text_right.setText(array.texts1[numRight]);//достаем из массива текст img_right.setEnabled(true);//включаем вновь правую картинку } } //условие касания картинки конец return true; } }); //обрабатываем нажатие на левую картинку конец //обрабатываем нажатие на правую картинку начало img_right.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { //условие касания картинки начало if (event.getAction()==MotionEvent.ACTION_DOWN){ //если коснулся картинки начало img_left.setEnabled(false);//блокируем левую картинку if (numLeft<numRight) { img_right.setImageResource(R.drawable.true_otv); } else{ img_right.setImageResource(R.drawable.false_otv); } //если коснулся картинки конец }else if (event.getAction()==MotionEvent.ACTION_UP){ //если отпустил палец начало if (numLeft<numRight){ //если правая картинка больше if (count<20){ count=count+1; } //закрашиваем прогресс серым цветом начало for (int i =0;i<20;i++){ TextView tv = findViewById(progress[i]); tv.setBackgroundResource(R.drawable.style_points); } //закрашиваем прогресс серым цветом конец //определяем правильные ответы и закрашиваем зеленым цветом начало for (int i=0;i<count;i++){ TextView tv = findViewById(progress[i]); tv.setBackgroundResource(R.drawable.style_points_green); } //определяем правильные ответы и закрашиваем зеленым цветом конец }else{ //если правая картинка меньше if (count>0){ if(count==1){ count=0; }else{ count= count-2; } } //закрашиваем прогресс серым цветом начало for (int i =0;i<19;i++){ TextView tv = findViewById(progress[i]); tv.setBackgroundResource(R.drawable.style_points); } //закрашиваем прогресс серым цветом конец //определяем правильные ответы и закрашиваем зеленым цветом начало for (int i=0;i<count;i++){ TextView tv = findViewById(progress[i]); tv.setBackgroundResource(R.drawable.style_points_green); } //определяем правильные ответы и закрашиваем зеленым цветом конец } //если отпустил палец конец if (count==20){ //ВЫХОД ИЗ УРОВНЯ SharedPreferences save = getSharedPreferences("Save",MODE_PRIVATE); final int level = save.getInt("Level",1); if(level >1 ){ }else { SharedPreferences.Editor editor = save.edit(); editor.putInt("Level",2); editor.commit(); } dialogEnd.show(); }else { numLeft = random.nextInt(10);//генерирум случайное число от 0 до 9 img_left.setImageResource(array.images1[numLeft]);//достаем из массива картинку img_left.startAnimation(animation); text_left.setText(array.texts1[numLeft]);//достаем из массива текст numRight = random.nextInt(10);//генерируем случайное число от 0-9 //цикл с предусловием, проверяющие равенство чисел начало while (numLeft==numRight){ numRight = random.nextInt(10); } //цикл с предусловием, проверяющие равенство чисел конец img_right.setImageResource(array.images1[numRight]);//достаем из массива картинку img_right.startAnimation(animation); text_right.setText(array.texts1[numRight]);//достаем из массива текст img_left.setEnabled(true);//включаем вновь ЛЕВУЮ картинку } } //условие касания картинки конец return true; } }); //обрабатываем нажатие на правую картинку конец } //системная кнопка начало @Override public void onBackPressed () { //обрабатываем нажатие кнопки -начало try { //вернуться назад к выбору уровня начало Intent intent = new Intent(Level1.this,GameLevels.class); //создали намерение для перехода startActivity(intent);//старт намерения finish();//закрыть этот класс //вернуться назад к выбору уровня крнец }catch (Exception e){ } //обрабатываем нажатие кнопки -конец } //ситсемная кнопка конец }
package com.example.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.validation.BindingResult; import javax.validation.Valid; import java.security.Principal; import java.util.ArrayList; @Controller public class HomeController { @Autowired private UserService userService; @Autowired UserRepository userRepository; @Autowired XOrderRepository xOrderRepository; @GetMapping("/test") public String showTest(Model model){ model.addAttribute("o", xOrderRepository); XOrder x = new XOrder(); x.calculatePrice("a, b,c"); return "test"; } @GetMapping("/register") public String showRegistrationPage(Model model) { model.addAttribute("user", new User()); return "registration"; } @PostMapping("/register") public String processRegistrationPage(@Valid @ModelAttribute("user") User user, BindingResult result, Model model) { model.addAttribute("user", user); if (result.hasErrors()) { return "registration"; } else { userService.saveUser(user); model.addAttribute("message", "User Account Created"); } return "redirect:/"; } @RequestMapping("/") public String listOrders(Principal principal, Model model) { if(userService.getUser() != null) { model.addAttribute("user_id", userService.getUser().getId()); } model.addAttribute("orders", xOrderRepository.findAll()); return "index"; } @GetMapping("/add") public String orderForm(Model model) { model.addAttribute("order", new XOrder()); return "orderform"; } @PostMapping("/process") public String processForm(@ModelAttribute XOrder order, Model model) { order.setUser(userService.getUser()); xOrderRepository.save(order); return "redirect:/"; } @RequestMapping("/login") public String login() { return "login"; } @RequestMapping("/secure") public String secure(Principal principal, Model model) { String username = principal.getName(); model.addAttribute("user", userRepository.findByUsername(username)); return "secure"; } @RequestMapping("/myorders") public String myOrders(Model model) { User user = userService.getUser(); /*ArrayList<XOrder> orders = (ArrayList<XOrder>) xOrderRepository.findAll(user);*/ /* model.addAttribute("orders", orders);*/ return "myorders"; } @RequestMapping("/allorders") public String allOrders(Model model) { if (userService.getUser() != null) { model.addAttribute("user_id", userService.getUser().getId()); } model.addAttribute("orders", xOrderRepository.findAll()); return "allorders"; } @RequestMapping("/detail/{id}") public String showMessage(@PathVariable("id") long id, Model model) { model.addAttribute("order", xOrderRepository.findById(id).get()); return "show"; } @RequestMapping("/update/{id}") public String updateMessage(@PathVariable("id") long id, Model model) { model.addAttribute("order", xOrderRepository.findById(id).get()); return "orderform"; } @RequestMapping("/delete/{id}") public String delMessage(@PathVariable("id") long id, Authentication auth) { xOrderRepository.deleteById(id); if (auth.getAuthorities().toString().equals("[ADMIN]")) { return "redirect:/allorders"; } else { return "redirect:/myorders"; } } }
package com.perhab.napalm.implementations.interfaceImplementation; import lombok.RequiredArgsConstructor; import java.util.concurrent.Callable; public class InnerClass implements InterfaceImplementation { @Override public Integer add(Integer a, Integer b) throws Exception { return new MyCallable(a, b).call(); } @RequiredArgsConstructor class MyCallable implements Callable<Integer> { private final Integer a; private final Integer b; @Override public Integer call() throws Exception { return a + b; } } }
/** * nGrinder common infra. */ package org.ngrinder.recorder.infra;
package lesson27.Ex3; public class Iphone extends Smartphone { private String operatingSystem; //hệ điều hành private String manufactureAddress; //nơi sản xuất private int timeWarranty; //thời gian bảo hành (năm) private String imei; //mã imei private String regionCode; //ví dụ J/A, VN/A, LL/A, ... public Iphone() { } public Iphone(String operatingSystem, String manufactureAddress, int timeWarranty, String imei, String regionCode) { this.operatingSystem = operatingSystem; this.manufactureAddress = manufactureAddress; this.timeWarranty = timeWarranty; this.imei = imei; this.regionCode = regionCode; } public Iphone(String seri, String brand, String name, float weight, float batteryCapacity, float inch, String operatingSystem, String manufactureAddress, int timeWarranty, String imei, String regionCode) { super(seri, brand, name, weight, batteryCapacity, inch); this.operatingSystem = operatingSystem; this.manufactureAddress = manufactureAddress; this.timeWarranty = timeWarranty; this.imei = imei; this.regionCode = regionCode; } public final String getOperatingSystem() { return operatingSystem; } public final void setOperatingSystem(String operatingSystem) { this.operatingSystem = operatingSystem; } public final String getManufactureAddress() { return manufactureAddress; } public final void setManufactureAddress(String manufactureAddress) { this.manufactureAddress = manufactureAddress; } public final int getTimeWarranty() { return timeWarranty; } public final void setTimeWarranty(int timeWarranty) { this.timeWarranty = timeWarranty; } public final String getImei() { return imei; } public final void setImei(String imei) { this.imei = imei; } public final String getRegionCode() { return regionCode; } public final void setRegionCode(String regionCode) { this.regionCode = regionCode; } @Override public void reset() { System.out.println("Khởi động lại Iphone"); } @Override public void turnOn() { System.out.println("Mở iphone lên"); } @Override public void turnOff() { System.out.println("Tắt iphone đi"); } @Override public void turnOffScreen() { System.out.println("Tắt màn hình iphone"); } @Override public void volumUp() { System.out.println("Tăng âm lượng lên"); } @Override public void volumDown() { System.out.println("Giảm âm lượng xuống"); } @Override public void lightUp() { System.out.println("Tăng độ sáng màn hình lên"); } @Override public void lightDown() { System.out.println("Giảm độ sáng màn hình"); } @Override public void connect(String something) { System.out.println("Kêt nối iphone với " + something); } @Override public void unlockWithPassword(String password) { System.out.println("Nhập " + password + " để mở khóa iphone"); } }
package convalida.annotations; import android.support.annotation.StringRes; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.SOURCE; /** * @author wellingtoncosta on 01/06/18 */ @Target(FIELD) @Retention(SOURCE) public @interface NumberLimitValidation { String min(); String max(); @StringRes int errorMessage(); boolean autoDismiss() default true; boolean required() default true; }
package com.example.dm2.ex20181109_1eval; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import org.w3c.dom.Text; public class Comprobacion extends AppCompatActivity { private TextView num1 , num2 ,texto1 , texto2, textDesp; private EditText resultado; private Spinner opciones; private String opcion; @Override protected void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); setContentView( R.layout.activity_comprobacion ); num1 = (TextView) findViewById( R.id.num1 ); num2 = (TextView) findViewById( R.id.num2 ); resultado = ( EditText ) findViewById( R.id.result ); texto1 = (TextView ) findViewById( R.id.salida ); texto2 = (TextView ) findViewById( R.id.salida2 ); textDesp = (TextView) findViewById( R.id.menuDespl ); opciones = (Spinner) findViewById( R.id.opciones ); } public void compro( View view ) { int result =14; if( Integer.parseInt( resultado.getText().toString() ) == result ){ texto1.setText( "¡ PERFECTO!" ); texto2.setText( "No eres una maquina" ); textDesp.setText("Elige una de las opciones en el desplegable"); final String[] options = {"Elija Opcion:","Darse de Alta" , "Ver Lista Museos"}; ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, options); adaptador.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item); opciones.setAdapter( adaptador ); opciones.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected( AdapterView< ? > parent, View view, int position, long id ) { opcion = opciones.getSelectedItem().toString(); nuevActivity( opcion ); } @Override public void onNothingSelected( AdapterView< ? > parent ) { } } ); }else{ finish(); } } public void nuevActivity(String opc ){ if( opcion.toString().equalsIgnoreCase( "Darse de Alta" )){ Intent alta = new Intent( this, AltaUsu.class ); startActivity( alta ); } if( opcion.toString().equalsIgnoreCase( "Ver lista museos" )){ Intent museos = new Intent( this, Museos.class ); startActivity( museos ); } } }
package com.tencent.mm.plugin.setting.ui.setting; import android.app.ProgressDialog; import android.content.Context; import android.os.Bundle; import android.widget.EditText; import android.widget.TextView; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.plugin.setting.a.f; import com.tencent.mm.plugin.setting.a.g; import com.tencent.mm.plugin.setting.a.i; import com.tencent.mm.ui.MMActivity; import com.tencent.mm.ui.base.h; public class SendFeedBackUI extends MMActivity implements e { private ProgressDialog eHw = null; private TextView mQC = null; private EditText meN; protected final int getLayoutId() { return g.edit_signature; } public void onCreate(Bundle bundle) { super.onCreate(bundle); initView(); } public void onDestroy() { com.tencent.mm.kernel.g.DF().b(153, this); super.onDestroy(); } protected final void initView() { setMMTitle(i.settings_feedbackui_title); this.meN = (EditText) findViewById(f.content); String stringExtra = getIntent().getStringExtra("intentKeyFrom"); if (stringExtra != null && stringExtra.equals("fromEnjoyAppDialog")) { this.mQC = (TextView) findViewById(f.view_question_text_view); this.mQC.setVisibility(0); this.mQC.setOnClickListener(new 1(this)); } setBackBtn(new 2(this)); addTextOptionMenu(0, getString(i.app_send), new 3(this)); } public final void a(int i, int i2, String str, l lVar) { if (this.eHw != null) { this.eHw.dismiss(); this.eHw = null; } if (i == 0 && i2 == 0) { h.a((Context) this, getString(i.settings_feedbackui_succ), getString(i.app_tip), new 4(this)); } else { h.a((Context) this, getString(i.settings_feedbackui_err), getString(i.app_tip), new 5(this)); } } }
package com.alexquasar.supplierParser.dto; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import java.io.File; import java.io.IOException; public class ConverterJSON { private ObjectMapper mapper; public ConverterJSON() { mapper = new ObjectMapper(); mapper.findAndRegisterModules(); mapper.enable(SerializationFeature.INDENT_OUTPUT); } public <T> T convertYAMLToJSON(String yamlText, Class<T> clazz) throws IOException { String jsonText = convertYAMLToJSON(yamlText); return mapper.readValue(jsonText, clazz); } public <T> T convertYAMLToJSON(File yamlFile, Class<T> clazz) throws IOException { String jsonText = convertYAMLToJSON(yamlFile); return mapper.readValue(jsonText, clazz); } public <T> T convertStringToJson(String content, Class<T> clazz) throws IOException { return mapper.readValue(content, clazz); } public String convertYAMLToJSON(String yamlText) throws IOException { Object obj = readYAML(yamlText); return mapper.writeValueAsString(obj); } public String convertYAMLToJSON(File yamlFile) throws IOException { Object obj = readYAML(yamlFile); return mapper.writeValueAsString(obj); } public Object readYAML(String yamlText) throws IOException { ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory()); return yamlReader.readValue(yamlText, Object.class); } public Object readYAML(File yamlFile) throws IOException { ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory()); return yamlReader.readValue(yamlFile, Object.class); } public <T> void writeJSON(String filePath, T obj) throws IOException { mapper.writeValue(new File(filePath), obj); } public <T> String writeJSONString(T obj) throws IOException { return mapper.writeValueAsString(obj); } }
package com.org.review.logging; import org.aspectj.lang.annotation.Pointcut; public class PointCuts { @Pointcut("within(com.org.review.*.*)") public void logEntryExit() { } }
package model; import java.util.List; /** * 下拉菜单Yml文件的实体类. * * @author SunYichuan */ public class ListYml { private String bigheader; private List<Section> toc; public String getBigheader() { return bigheader; } public void setBigheader(String bigheader) { this.bigheader = bigheader; } public void setToc(List<Section> toc) { this.toc = toc; } public List<Section> getToc() { return toc; } }
package day08ternaryoperator; import java.util.Scanner; public class TernaryOperator03 { public static void main(String[] args) { // kullanicidan iki sayi aliniz //kücük sayiiyi ekrana yazdirniz Scanner scan= new Scanner(System.in); System.out.println(" iki sayi giriniz"); double num1 = scan.nextDouble(); double num2 = scan.nextDouble(); double result = num1<=num2 ? num1 : num2; System.out.println(result); scan.close(); } }
package java2.views; import java2.businesslogic.logout.LogoutRequest; import java2.businesslogic.logout.LogoutResponse; import java2.businesslogic.logout.LogoutService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Scanner; @Component public class LogoutView implements View { @Autowired private LogoutService logoutService; @Override public void execute() { System.out.println("Logout with user!"); Scanner sc = new Scanner(System.in); System.out.print("Enter login:"); String login = sc.nextLine(); LogoutRequest request = new LogoutRequest(login, 'U'); LogoutResponse response = logoutService.logout(request); if(response.isSuccess()) { System.out.println("User '" + login + "' successfully logged out!"); } else { response.getErrors().forEach(error -> { System.out.println("ValidationError field = " + error.getField()); System.out.println("ValidationError message = " + error.getErrorMessage()); }); } } }
package com.av.db.layer.impl; import java.util.List; import org.apache.log4j.Logger; import org.hibernate.Criteria; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.av.db.dataobjects.Adeudo; import com.av.db.dataobjects.Tarjeta; import com.av.db.layer.interfaces.AdeudoLayer; import com.av.exceptions.AvException; /** * Clase que contiene la implementacion de funciones para la tabla de adeudos * utilizando la tecnologia de Hibernate * * @author J Francisco Ruvalcaba C * */ public class AdeudoLayerImpl extends HibernateDaoSupport implements AdeudoLayer { private static Logger log = Logger.getLogger(AdeudoLayerImpl.class); /** * Funcion que actualiza en la base de datos un adeudo en especifo */ @Override public void actualizar(Adeudo adeudo) throws AvException { log.info("Inicio - actualizar(Adeudo adeudo)"); log.debug("Id : " + adeudo.getId()); log.debug("Adeudo : " + adeudo.toString()); if (adeudo == null) { log.error("No se puede actualizar un adeudo nulo"); throw new AvException("Adeudo nulo a ser actualizado"); } if (adeudo.getId() < 0) { log.error("No se puede actualizar un adeudo con identificador " + "invalido"); throw new AvException("Adeudo con identificador invalido a ser " + "actualizado"); } getHibernateTemplate().update(adeudo); log.info("Fin - actualizar(Adeudo adeudo)"); }// actualizar /** * Funcion que agrega en la base de datos configura un nuevo adeudo */ @Override public void agregar(Adeudo adeudo) throws AvException { log.info("Inicio - agregar(Adeudo adeudo)"); log.debug("Adeudo : " + adeudo.toString()); if (adeudo == null) { log.error("No se puede agregar un adeudo nulo"); throw new AvException("Adeudo nulo a ser agregado"); } getHibernateTemplate().save(adeudo); log.info("Fin - agregar(Adeudo adeudo)"); }// agregar /** * Funcion que elimina un adeudo especifico de la base de datos configurada */ @Override public void eliminar(Adeudo adeudo) throws AvException { log.info("Inicio - eliminar(Adeudo adeudo)"); log.debug("Adeudo : " + adeudo.toString()); if (adeudo == null) { log.error("No se puede eliminar un adeudo nulo"); throw new AvException("Adeudo nulo a ser eliminado"); } if (adeudo.getId() < 0) { log .error("No se puede eliminar un adeudo con identificador negativo"); throw new AvException("Identificador negativo"); } getHibernateTemplate().delete(adeudo); log.info("Fin - eliminar(Adeudo adeudo)"); }// eliminar /** * Funcion que obtiene un adeudo de la base de datos configurada a partir de * su identificador */ @Override public Adeudo obtener(int id) { log.info("Inicio - obtener(int id)"); log.debug("Id : " + id); if (id < 0) { log .warn("No se puede obtener un adeudo con identificador negativo"); return null; } Adeudo tmp = getHibernateTemplate().get(Adeudo.class, id); if (tmp != null) { log.debug("Adeudo : " + tmp.toString()); } else { log.debug("Adeudo no encontrado"); } log.info("Fin - obtener(int id)"); return tmp; }// obtener /** * Funcion que obtiene el conjunto de todos los adeudos registrados en la * base de datos configurada */ @Override public Adeudo[] obtener() { log.info("Inicio - obtener()"); List<?> l = getSession().createCriteria(Adeudo.class) .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).addOrder( Order.asc(Adeudo.ID)).list(); Adeudo[] tmp = null; if (l != null && l.size() > 0) { log.debug("Cantidad obtenida : " + l.size()); tmp = new Adeudo[l.size()]; l.toArray(tmp); } log.info("Fin - obtener()"); return tmp; }// obtener /** * Funcion que obtiene los adeudos cargados en una tarjeta en especifico */ @Override public Adeudo[] obtener(Tarjeta t) { log.info("Inicio - obtener(Tarjeta t)"); List<?> l = getSession().createCriteria(Adeudo.class).add( Restrictions.eq(Adeudo.TARJETA, t)).setResultTransformer( Criteria.DISTINCT_ROOT_ENTITY).addOrder(Order.asc(Adeudo.ID)) .list(); Adeudo[] tmp = null; if (l != null && l.size() > 0) { log.debug("Cantidad obtenida : " + l.size()); tmp = new Adeudo[l.size()]; l.toArray(tmp); } log.info("Fin - obtener(Tarjeta t)"); return tmp; }// obtener }// AdeudoLayerImpl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package GProduction; import javax.microedition.lcdui.Graphics; import javax.microedition.lcdui.Image; /** * * @author Blondu */ public class ImageRotator_1 { private static int srcWidth, srcHeight; private int ARGB[]; private int sinRPlusH, cosRPlusH, w, h; private int minusHDiv2, hDiv2minusr, minusWDiv2, wDiv2minusr, wr, hr, iOriWr, temp1, temp2; private int[] ARGB_T; private double ip; private int grad, gradMinAlpha, gradPlusAlpha; private long time1, time2; static long time; private int[] jvalue1, jvalue2; private int wrPe2x10, hrPe2x10; private short cosInts[] = {1024, 1023, 1023, 1022, 1021, 1020, 1018, 1016, 1014, 1011, 1008, 1005, 1001, 997, 993, 989, 984, 979, 973, 968, 962, 955, 949, 942, 935, 928, 920, 912, 904, 895, 886, 877, 868, 858, 848, 838, 828, 817, 806, 795, 784, 772, 760, 748, 736, 724, 711, 698, 685, 671, 658, 644, 630, 616, 601, 587, 572, 557, 542, 527, 512, 496, 480, 464, 448, 432, 416, 400, 383, 366, 350, 333, 316, 299, 282, 265, 247, 230, 212, 195, 177, 160, 142, 124, 107, 89, 71, 53, 35, 17, 0, -17, -35, -53, -71, -89, -107, -124, -142, -160, -177, -195, -212, -230, -247, -265, -282, -299, -316, -333, -350, -366, -383, -400, -416, -432, -448, -464, -480, -496, -511, -527, -542, -557, -572, -587, -601, -616, -630, -644, -658, -671, -685, -698, -711, -724, -736, -748, -760, -772, -784, -795, -806, -817, -828, -838, -848, -858, -868, -877, -886, -895, -904, -912, -920, -928, -935, -942, -949, -955, -962, -968, -973, -979, -984, -989, -993, -997, -1001, -1005, -1008, -1011, -1014, -1016, -1018, -1020, -1021, -1022, -1023, -1023, -1024, -1023, -1023, -1022, -1021, -1020, -1018, -1016, -1014, -1011, -1008, -1005, -1001, -997, -993, -989, -984, -979, -973, -968, -962, -955, -949, -942, -935, -928, -920, -912, -904, -895, -886, -877, -868, -858, -848, -838, -828, -817, -806, -795, -784, -772, -760, -748, -736, -724, -711, -698, -685, -671, -658, -644, -630, -616, -601, -587, -572, -557, -542, -527, -512, -496, -480, -464, -448, -432, -416, -400, -383, -366, -350, -333, -316, -299, -282, -265, -247, -230, -212, -195, -177, -160, -142, -124, -107, -89, -71, -53, -35, -17, 0, 17, 35, 53, 71, 89, 107, 124, 142, 160, 177, 195, 212, 230, 247, 265, 282, 299, 316, 333, 350, 366, 383, 400, 416, 432, 448, 464, 480, 496, 512, 527, 542, 557, 572, 587, 601, 616, 630, 644, 658, 671, 685, 698, 711, 724, 736, 748, 760, 772, 784, 795, 806, 817, 828, 838, 848, 858, 868, 877, 886, 895, 904, 912, 920, 928, 935, 942, 949, 955, 962, 968, 973, 979, 984, 989, 993, 997, 1001, 1005, 1008, 1011, 1014, 1016, 1018, 1020, 1021, 1022, 1023, 1023, 1024}; private short sinInts[] = {0, 17, 35, 53, 71, 89, 107, 124, 142, 160, 177, 195, 212, 230, 247, 265, 282, 299, 316, 333, 350, 366, 383, 400, 416, 432, 448, 464, 480, 496, 511, 527, 542, 557, 572, 587, 601, 616, 630, 644, 658, 671, 685, 698, 711, 724, 736, 748, 760, 772, 784, 795, 806, 817, 828, 838, 848, 858, 868, 877, 886, 895, 904, 912, 920, 928, 935, 942, 949, 955, 962, 968, 973, 979, 984, 989, 993, 997, 1001, 1005, 1008, 1011, 1014, 1016, 1018, 1020, 1021, 1022, 1023, 1023, 1024, 1023, 1023, 1022, 1021, 1020, 1018, 1016, 1014, 1011, 1008, 1005, 1001, 997, 993, 989, 984, 979, 973, 968, 962, 955, 949, 942, 935, 928, 920, 912, 904, 895, 886, 877, 868, 858, 848, 838, 828, 817, 806, 795, 784, 772, 760, 748, 736, 724, 711, 698, 685, 671, 658, 644, 630, 616, 601, 587, 572, 557, 542, 527, 511, 496, 480, 464, 448, 432, 416, 400, 383, 366, 350, 333, 316, 299, 282, 265, 247, 230, 212, 195, 177, 160, 142, 124, 107, 89, 71, 53, 35, 17, 0, -17, -35, -53, -71, -89, -107, -124, -142, -160, -177, -195, -212, -230, -247, -265, -282, -299, -316, -333, -350, -366, -383, -400, -416, -432, -448, -464, -480, -496, -512, -527, -542, -557, -572, -587, -601, -616, -630, -644, -658, -671, -685, -698, -711, -724, -736, -748, -760, -772, -784, -795, -806, -817, -828, -838, -848, -858, -868, -877, -886, -895, -904, -912, -920, -928, -935, -942, -949, -955, -962, -968, -973, -979, -984, -989, -993, -997, -1001, -1005, -1008, -1011, -1014, -1016, -1018, -1020, -1021, -1022, -1023, -1023, -1024, -1023, -1023, -1022, -1021, -1020, -1018, -1016, -1014, -1011, -1008, -1005, -1001, -997, -993, -989, -984, -979, -973, -968, -962, -955, -949, -942, -935, -928, -920, -912, -904, -895, -886, -877, -868, -858, -848, -838, -828, -817, -806, -795, -784, -772, -760, -748, -736, -724, -711, -698, -685, -671, -658, -644, -630, -616, -601, -587, -572, -557, -542, -527, -512, -496, -480, -464, -448, -432, -416, -400, -383, -366, -350, -333, -316, -299, -282, -265, -247, -230, -212, -195, -177, -160, -142, -124, -107, -89, -71, -53, -35, -17, 0}; private int cosInt, sinInt; Image rotate_Img(Image img, int alpha) { w = img.getWidth(); h = img.getHeight(); ARGB = new int[w * h]; ip = Math.sqrt(w * w + h * h); grad = (int) (math.asin(h / ip) * 180 / Math.PI); img.getRGB(ARGB, 0, w, 0, 0, w, h); wDiv2minusr = w / 2; hDiv2minusr = h / 2; wrPe2x10 = wDiv2minusr << 7; hrPe2x10 = hDiv2minusr << 7; time1 = System.currentTimeMillis(); cosInt = cosInts[alpha]; sinInt = sinInts[alpha]; wr = rotWidth(alpha) >> 10; hr = rotHeight(alpha) >> 10; wr++; hr++; ARGB_T = new int[(wr) * (hr)]; minusWDiv2 = -wr / 2; minusHDiv2 = -hr / 2; jvalue1 = new int[wr]; jvalue2 = new int[wr]; for (int i = 0; i < wr; i++) { jvalue1[i] = ((cosInt * (i + minusWDiv2)) >> 3) + wrPe2x10; jvalue2[i] = ((-sinInt * (i + minusWDiv2)) >> 3) + hrPe2x10; } for (int i = 0; i < hr; i++) { sinRPlusH = (sinInt * (i + minusHDiv2)) >> 3; cosRPlusH = (cosInt * (i + minusHDiv2)) >> 3; iOriWr = i * wr; for (int j = 0; j < wr; j++) { temp1 = (jvalue1[j] + sinRPlusH) >> 7; temp2 = (cosRPlusH + jvalue2[j]) >> 7; if (temp1 >= 0 && temp2 >= 0 && temp1 < w && temp2 < h) { ARGB_T[iOriWr + j] = ARGB[temp2 * w + temp1]; } } } time2 = System.currentTimeMillis(); time = time2 - time1; return Image.createRGBImage(ARGB_T, wr, hr, true); } private int rotWidth(int alpha) { gradMinAlpha = grad - alpha; gradPlusAlpha = grad + alpha; while (gradMinAlpha < 0) { gradMinAlpha += 360; } while (gradPlusAlpha > 360) { gradPlusAlpha -= 360; } if (alpha >= 0 && alpha <= 90) { return (int) (cosInts[gradMinAlpha] * ip); } else if (alpha >= 180 && alpha <= 270) { return -(int) (cosInts[gradMinAlpha] * ip); } else if (alpha > 270) { return (int) (cosInts[gradPlusAlpha] * ip); } else { return -(int) (cosInts[gradPlusAlpha] * ip); } } private int rotHeight(int alpha) { if (alpha >= 0 && alpha <= 90) { return (int) (sinInts[gradPlusAlpha] * ip); } else if (alpha >= 180 && alpha <= 270) { return -(int) (sinInts[gradPlusAlpha] * ip); } else if (alpha > 270) { return (int) (sinInts[gradMinAlpha] * ip); } else { return -(int) (sinInts[gradMinAlpha] * ip); } } /* static Image resizeImage(Image src, int width, int height) { if (width != 0 && height != 0) { srcWidth = src.getWidth(); srcHeight = src.getHeight(); Image tmp = Image.createImage(width, srcHeight); Graphics g = tmp.getGraphics(); int ratio = (srcWidth << 16) / width; int pos = ratio / 2; //Redimensionare orizontala for (int x = 0; x < width; x++) { g.setClip(x, 0, 1, srcHeight); g.drawImage(src, x - (pos >> 16), 0, Graphics.LEFT | Graphics.TOP); pos += ratio; } Image resizedImage = Image.createImage(width, height); g = resizedImage.getGraphics(); ratio = (srcHeight << 16) / height; pos = ratio / 2; //Redimensionare verticala for (int y = 0; y < height; y++) { g.setClip(0, y, width, 1); g.drawImage(tmp, 0, y - (pos >> 16), Graphics.LEFT | Graphics.TOP); pos += ratio; } return resizedImage; } return Image.createImage(1, 1); }*/ }
package Test; import GameLogic.Dice; import org.junit.jupiter.api.Test; import java.util.ArrayList; import static org.junit.jupiter.api.Assertions.*; class DiceTest { @Test void testThrowDice() { Dice dice = new Dice(); int roll; for(int i=0;i<100000;i++) { roll = dice.throwDice(); if(roll < 1 || roll > 6) { fail("Number is outside the range of a dice!"); } } } @Test void testGetRolls() { Dice dice = new Dice(); dice.rollXDice(5); if(!(dice.getRolls() instanceof ArrayList)) { fail("Type returned is incorrect"); } } //method not implemented yet /* @Test void determineRollWinner() { } */ @Test void testRollXDice() { Dice dice = new Dice(); for(int i=0;i<100;i++) { dice.rollXDice(i); if(dice.getRolls().size() != i) { fail("Method returning incorrect number of rolls"); } } } }
package com.simonk.gui.configurations.springconfig; import java.util.HashMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.Scope; import com.github.sergueik.jprotractor.NgWebDriver; import com.simonk.gui.configurations.CucumberWorld; import com.simonk.gui.configurations.FrameworkProperties; import com.simonk.gui.configurations.webdriver.Driver; import com.simonk.gui.pageobjects.AngularCalculatorPage; import com.simonk.gui.utility.exceptions.InvalidDriverTypeSelectedException; import com.simonk.gui.utility.localisation.LocaleHelper; import com.simonk.gui.utility.reporting.ReportEnvironmentHelper; @Configuration @PropertySource(value = {"classpath:/framework.properties"}) public class SpringConfig { private static final Logger LOG = LogManager.getLogger(SpringConfig.class); @Bean public CucumberWorld cucumberWorld() { return new CucumberWorld(); } @Bean(destroyMethod = "quit") @Scope("singleton") public Driver driver() { Driver wd = null; try { wd = new Driver(properties()); } catch(InvalidDriverTypeSelectedException ex) { LOG.debug("Invalid driver specified" + ex); System.exit(1); } return wd; } @Bean @Scope("singleton") public NgWebDriver ngDriver() { NgWebDriver ng = new NgWebDriver(driver()); return ng; } @Bean public FrameworkProperties properties() { return new FrameworkProperties(); } @Bean @Scope("singleton") public LocaleHelper localeHelper() { return new LocaleHelper(properties().getApplicationLanguage()); } @Bean public AngularCalculatorPage angularLoginPage() { return new AngularCalculatorPage( ngDriver(), properties().seleniumImplicitWaitTime(), properties().getTestServerBaseAddress() ); } @Bean public ReportEnvironmentHelper envHelper() throws Exception { HashMap<String, String> props = new HashMap<String, String>(); props.put("Language:", properties().getApplicationLanguage()); props.put("Browser:", properties().getBrowserType()); props.put("Platform:", properties().getPlatformType()); props.put("Environment:", properties().getTestServerBaseAddress()); props.put("Architecture:", properties().getGridOrLocal()); props.put("Grid Address:", properties().getGridAddress()); props.put("Selenium Wait:", String.valueOf(properties().seleniumImplicitWaitTime())); props.put("Product Name:", String.valueOf(properties().getProductName())); props.put("Database Conn:", String.valueOf(properties().getDatabaseConn())); props.put("Angular Frontend:", String.valueOf(properties().getAngular())); return new ReportEnvironmentHelper(props); } }
package org.example.api; import org.example.client.RetrofitClient; import org.example.model.AuthRequest; import org.example.model.AuthResponse; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.POST; public interface AuthApi extends RetrofitClient.Api { @POST("api/authenticate") Call<AuthResponse> authenticate(@Body AuthRequest authRequest); }
/* * Copyright © 2019 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.dom.builder.shared; /** Tests for {@link HtmlParagraphBuilder}. */ public class HtmlParagraphBuilderTest extends ElementBuilderTestBase<ParagraphBuilder> { @Override protected ParagraphBuilder createElementBuilder(ElementBuilderFactory factory) { return factory.createParagraphBuilder(); } @Override protected void endElement(ElementBuilderBase<?> builder) { builder.endParagraph(); } @Override protected ParagraphBuilder startElement(ElementBuilderBase<?> builder) { return builder.startParagraph(); } }
package com.jim.multipos.utils.rxevents.admin_auth_events; public class InfoEvent { String mail; public InfoEvent(String mail) { this.mail = mail; } public String getMail() { return mail; } }
/* */ package com.cleverfishsoftware.estreaming.streamprocessor; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import java.util.Arrays; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; /** * * @author peter */ public class KafkaStreamHandler extends SimpleChannelInboundHandler<String> { private static AtomicInteger instance = new AtomicInteger(0); private final ExecutorService executor; public KafkaStreamHandler() { String bootstrapServers = System.getProperty("bootstrap.servers"); if (bootstrapServers == null || bootstrapServers.length() == 0) { bootstrapServers = "localhost:9092"; } String consumerGroupId = System.getProperty("group.id"); if (consumerGroupId == null || consumerGroupId.length() == 0) { consumerGroupId = "KafkaStreamHandler"; } String consumerId = System.getProperty("consumer.id"); if (consumerId == null || consumerId.length() == 0) { consumerId = "KafkaStreamHandler-" + instance.incrementAndGet(); } String topicOffset = System.getProperty("topicOffset"); if (topicOffset == null || topicOffset.length() == 0) { topicOffset = "--from-beginning"; } String topic = System.getProperty("topic"); if (topic == null || topic.length() == 0) { topic = "topic-1"; } Properties kafkaProperties = new Properties(); kafkaProperties.put("bootstrap.servers", bootstrapServers); kafkaProperties.put("group.id", consumerGroupId); kafkaProperties.put("enable.auto.commit", "true"); kafkaProperties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); kafkaProperties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); kafkaProperties.put("session.timeout.ms", "10000"); kafkaProperties.put("fetch.min.bytes", "50000"); kafkaProperties.put("receive.buffer.bytes", "262144"); kafkaProperties.put("max.partition.fetch.bytes", "2097152"); executor = Executors.newSingleThreadExecutor(); RunnableKafkaConsumer consumer = new RunnableKafkaConsumer(consumerId, kafkaProperties, Arrays.asList(new String[]{topic}), 0); executor.submit(consumer); } @Override public void channelActive(ChannelHandlerContext ctx) { ctx.writeAndFlush("HELO: Type the path of the file to retrieve.\n"); } @Override public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (ctx.channel().isActive()) { ctx.writeAndFlush("ERR: " + cause.getClass().getSimpleName() + ": " + cause.getMessage() + '\n').addListener(ChannelFutureListener.CLOSE); } } }
package com.sharpower.action; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.opensymphony.xwork2.ActionSupport; import com.sharpower.entity.UserOperationRecode; import com.sharpower.service.UserOperationRecodeService; public class AjaxUserOperationRecodeAction extends ActionSupport { private static final long serialVersionUID = 1L; private UserOperationRecodeService userOperationRecodeService; private List<UserOperationRecode> userOperationRecodes = new ArrayList<>(); private Map<String, Object> result = new HashMap<>(); private Integer userId; private Date beginTime; private Date endTime; private int page; private int rows; public void setUserOperationRecodeService(UserOperationRecodeService userOperationRecodeService) { this.userOperationRecodeService = userOperationRecodeService; } public List<UserOperationRecode> getUserOperationRecodes() { return userOperationRecodes; } public Map<String, Object> getResult() { return result; } public void setUserId(Integer userId) { this.userId = userId; } public void setBeginTime(Date beginTime) { this.beginTime = beginTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public void setPage(int page) { this.page = page; } public void setRows(int rows) { this.rows = rows; } public String findUserOperationRecode(){ String hql = "from UserOperationRecode ur where ur.user.id=? and ur.dateTime>? and ur.dateTime<?"; long total; try { userOperationRecodes = userOperationRecodeService.findEntityByHQLPaging(hql, (page-1)*rows, rows, userId, beginTime, endTime); total = (Long) userOperationRecodeService.uniqueResult("SELECT count(*) From UserOperationRecode"); result.put("total", total); result.put("rows", userOperationRecodes); } catch (Exception e) { e.printStackTrace(); } return SUCCESS; } }
package auth.nosy.tech.nosyauth.mapper; import auth.nosy.tech.nosyauth.dto.TokenCollectionDto; import auth.nosy.tech.nosyauth.model.TokenCollection; import org.mapstruct.Mapper; import org.mapstruct.factory.Mappers; @Mapper public abstract class TokenCollectionMapper { public static final TokenCollectionMapper INSTANCE = Mappers.getMapper( TokenCollectionMapper.class ); public abstract TokenCollectionDto toTokenCollectionDto(TokenCollection tokenCollection); }
package com.数据解析.XML解析.使用DOM; //特点: //1.基于树形结构 //2.一次性加载文本到内存中,可以随机访问,(同时耗内存) , 更适合web开发,灵活性强 import org.junit.jupiter.api.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.InputStream; public class XMLDemo { @Test public void parseXML_() throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/数据解析/XML解析/person2.xml"); Document doc = documentBuilder.parse(is); NodeList adress_list = doc.getElementsByTagName("linkman"); System.out.println("一共有地址信息 "+adress_list.getLength()+" 个"); Node node = null; NodeList chridList = null; for(int i=0;i<adress_list.getLength();i++){ node = adress_list.item(i); //此方法获取的子节点 ,不仅包含子孙节点,还包含空格(text) chridList = node.getChildNodes(); for(int j=0;j<chridList.getLength();j++){ //此处要判断节点的名字以区分空格换行和孙子节点 if(chridList.item(j).getNodeName().equals("name")){ System.out.println(chridList.item(j).getFirstChild().getNodeValue()); }else if(chridList.item(j).getNodeName().equals("email")){ System.out.println(chridList.item(j).getFirstChild().getNodeValue()); } } } } }
package hofbo.tactical_material_game; import android.util.Log; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.HashMap; import java.util.Map; /** * Created by Deniz on 01.02.2018. */ public class Lobby { private FirebaseDatabase db = FirebaseDatabase.getInstance(); private DatabaseReference mDatabase = db.getReference(); public Lobby() { } public Lobby(String player1, String player2){ } public void createLobby(String player1){ Lobby lobby = new Lobby(); DatabaseReference pushedPostRef = mDatabase.child("looby").push(); String postId = pushedPostRef.getKey(); Log.d("LOBBY:",postId); Map<String, String> lobbys = new HashMap<>(); lobbys.put("player1", player1); mDatabase.child("lobby").child(player1).setValue(lobbys); } }
package br.com.bytebank.banco.teste.util; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import br.com.bytebank.banco.modelo.Conta; import br.com.bytebank.banco.modelo.ContaCorrente; import br.com.bytebank.banco.modelo.ContaPoupanca; public class TesteLambda { public static void main(String[] args) throws Exception { List<Conta> lista = new ArrayList<>(); lista.add(new ContaPoupanca(933, 66666)); lista.add(new ContaCorrente(933, 77777)); lista.add(new ContaPoupanca(933, 11111)); lista.add(new ContaCorrente(933, 22222)); lista.add(new ContaPoupanca(933, 99999)); lista.add(new ContaCorrente(933, 88888)); lista.add(new ContaPoupanca(933, 55555)); lista.add(new ContaCorrente(933, 44444)); //cria nomes lista.get(0).getTitular().setNome("AAAAAA"); lista.get(1).getTitular().setNome("BBBBBB"); lista.get(2).getTitular().setNome("CCCCCC"); lista.get(3).getTitular().setNome("DDDDDD"); lista.get(4).getTitular().setNome("EEEEEE"); lista.get(5).getTitular().setNome("FFFFFF"); lista.get(6).getTitular().setNome("GGGGGG"); lista.get(7).getTitular().setNome("HHHHHH"); // cria saldos double valor = 0.0; for (Conta conta : lista) { valor += 100.0; conta.deposita(valor); } // ordena lista Scanner input = new Scanner(System.in); int opcao; boolean fim = false; while (!fim) { try { System.out.println("Digite o método de ordenacao: " + "(1-Numero) (2-Agencia) (3-Saldo) (4-Nome) (5-fim)"); opcao = Integer.parseInt(input.next()); switch (opcao) { case 1: lista.sort((c1, c2) -> Integer.compare(c1.getNumero(), c2.getNumero())); break; case 2: lista.sort((c1, c2) -> Integer.compare(c1.getAgencia(), c2.getAgencia())); break; case 3: lista.sort(null); break; case 4: lista.sort((c1, c2) -> c1.getTitular().getNome().compareToIgnoreCase(c2.getTitular().getNome())); break; case 5: fim = true; break; default: System.out.println("Opção inválida, Digite novamente!"); break; } lista.forEach(conta -> System.out.println(conta + ", " + conta.getTitular().getNome() + ", " + conta.getSaldo())); } catch (Exception e) { System.out.println("Opção não é númerica, Digite Novamente!"); } } input.close(); } }
package day17arraylists; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Lists01 { public static void main(String[] args) { //How to create a list //1.Way ArrayList<Integer> list1 = new ArrayList<>(); //how to print a list on the console System.out.println(list1); //[] //How to add elements into a list list1.add(12); list1.add(11); list1.add(10); //put an elements specific place list1.add(1, 13); System.out.println(list1); //[12, 13, 11, 10] //How to sort list elements in ascending order Collections.sort(list1); System.out.println(list1); //[10, 11, 12, 13] // how to get specific elements from a list System.out.println(list1.get(2));//12 // System.out.println(list1.get(4)); // There is no index 4, because of that get run time error //2.Way List<Integer> list2 = new ArrayList<>(); list2.add(9); list2.add(2); list2.add(19); list2.add(4); list2.add(71); list2.add(-3); /* Type code to find the minimum and maximum value from the list2 */ Collections.sort(list2); int min = list2.get(0); int max = list2.get(list2.size()-1); System.out.println(min +" : " + max); //-3 : 71 //how to check is a list is empty list or not System.out.println(list2.isEmpty()); // false because my list is not empty List<String> list3 = new ArrayList<>(); System.out.println(list3.isEmpty()); // true //How to remove an element from a list by using index //Below code will remove the element at index 2, and will return the removed element System.out.println(list2.remove(2)); // 4==> removed element System.out.println(list2);// [-3, 2, 9, 19, 71] // System.out.println(list2.remove(6)); // run time error //How to remove an element from a list by using the element value //Note: For integer lists, you can not remove an element by using element value, // because when you put integer inside remove method it will accept as index. // list2.remove(19); list3.add("Ali"); list3.add("Veli"); list3.add("Mary"); list3.add("Sunny"); list3.add("Tony"); System.out.println(list3); //[Ali, Veli, Mary, Sunny, Tony] System.out.println(list3.remove("Mary"));//true System.out.println(list3); //[Ali, Veli, Sunny, Tony] //Remove Veli and add Velihan in the index of Veli //1. Way int idx = list3.indexOf("Veli"); list3.remove("Veli"); list3.add(idx, "Velihan"); System.out.println(list3);//[Ali, Velihan, Sunny, Tony] //2.Way //set() method is used to update an element by using index //set() method returns the previous element System.out.println(list3.set(list3.indexOf("Sunny"), "Jhonny")); //Sunny System.out.println(list3); //[Ali, Velihan, Jhonny, Tony] } }
package servlets; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MessageServlet extends HttpServlet { private String message; public void init(ServletConfig config) throws ServletException { message = config.getInitParameter("message"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.getWriter().println("<h1>" + message + "</h1>"); } }
package Forms; /** * Class, that contains 2 strings and using cmpThread * compares them symbol by symbol */ public class stringComparisonThread extends Thread { private String firstString; private String secondString; private cmpThread compareChars; private String result; /** * Constructor * @param first first line * @param second second line */ public stringComparisonThread(String first, String second) { firstString = first; secondString = second; } /** * @return result string */ public String getResult() { return result; } /** * sends 2 symbols to a cmpThread and compares 2 strings symbol by symbol */ @Override public void run() { if (firstString.length() != secondString.length()) { result = "Strings have different length."; return; } for (int i = 0; (i < firstString.length() && i < secondString.length()); i++) { compareChars = new cmpThread(firstString.charAt(i), secondString.charAt(i)); compareChars.start(); try { compareChars.join(); } catch (InterruptedException e) { e.printStackTrace(); } if (!compareChars.getResult()) { result = "Strings are different. First different symbol is " + (i + 1) + ". Symbol '" + firstString.charAt(i) + "' was changed with '" + secondString.charAt(i) + "'."; return; } } result = "Strings are equal."; return; } }
package leetcode.easy; import common.PrintableMain; import java.util.ArrayList; import java.util.Comparator; import java.util.PriorityQueue; /** * Created by Choen-hee Park * User : chpark * Date : 14/08/2020 * Time : 1:14 AM */ public class Solution021_MergeTwoSortedLists extends PrintableMain { private static class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } public static void main(String[] args) { ListNode l3 = new ListNode(4); ListNode l2 = new ListNode(2, l3); ListNode l1 = new ListNode(1, l2); ListNode l6 = new ListNode(4); ListNode l5 = new ListNode(3, l6); ListNode l4 = new ListNode(1, l5); ListNode result = mergeTwoLists(l1, l4); while (result != null) { System.out.print(result.val + " "); result = result.next; } System.out.println(); result = mergeTwoLists(null, null); while (result != null) { System.out.print(result.val + " "); result = result.next; } System.out.println(); } private static ListNode mergeTwoLists(ListNode l1, ListNode l2) { PriorityQueue<Integer> pq = new PriorityQueue<>(); while (l1 != null) { pq.add(l1.val); l1 = l1.next; } while (l2 != null) { pq.add(l2.val); l2 = l2.next; } if (pq.isEmpty()) return null; ListNode result = new ListNode(pq.poll()); /* while (!pq.isEmpty()) { ListNode newNode = new ListNode(pq.poll()); ListNode current = result; while (current.next != null) { current = current.next; } current.next = newNode; } */ ListNode current = result; while (!pq.isEmpty()) { current.next = new ListNode(pq.poll()) ; current= current.next; } return result; } }
package menuItem; import input.MouseInput; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.image.BufferedImage; import util.Util; public class MenuItem { private BufferedImage image; private Rectangle hitBox; private MouseInput mouse; private String stateChange; private int x, y; public MenuItem(String path, String stateChange, MouseInput mouse, int x, int y) { this.mouse = mouse; this.x = x; this.y = y; this.stateChange = stateChange; image = Util.getImage(path); hitBox = new Rectangle(x, y, image.getWidth(), image.getHeight()); } public String clicked() { if (hitBox.contains(mouse.getX(), mouse.getY())) { if (mouse.isLeftMouseClicked()) { return stateChange; } } return null; } public void render(Graphics g) { g.drawImage(image, x, y, null); } public String getStateChange() { return stateChange; } public Rectangle getHitBox() { return hitBox; } }
package bruteforcegen; public class NextString { public String getNextKey(String key){ char[] chars = key.toCharArray(); int size = chars.length; boolean acarreo = Character.isLetterOrDigit(chars[size-1]); for(int i = size-1 ; i>=0 ;i--) { if(acarreo)chars[i]++; if(!Character.isLetterOrDigit(chars[i])){ chars[i]--; if(chars[i]=='9') { chars[i]='a'; acarreo = false; } else if(chars[i]=='Z') { chars[i]= '0'; acarreo = true; } }else{ acarreo = false; } } char[] chars2 =null; if(acarreo){ chars2 = new char[chars.length+1]; for(int i=0;i<chars.length;i++){ chars2[i+1] = chars[i]; } chars2[0]='0'; } String nextCve = (acarreo)?new String(chars2):new String(chars); // System.out.println(nextCve); return nextCve; //return null; } public static String getNextString(String value){ char[] array = value.toCharArray(); char[] nextSequence = new char[array.length]; int size = array.length; boolean firstLoop = true; boolean increaseNext = false; for(int index = size-1 ; index>=0 ;index--) { char currentChar = array[index]; if(firstLoop || increaseNext){ Object[] nextKey = NextCharCalc.getNextKey(currentChar); currentChar = (Character)nextKey[0]; increaseNext = (Boolean)nextKey[1]; firstLoop = false; } nextSequence[index] = currentChar; } String nextString = new String(nextSequence); if( increaseNext ){ nextString = "0" + nextString; } return nextString; } }
package sickbook.Background; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.NoSuchProviderException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendMail extends AsyncTask{ private Context context; private Session session; private String email; private String subject; private String message; private ProgressDialog progressDialog; /** * Constructor for the SendMail object * @param context : the app context * @param email : email to be sending to * @param subject : subject of the email * @param message : the message in the email */ public SendMail(Context context, String email, String subject, String message){ this.context = context; this.email = email; this.subject = subject; this.message = message; } @Override protected void onPreExecute() { super.onPreExecute(); } /** * An async task that runs in the background of the app * gets the email of the sender and the receiver * Sends an email to the address of the receiver wit the given subject and message * @param objects : objects array to run in background * @return : null */ @Override protected Object doInBackground(Object[] objects) { Properties properties = new Properties(); // the properties are the setting on which the email will sent and through which medium properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.ssl.trust", "smtp.gmail.com"); properties.setProperty("mail.smtp.ssl.enable", "true"); properties.put("mail.smtp.user", Config.EMAIL); Session session = Session.getDefaultInstance(properties); //create a session with the given properties Message msg = new MimeMessage(session); try { msg.setFrom(new InternetAddress(Config.EMAIL)); // from email InternetAddress[] toAddresses = { new InternetAddress(email) }; //set address ot the receiver msg.setRecipients(Message.RecipientType.TO, toAddresses); //to email msg.setSubject(subject); //set subject msg.setText(message);//set message } catch (MessagingException e) { e.printStackTrace(); } // sends the e-mail Transport t = null; try { t = session.getTransport("smtp"); t.connect(Config.EMAIL, Config.PASSWORD); t.sendMessage(msg, msg.getAllRecipients()); t.close(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } return null; } }
package Arrays; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class MapIntoArrayList { public static void main(String[] args) { Map<String, Integer> marks = new HashMap<String, Integer>(); marks.put("A", 100); marks.put("B", 100); marks.put("C", 100); marks.put("D", 100); //System.out.println(marks); // Iterator it = marks.keySet().iterator(); // // while (it.hasNext()) { // it.next(); // } List<String> list = new ArrayList<String>(marks.keySet()); System.out.println(list); List<Integer> l = new ArrayList<Integer>(marks.values()); System.out.println(l); } }
package co.fcode.ged18.estrutura; /*************** *@author UANJOS* ***************/ import java.util.ArrayList; import java.util.Collections; import co.fcode.ged18.*; public class Societario { //-------------------VARIÁVEIS TIPOS DE ORGANIZAÇÃO-------------------// private Organizacao Atos; // ATOS private Organizacao Fed; // FEDERAL private Organizacao Est; // ESTADUAL private Organizacao Mun; // MUNICIPAL private Organizacao Dvrs; // DIVERSOS //-----------------------FIM DA DECLARAÇÃO----------------------------// //-------------------VARIÁVEIS TIPOS DE DOCUMENTOS-------------------// private TipoDocumento DocConsoc; // CONTRATO SOCIAL private TipoDocumento DocAltcon; // ALTERAÇÃO CONTRATUAL private TipoDocumento DocDist; // DISTRATO private TipoDocumento DocAta; // ATA DE REUNIÃO/ASSEMBLÉIA private TipoDocumento DocReqemp; // REQUERIMENTO DE EMPRESÁRIO private TipoDocumento DocEnquad; // ENQUADRAMENTO private TipoDocumento DocDesenq; // DESENQUADRAMENTO private TipoDocumento DocReenq; // REENQUADRAMENTO private TipoDocumento DocBalreg; // BALANÇO REGISTRADO private TipoDocumento DocProinc; // PROTOCOLO E JUSTIFICAÇÃO private TipoDocumento DocParal; // PARALISAÇÃO private TipoDocumento DocLavpal; // LAUDO DE AVALIAÇÃO DO PATRIMÔNIO LÍQUIDO private TipoDocumento DocEstat; // ESTATUTO private TipoDocumento DocCnpj; // CNPJ private TipoDocumento DocCertbx; // CERTIDÃO DE BAIXA private TipoDocumento DocInsest; // INSCRIÇÃO ESTADUAL private TipoDocumento DocLdexcb; // CERTIDÃO DE BAIXA DA INSCRIÇÃO ESTADUAL private TipoDocumento DocCertcb; // CERTIF DE APROVAÇÃO DO CORPO DE BOMBEIROS private TipoDocumento DocAlvara; // ALVARÁ private TipoDocumento DocFincad; // FICHA DE INFORMAÇÕES CADASTRAIS private TipoDocumento DocBxiss; // MEMORANDO DE BAIXA ISS private TipoDocumento DocBxalv; // BAIXA DO ALVARÁ private TipoDocumento DocSanipj; // TERMO DE LICENÇA DE FUNCIONAMENTO SANITÁRIO private TipoDocumento DocCis; // CERTIFICADO DE INSPEÇÃO SANITÁRIA private TipoDocumento DocSanipf; // TERMO DE ASSENTIMENTO SANITÁRIO private TipoDocumento DocSmtr; // CERTIDÃO DE ASSESSIBILIDADE private TipoDocumento DocSmo; // DECLARAÇÃO DE REBAIXAMENTO DE MEIO FIO private TipoDocumento DocCinstc; // CERTIDÃO DE INSTALAÇÃO COMERCIAL private TipoDocumento DocHabite; // HABITE-SE private TipoDocumento DocCtrans; // CERTIDÃO DE TRANSFORMAÇÃO DE USO private TipoDocumento DocSmac; // REQUERIMENTO DE MEIO AMBIENTE private TipoDocumento DocPlpubl; // PLANTA DE AUTORIZAÇÃO DE PUBLICIDADE private TipoDocumento DocTxmeca; // TAXA DE MESAS E CADEIRAS private TipoDocumento DocTxpubl; // TAXA DE PUBLICIDADE private TipoDocumento DocIptu; // IPTU private TipoDocumento DocConloc; // CONTRATO DE LOCAÇÃO private TipoDocumento DocCpf; // CPF DOS SÓCIOS private TipoDocumento DocRg; // RG DOS SÓCIOS private TipoDocumento DocCompre; // COMPROVANTE DE RESIDÊNCIA DOS SÓCIOS private TipoDocumento DocRegpro; // REGISTRO PROFISSIONAL private TipoDocumento DocPcv; // PROMESSA DE COMPRA E VENDA private TipoDocumento DocNit; // NIT - NUMERO DE INSCRIÇÃO DO TRABALHADOR/SÓCIO private TipoDocumento DocProtoc; // PROTOCOLO private TipoDocumento DocQdrsoc; // QUADRO SOCIETÁRIO //-----------------------FIM DA DECLARAÇÃO----------------------------// //-------------------LISTA DE TIPOS DE DOCUMENTOS---------------------// private ArrayList<TipoDocumento> TiposAtos; // TIPOS ATOS private ArrayList<TipoDocumento> TiposFed; // TIPOS FEDERAL private ArrayList<TipoDocumento> TiposEst; // TIPOS ESTADUAL private ArrayList<TipoDocumento> TiposMun; // TIPOS MUNICIPAL private ArrayList<TipoDocumento> TiposDvrs; // TIPOS DIVERSOS //-----------------------FIM DA DECLARAÇÃO----------------------------// private ArrayList<Organizacao> organizacoes; private Unidade soc; public Societario(){ setDocConsoc(new TipoDocumento(1,"Contrato Social","CONSOC")); setDocAltcon(new TipoDocumento(2,"Alteração Contratual","ALTCON")); setDocDist(new TipoDocumento(3,"Distrato","DIST")); setDocAta(new TipoDocumento(4,"Ata de Reunião-Assembleia","ATA")); setDocReqemp(new TipoDocumento(5,"Requerimento de Empresário","REQEMP")); setDocEnquad(new TipoDocumento(6, "Enquadramento", "ENQUAD")); setDocDesenq(new TipoDocumento(7,"Desenquadramento","DESENQ")); setDocReenq(new TipoDocumento(8,"Reequadramento","REENQ")); setDocBalreg(new TipoDocumento(9,"Balanço Registrado","BALREG")); setDocProinc(new TipoDocumento(10,"Protocolo e Justificação","PROINC")); setDocParal(new TipoDocumento(11,"Paralisação","PARAL")); setDocLavpal(new TipoDocumento(12,"Laudo de Avaliação do Patrimônio Líquido","LAVPAL")); setDocEstat(new TipoDocumento(13,"Estatuto","ESTAT")); setDocCnpj(new TipoDocumento(14,"CNPJ","CNPJ")); setDocCertbx(new TipoDocumento(15, "Certidão de Baixa", "CERTBX")); setDocInsest(new TipoDocumento(16, "Inscrição Estadual", "INSEST")); setDocLdexcb(new TipoDocumento(17, "Certidão de Baixa de Inscrição Estadual", "LDEXCB")); setDocCertcb(new TipoDocumento(18, "Certificado de Aprovação do Corpo de Bombeiros", "CERTCB")); setDocAlvara(new TipoDocumento(19, "Alvará", "ALVARA")); setDocFincad(new TipoDocumento(20, "Ficha de Informações Cadastrais", "FINCAD")); setDocBxiss(new TipoDocumento(21, "Memorando de Baixa Iss", "BXISS")); setDocBxalv(new TipoDocumento(22, "Baixa do Alvará", "BXALV")); setDocSanipj(new TipoDocumento(23, "Termo de Licensa de Funcionamento Sanitário", "SANIPJ")); setDocCis(new TipoDocumento(24, "Certificado de Inspeção Sanitária", "CIS")); setDocSanipf(new TipoDocumento(25, "Termo de Assentimento Sanitário", "SANIPF")); setDocSmtr(new TipoDocumento(26, "Certidão de Acessibilidade", "SMTR")); setDocSmo(new TipoDocumento(27, "Declaração de Rebaixamento de Meio Fio", "SMO")); setDocCinstc(new TipoDocumento(28, "Certidão de Instalação Comercial", "CINSCT")); setDocHabite(new TipoDocumento(29, "Habite-se", "HABITE")); setDocCtrans(new TipoDocumento(30, "Certidão de Transformação de Uso", "CTRANS")); setDocSmac(new TipoDocumento(31, "Requerimento de Meio Ambiente", "SMAC")); setDocPlpubl(new TipoDocumento(32, "Planta de Autorização de Publicidade", "PLPUBL")); setDocTxmeca(new TipoDocumento(33, "Taxa de Mesas e Cadeiras", "TXMECA")); setDocTxpubl(new TipoDocumento(34, "Taxa de Publicidade", "TXPUBL")); setDocIptu(new TipoDocumento(35, "Iptu", "IPTU")); setDocConloc(new TipoDocumento(36, "Contrato de Locação", "CONLOC")); setDocCpf(new TipoDocumento(37, "Cpf dos Sócios", "CPF")); setDocRg(new TipoDocumento(38, "Rg dos Sócios", "RG")); setDocCompre(new TipoDocumento(39, "Comprovante de Residência dos Sócios", "COMPRE")); setDocRegpro(new TipoDocumento(40, "Registro Profissional", "REGPRO")); setDocPcv(new TipoDocumento(41, "Promessa de Compra e Venda", "PCV")); setDocNit(new TipoDocumento(42, "Número de Inscrição do Trabalhador-Sócio", "NIT")); setDocProtoc(new TipoDocumento(43, "Protocolo", "PROTOC")); setDocQdrsoc(new TipoDocumento(44, "Quadro Societário", "Qdrsoc")); setTiposAtos(new ArrayList<TipoDocumento>()); setTiposFed(new ArrayList<TipoDocumento>()); setTiposEst(new ArrayList<TipoDocumento>()); setTiposMun(new ArrayList<TipoDocumento>()); setTiposDvrs(new ArrayList<TipoDocumento>()); TiposAtos.add(getDocConsoc()); TiposAtos.add(getDocAltcon()); TiposAtos.add(getDocDist()); TiposAtos.add(getDocAta()); TiposAtos.add(getDocReqemp()); TiposAtos.add(getDocBalreg()); TiposAtos.add(getDocProinc()); TiposAtos.add(getDocParal()); TiposAtos.add(getDocLavpal()); TiposAtos.add(getDocEstat()); TiposAtos.add(getDocEnquad()); TiposFed.add(getDocCnpj()); TiposFed.add(getDocCertbx()); TiposFed.add(getDocProtoc()); TiposFed.add(getDocQdrsoc()); TiposEst.add(getDocInsest()); TiposEst.add(getDocParal()); TiposEst.add(getDocCertbx()); TiposEst.add(getDocLdexcb()); TiposEst.add(getDocCertcb()); TiposEst.add(getDocProtoc()); TiposMun.add(getDocAlvara()); TiposMun.add(getDocFincad()); TiposMun.add(getDocParal()); TiposMun.add(getDocBxiss()); TiposMun.add(getDocBxalv()); TiposMun.add(getDocSanipj()); TiposMun.add(getDocCis()); TiposMun.add(getDocSanipf()); TiposMun.add(getDocSmtr()); TiposMun.add(getDocSmo()); TiposMun.add(getDocCinstc()); TiposMun.add(getDocHabite()); TiposMun.add(getDocCtrans()); TiposMun.add(getDocSmac()); TiposMun.add(getDocPlpubl()); TiposMun.add(getDocTxmeca()); TiposMun.add(getDocTxpubl()); TiposMun.add(getDocIptu()); TiposMun.add(getDocProtoc()); TiposDvrs.add(getDocConloc()); TiposDvrs.add(getDocCpf()); TiposDvrs.add(getDocRg()); TiposDvrs.add(getDocCompre()); TiposDvrs.add(getDocRegpro()); TiposDvrs.add(getDocPcv()); TiposDvrs.add(getDocNit()); setAtos(new Organizacao(1,"Atos","ATOS",TiposAtos)); setFed(new Organizacao(2,"Federal","FED",TiposFed)); setEst(new Organizacao(3,"Estadual","EST",TiposEst)); setMun(new Organizacao(4,"Municipal","MUN",TiposMun)); setDvrs(new Organizacao(5,"Diversos","DVRS",TiposDvrs)); setOrganizacoes(new ArrayList<Organizacao>()); getOrganizacoes().add(getAtos()); getOrganizacoes().add(getFed()); getOrganizacoes().add(getEst()); getOrganizacoes().add(getMun()); getOrganizacoes().add(getDvrs()); setSoc(new Unidade(5,"Societário","SC",getOrganizacoes())); /* Organização dos Arrays em Ordem Crescente! - Fellipe Pimentel */ Collections.sort(getTiposAtos(), new ComparadorTipoDocumento()); Collections.sort(getTiposDvrs(), new ComparadorTipoDocumento()); Collections.sort(getTiposEst(), new ComparadorTipoDocumento()); Collections.sort(getTiposFed(), new ComparadorTipoDocumento()); Collections.sort(getTiposMun(), new ComparadorTipoDocumento()); Collections.sort(getOrganizacoes(), new ComparadorOrganizacao()); } //------------------------------------------------------------------------------------------------ /** * @return the tiposDvrs */ public ArrayList<TipoDocumento> getTiposDvrs() { return TiposDvrs; } /** * @param tiposDvrs the tiposDvrs to set */ public void setTiposDvrs(ArrayList<TipoDocumento> tiposDvrs) { TiposDvrs = tiposDvrs; } /** * @return the tiposMun */ public ArrayList<TipoDocumento> getTiposMun() { return TiposMun; } /** * @param tiposMun the tiposMun to set */ public void setTiposMun(ArrayList<TipoDocumento> tiposMun) { TiposMun = tiposMun; } /** * @return the tiposEst */ public ArrayList<TipoDocumento> getTiposEst() { return TiposEst; } /** * @param tiposEst the tiposEst to set */ public void setTiposEst(ArrayList<TipoDocumento> tiposEst) { TiposEst = tiposEst; } /** * @return the tiposFed */ public ArrayList<TipoDocumento> getTiposFed() { return TiposFed; } /** * @param tiposFed the tiposFed to set */ public void setTiposFed(ArrayList<TipoDocumento> tiposFed) { TiposFed = tiposFed; } /** * @return the tiposAtos */ public ArrayList<TipoDocumento> getTiposAtos() { return TiposAtos; } /** * @param tiposAtos the tiposAtos to set */ public void setTiposAtos(ArrayList<TipoDocumento> tiposAtos) { TiposAtos = tiposAtos; } //------------------------------------------------------------------------------------------------ public TipoDocumento getDocQdrsoc() { return DocQdrsoc; } public void setDocQdrsoc(TipoDocumento docQdrsoc) { DocQdrsoc = docQdrsoc; } public TipoDocumento getDocProtoc() { return DocProtoc; } public void setDocProtoc(TipoDocumento docProtoc) { DocProtoc = docProtoc; } public TipoDocumento getDocNit() { return DocNit; } /** * @param docNit the docNit to set */ public void setDocNit(TipoDocumento docNit) { DocNit = docNit; } public TipoDocumento getDocEnquad() { return DocEnquad; } public void setDocEnquad(TipoDocumento docEnquad) { DocEnquad = docEnquad; } /** * @return the docPcv */ public TipoDocumento getDocPcv() { return DocPcv; } /** * @param docPcv the docPcv to set */ public void setDocPcv(TipoDocumento docPcv) { DocPcv = docPcv; } /** * @return the docRegpro */ public TipoDocumento getDocRegpro() { return DocRegpro; } /** * @param docRegpro the docRegpro to set */ public void setDocRegpro(TipoDocumento docRegpro) { DocRegpro = docRegpro; } /** * @return the docCompre */ public TipoDocumento getDocCompre() { return DocCompre; } /** * @param docCompre the docCompre to set */ public void setDocCompre(TipoDocumento docCompre) { DocCompre = docCompre; } /** * @return the docRg */ public TipoDocumento getDocRg() { return DocRg; } /** * @param docRg the docRg to set */ public void setDocRg(TipoDocumento docRg) { DocRg = docRg; } /** * @return the docCpf */ public TipoDocumento getDocCpf() { return DocCpf; } /** * @param docCpf the docCpf to set */ public void setDocCpf(TipoDocumento docCpf) { DocCpf = docCpf; } /** * @return the docConloc */ public TipoDocumento getDocConloc() { return DocConloc; } /** * @param docConloc the docConloc to set */ public void setDocConloc(TipoDocumento docConloc) { DocConloc = docConloc; } /** * @return the docIptu */ public TipoDocumento getDocIptu() { return DocIptu; } /** * @param docIptu the docIptu to set */ public void setDocIptu(TipoDocumento docIptu) { DocIptu = docIptu; } /** * @return the docTxpubl */ public TipoDocumento getDocTxpubl() { return DocTxpubl; } /** * @param docTxpubl the docTxpubl to set */ public void setDocTxpubl(TipoDocumento docTxpubl) { DocTxpubl = docTxpubl; } /** * @return the docTxmeca */ public TipoDocumento getDocTxmeca() { return DocTxmeca; } /** * @param docTxmeca the docTxmeca to set */ public void setDocTxmeca(TipoDocumento docTxmeca) { DocTxmeca = docTxmeca; } /** * @return the docPlpubl */ public TipoDocumento getDocPlpubl() { return DocPlpubl; } /** * @param docPlpubl the docPlpubl to set */ public void setDocPlpubl(TipoDocumento docPlpubl) { DocPlpubl = docPlpubl; } /** * @return the docSmac */ public TipoDocumento getDocSmac() { return DocSmac; } /** * @param docSmac the docSmac to set */ public void setDocSmac(TipoDocumento docSmac) { DocSmac = docSmac; } /** * @return the docCtrans */ public TipoDocumento getDocCtrans() { return DocCtrans; } /** * @param docCtrans the docCtrans to set */ public void setDocCtrans(TipoDocumento docCtrans) { DocCtrans = docCtrans; } /** * @return the docHabite */ public TipoDocumento getDocHabite() { return DocHabite; } /** * @param docHabite the docHabite to set */ public void setDocHabite(TipoDocumento docHabite) { DocHabite = docHabite; } /** * @return the docCinstc */ public TipoDocumento getDocCinstc() { return DocCinstc; } /** * @param docCinstc the docCinstc to set */ public void setDocCinstc(TipoDocumento docCinstc) { DocCinstc = docCinstc; } /** * @return the docSmo */ public TipoDocumento getDocSmo() { return DocSmo; } /** * @param docSmo the docSmo to set */ public void setDocSmo(TipoDocumento docSmo) { DocSmo = docSmo; } /** * @return the docSmtr */ public TipoDocumento getDocSmtr() { return DocSmtr; } /** * @param docSmtr the docSmtr to set */ public void setDocSmtr(TipoDocumento docSmtr) { DocSmtr = docSmtr; } public TipoDocumento getDocSanipf() { return DocSanipf; } public void setDocSanipf(TipoDocumento docSanipf) { DocSanipf = docSanipf; } public TipoDocumento getDocCis() { return DocCis; } public void setDocCis(TipoDocumento docCis) { DocCis = docCis; } public TipoDocumento getDocBxalv() { return DocBxalv; } public void setDocBxalv(TipoDocumento docBxalv) { DocBxalv = docBxalv; } public TipoDocumento getDocSanipj() { return DocSanipj; } public void setDocSanipj(TipoDocumento docSanipj) { DocSanipj = docSanipj; } public TipoDocumento getDocBxiss() { return DocBxiss; } public void setDocBxiss(TipoDocumento docBxiss) { DocBxiss = docBxiss; } public TipoDocumento getDocFincad() { return DocFincad; } public void setDocFincad(TipoDocumento docFincad) { DocFincad = docFincad; } public TipoDocumento getDocAlvara() { return DocAlvara; } public void setDocAlvara(TipoDocumento docAlvara) { DocAlvara = docAlvara; } /** * @return the docCertcb */ public TipoDocumento getDocCertcb() { return DocCertcb; } /** * @param docCertcb the docCertcb to set */ public void setDocCertcb(TipoDocumento docCertcb) { DocCertcb = docCertcb; } /** * @return the docLdexcb */ public TipoDocumento getDocLdexcb() { return DocLdexcb; } /** * @param docLdexcb the docLdexcb to set */ public void setDocLdexcb(TipoDocumento docLdexcb) { DocLdexcb = docLdexcb; } /** * @return the docInsest */ public TipoDocumento getDocInsest() { return DocInsest; } /** * @param docInsest the docInsest to set */ public void setDocInsest(TipoDocumento docInsest) { DocInsest = docInsest; } /** * @return the docCertbx */ public TipoDocumento getDocCertbx() { return DocCertbx; } /** * @param docCertbx the docCertbx to set */ public void setDocCertbx(TipoDocumento docCertbx) { DocCertbx = docCertbx; } /** * @return the docCnpj */ public TipoDocumento getDocCnpj() { return DocCnpj; } /** * @param docCnpj the docCnpj to set */ public void setDocCnpj(TipoDocumento docCnpj) { DocCnpj = docCnpj; } /** * @return the docEstat */ public TipoDocumento getDocEstat() { return DocEstat; } /** * @param docEstat the docEstat to set */ public void setDocEstat(TipoDocumento docEstat) { DocEstat = docEstat; } /** * @return the docParal */ public TipoDocumento getDocParal() { return DocParal; } /** * @param docParal the docParal to set */ public void setDocParal(TipoDocumento docParal) { DocParal = docParal; } /** * @return the docLavpal */ public TipoDocumento getDocLavpal() { return DocLavpal; } /** * @param docLavpal the docLavpal to set */ public void setDocLavpal(TipoDocumento docLavpal) { DocLavpal = docLavpal; } /** * @return the docProinc */ public TipoDocumento getDocProinc() { return DocProinc; } /** * @param docProinc the docProinc to set */ public void setDocProinc(TipoDocumento docProinc) { DocProinc = docProinc; } /** * @return the docBalreg */ public TipoDocumento getDocBalreg() { return DocBalreg; } /** * @param docBalreg the docBalreg to set */ public void setDocBalreg(TipoDocumento docBalreg) { DocBalreg = docBalreg; } /** * @return the docReenq */ public TipoDocumento getDocReenq() { return DocReenq; } /** * @param docReenq the docReenq to set */ public void setDocReenq(TipoDocumento docReenq) { DocReenq = docReenq; } /** * @return the docDesenq */ public TipoDocumento getDocDesenq() { return DocDesenq; } /** * @param docDesenq the docDesenq to set */ public void setDocDesenq(TipoDocumento docDesenq) { DocDesenq = docDesenq; } /** * @return the docReqemp */ public TipoDocumento getDocReqemp() { return DocReqemp; } /** * @param docReqemp the docReqemp to set */ public void setDocReqemp(TipoDocumento docReqemp) { DocReqemp = docReqemp; } /** * @return the docAta */ public TipoDocumento getDocAta() { return DocAta; } /** * @param docAta the docAta to set */ public void setDocAta(TipoDocumento docAta) { DocAta = docAta; } /** * @return the docDist */ public TipoDocumento getDocDist() { return DocDist; } /** * @param docDist the docDist to set */ public void setDocDist(TipoDocumento docDist) { DocDist = docDist; } /** * @return the docAltcon */ public TipoDocumento getDocAltcon() { return DocAltcon; } /** * @param docAltcon the docAltcon to set */ public void setDocAltcon(TipoDocumento docAltcon) { DocAltcon = docAltcon; } /** * @return the docConsoc */ public TipoDocumento getDocConsoc() { return DocConsoc; } /** * @param docConsoc the docConsoc to set */ public void setDocConsoc(TipoDocumento docConsoc) { DocConsoc = docConsoc; } //------------------------------------------------------------------------------------------------- /** * @return the dvrs */ public Organizacao getDvrs() { return Dvrs; } /** * @param dvrs the dvrs to set */ public void setDvrs(Organizacao dvrs) { Dvrs = dvrs; } /** * @return the mun */ public Organizacao getMun() { return Mun; } /** * @param mun the mun to set */ public void setMun(Organizacao mun) { Mun = mun; } /** * @return the est */ public Organizacao getEst() { return Est; } /** * @param est the est to set */ public void setEst(Organizacao est) { Est = est; } /** * @return the fed */ public Organizacao getFed() { return Fed; } /** * @param fed the fed to set */ public void setFed(Organizacao fed) { Fed = fed; } /** * @return the atos */ public Organizacao getAtos() { return Atos; } /** * @param atos the atos to set */ public void setAtos(Organizacao atos) { Atos = atos; } public ArrayList<Organizacao> getOrganizacoes() { return organizacoes; } public void setOrganizacoes(ArrayList<Organizacao> organizacoes) { this.organizacoes = organizacoes; } public Unidade getSoc() { return soc; } public void setSoc(Unidade soc) { this.soc = soc; } }
package bigint; import java.util.Scanner; /** * * @author Emerson */ public class BigIntMain { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNextLine()) { String line = sc.nextLine(); if (line.startsWith("#")) { } else { String parts[] = line.split(" "); if (line.equals("")) { System.out.println(line); } else if (parts.length != 3) { System.out.println(line); System.out.println("# Syntax error"); } else { try { BigIntCore bi1 = new BigIntCore(parts[0]); BigIntCore bi2 = new BigIntCore(parts[2]); System.out.println(line); switch (parts[1]) { case "+": System.out.println("# " + BigIntCore.add(bi1, bi2)); System.out.println(""); break; case "-": System.out.println("# " + BigIntCore.subtract(bi1, bi2)); System.out.println(""); break; case "*": System.out.println("# " + BigIntExtended.multiply(bi1, bi2)); System.out.println(""); break; case "/": BigIntCore[] result = BigIntExtended.divide(bi1, bi2); System.out.println("# " + result[0] + " " + result[1]); System.out.println(""); break; case "gcd": System.out.println("# " + BigIntExtended.gcd(bi1, bi2)); System.out.println(""); break; case "<": System.out.println("# " + (bi1.compare(bi2) == -1)); System.out.println(""); break; case ">": System.out.println("# " + (bi1.compare(bi2) == 1)); System.out.println(""); break; case "=": System.out.println("# " + (bi1.compare(bi2) == 0)); System.out.println(""); break; } } catch (NumberFormatException e) { System.out.println(line); System.out.println("# Syntax error"); } catch (IllegalArgumentException e) { System.out.println(line); System.out.println("# Syntax error"); } } } } } public static void sample() { BigIntCore bi1 = new BigIntCore("178945648692123653163141415131361361789456486921236531631414151313613617894564869212365316314141513136136178945648692123653163141415131361361789456486921236531631414151313613617894564869212365316314141513136136178945648692123653163141415131361361789456486921236531631414151313613617894564869212365316314141513136136"); System.out.println("BigInt1 = " + bi1.toString()); BigIntCore bi2 = new BigIntCore("178945648692123653163141415131361361789456486921236531631414151313613617894564869212365316314141513136136178945648692123653163141415131361361789456486921236531631414151313613617894564869212365316314141513136136"); System.out.println("BigInt2 = " + bi2.toString()); System.out.println("half bi1 = " + BigIntCore.half(bi1)); System.out.println("BigInt1 + BigInt2 = " + BigIntCore.add(bi1, bi2)); System.out.println("BigInt1 - BigInt2 = " + BigIntCore.subtract(bi1, bi2)); System.out.println("BigInt1 * BigInt2 = " + BigIntExtended.multiply(bi1, bi2)); BigIntCore[] divide = BigIntExtended.divide(bi1, bi2); System.out.println("BigInt1 / BigInt2 = " + divide[0] + " with " + divide[1] + " remainder"); System.out.println("GCD of BigInt1 and BigInt2 = " + BigIntExtended.gcd(bi1, bi2)); } }
package com.smxknife.energy.stream.alarm; import com.smxknife.energy.common.util.ProtostuffUtil; import com.smxknife.energy.services.alarm.spi.domain.AlarmRecord; import org.apache.flink.streaming.connectors.kafka.KafkaSerializationSchema; import org.apache.kafka.clients.producer.ProducerRecord; import javax.annotation.Nullable; import java.nio.charset.StandardCharsets; /** * @author smxknife * 2021/5/18 */ public class AlarmRecordSerializationSchema implements KafkaSerializationSchema<AlarmRecord> { @Override public ProducerRecord<byte[], byte[]> serialize(AlarmRecord alarmRecord, @Nullable Long aLong) { return new ProducerRecord<byte[], byte[]>("alarmRecords", alarmRecord.getRuleUid().getBytes(StandardCharsets.UTF_8), ProtostuffUtil.serialize(alarmRecord)); } }
package StaticClass; public class StaticClass { int a = 0; public void ObjectLevelStatic() { a = a +1; // System.out.println("I am Static Method"); } public static void main(String[] args) { StaticClass obj = new StaticClass(); obj.ObjectLevelStatic(); System.out.println(obj.a); StaticClass obj1 = new StaticClass(); obj1.ObjectLevelStatic(); System.out.println(obj1.a); } }
package net.dragberry.webapp2.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet Filter implementation class Webapp2Filter */ public class Webapp2Filter implements Filter { private FilterConfig config; /** * Default constructor. */ public Webapp2Filter() { } /** * @see Filter#destroy() */ public void destroy() { } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; ServletContext sc = config.getServletContext(); String filterName = config.getFilterName(); String serverPath = "Server Path: " + httpRequest.getServletPath(); sc.log(filterName + " | " + serverPath + " | before request"); chain.doFilter(request, response); sc.log(filterName + " | " + serverPath + " | after request"); } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { this.config = fConfig; } }