text
stringlengths
10
2.72M
/* * 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 clases; import java.io.IOException; import java.io.ObjectOutputStream; /** * * @author Wdavid */ public class MedidasdeHombre implements java.io.Serializable { private String TalleDelantero; private String TalleTrasero; private String Pecho; private String Cintura; private String Base; private String Espalda; private String LargodeManga; private String Puño; private String LargodePantalon; private String AltodeRodilla; private String AnchodeRodilla; private String Anchodepierna; private String ContoronodeCuello; private String LargodeCamisa; private Persona personas; public MedidasdeHombre(String talletra, String talledela, String pecho, String altorodi, String anchopier, String espalda, String anchoderodi, String cintura, String base, String largodepanta, String largodemanga, String puno, String largodecamisa, String contorcuello, Persona personas) { this.TalleDelantero = talledela; this.TalleTrasero = talletra; this.Pecho = pecho; this.Cintura = cintura; this.Base = base; this.Espalda = espalda; this.LargodeManga = largodemanga; this.Puño = puno; this.LargodePantalon = largodepanta; this.AltodeRodilla = altorodi; this.AnchodeRodilla = anchoderodi; this.Anchodepierna = anchopier; this.ContoronodeCuello = contorcuello; this.LargodeCamisa = largodecamisa; this.personas = personas; // } public String getTalleDelantero() { return TalleDelantero; } public void setTalleDelantero(String TalleDelantero) { this.TalleDelantero = TalleDelantero; } public String getTalleTrasero() { return TalleTrasero; } public void setTalleTrasero(String TalleTrasero) { this.TalleTrasero = TalleTrasero; } public String getPecho() { return Pecho; } public void setPecho(String Pecho) { this.Pecho = Pecho; } public String getCintura() { return Cintura; } public void setCintura(String Cintura) { this.Cintura = Cintura; } public String getBase() { return Base; } public void setBase(String Base) { this.Base = Base; } public String getEspalda() { return Espalda; } public void setEspalda(String Espalda) { this.Espalda = Espalda; } public String getLargodeManga() { return LargodeManga; } public void setLargodeManga(String LargodeManga) { this.LargodeManga = LargodeManga; } public String getPuño() { return Puño; } public void setPuño(String Puño) { this.Puño = Puño; } public String getLargodePantalon() { return LargodePantalon; } public void setLargodePantalon(String LargodePantalon) { this.LargodePantalon = LargodePantalon; } public String getAltodeRodilla() { return AltodeRodilla; } public void setAltodeRodilla(String AltodeRodilla) { this.AltodeRodilla = AltodeRodilla; } public String getAnchodeRodilla() { return AnchodeRodilla; } public void setAnchodeRodilla(String AnchodeRodilla) { this.AnchodeRodilla = AnchodeRodilla; } public String getAnchodepierna() { return Anchodepierna; } public void setAnchodepierna(String Anchodepierna) { this.Anchodepierna = Anchodepierna; } public String getContoronodeCuello() { return ContoronodeCuello; } public void setContoronodeCuello(String ContoronodeCuello) { this.ContoronodeCuello = ContoronodeCuello; } public String getLargodeCamisa() { return LargodeCamisa; } public void setLargodeCamisa(String LargodeCamisa) { this.LargodeCamisa = LargodeCamisa; } public Persona getPersonas() { return personas; } public void setPersonas(Persona personas) { this.personas = personas; } public void guardar(ObjectOutputStream salida) throws IOException { salida.writeObject(this); } }
package ru.otus.sua.L03; import java.util.*; //Написать свою реализацию ArrayList на основе массива. // class MyArrayList<E> implements List<E>{...} // //Проверить, что на ней работают методы // addAll(Collection<? super T> c, T... elements) // static <E> void copy(List<? super T> dest, List<? extends T> src) // static <E> void sort(List<E> list, Comparator<? super T> c) // из java.util.Collections public class MyArrayList<E> implements List<E> { private Object[] myEl; private int mySize; private final int INIT_SIZE = 11; public MyArrayList() { clear(); } public MyArrayList(int size) { myEl = new Object[size]; mySize = 0; } public MyArrayList(Collection<? extends E> c) { myEl = c.toArray(); mySize = myEl.length; } // ============================================================================== @Override public int size() { return mySize; } @Override public boolean isEmpty() { return myEl.length == 0; } @Override public boolean contains(Object o) { return indexOf(o) != -1; } @Override public Iterator<E> iterator() { return listIterator(); } @Override public ListIterator<E> listIterator() { return listIterator(0); } @Override public ListIterator<E> listIterator(int index) { return new MyArrayListIterator(index); } @Override public Object[] toArray() { Object[] a = new Object[mySize]; System.arraycopy(myEl, 0, a, 0, mySize); return a; } @Override public <T> T[] toArray(T[] a) { if (a.length < mySize) return (T[]) this.toArray(); System.arraycopy(myEl, 0, a, 0, mySize); // If the list fits in the specified array with room to spare (i.e., the array has more elements than the list), // the element in the array immediately following the end of the list is set to null. // (This is useful in determining the length of the list only if the caller knows that the list does not // contain any null elements.) // __FROM__ https://docs.oracle.com/javase/10/docs/api/java/util/List.html#toArray(T%5B%5D) if (a.length > mySize) a[mySize] = null; return a; } @Override public boolean add(E e) { add(mySize, e); return true; // Returns: true if this collection changed as a result of the call // __FROM__ https://docs.oracle.com/javase/10/docs/api/java/util/Collection.html#add(E) } @Override public void add(int index, E e) { checkIndexForAdd(index); growResizingCheck(); movingRight(index); myEl[index] = e; mySize++; } private void growResizingCheck() { if (mySize == myEl.length) { Object[] a = new Object[mySize + INIT_SIZE * 2]; // slow growing System.arraycopy(myEl, 0, a, 0, mySize); myEl = a; } } private void movingRight(int index) { for (int i = mySize; i > index; i--) { myEl[i] = myEl[i - 1]; } } @Override public E remove(int index) { checkIndex(index); E e = (E) myEl[index]; movingLeft(index); mySize--; return e; } private void movingLeft(int index) { for (int i = index; i < mySize - 1; i++) { myEl[i] = myEl[i + 1]; } } @Override public boolean remove(Object o) { int index = indexOf(o); if (index == -1) return false; Object ro = remove(index); if (o.equals(ro)) return true; else return false; } @Override public void clear() { myEl = new Object[INIT_SIZE]; mySize = 0; } @Override public int indexOf(Object o) { for (int i = 0; i < mySize; i++) { if ((o == null && get(i) == null) || (o != null && get(i).equals(o))) return i; } return -1; } @Override public int lastIndexOf(Object o) { for (int i = mySize - 1; i >= 0; i--) { if ((o == null && get(i) == null) || (o != null && get(i).equals(o))) return i; } return -1; } @Override public E get(int index) { checkIndex(index); return (E) myEl[index]; } @Override public E set(int index, E e) { checkIndex(index); E re = (E) myEl[index]; myEl[index] = e; return re; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); for (int i = 0; i < mySize; i++) { sb.append(", "); if (myEl[i] != null) { sb.append(((E) myEl[i]).toString()); } else { sb.append("null"); } } sb.delete(1, 3); sb.append("]"); return sb.toString(); } // -------------------------------- ALLs ------------------------------------- @Override public boolean addAll(Collection<? extends E> c) { for (E e : c) { add(e); } return true; } @Override public boolean addAll(int index, Collection<? extends E> c) { checkIndex(index); for (E e : c) { // dumb inserting add(index, e); index++; } return true; } @Override public boolean removeAll(Collection<?> c) { boolean ret = false; for (Object o : c) { int index = indexOf(o); if (index != -1) { ret = true; remove(index); } } return ret; } @Override public boolean containsAll(Collection<?> c) { for (Object o : c) { if (indexOf(o) == -1) { return false; } } return true; } @Override public boolean retainAll(Collection<?> c) { boolean ret = false; int i = 0; do { i = 0; for (; i < mySize; i++) { Object o = myEl[i]; // System.out.print(o.toString()); if (!c.contains(o)) { ret = true; remove(o); // System.out.print("r"); break; } // System.out.print(" "); } // System.out.println(" i="+i+" l="+mySize); } while (i < mySize); return ret; } @Override public List<E> subList(int fromIndex, int toIndex) { checkIndex(fromIndex); checkIndex(toIndex - 1); // Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. // (If fromIndex and toIndex are equal, the returned list is empty.) List<E> le = new MyArrayList<>(); if (fromIndex == toIndex) return le; for (int i = fromIndex; i < toIndex; i++) { le.add((E) myEl[i]); } return le; } // ================ IMPLEMENTED ABOVE THIS ======================== // void trimToSize() // void forEach​(Consumer<? super E> action) // void ensureCapacity​(int minCapacity) // boolean removeIf​(Predicate<? super E> filter) // protected void removeRange​(int fromIndex, int toIndex) // Spliterator<E> spliterator() // Object clone() // static <E> List<E> of()................. // ==================================== TOOLS ========================================== private void checkIndex(int index) { if (index < 0 || index >= mySize) throw new IndexOutOfBoundsException(); } private void checkIndexForAdd(int index) { if (index == 0) return; if (index < 0 || index > mySize) throw new IndexOutOfBoundsException(); } // ==================================== ITERATOR ======================================== private class MyArrayListIterator implements ListIterator { private int index = 0; private int lastIndex = -1; public MyArrayListIterator(int index) { this.index = index; } @Override public boolean hasNext() { return index < size(); } @Override public Object next() { if (!hasNext()) throw new NoSuchElementException(); lastIndex = index; Object o = MyArrayList.this.get(index); index++; return o; } @Override public boolean hasPrevious() { return index > 0; } @Override public Object previous() { if (!hasPrevious()) throw new NoSuchElementException(); index--; lastIndex = index; Object o = MyArrayList.this.get(index); return o; } @Override public int nextIndex() { return index; } @Override public int previousIndex() { return index - 1; //TODO what about <0 ? } @Override public void remove() { if (lastIndex < 0) throw new IllegalStateException(); MyArrayList.this.remove(lastIndex); if (lastIndex < index) index--; lastIndex--; } @Override public void set(Object o) { if (lastIndex < 0) throw new IllegalStateException(); MyArrayList.this.set(lastIndex, (E) o); } @Override public void add(Object o) { MyArrayList.this.add(index, (E) o); index++; lastIndex = -1; } } }
package be.kdg.fastrada.integratie; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; import static org.junit.Assert.assertEquals; /** * Test for the Password Reset/Forget Screen. */ public class ITPasswordScreen { @Test public void testForgotPasswordScreen(){ WebDriver driver = new HtmlUnitDriver(); driver.get("http://127.0.0.1:8080/fastrada/forgotpassword"); String title = driver.getTitle(); assertEquals("Fastrada - Forgot Password", title); WebElement element = driver.findElement(By.name("email")); String tagName = element.getTagName(); assertEquals("input", tagName); element = driver.findElement(By.name("submit")); tagName = element.getTagName(); assertEquals("input", tagName); String type = element.getAttribute("type"); assertEquals("submit", type); } @Test public void testAvailability(){ WebDriver driver = new HtmlUnitDriver(); driver.get("http://127.0.0.1:8080/fastrada"); WebElement element = driver.findElement(By.name("forgotPassword")); String tagName = element.getTagName(); assertEquals("a", tagName); element.click(); (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { return d.getTitle().equals("Fastrada - Forgot Password"); } }); } }
package com.yummy.util; import sun.misc.BASE64Encoder; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class PictureUtil { /** * 图片转base64字符串 * @param imagePath 图片存储的路径 * @return base64字符串 */ public static String imageChangeBase64(String imagePath){ InputStream inputStream = null; byte[] data = null; try { inputStream = new FileInputStream(imagePath); data = new byte[inputStream.available()]; inputStream.read(data); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } // 加密 BASE64Encoder encoder = new BASE64Encoder(); return "data:image/png;base64," + encoder.encode(data); } }
import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * @Author: Asher Huang * @Date: 2019-10-05 * @Description: PACKAGE_NAME * @Version:1.0 */ public class HashSetDemo { public static void main(String[] args) { // 向HashSet中添加元素:Red,Blue,Yellow,Pink,White,并遍历打印输出 Set set = new HashSet(); set.add("Red"); set.add("Blue"); set.add("Yellow"); set.add("Pink"); set.add("While"); System.out.println("set中的元素有:"); Iterator iterator = set.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } for (Iterator iter = set.iterator(); iter.hasNext(); ) { System.out.println(iter.next()); } Object[] strings= set.toArray(); for (int i = 0; i <strings.length ; i++) { System.out.println(strings[i]); } } }
package aufgabe1.dictionary; import java.util.ArrayList; import java.util.List; /** * SortedArrayDictionary implementiert ein Dictionary mit einem Feld, in dem die Datensätze * lückenlos und sortiert gespeichert werden. Für die Suche wird binäre Suche eingesetzt. */ public class SortedArrayDictionary<K extends Comparable<? super K>, V> implements Dictionary<K, V> { private final static int INITIAL_CAPACITY = 10; private final static int INCREASE_FACTOR = 2; @SuppressWarnings("unchecked") private Element<K,V>[] data = new Element[INITIAL_CAPACITY]; private int length; @Override public V insert(K key, V value) { // Check if the key already exists int index; if ((index = getKeyIndex(key)) != -1) { V oldval = data[index].value; data[index].value = value; return oldval; } if (this.length == data.length) { ensureCapacity(INCREASE_FACTOR * data.length); } Element<K, V> newElement = new Element<K, V>(key, value); // Create an empty place in the data array where the new element // will be stored. int i = this.length - 1; while (i >= 0 && key.compareTo(data[i].key) < 0) { data[i + 1] = data[i]; i--; } data[i+1] = newElement; this.length++; return null; } private void ensureCapacity(int newCapacity) { @SuppressWarnings("unchecked") Element<K, V>[] newData = new Element[newCapacity]; System.arraycopy(data, 0, newData, 0, this.length); this.data = newData; } @Override public V search(K key) { int index = getKeyIndex(key); if (index != - 1) { return data[index].value; } else { return null; } } /** * Tries to retrieve the index of the internal element of the key. * @return Array index of the key or -1 in case the key does not exist. */ private int getKeyIndex(K key) { // binary search as usual... int li = 0; int re = this.length - 1; int m = -1; while (li <= re) { m = (li + re) / 2; if (key.compareTo(data[m].key) < 0) { re = m - 1; } else if (key.compareTo(data[m].key) > 0) { li = m + 1; } else { return m; } } return -1; } @Override public V remove(K key) { // search for key int index = getKeyIndex(key); V retval = data[index].value; if (index == -1) return null; // delete key and fill the gap int i; for (i = index; i < length - 1; i++) { data[i] = data[i +1]; } data[i + 1] = null; this.length--; return retval; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("SortedArrayDictionary (len:%d)\n{\n", this.length)); for (int i = 0; i < this.length; i++) { sb.append(String.format("\t'%s' => '%s'\n", data[i].key.toString(), data[i].value.toString())); } sb.append("}"); return sb.toString(); } @Override public List<Element<K, V>> getEntries() { List<Element<K, V>> ret = new ArrayList<Element<K, V>>(this.length); for (int i = 0; i < this.length; ++i) { ret.add(data[i]); } return ret; } }
package sample; import javafx.beans.property.*; import java.time.LocalDate; public class Occupancy { private SimpleIntegerProperty occupancyNumber; private SimpleIntegerProperty employeeNumber; private SimpleIntegerProperty customerNumber; private SimpleIntegerProperty roomNumber; private SimpleDoubleProperty rateApplied; private SimpleDoubleProperty phoneCharge; private ObjectProperty<LocalDate> dateOccupied; private SimpleStringProperty employeeName; private SimpleStringProperty customerName; private SimpleStringProperty roomDescription; public Occupancy(int occupancyNumber, int employeeNumber, String employeeName, int customerNumber, String customerName, int roomNumber, String roomDescription, double rateApplied, double phoneCharge, LocalDate dateOccupied) { this.occupancyNumber = new SimpleIntegerProperty(occupancyNumber) ; this.employeeNumber = new SimpleIntegerProperty(employeeNumber); this.customerNumber = new SimpleIntegerProperty(customerNumber); this.roomNumber = new SimpleIntegerProperty(roomNumber); this.rateApplied = new SimpleDoubleProperty(rateApplied); this.phoneCharge = new SimpleDoubleProperty(phoneCharge); this.dateOccupied = new SimpleObjectProperty<>(dateOccupied); this.customerName = new SimpleStringProperty(customerName); this.employeeName = new SimpleStringProperty(employeeName); this.roomDescription = new SimpleStringProperty(roomDescription); } public int getRoomNumber() { return roomNumber.get(); } public SimpleIntegerProperty roomNumberProperty() { return roomNumber; } public void setRoomNumber(int roomNumber) { this.roomNumber.set(roomNumber); } public String getRoomDescription() { return roomDescription.get(); } public SimpleStringProperty roomDescriptionProperty() { return roomDescription; } public void setRoomDescription(String roomDescription) { this.roomDescription.set(roomDescription); } public int getEmployeeNumber() { return employeeNumber.get(); } public SimpleIntegerProperty employeeNumberProperty() { return employeeNumber; } public void setEmployeeNumber(int employeeNumber) { this.employeeNumber.set(employeeNumber); } public int getCustomerNumber() { return customerNumber.get(); } public SimpleIntegerProperty customerNumberProperty() { return customerNumber; } public void setCustomerNumber(int customerNumber) { this.customerNumber.set(customerNumber); } public String getEmployeeName() { return employeeName.get(); } public SimpleStringProperty employeeNameProperty() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName.set(employeeName); } public String getCustomerName() { return customerName.get(); } public SimpleStringProperty customerNameProperty() { return customerName; } public void setCustomerName(String customername) { this.customerName.set(customername); } public LocalDate getDateOccupied() { return dateOccupied.get(); } public ObjectProperty<LocalDate> dateOccupiedProperty() { return dateOccupied; } public void setDateOccupied(LocalDate dateOccupied) { this.dateOccupied.set(dateOccupied); } public int getOccupancyNumber() { return occupancyNumber.get(); } public SimpleIntegerProperty occupancyNumberProperty() { return occupancyNumber; } public void setOccupancyNumber(int occupancyNumber) { this.occupancyNumber.set(occupancyNumber); } public double getRateApplied() { return rateApplied.get(); } public SimpleDoubleProperty rateAppliedProperty() { return rateApplied; } public void setRateApplied(double rateApplied) { this.rateApplied.set(rateApplied); } public double getPhoneCharge() { return phoneCharge.get(); } public SimpleDoubleProperty phoneChargeProperty() { return phoneCharge; } public void setPhoneCharge(double phoneCharge) { this.phoneCharge.set(phoneCharge); } }
package jp.w3ch.examples; import com.typesafe.config.*; public class MyApp1 { public static void main(String[] args) { Config config = ConfigFactory.load("myapp1/hello"); System.out.println("Hello " + config.getString("app.message") + "!"); } }
package StepDefinition; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Actions; import CucumberTest.SeleniumTest; import CucumberTest.TestDrivers; import cucumber.api.Scenario; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class Test_Steps { public static WebDriver driver; @Given("^User is on Home Page \"([^\"]*)\" and using \"([^\"]*)\" browser$") public void user_is_on_Home_Page(String pageUrl, String browserName) throws Throwable { driver = TestDrivers.DriverInit(browserName); TestDrivers.GoToPage(driver, pageUrl); } @When("^User Navigate to LogIn Page$") public void user_Navigate_to_LogIn_Page() throws Throwable { TestDrivers.DriverSleep(30000); String newValue = "Hello. Sign inYour AccountSign inYour Account"; if (TestDrivers.ClickByTagNameAndAttribute(driver, "A", "text", "Hello. Sign inYour AccountSign inYour Account", false) == null) { newValue = "Your Amazon.com"; TestDrivers.ClickByTagNameAndAttribute(driver, "A", "text", newValue, true); } else { TestDrivers.ClickByTagNameAndAttribute(driver, "A", "text", newValue, true); } TestDrivers.clickElementByTagNameAndAttributeAndIndex(driver, "A", "text", "Hello. Sign inYour AccountSign inYour Account", 0); // SeleniumTest.clickElementByTagNameAndAttributeAndIndex(driver, // "SPAN", // "textContent", "Hello. Sign in", 0); TestDrivers.clickElementByTagNameAndAttributeAndIndex(driver, "SPAN", "textContent", "Sign in", 0); } @When("^User enters UserName \"([^\"]*)\" and Password \"([^\"]*)\"$") public void user_enters_UserName_and_Password(String userName, String password) throws Throwable { Thread.sleep(5000); TestDrivers.FindElementById(driver, "ap_email").sendKeys(userName); TestDrivers.FindElementById(driver, "ap_password").sendKeys(password); TestDrivers.FindElementById(driver, "signInSubmit-input").click(); } @Then("^Message displayed Login Successfully$") public void message_displayed_Login_Successfully() throws Throwable { System.out.println("Login Successfully"); } @When("^User Navigate Amazon Video Page$") public void user_Navigate_VideoPage() { // Actions vact=new Actions(driver); // vact.moveToElement(driver.findElement(By.id("nav-link-shopall"))).build().perform(); TestDrivers.DriverSleep(20000); String newValue = "Shop byDepartment"; // if (TestDrivers.ClickByTagNameAndAttribute(driver, "A", "text", // "Shop byDepartment", false) == null) { // newValue = "Explore Amazon"; // TestDrivers.ClickByTagNameAndAttribute(driver, "A", "text", // newValue, true); // // } else { // TestDrivers.ClickByTagNameAndAttribute(driver, "A", "text", // newValue, true); // } WebElement we = null; we = TestDrivers.ClickByTagNameAndAttribute(driver, "A", "text", newValue, false); if (we == null) { newValue = "Explore Amazon"; TestDrivers.MouseHooverOverElement(driver, we, "Shop byDepartment"); } else { TestDrivers.MouseHooverOverElement(driver, we, newValue); } TestDrivers.clickElementByTagNameAndAttributeAndIndex(driver, "SPAN", "textContent", "Amazon Video", 0); TestDrivers.clickElementByTagNameAndAttributeAndIndex(driver, "SPAN", "textContent", "Amazon Video", 2); } @Then("^Message displayed \"([^\"]*)\"$") public void messageDisplayed(String messageDisplayed) { SeleniumTest.verifyElementByTagNameAndAttributeAndIndex(driver, "H1", "textContent", "\n Amazon Video\n ", 0); } @When("^User LogOut from the Application$") public void user_LogOut_from_the_Application() throws Throwable { Thread.sleep(5000); // if (SeleniumTest.clickElementByTagNameAndAttributeAndIndex(driver, // "SPAN", // "textContent", "Your Account", 0) == null) { // SeleniumTest.clickElementByTagNameAndAttributeAndIndex(driver, // "SPAN", // "textContent", "Account & Lists", 0); // // } Actions act = new Actions(driver); act.moveToElement(driver.findElement(By.id("nav-link-yourAccount"))) .build().perform(); TestDrivers.ClickByTagNameAndAttribute(driver, "SPAN", "textContent", "Not Adelaide? Sign Out", true); } @Then("^Logout Successfully$") public void message_displayed_Logout_Successfully() throws InterruptedException { Thread.sleep(5000); TestDrivers.verifyElementByTagNameAndAttributeAndIndex(driver, "INPUT", "id", "ap_email", 0); System.out.println("LogOut Successfully"); Thread.sleep(5000); driver.quit(); } }
/* * Copyright (c) TIKI Inc. * MIT license. See LICENSE file in root directory. */ package com.mytiki.blockchain.features.latest.block; import com.mytiki.common.ApiConstants; import com.mytiki.common.reply.ApiReplyAO; import com.mytiki.common.reply.ApiReplyAOFactory; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping(value = BlockController.PATH_CONTROLLER) public class BlockController { public static final String PATH_CONTROLLER = ApiConstants.API_LATEST_ROUTE + "block"; private final BlockService blockService; public BlockController(BlockService blockService) { this.blockService = blockService; } @RequestMapping(method = RequestMethod.POST) public ApiReplyAO<BlockAORsp> postRefresh(@RequestBody BlockAOWrite body){ return ApiReplyAOFactory.ok(blockService.write(body)); } @RequestMapping(method = RequestMethod.GET) public ApiReplyAO<List<BlockAORsp>> getBlock( @RequestParam(required = false) String address, @RequestParam(required = false) String hash ){ return ApiReplyAOFactory.ok(blockService.find(hash, address)); } }
package com.redsun.platf.web.interceptor; import com.redsun.platf.entity.account.UserAccount; import com.redsun.platf.entity.sys.SystemLanguage; import com.redsun.platf.entity.sys.SystemTheme; import com.redsun.platf.service.account.AccountManager; import com.redsun.platf.service.sys.ConfigLoaderService; import com.redsun.platf.sys.EPApplicationAttributes; import com.redsun.platf.util.LogUtils; import com.redsun.platf.web.framework.RequestThreadResourceManager; import org.slf4j.Logger; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.annotation.Resource; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * 標准request 的攔截器 全局配置 * * @author dick pan * // <mvc:interceptors> * // <bean * // class="cn.li.controller.StandardRequestInterceptor" /> * // <bean * // class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> * // <property name="paramName" value="language" /> * // </bean> * // </mvc:interceptors> */ @Component public class StandardRequestInterceptor implements HandlerInterceptor { private Logger log = LogUtils.getLogger(this.getClass()); /** * 帳號管理* */ @Resource protected AccountManager userManager; @Resource(name = "applicationConfigLoader") ConfigLoaderService configLoader; private List<SystemTheme> themes; private List<SystemLanguage> languages; // private List<Authority> allAuthorityList; //auth list public void init() { // log.debug("StandardRequestInterceptor inited!"); } public StandardRequestInterceptor() { } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (themes == null) themes = configLoader.getThemes(); if (languages == null) languages = configLoader.getLanguages(); setConfigToRequest(request, EPApplicationAttributes.THEME_NAME, themes); setConfigToRequest(request, EPApplicationAttributes.LOCALE_NAME, languages); // v201207 store object to requestThreadResources RequestThreadResourceManager.setResource(EPApplicationAttributes.THEME_NAME, themes); RequestThreadResourceManager.setResource(EPApplicationAttributes.LOCALE_NAME, languages); // WebUtils.setSessionAttribute(request,EPApplicationAttributes.APPLICATION_CONFIG,RequestThreadResourceManager.class); log.debug("[webRequestInterceptor] load languages:{},themes:{}" , languages, themes); if (!findCurrentUser()) { handleNotAuthorized(request, response, handler);//無權403ERROR return false; // return true; } else { return true; } } /** * save to request session * @return user != null */ private boolean findCurrentUser() { /*根據authortication 取得user*/ Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication==null) return false; String name = ((User) authentication.getPrincipal()).getUsername(); UserAccount user = userManager.getUserDao().findUniqueBy("loginName", name); log.debug("current user {}", user); //save to request session RequestThreadResourceManager.setResource(UserAccount.class, user); return user != null; } @SuppressWarnings("rawtypes") private void setConfigToRequest(HttpServletRequest request, String attribute, List configValues) { List languageConfig = (List) request .getSession().getAttribute(attribute); if (languageConfig == null) { request.getSession().setAttribute( attribute, configValues); log.debug("[webRequestInterceptor]config load " + attribute + configValues); } else log.debug("[webRequestInterceptor]config reload only"); } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { log.debug("[webRequestInterceptor]postHandle themes{}:", request.getSession().getAttribute( EPApplicationAttributes.THEME_NAME)); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // log.debug("[webRequestInterceptor]afterCompletion themes:" + request.getSession().getAttribute( // EPApplicationAttributes.THEME_NAME)); } /** * Handle a request that is not authorized according to this interceptor. * Default implementation sends HTTP status code 403 ("forbidden"). * <p>This method can be overridden to write a custom message, forward or * redirect to some error page or login page, or throw a ServletException. * * @param request current HTTP request * @param response current HTTP response * @param handler chosen handler to execute, for type and/or instance evaluation * @throws javax.servlet.ServletException if there is an internal error * @throws java.io.IOException in case of an I/O error when writing the response */ protected void handleNotAuthorized(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException { response.sendError(HttpServletResponse.SC_FORBIDDEN); } }
package cn.tree.ergodic; import lombok.Data; /** * @Author: xiaoni * @Date: 2020/3/17 19:58 */ @Data public class TreeNode { int data; TreeNode leftChild; TreeNode rightChild; public TreeNode(int data) { this.data = data; } }
package biotools.biotoolsCompose.poc.sib; import de.metaframe.jabc.framework.sib.annotation.SIBClass; @SIBClass("biotoolsCompose/demo-sibs/ShowPng") public class ShowPng extends AbstractBiotoolsComposeSIB { }
/** * NOTE: This class is auto generated by the swagger code generator program (2.4.19). * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ package com.techtest.mobilab.services.api; import com.techtest.mobilab.services.model.ModelApiResponse; import com.techtest.mobilab.services.model.Transaction; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import javax.validation.Valid; import javax.validation.constraints.*; import java.text.ParseException; import java.util.List; @javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2021-04-06T09:18:58.057Z") @Validated @Api(value = "transaction", description = "the transaction API") @RequestMapping(value = "") public interface TransactionApi { @CrossOrigin("*") @ApiOperation(value = "make a transaction between accounts", nickname = "makeTransaction", notes = "", response = ModelApiResponse.class, tags = { "transactions", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Success creating a bank account.", response = ModelApiResponse.class), @ApiResponse(code = 405, message = "Invalid input") }) @RequestMapping(value = "/transaction", produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.POST) ResponseEntity<ModelApiResponse> makeTransaction( @ApiParam(value = "", required = true) @Valid @RequestBody Transaction body); @CrossOrigin("*") @ApiOperation(value = "Find transactions between two dates", nickname = "getTransactions", notes = "", response = Transaction.class, responseContainer = "List", tags = { "transactions", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Transaction.class, responseContainer = "List"), @ApiResponse(code = 400, message = "Invalid date supplied"), @ApiResponse(code = 404, message = "No Transaction found") }) @RequestMapping(value = "/transaction", produces = { "application/json" }, method = RequestMethod.GET) ResponseEntity<List<Transaction>> getTransactions( @ApiParam(value = "the start date from where to start the search") @Valid @RequestParam(value = "start", required = false) String start, @ApiParam(value = "the end date of the search") @Valid @RequestParam(value = "end", required = false) String end) throws ParseException; }
import javax.xml.bind.annotation.XmlIDREF; public interface Action { int getMaxDistance(); int getMaxHeightJump(); String getName(); public default void jump() { System.out.println(getName() + " прыгает"); } public default void run() { System.out.println(getName() + " бегает"); } }
package am.bizis.cds.dpfdp4; /** * <p>Označení druhu příjmů podle § 10 odst. 1 zákona<br /> * A – příležitostná činnost<br /> * B - prodej nemovitostí<br /> * C - prodej movitých věcí<br /> * D - prodej cenných papírů<br /> * E - příjmy z převodu podle § 10 odst. 1, písm. c) zákona<br /> * F - jiné ostatní příjmy</p> * @author alex */ public enum KodDrPrij10 { A("A","příležitostná činnost"), B("B","prodej nemovitostí"), C("C","prodej movitých věcí"), D("D","prodej cenných papírů"), E("E","příjmy z převodu podle § 10 odst. 1, písm. c) zákona"), F("F","jiné ostatní příjmy"); String kod,popis; KodDrPrij10(String kod,String popis){ this.kod=kod; this.popis=popis; } }
package com.bnade.wow.config; import com.bnade.wow.interceptor.CORSInterceptor; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import java.lang.reflect.Method; /** * 缓存相关配置 * Created by liufeng0103@163.com on 2017/7/4. */ @Configuration @EnableCaching public class CacheConfig extends CachingConfigurerSupport { @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate); // 缓存时间,默认为0表示永久,单位秒 cacheManager.setDefaultExpiration(60 * 60 * 1); return cacheManager; } @Bean public KeyGenerator customKeyGenerator() { return new KeyGenerator() { @Override public Object generate(Object o, Method method, Object... objects) { StringBuilder sb = new StringBuilder(); sb.append(o.getClass().getName()); sb.append(method.getName()); for (Object obj : objects) { sb.append(obj.toString()); } return sb.toString(); } }; } }
package pobj.tme4; import java.io.*; import java.util.List; import pobj.util.Chrono; public class WordCount { public void main() { Chrono chronoHMS = new Chrono(); wordcount(new HashMultiSet<String>()); chronoHMS.stop(); Chrono chronoNMS = new Chrono(); wordcount(new NaiveMultiSet<String>()); chronoNMS.stop(); } public static void wordcount(MultiSet<String> ms) { String file = "data/WarAndPeaceShort.txt"; try { BufferedReader br = new BufferedReader(new FileReader(file)); String line = null; while ((line = br.readLine()) != null) { for (String word : line.split("\\P{L}+")) { if (word.equals("")) continue; // ignore les mots vides else { ms.add(word); } } } br.close(); } catch (IOException io) { System.out.println(io.getMessage()); io.printStackTrace(); } List<String> list = ms.elements(); list.sort(ms.getComparer()); for (int i = 0; i < 10; i++) { System.out.println(list.get(i)); } } }
package com.wrathOfLoD.GameLaunching.Vendors; import com.wrathOfLoD.Controllers.NPCControllers.FlyingNPCController; import com.wrathOfLoD.Controllers.NPCControllers.NPCController; import com.wrathOfLoD.Controllers.NPCControllers.NotFlyingNPCController; import com.wrathOfLoD.Controllers.NPCControllers.PetController; import com.wrathOfLoD.GameClock.TimeModel; import com.wrathOfLoD.Models.Entity.Character.Avatar; import com.wrathOfLoD.Models.Entity.Character.NPC; import com.wrathOfLoD.Models.Entity.Character.Pet; import com.wrathOfLoD.Models.Entity.EntityCanMoveVisitor.FlyingCanMoveVisitor; import com.wrathOfLoD.Models.Entity.EntityCanMoveVisitor.TerrestrialCanMoveVisitor; import com.wrathOfLoD.Models.LocationTracker.LocationTrackerManager; import com.wrathOfLoD.Models.Map.Map; import com.wrathOfLoD.Models.Map.MapArea; import com.wrathOfLoD.Models.Occupation.Occupation; import com.wrathOfLoD.Models.Occupation.Smasher; import com.wrathOfLoD.Models.Occupation.Sneak; import com.wrathOfLoD.Models.Occupation.Summoner; import com.wrathOfLoD.Models.Skill.SmasherSkillManager; import com.wrathOfLoD.Models.Skill.SneakSkillManager; import com.wrathOfLoD.Models.Skill.SummonerSkillManager; import com.wrathOfLoD.Models.Stats.Stats; import com.wrathOfLoD.Models.Stats.StatsModifiable; import com.wrathOfLoD.Utility.Position; /** * Created by luluding on 4/15/16. */ public class EntityVendor { public static Avatar createNewPlayer(String name, Occupation occupation, Position startingPosition, MapArea mapArea){ Avatar avatar = Avatar.getInstance(); //Stats stats = new Stats(avatar); avatar.configureAvatar(name, startingPosition, occupation, occupation.createSkillManager()); avatar.populateAbilities(); mapArea.addEntity(avatar, startingPosition); Map.getInstance().setActiveMapArea(mapArea); LocationTrackerManager.getInstance().registerEntity(avatar,mapArea); return avatar; } public static Avatar createNewSmasherPlayer(String name, Position startingPosition, MapArea mapArea){ Avatar avatar = Avatar.getInstance(); Stats stats = new Stats(avatar); avatar.configureAvatar(name, startingPosition, new Smasher(), new SmasherSkillManager()); avatar.populateAbilities(); mapArea.addEntity(avatar, startingPosition); Map.getInstance().setActiveMapArea(mapArea); LocationTrackerManager.getInstance().registerEntity(avatar,mapArea); return avatar; } public static Avatar createNewSummonerPlayer(String name, Position startingPosition, MapArea mapArea){ Avatar avatar = Avatar.getInstance(); Stats stats = new Stats(avatar); avatar.configureAvatar(name, startingPosition, new Summoner(), new SummonerSkillManager()); avatar.populateAbilities(); mapArea.addEntity(avatar, startingPosition); Map.getInstance().setActiveMapArea(mapArea); LocationTrackerManager.getInstance().registerEntity(avatar,mapArea); return avatar; } public static Avatar createNewSneakPlayer(String name, Position startingPosition, MapArea mapArea){ Avatar avatar = Avatar.getInstance(); Stats stats = new Stats(avatar); avatar.configureAvatar(name, startingPosition, new Sneak(), new SneakSkillManager()); avatar.populateAbilities(); mapArea.addEntity(avatar, startingPosition); Map.getInstance().setActiveMapArea(mapArea); LocationTrackerManager.getInstance().registerEntity(avatar,mapArea); return avatar; } public static NPC createEnemy(Position startingPosition, MapArea mapArea){ NPC enemy = new NPC("SlothHater", startingPosition, new Smasher(), 1, 1, new TerrestrialCanMoveVisitor()); enemy.setAggroLevel(1); StatsModifiable move = StatsModifiable.createMovementStatsModifiable(30); enemy.changeMovementSpeed(move); mapArea.addEntity(enemy, startingPosition); LocationTrackerManager.getInstance().registerEntity(enemy,mapArea); NPCController controller = new NotFlyingNPCController(enemy); TimeModel.getInstance().registerTickable(controller); return enemy; } public static Pet createPet(Position position, MapArea mapArea){ Pet pet = new Pet("SlothHater", position, new Smasher(), new TerrestrialCanMoveVisitor()); pet.setAggroLevel(0); mapArea.addEntity(pet, position); LocationTrackerManager.getInstance().registerEntity(pet, mapArea); NPCController controller = new PetController(pet); TimeModel.getInstance().registerTickable(controller); return pet; } public static NPC createFlyingEnemy(Position startingPosition, MapArea mapArea){ NPC enemy = new NPC("FlyingSlothHater", startingPosition, new Smasher(), 1, 1, new FlyingCanMoveVisitor()); enemy.setAggroLevel(1); StatsModifiable move = StatsModifiable.createMovementStatsModifiable(30); enemy.changeMovementSpeed(move); mapArea.addEntity(enemy, startingPosition); LocationTrackerManager.getInstance().registerEntity(enemy,mapArea); NPCController controller = new FlyingNPCController(enemy); TimeModel.getInstance().registerTickable(controller); return enemy; } }
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org) package org.xbill.DNS; import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.util.Date; import org.xbill.DNS.utils.base64; /** * Transaction Signature - this record is automatically generated by the resolver. TSIG records * provide transaction security between the sender and receiver of a message, using a shared key. * * @see Resolver * @see TSIG * @see <a href="https://tools.ietf.org/html/rfc2845">RFC 2845: Secret Key Transaction * Authentication for DNS (TSIG)</a> * @author Brian Wellington */ public class TSIGRecord extends Record { private Name alg; private Instant timeSigned; private Duration fudge; private byte[] signature; private int originalID; private int error; private byte[] other; TSIGRecord() {} /** * Creates a TSIG Record from the given data. This is normally called by the TSIG class * * @param alg The shared key's algorithm * @param timeSigned The time that this record was generated * @param fudge The fudge factor for time - if the time that the message is received is not in the * range [now - fudge, now + fudge], the signature fails * @param signature The signature * @param originalID The message ID at the time of its generation * @param error The extended error field. Should be 0 in queries. * @param other The other data field. Currently used only in BADTIME responses. * @see TSIG * @deprecated use {@link #TSIGRecord(Name, int, long, Name, Instant, Duration, byte[], int, int, * byte[])} */ @Deprecated public TSIGRecord( Name name, int dclass, long ttl, Name alg, Date timeSigned, int fudge, byte[] signature, int originalID, int error, byte[] other) { this( name, dclass, ttl, alg, timeSigned.toInstant(), Duration.ofSeconds(fudge), signature, originalID, error, other); } /** * Creates a TSIG Record from the given data. This is normally called by the TSIG class * * @param alg The shared key's algorithm * @param timeSigned The time that this record was generated * @param fudge The fudge factor for time - if the time that the message is received is not in the * range [now - fudge, now + fudge], the signature fails * @param signature The signature * @param originalID The message ID at the time of its generation * @param error The extended error field. Should be 0 in queries. * @param other The other data field. Currently used only in BADTIME responses. * @see TSIG */ public TSIGRecord( Name name, int dclass, long ttl, Name alg, Instant timeSigned, Duration fudge, byte[] signature, int originalID, int error, byte[] other) { super(name, Type.TSIG, dclass, ttl); this.alg = checkName("alg", alg); this.timeSigned = timeSigned; checkU16("fudge", (int) fudge.getSeconds()); this.fudge = fudge; this.signature = signature; this.originalID = checkU16("originalID", originalID); this.error = checkU16("error", error); this.other = other; } @Override protected void rrFromWire(DNSInput in) throws IOException { alg = new Name(in); long timeHigh = in.readU16(); long timeLow = in.readU32(); long time = (timeHigh << 32) + timeLow; timeSigned = Instant.ofEpochSecond(time); fudge = Duration.ofSeconds(in.readU16()); int sigLen = in.readU16(); signature = in.readByteArray(sigLen); originalID = in.readU16(); error = in.readU16(); int otherLen = in.readU16(); if (otherLen > 0) { other = in.readByteArray(otherLen); } else { other = null; } } @Override protected void rdataFromString(Tokenizer st, Name origin) throws IOException { throw st.exception("no text format defined for TSIG"); } /** Converts rdata to a String */ @Override protected String rrToString() { StringBuilder sb = new StringBuilder(); sb.append(alg); sb.append(" "); if (Options.check("multiline")) { sb.append("(\n\t"); } sb.append(timeSigned.getEpochSecond()); sb.append(" "); sb.append((int) fudge.getSeconds()); sb.append(" "); sb.append(signature.length); if (Options.check("multiline")) { sb.append("\n"); sb.append(base64.formatString(signature, 64, "\t", false)); } else { sb.append(" "); sb.append(base64.toString(signature)); } sb.append(" "); sb.append(Rcode.TSIGstring(error)); sb.append(" "); if (other == null) { sb.append(0); } else { sb.append(other.length); if (Options.check("multiline")) { sb.append("\n\n\n\t"); } else { sb.append(" "); } if (error == Rcode.BADTIME) { if (other.length != 6) { sb.append("<invalid BADTIME other data>"); } else { long time = ((long) (other[0] & 0xFF) << 40) + ((long) (other[1] & 0xFF) << 32) + ((other[2] & 0xFF) << 24) + ((other[3] & 0xFF) << 16) + ((other[4] & 0xFF) << 8) + (other[5] & 0xFF); sb.append("<server time: "); sb.append(Instant.ofEpochSecond(time)); sb.append(">"); } } else { sb.append("<"); sb.append(base64.toString(other)); sb.append(">"); } } if (Options.check("multiline")) { sb.append(" )"); } return sb.toString(); } /** Returns the shared key's algorithm */ public Name getAlgorithm() { return alg; } /** Returns the time that this record was generated */ public Instant getTimeSigned() { return timeSigned; } /** Returns the time fudge factor */ public Duration getFudge() { return fudge; } /** Returns the signature */ public byte[] getSignature() { return signature; } /** Returns the original message ID */ public int getOriginalID() { return originalID; } /** Returns the extended error */ public int getError() { return error; } /** Returns the other data */ public byte[] getOther() { return other; } @Override protected void rrToWire(DNSOutput out, Compression c, boolean canonical) { alg.toWire(out, null, canonical); long time = timeSigned.getEpochSecond(); int timeHigh = (int) (time >> 32); long timeLow = time & 0xFFFFFFFFL; out.writeU16(timeHigh); out.writeU32(timeLow); out.writeU16((int) fudge.getSeconds()); out.writeU16(signature.length); out.writeByteArray(signature); out.writeU16(originalID); out.writeU16(error); if (other != null) { out.writeU16(other.length); out.writeByteArray(other); } else { out.writeU16(0); } } }
package gui.form.valid; import gui.form.ValueChangeEvent; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * This class provides an adapter for data validators. This was * designed for use with FormItem objects, but any source can be used. * * A StatusEvent is sent (via statusChanged) the first time the data * is validated, and then each time the validity status changes. * * One source can have multiple "daisy-chained" validators. These * validators are tested in order, so that more complex (slower) * validation is only done if easier (faster) validation succeeds. * * Also, one validator object can be used to validate multiple * sources, even if there are multiple StatusListeners registered. * That is, the StatusChange events are per-source. * * Sub-classes must override the isValid(Object) method. Also, in * order to facilitate using this class as a plug-in, the initialize() * method may be overridden. This method takes a single String, and * should interpret that String as needed in order to meet any * specific requirements. No other methods should need to be * overridden. */ public abstract class ValidationAdapter implements Validator { private static final long serialVersionUID = 1L; /** Data structure which contains the source-specific information. */ static class DataSource implements Serializable { private static final long serialVersionUID = 4; private List<StatusListener> listeners; private boolean initialized; // true if source was initialized private boolean wasValid; // true if source was valid protected DataSource (final boolean initialStatus) { listeners = new ArrayList<StatusListener>(); initialized = false; wasValid = initialStatus; } } // This mapping of DataSource objects tracks info for each source. private Map<Object, DataSource> sources = new HashMap<Object, DataSource>(); // The initial status for all data sources private boolean initialStatus = false; // Returned if the value is null private boolean isNullValid = false; public ValidationAdapter() { } public ValidationAdapter (final boolean initialStatus) { this.initialStatus = initialStatus; } /** * Interpret the given String as needed in order to initialize the * Validator as a plug-in. Should return true only if the * initialization succeeds. */ public boolean initialize (final String arguments) { return true; } public void setNullValidity (final boolean status) { isNullValid = status; } public boolean isNullValid() { return isNullValid; } public abstract boolean isValid (Object value); public boolean validate (final Object source, final Object value) { boolean isValidNow = isValid (value); DataSource dataSource = sources.get (source); if (dataSource == null) dataSource = addDataSource (source); if (!dataSource.initialized) // first time for this source { dataSource.initialized = true; dataSource.wasValid = !isValidNow; // force event the 1st time } if (isValidNow != dataSource.wasValid) // state changed { fireChangedEvent (source, value, isValidNow); dataSource.wasValid = isValidNow; } return isValidNow; } public void valueChanged (final ValueChangeEvent e) { validate (e.getSource(), e.getValue()); } public void addStatusListener (final Object source, final StatusListener listener) { DataSource dataSource = sources.get (source); if (dataSource == null) dataSource = addDataSource (source); dataSource.listeners.add (listener); } public void removeStatusListener (final Object source, final StatusListener listener) { DataSource dataSource = sources.get (source); if (dataSource != null) dataSource.listeners.remove (listener); } public void fireChangedEvent (final Object source, final Object value, final boolean status) { DataSource dataSource = sources.get (source); if (dataSource != null && !dataSource.listeners.isEmpty()) { StatusEvent event = new StatusEvent (source, value, status); for (StatusListener listener : dataSource.listeners) listener.stateChanged (event); } } DataSource addDataSource (final Object source) { DataSource dataSource = new DataSource (initialStatus); sources.put (source, dataSource); return dataSource; } }
package com.su.subike.bike.entity; import lombok.Data; /** * @ClassName BikeLocation * @Description TODO * @Author 434945072@qq.com * Data 2019/3/16 14:06 * Version 1.0 **/ @Data public class BikeLocation { private String id; private Long bikeNumber; private int status; private Double[] coordinates; private Double distance; }
package com.exceptions; public class MyQueueException extends Exception{ @Override public String getMessage() { return "Invalide date for Queue"; } }
package com.lenovohit.hcp.pharmacy.web.rest; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.lenovohit.core.dao.Page; import com.lenovohit.core.manager.GenericManager; import com.lenovohit.core.utils.JSONUtils; import com.lenovohit.core.utils.StringUtils; import com.lenovohit.core.web.MediaTypes; import com.lenovohit.core.web.utils.Result; import com.lenovohit.core.web.utils.ResultUtils; import com.lenovohit.hcp.base.model.HcpCtrlParam; import com.lenovohit.hcp.base.model.HcpUser; import com.lenovohit.hcp.base.utils.CtrlParamUtil; import com.lenovohit.hcp.base.web.rest.HcpBaseRestController; import com.lenovohit.hcp.pharmacy.model.PhaStoreInfo; import com.lenovohit.hcp.pharmacy.model.PhaStoreSumInfo; @RestController @RequestMapping("/hcp/pharmacy/phaStoreSumInfo") public class PhaStoreSumInfoRestController extends HcpBaseRestController { @Autowired private GenericManager<PhaStoreSumInfo, String> phaStoreSumInfoManager; @Autowired private GenericManager<PhaStoreInfo, String> phaStoreInfoManager; /** * 分页查询 * @param start * @param limit * @param data * @return */ @RequestMapping(value = "/page/{start}/{limit}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forPage(@PathVariable("start") String start, @PathVariable("limit") String limit, @RequestParam(value = "data", defaultValue = "") String data){ PhaStoreSumInfo storeQuery = JSONUtils.deserialize(data, PhaStoreSumInfo.class); JSONObject json = JSONObject.parseObject(data); String chanel = json.getString("chanel"); StringBuilder jql = new StringBuilder( " select store from PhaStoreSumInfo store left join store.drugInfo drug left join store.companyInfo company where 1 = 1 "); List<Object> values = new ArrayList<Object>(); HcpUser user = this.getCurrentUser(); if(chanel ==null || "person".equals(chanel)){ jql.append(" and store.hosId = ? "); values.add(user.getHosId()); } else if (StringUtils.isNotBlank(storeQuery.getHosId())){ jql.append(" and store.hosId = ? "); values.add(storeQuery.getHosId()); } //查询码(药品名称/拼音/五笔/药品编码)、药品分类、药品性质、药品规格、库房、有效期(默认<=) if(!StringUtils.isEmpty(storeQuery.getTradeName())){ jql.append("and (store.tradeName like ? or drug.commonName like ? or drug.tradeName like ? or drug.commonSpell like ? or drug.tradeSpell like ? or drug.commonWb like ? or drug.tradeWb like ? or store.drugCode like ? or drug.barcode = ? ) "); values.add("%"+storeQuery.getTradeName()+"%"); values.add("%"+storeQuery.getTradeName()+"%"); values.add("%"+storeQuery.getTradeName()+"%"); values.add("%"+storeQuery.getTradeName()+"%"); values.add("%"+storeQuery.getTradeName()+"%"); values.add("%"+storeQuery.getTradeName()+"%"); values.add("%"+storeQuery.getTradeName()+"%"); values.add("%"+storeQuery.getTradeName()+"%"); values.add(storeQuery.getTradeName()); } if(!StringUtils.isEmpty(storeQuery.getDrugType())){ jql.append("and store.drugType = ? "); values.add(storeQuery.getDrugType()); } if (storeQuery.getDrugInfo() != null) { if(!StringUtils.isEmpty(storeQuery.getDrugInfo().getDrugQuality())){ jql.append("and drug.drugQuality = ? "); values.add(storeQuery.getDrugInfo().getDrugQuality()); } } if(!StringUtils.isEmpty(storeQuery.getSpecs())){ jql.append("and store.specs = ? "); values.add(storeQuery.getSpecs()); } if(!StringUtils.isEmpty(storeQuery.getDeptId())){ jql.append("and store.deptId = ? "); values.add(storeQuery.getDeptId()); } jql.append("order by store.hosId,store.deptId,store.updateTime desc"); Page page = new Page(); page.setStart(start); page.setPageSize(limit); page.setQuery(jql.toString()); page.setValues(values.toArray()); phaStoreSumInfoManager.findPage(page); return ResultUtils.renderPageResult(page); } /** * 库存预警分页查询 * @param start * @param limit * @param data * @return */ @RequestMapping(value = "/pageInventWarn/{start}/{limit}/{isWarn}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forInventWarnPage(@PathVariable("start") String start, @PathVariable("limit") String limit,@PathVariable("isWarn") boolean isWarn, @RequestParam(value = "data", defaultValue = "") String data){ PhaStoreSumInfo storeQuery = JSONUtils.deserialize(data, PhaStoreSumInfo.class); StringBuilder jql = new StringBuilder( " select store from PhaStoreSumInfo store left join store.drugInfo drug left join store.companyInfo company where 1 = 1 "); List<Object> values = new ArrayList<Object>(); // 当前医院 jql.append(" and store.hosId = '" + this.getCurrentUser().getHosId() + "' "); // 当前科室 jql.append(" and store.deptId = '" + this.getCurrentUser().getLoginDepartment().getId() + "' "); // 临界值 jql.append(" and (store.alertNum - store.storeSum) >= 0"); //查询码(药品名称/拼音/五笔/药品编码)、药品分类、药品性质、药品规格、库房、有效期(默认<=) if(!StringUtils.isEmpty(storeQuery.getTradeName())){ jql.append("and (store.tradeName like ? or drug.commonName like ? or drug.tradeName like ? or drug.commonSpell like ? or drug.commonWb like ? or store.drugCode like ? or drug.barcode = ? ) "); values.add("%"+storeQuery.getTradeName()+"%"); values.add("%"+storeQuery.getTradeName()+"%"); values.add("%"+storeQuery.getTradeName()+"%"); values.add("%"+storeQuery.getTradeName()+"%"); values.add("%"+storeQuery.getTradeName()+"%"); values.add("%"+storeQuery.getTradeName()+"%"); values.add(storeQuery.getTradeName()); } if(!StringUtils.isEmpty(storeQuery.getDrugType())){ jql.append("and store.drugType = ? "); values.add(storeQuery.getDrugType()); } if (storeQuery.getDrugInfo() != null) { if(!StringUtils.isEmpty(storeQuery.getDrugInfo().getDrugQuality())){ jql.append("and drug.drugQuality = ? "); values.add(storeQuery.getDrugInfo().getDrugQuality()); } } if(!StringUtils.isEmpty(storeQuery.getSpecs())){ jql.append("and store.specs = ? "); values.add(storeQuery.getSpecs()); } if(!StringUtils.isEmpty(storeQuery.getDeptId())){ jql.append("and store.deptId = ? "); values.add(storeQuery.getDeptId()); } Page page = new Page(); page.setStart(start); page.setPageSize(limit); page.setQuery(jql.toString()); page.setValues(values.toArray()); phaStoreSumInfoManager.findPage(page); return ResultUtils.renderPageResult(page); } /** * 滞留预警分页查询 * @param start * @param limit * @param data * @return */ @RequestMapping(value = "/pageDetentWarn/{start}/{limit}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forDetentWarnPage(@PathVariable("start") String start, @PathVariable("limit") String limit, @RequestParam(value = "data", defaultValue = "") String data){ PhaStoreInfo storeQuery = JSONUtils.deserialize(data, PhaStoreInfo.class); StringBuilder jql = new StringBuilder( " select store from PhaStoreInfo store left join store.drugInfo drug left join store.companyInfo company where 1 = 1 "); List<Object> values = new ArrayList<Object>(); // 当前医院 jql.append(" and store.hosId = '" + this.getCurrentUser().getHosId() + "' "); // 当前科室 jql.append(" and store.deptId = '" + this.getCurrentUser().getLoginDepartment().getId() + "' "); HcpCtrlParam hcpCtrlParam = CtrlParamUtil.getCtrlParm(this.getCurrentUser().getHosId(), "DRUG_UPDATE_TIME"); //一级预警 HcpCtrlParam levelLow = CtrlParamUtil.getCtrlParm(this.getCurrentUser().getHosId(), "ALERT_LEVEL_LOW"); //二级预警 HcpCtrlParam levelMedium = CtrlParamUtil.getCtrlParm(this.getCurrentUser().getHosId(), "ALERT_LEVEL_MEDIUM"); //三级预警 HcpCtrlParam levelHigh = CtrlParamUtil.getCtrlParm(this.getCurrentUser().getHosId(), "ALERT_LEVEL_HIGH"); if (hcpCtrlParam != null) { jql.append(" and (( (store.stayAlert IS NULL) AND DATEDIFF( DAY,store.updateTime,getdate()) >= " + hcpCtrlParam.getControlParam() + " ) OR ( (store.stayAlert IS NOT NULL) AND store.stayAlert < DATEDIFF(DAY,store.updateTime,getdate()))) "); } //查询码(药品名称/拼音/五笔/药品编码)、药品分类、药品性质、药品规格、库房、有效期(默认<=) if(!StringUtils.isEmpty(storeQuery.getTradeName())){ jql.append("and (store.tradeName like ? or drug.commonSpell like ? or drug.commonName like ? or drug.tradeName like ? or drug.commonWb like ? or store.drugCode like ? or drug.barcode = ? ) "); values.add("%"+storeQuery.getTradeName()+"%"); values.add("%"+storeQuery.getTradeName()+"%"); values.add("%"+storeQuery.getTradeName()+"%"); values.add("%"+storeQuery.getTradeName()+"%"); values.add("%"+storeQuery.getTradeName()+"%"); values.add("%"+storeQuery.getTradeName()+"%"); values.add(storeQuery.getTradeName()); } if(!StringUtils.isEmpty(storeQuery.getDrugType())){ jql.append("and store.drugType = ? "); values.add(storeQuery.getDrugType()); } if (storeQuery.getDrugInfo() != null) { if(!StringUtils.isEmpty(storeQuery.getDrugInfo().getDrugQuality())){ jql.append("and drug.drugQuality = ? "); values.add(storeQuery.getDrugInfo().getDrugQuality()); } } if(!StringUtils.isEmpty(storeQuery.getSpecs())){ jql.append("and store.specs = ? "); values.add(storeQuery.getSpecs()); } if(!StringUtils.isEmpty(storeQuery.getDeptId())){ jql.append("and store.deptId = ? "); values.add(storeQuery.getDeptId()); } jql.append(" order by DATEDIFF(DAY,getdate(),store.updateTime) desc "); Map<String,Object> map = new HashMap<String,Object>(); if(levelLow!=null && StringUtils.isNumeric(levelLow.getControlParam())){ map.put("levelLow", levelLow.getControlParam()); } if(levelMedium!=null && StringUtils.isNumeric(levelMedium.getControlParam())){ map.put("levelMedium", levelMedium.getControlParam()); } if(levelHigh!=null && StringUtils.isNumeric(levelHigh.getControlParam())){ map.put("levelHigh", levelHigh.getControlParam()); } Map<String,Object> dataMap = new HashMap<String,Object>(); Page page = new Page(); page.setStart(start); page.setPageSize(limit); page.setQuery(jql.toString()); page.setValues(values.toArray()); phaStoreInfoManager.findPage(page); if(page!=null && page.getResult()!=null){ dataMap.put("alertLevel", map); dataMap.put("data", page.getResult()); page.setResult(dataMap); } return ResultUtils.renderPageResult(page); } /** * 查询列表 * @param data * @return */ @RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forList(@RequestParam(value = "data", defaultValue = "") String data) { System.out.println(data); PhaStoreSumInfo query = JSONUtils.deserialize(data, PhaStoreSumInfo.class); StringBuilder jql = new StringBuilder( " select store from PhaStoreSumInfo store left join store.drugInfo drug where 1 = 1 "); List<Object> values = new ArrayList<Object>(); System.out.println(query); //查询码(药品名称/拼音/五笔/药品编码)、药品分类、药品性质、药品规格、库房、有效期(默认<=) if(!StringUtils.isEmpty(query.getTradeName())){ jql.append("and (store.tradeName like ? or drug.commonSpell like ? or drug.commonWb like ? or store.drugCode like ? or drug.barcode = ? ) "); values.add("%"+query.getTradeName()+"%"); values.add("%"+query.getTradeName()+"%"); values.add("%"+query.getTradeName()+"%"); values.add("%"+query.getTradeName()+"%"); values.add(query.getTradeName()); } if(StringUtils.isNotBlank(query.getDrugInfo())&& StringUtils.isNotBlank(query.getDrugInfo().getId())){ jql.append(" and drug.id = ?"); values.add(query.getDrugInfo().getId()); } if(StringUtils.isNotEmpty(query.getDrugCode())){ jql.append(" and store.drugCode = ?"); values.add(query.getDrugCode()); } if(StringUtils.isNotEmpty(query.getDeptId())){ jql.append(" and store.deptId = ?"); values.add(query.getDeptId()); } if(StringUtils.isNotEmpty(query.getHosId())){ jql.append(" and store.hosId = ?"); values.add(query.getHosId()); } List<PhaStoreSumInfo> models = phaStoreSumInfoManager.find(jql.toString(), values.toArray()); return ResultUtils.renderSuccessResult(models); } /** * 查询列表--本院库存 * @param data * @return */ @RequestMapping(value = "/loadHosSum", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forloadHosSum(@RequestParam(value = "data", defaultValue = "") String data) { System.out.println(data); PhaStoreSumInfo query = JSONUtils.deserialize(data, PhaStoreSumInfo.class); StringBuilder jql = new StringBuilder( " select sum(storeSum),drugCode,hosId from PhaStoreSumInfo group by hosId,drugCode having hosId=? and drugCode = ? "); List<Object> values = new ArrayList<Object>(); System.out.println(query); values.add(query.getHosId()); values.add(query.getDrugCode()); List<PhaStoreSumInfo> models = phaStoreSumInfoManager.find(jql.toString(), values.toArray()); return ResultUtils.renderSuccessResult(models); } /** * 更新 * @param data * @return */ @RequestMapping(value = "/update", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8) public Result forUpdate(@RequestBody String data) { PhaStoreSumInfo model = JSONUtils.deserialize(data, PhaStoreSumInfo.class); if(model==null || StringUtils.isBlank(model.getId())){ return ResultUtils.renderFailureResult("不存在此对象"); } Date now = new Date(); HcpUser user = this.getCurrentUser(); model.setUpdateOper(user.getName()); model.setUpdateTime(now); // PhaDrugInfo info = this.phaDrugInfoManager.get(model.getDrugInfo().getId()); // model.setDrugInfo(info); this.phaStoreSumInfoManager.save(model); return ResultUtils.renderSuccessResult(); } // 只允许更新部分字段 @RequestMapping(value = "/saveEdit", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8) public Result forSaveEdit(@RequestBody String data) { try { List<PhaStoreSumInfo> inputList = (List<PhaStoreSumInfo>) JSONUtils.parseObject(data,new TypeReference< List<PhaStoreSumInfo>>(){}); if (inputList==null){ throw new RuntimeException("不存在inputList对象"); } List<PhaStoreSumInfo> storeSumInfoList = new ArrayList<>(); for( PhaStoreSumInfo input : inputList ) { if(input==null || StringUtils.isBlank(input.getId())){ throw new RuntimeException("不存在input对象"); } // 先查再更新,只更新部分字段,不影响其他字段 PhaStoreSumInfo storeSumInfo = (PhaStoreSumInfo) phaStoreSumInfoManager.get(input.getId()); if (storeSumInfo == null) { throw new RuntimeException("未找到【"+input.getTradeName()+"】库存明细记录"); } // PhaDrugInfo drugInfo = (PhaDrugInfo) phaDrugInfoManager.get(inputInfo.getDrugId()); // 警戒库存量、药品位置、停用标志 BigDecimal inputNum = input.getAlertNum(); if (inputNum == null) inputNum = new BigDecimal(0); BigDecimal packQty = new BigDecimal(input.getDrugInfo().getPackQty()); BigDecimal alertNum = inputNum.multiply(packQty); storeSumInfo.setAlertNum(alertNum); storeSumInfo.setLocation(input.getLocation()); storeSumInfo.setStop(input.isStop()); storeSumInfoList.add(storeSumInfo); } phaStoreSumInfoManager.batchSave(storeSumInfoList); } catch(Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); return ResultUtils.renderFailureResult(e.getMessage()); } return ResultUtils.renderSuccessResult("保存成功"); } }
package com.company; import ru.ifmo.se.pokemon.*; public class Staraptor extends Stravia { public Staraptor() { this("Staraptor",1); } public Staraptor(String name,int level){ super(name,level); this.setType(Type.NORMAL,Type.FLYING); this.setStats(85,120,70,50,60,100); this.addMove(new Rest()); } }
package Sekcja5.Exercises; public class Exercise25LargestPrime { public static int getLargestPrime(int number){ if (number < 2){ return -1; } for (int i = 2; i < number; i++) { if (number % i == 0){ number /= i; i--; } } return number; } public static void main(String[] args) { System.out.println(getLargestPrime(5)); System.out.println(getLargestPrime(45)); System.out.println(getLargestPrime(90)); System.out.println(getLargestPrime(72)); } }
package gov.nih.mipav.view.renderer.WildMagic.Poisson.Octree; import java.util.Arrays; import java.util.Comparator; /** * Quick and merge sort implementations that create no garbage, unlike {@link * Arrays#sort}. The merge sort is stable, the quick sort is not. */ public class SortUtil { /** * Quick sorts the supplied array using the specified comparator. */ public static void qsort (Object[] a, Comparator comp) { qsort(a, 0, a.length-1, comp); } /** * Quick sorts the supplied array using the specified comparator. * * @param lo0 the index of the lowest element to include in the sort. * @param hi0 the index of the highest element to include in the sort. */ @SuppressWarnings("unchecked") public static void qsort (Object[] a, int lo0, int hi0, Comparator comp) { // bail out if we're already done if (hi0 <= lo0) { return; } // if this is a two element list, do a simple sort on it Object t; if (hi0 - lo0 == 1) { // if they're not already sorted, swap them if (comp.compare(a[hi0], a[lo0]) < 0) { t = a[lo0]; a[lo0] = a[hi0]; a[hi0] = t; } return; } // the middle element in the array is our partitioning element Object mid = a[(lo0 + hi0)/2]; // set up our partitioning boundaries int lo = lo0-1, hi = hi0+1; // loop through the array until indices cross for (;;) { // find the first element that is greater than or equal to // the partition element starting from the left Index. while (comp.compare(a[++lo], mid) < 0); // find an element that is smaller than or equal to // the partition element starting from the right Index. while (comp.compare(mid, a[--hi]) < 0); // swap the two elements or bail out of the loop if (hi > lo) { t = a[lo]; a[lo] = a[hi]; a[hi] = t; } else { break; } } // if the right index has not reached the left side of array // must now sort the left partition if (lo0 < lo-1) { qsort(a, lo0, lo-1, comp); } // if the left index has not reached the right side of array // must now sort the right partition if (hi+1 < hi0) { qsort(a, hi+1, hi0, comp); } } public static void qsort (int[] a, int lo0, int hi0, Comparator comp) { // bail out if we're already done if (hi0 <= lo0) { return; } // if this is a two element list, do a simple sort on it int t; if (hi0 - lo0 == 1) { // if they're not already sorted, swap them if (comp.compare(a[hi0], a[lo0]) < 0) { t = a[lo0]; a[lo0] = a[hi0]; a[hi0] = t; } return; } // the middle element in the array is our partitioning element int mid = a[(lo0 + hi0)/2]; // set up our partitioning boundaries int lo = lo0-1, hi = hi0+1; // loop through the array until indices cross for (;;) { // find the first element that is greater than or equal to // the partition element starting from the left Index. while (comp.compare(a[++lo], mid) < 0); // find an element that is smaller than or equal to // the partition element starting from the right Index. while (comp.compare(mid, a[--hi]) < 0); // swap the two elements or bail out of the loop if (hi > lo) { t = a[lo]; a[lo] = a[hi]; a[hi] = t; } else { break; } } // if the right index has not reached the left side of array // must now sort the left partition if (lo0 < lo-1) { qsort(a, lo0, lo-1, comp); } // if the left index has not reached the right side of array // must now sort the right partition if (hi+1 < hi0) { qsort(a, hi+1, hi0, comp); } } /** * Merge sorts the supplied array using the specified comparator. * * @param src contains the elements to be sorted. * @param dest must contain the same values as the src array. */ public static void msort (Object[] src, Object[] dest, Comparator comp) { msort(src, dest, 0, src.length, 0, comp); } /** * Merge sorts the supplied array using the specified comparator. * * @param src contains the elements to be sorted. * @param dest must contain the same values as the src array. */ public static void msort (Object[] src, Object[] dest, int low, int high, Comparator comp) { msort(src, dest, low, high, 0, comp); } /** Implements the actual merge sort. */ @SuppressWarnings("unchecked") protected static void msort (Object[] src, Object[] dest, int low, int high, int offset, Comparator comp) { // use an insertion sort on small arrays int length = high - low; if (length < INSERTION_SORT_THRESHOLD) { for (int ii = low; ii < high; ii++) { for (int jj = ii; jj > low && comp.compare(dest[jj-1], dest[jj]) > 0; jj--) { Object temp = dest[jj]; dest[jj] = dest[jj-1]; dest[jj-1] = temp; } } return; } // recursively sort each half of dest into src int destLow = low, destHigh = high; low += offset; high += offset; int mid = (low + high) >> 1; msort(dest, src, low, mid, -offset, comp); msort(dest, src, mid, high, -offset, comp); // if the list is already sorted, just copy from src to dest; this // optimization results in faster sorts for nearly ordered lists if (comp.compare(src[mid-1], src[mid]) <= 0) { System.arraycopy(src, low, dest, destLow, length); return; } // merge the sorted halves (now in src) into dest for (int ii = destLow, pp = low, qq = mid; ii < destHigh; ii++) { if (qq >= high || pp < mid && comp.compare(src[pp], src[qq]) <= 0) { dest[ii] = src[pp++]; } else { dest[ii] = src[qq++]; } } } /** The size at or below which we will use insertion sort because it's * probably faster. */ private static final int INSERTION_SORT_THRESHOLD = 7; }
package com.model.service; import java.util.List; import com.model.data.ModelType; import com.model.data.Vendor; public interface VendorService { public void save(Vendor obj); public List<Vendor> finds(); public Vendor get(Vendor obj); public Vendor get(String id); }
package viewGraphic; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.text.Text; import model.Model; public class PlayerSetupMenu extends Menu{ int nbPlayer; PlayerSetupMenu(int nbPlayer) { this.nbPlayer = nbPlayer; mainPane = new BorderPane(); this.addTitle("Selectionnez les joueurs", 200); // Text title = new Text("Selectionnez les joueurs"); // title.setTranslateX(400); // mainPane.setTop(title); Color[] colorList = {Color.CORNFLOWERBLUE, Color.HOTPINK, Color.SEAGREEN, Color.CHOCOLATE}; GridPane playerGrid = new GridPane(); for (int i = 0; i < nbPlayer; i++) { Group box = new Group(); Rectangle background = new Rectangle(220, 120); background.setFill(colorList[i]); box.getChildren().add(background); VBox player = new VBox(); box.getChildren().add(player); Text playerNb = new Text("Joueur " + (i+1)); player.getChildren().add(playerNb); player.setMargin(playerNb, new Insets(5,5,5,5)); TextField name = new TextField(); name.setText("Joueur " + (i+1)); player.getChildren().add(name); player.setMargin(name, new Insets(5,5,5,5)); CheckBox cb = new CheckBox("Ordinateur"); player.getChildren().add(cb); player.setMargin(cb, new Insets(5,5,5,5)); playerGrid.add(box, i%2, (int)i/2); playerGrid.setMargin(box, new Insets(10,10,10,10)); playerGrid.setTranslateX(300); playerGrid.setTranslateY(150); } Button sauver = new Button("Jouer"); sauver.setPrefWidth(100); sauver.setPrefHeight(50); sauver.setTranslateX(490); sauver.setTranslateY(175); sauver.setOnMouseClicked(new EventHandler<MouseEvent>() { public void handle(MouseEvent e) { Model.setNbPlayer(nbPlayer); for (int i = 0; i < nbPlayer; i++) { if (Model.bigDuel && Model.player.length == 2) Model.boardSize = 7; boolean isIA = ((CheckBox)((VBox)((Group)playerGrid.getChildren().get(i)).getChildren().get(1)).getChildren().get(2)).isSelected(); Model.createPlayer(i, (Color)((Rectangle)((Group)playerGrid.getChildren().get(i)).getChildren().get(0)).getFill(), ((TextField)((VBox)((Group)playerGrid.getChildren().get(i)).getChildren().get(1)).getChildren().get(1)).getText(), isIA); } Main.setup(nbPlayer); } }); mainPane.setBottom(sauver); mainPane.setCenter(playerGrid); root.getChildren().add(mainPane); } }
package at.fhv.teama.easyticket.server.address; import at.fhv.teama.easyticket.dto.AddressDto; import at.fhv.teama.easyticket.server.mapping.MapperContext; import org.mapstruct.Context; import org.mapstruct.Mapper; import org.mapstruct.NullValueCheckStrategy; @Mapper(componentModel = "spring", nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS) public interface AddressMapper { AddressDto addressToAddressDto(Address address, @Context MapperContext context); Address addressDtoToAddress(AddressDto address, @Context MapperContext context); }
/* * Copyright 2002-2023 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 * * https://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.jms.support.converter; import java.io.ByteArrayInputStream; import java.lang.reflect.Method; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonView; import jakarta.jms.BytesMessage; import jakarta.jms.JMSException; import jakarta.jms.Session; import jakarta.jms.TextMessage; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; import org.springframework.core.MethodParameter; import org.springframework.lang.Nullable; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * @author Arjen Poutsma * @author Dave Syer * @author Stephane Nicoll */ class MappingJackson2MessageConverterTests { private MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); private Session sessionMock = mock(); @BeforeEach public void setup() { converter.setEncodingPropertyName("__encoding__"); converter.setTypeIdPropertyName("__typeid__"); } @Test void toBytesMessage() throws Exception { BytesMessage bytesMessageMock = mock(); Date toBeMarshalled = new Date(); given(sessionMock.createBytesMessage()).willReturn(bytesMessageMock); converter.toMessage(toBeMarshalled, sessionMock); verify(bytesMessageMock).setStringProperty("__encoding__", "UTF-8"); verify(bytesMessageMock).setStringProperty("__typeid__", Date.class.getName()); verify(bytesMessageMock).writeBytes(isA(byte[].class)); } @Test void fromBytesMessage() throws Exception { BytesMessage bytesMessageMock = mock(); Map<String, String> unmarshalled = Collections.singletonMap("foo", "bar"); byte[] bytes = "{\"foo\":\"bar\"}".getBytes(); final ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes); given(bytesMessageMock.getStringProperty("__typeid__")).willReturn(Object.class.getName()); given(bytesMessageMock.propertyExists("__encoding__")).willReturn(false); given(bytesMessageMock.getBodyLength()).willReturn(Long.valueOf(bytes.length)); given(bytesMessageMock.readBytes(any(byte[].class))).willAnswer( (Answer<Integer>) invocation -> byteStream.read((byte[]) invocation.getArguments()[0])); Object result = converter.fromMessage(bytesMessageMock); assertThat(unmarshalled).as("Invalid result").isEqualTo(result); } @Test void toTextMessageWithObject() throws Exception { converter.setTargetType(MessageType.TEXT); TextMessage textMessageMock = mock(); Date toBeMarshalled = new Date(); given(sessionMock.createTextMessage(isA(String.class))).willReturn(textMessageMock); converter.toMessage(toBeMarshalled, sessionMock); verify(textMessageMock).setStringProperty("__typeid__", Date.class.getName()); } @Test void toTextMessageWithMap() throws Exception { converter.setTargetType(MessageType.TEXT); TextMessage textMessageMock = mock(); Map<String, String> toBeMarshalled = new HashMap<>(); toBeMarshalled.put("foo", "bar"); given(sessionMock.createTextMessage(isA(String.class))).willReturn(textMessageMock); converter.toMessage(toBeMarshalled, sessionMock); verify(textMessageMock).setStringProperty("__typeid__", HashMap.class.getName()); } @Test void fromTextMessage() throws Exception { TextMessage textMessageMock = mock(); MyBean unmarshalled = new MyBean("bar"); String text = "{\"foo\":\"bar\"}"; given(textMessageMock.getStringProperty("__typeid__")).willReturn(MyBean.class.getName()); given(textMessageMock.getText()).willReturn(text); MyBean result = (MyBean)converter.fromMessage(textMessageMock); assertThat(unmarshalled).as("Invalid result").isEqualTo(result); } @Test void fromTextMessageWithUnknownProperty() throws Exception { TextMessage textMessageMock = mock(); MyBean unmarshalled = new MyBean("bar"); String text = "{\"foo\":\"bar\", \"unknownProperty\":\"value\"}"; given(textMessageMock.getStringProperty("__typeid__")).willReturn(MyBean.class.getName()); given(textMessageMock.getText()).willReturn(text); MyBean result = (MyBean)converter.fromMessage(textMessageMock); assertThat(unmarshalled).as("Invalid result").isEqualTo(result); } @Test void fromTextMessageAsObject() throws Exception { TextMessage textMessageMock = mock(); Map<String, String> unmarshalled = Collections.singletonMap("foo", "bar"); String text = "{\"foo\":\"bar\"}"; given(textMessageMock.getStringProperty("__typeid__")).willReturn(Object.class.getName()); given(textMessageMock.getText()).willReturn(text); Object result = converter.fromMessage(textMessageMock); assertThat(unmarshalled).as("Invalid result").isEqualTo(result); } @Test void fromTextMessageAsMap() throws Exception { TextMessage textMessageMock = mock(); Map<String, String> unmarshalled = Collections.singletonMap("foo", "bar"); String text = "{\"foo\":\"bar\"}"; given(textMessageMock.getStringProperty("__typeid__")).willReturn(HashMap.class.getName()); given(textMessageMock.getText()).willReturn(text); Object result = converter.fromMessage(textMessageMock); assertThat(unmarshalled).as("Invalid result").isEqualTo(result); } @Test void toTextMessageWithReturnType() throws JMSException, NoSuchMethodException { Method method = this.getClass().getDeclaredMethod("summary"); MethodParameter returnType = new MethodParameter(method, -1); testToTextMessageWithReturnType(returnType); verify(sessionMock).createTextMessage("{\"name\":\"test\"}"); } @Test void toTextMessageWithNullReturnType() throws JMSException, NoSuchMethodException { testToTextMessageWithReturnType(null); verify(sessionMock).createTextMessage("{\"name\":\"test\",\"description\":\"lengthy description\"}"); } @Test void toTextMessageWithReturnTypeAndNoJsonView() throws JMSException, NoSuchMethodException { Method method = this.getClass().getDeclaredMethod("none"); MethodParameter returnType = new MethodParameter(method, -1); testToTextMessageWithReturnType(returnType); verify(sessionMock).createTextMessage("{\"name\":\"test\",\"description\":\"lengthy description\"}"); } @Test void toTextMessageWithReturnTypeAndMultipleJsonViews() throws JMSException, NoSuchMethodException { Method method = this.getClass().getDeclaredMethod("invalid"); MethodParameter returnType = new MethodParameter(method, -1); assertThatIllegalArgumentException().isThrownBy(() -> testToTextMessageWithReturnType(returnType)); } private void testToTextMessageWithReturnType(MethodParameter returnType) throws JMSException, NoSuchMethodException { converter.setTargetType(MessageType.TEXT); TextMessage textMessageMock = mock(); MyAnotherBean bean = new MyAnotherBean("test", "lengthy description"); given(sessionMock.createTextMessage(isA(String.class))).willReturn(textMessageMock); converter.toMessage(bean, sessionMock, returnType); verify(textMessageMock).setStringProperty("__typeid__", MyAnotherBean.class.getName()); } @Test void toTextMessageWithJsonViewClass() throws JMSException { converter.setTargetType(MessageType.TEXT); TextMessage textMessageMock = mock(); MyAnotherBean bean = new MyAnotherBean("test", "lengthy description"); given(sessionMock.createTextMessage(isA(String.class))).willReturn(textMessageMock); converter.toMessage(bean, sessionMock, Summary.class); verify(textMessageMock).setStringProperty("__typeid__", MyAnotherBean.class.getName()); verify(sessionMock).createTextMessage("{\"name\":\"test\"}"); } @Test void toTextMessageWithAnotherJsonViewClass() throws JMSException { converter.setTargetType(MessageType.TEXT); TextMessage textMessageMock = mock(); MyAnotherBean bean = new MyAnotherBean("test", "lengthy description"); given(sessionMock.createTextMessage(isA(String.class))).willReturn(textMessageMock); converter.toMessage(bean, sessionMock, Full.class); verify(textMessageMock).setStringProperty("__typeid__", MyAnotherBean.class.getName()); verify(sessionMock).createTextMessage("{\"name\":\"test\",\"description\":\"lengthy description\"}"); } @JsonView(Summary.class) public MyAnotherBean summary() { return new MyAnotherBean(); } public MyAnotherBean none() { return new MyAnotherBean(); } @JsonView({Summary.class, Full.class}) public MyAnotherBean invalid() { return new MyAnotherBean(); } public static class MyBean { private String foo; public MyBean() { } public MyBean(String foo) { this.foo = foo; } public String getFoo() { return foo; } public void setFoo(String foo) { this.foo = foo; } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MyBean bean = (MyBean) o; if (foo != null ? !foo.equals(bean.foo) : bean.foo != null) { return false; } return true; } @Override public int hashCode() { return foo != null ? foo.hashCode() : 0; } } private interface Summary {} private interface Full extends Summary {} @SuppressWarnings("unused") private static class MyAnotherBean { @JsonView(Summary.class) private String name; @JsonView(Full.class) private String description; private MyAnotherBean() { } public MyAnotherBean(String name, String description) { this.name = name; this.description = description; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } }
import java.util.Scanner; public class MenuProgram { /* * @author: Aaron Lack, alack * Last edited: 2/7/20 * Pseudocode: * The user must input either A,B,C, or E to view a specific pattern * Write a bunch of if statements that take the user character value to display appropriate pattern * Look up how to make a menu based program, cite any online resources you use. * Write loops for how to make the shapes. * I found a great resource on how to make some of the patterns to make * Website: https://www.edureka.co/blog/30-pattern-programs-in-java/ */ public static void menuProgram(int size) { //Pattern A: //Size is the input the user takes that determines //This section of the loop decreases the elements in the rows, ex: from 5 to 1 Scanner sc = new Scanner(System.in); System.out.println("Please enter a character to display a pattern: "); //Initializes it to something, D is irrelevant, so it will won't throw an error. char pattern = 'D'; //This is a condition that allows the patterns to keep displaying while (pattern != 'E') { //This takes the user input and evaluates the options for if/else statements. //I have displayed the options here and in main to start out. //The code works well, but options are displayed before the pattern. //You can still enter a value to get this code to work. pattern = sc.next().charAt(0); System.out.println("________Menu________"); System.out.println("A: Pattern 1"); System.out.println("B: Pattern 2"); System.out.println("C: Pattern 3"); System.out.println("E: Exit"); if (pattern == 'A') { for (int i = 1; i <= size; i++) { for (int j = 1; j < i; j++) { System.out.print(" "); } for (int k = i; k <= size; k++) { System.out.print(k+" "); } System.out.println(); } //This section of the loop increases the elements of the row, ex: back from 1 to 5. for (int i = size-1; i >= 1; i--) { for (int j = 1; j < i; j++) { System.out.print(" "); } for (int k = i; k <= size; k++) { System.out.print(k+" "); } System.out.println(); } } //Pattern B: else if (pattern == 'B') { for (int i=1; i<= size ; i++) { for (int j = i; j < size ; j++) { System.out.print(" "); } for (int k = 1; k <= (2*i -1) ;k++) { if( k==1 || i == size || k==(2*i-1)) { System.out.print("*"); } else { System.out.print(" "); } } System.out.println(""); } } //Pattern C //For this pattern it increases the values when given a size else if (pattern == 'C') { for (int i=1; i<= size ; i++) { for (int j = size; j > i ; j--) { System.out.print(" "); } System.out.print("*"); for (int k = 1; k < 2*(i -1) ;k++) { System.out.print(" "); } if( i==1) { System.out.println(""); } else { System.out.println("*"); } } //This nested for loop decreases the size when given a value. for (int i=size-1; i>= 1 ; i--) { for (int j = size; j > i ; j--) { System.out.print(" "); } System.out.print("*"); for (int k = 1; k < 2*(i -1) ;k++) { System.out.print(" "); } if( i==1) { System.out.println(""); } else { System.out.println("*"); } } } else { System.out.println("Exiting Program"); } } } public static void main(String[] args) { //This will be inside main Scanner sc = new Scanner(System.in); System.out.print("Enter the size of the pattern: "); int size = sc.nextInt(); System.out.println("________Menu________"); System.out.println("A: Pattern 1"); System.out.println("B: Pattern 2"); System.out.println("C: Pattern 3"); System.out.println("E: Exit"); menuProgram(size); } }
package com.mingrisoft; import java.sql.*; /** * @author Administrator */ public class SubjoinDate { String url = "jdbc:jtds:sqlserver://localhost:1433;DatabaseName=master"; String username = "sa"; String password = ""; private Connection con = null; private Statement stmt = null; private ResultSet rs = null; public SubjoinDate() { // 通过构造方法加载数据库驱动 try { Class.forName("net.sourceforge.jtds.jdbc.Driver"); } catch (Exception ex) { System.out.println("数据库加载失败"); } } public boolean Connection() { //创建数据库连接 try { con = DriverManager.getConnection(url, username, password); } catch (SQLException e) { System.out.println(e.getMessage()); System.out.println("creatConnectionError!"); } return true; } //对数据库的查询操作 public ResultSet selectStatic(String sql) throws SQLException { ResultSet rs=null; if (con == null) { Connection(); } try { stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); rs = stmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } closeConnection(); return rs; } //更新数据库 public boolean executeUpdate(String dataName, String mPath, String lPath) { if (con == null) { Connection(); // 数据库连接 } try { stmt = con.createStatement(); int iCount = stmt.executeUpdate("EXEC sp_attach_db @dbname = '" + dataName + "', @filename1='" + mPath + "', @filename2 = '" + lPath + "'");// 执行数据库附加 } catch (SQLException e) { System.out.println(e.getMessage()); return false; } closeConnection(); // 调用关闭数据库连接方法 return true; } //关闭数据库的操作 public void closeConnection() { if (con != null && stmt != null && rs != null) { try { rs.close(); stmt.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); System.out.println("Failed to close connection!"); } finally { con = null; } } } }
package cuc.edu.cn.hynnsapp02.ui.fragments; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.Collections; import java.util.List; import cuc.edu.cn.hynnsapp02.R; import q.rorbin.verticaltablayout.VerticalTabLayout; import q.rorbin.verticaltablayout.adapter.TabAdapter; import q.rorbin.verticaltablayout.widget.TabView; public class Fragment3 extends Fragment { ViewPager viewpager; View view; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { view=inflater.inflate(R.layout.fragment3, null); viewpager = (ViewPager) view.findViewById(R.id.viewpager1); viewpager.setAdapter(new MyPagerAdapter()); initTab1(); return view; } private void initTab1() { VerticalTabLayout tablayout =view.findViewById(R.id.tablayout1); tablayout.setupWithViewPager(viewpager); } private class MyPagerAdapter extends PagerAdapter implements TabAdapter { List<String> titles; List<Integer> layouts; public MyPagerAdapter() { titles = new ArrayList<>(); Collections.addAll(titles, "热门精选", "喜剧片", "动作片", "爱情片", "科幻片", "动画片", "纪录片", "悬疑片", "犯罪片", "奇幻片", "歌舞片", "青春片", "文艺片", "励志片"); layouts=new ArrayList<>(); Collections.addAll(layouts, R.layout.pageviewers_hot, R.layout.pageviewers_comedy, R.layout.pageviewers_action, R.layout.pageviewers_love, R.layout.pageviewers_science, R.layout.pageviewers_animation, R.layout.pageviewers_document,R.layout.pageviewers_suspen, R.layout.pageviewers_crime, R.layout.pageviewers_fantasy, R.layout.pageviewers_dance, R.layout.pageviewers_young, R.layout.pageviewers_literary, R.layout.pageviewers_encourage); } @Override public int getCount() { return titles.size(); } @Override public TabView.TabBadge getBadge(int position) { return null; } @Override public TabView.TabIcon getIcon(int position) { return null; } @Override public TabView.TabTitle getTitle(int position) { return new TabView.TabTitle.Builder() .setContent(titles.get(position)) .setTextColor(Color.WHITE, 0xBBFFFFFF) .build(); } @Override public int getBackground(int position) { return 0; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { // TextView tv = new TextView(getActivity()); // tv.setTextColor(Color.WHITE); // tv.setGravity(Gravity.CENTER); // tv.setText(titles.get(position)); // tv.setTextSize(18); //布局填充器 LayoutInflater mLayoutInflater = LayoutInflater.from(getActivity()); View view1 = mLayoutInflater.inflate(layouts.get(position), null); container.addView(view1); return view1; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } } }
package net.awesomekorean.podo.lesson.lessonVideo; import androidx.appcompat.app.AppCompatActivity; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.view.WindowManager; import android.widget.MediaController; import android.widget.Toast; import android.widget.VideoView; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import net.awesomekorean.podo.R; import kr.co.prnd.YouTubePlayerView; public class VideoFrame extends AppCompatActivity { YouTubePlayerView videoView; final String VIDEO = "video"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video_frame); // 상태바 제거 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); videoView = findViewById(R.id.videoView); String videoId = getIntent().getStringExtra(VIDEO); videoView.play(videoId, new YouTubePlayerView.OnInitializedListener() { @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) { } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) { Toast.makeText(getApplicationContext(), youTubeInitializationResult.toString(), Toast.LENGTH_LONG).show(); } }); } @Override public void onBackPressed() { finish(); } }
package socialnetwork.repository.database; import socialnetwork.domain.Message; import socialnetwork.domain.Prietenie; import socialnetwork.domain.Tuple; import socialnetwork.domain.Utilizator; import socialnetwork.domain.validators.MessageValidator; import socialnetwork.domain.validators.Validator; import socialnetwork.repository.Repository; import java.sql.*; import java.time.LocalDate; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class MessageDbRepository implements Repository<Long, Message> { private String url; private String username; private String password; private Validator<Message> validator; public MessageDbRepository(String url, String username, String password, MessageValidator validator) { this.url = url; this.username = username; this.password = password; this.validator = validator; } @Override public Optional<Message> findOne(Long aLong) { Optional<Message> me = Optional.empty(); try { Connection connection = DriverManager.getConnection(url,username,password); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM \"Messages\" WHERE \"Id\"=?;"); preparedStatement.setLong(1,aLong); ResultSet resultSet = preparedStatement.executeQuery(); resultSet.next(); Long id = resultSet.getLong("Id"); Long from = resultSet.getLong("From"); Long reply = resultSet.getLong("Reply"); String txt = resultSet.getString("Text"); LocalDate data = resultSet.getDate("Date").toLocalDate(); LocalTime ora = resultSet.getTime("Time").toLocalTime(); PreparedStatement preparedStatement1 = connection.prepareStatement("SELECT * FROM \"Users\" WHERE \"Id\"=?;"); preparedStatement1.setLong(1,from); ResultSet resultSet1 = preparedStatement1.executeQuery(); resultSet1.next(); String nume = resultSet1.getString("Nume"); String prenume = resultSet1.getString("Prenume"); Utilizator user = new Utilizator(nume,prenume); user.setId(from); Message m = new Message(user,txt); m.setId(id); PreparedStatement statement2 = connection.prepareStatement("SELECT * FROM \"Recievers\" WHERE \"Id_message\" = ? " ); statement2.setLong(1,aLong); ResultSet resultSet2 = statement2.executeQuery(); List<Utilizator> TO = new ArrayList<>(); while (resultSet2.next()){ Long id_to = resultSet2.getLong("Id_user"); PreparedStatement statement3 = connection.prepareStatement("SELECT * FROM \"Users\" WHERE \"Users\".\"Id\"= ?"); statement3.setLong(1,id_to); ResultSet resultSet3 = statement3.executeQuery(); while (resultSet3.next()){ String nume_to = resultSet3.getString("Nume"); String prenume_to = resultSet3.getString("Prenume"); Utilizator to = new Utilizator(nume_to,prenume_to); to.setId(id_to); TO.add(to); } } m.setTo(TO); me = Optional.of(m); //return Optional.of(m); } catch (SQLException throwables) { throwables.printStackTrace(); } return me; } @Override public Iterable<Message> findAll() { List<Message> messages = new ArrayList<>(); try (Connection connection = DriverManager.getConnection(url, username, password); PreparedStatement statement = connection.prepareStatement( "SELECT \"Users\".\"Id\",\"Nume\",\"Prenume\" FROM \"Users\" INNER JOIN \"Messages\" on \"Users\".\"Id\"=\"From\"\n" + "GROUP BY(\"Users\".\"Id\")"); ResultSet resultSet = statement.executeQuery()) { //pt user Utilizator user = null; Long id = null; while (resultSet.next()) { id = resultSet.getLong("Id"); // id ul userului de la care primim mesajul String nume = resultSet.getString("Nume"); String prenume = resultSet.getString("Prenume"); user = new Utilizator(nume,prenume); user.setId(id); //pt mesaj if(id!=null){ PreparedStatement statement1 = connection.prepareStatement("SELECT * FROM \"Messages\" WHERE \"Messages\".\"From\"=? ;"); statement1.setLong(1,id); ResultSet resultSet1 = statement1.executeQuery(); while (resultSet1.next()){ Long id_mes = resultSet1.getLong(1); String mesaj = resultSet1.getString("Text"); Long reply = resultSet1.getLong("Reply"); LocalDate date = resultSet1.getDate("Date").toLocalDate(); LocalTime time = resultSet1.getTime("Time").toLocalTime(); Message message = new Message(user,mesaj); message.setDate(date.atTime(time)); message.setId(id_mes); //message.getReply().setId(reply); //pt to PreparedStatement statement2 = connection.prepareStatement("SELECT * FROM \"Recievers\" WHERE \"Id_message\" = ? " ); statement2.setLong(1,id_mes); ResultSet resultSet2 = statement2.executeQuery(); List<Utilizator> TO = new ArrayList<>(); while (resultSet2.next()){ Long id_to = resultSet2.getLong("Id_user"); PreparedStatement statement3 = connection.prepareStatement("SELECT * FROM \"Users\" WHERE \"Users\".\"Id\"= ?"); statement3.setLong(1,id_to); ResultSet resultSet3 = statement3.executeQuery(); while (resultSet3.next()){ String nume_to = resultSet3.getString("Nume"); String prenume_to = resultSet3.getString("Prenume"); Utilizator to = new Utilizator(nume_to,prenume_to); to.setId(id_to); TO.add(to); } } message.setTo(TO); messages.add(message); } }} } catch (SQLException e) { e.printStackTrace(); } return messages; } @Override public Optional<Message> save(Message entity) { try (Connection connection = DriverManager.getConnection(url, username, password)) { PreparedStatement messageStatement = connection.prepareStatement("INSERT INTO \"Messages\" (\"From\", \"Text\", \"Reply\" ,\"Time\", \"Date\") VALUES (? , ? , ?, ?, ?) RETURNING \"Id\"; "); messageStatement.setLong(1, entity.getFrom().getId()); messageStatement.setString(2, entity.getMessage()); LocalDate a = LocalDate.of(entity.getDate().getYear(),entity.getDate().getMonthValue(),entity.getDate().getDayOfMonth()); messageStatement.setDate(5, Date.valueOf(a)); LocalTime b = LocalTime.of(entity.getDate().getHour(),entity.getDate().getMinute(),entity.getDate().getSecond()); messageStatement.setTime(4, Time.valueOf(b)); if (entity.getReply() != null) { messageStatement.setLong(3, entity.getReply().getId()); } else { messageStatement.setLong(3, -1); } //messageStatement.execute(); ResultSet rez = messageStatement.executeQuery(); rez.next(); Long id = rez.getLong(1); messageStatement.close(); //PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM \"Messages\" WHERE (\"From\"=? " AND \"Text\"=?); " ); //preparedStatement.setLong(1,entity.getFrom().getId()); //preparedStatement.setString(2,entity.getMessage()); //esultSet resultSet = preparedStatement.executeQuery(); // Long id = resultSet.getLong(1); for (Utilizator user : entity.getTo()) { PreparedStatement recieveStatement = connection.prepareStatement("INSERT INTO \"Recievers\" (\"Id_message\", \"Id_user\") VALUES (?, ?)"); recieveStatement.setLong(1, id); recieveStatement.setLong(2, user.getId()); recieveStatement.execute(); recieveStatement.close(); } } catch (SQLException throwables) { throwables.printStackTrace(); } return Optional.empty(); } @Override public Optional<Message> delete(Long aLong) { return Optional.empty(); } @Override public Optional<Message> update(Message entity) { try { Connection connection = DriverManager.getConnection(url,username,password); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE \"Messages\" SET \"Reply\"=? WHERE \"Id\"=?;"); preparedStatement.setLong(1,entity.getReply().getId()); preparedStatement.setLong(2,entity.getId()); return Optional.of(entity); } catch (SQLException throwables) { throwables.printStackTrace(); } return Optional.empty(); } @Override public Optional<Message> findd(String a, String b) { return Optional.empty(); } @Override public Optional<Message> finddd(String a) { return null; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.fastHotel.modelo; import java.util.ArrayList; /** * * @author rudolf */ public class Frigobar { private int idFrigobar; private ArrayList<Producto> listaProductos; private Empleado empleado; public Frigobar(int idFrigobar){ this.idFrigobar = idFrigobar; this.listaProductos = new ArrayList<>(); } public int getIdFrigobar() { return idFrigobar; } public void setIdFrigobar(int idFrigobar) { this.idFrigobar = idFrigobar; } public Empleado getEmpleado() { return empleado; } public void setEmpleado(Empleado empleado) { this.empleado = empleado; } public void agregarProducto(Producto producto){ listaProductos.add(producto); } }
package xtrus.ex.cms.message; import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import org.apache.commons.io.IOUtils; import com.esum.framework.net.socket.PacketUtils; import xtrus.ex.cms.CmsCode; import xtrus.ex.cms.CmsConfig; import xtrus.ex.cms.CmsException; public class Cms0620 extends CommonCmsMessage { private int blockNo; // 4 byte private int lastSequenceNo; // 3 byte public Cms0620() { setDocTypeCode(DocTypeCode.CMS0620); } public int getBlockNo() { return blockNo; } public void setBlockNo(int blockNo) { this.blockNo = blockNo; } public int getLastSequenceNo() { return lastSequenceNo; } public void setLastSequenceNo(int lastSequenceNo) { this.lastSequenceNo = lastSequenceNo; } @Override public void marshal(byte[] rawBytes) throws CmsException { ByteArrayInputStream in = null; try { in = new ByteArrayInputStream(rawBytes); commonMarshal(in); this.blockNo = PacketUtils.readToInt(in, 4); this.lastSequenceNo = PacketUtils.readToInt(in, 3); } catch (Exception e) { throw new CmsException(CmsCode.ERROR_MESSAGE, "marshal()", e.getMessage(), e); } finally { IOUtils.closeQuietly(in); } } @Override public byte[] unmarshal() throws CmsException { StringBuffer buffer = new StringBuffer(); buffer.append(commonUnmarshal()); try { buffer.append(PacketUtils.writeToNumeric(""+this.blockNo, 4)); buffer.append(PacketUtils.writeToNumeric(""+this.lastSequenceNo, 3)); } catch (Exception e) { throw new CmsException(CmsCode.ERROR_MESSAGE, "unmarshal()", e.getMessage(), e); } try { return buffer.toString().getBytes(CmsConfig.DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { return buffer.toString().getBytes(); } } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(super.toString()); buffer.append("[blockNo]=["+blockNo+"]"+System.lineSeparator()); buffer.append("[lastSequenceNo]=["+lastSequenceNo+"]"+System.lineSeparator()); return buffer.toString(); } }
package com.proxiad.games.extranet.controller; import javax.persistence.EntityNotFoundException; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.web.bind.annotation.*; import com.proxiad.games.extranet.annotation.AdminTokenSecurity; import com.proxiad.games.extranet.annotation.BypassSecurity; import com.proxiad.games.extranet.dto.ModifyTimeDto; import com.proxiad.games.extranet.dto.RoomDto; import com.proxiad.games.extranet.dto.RoomTrollDto; import com.proxiad.games.extranet.mapper.RoomMapper; import com.proxiad.games.extranet.model.Room; import com.proxiad.games.extranet.repository.RoomRepository; import com.proxiad.games.extranet.service.RoomService; import com.proxiad.games.extranet.service.TrollService; @RestController @CrossOrigin public class RoomController { @Autowired private RoomService roomService; @Autowired private RoomRepository roomRepository; @Autowired private RoomMapper roomMapper; @Autowired private SimpMessagingTemplate simpMessagingTemplate; @Autowired private TrollService trollService; @GetMapping("/room") @AdminTokenSecurity public List<RoomDto> listAllRooms() { return roomService.findAll(); } @PutMapping(value = "/room") @AdminTokenSecurity public ResponseEntity<?> newRoom() { return new ResponseEntity<>(roomService.newRoom(), HttpStatus.OK); } @PatchMapping(value = "/room/{id}/name") @AdminTokenSecurity public ResponseEntity<?> updateRoomName(@PathVariable("id") Integer id, @RequestBody RoomDto updatedRoom) { Room room = roomRepository.findById(id) .orElseThrow(() -> new EntityNotFoundException("No room with id " + id)); room.setName(updatedRoom.getName()); roomRepository.save(room); return new ResponseEntity<>(updatedRoom.getName(), HttpStatus.OK); } @DeleteMapping(value = "/room/{id}") @AdminTokenSecurity public ResponseEntity<?> deleteRoom(@PathVariable("id") Integer id) { roomService.deleteRoom(id); return new ResponseEntity<>("deleted", HttpStatus.OK); } @PostMapping(value = "/room/{id}/reinit") @AdminTokenSecurity public ResponseEntity<?> reinitRoom(@PathVariable("id") Integer id) { Room room = roomService.reinitRoom(id); this.simpMessagingTemplate.convertAndSend("/topic/room/" + room.getId() + "/reinit", new RoomDto()); return new ResponseEntity<>(roomMapper.toDto(room), HttpStatus.OK); } @RequestMapping("/user/troll") @BypassSecurity public void troll(@RequestParam("salle") String roomName) { Room room = roomRepository.findByNameIgnoreCase(roomName) .orElseThrow(() -> new EntityNotFoundException("Your room is unknown. Please contact the administrator.")); final RoomTrollDto roomTrollDto = trollService.trollRoom(room); this.simpMessagingTemplate.convertAndSend("/topic/room/admin/troll", roomTrollDto); this.simpMessagingTemplate.convertAndSend("/topic/room/" + room.getId() + "/troll", roomTrollDto); } @PostMapping("/room/modifyTime") @AdminTokenSecurity public void modifyTime(@RequestBody ModifyTimeDto modifyTimeDto) { modifyTimeDto = trollService.modifyTime(modifyTimeDto); this.simpMessagingTemplate.convertAndSend("/topic/room/admin/modifyTime", modifyTimeDto); this.simpMessagingTemplate.convertAndSend("/topic/room/" + modifyTimeDto.getRoomId() + "/modifyTime", modifyTimeDto); } }
package lsinf1225.uclove; import android.content.Context; /** * Created by Guillaume on 29/04/16. */ public class Score { private String loginGive; private String loginGet; private int quotation; // Constructeur public Score(String loginGive, String loginGet, int quotation) { this.loginGive=loginGive; this.loginGet=loginGet; this.quotation=quotation; } public Score() { } public String getLoginGive() { return loginGive; } public void setLoginGive(String loginGive) { this.loginGive = loginGive; } public String getLoginGet() { return loginGet; } public void setLoginGet(String loginGet) { this.loginGet = loginGet; } public int getQuotation() { return quotation; } public void setQuotation(int quotation) { this.quotation = quotation; } public static double getAverage(User user, Context context){ ScoreManager sm = new ScoreManager(context); sm.open(); double ret = sm.getAverage(user); sm.close(); return ret; } public static void addScore(User usergive, User userget, int sc, Context context){ ScoreManager sm = new ScoreManager(context); sm.open(); sm.addScore(new Score(usergive.getLoginStr(), userget.getLoginStr(), sc)); sm.close(); } } // class Score
/* ------------------------------------------------------------------------------ * 软件名称:美播手机版 * 公司名称:多宝科技 * 开发作者:Yongchao.Yang * 开发时间:2014年10月14日/2014 * All Rights Reserved 2012-2015 * ------------------------------------------------------------------------------ * 注意:本内容均来自乐多科技,仅限内部交流使用,未经过公司许可 禁止转发 * ------------------------------------------------------------------------------ * prj-name:com.rednovo.ace.communication * fileName:WorkerPool.java * ------------------------------------------------------------------------------- */ package com.rednovo.ace.communication.server; import java.nio.channels.SelectionKey; import java.util.ArrayList; import java.util.HashMap; /** * 工作线程池 * * @author yongchao.Yang/2014年10月14日 */ public class ServerWorkerPool { private ArrayList<String> channelList = new ArrayList<String>(); private HashMap<String, ServerReader> readerPool = new HashMap<String, ServerReader>(); private HashMap<String, ServerWriter> writerPool = new HashMap<String, ServerWriter>(); // private static Logger logger = Logger.getLogger(ServerWorkerPool.class); private static ServerWorkerPool pool = null; public static ServerWorkerPool getInstance() { if (pool == null) { pool = new ServerWorkerPool(); } return pool; } /** * */ private ServerWorkerPool() {} /** * 注册新的会话。 * * @param key * @param mgr * @author Yongchao.Yang * @since 2014年10月22日下午12:30:56 */ public void registChannel(SelectionKey key) { String id = key.attachment().toString(); if (!this.channelList.contains(id)) { // logger.debug("[ServerWorkerPool][sessionId:" + id + ",注册读写线程]"); this.channelList.add(id); this.addReader(key); this.addWriter(key); } } /** * 获取空闲线程 * * @author Yongchao.Yang * @throws Exception * @since 2014年10月14日下午2:53:00 */ public ServerWriter getWriter(String id) { return this.writerPool.get(id); } /** * 获取可用的读取线程.如果忙碌,会重试5次,每次等待时长为waitTime * * @return * @throws Exception * @author Yongchao.Yang * @since 2014年10月14日下午3:03:47 */ public ServerReader getReader(String id) { return this.readerPool.get(id); } /** * 停止运行reader和 writer * * @param id * @author Yongchao.Yang * @since 2014年10月21日下午1:00:14 */ public void stopWorker(String id) { if (this.channelList.remove(id)) { ServerReader r = this.getReader(id); r.stopWork(); ServerWriter w = this.getWriter(id); w.stopRun(); this.readerPool.remove(id); this.writerPool.remove(id); } } private synchronized void addReader(SelectionKey key) { String id = key.attachment().toString(); if (!this.readerPool.containsKey(id)) { ServerReader reader = new ServerReader(key); this.readerPool.put(id, reader); reader.start(); } } private synchronized void addWriter(SelectionKey key) { String id = key.attachment().toString(); if (!this.writerPool.containsKey(id)) { ServerWriter writer = new ServerWriter(key); this.writerPool.put(id, writer); writer.start(); } } }
package com.mitobit.camel.component.nexmo; import java.util.Map; import org.apache.camel.Endpoint; import org.apache.camel.impl.DefaultComponent; import org.apache.camel.spi.UriEndpoint; /** * Represents the component that manages {@link NexmoEndpoint}. */ @UriEndpoint(title = "Nexmo", scheme = "nexmo", consumerClass = NexmoConsumer.class, consumerPrefix = "consumer", syntax = "nexmo") public class NexmoComponent extends DefaultComponent { @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { Endpoint endpoint = new NexmoEndpoint(uri, this); setProperties(endpoint, parameters); return endpoint; } }
package com.comyou.qrscandemo; import android.app.Activity; import android.graphics.Rect; import android.os.Bundle; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.RelativeLayout; import android.widget.Toast; import android.widget.RelativeLayout.LayoutParams; import com.comyou.qrscan.QRScanListener; import com.comyou.qrscan.QRScanManager; public final class MainActivity extends Activity implements QRScanListener { QRScanManager qrScanManager; RelativeLayout layout_contain; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.activity_qrscan); qrScanManager = new QRScanManager(this); layout_contain = (RelativeLayout) findViewById(R.id.layout_contain); qrScanManager.initWithSurfaceView(this, R.id.surfaceview); qrScanManager.setBeepResource(R.raw.beep); Rect rect = initCrop(); qrScanManager.setCropRect(rect); ScanLineView scanline = (ScanLineView) findViewById(R.id.scanline); // 动画效果 TranslateAnimation animation = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 1.0f); animation.setDuration(4500); animation.setRepeatCount(-1); animation.setRepeatMode(Animation.RESTART); scanline.startAnimation(animation); } private Rect initCrop() { int screenWidth = getWindowManager().getDefaultDisplay().getWidth(); LayoutParams params = (LayoutParams) layout_contain.getLayoutParams(); int x = params.leftMargin; int y = params.topMargin; int width = screenWidth - 2 * x; int height = width; params.height = height; layout_contain.setLayoutParams(params); return new Rect(x, y, width + x, height + y); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); qrScanManager.onResume(); } @Override protected void onPause() { qrScanManager.onPause(); super.onPause(); } @Override protected void onDestroy() { qrScanManager.onDestroy(); super.onDestroy(); } @Override public void onScanResult(String content) { StringBuffer unicode = new StringBuffer(); String result; int num = 0; for (int i = 0; i < content.length(); i++) { char c = content.charAt(i); if(c == '&') unicode.append("&"); else{ int c_code = (int) c; --c_code; unicode.append(c_code + "|"); } } result = unicode.toString(); unicode.delete(0, result.length()); //全部解密 // for (int i = 0; i < result.length(); ++i){ // char c = result.charAt(i); // // if (c == '|'){ // char temp = (char) num; // unicode.append(temp); // num = 0; // } // else if (c == '&') unicode.append("&"); // else num = c - '0' + num * 10; // } // result = unicode.toString(); //部分解密 for (int i = 0, count = 1; i < result.length(); ++i){ char c = result.charAt(i); if (c == '|'){ if (count == 1 || count == 2 || count == 4 || count == 5 || count == 6 || count == 8) { char temp = (char) num; unicode.append(temp); } num = 0; } else if (c == '&'){ if (count == 1 || count == 2 || count == 4 || count == 5 || count == 6 || count == 8) unicode.append("\n"); ++count; } else num = c - '0' + num * 10; } result = unicode.toString(); Toast.makeText(this, result, Toast.LENGTH_SHORT).show(); } }
package com.example.giftishare.data.model; import android.arch.persistence.room.ColumnInfo; import android.arch.persistence.room.Entity; import android.arch.persistence.room.PrimaryKey; import android.support.annotation.NonNull; import java.util.Date; import java.util.UUID; /** * Created by KS-KIM on 19/02/04. */ @Entity(tableName = "coupons") public class Coupon { @PrimaryKey @ColumnInfo(name = "id") String mId; @ColumnInfo(name = "name") String mName; @ColumnInfo(name = "category") String mCategory; @ColumnInfo(name = "company") String mCompany; @ColumnInfo(name = "price") Integer mPrice; @ColumnInfo(name = "deadline") Date mDeadline; @ColumnInfo(name = "owner") String mOwner; // get coupon from firebase realtime database public Coupon(@NonNull String id, @NonNull String name, @NonNull String category, @NonNull String company, @NonNull Integer price, @NonNull Date deadline, @NonNull String owner) { mId = id; mName = name; mCategory = category; mCompany = company; mPrice = price; mDeadline = deadline; mOwner = owner; } // generate new coupon from user public Coupon(@NonNull String name, @NonNull String category, @NonNull String company, @NonNull Integer price, @NonNull Date deadline, @NonNull String owner) { this(UUID.randomUUID().toString(), name, category, company, price, deadline, owner); } }
package codingexercises; // Coding Exercise 19: Last Digit Checker public class LastDigitChecker { public static void main(String[] args) { System.out.println(hasSameLastDigit(41, 22, 71)); System.out.println(hasSameLastDigit(23, 32, 42)); System.out.println(hasSameLastDigit(9, 99, 999)); System.out.println(hasSameLastDigit(1000, 40, 311)); System.out.println(hasSameLastDigit(3421, 40, 311)); System.out.println("*********************"); System.out.println(isValid(10)); System.out.println(isValid(468)); System.out.println(isValid(1051)); System.out.println(isValid(1000)); } public static boolean hasSameLastDigit(int x, int y, int z) { // number range 10 - 1000 inclusive // without isValid: // if ( x < 10 || x > 1000 || y < 10 || y > 1000 || z < 10 || z > 1000) if ( !isValid(x) || !isValid(y) || !isValid(z) ) { return false; } else { int xDigit = x % 10; int yDigit = y % 10; int zDigit = z % 10; return ( (xDigit == yDigit) || (xDigit == zDigit) || (yDigit == zDigit) ); } } public static boolean isValid(int num) { // number range 10 - 1000 inclusive if ( num > 9 && num < 1001) { return true; } else { return false; } } }
package com.miyatu.tianshixiaobai.adapter; import android.text.Html; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.miyatu.tianshixiaobai.MyApp; import com.miyatu.tianshixiaobai.R; import com.miyatu.tianshixiaobai.activities.Community.CompanyReleaseDetailsActivity; import com.miyatu.tianshixiaobai.custom.CustomRatingBar; import com.miyatu.tianshixiaobai.custom.RoundImageView; import com.miyatu.tianshixiaobai.entity.XiaoBaiReleaseEntity; import java.text.DecimalFormat; import java.util.Arrays; import java.util.List; import static com.miyatu.tianshixiaobai.utils.DateUtil.getDateToString; public class XiaoBaiReleaseFragmentAdapter extends BaseQuickAdapter<XiaoBaiReleaseEntity.ListBean, BaseViewHolder> { public XiaoBaiReleaseFragmentAdapter(int layoutResId, @Nullable List<XiaoBaiReleaseEntity.ListBean> data) { super(layoutResId, data); } @Override protected void convert(BaseViewHolder helper, XiaoBaiReleaseEntity.ListBean item) { helper.setGone(R.id.linID, false); //隐藏ID RoundImageView ivPortrait = helper.getView(R.id.ivPortrait); Glide.with(mContext).load(MyApp.imageUrl + item.getShop_icon()).into(ivPortrait); if (item.getDistance() != null && !item.getDistance().equals("")) { DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足. String distance = decimalFormat.format(Double.parseDouble(item.getDistance()) / 1000);//format 返回的是字符串 helper.setText(R.id.tvDistance, distance + "KM"); } CustomRatingBar ratingBar = helper.getView(R.id.ratingBar); ratingBar.setStarMark(item.getStars()); helper.setText(R.id.tvName, item.getShop_name()); helper.setText(R.id.tvContent, item.getContent()); if (item.getAdd_time() != null && !item.getAdd_time().equals("")) { helper.setText(R.id.tvDate, getDateToString(Long.parseLong(item.getAdd_time()) * 1000, "yyyy-MM-dd HH:mm:ss")); } ImageView ivLike = helper.getView(R.id.ivLike); Glide.with(mContext).load(item.getIs_zan().equals("0") ? R.mipmap.icon_like : R.mipmap.icon_like2).into(ivLike); TextView tvLikeNum = helper.getView(R.id.tvLikeNum); tvLikeNum.setTextColor(item.getIs_zan().equals("0") ? mContext.getResources().getColor(R.color.color_8f8f8f) : mContext.getResources().getColor(R.color.color_fe6e04)); tvLikeNum.setText(item.getZan_count()); helper.setText(R.id.tvCommentNum, item.getReply_count() + ""); RecyclerView recyPhoto = helper.getView(R.id.photoRecyclerView); if (item.getImage() != null && !item.getImage().equals("")) { recyPhoto = helper.getView(R.id.photoRecyclerView); String photoUri[] = item.getImage().split("\\|"); PhotoAdapter photoAdapter = new PhotoAdapter(R.layout.item_item_xiao_bai_release_photo, Arrays.asList(photoUri)); recyPhoto.setAdapter(photoAdapter); recyPhoto.setLayoutManager(new GridLayoutManager(mContext, 3)); recyPhoto.setNestedScrollingEnabled(false); recyPhoto.setAdapter(photoAdapter); } else { recyPhoto.setVisibility(View.GONE); } RecyclerView recyComment = helper.getView(R.id.commentRecyclerView); CommentAdapter commentAdapter = new CommentAdapter(R.layout.item_item_xiao_bai_release_comment, item.getReply()); recyComment.setAdapter(commentAdapter); recyComment.setLayoutManager(new LinearLayoutManager(mContext)); recyComment.setNestedScrollingEnabled(false); recyComment.setAdapter(commentAdapter); helper.addOnClickListener(R.id.ivPortrait); helper.addOnClickListener(R.id.linViewDetails); helper.addOnClickListener(R.id.linLike); helper.addOnClickListener(R.id.linComment); } public static class PhotoAdapter extends BaseQuickAdapter<String, BaseViewHolder> { public PhotoAdapter(int layoutResId, @Nullable List<String> data) { super(layoutResId, data); } @Override protected void convert(BaseViewHolder helper, String item) { ImageView ivPhoto = helper.getView(R.id.ivPhoto); Glide.with(mContext).load(MyApp.imageUrl + item).into(ivPhoto); } } public class CommentAdapter extends BaseQuickAdapter<XiaoBaiReleaseEntity.ListBean.ReplyBean, BaseViewHolder> { public CommentAdapter(int layoutResId, @Nullable List<XiaoBaiReleaseEntity.ListBean.ReplyBean> data) { super(layoutResId, data); } @Override protected void convert(BaseViewHolder helper, XiaoBaiReleaseEntity.ListBean.ReplyBean item) { helper.setText(R.id.tvCommentContent, Html.fromHtml("<font color= \"#502d00\">" + item.getNickname() + "</font>&nbsp&nbsp&nbsp<font color= \"#333333\"><small>" + item.getContent() + "</small></font>")); } } } //public class XiaoBaiReleaseFragmentAdapter extends RecyclerView.Adapter<BaseViewHolder> { // private Context context; // private int viewType; // private List<XiaoBaiReleaseEntity> dataList; // private List<XiaoBaiReleaseEntity> distanceList; // private List<XiaoBaiReleaseEntity> projectList; // private OnItemClickListener itemListener; // private OnClickListener listener; // // public static final int TYPE_RELEASE = 1; // public static final int TYPE_DISTANCE = 2; // public static final int TYPE_PROJECT = 3; // // // public int getItemViewType(int position) { // return viewType; // } // // public void setViewType(int viewType) { // this.viewType = viewType; // } // // public XiaoBaiReleaseFragmentAdapter(Context context, List<XiaoBaiReleaseEntity> data, int viewType) { // this.context = context; // this.viewType = viewType; // if (viewType == TYPE_RELEASE) { // this.dataList = data; // } // else if (viewType == TYPE_DISTANCE) { // this.distanceList = data; // } // else { // this.projectList = data; // } // } // // public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // switch (viewType) { // case TYPE_RELEASE: // View view = LayoutInflater.from(context).inflate(R.layout.item_information_xiao_bai_release, parent, false); // return new ReleaseHolder(view); // case TYPE_DISTANCE: // view = LayoutInflater.from(context).inflate(R.layout.item_information_xiao_bai_release_distance, parent, false); // return new DistanceHolder(view); // case TYPE_PROJECT: // view = LayoutInflater.from(context).inflate(R.layout.item_xiao_bai_release_project, parent, false); // return new ProjectHolder(view); // } // return null; // } // // @Override // public void onBindViewHolder(@NonNull final BaseViewHolder holder, final int position) { // // if (holder instanceof ReleaseHolder) { // XiaoBaiReleaseEntity entity = dataList.get(position); // ((ReleaseHolder) holder).portrait.setImageResource(entity.getPortrait()); // ((ReleaseHolder) holder).name.setText(entity.getName()); // ((ReleaseHolder) holder).id.setText(entity.getId() + ""); // ((ReleaseHolder) holder).introduce.setText(entity.getIntroduce()); // ((ReleaseHolder) holder).date.setText(entity.getDate()); // ((ReleaseHolder) holder).distance.setText(entity.getDistance()); // // //// ((ReleaseHolder) holder).commentNumber.setText(entity.getCommentNumber() + ""); //// ((ReleaseHolder) holder).likeNumber.setText(entity.getLikeNumber() + ""); // // ((ReleaseHolder) holder).viewDetails.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // listener.onClick(position,v); // } // }); // ((ReleaseHolder) holder).imgPop.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // listener.onClick(position,v); // } // }); // // PhotoAdapter photoAdapter = new PhotoAdapter(context, entity.getPhotoList()); // ((ReleaseHolder) holder).photoRecyclerView.setLayoutManager(new GridLayoutManager(context, 3)); // ((ReleaseHolder) holder).photoRecyclerView.setNestedScrollingEnabled(false); // ((ReleaseHolder) holder).photoRecyclerView.setAdapter(photoAdapter); // // CommentAdapter commentAdapter = new CommentAdapter(context, entity.getCommentList()); // ((ReleaseHolder) holder).commentRecyclerView.setLayoutManager(new LinearLayoutManager(context)); // ((ReleaseHolder) holder).commentRecyclerView.setNestedScrollingEnabled(false); // ((ReleaseHolder) holder).commentRecyclerView.setAdapter(commentAdapter); // // } // else if (holder instanceof DistanceHolder) { // XiaoBaiReleaseEntity entity = distanceList.get(position); // ((DistanceHolder) holder).distance.setText(entity.getDistance()); // // if (entity.isDistanceSelected() == true) { // ((DistanceHolder) holder).distance.setBackground(context.getResources().getDrawable(R.drawable.xiao_bai_release_distance_background2)); // ((DistanceHolder) holder).distance.setTextColor(context.getResources().getColor(R.color.color_ffbe4c)); // } // else { // ((DistanceHolder) holder).distance.setBackground(context.getResources().getDrawable(R.drawable.xiao_bai_release_distance_background1)); // ((DistanceHolder) holder).distance.setTextColor(context.getResources().getColor(R.color.color_999999)); // } // // ((DistanceHolder) holder).distance.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // listener.onClick(position,v); // } // }); // } // else if (holder instanceof DistanceHolder) { // XiaoBaiReleaseEntity entity = distanceList.get(position); // ((DistanceHolder) holder).distance.setText(entity.getDistance()); // // if (entity.isDistanceSelected() == true) { // ((DistanceHolder) holder).distance.setBackground(context.getResources().getDrawable(R.drawable.xiao_bai_release_distance_background2)); // ((DistanceHolder) holder).distance.setTextColor(context.getResources().getColor(R.color.color_ffbe4c)); // } // else { // ((DistanceHolder) holder).distance.setBackground(context.getResources().getDrawable(R.drawable.xiao_bai_release_distance_background1)); // ((DistanceHolder) holder).distance.setTextColor(context.getResources().getColor(R.color.color_999999)); // } // // ((DistanceHolder) holder).distance.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // listener.onClick(position,v); // } // }); // } // else if (holder instanceof ProjectHolder) { // XiaoBaiReleaseEntity entity = projectList.get(position); // ((ProjectHolder) holder).project.setText(entity.getProject()); // // if (entity.isProjectSelected() == true) { // ((ProjectHolder) holder).project.setBackground(context.getResources().getDrawable(R.drawable.xiao_bai_release_distance_background2)); // ((ProjectHolder) holder).project.setTextColor(context.getResources().getColor(R.color.color_ffbe4c)); // } // else { // ((ProjectHolder) holder).project.setBackground(context.getResources().getDrawable(R.drawable.xiao_bai_release_distance_background1)); // ((ProjectHolder) holder).project.setTextColor(context.getResources().getColor(R.color.color_999999)); // } // // ((ProjectHolder) holder).project.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // listener.onClick(position,v); // } // }); // } // } // // @Override // public int getItemCount() { // if (viewType == TYPE_RELEASE) { // return dataList.size(); // } // else if (viewType == TYPE_DISTANCE){ // return distanceList.size(); // } // else { // return projectList.size(); // } // } // // // class ReleaseHolder extends BaseViewHolder { // private ImageView portrait; // private TextView name; // private TextView id; // private TextView introduce; // private TextView date; //// private TextView commentNumber; //// private TextView likeNumber; // private ImageView imgPop; // private TextView distance; // private RecyclerView photoRecyclerView; // private RecyclerView commentRecyclerView; // private LinearLayout viewDetails; // // public ReleaseHolder(@NonNull View itemView) { // super(itemView); // portrait = itemView.findViewById(R.id.portrait); // name = itemView.findViewById(R.id.name); // id = itemView.findViewById(R.id.id); // introduce = itemView.findViewById(R.id.introduce); // date = itemView.findViewById(R.id.date); //// commentNumber = itemView.findViewById(R.id.commentNumber); //// likeNumber = itemView.findViewById(R.id.likeNumber); // imgPop = itemView.findViewById(R.id.imgPop); // distance = itemView.findViewById(R.id.distance); // photoRecyclerView = itemView.findViewById(R.id.photoRecyclerView); // commentRecyclerView = itemView.findViewById(R.id.commentRecyclerView); // viewDetails = itemView.findViewById(R.id.viewDetails); // } // } // // class DistanceHolder extends BaseViewHolder { // private TextView distance; // // public DistanceHolder(@NonNull View itemView) { // super(itemView); // distance = itemView.findViewById(R.id.distance); // } // } // // class ProjectHolder extends BaseViewHolder { // private TextView project; // // public ProjectHolder(@NonNull View itemView) { // super(itemView); // project = itemView.findViewById(R.id.project); // } // } // // // class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.ViewHolder> { // private Context context; // private List<Integer> data; // // public PhotoAdapter(Context context, List<Integer> data) { // this.context = context; // this.data = data; // } // // @Override // public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // View itemView = LayoutInflater.from(context).inflate(R.layout.item_item_xiao_bai_release, parent, false); // return new ViewHolder(itemView); // } // // @Override // public void onBindViewHolder(@NonNull ViewHolder holder, final int position) { // int photo = data.get(position); // // holder.photo.setImageResource(photo); // // holder.iconVideo.setVisibility(View.GONE); // } // // @Override // public int getItemCount() { // return data.size(); // } // // public class ViewHolder extends RecyclerView.ViewHolder { // private ImageView photo; // private ImageView iconVideo; // // public ViewHolder(View itemView) { // super(itemView); // photo = itemView.findViewById(R.id.photo); // iconVideo = itemView.findViewById(R.id.icon_video); // } // } // } // // class CommentAdapter extends RecyclerView.Adapter<CommentAdapter.ViewHolder> { // private Context context; // private List<XiaoBaiReleaseEntity.CommentBean> data; // // public CommentAdapter(Context context, List<XiaoBaiReleaseEntity.CommentBean> data) { // this.context = context; // this.data = data; // } // // @Override // public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // View itemView = LayoutInflater.from(context).inflate(R.layout.item_item_xiao_bai_release_comment, parent, false); // return new ViewHolder(itemView); // } // // @Override // public void onBindViewHolder(@NonNull ViewHolder holder, final int position) { // String name = data.get(position).getName(); // String content = data.get(position).getContent(); // // String commentContent = "<font color= \"#502d00\">" + name + "&nbsp&nbsp&nbsp<small>" + content + "</small></font>"; // holder.commentContent.setText(Html.fromHtml(commentContent)); // } // // @Override // public int getItemCount() { // return data.size(); // } // // public class ViewHolder extends RecyclerView.ViewHolder { // private TextView commentContent; // // public ViewHolder(View itemView) { // super(itemView); // commentContent = itemView.findViewById(R.id.commentContent); // } // } // } // // // public void setOnItemClickListener(OnItemClickListener itemListener) { // this.itemListener = itemListener; // } // // public void setOnClickListener(OnClickListener listener) { // this.listener = listener; // } // // public interface OnItemClickListener { // void onItemClick(int position); // } // // public interface OnClickListener { // void onClick(int position, View view); // } //}
package com.dungnguyen.small.twitter.model; /** * Created by Admin on 3/5/2016. */ public class Tweet { public long id; public String content; public String author; public String [] images; /** * Data in each tweet * @param id * @param content * @param author * @param images */ public Tweet(long id, String content, String author, String [] images) { this.id = id; this.content = content; this.author = author; this.images = images; } }
package Services.Orchestration.Requests; public class OrchestrationRequest { public int id; public int ownerID; public int startJobID; }
import java.util.Scanner; public class BMI{ public static void main(String[] args){ Scanner value = new Scanner(System.in); double height; double weight; double BMI; System.out.print("Enter your height in meters: "); height = value.nextDouble(); System.out.print("Enter your weight in kg: "); weight = value.nextDouble(); BMI = weight/ (height * height); System.out.println("Your BMI value is " + BMI); System.out.println(); System.out.println("BMI VALUES \n Underweight: less than 18.5 \n Normal: between 18.5 and 24.9\n Overweight: between 25 and 29.9 \n Obese: 30 or greater"); System.out.printf("value of %f + %f is %f%n", height, weight,(weight + height)); } }
package com.tyj.venus.entity; import lombok.Data; import javax.persistence.*; import java.io.Serializable; import java.util.Date; @Data @Entity @Table(name = "t_user") public class UserInfo implements Serializable { @Id @Column(name = "user_id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer userId; @Column(name = "username") private String username; @Column(name = "phone") private String phone; @Column(name = "email") private String email; @Column(name = "nickname") private String nickname; @Column(name = "birthday") private String birthday; @Column(name = "gender") private String gender; @Column(name = "password") private String password; @Column(name = "token") private String token; @Column(name = "avatar") private String avatar; @Column(name = "description") private String description; // 登录次数 @Column(name = "login_count") private Integer loginCount; // 粉丝数 @Column(name = "followers_count") private Integer followersCount; // 关注数 @Column(name = "friends_count") private Integer friendsCount; // 帖子数 @Column(name = "statuses_count") private Integer statusesCount; // 收藏数 @Column(name = "favourites_count") private Integer favouritesCount; @Column(name = "login_at") private Date loginAt; @Column(name = "created_at") private Date createdAt; @Column(name = "update_at") private Date updateAt; }
package kr.co.flyingturtle.repository.vo; import java.util.Date; import java.util.List; import org.springframework.web.multipart.MultipartFile; public class Canvas extends Page { private int canNo; private int ssbjNo; private String ssbjName; private String sysName; private String oriName; private String path; private int size; private Date regDate; private int sbjNo; private String sbjName; private String title; public int getCanNo() { return canNo; } public void setCanNo(int canNo) { this.canNo = canNo; } public int getSsbjNo() { return ssbjNo; } public void setSsbjNo(int ssbjNo) { this.ssbjNo = ssbjNo; } public String getSsbjName() { return ssbjName; } public void setSsbjName(String ssbjName) { this.ssbjName = ssbjName; } public String getSysName() { return sysName; } public void setSysName(String sysName) { this.sysName = sysName; } public String getOriName() { return oriName; } public void setOriName(String oriName) { this.oriName = oriName; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public Date getRegDate() { return regDate; } public void setRegDate(Date regDate) { this.regDate = regDate; } public int getSbjNo() { return sbjNo; } public void setSbjNo(int sbjNo) { this.sbjNo = sbjNo; } public String getSbjName() { return sbjName; } public void setSbjName(String sbjName) { this.sbjName = sbjName; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
package db; import java.io.File; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import org.jooq.impl.DSL; import org.jooq.impl.SQLDataType; import utils.DbUtils; public class SmallProvidDbCreator { public static void createSmallProvidenceDb(File crawlDbFile, File outputDbFile) throws SQLException { DbConnection crawlDb = new DbConnection(crawlDbFile, true) {}; DbConnection outputDb = new DbConnection(outputDbFile, false) { @Override protected void prepare() { try { this.connection.setAutoCommit(false); } catch (SQLException e) { e.printStackTrace(); } } @Override protected void createTables() { this.context.createTable("sentence") .column("id", SQLDataType.INTEGER.identity(true)) .column("sentence", SQLDataType.CLOB) .constraints( DSL.unique("sentence") ) .execute(); this.context.createTable("sentence_pld") .column("id", SQLDataType.INTEGER.identity(true)) .column("sentence", SQLDataType.INTEGER) .column("pld", SQLDataType.VARCHAR) .constraints( DSL.unique("sentence", "pld"), DSL.foreignKey("sentence").references("sentence") ) .execute(); this.context.createIndex().on("sentence", "sentence").execute(); this.context.createIndex().on("sentence", "pld").execute(); this.context.createTable("lemma") .column("id", SQLDataType.INTEGER.identity(true)) .column("lemma", SQLDataType.VARCHAR) .constraints( DSL.unique("lemma") ) .execute(); this.context.createTable("term") .column("id", SQLDataType.INTEGER.identity(true)) .column("premod", SQLDataType.VARCHAR) .column("nouns", SQLDataType.VARCHAR) .column("postmod", SQLDataType.VARCHAR) .constraints( DSL.unique("premod", "nouns", "postmod") ) .execute(); this.context.createTable("matching") .column("id", SQLDataType.INTEGER.identity(true)) .column("sentence", SQLDataType.INTEGER) .column("pattern", SQLDataType.VARCHAR) .constraints( DSL.unique("sentence", "pattern") ) .execute(); this.context.createIndex().on("matching", "sentence").execute(); this.context.createIndex().on("matching", "pattern").execute(); } }; PreparedStatement insertSentenceQuery = crawlDb.connection.prepareStatement("INSERT INTO sentence (id, sentence) VALUES (?, ?)"); ResultSet sentences = outputDb.connection.createStatement().executeQuery("SELECT id, sentence FROM sentence"); while (sentences.next()) { insertSentenceQuery.setInt(1, sentences.getInt(1)); insertSentenceQuery.setString(1, sentences.getString(2)); insertSentenceQuery.execute(); } outputDb.connection.commit(); PreparedStatement insertSentencePldQuery = crawlDb.connection.prepareStatement("INSERT INTO sentence_pld (sentence, pld) VALUES (?, ?)"); PreparedStatement getPldQuery = crawlDb.connection.prepareStatement("SELECT pld FROM pld WHERE id = ?"); ResultSet sentencePlds = outputDb.connection.createStatement().executeQuery("SELECT sentence, pld FROM sentence_pld"); while (sentencePlds.next()) { getPldQuery.setInt(1, sentencePlds.getInt(2)); String pld = DbUtils.getFirstRow(getPldQuery.executeQuery()).getString(1); insertSentencePldQuery.setInt(1, sentencePlds.getInt(1)); insertSentencePldQuery.setString(2, pld); insertSentencePldQuery.execute(); } outputDb.connection.commit(); PreparedStatement insertLemmaQuery = crawlDb.connection.prepareStatement("INSERT INTO lemma (id, lemma) VALUES (?, ?)"); ResultSet lemmas = outputDb.connection.createStatement().executeQuery("SELECT id, words FROM lemmagroup"); while (lemmas.next()) { insertLemmaQuery.setInt(1, lemmas.getInt(1)); insertLemmaQuery.setString(2, lemmas.getString(2)); insertLemmaQuery.execute(); } outputDb.connection.commit(); PreparedStatement insertTermQuery = crawlDb.connection.prepareStatement("INSERT INTO term (id, premod, nouns, postmod) VALUES (?, ?, ?, ?)"); PreparedStatement getTermQuery = crawlDb.connection.prepareStatement("SELECT pre.words, ng.words, post.words FROM premod as pre, noungroup as ng, postmod as post WHERE pre.id = ? AND ng.id = ? AND post.id = ?"); ResultSet terms = outputDb.connection.createStatement().executeQuery("SELECT id, premod, noungroup, postmod FROM term"); while (terms.next()) { getTermQuery.setInt(1, terms.getInt(2)); getTermQuery.setInt(2, terms.getInt(3)); getTermQuery.setInt(3, terms.getInt(4)); ResultSet term = DbUtils.getFirstRow(getTermQuery.executeQuery()); insertTermQuery.setInt(1, sentencePlds.getInt(1)); insertTermQuery.setString(2, term.getString(1)); insertTermQuery.setString(3, term.getString(2)); insertTermQuery.setString(4, term.getString(3)); insertTermQuery.execute(); } outputDb.connection.commit(); Map<Integer, String> patternMap = new HashMap<Integer, String>(); PreparedStatement insertMatchingQuery = crawlDb.connection.prepareStatement("INSERT INTO matching (id, sentence, pattern) VALUES (?, ?, ?)"); PreparedStatement getPatternQuery = crawlDb.connection.prepareStatement("SELECT name FROM pattern WHERE id = ?"); ResultSet matchings = outputDb.connection.createStatement().executeQuery("SELECT id, sentence, pattern FROM matching"); while (matchings.next()) { int patternId = matchings.getInt(3); String patternName = patternMap.get(patternId); if (patternName == null) { getPatternQuery.setInt(1, patternId); patternName = DbUtils.getFirstRow(getPatternQuery.executeQuery()).getString(1); patternMap.put(patternId, patternName); } insertMatchingQuery.setInt(1, matchings.getInt(1)); insertMatchingQuery.setInt(2, matchings.getInt(2)); insertMatchingQuery.setString(3, patternName); insertMatchingQuery.execute(); } outputDb.connection.commit(); crawlDb.close(); outputDb.close(); } public static void createJoinedPairDb(File crawlDbFile, File tupleDbFile, File outputDbFile, PairType pairType) throws SQLException { DbConnection crawlDb = new DbConnection(crawlDbFile, true) {}; DbConnection tupleDb = new DbConnection(tupleDbFile, true) {}; DbConnection outputDb = new DbConnection(outputDbFile, false) { @Override protected void prepare() { try { this.connection.setAutoCommit(false); } catch (SQLException e) { e.printStackTrace(); } } @Override protected void createTables() { if (pairType == PairType.LEMMA) { this.context.createTable("tuple") .column("id", SQLDataType.INTEGER.identity(true)) .column("instance", SQLDataType.VARCHAR) .column("class", SQLDataType.VARCHAR) .column("count", SQLDataType.INTEGER) .column("pld_count", SQLDataType.INTEGER) .column("tuple_id", SQLDataType.INTEGER) .constraints( DSL.unique("instance", "class") ) .execute(); } else { this.context.createTable("tuple") .column("id", SQLDataType.INTEGER.identity(true)) .column("instance_premod", SQLDataType.VARCHAR) .column("instance_nouns", SQLDataType.VARCHAR) .column("instance_postmod", SQLDataType.VARCHAR) .column("class_premod", SQLDataType.VARCHAR) .column("class_nouns", SQLDataType.VARCHAR) .column("class_postmod", SQLDataType.VARCHAR) .column("count", SQLDataType.INTEGER) .column("pld_count", SQLDataType.INTEGER) .column("tuple_id", SQLDataType.INTEGER) .constraints( DSL.unique("instance_premod", "instance_nouns", "instance_nouns", "class_premod", "class_nouns", "class_postmod") ) .execute(); } this.context.createTable("tuple_pld") .column("id", SQLDataType.INTEGER.identity(true)) .column("pld", SQLDataType.VARCHAR) .column("tuple", SQLDataType.INTEGER) .constraints( DSL.unique("pld", "tuple"), DSL.foreignKey("tuple").references("tuple") ) .execute(); } }; int tupleCount = DbUtils.getFirstRow(tupleDb.connection.createStatement().executeQuery("SELECT count(*) FROM " + pairType.name().toLowerCase() + "_pair")).getInt(1); PreparedStatement getTermQuery = crawlDb.connection.prepareStatement( pairType == PairType.LEMMA ? "SELECT words FROM lemmagroup WHERE id = ?" : "SELECT pre.words, ng.words, post.words FROM term as t, premod as pre, noungroup as ng, postmod as post WHERE t.id = ? AND pre.id = t.premod AND ng.id = t.noungroup AND post.id = t.postmod" ); PreparedStatement insertTupleQuery = outputDb.connection.prepareStatement( pairType == PairType.LEMMA ? "INSERT INTO tuple (instance, class, count, pld_count, tuple_id) VALUES (?, ?, ?, ?, ?)": "INSERT INTO tuple (instance_premod, instance_nouns, instance_postmod, class_premod, class_nouns, class_postmod, count, pld_count, tuple_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)" ); PreparedStatement getPldsQuery = tupleDb.connection.prepareStatement("SELECT pld FROM " + pairType.name().toLowerCase()+ "_pair_pld WHERE " + pairType.name().toLowerCase() + "_pair = ?"); PreparedStatement getPldQuery = crawlDb.connection.prepareStatement("SELECT pld FROM pld WHERE id = ?"); PreparedStatement insertPldQuery = outputDb.connection.prepareStatement("INSERT INTO tuple_pld (pld, tuple) VALUES (?, ?)"); ResultSet tuples = tupleDb.connection.createStatement().executeQuery("SELECT id, instance, class, count, pld_count FROM " + pairType.name().toLowerCase() + "_pair"); int i = 0; while (tuples.next()) { if (i % 1000000 == 0) { System.out.println(String.format("tuples %.2f %%", 100.0D * i / tupleCount)); } i++; int tupleId = tuples.getInt(1); getTermQuery.setInt(1, tuples.getInt(2)); ResultSet instanceTerm = DbUtils.getFirstRow(getTermQuery.executeQuery()); getTermQuery.setInt(1, tuples.getInt(3)); ResultSet classTerm = DbUtils.getFirstRow(getTermQuery.executeQuery()); if (pairType == PairType.LEMMA) { insertTupleQuery.setString(1, instanceTerm.getString(1)); insertTupleQuery.setString(2, classTerm.getString(1)); insertTupleQuery.setInt(3, tuples.getInt(4)); insertTupleQuery.setInt(4, tuples.getInt(5)); insertTupleQuery.setInt(5, tupleId); } else { insertTupleQuery.setString(1, instanceTerm.getString(1)); insertTupleQuery.setString(2, instanceTerm.getString(2)); insertTupleQuery.setString(3, instanceTerm.getString(3)); insertTupleQuery.setString(4, classTerm.getString(1)); insertTupleQuery.setString(5, classTerm.getString(2)); insertTupleQuery.setString(6, classTerm.getString(3)); insertTupleQuery.setInt(7, tuples.getInt(4)); insertTupleQuery.setInt(8, tuples.getInt(5)); insertTupleQuery.setInt(9, tupleId); } insertTupleQuery.execute(); getPldsQuery.setInt(1, tupleId); ResultSet plds = getPldsQuery.executeQuery(); while (plds.next()) { getPldQuery.setInt(1, plds.getInt(1)); String pld = DbUtils.getFirstRow(getPldQuery.executeQuery()).getString(1); insertPldQuery.setString(1, pld); insertPldQuery.setInt(2, tupleId); insertPldQuery.execute(); } if (i % 1000000 == 0) { outputDb.connection.commit(); } } outputDb.connection.commit(); crawlDb.close(); tupleDb.close(); outputDb.close(); } }
import static org.junit.Assert.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class TowersOfHanoiTest { private static TowersOfHanoi th;static int n; @BeforeClass public static void setUpBeforeClass() throws Exception { th = new TowersOfHanoi(); n=3; } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testSolve() { th.solve(n, "X", "Y", "Z"); } }
// Generated by Dagger (https://google.github.io/dagger). package org.drulabs.bankbuddy.di; import dagger.internal.Factory; import dagger.internal.Preconditions; import javax.inject.Provider; import org.drulabs.bankbuddy.local.database.BankBuddyDB; import org.drulabs.bankbuddy.local.database.UserInfoDAO; public final class LocalPersistenceModule_ProvidesUserInfoDAOFactory implements Factory<UserInfoDAO> { private final LocalPersistenceModule module; private final Provider<BankBuddyDB> bankBuddyDBProvider; public LocalPersistenceModule_ProvidesUserInfoDAOFactory( LocalPersistenceModule module, Provider<BankBuddyDB> bankBuddyDBProvider) { this.module = module; this.bankBuddyDBProvider = bankBuddyDBProvider; } @Override public UserInfoDAO get() { return provideInstance(module, bankBuddyDBProvider); } public static UserInfoDAO provideInstance( LocalPersistenceModule module, Provider<BankBuddyDB> bankBuddyDBProvider) { return proxyProvidesUserInfoDAO(module, bankBuddyDBProvider.get()); } public static LocalPersistenceModule_ProvidesUserInfoDAOFactory create( LocalPersistenceModule module, Provider<BankBuddyDB> bankBuddyDBProvider) { return new LocalPersistenceModule_ProvidesUserInfoDAOFactory(module, bankBuddyDBProvider); } public static UserInfoDAO proxyProvidesUserInfoDAO( LocalPersistenceModule instance, BankBuddyDB bankBuddyDB) { return Preconditions.checkNotNull( instance.providesUserInfoDAO(bankBuddyDB), "Cannot return null from a non-@Nullable @Provides method"); } }
package com.linkedlist.problems; public class JoinFirstLast { public static void main(String args[]){ System.out.println("HelloWorld"); } }
package com.android_dev.tatenuufrn.domain; import com.android_dev.tatenuufrn.databases.TatenUFRNDatabase; import com.raizlabs.android.dbflow.annotation.Column; import com.raizlabs.android.dbflow.annotation.ModelContainer; import com.raizlabs.android.dbflow.annotation.PrimaryKey; import com.raizlabs.android.dbflow.annotation.Table; import com.raizlabs.android.dbflow.structure.BaseModel; /** * Created by adelinosegundo on 11/24/15. */ @Table(databaseName = TatenUFRNDatabase.NAME) @ModelContainer public class User extends BaseModel { @Column @PrimaryKey(autoincrement = false) private String id; @Column private String login; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } }
import java.util.ArrayList; import java.util.Scanner; /* * 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. */ /** * * @author Grullon */ public class Tournament { private Scanner reader; private ArrayList<Jumper> jumpers; public Tournament(Scanner reader){ this.reader = reader; this.jumpers = new ArrayList<Jumper>(); } public void begin(){ System.out.println("Kumpula ski jumping week"); System.out.println(""); System.out.println("Write the names of the participants one at a time; an empty string brings you to the jumping phase."); while(true){ System.out.print(" Participant name: "); String jumper = reader.nextLine(); if(jumper.isEmpty()){ break; }else{ jumpers.add(new Jumper(jumper)); } } System.out.println(""); System.out.println("The tournament begins!"); startTournament(); } public void startTournament(){ Round round = new Round(jumpers, reader); round.startRound(); } }
package com.wangyang.basic.dao; import com.wangyang.model.Course; import com.wangyang.util.IBaseDao; import java.util.List; public interface ICourseDao extends IBaseDao<Course> { List<Course> findByGradeId(int gradeId); }
import Exercice.*; import AlgoClassic.*; import javax.swing.plaf.synth.SynthLabelUI; import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.StampedLock; public class test { public static void main (String[] args){ int[] tmp; //int[] arr1={4,5,8}; //int[] arr2={10,9,1,8}; /* int[] test ={2,1,2,3,5,6,7,3}; QuickSort qs =new QuickSort(); qs.quickSort(test,0, test.length-1); */ //MergeSort ms =new MergeSort(); //ms.Sort(test); //System.out.print(val); /* int[] arr ={3,2,1,5,6,4}; KthLargestElement kle = new KthLargestElement(); int val = kle.findKthLargest(arr,2); System.out.println(val); for(int i: arr){ System.out.print(i); } */ /* System.out.println(""); for(int i=0; i<test.length;i++){ System.out.print(test[i]+" "); }*/ NonDecreasingArray nda= new NonDecreasingArray(); int[] test={4,2,13,15}; System.out.println(nda.checkPossibility(test)); } }
package ru.job4j.search; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.function.Predicate; public class Search { public static void main(String[] args) throws Exception { Path startDir = Paths.get("/home/alex/project/job4j/io"); search(startDir, t -> t.toFile().getName().endsWith("html")).forEach(System.out::println); } public static List<Path> search(Path root, Predicate<Path> condition) throws Exception { SearchFiles searcher = new SearchFiles(condition); Files.walkFileTree(root, searcher); return searcher.getPaths(); } }
package com.route_category_note.model; public class Route_Category_NoteVO implements java.io.Serializable{ private String route_no; private String route_cate_no; public String getRoute_no() { return route_no; } public void setRoute_no(String route_no) { this.route_no = route_no; } public String getRoute_cate_no() { return route_cate_no; } public void setRoute_cate_no(String route_cate_no) { this.route_cate_no = route_cate_no; } }
package com.snxy.pay.config.wx; public enum WxBillCodeEnum { SYSTEMERROR("SYSTEMERROR","接口返回错误"), INVALID_TRANSACTIONID("INVALID_TRANSACTIONID","无效 transaction_id"), PARAM_ERROR("PARAM_ERROR","参数错误"); private String errCode ; private String msg; WxBillCodeEnum(String errCode, String msg) { this.errCode = errCode ; this.msg = msg; } public String getErrCode() { return errCode; } public void setErrCode(String errCode) { this.errCode = errCode; } @Override public String toString() { return "WxBillCodeEnum{" + "errCode='" + errCode + '\'' + ", msg='" + msg + '\'' + '}'; } }
package com.homework.pattern.factorymethod; /** * @author lq * @version 1.0 * @desc * @date 2019/3/18 23:50 **/ public class EnglishBookFactory implements IBookFactory { @Override public IBook create() { return new EnglishBook(); } }
package it.sevenbits.codecorrector.formatter.javaformatter.handle; import it.sevenbits.codecorrector.formatter.javaformatter.JavaConverterConfig; import it.sevenbits.codecorrector.formatter.javaformatter.State; /** * Created by remmele on 05.07.16. */ public class AddSpaceInBuffer implements IHandler { public String doAction(final Character character, final JavaConverterConfig config) { config.appendInBuffer(character); config.setState(State.Space); return ""; } }
package com.evpa.spring.redis.cass.controller; import com.evpa.spring.redis.cass.dao.Stb; import com.evpa.spring.redis.cass.service.StbService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.Date; @RestController @RequestMapping("/v1") public class StbController { private static final Logger LOGGER = LoggerFactory.getLogger(StbController.class); @Autowired StbService service; @PostMapping(value = "/stb", consumes="application/json") public ResponseEntity createStb(@Valid @RequestBody Stb stb) { LOGGER.info("stb::{}",stb); service.save(stb); return ResponseEntity.status(HttpStatus.CREATED).build(); } @PostMapping(value = "/stb/invalidate") public ResponseEntity invalidateCache() { service.invalidate(); return ResponseEntity.status(HttpStatus.OK).build(); } @PostMapping(value = "/stb/{key}/{dt}") public ResponseEntity updateLastUpdatedTime(@PathVariable long dt, @PathVariable String key) { LOGGER.info("key:: {} dt:: {}",key,dt); service.updateLastUpdatedTime(new Date(dt),key); return ResponseEntity.ok().build(); } @PostMapping(value = "/stb/crc/{key}/{crcScheduled}") public ResponseEntity updateCrcScheduled(@PathVariable long crcScheduled, @PathVariable String key) { LOGGER.info("key:: {} crcScheduled:: {}",key, crcScheduled); service.updateCrcScheduled(crcScheduled, new Date(), key); return ResponseEntity.ok().build(); } @PostMapping(value = "/stbs", consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity createStbs(@Valid @RequestBody Iterable<Stb> stbs) { service.saveAll(stbs); return ResponseEntity.status(HttpStatus.CREATED).build(); } @GetMapping(value = "/stb/{key}", produces = MediaType.APPLICATION_JSON_VALUE) public Stb findStb(@PathVariable String key) { LOGGER.info("key:: {}",key); return service.find(key).get(); } @GetMapping(value = "/stb", produces = MediaType.APPLICATION_JSON_VALUE) public Iterable<Stb> findAll() { return service.findAll(); } }
package com.uniinfo.cloudplat.vo; import com.uniinfo.common.base.RespInfo; public class AccessTokenRespVO extends RespInfo { private String access_token;// string 用于调用access_token,接口获取授权后的access token。 private long expires_in;// string access_token的生命周期,单位是秒数。 private String uid;// string 当前授权用户的UID。 public String getAccess_token() { return access_token; } public void setAccess_token(String accessToken) { access_token = accessToken; } public long getExpires_in() { return expires_in; } public void setExpires_in(long expiresIn) { expires_in = expiresIn; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } }
package com.example.usuario.recyclerview; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class Bienvenida extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bienvenida); startActivity(new Intent(Bienvenida.this, MainActivity.class)); finish(); } }
package com.alibaba.druid.bvt.pool.profile; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidPooledConnection; import junit.framework.TestCase; public class ProfileEnableTest extends TestCase { private DruidDataSource dataSource; protected void setUp() throws Exception { dataSource = new DruidDataSource(); dataSource.setUrl("jdbc:mock:xxx"); dataSource.setMaxWait(1000); } protected void tearDown() throws Exception { dataSource.close(); } public void testDefault() throws Exception { for (int i = 0; i < 10; ++i) { DruidPooledConnection conn = dataSource.getConnection(); System.out.println("physicalConnectNanoSpan : " + conn.getPhysicalConnectNanoSpan()); System.out.println("physicalConnectionUsedCount : " + conn.getPhysicalConnectionUsedCount()); System.out.println("connectNotEmptyWaitNanos : " + conn.getConnectNotEmptyWaitNanos()); conn.close(); } } }
package FlowProccessor.model.impl; import FlowProccessor.model.IBotFlowModel; import org.telegram.telegrambots.api.interfaces.BotApiObject; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Optional; import java.util.stream.Stream; public abstract class BotBaseModelEntity implements BotApiObject, IBotFlowModel { public Object get(String fieldName){ Optional<Method> getterMethodOptional = Stream.of(getClass().getMethods()) .filter(method1 -> method1.getName().equalsIgnoreCase("get" + fieldName) || method1.getName().equalsIgnoreCase("is" + fieldName)) .findFirst(); Object val = null; try { val = getterMethodOptional .orElseThrow(() -> new RuntimeException("No getter found for field with value: " + fieldName)) .invoke(this); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } return val; } public void set(String fieldName, Object value){ Optional<Method> setterMethodOptional = Stream.of(getClass().getMethods()) .filter(method1 -> method1.getName().equalsIgnoreCase("set" + fieldName)) .findFirst(); try { setterMethodOptional .orElseThrow(() -> new RuntimeException("No setter found for field with value: " + fieldName)) .invoke(this, value); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } }
package uy.edu.um.adt.linkedlist; import java.util.Iterator; public class MyListIterator<T> implements Iterator<T> { private Node<T> data; public MyListIterator(Node<T> first) { data = first; } @Override public boolean hasNext() { return data != null; } @Override public T next() { T value = data.getValue(); data = data.getNext(); return value; } }
/* * 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 pertemuan7; /** * * @author Angga */ public class StringBuilderCapLen { public static void main(String[] args) { StringBuilder buffer = new StringBuilder("Hello,How Are You?"); System.out.printf("buffer = %s\nlength = %d\ncapacity = %d\n\n",buffer.toString(),buffer.length(),buffer.capacity()); buffer.ensureCapacity(75); System.out.printf("New capacity = %d\n\n",buffer.capacity()); buffer.setLength(10); System.out.printf("New length = %d\nbuffer = %s\n",buffer.length(),buffer.toString()); } }
/* * © Copyright 2016 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied * verbatim in the file “COPYING“. In applying this licence, CERN does not waive the privileges and immunities granted * to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction. */ package cern.molr.commons.mission; import cern.molr.commons.domain.Mission; import cern.molr.commons.exception.MissionMaterializationException; /** * Interface that provides a way to instantiate {@link Mission}s * * @author tiagomr */ public interface MissionMaterializer { /** * Tries to instantiate a mission from a given {@link Class} * * @param classType {@link Class} from which the {@link Mission} will be generated * @return A {@link Mission} * @see Mission */ Mission materialize(Class<?> classType) throws MissionMaterializationException; }
package org.usfirst.frc.team178.robot.commands; import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc.team178.robot.Robot; import org.usfirst.frc.team178.robot.subsystems.Intake; /** * */ public class CorrectIntake extends Command { Intake intake; public CorrectIntake() { requires(Robot.intake); // Use requires() here to declare subsystem dependencies // eg. requires(chassis); } // Called just before this Command runs the first time protected void initialize() { intake = Robot.intake; } // Called repeatedly when this Command is scheduled to run protected void execute() { if(intake.getIntakeLocation()!=intake.isTopLimitSwitchTripped()&& intake.getIntakeLocation()) { Robot.intake.liftIntake(); } else if(intake.getIntakeLocation()!=intake.isBottomLimitSwitchTripped()&& !intake.getIntakeLocation()) { Robot.intake.dropIntake(); } else { Robot.intake.setUpDown(0); } } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
package org.jphototagger.program.module.imagecollections; import java.awt.Container; import java.awt.event.MouseEvent; import javax.swing.ListModel; import org.jphototagger.lib.swing.Dialog; import org.jphototagger.lib.swing.util.MnemonicUtil; import org.jphototagger.lib.util.Bundle; import org.jphototagger.program.factory.ModelFactory; import org.jphototagger.program.resource.GUI; /** * Dialog zum Anzeigen und Auswählen der Namen von Bildsammlungen. * * @author Elmar Baumann */ public final class ImageCollectionsDialog extends Dialog { private static final long serialVersionUID = 1L; private boolean ok = false; public ImageCollectionsDialog() { super(GUI.getAppFrame(), true); initComponents(); postInitComponents(); } private void postInitComponents() { setHelpPageUrl(Bundle.getString(ImageCollectionsDialog.class, "ImageCollectionsDialog.HelpPage")); MnemonicUtil.setMnemonics((Container) this); } public boolean isCollectionSelected() { return ok && (listImageCollectionNames.getSelectedValue() != null); } public String getSelectedCollectionName() { Object value = listImageCollectionNames.getSelectedValue(); return ((value == null) ||!ok) ? null : value.toString(); } private void checkDoubleClick(MouseEvent evt) { if (evt.getClickCount() == 2) { int index = listImageCollectionNames.locationToIndex(evt.getPoint()); ListModel<?> model = listImageCollectionNames.getModel(); Object item = model.getElementAt(index); if (item != null) { ok = true; setVisible(true); } } } private void handleButtonOkClicked() { ok = true; setVisible(false); } @Override protected void escape() { setVisible(false); } /** * This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") private void initComponents() {//GEN-BEGIN:initComponents labelSelectImageCollection = new javax.swing.JLabel(); scrollPaneImageCollectionNames = new javax.swing.JScrollPane(); listImageCollectionNames = new org.jdesktop.swingx.JXList(); buttonOk = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jphototagger/program/module/imagecollections/Bundle"); // NOI18N setTitle(bundle.getString("ImageCollectionsDialog.title")); // NOI18N setName("Form"); // NOI18N labelSelectImageCollection.setLabelFor(listImageCollectionNames); labelSelectImageCollection.setText(bundle.getString("ImageCollectionsDialog.labelSelectImageCollection.text")); // NOI18N labelSelectImageCollection.setName("labelSelectImageCollection"); // NOI18N scrollPaneImageCollectionNames.setName("scrollPaneImageCollectionNames"); // NOI18N listImageCollectionNames.setModel(ModelFactory.INSTANCE.getModel(org.jphototagger.program.module.imagecollections.ImageCollectionsListModel.class)); listImageCollectionNames.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); listImageCollectionNames.setCellRenderer(new org.jphototagger.program.module.imagecollections.ImageCollectionsListCellRenderer()); listImageCollectionNames.setName("listImageCollectionNames"); // NOI18N listImageCollectionNames.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { listImageCollectionNamesMouseClicked(evt); } }); scrollPaneImageCollectionNames.setViewportView(listImageCollectionNames); buttonOk.setText(bundle.getString("ImageCollectionsDialog.buttonOk.text")); // NOI18N buttonOk.setName("buttonOk"); // NOI18N buttonOk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonOkActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(scrollPaneImageCollectionNames, javax.swing.GroupLayout.DEFAULT_SIZE, 240, Short.MAX_VALUE) .addComponent(labelSelectImageCollection, javax.swing.GroupLayout.DEFAULT_SIZE, 240, Short.MAX_VALUE) .addComponent(buttonOk, javax.swing.GroupLayout.Alignment.TRAILING)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(labelSelectImageCollection) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(scrollPaneImageCollectionNames, javax.swing.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(buttonOk) .addContainerGap()) ); pack(); }//GEN-END:initComponents private void buttonOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOkActionPerformed handleButtonOkClicked(); }//GEN-LAST:event_buttonOkActionPerformed private void listImageCollectionNamesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listImageCollectionNamesMouseClicked checkDoubleClick(evt); }//GEN-LAST:event_listImageCollectionNamesMouseClicked // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton buttonOk; private javax.swing.JLabel labelSelectImageCollection; private org.jdesktop.swingx.JXList listImageCollectionNames; private javax.swing.JScrollPane scrollPaneImageCollectionNames; // End of variables declaration//GEN-END:variables }
package com.hhdb.csadmin.plugin.tree.ui.rightMenu.action; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import com.hhdb.csadmin.common.bean.ServerBean; import com.hh.frame.common.log.LM; import com.hh.frame.swingui.event.CmdEvent; import com.hh.frame.swingui.event.ErrorEvent; import com.hh.frame.swingui.event.HHEvent; import com.hhdb.csadmin.plugin.tree.HTree; import com.hhdb.csadmin.plugin.tree.ui.BaseDialog; import com.hhdb.csadmin.plugin.tree.ui.BaseTextArea; import com.hhdb.csadmin.plugin.tree.ui.BaseTreeNode; import com.hhdb.csadmin.plugin.tree.util.BaseChangeInterface; import com.hhdb.csadmin.plugin.tree.util.TreeNodeUtil; /** * 创建Schema * * @author huyuanzhui * */ public class CreateSchema extends JPanel implements BaseChangeInterface { private static final long serialVersionUID = -974885363090566734L; private JTextField jschema = new JTextField(); //private JComboBox<String> jowner = new JComboBox<String>(); private BaseTextArea comment; private BaseTreeNode treeNode; private HTree htree; public CreateSchema(final BaseTreeNode treeNode,HTree htree) { this.htree = htree; this.treeNode = treeNode; CmdEvent getsbEvent = new CmdEvent(htree.PLUGIN_ID, "com.hhdb.csadmin.plugin.conn", "GetServerBean"); HHEvent rsbevent = htree.sendEvent(getsbEvent); ServerBean serverbean = (ServerBean)rsbevent.getObj(); setLayout(new BorderLayout()); initCompant(serverbean); BaseDialog baseDialog = new BaseDialog(null, this, "新建模式", ""); baseDialog.setSize(310, 280); baseDialog.showDialog(); } private void initCompant(ServerBean serverBean) { comment = new BaseTextArea(100); comment.setRowAsColumn(3, 6); JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); panel.setPreferredSize(new Dimension(280, 180)); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.BOTH; gbc.anchor = GridBagConstraints.NORTHWEST; gbc.insets = new Insets(10, 10, 10, 10); gbc.gridx = 0; gbc.gridy = 0; panel.add(new JLabel("名称:"), gbc); gbc.gridx = 1; gbc.gridy = 0; gbc.gridwidth = 1; gbc.weightx = 0.5; panel.add(jschema, gbc); gbc.gridx = 0; gbc.gridy = 2; panel.add(new JLabel("注释:"), gbc); gbc.gridx = 1; gbc.gridy = 2; gbc.gridwidth = 1; gbc.weightx = 0.5; panel.add(comment, gbc); add(panel, BorderLayout.NORTH); repaint(); } @Override public boolean execute() { String schemaName = jschema.getText(); if (schemaName.trim().equals("")) { JOptionPane.showMessageDialog(null, "模式名不能为空!!", "提示", JOptionPane.INFORMATION_MESSAGE); } else if(schemaName.indexOf("\"")>0){ JOptionPane.showMessageDialog(null, "模式名不能含有此类字符!", "提示", JOptionPane.INFORMATION_MESSAGE); } else if(schemaName.indexOf("\'")>0){ JOptionPane.showMessageDialog(null, "模式名不能含有此类字符!", "提示", JOptionPane.INFORMATION_MESSAGE); } else { CmdEvent getsbEvent = new CmdEvent(htree.PLUGIN_ID, "com.hhdb.csadmin.plugin.conn", "GetServerBean"); HHEvent rsbevent = htree.sendEvent(getsbEvent); ServerBean serverbean = (ServerBean)rsbevent.getObj(); String commentText = comment.getText(); StringBuilder sql = new StringBuilder(50); sql.append("CREATE SCHEMA \""); sql.append(schemaName); sql.append("\"\r\n"); sql.append("AUTHORIZATION "); sql.append(serverbean.getUserName()).append(";"); if (!commentText.trim().isEmpty()) { sql.append("\r\n"); sql.append("COMMENT ON SCHEMA "); sql.append(schemaName); sql.append("\r\n"); sql.append(" IS "); sql.append("'").append(commentText).append("'"); } String toID="com.hhdb.csadmin.plugin.conn"; CmdEvent event = new CmdEvent(htree.PLUGIN_ID, toID, "ExecuteUpdateBySqlEvent"); event.addProp("sql_str", sql.toString()); HHEvent ev = htree.sendEvent(event); if(ev instanceof ErrorEvent){ JOptionPane.showMessageDialog(null, ((ErrorEvent) ev).getErrorMessage(), "错误", JOptionPane.ERROR_MESSAGE); }else{ // BaseTreeNode temptreenode = new BaseTreeNode(); // MetaTreeNodeBean mtn = new MetaTreeNodeBean(); // mtn.setName(schemaName); // mtn.setOpenIcon("schema.png"); // mtn.setType(TreeNodeUtil.SCHEMA_ITEM_TYPE); // mtn.setUnique(true); // temptreenode.setMetaTreeNodeBean(mtn); if(treeNode.getType().equals(TreeNodeUtil.SCHEMA_ITEM_TYPE)){ // temptreenode.setParentBaseTreeNode(treeNode.getParentBaseTreeNode()); // ((BaseTree)(htree.getComponent())).getTreeModel().insertNodeInto // (temptreenode,treeNode.getParentBaseTreeNode(),treeNode.getParentBaseTreeNode().getChildCount()); try { htree.treeService.refreshSchemaCollection(treeNode.getParentBaseTreeNode()); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else{ // temptreenode.setParentBaseTreeNode(treeNode); // ((BaseTree)(htree.getComponent())).getTreeModel().insertNodeInto // (temptreenode,treeNode,treeNode.getChildCount()); try { htree.treeService.refreshSchemaCollection(treeNode); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } } } return true; } }
import java.io.*; import java.util.*; class Productos implements Serializable{ private static final long serialVersionUID = 1L; protected String ID; protected String nombreProducto; protected String unidades; protected int cantidad; protected String descripcion; protected int precioCompra; protected int precioVenta; public Productos() {} Productos(String ID, String nombreProducto, String unidades,int cantidad, String descripcion, int precioCompra, int precioVenta) { this.ID=ID; this.nombreProducto=nombreProducto; this.unidades=unidades; this.descripcion=descripcion; this.precioCompra=precioCompra; this.precioVenta=precioVenta; this.cantidad=cantidad; } public String getID() { return ID; } public void setID(String iD) { this.ID = iD; } public String getNombreProducto() { return nombreProducto; } public void setNombreProducto(String nombreProducto) { this.nombreProducto = nombreProducto; } public String getUnidades() { return unidades; } public void setUnidades(String unidades) { this.unidades = unidades; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public int getPrecioCompra() { return precioCompra; } public void setPrecioCompra(int precioCompra) { this.precioCompra = precioCompra; } public int getPrecioVenta() { return precioVenta; } public void setPrecioVenta(int precioVenta) { this.precioVenta = precioVenta; } public int getCantidad() { return cantidad; } public void setCantidad(int cantidad) { this.cantidad = cantidad; } public String toString() { return("El producto de nombre "+nombreProducto+"\nCon ID "+ID+"\nCuya unidad es "+unidades+"\nLa cantidad de productos es "+cantidad+"\nLa Descripción es "+descripcion+"\nSu precio de venta es $" + precioVenta+"\nSu precio de compra es $"+precioCompra); } } class Venta implements Serializable{ private static final long serialVersionUID = 1L; int ganancia; int IVA; int cantidadV; String nombreProductoV; String IDV; int total; Date fecha; public Date getFecha() { return fecha; } public void setFecha(Date fecha) { this.fecha = fecha; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public int getCantidadV() { return cantidadV; } public void setCantidadV(int cantidadV) { this.cantidadV = cantidadV; } public String getNombreProductoV() { return nombreProductoV; } public void setNombreProductoV(String nombreProductoV) { this.nombreProductoV = nombreProductoV; } public String getIDV() { return IDV; } public void setIDV(String iDV) { IDV = iDV; } public Venta(int ganancia) { this.ganancia = ganancia; } public int getIVA() { return IVA; } public void setIVA(int iVA) { IVA = iVA; } public double getGanancia() { return ganancia; } public void setGanancia(int ganancia) { this.ganancia = ganancia; } public String toString() { return "La fecha de compra es "+fecha+"\nSe vendieron "+cantidadV+" de "+nombreProductoV+" con ID "+IDV+" y el total de la ganancia fue $"+ganancia+" mas el IVA $"+IVA+" el precio total es de $"+(ganancia+IVA); } } public class Inventario { public static void main(String[] args) { @SuppressWarnings("resource") Scanner lector= new Scanner(System.in); //Programa que guarda objetos de tipo inventario(cualquier numero) //Cada vez que se corre el programa crea un nuevo archivo int num=30; java.util.Date fechaActual = new java.util.Date(); Productos[]producto=new Productos[100]; Venta[]venta=new Venta[100]; int cont3=1,total=0; for(int i=0;i<100;i++){ File extra=new File("Venta"+cont3); if(extra.exists()){ cont3++; } else{ i=100; } } String name1="producto"; File file=new File(name1);//Esto hace que puedas crear un archivo nuevo cada corrida if(!file.exists()){ try{ file.createNewFile();//se crea el archivo con la condicion de no existe System.out.println(file.getName()+" Se ha creado el archivo"); } catch(IOException ex){ ex.printStackTrace(); } for(int i=0;i<num;i++){ System.out.println("Introduce el ID del producto"); lector.nextLine(); String ID = lector.nextLine(); System.out.println("Introduce nombre del producto"); String nombreProducto=lector.nextLine(); System.out.println("Introduce la unidad de medida"); String unidades=lector.nextLine(); System.out.println("Introduce numero de productos"); int cantidad = lector.nextInt(); System.out.println("Introduce descripcion"); lector.nextLine(); String descripcion = lector.nextLine(); System.out.println("Introduce el precio de compra"); int precioCompra = lector.nextInt(); System.out.println("Introduce el precio de la venta"); int precioVenta = lector.nextInt(); producto[i]=new Productos(ID,nombreProducto,unidades,cantidad,descripcion,precioCompra,precioVenta); if(producto[i].getCantidad()<100) { System.out.println("La cantidad de productos es demasiado baja"); } System.out.println(); try{ @SuppressWarnings("resource") ObjectOutputStream ObjetoArchivo= new ObjectOutputStream(new FileOutputStream(name1)); ObjetoArchivo.writeObject(producto); } catch(Exception mono){ } } } else { try{ @SuppressWarnings("resource") ObjectInputStream ObjetoArchivo1=new ObjectInputStream(new FileInputStream(name1)); Productos[] PersonalRec=(Productos[])ObjetoArchivo1.readObject(); int aux=0; while(PersonalRec[aux]!=null){ producto[aux]=PersonalRec[aux]; aux++; num=aux; //Busca el archivo introducido y lo imprime en pantalla } } catch(Exception mono){ } } String name2="Venta"+cont3; File file1=new File(name2);//Esto hace que puedas crear un archivo nuevo cada corrida if(!file1.exists()){ try{ file1.createNewFile();//se crea el archivo con la condicion de no existe System.out.println(file1.getName()+" Se ha creado el archivo"); } catch(IOException ex){ ex.printStackTrace(); } } System.out.println("====================================="); System.out.println("Desea realizar alguna operacion\n1=si\n2=no"); int res1=lector.nextInt(); int cont=0,s=0; while(res1==1){ System.out.println("introduzca accion que desea realizar\n1=Ver inventario\n2=Buscar producto\n3=Ver archivo anterior\n4=Salir\n5=Cambiar producto" + "\n6=Generar una compra\n7=Agregar un elemento\n8=Eliminar producto\n9=Mostrar venta\n10=Comprar producto\n11=Calcular ganancias pasadas"); int op=lector.nextInt(); switch(op){ case 1: System.out.println("====================================="); try{ @SuppressWarnings("resource") ObjectInputStream ObjetoArchivo1=new ObjectInputStream(new FileInputStream(name1)); Productos[] PersonalRec=(Productos[])ObjetoArchivo1.readObject(); for(int i=0;i<num;i++){ System.out.println(PersonalRec[i]); System.out.println(); //lee los objetos guardados } } catch(Exception mono){ } System.out.println("====================================="); break; case 2: System.out.println("Introduce el ID del producto a buscar"); lector.nextLine(); System.out.println("====================================="); String ID1=lector.nextLine(); for(int i=0;i<num;i++){ if(ID1.equals(producto[i].getID())){ System.out.println(producto[i].toString()); //busca un objeto serializado con el ID del producto } } System.out.println("====================================="); break; case 4: res1=2; break; case 3: int con1=1; System.out.println("El nombre de los archivos son los siguientes:"); while(con1<cont3) { System.out.println("Venta"+con1); con1++; } System.out.println("introduce el nombre del archivo a buscar"); lector.nextLine(); String nombrearch=lector.nextLine(); System.out.println("====================================="); try{ @SuppressWarnings("resource") ObjectInputStream ObjetoArchivo1=new ObjectInputStream(new FileInputStream(nombrearch)); Venta[] PersonalRec=(Venta[])ObjetoArchivo1.readObject(); int aux=0; while(PersonalRec[aux]!=null){ System.out.println(PersonalRec[aux]); System.out.println(); aux++; //Busca el archivo introducido y lo imprime en pantalla } } catch(Exception mono){ } System.out.println("====================================="); break; case 5: System.out.println("Introduce el ID del producto a buscar"); lector.nextLine(); System.out.println("====================================="); String ID2=lector.nextLine(); for(int i=0;i<num;i++){ if(ID2.equals(producto[i].getID())){ System.out.println("Introduce el ID del producto"); lector.nextLine(); String ID = lector.nextLine(); System.out.println("Introduce nombre del producto"); String nombreProducto=lector.nextLine(); System.out.println("Introduce la unidad de medida"); String unidades=lector.nextLine(); System.out.println("Introduce numero de productos"); int cantidad = lector.nextInt(); System.out.println("Introduce descripcion"); lector.nextLine(); String descripcion = lector.nextLine(); System.out.println("Introduce el precio de compra"); int precioCompra = lector.nextInt(); System.out.println("Introduce el precio de la venta"); int precioVenta = lector.nextInt(); producto[i].setID(ID); producto[i].setNombreProducto(nombreProducto); producto[i].setUnidades(unidades); producto[i].setCantidad(cantidad); producto[i].setDescripcion(descripcion); producto[i].setPrecioCompra(precioCompra); producto[i].setPrecioVenta(precioVenta); System.out.println(); if(producto[i].getCantidad()<100) { System.out.println("La cantidad de productos es demasiado baja"); } try{ @SuppressWarnings("resource") ObjectOutputStream ObjetoArchivo= new ObjectOutputStream(new FileOutputStream(name1)); ObjetoArchivo.writeObject(producto); } catch(Exception mono){ } } } System.out.println("====================================="); break; case 6: int w=1,aviso=0; while(w!=0) { System.out.println("Introduce el ID del producto que desea comprar"); lector.nextLine(); String ID=lector.nextLine(); System.out.println("Introduce la cantidad de productos"); int cantidad=lector.nextInt(); for(int i=0;i<num;i++) { if(producto[i].getID().equals(ID)) { int o=producto[i].getCantidad()-cantidad; producto[i].setCantidad(o); int x,y,ganancia,IVA=0; x=cantidad*producto[i].getPrecioCompra(); y=cantidad*producto[i].getPrecioVenta(); ganancia=y-x; IVA=(ganancia*16)/100; if(venta[s]!=null) { s++; venta[s]=new Venta(ganancia); venta[s].setGanancia(ganancia); venta[s].setCantidadV(cantidad); venta[s].setNombreProductoV(producto[i].getNombreProducto()); venta[s].setIDV(producto[i].getID()); venta[s].setIVA(IVA); total=total+ganancia+IVA; venta[s].setTotal(total); venta[s].setFecha(fechaActual); } else { venta[s]=new Venta(ganancia); venta[s].setGanancia(ganancia); venta[s].setCantidadV(cantidad); venta[s].setNombreProductoV(producto[i].getNombreProducto()); venta[s].setIDV(producto[i].getID()); venta[s].setIVA(IVA); total=total+ganancia+IVA; venta[s].setTotal(total); venta[s].setFecha(fechaActual); } try{ @SuppressWarnings("resource") ObjectOutputStream ObjetoArchivo= new ObjectOutputStream(new FileOutputStream(name2)); ObjetoArchivo.writeObject(venta); } catch(Exception mono){ } try{ @SuppressWarnings("resource") ObjectOutputStream ObjetoArchivo= new ObjectOutputStream(new FileOutputStream(name1)); ObjetoArchivo.writeObject(producto); } catch(Exception mono){ } } if(producto[i].getCantidad()<100) { aviso++; } } if(aviso!=0) { System.out.println("La cantidad de productos es demasiado baja"); aviso=0; } System.out.println("Desea continuar?\n0=no\n1=si"); w=lector.nextInt(); } cont=1; break; case 7: num++; for(int i=num-1;i<num;i++){ System.out.println("Introduce el ID del producto"); lector.nextLine(); String ID = lector.nextLine(); System.out.println("Introduce nombre del producto"); String nombreProducto=lector.nextLine(); System.out.println("Introduce la unidad de medida"); String unidades=lector.nextLine(); System.out.println("Introduce numero de productos"); int cantidad = lector.nextInt(); System.out.println("Introduce descripcion"); lector.nextLine(); String descripcion = lector.nextLine(); System.out.println("Introduce el precio de compra"); int precioCompra = lector.nextInt(); System.out.println("Introduce el precio de la venta"); int precioVenta = lector.nextInt(); producto[i]=new Productos(ID,nombreProducto,unidades,cantidad,descripcion,precioCompra,precioVenta); System.out.println(); try{ @SuppressWarnings("resource") ObjectOutputStream ObjetoArchivo= new ObjectOutputStream(new FileOutputStream(name1)); ObjetoArchivo.writeObject(producto); } catch(Exception mono){ } if(producto[i].getCantidad()<100) { System.out.println("La cantidad de productos es demasiado baja"); } } break; case 8: System.out.println("Introduce el ID del elemento a eliminar"); lector.nextLine(); String ID3=lector.nextLine(); for(int i=0;i<num;i++){ if(ID3.equals(producto[i].getID())){ for(int j=i;j<num;j++) { if(j==num-1) { } else { producto[j]=producto[j+1]; } } } } num--; System.out.println("====================================="); try{ @SuppressWarnings("resource") ObjectOutputStream ObjetoArchivo= new ObjectOutputStream(new FileOutputStream(name1)); ObjetoArchivo.writeObject(producto); } catch(Exception mono){ } break; case 9: System.out.println("====================================="); if(cont==1) { try{ @SuppressWarnings("resource") ObjectInputStream ObjetoArchivo1=new ObjectInputStream(new FileInputStream(name2)); Venta[] PersonalRec=(Venta[])ObjetoArchivo1.readObject(); int aux=0; while(PersonalRec[aux]!=null){ System.out.println(PersonalRec[aux]); aux++; } System.out.println("El total de la ganancia es $"+total); } catch(Exception mono){ } System.out.println("====================================="); } else { System.out.println("No se ha regritrado ninguna venta"); System.out.println("====================================="); } break; case 10: System.out.println("Introduce el ID para comprar producto"); String ID5=lector.nextLine(); ID5=lector.nextLine(); System.out.println("Introduce la cantidad de producto a insertar"); int cantidad=lector.nextInt(); for(int i=0;i<num;i++) { if(producto[i].getID().equals(ID5)) { if((producto[i].getPrecioCompra()*cantidad)>total) { System.out.println("No tienes dinero suficiente"); } else { total=total-(producto[i].getPrecioCompra()*cantidad); producto[i].setCantidad(producto[i].getCantidad()+cantidad); System.out.println("La compra del producto se realizo"); } } } System.out.println("====================================="); break; case 11: int con=1,acum = 0; Venta[]ventas=new Venta[100]; System.out.println("El nombre de los archivos son los siguientes:"); while(con<cont3) { System.out.println("Venta"+con); con++; } System.out.println("introduce el numero del archivo de inicio"); lector.nextLine(); int nombrearch1=lector.nextInt(); System.out.println("====================================="); System.out.println("introduce el numero del archivo de final"); lector.nextLine(); int nombrearch2=lector.nextInt(); System.out.println("====================================="); while(nombrearch1<=nombrearch2) { try{ @SuppressWarnings("resource") ObjectInputStream ObjetoArchivo1=new ObjectInputStream(new FileInputStream("Venta"+nombrearch1)); Venta[] PersonalRec=(Venta[])ObjetoArchivo1.readObject(); int aux=0; while(PersonalRec[aux]!=null){ System.out.println(PersonalRec[aux]); ventas[aux]=PersonalRec[aux]; aux++; con=aux; } System.out.println("====================================="); } catch(Exception mono){ } acum=acum+ventas[con-1].getTotal(); nombrearch1++; } System.out.println("El total de ganancias de esa fecha es $"+acum); System.out.println("Menos el 16% de IVA perteneciente a hacienda es $"+(acum*16)/100); acum=acum-(acum*16)/100; System.out.println("El total libre de impuestos es $"+acum); System.out.println("====================================="); break; } } } }
package servlet; import java.io.IOException; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import agregadores.LojaProduto; import servicos.ServicoFachada; @WebServlet("/ServletLojaProduto") public class ServletLojaProduto extends HttpServlet { /* private static final long serialVersionUID = 1L; ServicoFachada servicoFachada = new ServicoFachada(); ArrayList<LojaProduto> ListLojaProduto = servicoFachada.buscarLojaProduto(); */ }
package utn.sau.hp.com.modelo; // Generated 04/12/2014 23:31:51 by Hibernate Tools 3.6.0 import java.util.HashSet; import java.util.Set; /** * Areas generated by hbm2java */ public class Areas implements java.io.Serializable { private Integer id; private Carreras carreras; private String areaDescripcion; private Set actividadeses = new HashSet(0); private Set competenciases = new HashSet(0); public Areas() { } public Areas(String areaDescripcion) { this.areaDescripcion = areaDescripcion; } public Areas(Carreras carreras, String areaDescripcion, Set actividadeses, Set competenciases) { this.carreras = carreras; this.areaDescripcion = areaDescripcion; this.actividadeses = actividadeses; this.competenciases = competenciases; } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public Carreras getCarreras() { return this.carreras; } public void setCarreras(Carreras carreras) { this.carreras = carreras; } public String getAreaDescripcion() { return this.areaDescripcion; } public void setAreaDescripcion(String areaDescripcion) { this.areaDescripcion = areaDescripcion; } public Set getActividadeses() { return this.actividadeses; } public void setActividadeses(Set actividadeses) { this.actividadeses = actividadeses; } public Set getCompetenciases() { return this.competenciases; } public void setCompetenciases(Set competenciases) { this.competenciases = competenciases; } }
package com.uchain.core.datastore; public class DataStoreConstant { public static final byte[] HeaderPrefix = new byte[] { (byte) StoreType.getStoreType(StoreType.Data), (byte) DataType.getDataType(DataType.BlockHeader) }; public static final byte[] TxPrefix = new byte[] { (byte) StoreType.getStoreType(StoreType.Data), (byte) DataType.getDataType(DataType.Transaction) }; public static final byte[] AccountPrefix = new byte[] { (byte) StoreType.getStoreType(StoreType.Data), (byte) DataType.getDataType(DataType.Account) }; public static final byte[] ContractPrefix = new byte[] { (byte) StoreType.getStoreType(StoreType.Data), (byte) DataType.getDataType(DataType.Contract) }; public static final byte[] CodePrefix = new byte[] { (byte) StoreType.getStoreType(StoreType.Data), (byte) DataType.getDataType(DataType.Code) }; public static final byte[] HeightToIdIndexPrefix = new byte[] { (byte) StoreType.getStoreType(StoreType.Index), (byte) IndexType.getIndexType(IndexType.BlockHeightToId) }; public static final byte[] NameToAccountIndexPrefix = new byte[] { (byte) StoreType.getStoreType(StoreType.Index), (byte) IndexType.getIndexType(IndexType.NameToAccount) }; public static final byte[] HeadBlockStatePrefix = new byte[] { (byte) StoreType.getStoreType(StoreType.Index), (byte) StateType.getStateType(StateType.HeadBlock) }; public static final byte[] BlockPrefix = new byte[]{(byte) StoreType.getStoreType(StoreType.Data), (byte) DataType.getDataType(DataType.Block)}; public static final byte[] ForkItemPrefix = new byte[] { (byte) StoreType.getStoreType(StoreType.Data), (byte) DataType.getDataType(DataType.ForkItem) }; public static final byte[] SwitchStatePrefix = new byte[] { (byte) StoreType.getStoreType(StoreType.Index), (byte) StateType.getStateType(StateType.SwitchState) }; }
/** * Instead of using implicit locking via the synchronized keyword the * Concurrency API supports various explicit locks specified by the Lock * interface. Locks support various methods for finer grained lock control * thus are more expressive than implicit monitors **/ public class Locks { /** * A lock is acquired via lock() and released via unlock(). It's * important to wrap your code into a try/finally block to ensure * unlocking in case of exceptions **/ //mutual exclusion lock that implements reentrant characteristics ReentrantLock lock = new ReentrantLock(); int count1 = 0; void increment() { lock.lock(); try { count1++; } finally { lock.unlock(); } } /** * Threads can call various methods for greater control over the resource **/ boolean locked = lock.isLocked(); boolean mine = lock.isHeldByCurrentThread(); //alternative to lock(), if true the lock was set by current thread. boolean lockAquired = lock.tryLock(); /** * ReadWriteLock specifies another type of lock maintaining a pair * of locks for read and write access * The same principle just with lock.readLock().* is used when reading. **/ ExecutorService executor = Executors.newFixedThreadPool(2); Map<String, String> map = new HashMap<>(); ReadWriteLock lock2 = new ReentrantReadWriteLock(); executor.submit(() -> { lock2.writeLock().lock(); try { TimeUnit.SECONDS.sleep(1); map.put("javel", "sedet"); } finally { lock2.writeLock().unlock(); } }); /** * StampedLock * StampedLock return a stamp represented by a long value. You can use * these stamps to either release a lock or to check if the lock is still * valid **/ StampedLock lock3 = new StampedLock(); executor.submit(() -> { long stamp = lock.writeLock(); try { TimeUnit.SECONDS.sleep(1); map.put("javel", "sedet"); } finally { lock.unlockWrite(stamp); } }); //A read lock can also be converted to a writeLock long stamp = lock.readLock(); stamp = lock.tryConvertToWriteLock(stamp); //the lock-change was successfull if(stamp != 0L) //TODO SEMAPHORES! /** * Bonus: * In addition to the normal synchronized method, * you can also use the keyword in a block statement. **/ int count = 0; void incrementSync() { synchronized (this) { count = count+1; } } }
package com.krish.array; import java.util.PriorityQueue; public class TopNValuesInArray { public static void main(String[] args) { int[] arr = { 6, 2, 1, 7, 9, 8, 3, 4, 5}; topN(arr, 3); } private static void topN(int[] arr, int n) { PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); if (n > arr.length) return; for (int i = 0; i < arr.length; i++) { if (pq.size() < n) { pq.offer(arr[i]); continue; } if (pq.peek() < arr[i]) { pq.poll(); pq.offer(arr[i]); } } System.out.println(pq); } }
package com.projectseyupo.receivers; import android.app.ActivityManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.facebook.react.HeadlessJsTaskService; import com.projectseyupo.MainActivity; import com.projectseyupo.services.ServiceLock; import java.util.List; public class Locking extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals("com.projectseyupo.JsStartService.LockDev")) { if(!isAppOnForeground(context)) { Intent i = new Intent(context, ServiceLock.class); context.startService(i); HeadlessJsTaskService.acquireWakeLockNow(context); } else { Intent i = new Intent(context, MainActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.addFlags (Intent.FLAG_ACTIVITY_SINGLE_TOP); i.putExtra("close_activity",true); context.startActivity(i); Intent intents = new Intent(context, ServiceLock.class); context.startService(intents); HeadlessJsTaskService.acquireWakeLockNow(context); } } } private boolean isAppOnForeground(Context context) { /** We need to check if app is in foreground otherwise the app will crash. http://stackoverflow.com/questions/8489993/check-android-application-is-in-foreground-or-not **/ ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses(); if (appProcesses == null) { return false; } final String packageName = context.getPackageName(); for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) { if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) { return true; } } return false; } }
package app.interfaces; import app.Dimension; import app.Goal; public class GoalCreator extends Interface { private final Dimension dimension; public GoalCreator(Dimension dimension) { this.dimension = dimension; continueInput = false; } @Override public boolean takeAction() { System.out.println("Enter your goal"); sc.nextLine(); String goal = sc.nextLine(); Goal goalObj = new Goal(goal); dimension.addGoal(goalObj); return false; } @Override public void displaySpecificMenuOptions() { } }
package dataMapper; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; import domain.Customer; import domain.DomainObject; import utils.DBConnection; import utils.IdentityMap; public class CustomerMapper extends DataMapper{ /** * function to insert record to table Customer * @param Customer obj * @return success or failed */ @Override public boolean insert(DomainObject obj) { Customer customer = (Customer)obj; String insertCustomer="INSERT INTO fuhnw47e9sr8fzla.Customer " + "(customerId, firstname, lastname, title, identityNumber, identityType, number, email)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?);"; int result = 0; try { Connection conn = DBConnection.getConnection(); PreparedStatement pStatement = (PreparedStatement) conn.prepareStatement(insertCustomer); pStatement.setInt(1, customer.getCustomerId()); pStatement.setString(2, customer.getFirstname()); pStatement.setString(3, customer.getLastname()); pStatement.setString(4, customer.getTitle()); pStatement.setString(5, customer.getIdentityNumber()); pStatement.setString(6, customer.getIdentityType()); pStatement.setString(7, customer.getNumber()); pStatement.setString(8, customer.getEmail()); result = pStatement.executeUpdate(); DBConnection.closePreparedStatement(pStatement); DBConnection.closeConnection(conn); } catch (Exception e) { e.printStackTrace(); } if (result == 0) return false; else return true; } /** * function to delete record by customerId from table Customer * @param Customer obj * @return success or failed */ @Override public boolean delete(DomainObject obj) { Customer customer = (Customer)obj; String deleteCustomerById = "DELETE FROM fuhnw47e9sr8fzla.Customer WHERE customerId = ?"; int result = 0; try { Connection conn = DBConnection.getConnection(); PreparedStatement pStatement = (PreparedStatement) conn.prepareStatement(deleteCustomerById); pStatement.setInt(1, customer.getCustomerId()); result = pStatement.executeUpdate(); DBConnection.closePreparedStatement(pStatement); DBConnection.closeConnection(conn); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if (result == 0) return false; else return true; } /** * function to update record by customerId in table Customer * @param Customer obj * @return success or failed */ @Override public boolean update (DomainObject obj) { Customer customer = (Customer)obj; String updateCustomerById = "UPDATE fuhnw47e9sr8fzla.Customer SET " + "firstname=?, lastname=?, title=?, identityNumber=?, identityType=?," + " number=?, email=? WHERE customerId=?"; int result = 0; try { Connection conn = DBConnection.getConnection(); PreparedStatement pStatement = (PreparedStatement) conn.prepareStatement(updateCustomerById); pStatement.setString(1, customer.getFirstname()); pStatement.setString(2, customer.getLastname()); pStatement.setString(3, customer.getTitle()); pStatement.setString(4, customer.getIdentityNumber()); pStatement.setString(5, customer.getIdentityType()); pStatement.setString(6, customer.getNumber()); pStatement.setString(7, customer.getEmail()); pStatement.setInt(8, customer.getCustomerId()); result = pStatement.executeUpdate(); DBConnection.closePreparedStatement(pStatement); DBConnection.closeConnection(conn); } catch (Exception e) { e.printStackTrace(); } if (result == 0) return false; else return true; } /** * function to find record by customerId from table Customer * @param Customer obj * @return list of Customer objects */ public List<Customer> findCustomerById(Customer customer){ String findCustomerById = "SELECT * from fuhnw47e9sr8fzla.Customer WHERE customerId = ?"; List<Customer> result = new ArrayList<Customer>(); try { Connection conn = DBConnection.getConnection(); PreparedStatement pStatement = (PreparedStatement) conn.prepareStatement(findCustomerById); pStatement.setInt(1, customer.getCustomerId()); ResultSet resultSet = pStatement.executeQuery(); while(resultSet.next()) { Customer c = new Customer(); //adapting IDENTITY MAP, get identityMap for Room. IdentityMap<Customer> identityMap = IdentityMap.getInstance(c); c.setCustomerId(resultSet.getInt(1)); c.setFirstname(resultSet.getString(2)); c.setLastname(resultSet.getString(3)); c.setTitle(resultSet.getString(4)); c.setIdentityNumber(resultSet.getString(5)); c.setIdentityType(resultSet.getString(6)); c.setNumber(resultSet.getString(7)); c.setEmail(resultSet.getString(8)); //put Room Object r in the identity map identityMap.put(c.getCustomerId(), c); result.add(c); } } catch (Exception e) { e.printStackTrace(); } return result; } /** * function to find record by email from table Customer * @param Customer obj * @return list of Customer objects */ public List<Customer> findCustomerByEmail(Customer customer){ String findCustomerById = "SELECT * from fuhnw47e9sr8fzla.Customer WHERE email = ?"; List<Customer> result = new ArrayList<Customer>(); try { Connection conn = DBConnection.getConnection(); PreparedStatement pStatement = (PreparedStatement) conn.prepareStatement(findCustomerById); pStatement.setString(1, customer.getEmail()); ResultSet resultSet = pStatement.executeQuery(); while(resultSet.next()) { Customer c = new Customer(); //adapting IDENTITY MAP, get identityMap for Customer. IdentityMap<Customer> identityMap = IdentityMap.getInstance(c); c.setCustomerId(resultSet.getInt(1)); c.setFirstname(resultSet.getString(2)); c.setLastname(resultSet.getString(3)); c.setTitle(resultSet.getString(4)); c.setIdentityNumber(resultSet.getString(5)); c.setIdentityType(resultSet.getString(6)); c.setNumber(resultSet.getString(7)); c.setEmail(resultSet.getString(8)); //put Room Object r in the identity map identityMap.put(c.getCustomerId(), c); result.add(c); } } catch (Exception e) { e.printStackTrace(); } return result; } }
package dakrory.a7med.cargomarine.CustomViews; import android.app.Activity; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.core.content.FileProvider; import androidx.recyclerview.widget.RecyclerView; import com.app.adprogressbarlib.AdCircleProgress; import com.squareup.picasso.Picasso; import java.io.File; import java.util.List; import dakrory.a7med.cargomarine.BuildConfig; import dakrory.a7med.cargomarine.Models.vehicalsDetails; import dakrory.a7med.cargomarine.R; import dakrory.a7med.cargomarine.ViewFullImage; import dakrory.a7med.cargomarine.ViewFullPdf; import dakrory.a7med.cargomarine.helpers.Constants; import dakrory.a7med.cargomarine.helpers.FilePath; public class vehicalPdfsAdapter extends RecyclerView.Adapter<vehicalPdfsAdapter.ViewHolder> { private List<vehicalsDetails.urlItem> listdata; private Activity activity; RecyclerView recyclerView; public vehicalPdfsAdapter(RecyclerView recyclerView, List<vehicalsDetails.urlItem> listdata, Activity activity) { this.listdata = listdata; this.activity = activity; this.recyclerView = recyclerView; } @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, @NonNull int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); View listItem = layoutInflater.inflate(R.layout.list_item_pdf, parent, false); ViewHolder viewHolder = new ViewHolder(listItem); return viewHolder; } @Override public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) { final vehicalsDetails.urlItem myImageData = listdata.get(position); if(listdata.get(position).getType()==vehicalsDetails.TYPE_FILE) { myImageData.getCallBackViewChanger().setViewToPercentage(holder.loader,holder.overlayView,holder.markView); if (listdata.get(position).getUrl() != null) { holder.nameFile.setText(listdata.get(position).getUrl()); } holder.relativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { holder.nameFile.setText(myImageData.getUrl()); Uri uri = Uri.parse(myImageData.getUrl()); Log.v("AhmedDakrory","CodeNew: "+myImageData.getUrl()); //String selectedFilePath = FilePath.getPath(activity, uri); final File pdfFile = new File(uri.getPath()); if (pdfFile.exists()) //Checking for the file is exist or not { Uri path = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".provider",pdfFile); viewPdf(path,activity); }else{ Log.v("AhmedDakrory","Non CodeNew: "+myImageData.getUrl()); } } }); }else { activity.runOnUiThread(new Runnable() { @Override public void run() { holder.nameFile.setText(listdata.get(position).getUrl()); //Picasso.get().load(Constants.ImageBaseUrl + listdata.get(position).getUrl()).placeholder(R.drawable.animation_loader).into(holder.imageView); holder.loader.setVisibility(View.GONE); holder.overlayView.setVisibility(View.GONE); holder.markView.setTextColor(activity.getResources().getColor(R.color.colorGreenSign)); } }); holder.relativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //action after load Log.v("AhmedDakrory","Code: "+myImageData.getType()); Intent openFullView =new Intent(activity, ViewFullPdf.class); openFullView.putExtra(Constants.ImageUrl_Type,myImageData.getType()); openFullView.putExtra(Constants.SET_MODE_INTENT,Constants.MODE_VIEW); openFullView.putExtra(Constants.ImageUrl_INTENT,Constants.PdfBaseUrl+myImageData.getUrl()+"&Pdf=1"); activity.startActivity(openFullView); } }); } } private void viewPdf(Uri file, final Activity activity) { Intent intent; intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(file, "application/pdf"); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); try { activity.startActivity(intent); } catch (ActivityNotFoundException e) { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle("No Application Found"); builder.setMessage("Download one from Android Market?"); builder.setPositiveButton("Yes, Please", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent marketIntent = new Intent(Intent.ACTION_VIEW); marketIntent.setData(Uri.parse("market://details?id=com.adobe.reader")); activity.startActivity(marketIntent); } }); builder.setNegativeButton("No, Thanks", null); builder.create().show(); } } @Override public int getItemCount() { return listdata.size(); } public static class ViewHolder extends RecyclerView.ViewHolder { public TextView markView; public TextView nameFile; public TextView overlayView; public RelativeLayout relativeLayout; public AdCircleProgress loader; public ViewHolder(View itemView) { super(itemView); this.markView = (TextView) itemView.findViewById(R.id.mark); this.nameFile = (TextView) itemView.findViewById(R.id.nameFile); this.loader = (AdCircleProgress) itemView.findViewById(R.id.donut_progress); this.overlayView=(TextView)itemView.findViewById(R.id.backgroundWhite); relativeLayout = (RelativeLayout)itemView.findViewById(R.id.relativeLayout); } } }
package com.transport.action; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.transport.constant.ActionConstant; import com.transport.constant.MapConstant; import com.transport.constant.MiscConstant; import com.transport.constant.ModuleConstant; import com.transport.constant.ParamConstant; import com.transport.form.MaintenanceInspectionFormBean; import com.transport.model.InspectionDetails; import com.transport.model.InspectionHeader; import com.transport.model.User; import com.transport.service.ServiceManager; import com.transport.service.ServiceManagerImpl; import com.transport.util.TransportUtils; /** * * @author edwarddavid * @since 21Mar2020 * DateUpdated: 09Aug2020 */ public class MaintenanceInspectionAction extends Action { private final static Logger logger = Logger.getLogger(MaintenanceInspectionAction.class); @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { MaintenanceInspectionFormBean formBean = (MaintenanceInspectionFormBean) form; String forwardAction = ActionConstant.NONE; String command = request.getParameter("command"); //session expired checking if (request.getSession().getAttribute(MiscConstant.USER_SESSION) == null) { forwardAction = ActionConstant.SHOW_AJAX_EXPIRED; } else { if (command!=null) { int module = ModuleConstant.MAINTENANCE_INSPECTION; if (command.equalsIgnoreCase(ParamConstant.ADD)) { //get fresh/updated list data from DB for click ADD and EDIT link formBean.populateDropdownList(request, false); formBean.populateInspectionList(request); formBean.setTransactionStatus(false); formBean.setTransactionMessage(MiscConstant.TRANS_MESSSAGE_RESET); forwardAction = ActionConstant.SHOW_AJAX_ADD; } else if (command.equalsIgnoreCase(ParamConstant.AJAX_EDIT)) { //fetch the data int id = Integer.parseInt(request.getParameter("id")); boolean isSummary = Boolean.parseBoolean(request.getParameter("isSummary")); formBean.setIsSummary(isSummary); InspectionHeader model = new InspectionHeader(); model.setId(id); HashMap<String,Object> dataMap = new HashMap<String, Object>(); dataMap.put(MapConstant.MODULE, module); dataMap.put(MapConstant.CLASS_DATA, model); dataMap.put(MapConstant.ACTION, ActionConstant.GET_DATA); ServiceManager service = new ServiceManagerImpl(); Map<String, Object> resultMap = service.executeRequest(dataMap); if (resultMap!=null && !resultMap.isEmpty()) { model = (InspectionHeader) resultMap.get(MapConstant.CLASS_DATA); formBean.populateFormBean(model); @SuppressWarnings("unchecked") List<InspectionDetails> detailsList = (List<InspectionDetails> )resultMap.get(MapConstant.CLASS_LIST); if (!isSummary) { formBean.populateDetailsFormBean(detailsList); } else { //filter the list with Repair and Replace status only List<InspectionDetails> filteredList = new ArrayList<>(); for (InspectionDetails item: detailsList) { if (item.getStatusId() == 1602 || item.getStatusId() == 1603) { filteredList.add(item); } } formBean.populateDetailsFormBean(filteredList); } formBean.populateCategoryList(); } //get fresh/updated list data from DB for click ADD and EDIT link formBean.populateDropdownList(request, true); formBean.setTransactionStatus(false); formBean.setTransactionMessage(MiscConstant.TRANS_MESSSAGE_RESET); forwardAction = ActionConstant.SHOW_AJAX_EDIT; } else if (command.equalsIgnoreCase(ParamConstant.AJAX_SAVE) || command.equalsIgnoreCase(ParamConstant.AJAX_UPDATE)) { User user = (User) request.getSession().getAttribute(MiscConstant.USER_SESSION); InspectionHeader model = formBean.populateInspectionHeader(); if (command.equalsIgnoreCase(ParamConstant.AJAX_SAVE)) { formBean.populateInspectionDetailsList(formBean.getInspectionId(),formBean.getInspectionStatusId(),formBean.getInspectionRemarks(), formBean.getPlanDate(), formBean.getActualDate(), Boolean.FALSE); } else { formBean.populateInspectionDetailsList(formBean.getInspectionId(),formBean.getInspectionStatusId(),formBean.getInspectionRemarks(), formBean.getPlanDate(), formBean.getActualDate(), Boolean.TRUE); } HashMap<String,Object> dataMap = new HashMap<String, Object>(); dataMap.put(MapConstant.MODULE, module); dataMap.put(MapConstant.CLASS_DATA, model); //Header dataMap.put(MapConstant.CLASS_LIST, formBean.getModelDetailsList()); //Details dataMap.put(MapConstant.USER_SESSION_DATA, user); if (command.equalsIgnoreCase(ParamConstant.AJAX_SAVE)) { dataMap.put(MapConstant.ACTION, ActionConstant.SAVE); } else { dataMap.put(MapConstant.ACTION, ActionConstant.UPDATE); } ServiceManager service = new ServiceManagerImpl(); Map<String, Object> resultMap = service.executeRequest(dataMap); boolean tranctionStatus = false; if (resultMap!=null && !resultMap.isEmpty()) { //check resultmap action status tranctionStatus = (boolean) resultMap.get(MapConstant.TRANSACTION_STATUS); @SuppressWarnings("unchecked") List<InspectionDetails> detailsList = (List<InspectionDetails>)resultMap.get(MapConstant.CLASS_LIST); if (command.equalsIgnoreCase(ParamConstant.AJAX_SAVE)) { formBean.populateDetailsFormBean(detailsList); } else { if (!formBean.getIsSummary()) { formBean.populateDetailsFormBean(detailsList); } else { //Edit Summary Update dataMap.clear(); dataMap = new HashMap<String, Object>(); dataMap.put(MapConstant.MODULE, module); dataMap.put(MapConstant.CLASS_DATA, model); dataMap.put(MapConstant.ACTION, ActionConstant.GET_DATA); resultMap.clear(); resultMap = service.executeRequest(dataMap); if (resultMap!=null && !resultMap.isEmpty()) { @SuppressWarnings("unchecked") List<InspectionDetails> freshDetailsList = (List<InspectionDetails> )resultMap.get(MapConstant.CLASS_LIST); //filter the list with Repair and Replace status only List<InspectionDetails> filteredList = new ArrayList<>(); for (InspectionDetails item: freshDetailsList) { if (item.getStatusId() == 1602 || item.getStatusId() == 1603) { filteredList.add(item); } } formBean.populateDetailsFormBean(filteredList); } } } formBean.setTransactionStatus(tranctionStatus); //get the dropdown list from session boolean isEdit = (command.equalsIgnoreCase(ParamConstant.AJAX_UPDATE)? true: false); formBean.populateDropdownListFromSession(request, isEdit); if (tranctionStatus) { //show success page and add confirmation message if (command.equalsIgnoreCase(ParamConstant.AJAX_SAVE)) { formBean.setTransactionMessage(MiscConstant.TRANS_MESSSAGE_SAVED); TransportUtils.writeLogInfo(logger, MiscConstant.TRANS_MESSSAGE_SAVED+" - "+module); }else { formBean.setTransactionMessage(MiscConstant.TRANS_MESSSAGE_UPDATED); TransportUtils.writeLogInfo(logger, MiscConstant.TRANS_MESSSAGE_UPDATED+" - "+module);; } forwardAction = ActionConstant.AJAX_SUCCESS; } else { formBean.setTransactionMessage(MiscConstant.TRANS_MESSSAGE_ERROR); TransportUtils.writeLogInfo(logger, MiscConstant.TRANS_MESSSAGE_ERROR+" - "+module); forwardAction = ActionConstant.AJAX_FAILED; } } } else if (command.equalsIgnoreCase(ParamConstant.AJAX_DELETE)) { //fetch the data int id = Integer.parseInt(request.getParameter("id")); User user = (User) request.getSession().getAttribute(MiscConstant.USER_SESSION); InspectionHeader model = new InspectionHeader(); model.setId(id); HashMap<String,Object> dataMap = new HashMap<String, Object>(); dataMap.put(MapConstant.MODULE, module); dataMap.put(MapConstant.CLASS_DATA, model); dataMap.put(MapConstant.ACTION, ActionConstant.DELETE); dataMap.put(MapConstant.USER_SESSION_DATA, user); ServiceManager service = new ServiceManagerImpl(); Map<String, Object> resultMap = service.executeRequest(dataMap); if (resultMap!=null && !resultMap.isEmpty()) { //check resultmap action status boolean tranctionStatus = (boolean) resultMap.get(MapConstant.TRANSACTION_STATUS); formBean.setTransactionStatus(tranctionStatus); // formBean.populateCriteriaDropdownList(request); if (tranctionStatus) { //show success page //add confirmation message formBean.setTransactionMessage(MiscConstant.TRANS_MESSSAGE_DELETED); //logger.info(MiscConstant.TRANS_MESSSAGE_DELETED); TransportUtils.writeLogInfo(logger, MiscConstant.TRANS_MESSSAGE_DELETED+" - "+module); forwardAction = ActionConstant.AJAX_SUCCESS; } else { formBean.setTransactionMessage(MiscConstant.TRANS_MESSSAGE_ERROR); //logger.info(MiscConstant.TRANS_MESSSAGE_ERROR); TransportUtils.writeLogInfo(logger, MiscConstant.TRANS_MESSSAGE_ERROR+" - "+module); forwardAction = ActionConstant.AJAX_FAILED; } } } else if (command.equalsIgnoreCase(ParamConstant.AJAX_SEARCH)) { //get all the records from DB int page = 1; if(request.getParameter("page") != null) { page = Integer.parseInt(request.getParameter("page")); } int offset = (page-1) * MiscConstant.RECORDS_PER_PAGE; String category = null; if(request.getParameter("category") != null) { category=(String) request.getParameter("category"); formBean.setCategory(category); if (category.equals("filter")) { category = ActionConstant.SEARCHBY; } else { category = ActionConstant.SEARCHALL; } } String searchValue = formBean.getSearchValue(); HashMap<String,Object> dataMap = new HashMap<String, Object>(); dataMap.put(MapConstant.SEARCH_VALUE, searchValue); dataMap.put(MapConstant.MODULE, module); dataMap.put(MapConstant.ACTION, category); dataMap.put(MapConstant.PAGINATION_LIMIT, MiscConstant.RECORDS_PER_PAGE); dataMap.put(MapConstant.PAGINATION_OFFSET, offset); ServiceManager service = new ServiceManagerImpl(); Map<String, Object> resultMap = service.executeRequest(dataMap); if (resultMap!=null && !resultMap.isEmpty()) { @SuppressWarnings("unchecked") List<InspectionHeader> qryList = (List<InspectionHeader>) resultMap.get(MapConstant.CLASS_LIST); formBean.setModelList(qryList); int totalNoOfRecords = (int) resultMap.get(MapConstant.PAGINATION_TOTALRECORDS); int noOfPages = (int) Math.ceil(totalNoOfRecords * 1.0 / MiscConstant.RECORDS_PER_PAGE); formBean.setNoOfPages(noOfPages); formBean.setCurrentPage(page); } else { formBean.setModelList(null); formBean.setNoOfPages(0); formBean.setCurrentPage(0); } forwardAction = ActionConstant.SHOW_AJAX_TABLE; } else if (command.equalsIgnoreCase(ParamConstant.AJAX_VIEW)) { // fetch the data int id = Integer.parseInt(request.getParameter("id")); boolean isSummary = Boolean.valueOf(request.getParameter("isSummary")); InspectionHeader model = new InspectionHeader(); model.setId(id); HashMap<String, Object> dataMap = new HashMap<String, Object>(); dataMap.put(MapConstant.MODULE, module); dataMap.put(MapConstant.CLASS_DATA, model); dataMap.put(MapConstant.ACTION, ActionConstant.GET_DATA); ServiceManager service = new ServiceManagerImpl(); Map<String, Object> resultMap = service.executeRequest(dataMap); if (resultMap != null && !resultMap.isEmpty()) { model = (InspectionHeader) resultMap.get(MapConstant.CLASS_DATA); //generate report dataMap.clear();; resultMap.clear(); String path = TransportUtils.getReportPath(request); dataMap.put("isSummary", isSummary); dataMap.put(MapConstant.CLASS_DATA, model); dataMap.put(MapConstant.REPORT_LOCALPATH, path); dataMap.put(MapConstant.MODULE, module); dataMap.put(MapConstant.ACTION, ActionConstant.GENERATE_REPORT); if (isSummary) { dataMap.put(MapConstant.RPT_TITLE, MiscConstant.RPT_MAINTENANCE_INSPECTION_SUMMARY_TITLE); dataMap.put(MapConstant.RPT_JASPER, MiscConstant.RPT_MAINTENANCE_INSPECTION_SUMMARY_REPORT); dataMap.put(MapConstant.RPT_PDF, MiscConstant.PDF_MAINTENANCE_INSPECTION_SUMMARY_REPORT); } else { dataMap.put(MapConstant.RPT_TITLE, MiscConstant.RPT_MAINTENANCE_INSPECTION_TITLE); dataMap.put(MapConstant.RPT_JASPER, MiscConstant.RPT_MAINTENANCE_INSPECTION_REPORT); dataMap.put(MapConstant.RPT_PDF, MiscConstant.PDF_MAINTENANCE_INSPECTION_REPORT); } dataMap.put("ChkNo", TransportUtils.getResourcesPath(request) + File.separator + "chkNo.png"); dataMap.put("ChkYes", TransportUtils.getResourcesPath(request) + File.separator + "chkYes.png"); resultMap = service.executeRequest(dataMap); boolean isReportGenerated = (boolean) resultMap.get(MapConstant.BOOLEAN_DATA); if (isReportGenerated) { if (isSummary) { response.getWriter().println(MiscConstant.PDF_MAINTENANCE_INSPECTION_SUMMARY_REPORT); } else { response.getWriter().println(MiscConstant.PDF_MAINTENANCE_INSPECTION_REPORT); } TransportUtils.writeLogInfo(logger, MiscConstant.RPT_MESSSAGE_GENERATED_SUCCESS + "-" + module); } else { //need to add message here if report generation failed, make the message dynamic TransportUtils.writeLogInfo(logger, MiscConstant.RPT_MESSSAGE_GENERATED_FAILED + "-" + module); } } } } else { //show main screen forwardAction = ActionConstant.SHOW_AJAX_MAIN; } } return mapping.findForward(forwardAction); } }
package com.github.xiaomi007.annotations.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * //TODO: Javadoc on com.github.xiaomi007.annotations.annotations.Table * * @author Damien * @version //TODO version * @since 2016-11-01 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Table { String table(); }
package abstractInterface; /** * 简述: * * @author WangLipeng 1243027794@qq.com * @version 1.0 * @since 2020/1/13 11:12 */ public interface TestInterface { public static final Integer a =1; default void print(){ System.out.println(); } }
package za.co.openwindow.ninemensmorris.game; /** * Created by student on 2017/10/17. */ public enum Token { PLAYER_1, PLAYER_2, NO_PLAYER, OFFBOARD; }
/* MinMaxIntPair -- a class within the Cellular Automaton Explorer. Copyright (C) 2006 David B. Bahr (http://academic.regis.edu/dbahr/) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package cellularAutomata.util; /** * Stores two integers, a minimum and a maximum. * * @author David Bahr */ public class MinMaxIntPair { public int min = 0; public int max = 0; /** * Create a pair of numbers for a minimum and a maximum. * * @param minimum The minimum. * @param maximum The maximum. */ public MinMaxIntPair(int minimum, int maximum) { min = minimum; max = maximum; } }
// // Decompiled by Procyon v0.5.36 // package com.davivienda.sara.tablas.zona.servicio; import com.davivienda.sara.base.exception.EntityServicioExcepcion; import javax.persistence.EntityManager; import com.davivienda.sara.entitys.Zona; import com.davivienda.sara.base.BaseEntityServicio; public class ZonaServicio extends BaseEntityServicio<Zona> { public ZonaServicio(final EntityManager em) { super(em, Zona.class); } @Override public Zona actualizar(final Zona objetoModificado) throws EntityServicioExcepcion { Zona objetoActual = super.buscar(objetoModificado.getIdZona()); if (objetoActual == null) { super.adicionar(objetoModificado); objetoActual = super.buscar(objetoModificado.getIdZona()); } else { objetoActual.actualizarEntity(objetoModificado); objetoActual = super.actualizar(objetoActual); } return objetoActual; } @Override public void borrar(final Zona entity) throws EntityServicioExcepcion { final Zona objetoActual = super.buscar(entity.getIdZona()); super.borrar(objetoActual); } }
package DesignPatterns.Mediator; import DesignPatternCodeGenerator.CodeGenerator; import org.eclipse.jdt.core.dom.*; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; public class MediatorClass extends CodeGenerator { String mediatorInterface, colleagueInterface, colleague1Class, colleague2Class; public MediatorClass(String filename, String mediatorInterface, String colleagueInterface, String colleague1Class, String colleague2Class) { super(filename); this.mediatorInterface = mediatorInterface; this.colleagueInterface = colleagueInterface; this.colleague1Class = colleague1Class; this.colleague2Class = colleague2Class; } public Document buildCode() throws BadLocationException { this.createTypeDeclaration(this.fileName, false, CodeGenerator.publicKeyword, false, false, null, this.mediatorInterface); // fields FieldDeclaration colleague1 = this.createFieldDeclaration("colleague1", this.createSimpleType(this.colleagueInterface), CodeGenerator.privateKeyword, false); FieldDeclaration colleague2 = this.createFieldDeclaration("colleague2", this.createSimpleType(this.colleagueInterface), CodeGenerator.privateKeyword, false); this.classDeclaration.bodyDeclarations().add(colleague1); this.classDeclaration.bodyDeclarations().add(colleague2); // constructor MethodDeclaration constructor = this.createConstructor(this.fileName, CodeGenerator.publicKeyword); Block constructorBlock = this.createBlock(); FieldAccess colleague1This = this.createFieldAccessExpression( this.abstractSyntaxTree.newSimpleName("colleague1") ); ClassInstanceCreation colleague1Instance = this.createInstanceCreationExpression( this.createSimpleType(this.colleague1Class) ); Assignment colleague1Assignment = this.createAssignmentExpression(colleague1This, colleague1Instance); FieldAccess colleague2This = this.createFieldAccessExpression( this.abstractSyntaxTree.newSimpleName("colleague2") ); ClassInstanceCreation colleague2Instance = this.createInstanceCreationExpression( this.createSimpleType(this.colleague2Class) ); Assignment colleague2Assignment = this.createAssignmentExpression(colleague2This, colleague2Instance); constructorBlock.statements().add(this.abstractSyntaxTree.newExpressionStatement(colleague1Assignment)); constructorBlock.statements().add(this.abstractSyntaxTree.newExpressionStatement(colleague2Assignment)); constructor.setBody(constructorBlock); // overridden method MethodDeclaration sendMethod = this.declareMethod("send", this.createPrimitiveType(CodeGenerator.voidType), CodeGenerator.publicKeyword, false, false); SingleVariableDeclaration messageParameter = this.createSingleVariableDeclaration("message", this.createSimpleType("String")); SingleVariableDeclaration colleagueParameter = this.createSingleVariableDeclaration("colleague", this.createSimpleType(this.colleagueInterface)); sendMethod.parameters().add(messageParameter); sendMethod.parameters().add(colleagueParameter); Block sendMethodBlock = this.createBlock(); StringLiteral printValue = this.abstractSyntaxTree.newStringLiteral(); printValue.setLiteralValue("Mediator : Mediating the interaction"); Statement printStatement = this.createPrintStatement(printValue); sendMethodBlock.statements().add(printStatement); FieldAccess colleague1ThisAgain = this.createFieldAccessExpression( this.abstractSyntaxTree.newSimpleName("colleague1") ); InfixExpression infixExpression1 = this.createInfixExpression( this.abstractSyntaxTree.newSimpleName("colleague"), colleague1ThisAgain, CodeGenerator.equalsOperator ); MethodInvocation receive1 = this.createMethodInvocation("receive", this.abstractSyntaxTree.newSimpleName("colleague1")); receive1.arguments().add(this.abstractSyntaxTree.newSimpleName("message")); IfStatement ifStatement1 = this.createIfStatement( infixExpression1, this.abstractSyntaxTree.newExpressionStatement(receive1), null); sendMethodBlock.statements().add(ifStatement1); FieldAccess colleague2ThisAgain = this.createFieldAccessExpression( this.abstractSyntaxTree.newSimpleName("colleague2") ); InfixExpression infixExpression2 = this.createInfixExpression( this.abstractSyntaxTree.newSimpleName("colleague"), colleague2ThisAgain, CodeGenerator.equalsOperator ); MethodInvocation receive2 = this.createMethodInvocation("receive", this.abstractSyntaxTree.newSimpleName("colleague2")); receive2.arguments().add(this.abstractSyntaxTree.newSimpleName("message")); IfStatement ifStatement2 = this.createIfStatement( infixExpression2, this.abstractSyntaxTree.newExpressionStatement(receive2), null); sendMethodBlock.statements().add(ifStatement2); sendMethod.setBody(sendMethodBlock); // add methods to class this.classDeclaration.bodyDeclarations().add(constructor); this.classDeclaration.bodyDeclarations().add(sendMethod); // add class to CU this.compilationUnit.types().add(this.classDeclaration); // apply edits to the document this.applyEdits();; // return document return this.document; } }
package be.openclinic.finance; import be.openclinic.common.OC_Object; import be.mxs.common.util.db.MedwanQuery; import be.mxs.common.util.system.Debug; import be.mxs.common.util.system.ScreenHelper; import java.util.Date; import java.util.Vector; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; public class InsurarCredit extends OC_Object { private Date date; private String invoiceUid; private double amount; private String type; private String comment; private String insurarUid; private String patientName; //--- GETTERS && SETTERS ---------------------------------------------------------------------- public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getInvoiceUid() { return invoiceUid; } public void setInvoiceUid(String invoiceUid) { this.invoiceUid = invoiceUid; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getInsurarUid() { return insurarUid; } public void setInsurarUid(String insurarUid) { this.insurarUid = insurarUid; } public String getPatientName() { return patientName; } public void setPatientName(String patientName) { this.patientName = patientName; } //--- GET ------------------------------------------------------------------------------------- public static InsurarCredit get(String uid){ InsurarCredit insurarcredit = new InsurarCredit(); if(uid!=null && uid.length()>0){ String [] ids = uid.split("\\."); if (ids.length==2){ PreparedStatement ps = null; ResultSet rs = null; Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection(); try{ String sSelect = "SELECT * FROM OC_INSURARCREDITS WHERE OC_INSURARCREDIT_SERVERID = ? AND OC_INSURARCREDIT_OBJECTID = ?"; ps = oc_conn.prepareStatement(sSelect); ps.setInt(1,Integer.parseInt(ids[0])); ps.setInt(2,Integer.parseInt(ids[1])); rs = ps.executeQuery(); if(rs.next()){ insurarcredit.setUid(uid); insurarcredit.setDate(rs.getTimestamp("OC_INSURARCREDIT_DATE")); insurarcredit.setInvoiceUid(rs.getString("OC_INSURARCREDIT_INVOICEUID")); insurarcredit.setAmount(rs.getDouble("OC_INSURARCREDIT_AMOUNT")); insurarcredit.setType(rs.getString("OC_INSURARCREDIT_TYPE")); insurarcredit.setComment(rs.getString("OC_INSURARCREDIT_COMMENT")); insurarcredit.setInsurarUid(rs.getString("OC_INSURARCREDIT_INSURARUID")); insurarcredit.setCreateDateTime(rs.getTimestamp("OC_INSURARCREDIT_CREATETIME")); insurarcredit.setUpdateDateTime(rs.getTimestamp("OC_INSURARCREDIT_UPDATETIME")); insurarcredit.setUpdateUser(rs.getString("OC_INSURARCREDIT_UPDATEUID")); insurarcredit.setVersion(rs.getInt("OC_INSURARCREDIT_VERSION")); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); oc_conn.close(); } catch(Exception e){ e.printStackTrace(); } } } } return insurarcredit; } public boolean store(int userId){ boolean bStored = true; PreparedStatement ps = null; ResultSet rs = null; String[] ids; boolean recordExists = false; String sQuery = ""; Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection(); // get ids if object does not have any if(this.getUid()==null || this.getUid().length()==0){ ids = new String[]{ MedwanQuery.getInstance().getConfigString("serverId"), MedwanQuery.getInstance().getOpenclinicCounter("OC_INSURARCREDITS")+"" }; this.setUid(ids[0]+"."+ids[1]); } else{ ids = this.getUid().split("\\."); // check existence when object allready has ids try{ sQuery = "SELECT * FROM OC_INSURARCREDITS WHERE OC_INSURARCREDIT_SERVERID = ? AND OC_INSURARCREDIT_OBJECTID = ?"; ps = oc_conn.prepareStatement(sQuery); ps.setInt(1,Integer.parseInt(ids[0])); ps.setInt(2,Integer.parseInt(ids[1])); rs = ps.executeQuery(); if(rs.next()) recordExists = true; } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); } catch(Exception e){ e.printStackTrace(); } } } //*** SAVE OBJECT *** try{ if(recordExists){ //*** UPDATE *** sQuery = "UPDATE OC_INSURARCREDITS SET"+ " OC_INSURARCREDIT_DATE = ?," + " OC_INSURARCREDIT_INVOICEUID = ?," + " OC_INSURARCREDIT_AMOUNT = ?," + " OC_INSURARCREDIT_TYPE = ?," + " OC_INSURARCREDIT_COMMENT = ?," + " OC_INSURARCREDIT_UPDATETIME = ?," + " OC_INSURARCREDIT_UPDATEUID = ?," + " OC_INSURARCREDIT_INSURARUID = ?," + " OC_INSURARCREDIT_VERSION = OC_INSURARCREDIT_VERSION+1" + " WHERE OC_INSURARCREDIT_SERVERID = ? AND OC_INSURARCREDIT_OBJECTID = ?"; ps = oc_conn.prepareStatement(sQuery); ps.setDate(1,new java.sql.Date(this.getDate().getTime())); Debug.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@"+this.getInvoiceUid()); ps.setString(2,this.getInvoiceUid()); ps.setDouble(3,this.getAmount()); ps.setString(4,this.getType()); ps.setString(5,this.getComment()); ps.setDate(6,new java.sql.Date(new java.util.Date().getTime())); // now ps.setInt(7,userId); ps.setString(8,this.getInsurarUid()); ps.setInt(9,Integer.parseInt(ids[0])); ps.setInt(10,Integer.parseInt(ids[1])); ps.execute(); ps.close(); } else{ //*** INSERT *** sQuery = "INSERT INTO OC_INSURARCREDITS("+ " OC_INSURARCREDIT_SERVERID,"+ " OC_INSURARCREDIT_OBJECTID,"+ " OC_INSURARCREDIT_DATE," + " OC_INSURARCREDIT_INVOICEUID," + " OC_INSURARCREDIT_AMOUNT," + " OC_INSURARCREDIT_TYPE," + " OC_INSURARCREDIT_COMMENT," + " OC_INSURARCREDIT_CREATETIME," + " OC_INSURARCREDIT_UPDATETIME," + " OC_INSURARCREDIT_UPDATEUID," + " OC_INSURARCREDIT_VERSION," + " OC_INSURARCREDIT_INSURARUID" + " )"+ " VALUES(?,?,?,?,?,?,?,?,?,?,1,?)"; ps = oc_conn.prepareStatement(sQuery); ps.setInt(1,Integer.parseInt(ids[0])); ps.setInt(2,Integer.parseInt(ids[1])); ps.setDate(3,new java.sql.Date(this.getDate().getTime())); ps.setString(4,this.getInvoiceUid()); ps.setDouble(5,this.getAmount()); ps.setString(6,this.getType()); ps.setString(7,this.getComment()); ps.setDate(8,new java.sql.Date(new java.util.Date().getTime())); // now ps.setDate(9,new java.sql.Date(new java.util.Date().getTime())); // now ps.setInt(10,userId); ps.setString(11,this.getInsurarUid()); ps.execute(); ps.close(); } //*** update invoice data if an invoice is selected for the this credit *** // (credits without an invoice can be attached to an invoice later)) if(this.getInvoiceUid().length() > 0){ InsurarInvoice invoice = InsurarInvoice.get(this.getInvoiceUid()); invoice.setBalance(invoice.getBalance()-this.getAmount()); invoice.store(); } } catch(Exception e){ e.printStackTrace(); bStored = false; Debug.println("OpenClinic => Debet.java => store => "+e.getMessage()+" = "+sQuery); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); oc_conn.close(); } catch(Exception e){ e.printStackTrace(); } } return bStored; } public static Vector getInsurarCreditsViaInvoiceUID(String sInvoiceUid){ String sSelect = ""; PreparedStatement ps = null; ResultSet rs = null; Vector vCredits = new Vector(); Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection(); try{ sSelect = "SELECT * FROM OC_INSURARCREDITS WHERE OC_INSURARCREDIT_INVOICEUID = ?"; ps = oc_conn.prepareStatement(sSelect); ps.setString(1,sInvoiceUid); rs = ps.executeQuery(); while (rs.next()){ vCredits.add(rs.getInt("OC_INSURARCREDIT_SERVERID")+"."+rs.getInt("OC_INSURARCREDIT_OBJECTID")); } } catch(Exception e){ e.printStackTrace(); Debug.println("OpenClinic => InsurarCredit.java => getInsurarCreditsViaInvoiceUID => "+e.getMessage()+" = "+sSelect); } finally{ try{ if(rs!=null)rs.close(); if(ps!=null)ps.close(); oc_conn.close(); } catch(Exception e){ e.printStackTrace(); } } return vCredits; } //--- GET UNASSIGNED INSURAR CREDITS ---------------------------------------------------------- public static Vector getUnassignedInsurarCredits(String sInsurarUid){ String sSelect = ""; PreparedStatement ps = null; ResultSet rs = null; Vector vUnassignedCredits = new Vector(); Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection(); try{ sSelect = "SELECT * FROM OC_INSURARCREDITS"+ " WHERE OC_INSURARCREDIT_INSURARUID = ?"+ " AND (OC_INSURARCREDIT_INVOICEUID IS NULL OR OC_INSURARCREDIT_INVOICEUID='')"; ps = oc_conn.prepareStatement(sSelect); ps.setString(1,sInsurarUid); rs = ps.executeQuery(); while (rs.next()){ vUnassignedCredits.add(rs.getInt("OC_INSURARCREDIT_SERVERID")+"."+rs.getInt("OC_INSURARCREDIT_OBJECTID")); } } catch(Exception e){ e.printStackTrace(); Debug.println("OpenClinic => InsurarCredit.java => getUnassignedInsurarCredits => "+e.getMessage()+" = "+sSelect); } finally{ try{ if(rs!=null)rs.close(); if(ps!=null)ps.close(); oc_conn.close(); } catch(Exception e){ e.printStackTrace(); } } return vUnassignedCredits; } public static Vector getInsurarCredits(String sInsurarUid, String sDateBegin, String sDateEnd, String sAmountMin, String sAmountMax){ String sSelect = ""; PreparedStatement ps = null; ResultSet rs = null; Vector vUnassignedDebets = new Vector(); Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection(); try{ sSelect = "SELECT * FROM OC_INSURARCREDITS WHERE OC_INSURARCREDIT_INSURARUID = ? "; if ((sDateBegin.length()>0)&&(sDateEnd.length()>0)){ sSelect +=" AND OC_INSURARCREDIT_DATE BETWEEN ? AND ? "; } else if (sDateBegin.length()>0){ sSelect +=" AND OC_INSURARCREDIT_DATE >= ? "; } else if (sDateEnd.length()>0){ sSelect +=" AND OC_INSURARCREDIT_DATE <= ? "; } if ((sAmountMin.length()>0)&&(sAmountMax.length()>0)){ sSelect +=" AND OC_INSURARCREDIT_AMOUNT > ? AND OC_INSURARCREDIT_AMOUNT < ? "; } else if (sAmountMin.length()>0){ sSelect +=" AND OC_INSURARCREDIT_AMOUNT > ? "; } else if (sAmountMax.length()>0){ sSelect +=" AND OC_INSURARCREDIT_AMOUNT < ? "; } ps = oc_conn.prepareStatement(sSelect); ps.setString(1,sInsurarUid); int iIndex = 2; if ((sDateBegin.length()>0)&&(sDateEnd.length()>0)){ ps.setDate(iIndex++, ScreenHelper.getSQLDate(sDateBegin)); ps.setDate(iIndex++, ScreenHelper.getSQLDate(ScreenHelper.getDateAdd(sDateEnd,"1"))); } else if (sDateBegin.length()>0){ ps.setDate(iIndex++,ScreenHelper.getSQLDate(sDateBegin)); } else if (sDateEnd.length()>0){ ps.setDate(iIndex++,ScreenHelper.getSQLDate(sDateEnd)); } if ((sAmountMin.length()>0)&&(sAmountMax.length()>0)){ ps.setDouble(iIndex++,Double.parseDouble(sAmountMin)); ps.setDouble(iIndex++,Double.parseDouble(sAmountMax)); } else if (sAmountMin.length()>0){ ps.setDouble(iIndex++,Double.parseDouble(sAmountMin)); } else if (sAmountMax.length()>0){ ps.setDouble(iIndex++,Double.parseDouble(sAmountMax)); } rs = ps.executeQuery(); while (rs.next()){ vUnassignedDebets.add(rs.getInt("OC_INSURARCREDIT_SERVERID")+"."+rs.getInt("OC_INSURARCREDIT_OBJECTID")); } } catch(Exception e){ e.printStackTrace(); Debug.println("OpenClinic => InsurarCredit.java => getInsurarCredits => "+e.getMessage()+" = "+sSelect); } finally{ try{ if(rs!=null)rs.close(); if(ps!=null)ps.close(); oc_conn.close(); } catch(Exception e){ e.printStackTrace(); } } return vUnassignedDebets; } }
package com.pointwest.training.main; import java.util.List; import com.pointwest.training.bean.AnimalBean; import com.pointwest.training.manager.AnimalShelterMgr; import com.pointwest.training.ui.HomePageUI; public class AnimalShelterMain { public static void main(String[] args) { // TODO Auto-generated method stub HomePageUI homePage = new HomePageUI(); AnimalShelterMgr aniManager = new AnimalShelterMgr(); boolean isExiting = false; int chooseSpecies = 0; String speciesName = "Animal"; String animalName; String animalGender; int animalAge; boolean isEmpty=true; boolean isFull=false; //main program loop do { isEmpty = aniManager.checkifEmpty(); homePage.displayMainMenu(isEmpty, isFull); int mainSelect =homePage.menuChoice(); switch (mainSelect) { case 1: homePage.displayAddAnimalSpeciesSelectMenu(); chooseSpecies = homePage.menuChoice(); switch (chooseSpecies) { case 1: speciesName = "Cat"; animalName = homePage.collectAddAnimalNameUI(speciesName); animalAge = homePage.collectAddAnimalAgeUI(speciesName); animalGender = homePage.collectAddAnimalGenderUI(speciesName); if (aniManager.addAnimalManager(speciesName, animalName, animalAge, animalGender)==false) { homePage.thereWasAProblem(); break; } homePage.animalAddedAdvisory(); break; case 2: speciesName = "Dog"; animalName = homePage.collectAddAnimalNameUI(speciesName); animalAge = homePage.collectAddAnimalAgeUI(speciesName); animalGender = homePage.collectAddAnimalGenderUI(speciesName); if (aniManager.addAnimalManager(speciesName, animalName, animalAge, animalGender)==false) { homePage.thereWasAProblem(); break; } homePage.animalAddedAdvisory(); break; case 3: speciesName = "Parrot"; animalName = homePage.collectAddAnimalNameUI(speciesName); animalAge = homePage.collectAddAnimalAgeUI(speciesName); animalGender = homePage.collectAddAnimalGenderUI(speciesName); if (aniManager.addAnimalManager(speciesName, animalName, animalAge, animalGender)==false) { homePage.thereWasAProblem(); break; } break; } if (aniManager.validateShelterCapacity()==true) { if (homePage.shelterIsFull()==false){ isExiting = true; break; } else isFull = true; } break; case 2: int uuID = homePage.removeAnimalUI(); boolean animalRemoved = aniManager.removeAnimalMgr(uuID); homePage.animalRemovedAdvisory(animalRemoved); if (animalRemoved==true) { isFull=false; } break; case 3: List<AnimalBean> aniList = aniManager.getAnimalList(); homePage.viewAnimalUI(aniList); break; } } while (isExiting == false); } }
package com.heyskill.element; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.ActionBar; import com.hc.element_ec.main.EcBottomFragment; import com.hc.element_ec.main.index.IndexFragment; import com.hc.element_ec.sign.SignInFragment; import com.hc.element_ec.sign.SignUpFragment; import com.heyskill.element_core.activities.BaseActivity; import com.heyskill.element_core.fragments.BaseFragment; import qiu.niorgai.StatusBarCompat; public class MainActivity extends BaseActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) actionBar.hide(); //沉浸式状态栏设置成透明 StatusBarCompat.translucentStatusBar(this,true); } @Override public BaseFragment setRootFragment() { //return new LauncherFragment(); // return new SignInFragment(); return new EcBottomFragment(); // return new IndexFragment(); } }
package com.byraphaelmedeiros.samples.solid.srp.good; /** * @author Raphael Medeiros (raphael.medeiros@gmail.com) * @since 05/06/2020 */ public class ValidateInvoiceNumberService { public boolean validateInvoiceNumber(long number, Object invoice) { return false; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package JDBC; /** * * @author Utilisateur */ public class ManufacturerEntity { private int id; private String name; private String city; private String state; private String phone; private String fax; private String mail; public ManufacturerEntity(int id, String name, String city, String state, String phone, String fax, String mail){ this.id=id; this.city=city; this.fax=fax; this.mail=mail; this.name=name; this.phone=phone; this.state=state; } public int getID(){ return id; } public String getName(){ return name; } public String getCity(){ return city; } public String getState(){ return state; } public String getPhone(){ return phone; } public String getFax(){ return fax; } public String getMail(){ return mail; } }
import java.util.LinkedList; /** NIfth.java * * Author: Greg Choice c9311718@uon.edu.au * * Created: * Updated: 28/09/2018 * * Description: * STNode sub-class for NIFTH rule * */ public class NIfth extends STNode { public NIfth(LinkedList<Token> tokenList, SymbolTable table) { super(NID.NIFTH); } }
package com.citi.yourbank.vo; import io.swagger.annotations.ApiModel; import lombok.Data; @ApiModel("AccountSummary") @Data public class AccountSummaryVO { private AccountVO account; private String associationType; private CustomerProfileVO ownerDetail; private String accountDescription; private String accountTitle; }
package ru.otus.sua.L11.dbservice.database; import org.hibernate.cfg.Configuration; import ru.otus.sua.L11.entity.*; public class HibernateConfiguration { public static Configuration getConfig() { Configuration configuration = new Configuration(); configuration.addAnnotatedClass(DataSet.class); configuration.addAnnotatedClass(UserDataSet.class); configuration.addAnnotatedClass(UberUserDataSet.class); configuration.addAnnotatedClass(PhoneDataSet.class); configuration.addAnnotatedClass(AddressDataSet.class); configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); configuration.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); configuration.setProperty("hibernate.connection.url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1"); // configuration.setProperty("hibernate.connection.url", "jdbc:h2:~/test"); configuration.setProperty("hibernate.connection.username", "sa"); configuration.setProperty("hibernate.connection.password", "sa"); configuration.setProperty("hibernate.show_sql", "true"); configuration.setProperty("hibernate.hbm2ddl.auto", "create-drop"); // configuration.setProperty("hibernate.connection.useSSL", "false"); // configuration.setProperty("hibernate.enable_lazy_load_no_trans", "true"); return configuration; } }