blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
c3e143b96e38f867589c6784e433a0bb8e0c7ee5
Java
fnfly2005/JavaSE_Base
/src/list/demo/ListDemo.java
UTF-8
1,460
3.765625
4
[]
no_license
package list.demo; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; public class ListDemo { public static void main(String[] args) { List list = new ArrayList(); List list1 = show1(list); show2(list1); show3(list1); } private static void show3(List list1) { System.out.println("java-常用对象API-集合框架-ListIterator接口"); ListIterator it = list1.listIterator();//获取列表迭代器对象,它可以实现在迭代过程中完成对元素的增删改查 System.out.println(list1); while(it.hasNext()) { Object obj = it.next(); if (obj.equals("abc3")) { it.set("abc5"); } else { System.out.println("next:"+obj); } } System.out.println(list1); } private static void show2(List list) { System.out.println("获取元素:"+list.get(0));//返回被查询的元素 System.out.println("获取子列表:"+list.subList(0,2));//返回被查询子列表 System.out.println("删除元素:"+list.remove(2));//返回被删除的元素 System.out.println("修改元素:"+list.set(1, "abc4"));//返回被修改的元素 } private static List show1(List list) { System.out.println("java-常用对象API-集合框架-List集合常见方法-添加元素"); list.add("abc1"); list.add("abc2"); list.add("abc3"); System.out.println(list); System.out.println("插入元素"); list.add(1, "abc9"); System.out.println(list); return list; } }
true
ff23332da7646eab4371e36a7cc751452e16993b
Java
GenieYeroshenko/CarsBase
/src/main/java/ru/yeroshenko/web/ord/ListOrdCarManagerServlet.java
UTF-8
2,007
2.375
2
[]
no_license
package ru.yeroshenko.web.ord; import ru.yeroshenko.dao.OrdDao; import ru.yeroshenko.domain.Account; import ru.yeroshenko.domain.CabDriver; import ru.yeroshenko.domain.Ord; import ru.yeroshenko.web.user.LogInServlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * Class, that creates dynamic content to display the information about all Orders for the CarManager from data base */ public class ListOrdCarManagerServlet extends HttpServlet { /** * @param request to display the information about all Orders from data base * @param response for getting information about authorization for data security * @throws ServletException * @throws IOException */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Account account = (Account) request.getSession().getAttribute(LogInServlet.AUTHORIZED_USER); if (account == null) { response.sendRedirect("/login"); return; } if (account instanceof CabDriver) { response.sendRedirect("/list-ord-driver"); return; } ServletContext context = request.getSession().getServletContext(); OrdDao ordDao = (OrdDao) context.getAttribute("ordDao"); String statusFromForm = request.getParameter("ordStatus"); List<Ord> ords; if (statusFromForm == null) { ords = ordDao.findAll(); } else { Ord.OrdStatus ordStatus = Ord.OrdStatus.valueOf(statusFromForm); ords = ordDao.findAllByStatus(ordStatus); } request.setAttribute("newListOfOrds", ords); request.getRequestDispatcher("/jsp/ord/ords-list-manager.jsp").forward(request, response); } }
true
5a41e6e98daad8e9b104a8d47d5b140d3517b947
Java
jz-joannazielinska/AGHNavi
/app/app/src/main/java/com/aghnavi/agh_navi/dmsl/utils/AnyplaceUtils.java
UTF-8
3,027
2.578125
3
[]
no_license
package com.aghnavi.agh_navi.dmsl.utils; import android.Manifest; import android.content.Context; import android.os.Environment; import android.support.v4.app.ActivityCompat; import android.support.v4.os.EnvironmentCompat; import java.io.File; import java.sql.SQLOutput; public class AnyplaceUtils { private static File getFolderRootFolder(Context ctx, String folder) throws Exception { if (!AndroidUtils.checkExternalStorageState()) { throw new Exception("Error: It seems that we cannot write on your sdcard!"); } File sdcard_root = ctx.getExternalFilesDir(null); if (sdcard_root == null) { throw new Exception("Error: It seems we cannot access the sdcard!"); } System.out.println("SDCARD" + sdcard_root.getAbsolutePath() + sdcard_root.exists() + sdcard_root.canRead()); File root = new File(sdcard_root, folder); System.out.println("ROOT" + root.getAbsolutePath() + root.exists() + root.canRead()); //if(root.mkdirs()) { // if (!root.isDirectory()) { // throw new Exception("Error: It seems we cannot write on the sdcard!"); // } //} //else { // System.out.println("GET FOLDER ROOT Cannot create directory!"); //} root.mkdirs(); if (root.isDirectory() == false) { throw new Exception("Error: It seems we cannot write on the sdcard!"); } return root; } /** * Returns the File to the root folder where floor plans are stored on the * device external memory * * @return - * @throws Exception - */ public static File getFloorPlansRootFolder(Context ctx) throws Exception { return getFolderRootFolder(ctx, "floor_plans"); } /** * Returns the File to the root folder where radio maps are stored on the * device external memory * * @return - * @throws Exception - */ public static File getRadioMapsRootFolder(Context ctx) throws Exception { return getFolderRootFolder(ctx, "radiomaps"); } /** * Returns the filename for the radiomap to be used according to the floor * selected * * @return - */ public static String getRadioMapFileName(String floor) { return "fl_" + (floor == null ? "-" : floor) + "_indoor-radiomap.txt"; } public static File getRadioMapFolder(Context ctx, String buid, String floor) throws Exception { File root = getRadioMapsRootFolder(ctx); File file = new File(root, (buid == null ? "-" : buid) + "fl_" + (floor == null ? "-" : floor)); //if(file.mkdirs()) { // if (!file.isDirectory()) { // throw new Exception("Error: It seems we cannot write on the sdcard!"); // } //} file.mkdirs(); if (file.isDirectory() == false) { throw new Exception("Error: It seems we cannot write on the sdcard!"); } return file; } }
true
ffd4b868cd74be865ff08685896c99592aa694fc
Java
frantacabala/brental
/bussines/src/main/java/org/lib/brental/bussines/impl/BrentalFacadeDefault.java
UTF-8
10,139
1.84375
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.lib.brental.bussines.impl; import java.util.Collection; import java.util.Date; import java.util.List; import org.lib.brental.bussines.BrentalFacadeService; import org.lib.brental.database.AbstractDataDAOFactoryService; import org.lib.brental.model.Adresa; import org.lib.brental.model.Auto; import org.lib.brental.model.AutoId; import org.lib.brental.model.Faktura; import org.lib.brental.model.FakturaId; import org.lib.brental.model.Lod; import org.lib.brental.model.Rezervace; import org.lib.brental.model.RezervaceId; import org.lib.brental.model.Vybaveni; import org.lib.brental.model.VybaveniId; import org.lib.brental.model.Zakaznik; import org.lib.brental.model.ZakaznikId; import org.lib.brental.model.Zamestnanec; import org.lib.brental.model.ZamestnanecId; import org.lib.brental.utils.BRentalException; import org.lib.brental.integration.AbstractDAOFactoryService; import org.lib.brental.model.Other; import org.lib.brental.model.Padlo; import org.lib.brental.model.Vesta; /** * * @author john */ public class BrentalFacadeDefault extends BrentalFacadeService { @Override public void vytvorAuto(String spz, int kapacita, int cena_zakoupeni, Date datum_zakoupeni, Date datum_tk) throws BRentalException { AbstractDataDAOFactoryService.getDefault().getAutoDAO().create(spz, kapacita, cena_zakoupeni, datum_zakoupeni, datum_tk); } @Override public void smazAuto(AutoId id) throws BRentalException { AbstractDataDAOFactoryService.getDefault().getAutoDAO().delete(id); } @Override public void aktualizujAuto(Auto auto) throws BRentalException { AbstractDataDAOFactoryService.getDefault().getAutoDAO().update(auto); } @Override public Collection<Auto> getAuta() throws BRentalException { // return AbstractDAOFactory.getDefault().getAutoDAO().getAll(); return AbstractDataDAOFactoryService.getDefault().getAutoDAO().getAll(); //return AbstractDAOFactoryService.getDefault().getAutoDAO().getAll(); } @Override public void vytvorFakturu(ZamestnanecId id_zam, Date datum_vystaveni, Date datum_splatnosti) throws BRentalException { AbstractDataDAOFactoryService.getDefault().getFakturaDAO().create(id_zam, datum_vystaveni, datum_splatnosti); } @Override public void smazFakturu(FakturaId id) throws BRentalException { AbstractDataDAOFactoryService.getDefault().getFakturaDAO().delete(id); } @Override public void aktualizujFakturu(Faktura fak) throws BRentalException { AbstractDataDAOFactoryService.getDefault().getFakturaDAO().update(fak); } @Override public Collection<Faktura> getFaktury() throws BRentalException { return AbstractDAOFactoryService.getDefault().getFakturaDAO().getAll(); } @Override public void vytvorLod(String nazev, int nakup_cena, Date datum_nakup, String barva, int pujc_cena, int vaha, String evid, int delka, int max_ponor, String model, int nostnost, int sirka, String typ, String vyrobce) throws BRentalException { AbstractDAOFactoryService.getDefault().getLodDAO().create(nazev, nakup_cena, datum_nakup, barva, pujc_cena, vaha, evid, delka, max_ponor, model, nostnost, sirka, typ, vyrobce); } @Override public void smazLod(VybaveniId id) throws BRentalException { AbstractDAOFactoryService.getDefault().getLodDAO().delete(id); } @Override public void aktualizujLod(Lod lod) throws BRentalException { AbstractDAOFactoryService.getDefault().getLodDAO().update(lod); } @Override public Collection<Vybaveni> getLode() throws BRentalException { return AbstractDataDAOFactoryService.getDefault().getLodDAO().getAll(); } @Override public void vytvorZakaznika(String jmeno, String prijimeni, Adresa adresa, int cislo_op) throws BRentalException { AbstractDAOFactoryService.getDefault().getZakaznikDAO().create(jmeno, prijimeni, adresa, cislo_op); } @Override public void smazZakanika(ZakaznikId id) throws BRentalException { AbstractDAOFactoryService.getDefault().getZakaznikDAO().delete(id); } @Override public void aktualizujZakaznika(Zakaznik zak) throws BRentalException { AbstractDAOFactoryService.getDefault().getZakaznikDAO().update(zak); } @Override public Collection<Zakaznik> getZakazniky() throws BRentalException { return AbstractDataDAOFactoryService.getDefault().getZakaznikDAO().getAll(); } @Override public void vytvorZamestnance(String jmeno, String prijimeni, String funkce, Adresa adresa, String login, String heslo) throws BRentalException { AbstractDAOFactoryService.getDefault().getZamestnanecDAO().create(jmeno, prijimeni, funkce, adresa, login, heslo); } @Override public void smazZamestnance(ZamestnanecId id) throws BRentalException { AbstractDAOFactoryService.getDefault().getZamestnanecDAO().delete(id); } @Override public void aktualizujZamestnance(Zamestnanec zam) throws BRentalException { AbstractDAOFactoryService.getDefault().getZamestnanecDAO().update(zam); } @Override public Collection<Zamestnanec> getZamestnance() throws BRentalException { return AbstractDataDAOFactoryService.getDefault().getZamestnanecDAO().getAll(); } @Override public void vytvorVestu(String nazev, int nakup_cena, Date datum_nakup, String barva, int pujc_cena, int vaha, String evid, String typ, String velikost, String vyrobce) throws BRentalException { AbstractDAOFactoryService.getDefault().getVestaDAO().create(nazev, nakup_cena, datum_nakup, barva, pujc_cena, vaha, evid, typ, velikost, vyrobce); } @Override public void smazVestu(VybaveniId id) throws BRentalException { AbstractDAOFactoryService.getDefault().getVestaDAO().delete(id); } @Override public void aktualizujVestu(Vesta vest) throws BRentalException { AbstractDAOFactoryService.getDefault().getVestaDAO().update(vest); } @Override public Collection<Vybaveni> getVesty() throws BRentalException { return AbstractDataDAOFactoryService.getDefault().getVestaDAO().getAll(); } /* @Override public Vybaveni vytvorVybaveni(String nazev, int pocet, String velikost) throws BRentalException { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void smazVybaveni(VybaveniId id) throws BRentalException { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void aktualizujVybaveni(Vybaveni vyb) throws BRentalException { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Collection<Vybaveni> getVybaveni() throws BRentalException { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } */ @Override public void vytvorPadlo(String nazev, int nakup_cena, Date datum_nakup, String barva, int pujc_cena, int vaha, String evid, int delka, int sirka_listu, String typ) throws BRentalException { AbstractDAOFactoryService.getDefault().getPadloDAO().create(nazev, nakup_cena, datum_nakup, barva, pujc_cena, vaha, evid, delka, sirka_listu, typ); } @Override public void smazPadlo(VybaveniId id) throws BRentalException { AbstractDAOFactoryService.getDefault().getPadloDAO().delete(id); } @Override public void aktualizujPadlo(Padlo padlo) throws BRentalException { AbstractDAOFactoryService.getDefault().getPadloDAO().update(padlo); } @Override public Collection<Vybaveni> getPadla() throws BRentalException { return AbstractDataDAOFactoryService.getDefault().getPadloDAO().getAll(); } @Override public void vytvorOther(String nazev, int nakup_cena, Date datum_nakup, String barva, int pujc_cena, int vaha, String evid, String poznamka) throws BRentalException { AbstractDAOFactoryService.getDefault().getOtherDAO().create(nazev, nakup_cena, datum_nakup, barva, pujc_cena, vaha, evid, poznamka); } @Override public void smazOther(VybaveniId id) throws BRentalException { AbstractDAOFactoryService.getDefault().getOtherDAO().delete(id); } @Override public void aktualizujOther(Other other) throws BRentalException { AbstractDAOFactoryService.getDefault().getOtherDAO().update(other); } @Override public Collection<Vybaveni> getOther() throws BRentalException { return AbstractDAOFactoryService.getDefault().getOtherDAO().getAll(); } @Override public void vytvorRezervaci(ZakaznikId id_zak, ZamestnanecId id_zam, FakturaId id_fak, List<VybaveniId> vybaveni, Date ds, Date dk) throws BRentalException { AbstractDAOFactoryService.getDefault().getRezervaceDAO().vytvorRezervaci(id_zak, id_zam, id_fak, vybaveni, ds, dk); } @Override public void zrusRezervaci(RezervaceId id) throws BRentalException { AbstractDAOFactoryService.getDefault().getRezervaceDAO().zrusRezervaci(id); } @Override public void prijmiRezervaci(Rezervace rez) throws BRentalException { AbstractDAOFactoryService.getDefault().getRezervaceDAO().prijmiRezervaci(rez); } @Override public Collection<VybaveniId> getVybaveni(Rezervace rez) throws BRentalException { return AbstractDAOFactoryService.getDefault().getRezervaceDAO().getVybaveni(rez); } @Override public Collection<Rezervace> getRezervace() throws BRentalException { return AbstractDAOFactoryService.getDefault().getRezervaceDAO().getRezervace(); } @Override public boolean isAvailable() { return true; } }
true
e091b4efc05417b818285c5764d8d902c9ba85ba
Java
naienmw/Workout
/app/src/main/java/com/naien/workout/my_adapter.java
UTF-8
1,094
2.5
2
[]
no_license
package com.naien.workout; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; class my_adapter extends ArrayAdapter<String> { public my_adapter(Context context, ArrayList<String> values) { super(context, R.layout.excercise_row_layout, values); } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater theInflater = LayoutInflater.from(getContext()); View theView = theInflater.inflate(R.layout.excercise_row_layout, parent, false); String tvShow = getItem(position); TextView theTextView = (TextView) theView.findViewById(R.id.textViewEx); theTextView.setText(tvShow); return theView; } public void add(String name){ super.add(name); } public void setNotifyOnChange(boolean onchange){ super.setNotifyOnChange(onchange); } }
true
1c2f275fda5a02f9fe9fd4e935e5c8acd2e1282f
Java
ghatzin/videostore
/adminPart/src/main/java/com/admin/service/impl/MovieServiceImpl.java
UTF-8
719
2.125
2
[]
no_license
package com.admin.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.admin.domain.Movie; import com.admin.repository.MovieRepository; import com.admin.service.MovieService; @Service public class MovieServiceImpl implements MovieService { @Autowired MovieRepository movieRepository; public Movie save(Movie movie) { return movieRepository.save(movie); } public List<Movie> findAll() { return (List<Movie>) movieRepository.findAll(); } public Movie findOne(Long id) { return movieRepository.findById(id).get(); } public void removeOne(Long id) { movieRepository.deleteById(id); } }
true
d3c5da1393c3be1eaa4243a5c8d5643cf80778d8
Java
yindanqing925/demo-parent
/netty-demo/demo-one/src/main/java/org/nh/netty/demo/one/common/order/OrderOperationResult.java
UTF-8
396
1.5
2
[]
no_license
package org.nh.netty.demo.one.common.order; import lombok.Data; import org.nh.netty.demo.one.common.OperationResult; /** * 订单操作结果 * * @author: yindanqing * @version: 1.0.0 * @date: 2022/11/18 22:53 */ @Data public class OrderOperationResult extends OperationResult { private final int tableId; private final String dish; private final boolean complete; }
true
258e549fc99eb0396f7e0633aea6787016413ad0
Java
polito-se2-21-r03/se1-ezshop
/src/main/java/it/polito/ezshop/model/persistence/JsonInterface.java
UTF-8
9,895
2.640625
3
[]
no_license
package it.polito.ezshop.model.persistence; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import it.polito.ezshop.model.*; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class JsonInterface { /** * Path of the users json file */ private final Path usersPath; /** * Path of the products json file */ private final Path productsPath; /** * Path of the account book json file */ private final Path accountBookPath; /** * Path of the customers json file */ private final Path customerListPath; /** * Instance of the Gson serializer/deserializer */ private final Gson gson; /** * Construct a new instance of JsonInterfaceImpl. * This constructor assumes that the desired path exists. * * @param path path that should contains the application data */ private JsonInterface(Path path) { // create the paths for each file this.usersPath = Paths.get(path.toString(), "users.json"); this.productsPath = Paths.get(path.toString(), "products.json"); this.accountBookPath = Paths.get(path.toString(), "account_book.json"); this.customerListPath = Paths.get(path.toString(), "customers.json"); // see https://jansipke.nl/serialize-and-deserialize-a-list-of-polymorphic-objects-with-gson/ // create a runtime adapter that instantiate the correct subclass of BalanceOperation RuntimeTypeAdapterFactory<BalanceOperation> runtimeTypeAdapterFactory = RuntimeTypeAdapterFactory .of(BalanceOperation.class, "_type") .registerSubtype(Credit.class, "credit") .registerSubtype(Debit.class, "debit") .registerSubtype(Order.class, "order") .registerSubtype(SaleTransaction.class, "sale") .registerSubtype(ReturnTransaction.class, "return"); this.gson = new GsonBuilder().registerTypeAdapterFactory(runtimeTypeAdapterFactory).create(); } /** * Create a new instance of JsonInterface. * This methods creates the destination path if it does not exist. * * @param path is the path of the destination directory * @return an instance of JsonInterface * @throws IOException if an I/O exception occurs */ public static JsonInterface create(String path) throws IOException { Path destinationDir = Paths.get(path); if (!Files.exists(destinationDir)) { Files.createDirectory(destinationDir); } return new JsonInterface(destinationDir); } /** * Clear all the persisted data. * * @throws IOException if an I/O exception occurs */ public void reset() throws IOException { for (Path path : Arrays.asList(usersPath, productsPath, accountBookPath, customerListPath)) { Files.deleteIfExists(path); } } /** * Read a list of users from the persistence layer. * If the persistence layer contains no users, an empty list is returned. * * @return a list of users * @throws IOException if an I/O exception occurs */ public List<User> readUsers() throws IOException { return readList(usersPath, User.class); } /** * Write a list of users to the persistence layer. * * @param users list of users to be persisted (null is treated as an empty list) * @throws IOException if an I/O exception occurs */ public void writeUsers(List<User> users) throws IOException { writeList(usersPath, users); } /** * Read a list of products from the persistence layer. * If the persistence layer contains no products, an empty list is returned. * * @return a list of products * @throws IOException if an I/O exception occurs */ public List<ProductType> readProducts() throws IOException { return readList(productsPath, ProductType.class); } /** * Write a list of products to the persistence layer. * * @param products list of products to be persisted (null is treated as an empty list) * @throws IOException if an I/O exception occurs */ public void writeProducts(List<ProductType> products) throws IOException { writeList(productsPath, products); } /** * Read the customer list from the persistence layer. * If the persistence layer contains no customer list, * a new clean instance is returned. * * @return the customer list * @throws IOException if an I/O exception occurs */ public CustomerList readCustomerList() throws IOException { String json = read(customerListPath); if (json == null || json.equals("")) { return new CustomerList(); } Type type = new TypeToken<CustomerList>() { }.getType(); CustomerList cl = gson.fromJson(json, type); if (cl != null) { // iterate over all customers cl.getAllCustomers().forEach(customer -> { if (customer.getCard() != null) { cl.loyaltyCards.stream() .filter(x -> x.equals(customer.getCard())) .findFirst().ifPresent(customer::setCard); } }); } return cl; } /** * Write a list of customers to the persistence layer. * * @param customerList the customer list to be persisted (null is treated as a clean instance) * @throws IOException if an I/O exception occurs */ public void writeCustomerList(CustomerList customerList) throws IOException { if (customerList == null) { customerList = new CustomerList(); } write(customerListPath, gson.toJson(customerList)); } /** * Read the account book from the persistence layer. * If the persistence layer contains no account book, a clean instance * (zero balance, no transactions) is returned. * * @return the account book * @throws IOException if an I/O exception occurs */ public AccountBook readAccountBook() throws IOException { String json = read(accountBookPath); if (json == null || json.equals("")) { return new AccountBook(); } Type type = new TypeToken<AccountBook>() { }.getType(); return gson.fromJson(json, type); } /** * Write the account book to the persistence layer. * * @param accountBook the account book to be persisted (null is treated as a clean instance) * @throws IOException if an I/O exception occurs */ public void writeAccountBook(AccountBook accountBook) throws IOException { if (accountBook == null) { accountBook = new AccountBook(); } write(accountBookPath, gson.toJson(accountBook)); } /** * Write a string to a file. * * @param path of the file * @param json is the string to write * @throws IOException if an I/O exceptions occurs while reading the file */ private void write(Path path, String json) throws IOException { try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) { writer.write(json, 0, json.length()); } } /** * Read all the lines of a file. * * @param path of the file * @return a string containing the lines of the file (null if the file does not exist) * @throws IOException if an I/O exceptions occurs while reading the file */ private String read(Path path) throws IOException { if (Files.notExists(path)) { return null; } try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } return sb.toString(); } } /** * Write a list of objects to a json file. * * @param path of the json file to write * @param data is the list of objects to write * @param <T> type of the objects to write * @throws IOException if an I/O exceptions occurs while reading the json file */ private <T> void writeList(Path path, List<T> data) throws IOException { if (data == null) { data = new ArrayList<>(); } write(path, gson.toJson(data)); } /** * Read a list of objects from a json file. * * @param path of the json file to read * @param cls class of the objects to read * @param <T> type of the objects to read * @return a possibly empty list of the read objects * @throws IOException if an I/O exceptions occurs while reading the json file */ private <T> List<T> readList(Path path, Class<T> cls) throws IOException { String json = read(path); if (json == null || json.equals("")) { return new ArrayList<>(); } Type type = TypeToken.getParameterized(List.class, cls).getType(); return gson.fromJson(json, type); } }
true
69c81a42a163d0996c7d491453da1e2b33e2dba3
Java
xukangning/haobangshou
/hbs/APPLICATION/server/vendor/vendororder/src/com/hbs/vendororder/action/VendorOrderBaseAction.java
GB18030
3,880
2.125
2
[]
no_license
/** * */ package com.hbs.vendororder.action; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import com.hbs.common.action.JianQuanUtil; import com.hbs.common.action.base.BaseAction; import com.hbs.domain.vendor.order.pojo.VendorOrder; import com.hbs.vendororder.manager.VendorOrderMgr; /** * Ӧ̶࣬ʵdoListdoGetInfo * @author xyf * */ @SuppressWarnings("serial") public abstract class VendorOrderBaseAction extends BaseAction { /** * logger. */ private static final Logger logger = Logger.getLogger(VendorOrderBaseAction.class); public static final String VENDOR_ORDER_MGR = "vendorOrderMgr"; VendorOrder vendorOrder; /** * @return the vendorOrder */ public VendorOrder getVendorOrder() { return vendorOrder; } /** * @param vendorOrder the vendorOrder to set */ public void setVendorOrder(VendorOrder vendorOrder) { this.vendorOrder = vendorOrder; } /** * ؽɫ * @return */ public abstract String getRoleName(); /** * Ƿڲʹátrue鿴еύݣʱݣfalse鿴ԼݣstaffId * @return */ protected abstract boolean getIsManager(); /** * ѯ * @action.input custOrder.ѯ * @action.result listб count * @return */ public String doList() { try { logger.debug("begin doList"); if(vendorOrder == null) vendorOrder = new VendorOrder(); if(getIsManager()) vendorOrder.setField("noState01", true); else setMyId(false); setPagination(vendorOrder); VendorOrderMgr mgr = getMgr(); setResult("list", mgr.getVendorOrderList(vendorOrder)); setTotalCount(mgr.getVendorOrderCount(vendorOrder)); setResult("count", getTotalCount()); setResult("jq", JianQuanUtil.getJQ(JianQuanUtil.TypeVendorOrderState, getRoleName())); logger.debug("end doList"); return SUCCESS; } catch(Exception e) { logger.error("catch Exception in doList", e); setErrorReason("ڲ"); return ERROR; } } /** * ȡӦ̶Ϣ * @action.input vendorOrder.commCode + vendorOrder.poNo * @action.result vendorOrder.* * @return */ public String doGetInfo() { try{ logger.debug("begin doGetInfo"); if(!findVendorOrder()) return ERROR; setResult("vendorOrder", vendorOrder); logger.debug("end doGetInfo"); return SUCCESS; }catch(Exception e) { logger.error("catch Exception in doGetInfo", e); setErrorReason("ڲ"); return ERROR; } } protected VendorOrderMgr getMgr() throws Exception { return (VendorOrderMgr)getBean(VENDOR_ORDER_MGR); } protected boolean findVendorOrder() throws Exception { if(vendorOrder == null || StringUtils.isEmpty(vendorOrder.getCommCode()) || StringUtils.isEmpty(vendorOrder.getPoNo())) { logger.debug("Ϊգ"); setErrorReason("Ϊգ"); return false; } VendorOrderMgr mgr = getMgr(); VendorOrder vendorOrder2 = mgr.getVendorOrder(vendorOrder.getCommCode(), vendorOrder.getPoNo(), true); if(vendorOrder2 == null || vendorOrder2.getStaffId() == null) { logger.debug("ûҵ"); setErrorReason("ûҵ"); return false; }else if(!getIsManager() && !vendorOrder2.getStaffId().equals(getLoginStaff().getStaffId().toString())) { logger.debug("Ȩ޴"); setErrorReason("Ȩ޴"); return false; } vendorOrder = vendorOrder2; return true; } protected void setMyId(boolean setName) throws Exception { vendorOrder.setStaffId(getLoginStaff().getStaffId().toString()); if(setName) vendorOrder.setStaffName(getLoginStaff().getStaffName()); } }
true
eac08e928483e761b96d3dca62f6482a3729ef71
Java
AmeerAyman/Operation-research
/src/orproject/OrProject.java
UTF-8
10,644
3.171875
3
[]
no_license
/* * 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 orproject; import java.util.Scanner; /** * * @author ameer */ public class OrProject { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner sc =new Scanner(System.in); System.out.println("which operation of these matrcies do you want to find:"); System.out.println("1- Scalar Multiply"+"\n"+"2- Transpose"); System.out.println("3- Symmatric Validation"+"\n"+"4- Sum"); System.out.println("5- Multiplication"+"\n"+"6- Equality Validation"); System.out.println("7- Zero Matrix"+"\n"+"8- Identity Matrix"); System.out.println("9- cheak validation for multiply"); char ch=sc.next().charAt(0); switch(ch){ case'1': MyMatrix m; System.out.println("enter the number of rows and columns:"); int ro=sc.nextInt(); int col=sc.nextInt(); m = new MyMatrix(ro, col); double arra[][]= new double[ro][col]; for(int i=0;i<ro;i++){ for(int j=0;j<col;j++){ System.out.println("enter the element for row "+(i+1)+" column "+(j+1)); arra[i][j]=sc.nextDouble(); } } //MyMatrix mm; System.out.println("enter the scalar"); double scal=sc.nextDouble(); m.setArrayMatrix(arra); m=m.scalarMultiply(scal); System.out.println("the result for scalar multiplying "); m.display(); break; case'2': try{ System.out.println("enter the number of rows and columns:"); int ro2=sc.nextInt(); int col2=sc.nextInt(); MyMatrix m2 = new MyMatrix(ro2, col2); double arra2[][]= new double[ro2][col2]; for(int i=0;i<ro2;i++){ for(int j=0;j<col2;j++){ System.out.println("enter the element for row "+(i+1)+" column "+(j+1)); arra2[i][j]=sc.nextDouble(); } } m2.setArrayMatrix(arra2); System.out.println("the result for transpose "); m2.transpose().display(); } catch(Exception e){ System.out.println("The size of matrix is notValid !!"); } break; case'3': try{ MyMatrix m3; System.out.println("enter the number of rows and columns:"); int ro3=sc.nextInt(); int col3=sc.nextInt(); m3 = new MyMatrix(ro3, col3); double arra3[][]= new double[ro3][col3]; for(int i=0;i<ro3;i++){ for(int j=0;j<col3;j++){ System.out.println("enter the element for row "+(i+1)+" column "+(j+1)); arra3[i][j]=sc.nextDouble(); } } m3.setArrayMatrix(arra3); System.out.println(m3.isSymmatric()); } catch(Exception e){ System.out.println("The size of matrix is notValid !!"); } break; case'4': try{ MyMatrix m4,m5,m6; System.out.println("enter the number of rows and columns for matrix 1:"); int ro4=sc.nextInt(); int col4=sc.nextInt(); m4 = new MyMatrix(ro4, col4); double arra4_1[][]= new double[ro4][col4]; for(int i=0;i<ro4;i++){ for(int j=0;j<col4;j++){ System.out.println("enter the element for row "+(i+1)+" column "+(j+1)); arra4_1[i][j]=sc.nextDouble(); } } m4.setArrayMatrix(arra4_1); System.out.println("enter the number of rows and columns for matrix 2:"); int ro4_2=sc.nextInt(); int col4_2=sc.nextInt(); m5 = new MyMatrix(ro4_2, col4_2); double arra4_2[][]= new double[ro4_2][col4_2]; for(int i=0;i<ro4_2;i++){ for(int j=0;j<col4_2;j++){ System.out.println("enter the element for row "+(i+1)+" column "+(j+1)); arra4_2[i][j]=sc.nextDouble(); } } m5.setArrayMatrix(arra4_2); m6=m4.sum(m5); System.out.println("The result of addition :"); m6.display(); } catch(Exception e){ System.out.println("The size of matrix is notValid !!"); } break; case'5': try{ MyMatrix m7,m8,m9; System.out.println("enter the number of rows and columns for matrix 1:"); int ro7=sc.nextInt(); int col7=sc.nextInt(); m7 = new MyMatrix(ro7, col7); double arra5_1[][]= new double[ro7][col7]; for(int i=0;i<ro7;i++){ for(int j=0;j<col7;j++){ System.out.println("enter the element for row "+(i+1)+" column "+(j+1)); arra5_1[i][j]=sc.nextDouble(); } } m7.setArrayMatrix(arra5_1); System.out.println("enter the number of rows and columns for matrix 2:"); int ro8=sc.nextInt(); int col8=sc.nextInt(); m8 = new MyMatrix(ro8, col8); double arra7_2[][]= new double[ro8][col8]; for(int i=0;i<ro8;i++){ for(int j=0;j<col8;j++){ System.out.println("enter the element for row "+(i+1)+" column "+(j+1)); arra7_2[i][j]=sc.nextDouble(); } } System.out.println(m7.validForMultiplication(m8)); m8.setArrayMatrix(arra7_2); m9=m7.multiplematrix(m8); System.out.println("The result of multiplication :"); m9.display(); } catch(Exception e){ System.out.println("The size of matrix is notValid !!"); } break; case'6': try{ MyMatrix m10,m11,m12; System.out.println("enter the number of rows and columns for matrix 1:"); int ro10=sc.nextInt(); int col10=sc.nextInt(); m10 = new MyMatrix(ro10, col10); double arra10[][]= new double[ro10][col10]; for(int i=0;i<ro10;i++){ for(int j=0;j<col10;j++){ System.out.println("enter the element for row "+(i+1)+" column "+(j+1)); arra10[i][j]=sc.nextDouble(); } } m10.setArrayMatrix(arra10); System.out.println("enter the number of rows and columns for matrix 2:"); int ro11=sc.nextInt(); int col11=sc.nextInt(); m11 = new MyMatrix(ro11, col11); double arra11[][]= new double[ro11][col11]; for(int i=0;i<ro11;i++){ for(int j=0;j<col11;j++){ System.out.println("enter the element for row "+(i+1)+" column "+(j+1)); arra11[i][j]=sc.nextDouble(); } } m11.setArrayMatrix(arra11); //m12=m10.equals(m11); System.out.println(m10.equals(m11)); } catch(Exception e){ System.out.println("The size of matrix is notValid !!"); } break; case'7': MyMatrix m13; System.out.println("enter the number of rows and columns for matrix :"); int ro13=sc.nextInt(); int col13=sc.nextInt(); m13 = new MyMatrix(ro13, col13); m13.display(); break; case'8': MyMatrix m14; System.out.println("enter matrix size"); int ro14=sc.nextInt(); m14=new MyMatrix(ro14,ro14); m14.display(); break; case'9': MyMatrix m15,m16; System.out.println("enter the number of rows and columns for matrix 1"); int ro15=sc.nextInt(); int col15=sc.nextInt(); m15=new MyMatrix(ro15,col15); System.out.println("enter the number of rows and columns for matrix 2"); int ro16=sc.nextInt(); int col16=sc.nextInt(); m16=new MyMatrix(ro16,col16); System.out.println(m15.validForMultiplication(m16)); break; } } }
true
4dcfac4db527dc55b0ac37496ece2e84a4b0e616
Java
Jared73431/DA106G3
/src/com/members/model/MembersService.java
UTF-8
3,517
2.109375
2
[]
no_license
package com.members.model; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.experience.model.ExperienceVO; import com.notificationlist.model.NotificationListVO; import java.sql.Date; public class MembersService { private MembersDAO_interface dao; public MembersService() { dao = new MembersDAO(); } public MembersVO addMembers(String known, Integer sexual, String mem_name, String mem_account, String email, String mem_password, Date birthday, String phone, String mem_zip, String address, Double height, byte[] picture) { MembersVO membersVO = new MembersVO(); // membersVO.setCoa_qualifications(coa_qualifications); membersVO.setKnown(known); membersVO.setSexual(sexual); membersVO.setMem_name(mem_name); membersVO.setMem_account(mem_account); // membersVO.setMem_status(mem_status); membersVO.setEmail(email); membersVO.setMem_password(mem_password); membersVO.setBirthday(birthday); membersVO.setPhone(phone); membersVO.setMem_zip(mem_zip); membersVO.setAddress(address); // membersVO.setReal_blance(real_blance); membersVO.setHeight(height); //membersVO.setReg_date(reg_date); membersVO.setPicture(picture); // membersVO.setLicense(license); dao.insert(membersVO); return membersVO; } public MembersVO updateMembers(String member_no, Integer coa_qualifications, String known, Integer sexual, String mem_name, String mem_account, Integer mem_status, String email, String mem_password, Date birthday, String phone, String mem_zip, String address, Integer real_blance, Double height, byte[] picture) { MembersVO membersVO = new MembersVO(); membersVO.setMember_no(member_no); membersVO.setCoa_qualifications(coa_qualifications); membersVO.setKnown(known); membersVO.setSexual(sexual); membersVO.setMem_name(mem_name); membersVO.setMem_account(mem_account); membersVO.setMem_status(mem_status); membersVO.setEmail(email); membersVO.setMem_password(mem_password); membersVO.setBirthday(birthday); membersVO.setPhone(phone); membersVO.setMem_zip(mem_zip); membersVO.setAddress(address); membersVO.setReal_blance(real_blance); membersVO.setHeight(height); // membersVO.setReg_date(reg_date); membersVO.setPicture(picture); // membersVO.setLicense(license); dao.update(membersVO); return membersVO; } public boolean deleteMembers(String member_no) { return dao.delete(member_no); } public MembersVO getOneMembers(String member_no) { return dao.findByPrimaryKey(member_no); } public List<MembersVO> getAll() { return dao.getAll(); } public List<MembersVO> getNoStatus(Integer mem_status){ return dao.getNoStatus(mem_status); } public MembersVO getOneMemberByAccount(String mem_account) { return dao.getOneMemberByAccount(mem_account); } public void updateMembersRealBlance(Integer real_blance, String member_no) { dao.updateMembersRealBlance(real_blance, member_no); } public void updateLicense(Integer coa_qualifications, byte[] license, String member_no) { dao.updateCoa(coa_qualifications, license, member_no); } public void updateStatus(Integer mem_status, String member_no) { dao.updateStatus(mem_status, member_no); } // 勝瑜加入抓通知 public Set<NotificationListVO> getNotesByMemberno(String member_no) { return dao.getNotesByMember(member_no); } // 勝瑜加入抓心得 public Set<ExperienceVO> getExperByMemberno(String member_no) { return dao.getExoerByMember(member_no); } }
true
d27c9ce118981bddedd1ed68f90a26f611d06df2
Java
Kietzmann/CodeWarsSolutions
/Java/AckermannFunction.java
UTF-8
284
2.84375
3
[]
no_license
public class Solution { public static int Ackermann(int m, int n) { if (m == 0) return n + 1; if ((m > 0) && (n == 0)) return Ackermann(m - 1, 1); if ((m > 0) && (n > 0)) return Ackermann(m - 1, Ackermann(m, n - 1)); else return 0; } }
true
6963de6c993e818ec2db151bbc0084a8df508a42
Java
DanielSVieira/FlightSearchAPI
/src/main/java/com/ryanair/api/searchflights/mapper/FilterFlightsMapper.java
UTF-8
864
2.3125
2
[]
no_license
package com.ryanair.api.searchflights.mapper; import org.joda.time.LocalDateTime; import com.ryanair.api.searchflights.datatransferobject.FilterFlightsDTO; public class FilterFlightsMapper { public static FilterFlightsDTO makeFilterFlightsDTO(String departure, String arrival, String departureTime, String arrivalTime) { return FilterFlightsDTO.builder() .departure(departure) .arrival(arrival) .departureTime(new LocalDateTime(departureTime)) .arrivalTime(new LocalDateTime(arrivalTime)) .build(); } public static FilterFlightsDTO makeFilterFlightsDTO(String departure, String arrival, LocalDateTime departureTime, LocalDateTime arrivalTime) { return FilterFlightsDTO.builder() .departure(departure) .arrival(arrival) .departureTime(departureTime) .arrivalTime(arrivalTime) .build(); } }
true
df3c04d03d34297bff8d79bfdf8b7deaae208064
Java
Skyouth1010/codesum
/src/main/java/socket/client/SocketClient.java
UTF-8
4,254
2.90625
3
[]
no_license
package socket.client; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.net.Socket; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SocketClient { private static final Logger logger = LoggerFactory.getLogger(SocketClient.class); private Socket conn = null; private BufferedReader input = null; private InetSocketAddress address = null; private int timeOut = 20000; private int readTimeOut = 20000; private boolean needResponse = true; private int bufferSize = 20 * 1024; private String encode = "GBK"; public SocketClient(String host, int port) throws IOException { try { conn = new Socket(); conn.setSoTimeout(timeOut); address = new InetSocketAddress(host, port); } catch (IOException e) { //logger.error("SOCKET创建失败", e); throw e; } } /** * send(socket交互) * @param request * @return * @throws BusinessException */ public String send(String request) throws IOException { byte[] rcvbuf = null; try { if (connect()) { try { conn.getOutputStream().write(request.getBytes(encode)); } catch (IOException e) { //logger.error("发送数据失败", e); throw e; } if (needResponse && connect()) { rcvbuf = receiveData(); } } if (rcvbuf != null) { String result = new String(rcvbuf); return result; } else { return null; } } finally { disconnect(); } } /** * receiveData(接收报文) * @return * @throws BusinessException */ private byte[] receiveData() throws IOException { try{ char[] cbuf = new char[bufferSize]; int len = 0; int time = 0; while (true) { if (time >= readTimeOut) { logger.error("error","receiveData timeOut"); return null; } // if (!input.ready()) { // time += 100; // Thread.sleep(100); // continue; // } len = input.read(cbuf, 0, bufferSize); break; // int lenTemp = input.read(cbuf, len, bufferSize-len); // if (lenTemp == -1) { // break; // } // len += lenTemp; } if (len < 0) { return null; } char[] buffer = new char[len]; System.arraycopy(cbuf, 0, buffer, 0, len); Arrays.fill(cbuf, (char) 0); return String.valueOf(buffer).getBytes(); }catch(Exception e){ //logger.error("接收返回包出错", e); throw e; } } /** * connect(建立连接) * @return * @throws BusinessException */ private boolean connect() throws IOException { if (!conn.isConnected()) { try { conn.connect(address, timeOut); input = new BufferedReader(new InputStreamReader(conn.getInputStream(), encode)); } catch (IOException e) { //logger.error("SOCKET连接失败", e); throw e; } } return true; } /** * disconnect(断开连接) * @throws BusinessException */ private void disconnect() throws IOException { try { if (input != null) { input.close(); } if (conn != null) { conn.close(); } } catch (IOException e) { //logger.error("SOCKET断连异常",e); throw e; } } public void setTimeOut(int timeOut) { this.timeOut = timeOut; } /** * @param bufferSize the bufferSize to set */ public void setBufferSize(int bufferSize) { this.bufferSize = bufferSize; } /** * @param encode the encode to set */ public void setEncode(String encode) { this.encode = encode; } public void setReadTimeOut(int readTimeOut) { this.readTimeOut = readTimeOut; } public void setNeedResponse(boolean needResponse) { this.needResponse = needResponse; } public static void main(String[] s) { try { SocketClient sc = new SocketClient("99.6.148.95", 9002); String response = sc.send("hello"); System.out.println(response); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
4ff9dc215a06ca249d53f7b044fff3e44bf036fa
Java
moutainhigh/kunlun-erp-core
/core-dto/src/main/java/com/kunlun/erp/core/dto/finance/response/FinanceAuditResultRespDto.java
UTF-8
1,515
2.125
2
[]
no_license
package com.kunlun.erp.core.dto.finance.response; import com.kunlun.erp.core.common.constants.SysConstant; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * @ClassName FinanceAuditResultRespDto * @Description 审核结果响应数据 * @Author Jm.zhang * @Date 2019/12/27 12:30 * @Version 1.0 **/ @ApiModel(description = "审核结果响应数据") public class FinanceAuditResultRespDto { @ApiModelProperty(value = "审核状态,0=未审核、1=通过、2=驳回",example = "2") private Integer audit_state; @ApiModelProperty(value = "审核状态释义",example = "通过") private String audit_state_str; @ApiModelProperty(value = "审核备注",example ="这是一个备注" ) private String approve_remarks; public Integer getAudit_state() { return audit_state; } public void setAudit_state(Integer audit_state) { this.audit_state = audit_state; if (audit_state!=null){ this.setAudit_state_str(SysConstant.FinanceAuditStatus.getFinanceAuditStatus(audit_state).getName()); } } public String getAudit_state_str() { return audit_state_str; } public void setAudit_state_str(String audit_state_str) { this.audit_state_str = audit_state_str; } public String getApprove_remarks() { return approve_remarks; } public void setApprove_remarks(String approve_remarks) { this.approve_remarks = approve_remarks; } }
true
f85e8b88b8e8356af06ce95e6c69ede645a50fe1
Java
zhang4838223/ewidebs
/src/main/java/net/ewide/platform/modules/sys/dao/UserOfficeDao.java
UTF-8
569
1.71875
2
[]
no_license
package net.ewide.platform.modules.sys.dao; import java.util.List; import net.ewide.platform.common.persistence.CrudDao; import net.ewide.platform.common.persistence.annotation.MyBatisDao; import net.ewide.platform.modules.sys.entity.UserOffice; /** * 用户机构DAO接口 * @author TianChong * @version 2016年3月29日 */ @MyBatisDao public interface UserOfficeDao extends CrudDao<UserOffice>{ public List<UserOffice> findUserOffices(String id); public List<UserOffice> findUserOfficesByOfficeId(String id); public void deleteByOfficeId(String id); }
true
17dd74c8909dd44ae308f2d47ddfb407da2cca54
Java
chiragsheth/Playground
/Power of a number using functions/Main.java
UTF-8
397
3.28125
3
[]
no_license
import java.util.Scanner; class Main { public static int power (int a,int b) { int pwr=1; for (int count=1;count<=b;count++) pwr=pwr*a; return pwr; } public static void main (String args []) { Scanner in = new Scanner ( System.in ); int n1 = in.nextInt ( ); int n2 = in.nextInt ( ); int pow=power (n1,n2); System.out.println(pow); } }
true
cb034e58f800d4a2ffc8c34b3c30a29e17f12470
Java
andrefnb/three_in_a_row_java
/pt.ips.pa/src/pt/ips/pa/controller/FXMLRankingWindowController.java
UTF-8
2,302
2.46875
2
[]
no_license
/* * 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 pt.ips.pa.controller; import java.net.URL; import java.util.ArrayList; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.ListView; import javafx.scene.layout.AnchorPane; import pt.ips.pa.model.interfaces.Iterator; import pt.ips.pa.model.jogo.GestorJogo; import pt.ips.pa.model.jogo.Jogador; import pt.ips.pa.model.jogo.RankingJogador; /** * FXML Controller class * * @author Asuspc */ public class FXMLRankingWindowController implements Initializable { @FXML private ListView<String> ListBaseRapido; @FXML private ListView<String> ListCorridaRapido; @FXML private ListView<String> ListCorridaNormal; @FXML private ListView<String> ListBaseNormal; @FXML private AnchorPane sceneRanking; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { sceneRanking.setStyle("-fx-background-image: url('" + getClass().getResource("/temas/background.png").toExternalForm() + "')"); } public void iniciarRankings(){ iniciarRanking(ListBaseRapido, GestorJogo.getInstance().getRankingBaseRapido()); iniciarRanking(ListCorridaRapido, GestorJogo.getInstance().getRankingCorridaRapido()); iniciarRanking(ListCorridaNormal, GestorJogo.getInstance().getRankingCorridaNormal()); iniciarRanking(ListBaseNormal, GestorJogo.getInstance().getRankingBaseNormal()); } private void iniciarRanking(ListView<String> listaRanking, RankingJogador ranking){ ArrayList <String> lista = new ArrayList(); Iterator<Jogador> it = ranking.getIterator(); int posicao =1; while (it.hasNext()) { Jogador jog = it.next(); lista.add(posicao+"º "+jog.getUsername()+" com "+jog.getPontuacao()+" pontos"); posicao++; } listaRanking.setItems(FXCollections.observableArrayList(lista)); } }
true
7efda65744c821630b7ea7fe59ad1cb2c320496e
Java
MattPutnam/Common
/src/common/collection/ListAdapter.java
UTF-8
1,068
3.125
3
[]
no_license
package common.collection; /** * Implements {@link ListListener} with no-op implementations as a convenience. * This class also provides the method {@link #anyChange(ListEvent)}, * which is called by each of the ListListener methods. If you want to override * {@link #elementAdded(ListEvent)}, {@link #elementRemoved(ListEvent)}, or * {@link #elementSet(ListEvent)} and still receive notifications via * anyChange(ListEvent), then those overrides must call super. * * @author Matt Putnam */ public class ListAdapter<E> implements ListListener<E> { @Override public void elementAdded(ListEvent<E> event) { anyChange(event); } @Override public void elementRemoved(ListEvent<E> event) { anyChange(event); } @Override public void elementSet(ListEvent<E> event) { anyChange(event); } @Override public void elementModified(ListEvent<E> event) { anyChange(event); } /** * Called if any change has occurred. * @param event - the associated ListEvent */ public void anyChange(ListEvent<E> event) {} }
true
e5573e96cfc676666cd2b35ea4ab4ee108ad68fb
Java
superman1478/SuperMiner
/src/superMiner/SummoningItem.java
UTF-8
267
2.140625
2
[]
no_license
package superMiner; public enum SummoningItem { LAVA_TITAN_POUCH (12788), UNKNOWN_SUMMONING_NECKLACE (25469), UNKNOWN_SUMMONING_NECKLACE_2 (24747); private final int id; SummoningItem(int id) { this.id = id; } public int getId() { return id; } }
true
55b9f6fe32e9bac54aa589dbedc3a9608b7160bf
Java
ShanShuan/nio_test
/src/main/java/com/ruiphone/buffer/TestBuffer.java
UTF-8
2,380
3.390625
3
[]
no_license
package com.ruiphone.buffer; import org.junit.Test; import java.nio.ByteBuffer; /** * Description: * 除boolean 都有对应的buffer * ByteBuffer * CharBuffer * ShortBuffer * InterBuffer * LongBuffer * FloatBuffer * DoubleBuffer * 通过allocate()获取缓冲数据 * * 缓冲区的核心方法 * put get * * mark 标记当前position 的位置,可通过reset()回到当前位置 * @author wang zifeng * @Date Create on 2019-08-19 11:49 * @since version1.0 Copyright 2018 Burcent All Rights Reserved. */ public class TestBuffer { @Test public void test01(){ String mby="我是谁?"; //分布一个指定缓冲区 的大小 ByteBuffer byteBuffer=ByteBuffer.allocate(1024); System.out.println("-----new --------"); System.out.println(byteBuffer.capacity()); System.out.println(byteBuffer.position()); System.out.println(byteBuffer.limit()); //写模式 put byteBuffer.put(mby.getBytes()); System.out.println("-------put------"); System.out.println(byteBuffer.capacity()); System.out.println(byteBuffer.position()); System.out.println(byteBuffer.limit()); //读模式 byteBuffer.flip(); System.out.println("------get-------"); System.out.println(byteBuffer.capacity()); System.out.println(byteBuffer.position()); System.out.println(byteBuffer.limit()); byte[] bytes=new byte[byteBuffer.limit()]; byteBuffer.get(bytes); System.out.println(new String(bytes,0,bytes.length)); System.out.println("-------------"); System.out.println(byteBuffer.capacity()); System.out.println(byteBuffer.position()); System.out.println(byteBuffer.limit()); //重复读 byteBuffer.rewind(); System.out.println("------rewind()-------"); System.out.println(byteBuffer.capacity()); System.out.println(byteBuffer.position()); System.out.println(byteBuffer.limit()); //清空缓冲区 缓冲区的数据还是存在 ,只是处于"被遗忘状态" byteBuffer.clear(); System.out.println("------clear()-------"); System.out.println(byteBuffer.capacity()); System.out.println(byteBuffer.position()); System.out.println(byteBuffer.limit()); } }
true
4977b14cb58b600306c48c8538d03f4831282dcf
Java
AlexanderTheGrape/Kalah
/src/kalah/Kalah.java
UTF-8
2,147
3.140625
3
[]
no_license
package kalah; import com.qualitascorpus.testsupport.IO; import com.qualitascorpus.testsupport.MockIO; /** * This class is the starting point for a Kalah implementation using * the test infrastructure. */ public class Kalah { public static void main(String[] args) { new Kalah().play(new MockIO()); } public void play(IO io) { boolean winCondition = false; Board board = new Board(); int inputNum; String suppliedInput; while (winCondition == false){ // main game here // TODO add actual thingies here io.println("+----+-------+-------+-------+-------+-------+-------+----+"); io.println("| P2 | 6[ 4] | 5[ 4] | 4[ 4] | 3[ 4] | 2[ 4] | 1[ 4] | 0 |"); io.println("| |-------+-------+-------+-------+-------+-------| |"); io.println("| 0 | 1[ 4] | 2[ 4] | 3[ 4] | 4[ 4] | 5[ 4] | 6[ 4] | P1 |"); io.println("+----+-------+-------+-------+-------+-------+-------+----+"); io.println("Player 1's turn - Specify house number or 'q' to quit: "); // player 1's turn suppliedInput = io.readFromKeyboard("Player 1's turn - Specify house number or 'q' to quit: "); if (suppliedInput.toLowerCase() == "q"){ break; } inputNum = Integer.parseInt(suppliedInput); board.MoveSeeds(inputNum -1, 1); // player 2's turn suppliedInput = io.readFromKeyboard("Player 1's turn - Specify house number or 'q' to quit: "); if (suppliedInput.toLowerCase() == "q"){ break; } inputNum = Integer.parseInt(suppliedInput); board.MoveSeeds(inputNum -1, 2); // TODO remove this later winCondition = true; } } public void defaultPrint(IO io){ // Replace what's below with your implementation io.println("+----+-------+-------+-------+-------+-------+-------+----+"); io.println("| P2 | 6[ 4] | 5[ 4] | 4[ 4] | 3[ 4] | 2[ 4] | 1[ 4] | 0 |"); io.println("| |-------+-------+-------+-------+-------+-------| |"); io.println("| 0 | 1[ 4] | 2[ 4] | 3[ 4] | 4[ 4] | 5[ 4] | 6[ 4] | P1 |"); io.println("+----+-------+-------+-------+-------+-------+-------+----+"); io.println("Player 1's turn - Specify house number or 'q' to quit: "); } }
true
aa8b0bcc1a13a57ff29d4ad714b32c35418202c6
Java
manningb/java-programming
/src/practical1/q2.java
UTF-8
679
3.125
3
[]
no_license
package practical1; import java.util.Scanner; public class q2 { public static void main(String[] args) { Scanner years = new Scanner(System.in); // Create a Scanner object for radius System.out.println("Enter a number of years"); int yearsIn = years.nextInt(); // Read user input final int currentPopulation = 312032486; int secondsPerYear = yearsIn * 365 * 24 * 60 * 60; int births = secondsPerYear/7; int deaths = secondsPerYear/13; int immigrants = secondsPerYear/45; int futurePopulation = currentPopulation + births + deaths + immigrants; System.out.println(futurePopulation); } }
true
5b264d5db0715dc8f30032ed790b3f3eb6e12d77
Java
nikalomoiris/example-rest-api
/src/main/java/app/mvc/resource/OrderResourceAssembler.java
UTF-8
1,090
2.515625
3
[]
no_license
package app.mvc.resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.EntityLinks; import org.springframework.hateoas.Link; import org.springframework.stereotype.Component; import app.mvc.domain.Order; @Component public class OrderResourceAssembler extends ResourceAssembler<Order, OrderResource> { // Provides helper methods that provide for the construction of links // using just the domain object type. This is accomplished by having // a REST endpoint class use the@ExposesResourceFor(Class domainClass) // annotation @Autowired protected EntityLinks entityLinks; private static final String UPDATE_REL = "update"; private static final String DELETE_REL = "delete"; @Override public OrderResource toResource(Order order) { OrderResource resource = new OrderResource(order); final Link selfLink = entityLinks.linkToSingleResource(order); resource.add(selfLink.withSelfRel()); resource.add(selfLink.withRel(UPDATE_REL)); resource.add(selfLink.withRel(DELETE_REL)); return resource; } }
true
04f2a8db2288cb7ae0549d0f6ddffb78981882f7
Java
hellfire3d/farctool3
/src/main/java/ennuo/craftworld/resources/structs/gfxmaterial/Wire.java
UTF-8
919
2.828125
3
[]
no_license
package ennuo.craftworld.resources.structs.gfxmaterial; import ennuo.craftworld.memory.Data; import ennuo.craftworld.memory.Output; public class Wire { public int boxFrom, boxTo; public byte portFrom, portTo; public Wire(Data data) { boxFrom = data.int32(); boxTo = data.int32(); portFrom = data.int8(); portTo = data.int8(); if (data.isEncoded()) boxFrom /= 2; if (data.isEncoded()) boxTo /= 2; data.bytes(5); // Padding bytes? } public static Wire[] array(Data data) { int count = data.int32(); Wire[] out = new Wire[count]; for (int i = 0; i < count; ++i) out[i] = new Wire(data); return out; } public void serialize(Output output) { output.int32(boxFrom); output.int32(boxTo); output.int8(portFrom); output.int8(portTo); output.pad(5); } }
true
a630f4ebcd94bdebf776bed7544cfe462158bd72
Java
huaweicloud/huaweicloud-sdk-java-v3
/services/osm/src/main/java/com/huaweicloud/sdk/osm/v2/model/IncidentInfoV2.java
UTF-8
9,336
1.59375
2
[ "Apache-2.0" ]
permissive
package com.huaweicloud.sdk.osm.v2.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.function.Consumer; /** * IncidentInfoV2 */ public class IncidentInfoV2 { @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "xcustomer_id") private String xcustomerId; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "xcustomer_name") private String xcustomerName; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "status") private Integer status; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "incident_id") private String incidentId; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "business_type_name") private String businessTypeName; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "incident_type_name") private String incidentTypeName; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "customer_id") private String customerId; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "dc_name") private String dcName; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "simple_description") private String simpleDescription; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "create_time") private OffsetDateTime createTime; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "label_list") private List<LabelInfo> labelList = null; public IncidentInfoV2 withXcustomerId(String xcustomerId) { this.xcustomerId = xcustomerId; return this; } /** * 子用户id * @return xcustomerId */ public String getXcustomerId() { return xcustomerId; } public void setXcustomerId(String xcustomerId) { this.xcustomerId = xcustomerId; } public IncidentInfoV2 withXcustomerName(String xcustomerName) { this.xcustomerName = xcustomerName; return this; } /** * 子用户名称 * @return xcustomerName */ public String getXcustomerName() { return xcustomerName; } public void setXcustomerName(String xcustomerName) { this.xcustomerName = xcustomerName; } public IncidentInfoV2 withStatus(Integer status) { this.status = status; return this; } /** * 状态 0:待受理 1:处理中 2:待确认结果 3:已完成 4:已撤销 12:无效 17: 待反馈 * minimum: 0 * maximum: 20 * @return status */ public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public IncidentInfoV2 withIncidentId(String incidentId) { this.incidentId = incidentId; return this; } /** * 工单id * @return incidentId */ public String getIncidentId() { return incidentId; } public void setIncidentId(String incidentId) { this.incidentId = incidentId; } public IncidentInfoV2 withBusinessTypeName(String businessTypeName) { this.businessTypeName = businessTypeName; return this; } /** * 问题类型名称 * @return businessTypeName */ public String getBusinessTypeName() { return businessTypeName; } public void setBusinessTypeName(String businessTypeName) { this.businessTypeName = businessTypeName; } public IncidentInfoV2 withIncidentTypeName(String incidentTypeName) { this.incidentTypeName = incidentTypeName; return this; } /** * 工单类型名称 * @return incidentTypeName */ public String getIncidentTypeName() { return incidentTypeName; } public void setIncidentTypeName(String incidentTypeName) { this.incidentTypeName = incidentTypeName; } public IncidentInfoV2 withCustomerId(String customerId) { this.customerId = customerId; return this; } /** * 客户id * @return customerId */ public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } public IncidentInfoV2 withDcName(String dcName) { this.dcName = dcName; return this; } /** * 区域名称 * @return dcName */ public String getDcName() { return dcName; } public void setDcName(String dcName) { this.dcName = dcName; } public IncidentInfoV2 withSimpleDescription(String simpleDescription) { this.simpleDescription = simpleDescription; return this; } /** * 简要描述 * @return simpleDescription */ public String getSimpleDescription() { return simpleDescription; } public void setSimpleDescription(String simpleDescription) { this.simpleDescription = simpleDescription; } public IncidentInfoV2 withCreateTime(OffsetDateTime createTime) { this.createTime = createTime; return this; } /** * 创建时间 * @return createTime */ public OffsetDateTime getCreateTime() { return createTime; } public void setCreateTime(OffsetDateTime createTime) { this.createTime = createTime; } public IncidentInfoV2 withLabelList(List<LabelInfo> labelList) { this.labelList = labelList; return this; } public IncidentInfoV2 addLabelListItem(LabelInfo labelListItem) { if (this.labelList == null) { this.labelList = new ArrayList<>(); } this.labelList.add(labelListItem); return this; } public IncidentInfoV2 withLabelList(Consumer<List<LabelInfo>> labelListSetter) { if (this.labelList == null) { this.labelList = new ArrayList<>(); } labelListSetter.accept(this.labelList); return this; } /** * 标签列表 * @return labelList */ public List<LabelInfo> getLabelList() { return labelList; } public void setLabelList(List<LabelInfo> labelList) { this.labelList = labelList; } @Override public boolean equals(java.lang.Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } IncidentInfoV2 that = (IncidentInfoV2) obj; return Objects.equals(this.xcustomerId, that.xcustomerId) && Objects.equals(this.xcustomerName, that.xcustomerName) && Objects.equals(this.status, that.status) && Objects.equals(this.incidentId, that.incidentId) && Objects.equals(this.businessTypeName, that.businessTypeName) && Objects.equals(this.incidentTypeName, that.incidentTypeName) && Objects.equals(this.customerId, that.customerId) && Objects.equals(this.dcName, that.dcName) && Objects.equals(this.simpleDescription, that.simpleDescription) && Objects.equals(this.createTime, that.createTime) && Objects.equals(this.labelList, that.labelList); } @Override public int hashCode() { return Objects.hash(xcustomerId, xcustomerName, status, incidentId, businessTypeName, incidentTypeName, customerId, dcName, simpleDescription, createTime, labelList); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class IncidentInfoV2 {\n"); sb.append(" xcustomerId: ").append(toIndentedString(xcustomerId)).append("\n"); sb.append(" xcustomerName: ").append(toIndentedString(xcustomerName)).append("\n"); sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append(" incidentId: ").append(toIndentedString(incidentId)).append("\n"); sb.append(" businessTypeName: ").append(toIndentedString(businessTypeName)).append("\n"); sb.append(" incidentTypeName: ").append(toIndentedString(incidentTypeName)).append("\n"); sb.append(" customerId: ").append(toIndentedString(customerId)).append("\n"); sb.append(" dcName: ").append(toIndentedString(dcName)).append("\n"); sb.append(" simpleDescription: ").append(toIndentedString(simpleDescription)).append("\n"); sb.append(" createTime: ").append(toIndentedString(createTime)).append("\n"); sb.append(" labelList: ").append(toIndentedString(labelList)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
true
704e54331de6fd86c6052739aee90f4d7a835c8d
Java
twrandunuge/Demo-221-MavenTestNGGitJenkins
/src/demo221MavenTestNGGitJenkins/SFDCTest.java
UTF-8
1,472
2.015625
2
[]
no_license
package demo221MavenTestNGGitJenkins; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import com.relevantcodes.extentreports.LogStatus; public class SFDCTest extends ReusableMethods{ @BeforeTest public void BeforeTest() { System.out.println("BeforeTest"); } @BeforeClass public void Initialize() { InitializeDriver(); CreateReport(); } @Test @Parameters("browser") public void LoginSFDC() throws InterruptedException { logger = report.startTest("LoginSFDC"); OpenUrl("https://login.salesforce.com"); Thread.sleep(2000); logger.log(LogStatus.INFO, "URL opened successfully"); WebElement Uname = driver.findElement(By.xpath("//input[@id='username']")); EnterText(Uname, "twr@company.com", "Username"); Thread.sleep(7000); WebElement pwd = driver.findElement(By.xpath("//input[@id='password']")); EnterText(pwd, "Lychee@123", "Password"); // pwd.sendKeys("Test4321"); WebElement loginBtn = driver.findElement(By.xpath("//*[@id='Login']")); Click(loginBtn, "Login Button"); // loginBtn.click(); } @AfterClass public void CloseTest() { CloseBrowser(); CloseReport(); } @AfterTest public void AfterTest() { System.out.println("AfterTest"); } }
true
4dded7fe7f1fc4959556cd6068323d2307878c48
Java
TeamMobileTennis/MobileTennis
/MobileTennis/android/src/de/teammt/mobiletennis/game/ui/UIBuilder.java
UTF-8
1,795
2.96875
3
[ "ISC" ]
permissive
package de.teammt.mobiletennis.game.ui; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.utils.Align; import de.teammt.mobiletennis.game.MobileTennis; public class UIBuilder { private UIBuilder(){} /** * Create a Label and return it * @param text The text that will be displayed on the Label * @param font The font of the text * @param width The width of the Label * @param height The height of the Label * @param xPos The x-position of the label * @param yPos The y-position of the label * @return label The label */ public static Label CreateLabel(String text, Label.LabelStyle font, float width, float height, float xPos, float yPos){ Label label = new Label(text, font); label.setAlignment(Align.center); label.setSize(width, height); label.setPosition(xPos, yPos, Align.center); return label; } /** * Create a TextButton and return it * @param text The text displayed on the Button * @param font The font of the text * @param width The width of the button * @param height The height of the button * @param xPos The x-position of the button * @param yPos The y-position of the button * @return button The TextButton */ public static TextButton CreateButton(String text, Label.LabelStyle font, float width, float height, float xPos, float yPos){ TextButton button = new TextButton(text, MobileTennis.skin, "default"); button.getLabel().setStyle(font); button.setSize(width, height); button.setPosition(xPos, yPos, Align.center); return button; } }
true
659abf808bcca059bc83462d1892eef21cf7c61a
Java
baixiufeng/mango
/javax/src/main/java/com/mango/service/FilmService.java
UTF-8
1,403
2.140625
2
[]
no_license
package com.mango.service; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.mango.mapper.FabulousMapper; import com.mango.mapper.FilmMapper; import com.mango.model.Fabulous; import com.mango.model.Film; import com.mango.utils.UuidUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; @Service public class FilmService { @Autowired private FilmMapper mapper; public int insert(Film film){ film.setId(UuidUtil.getUuid32()); film.setCreateTime(new Date()); int result= mapper.insert(film); return result; } public int update(Film film){ film.setUpdateTime(new Date()); int result= mapper.updateByPrimaryKey(film); return result; } public int delete(String id){ int result= mapper.deleteByPrimaryKey(id); return result; } public Film selectfindByid(String id){ Film result= mapper.selectByPrimaryKey(id); return result; } //分页查询用户 public PageInfo<Film> pageInfo(Integer pageNo, Integer pageSize, String uid){ PageHelper.startPage(pageNo,pageSize); List<Film> filmList = mapper.findAll(uid); PageInfo<Film> pagelist = new PageInfo<Film>(filmList); return pagelist; } }
true
6bb73e47337944e071f98ca44483fff614970847
Java
TwinkleStone/KidProject
/app/src/main/java/ddwu/mobile/final_project/ma01_20170993/FragmentHome.java
UTF-8
12,217
1.75
2
[]
no_license
package ddwu.mobile.final_project.ma01_20170993; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.PorterDuff; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.smarteist.autoimageslider.IndicatorAnimations; import com.smarteist.autoimageslider.SliderAnimations; import com.smarteist.autoimageslider.SliderView; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import javax.net.ssl.HttpsURLConnection; import ddwu.mobile.final_project.ma01_20170993.R; import ddwu.mobile.final_project.ma01_20170993.FindEvent.EventDetailActivity; import ddwu.mobile.final_project.ma01_20170993.FindEvent.EventDto; import ddwu.mobile.final_project.ma01_20170993.FindEvent.FindEventActivity; import ddwu.mobile.final_project.ma01_20170993.FindKindergarden.FindKindergardenActivity; import ddwu.mobile.final_project.ma01_20170993.RankBook.RankBookActivity; import ddwu.mobile.final_project.ma01_20170993.VaccinationCalendar.ScheduleActivity; public class FragmentHome extends Fragment implements Button.OnTouchListener{ ImageView img1; ImageView img2; RelativeLayout layout1; RelativeLayout layout2; ScrollView lvscroll; ArrayList<EventDto> eventList; Button btn; Button btnCard; Button btnBook; Button btnSchedule; Button btnMore; public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_home, container, false); lvscroll = v.findViewById(R.id.lvscroll); btn = v.findViewById(R.id.btnFind); btn.setOnTouchListener(this); btnCard = v.findViewById(R.id.btnCard); btnCard.setOnTouchListener(this); btnBook = v.findViewById(R.id.btnBook); btnBook.setOnTouchListener(this); btnSchedule = v.findViewById(R.id.btnSchedule); btnSchedule.setOnTouchListener(this); Intent i = (getActivity()).getIntent(); eventList = i.getParcelableArrayListExtra("eventList"); TextView tvIsFind = v.findViewById(R.id.tvIsFind); TextView tvName1 = v.findViewById(R.id.tvName1); TextView tvName2 = v.findViewById(R.id.tvName2); TextView tvPlace1 = v.findViewById(R.id.tvPlace1); TextView tvPlace2 = v.findViewById(R.id.tvPlace2); img1 = v.findViewById(R.id.imageView1); img2 = v.findViewById(R.id.imageView2); layout1 = v.findViewById(R.id.layout1); layout2 = v.findViewById(R.id.layout2); LinearLayout layout3 = v.findViewById(R.id.layisFind); if(eventList.size() == 0){ tvIsFind.setVisibility(View.VISIBLE); layout3.setVisibility(View.VISIBLE); layout1.setVisibility(View.GONE); layout2.setVisibility(View.GONE); } else { tvIsFind.setVisibility(View.GONE); layout3.setVisibility(View.GONE); layout1.setVisibility(View.VISIBLE); layout2.setVisibility(View.VISIBLE); tvName1.setText(eventList.get(0).getTitle()); tvName2.setText(eventList.get(1).getTitle()); tvPlace1.setText(eventList.get(0).getAddr1()); tvPlace2.setText(eventList.get(1).getAddr1()); layout1.setOnClickListener(clickListener); layout2.setOnClickListener(clickListener); } GetImageAsyncTask imgTask = new GetImageAsyncTask(1); GetImageAsyncTask imgTask2 = new GetImageAsyncTask(2); try{ imgTask.execute(eventList.get(0).getFirstimage()); imgTask2.execute(eventList.get(1).getFirstimage()); }catch(Exception e){ e.printStackTrace(); } btnMore = v.findViewById(R.id.btnMore); btnMore.setOnTouchListener(this); SliderView sliderView = v.findViewById(R.id.imageSlider); SliderAdapterExample adapter = new SliderAdapterExample(getActivity()); sliderView.setSliderAdapter(adapter); sliderView.setIndicatorAnimation(IndicatorAnimations.WORM); //set indicator animation by using SliderLayout.IndicatorAnimations. :WORM or THIN_WORM or COLOR or DROP or FILL or NONE or SCALE or SCALE_DOWN or SLIDE and SWAP!! sliderView.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION); sliderView.setAutoCycleDirection(SliderView.AUTO_CYCLE_DIRECTION_BACK_AND_FORTH); sliderView.setIndicatorSelectedColor(Color.DKGRAY); sliderView.setIndicatorUnselectedColor(Color.GRAY); sliderView.setScrollTimeInSec(4); //set scroll delay in seconds : sliderView.startAutoCycle(); return v; } View.OnClickListener clickListener = new View.OnClickListener(){ @Override public void onClick(View v) { switch (v.getId()){ case R.id.layout1: if(isOnline()) { Intent intent = new Intent(getActivity(), EventDetailActivity.class); intent.putExtra("event", (Serializable) eventList.get(0)); startActivity(intent); }else{ Toast.makeText(getActivity(), "인터넷을 연결해주세요.", Toast.LENGTH_SHORT).show(); } break; case R.id.layout2: if(isOnline()) { Intent intent2 = new Intent(getActivity(), EventDetailActivity.class); intent2.putExtra("event", (Serializable) eventList.get(1)); startActivity(intent2); }else{ Toast.makeText(getActivity(), "인터넷을 연결해주세요.", Toast.LENGTH_SHORT).show(); } break; } } }; @Override public boolean onTouch(View v, MotionEvent event) { Button i = null; int tmp = -1; switch (v.getId()) { case R.id.btnFind: i = btn; tmp = 0; break; case R.id.btnCard: i = btnCard; tmp = 1; break; case R.id.btnBook: i = btnBook; tmp = 2; break; case R.id.btnSchedule: i = btnSchedule; tmp = 3; break; case R.id.btnMore: i = btnMore; tmp = 4; break; } switch(event.getAction()){ case MotionEvent.ACTION_DOWN: lvscroll.requestDisallowInterceptTouchEvent(true); i.getBackground().setColorFilter(0x66ffffff, PorterDuff.Mode.SRC_ATOP); break; case MotionEvent.ACTION_UP: i.getBackground().clearColorFilter(); lvscroll.requestDisallowInterceptTouchEvent(false); if(tmp == 0) { Intent intent = new Intent(getActivity(), FindKindergardenActivity.class); startActivity(intent); } else if(tmp == 1){ Intent intent = new Intent(getActivity(), CardActivity.class); startActivity(intent); }else if(tmp == 2){ if(isOnline()) { Intent intent = new Intent(getActivity(), RankBookActivity.class); startActivity(intent); }else{ Toast.makeText(getActivity(), "인터넷을 연결해주세요.", Toast.LENGTH_SHORT).show(); } }else if(tmp == 3){ Intent intent = new Intent(getActivity(), ScheduleActivity.class); startActivity(intent); }else if(tmp == 4){ Intent intent = new Intent(getActivity(), FindEventActivity.class); intent.putParcelableArrayListExtra("eventList", eventList); startActivity(intent); } break; } return true; } /* 행사 이미지를 다운로드 후 이미지뷰에 표시하는 AsyncTask */ class GetImageAsyncTask extends AsyncTask<String, Void, Bitmap> { String imageAddress; int index; public GetImageAsyncTask(int index) { this.index = index; } @Override protected Bitmap doInBackground(String... params) { imageAddress = params[0]; Bitmap result = downloadImage(imageAddress); return result; } @Override protected void onPostExecute(Bitmap bitmap) { /*작성할 부분*/ /*네트워크에서 다운 받은 이미지 파일을 이미지뷰에 지정*/ if(bitmap != null){ switch (index) { case 1: img1.setImageBitmap(bitmap); break; case 2: img2.setImageBitmap(bitmap); break; } }else{ switch (index) { case 1: img1.setImageResource(R.drawable.noimage); break; case 2: img2.setImageResource(R.drawable.noimage); break; } } } /* 주소를 전달받아 bitmap 다운로드 후 반환 */ private Bitmap downloadImage(String address) { HttpURLConnection conn = null; InputStream stream = null; Bitmap result = null; try { URL url = new URL(address); conn = (HttpURLConnection)url.openConnection(); stream = getNetworkConnection(conn); result = readStreamToBitmap(stream); if (stream != null) stream.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) conn.disconnect(); } return result; } /* URLConnection 을 전달받아 연결정보 설정 후 연결, 연결 후 수신한 InputStream 반환 */ private InputStream getNetworkConnection(HttpURLConnection conn) throws Exception { conn.setReadTimeout(3000); conn.setConnectTimeout(3000); conn.setRequestMethod("GET"); conn.setDoInput(true); if (conn.getResponseCode() != HttpsURLConnection.HTTP_OK) { throw new IOException("HTTP error code: " + conn.getResponseCode()); } return conn.getInputStream(); } /* InputStream을 전달받아 비트맵으로 변환 후 반환 */ private Bitmap readStreamToBitmap(InputStream stream) { return BitmapFactory.decodeStream(stream); } } /* 네트워크 관련 메소드 */ /* 네트워크 환경 조사 */ private boolean isOnline() { ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); return (networkInfo != null && networkInfo.isConnected()); } }
true
ebee90e9266404b5f1ef937dddfde805f3df2ccc
Java
astridyang/sp19-s61b
/proj1b/Palindrome.java
UTF-8
971
3.828125
4
[]
no_license
public class Palindrome { public Deque<Character> wordToDeque(String word) { int length = word.length(); LinkedListDeque<Character> wd = new LinkedListDeque<>(); for (int i = 0; i < length; i++) { wd.addLast(word.charAt(i)); } return (Deque<Character>) wd; } public boolean isPalindrome(String word) { int length = word.length(); int middle = length / 2; for (int i = 0; i < middle; i++) { if (word.charAt(i) != word.charAt(length - i - 1)) { return false; } } return true; } public boolean isPalindrome(String word, CharacterComparator cc) { int length = word.length(); int middle = length / 2; for (int i = 0; i < middle; i++) { if (!cc.equalChars(word.charAt(i), word.charAt(length - i - 1))) { return false; } } return true; } }
true
02154ab9ecf8ce78826c208c824ef2bb33f90107
Java
baharzarin/OSMGraph
/VisualNode.java
UTF-8
179
2.265625
2
[]
no_license
// Copyright 2016 Bahar Zarin package project; public class VisualNode { public double x; public double y; public VisualNode(double x,double y) { this.x = x; this.y = y; } }
true
a610366c7e8a27bf9345f29783be48d82b30905e
Java
hellolujian/course-design
/library_reservation/src/main/java/cn/edu/ujs/service/SeatService.java
UTF-8
1,276
2.421875
2
[]
no_license
package cn.edu.ujs.service; import cn.edu.ujs.entity.Seat; import java.util.List; /** * Created by DELL on 2017/12/25. */ public interface SeatService { /**添加(更新)一个座位*/ Seat save(Seat seat); /**修改座位状态信息*/ void updateSeatStatus(String SeatId, Integer seatStatus); /**根据座位号查询*/ public Seat findOne(String seatId); /**根据座位状态查询*/ public List<Seat> findBySeatStatus(Integer seatStatus); /**查询没有被释放的座位*/ public List<Seat> findBySeatStatusNot(Integer seatStatus); /**系统自动分配一个座位*/ public Seat getOneSeat(Integer seatStatus); /**系统根据阅览室自动分配一个座位*/ public Seat getOneSeatByReadingRoom(String readingRoomId); /**查询所有座位*/ public List<Seat> findAll(); /**根据阅览室编号查询*/ public List<Seat> findByReadingRoomId(String readingRoomId); /**查询阅览室里可用的座位数量*/ public Integer findUsableCountByReadingRoom(Integer seatStatus, String readingRoomId); /**删除一个座位*/ public Integer deleteOneSeat(String seatId); /**批量删除座位*/ public Integer deleteManySeats(List<String> seatIdList); }
true
f4753cf7b10ae6c1cd6f87ed0ef210bbdc504f13
Java
Firwanaa/Inventory-Tracker---JavaFX
/src/firwanaa/InventoryList.java
UTF-8
836
2.859375
3
[]
no_license
/* * 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 firwanaa; import java.util.*; /** * * @author QQ */ public class InventoryList { private ArrayList<Inventory> invList = new ArrayList<>(); public InventoryList() { } public void add(Inventory inventory) { invList.add(inventory); } public Inventory get(int index) { return invList.get(index); } public int length() { return invList.size(); } @Override public String toString() { StringBuilder s = new StringBuilder(); for(Inventory i : invList){ s.append(i.toString()); s.append("\n"); } return s.toString(); } }
true
5e87b50adf248287e365d8310950734dd1b92deb
Java
BaronND/opslabJava
/02_JavaEE/src/main/java/JavaXml/DOM/DomRead1.java
UTF-8
1,308
2.859375
3
[]
no_license
package JavaXml.DOM; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class DomRead1 { public static void main(String[] args) { System.out.println(System.getProperty("user.dir")); //利用DOM解析XML的一般步骤 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder build = null; try { build = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } //获取Document对象 Document doc = null; try { doc = build.parse("src/JavaXml/xml/DomRead1.xml"); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } //查找name节点 NodeList nameList = doc.getElementsByTagName("name"); //输出nameList下的第一个子节点的文本内容 System.out.println(nameList.item(0).getFirstChild().getNodeValue()); } }
true
bd743a6f8576b57abe4575fdc0013021e0686cca
Java
ashokkumar-sarvepalli/java-assignments
/src/assignment/objectaccessencapsulationstatic/problem1/Shipment.java
UTF-8
551
2.703125
3
[]
no_license
package assignment.objectaccessencapsulationstatic.problem1; public class Shipment { private int id; private String shipperName; private String modeofTransportation; private float totalWeight; private String arrivalPort; private String departurePort; static int nextShipmentid = 1000; @Override public String toString() { return String.format("%-15s%-15s%-25s%-20s%-20s%-15s", this.id, this.shipperName, this.modeofTransportation, this.totalWeight + "Kg", this.arrivalPort, this.departurePort); } }
true
5559d0139f117f828edd15e985ace7fe67ad7c65
Java
jx1803/DM-boysRepository
/chengS/src/org/great/bean/PhaDrugBean.java
UTF-8
1,603
2.265625
2
[]
no_license
package org.great.bean; import org.springframework.stereotype.Component; //药房药品表 @Component public class PhaDrugBean { private int phaDrugId;// 药房药品id private int drugId;// 药品编号 private int drugNum;// 数量 private int useableId;// 停用启用状态 private long minimum;// 底限 private long maximum;//上限值 private StoDrugBean stoDrugBean;//药品信息 private String useable;//可用状态 public PhaDrugBean() { super(); } public int getPhaDrugId() { return phaDrugId; } public void setPhaDrugId(int phaDrugId) { this.phaDrugId = phaDrugId; } public int getDrugId() { return drugId; } public void setDrugId(int drugId) { this.drugId = drugId; } public int getDrugNum() { return drugNum; } public void setDrugNum(int drugNum) { this.drugNum = drugNum; } public int getUseableId() { return useableId; } public void setUseableId(int useableId) { this.useableId = useableId; } public StoDrugBean getStoDrugBean() { return stoDrugBean; } public void setStoDrugBean(StoDrugBean stoDrugBean) { this.stoDrugBean = stoDrugBean; } public long getMinimum() { return minimum; } public void setMinimum(long minimum) { this.minimum = minimum; } public long getMaximum() { return maximum; } public void setMaximum(long maximum) { this.maximum = maximum; } public String getUseable() { return useable; } public void setUseable(String useable) { this.useable = useable; } }
true
9e4085b61b11798a70d308f21976174c5522a205
Java
HJagpal1/IMS-Project
/src/main/java/com/qa/project/service/ItemsService.java
UTF-8
606
2.34375
2
[ "MIT" ]
permissive
package com.qa.project.service; import java.util.List; import com.qa.project.persistence.dao.Dao; import com.qa.project.persistence.domain.Items; public class ItemsService implements CrudService<Items>{ Dao<Items> itemDao; public ItemsService(Dao<Items> itemDao) { this.itemDao = itemDao; } @Override public List<Items> readAll() { return itemDao.readAll(); } @Override public void create(Items item) { itemDao.create(item); } @Override public void update(long id, Items item) { itemDao.update(id, item); } @Override public void delete(long id) { itemDao.delete(id); } }
true
eff44e67576d61cd0f071ecf4614bcfccdd42b51
Java
zyy68/JavaHomeWork
/demo_homeworks/src/com/第3章/demo/MethodsExp5.java
GB18030
788
3.734375
4
[]
no_license
/** * *MethodsExp5.java * *copyright@ sylvia.zhao Sylvia.Zhao * *created on 20181113 10:47:51 * */ package com.3.demo; /** * @author sylvia.zhao * */ public class MethodsExp5 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int isum; double dsum; isum=add(3, 4); System.out.println(isum); isum = add(23, 34, 45); System.out.println(isum); dsum = add(3.14, 8.13); System.out.println(isum); } //أһбһֵҲͬ static int add(int x,int y){ return x+y; } static int add(int x,int y,int z){ return x+y+z; } static double add(double x,double y){ return x+y; } }
true
fed10f4ad69a26ff641939a0448773cec15ef72d
Java
john15020113/KF5012-Capytec
/ChangePassword.java
UTF-8
2,226
2.796875
3
[]
no_license
package capytec; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.JButton; import javax.swing.JPasswordField; import java.awt.event.ActionListener; import java.util.Arrays; import java.awt.event.ActionEvent; public class ChangePassword extends JFrame { private JPanel contentPane; private JPasswordField password; private JPasswordField rePassword; private DatabaseConn database = new DatabaseConn(); /** * Create the frame. */ public ChangePassword(int id) { setTitle("Change Password"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 367, 157); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblNewPassword = new JLabel("New Password:"); lblNewPassword.setBounds(21, 21, 124, 14); contentPane.add(lblNewPassword); JLabel lblConfirmPassword = new JLabel("Confirm Password:"); lblConfirmPassword.setBounds(21, 59, 124, 14); contentPane.add(lblConfirmPassword); JButton btnChangePassword = new JButton("Change Password"); btnChangePassword.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (Arrays.equals(password.getPassword(), rePassword.getPassword())) { System.out.println(id); if (database.changePassword(id, new String(password.getPassword()))) { JOptionPane.showMessageDialog(null, "Password successfully Changed!"); } else { JOptionPane.showMessageDialog(null, "Password was not changed!", "error", JOptionPane.ERROR_MESSAGE); } } else { } } }); btnChangePassword.setBounds(168, 87, 149, 23); contentPane.add(btnChangePassword); password = new JPasswordField(); password.setBounds(136, 18, 181, 20); contentPane.add(password); rePassword = new JPasswordField(); rePassword.setBounds(136, 56, 181, 20); contentPane.add(rePassword); } }
true
d0314f8bc11e0ee37e64e72c47a94b1785acbde3
Java
AppleTrick/KH_Spring
/Spring06_AOP/src/com/test02/Woman.java
UTF-8
207
2.25
2
[]
no_license
package com.test02; public class Woman implements Student { @Override public void classWork() { // TODO Auto-generated method stub System.out.println(" 컴퓨터를 켜서 주식을 본다."); } }
true
a2d0ff52477de286ae544917cabd3cffb9d66475
Java
fatihyakut/ClientServer
/ServerSide/src/server/game/card/Card.java
UTF-8
2,949
3.125
3
[]
no_license
package server.game.card; import server.constant.Constants; public abstract class Card { private int point; private CARD_NUMBER number; private CARD_TYPE type; private String gifPath; public static enum PISHTI_STATE { NO_PISHTI, NORMAL_PISHTI, CLUB2_PISHTI, DIAMOND10_PISHTI, ACE_PISHTI, JACK_PISHTI } public static enum CARD_TYPE { SNAKE('s'), DIAMOND('d'), HEART('h'), CLUB('c'); private char symbol; private CARD_TYPE(char symbol) { this.symbol = symbol; } public char getSymbol() { return symbol; } } public static enum CARD_NUMBER { N2("2", 2), N3("3", 3), N4("4", 4), N5("5", 5), N6("6", 6), N7("7", 7), N8( "8", 8), N9("9", 9), N10("10", 10), NJ("J", 11), NQ("Q", 12), NK( "K", 13), NA("A", 14); private int number; private String symbol; private CARD_NUMBER(String symbol, int number) { this.number = number; this.symbol = symbol; } public int getNumber() { return number; } public String getSymbol() { return symbol; } public int toInt() { return number; } } public Card(String gifPath, CARD_TYPE type, CARD_NUMBER number, int point) { this.point = point; this.number = number; this.gifPath = gifPath; this.type = type; } public static Card create(CARD_TYPE type, CARD_NUMBER number) { Card c = null; StringBuilder gifPath = new StringBuilder(); gifPath.append(Constants.gifPath); gifPath.append(getGifName(type, number)); switch (type) { case DIAMOND: if (number == CARD_NUMBER.N10) { c = new Diamond10Card(gifPath.toString(), type, number); return c; } break; case CLUB: if (number == CARD_NUMBER.N2) { c = new Club2Card(gifPath.toString(), type, number); return c; } break; default: break; } switch (number) { case NJ: c = new JackCard(gifPath.toString(), type, number); return c; case NA: c = new AceCard(gifPath.toString(), type, number); return c; default: break; } c = new GeneralCard(gifPath.toString(), type, number); return c; } public CARD_TYPE getType() { return type; } private static String getGifName(CARD_TYPE type, CARD_NUMBER number) { if (type != null && number != null) return type.getSymbol() + number.toInt() + ".gif"; return null; } public int getPoint() { return point; } public int getNumber() { return this.number.toInt(); } public String getGifPath() { return gifPath; } public abstract PISHTI_STATE compareTo(Card card); @Override public boolean equals(Object card) { if (card == null || !(card instanceof Card)) return false; if (this.getNumber() == ((Card) card).getNumber()) return true; return false; } @Override public String toString() { return this.type.getSymbol() + " " + this.number.getSymbol() + " CARD"; } }
true
aa897d6644b688c73fdc4049c12d034341920120
Java
anggasenna/MobileProject
/MobileProject/src/main/java/com/example/demo/service/AbsenService.java
UTF-8
1,233
2.265625
2
[]
no_license
/* * 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.example.demo.service; import com.example.demo.dao.*; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.demo.model.*; import com.example.demo.repository.*; /** * * @author lutfi */ @Service public class AbsenService implements AbsenDao{ @Autowired AbsenRepository absenRepository; @Override public List<Absen> getAllAbsen() { List<Absen> absen = new ArrayList<>(); absenRepository.findAll().forEach(absen::add); return absen; } @Override public Absen getById(Long id) { Absen absen = absenRepository.findById(id).get(); return absen; } @Override public void SaveOrUpdate(Absen a) { absenRepository.save(a); } @Override public void deleteAbsen(Long id) { absenRepository.deleteById(id); } @Override public void deleteAbsen(Absen a) { absenRepository.delete(a); } }
true
8002454e805617b12d6c6fa901b3d279e59feba9
Java
manongwudi/springcloud-action
/chapter02-user/src/main/java/com/wudimanong/user/entity/GetSmsCodeReqVo.java
UTF-8
262
1.523438
2
[]
no_license
package com.wudimanong.user.entity; import java.io.Serializable; import lombok.Builder; import lombok.Data; /** * @author joe */ @Data @Builder public class GetSmsCodeReqVo implements Serializable { private String reqId; private String mobileNo; }
true
01a8f0c320fcb36d462aa5116f7da92212298446
Java
lkdevjava/keephealth
/src/com/kh/common/shiro/filter/PermissionFilter.java
UTF-8
1,382
2.203125
2
[]
no_license
package com.kh.common.shiro.filter; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.apache.shiro.web.filter.AccessControlFilter; public class PermissionFilter extends AccessControlFilter { private static Log logger = LogFactory.getLog(PermissionFilter.class); @Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object objcet) throws Exception { // Subject subject = getSubject(request, response); Subject subject = SecurityUtils.getSubject(); HttpServletRequest req = (HttpServletRequest) request; String contextPath = req.getContextPath(); System.out.println(contextPath); String url = req.getRequestURI(); System.out.println(subject.isPermitted(url)); url = StringUtils.replace(url, contextPath, ""); logger.debug("当前请求地址:"+url); subject.isPermitted(url); System.out.println(subject.isPermitted(url)); return false; } @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { return false; } }
true
9803c309f3982cc48f0d6b5f68a74dfb42795f1f
Java
gchq/koryphe
/core/src/test/java/uk/gov/gchq/koryphe/impl/function/ToDateStringTest.java
UTF-8
3,640
2.46875
2
[ "LicenseRef-scancode-proprietary-license", "Apache-2.0" ]
permissive
/* * Copyright 2020-2022 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.gov.gchq.koryphe.impl.function; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import uk.gov.gchq.koryphe.function.FunctionTest; import uk.gov.gchq.koryphe.util.JsonSerialiser; import java.io.IOException; import java.time.Instant; import java.util.Arrays; import java.util.Date; import java.util.TimeZone; import java.util.function.Function; import static org.assertj.core.api.Assertions.assertThat; class ToDateStringTest extends FunctionTest<ToDateString> { private static TimeZone originalTimezone; @BeforeAll public static void beforeClass() { originalTimezone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("UTC")); // For consistency } @AfterAll public static void afterClass() { TimeZone.setDefault(originalTimezone); } @Override protected Class[] getExpectedSignatureInputClasses() { return new Class[] { Date.class }; } @Override protected Class[] getExpectedSignatureOutputClasses() { return new Class[] { String.class }; } @Test @Override public void shouldJsonSerialiseAndDeserialise() throws IOException { // Given Function instance = getInstance(); String json = "{\n" + "\t\"class\": \"uk.gov.gchq.koryphe.impl.function.ToDateString\",\n" + "\t\"format\": \"YYYY-MM-dd HH:mm:ss.SSS\"\n" + "}"; // When String serialised = JsonSerialiser.serialise(instance); ToDateString deserialised = JsonSerialiser.deserialise(json, ToDateString.class); // Then JsonSerialiser.assertEquals(json, serialised); assertThat(deserialised).isEqualTo(instance); } @Override protected ToDateString getInstance() { return new ToDateString("YYYY-MM-dd HH:mm:ss.SSS"); } @Override protected Iterable<ToDateString> getDifferentInstancesOrNull() { return Arrays.asList( new ToDateString(), new ToDateString("dd-MMM-yy hh:mm:ss") ); } @Test public void shouldConvertDateToStringAccordingToFormat() { // Given ToDateString instance = getInstance(); // When String dateString = instance.apply(Date.from(Instant.EPOCH)); // Then assertThat(dateString).isEqualTo("1970-01-01 00:00:00.000"); } @Test public void shouldUseDefaultFormatIfNoneAreGiven() { // Given ToDateString instance = new ToDateString(); // When String dateString = instance.apply(Date.from(Instant.EPOCH)); // Then assertThat(dateString).isEqualTo("1970-01-01T00:00:00Z"); } @Test public void shouldReturnNullIfInputIsNull() { // Given ToDateString instance = new ToDateString(); // When String dateString = instance.apply(null); // Then assertThat(dateString).isNull(); } }
true
8eec1d51908b49a119f72a051d3642d012abf9c9
Java
praveenmunagapati/ms-registration-server
/externalModules/scharp/peptide/src/org/scharp/atlas/peptide/model/Peptide.java
UTF-8
5,467
2.03125
2
[ "MIT" ]
permissive
package org.scharp.atlas.peptide.model; import java.util.List; import java.util.Map; /** * Maps to a row from the peptide_view DB view. * * @version $Id: Peptide.java 26214 2013-05-02 02:49:04Z s.langley $ */ public class Peptide { private String peptide_id; // private String btk_code; private String peptide_sequence; private String child; private boolean parent; private String qc_passed; private String lanl_date; private String protein_cat_desc; private Integer protein_cat_id; //private String linked_parent; private String protein_align_pep; private List<PeptideGroup> peptideGroups; private List<PeptidePool> peptidePools; public List<PeptidePool> getPeptidePools() { return peptidePools; } public void setPeptidePools(List<PeptidePool> peptidePools) { this.peptidePools = peptidePools; } /** * @return the protein_align_pep */ public String getProtein_align_pep() { return protein_align_pep; } /** * @param protein_align_pep the protein_align_pep to set */ public void setProtein_align_pep(String protein_align_pep) { this.protein_align_pep = protein_align_pep; } /** * @return the peptide_id */ public String getPeptide_id() { return peptide_id; } /** * @param peptide_id the peptide_id to set */ public void setPeptide_id(String peptide_id) { this.peptide_id = peptide_id; } /** * @return the btk_code */ // public String getBtk_code() { // return btk_code; // } /** * @param btk_code the btk_code to set */ /* public void setBtk_code(String btk_code) { this.btk_code = btk_code; }*/ /** * @return the peptide_sequence */ public String getPeptide_sequence() { return peptide_sequence; } /** * @param peptide_sequence the peptide_sequence to set */ public void setPeptide_sequence(String peptide_sequence) { this.peptide_sequence = peptide_sequence; } /** * @return the child */ public String getChild() { return child; } /** * @param child the child to set */ public void setChild(String child) { this.child = child; } /** * @return the qc_passed */ public String getQc_passed() { return qc_passed; } /** * @param qc_passed the qc_passed to set */ public void setQc_passed(String qc_passed) { this.qc_passed = qc_passed; } public String getLanl_date() { return lanl_date; } public void setLanl_date(String lanl_date) { this.lanl_date = lanl_date; } /** * @return the protein_cat_desc */ public String getProtein_cat_desc() { return protein_cat_desc; } /** * @param protein_cat_desc the protein_cat_desc to set */ public void setProtein_cat_desc(String protein_cat_desc) { this.protein_cat_desc = protein_cat_desc; } /** * @return the linked_parent */ /* public String getLinked_parent() { return linked_parent; }*/ /** * linked_parent the linked_parent to set */ /* public void setLinked_parent(String linked_parent) { this.linked_parent = linked_parent; }*/ public Integer getProtein_cat_id() { return protein_cat_id; } public void setProtein_cat_id(Integer protein_cat_id) { this.protein_cat_id = protein_cat_id; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("Peptide["); sb.append("peptide_id:").append(this.getPeptide_id()).append(", "); //sb.append("btk_code:").append(this.getBtk_code()).append(", "); sb.append("peptide_sequence:").append(this.getPeptide_sequence()).append(", "); sb.append("protein_cat_desc:").append(this.getProtein_cat_desc()).append(", "); sb.append("protein_cat_id:").append(this.getProtein_cat_id()).append(", "); sb.append("child:").append(this.getChild()).append(", "); sb.append("lanl_date:").append(this.getLanl_date()).append(", "); sb.append("qc_passed:").append(this.getQc_passed()).append(", "); //sb.append("linked_parent:").append(this.getLinked_parent()).append(", "); sb.append("protein_align_pep:").append(this.getProtein_align_pep()); if (getPeptideGroups() != null) { sb.append(", PeptideGroups("); for (PeptideGroup group : getPeptideGroups()) { sb.append(group.getPeptide_group_id()).append(","); } sb.append(")"); } sb.append("]"); return sb.toString(); } /** * @return the peptideGroups */ public List<PeptideGroup> getPeptideGroups() { return peptideGroups; } /** * @param peptideGroups the peptideGroups to set */ public void setPeptideGroups(List<PeptideGroup> peptideGroups) { this.peptideGroups = peptideGroups; } public boolean isParent() { return parent; } public void setParent(boolean parent) { this.parent = parent; } }
true
124467f19003922c0bb2466e39182c4f47727d02
Java
noureddinsouad/Observatoire
/Observatiore/src/main/java/ma/observatoire/service/CooperativeServiceImpl.java
UTF-8
8,416
2.0625
2
[]
no_license
package ma.observatoire.service; import java.sql.Date; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TemporalType; import javax.persistence.TypedQuery; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import ma.observatoire.config.JwtRequestFilter; import ma.observatoire.dao.BrancheDao; import ma.observatoire.dao.ICooperativeDao; import ma.observatoire.dao.ProvinceDao; import ma.observatoire.dao.RegionDao; import ma.observatoire.dao.SecteurDao; import ma.observatoire.dao.UserDao; import ma.observatoire.entitie.Cooperative; import ma.observatoire.entitie.Region; import ma.observatoire.model.CooperativeDTO; @Repository public class CooperativeServiceImpl implements CooperativeService { @PersistenceContext private EntityManager em; private ICooperativeDao cooperativeDao; private RegionDao regionDao; private ProvinceDao provinceDao; private BrancheDao brancheDao; private SecteurDao secteurDao; private UserDao userDao; private JwtRequestFilter jwtRequestFilter; @Autowired public CooperativeServiceImpl(ICooperativeDao cooperativeDao, RegionDao regionDao, ProvinceDao provinceDao, BrancheDao brancheDao, SecteurDao secteurDao, UserDao userDao,JwtRequestFilter jwtRequestFilter) { this.cooperativeDao = cooperativeDao; this.regionDao = regionDao; this.provinceDao = provinceDao; this.brancheDao = brancheDao; this.secteurDao = secteurDao; this.userDao = userDao; this.jwtRequestFilter=jwtRequestFilter; } public ArrayList<Object[]> tets() { TypedQuery<Object[]> query = em.createQuery("select c.region, c.idRegion from Region c", Object[].class); return (ArrayList<Object[]>) query.getResultList(); } public List<Cooperative> list() { // TODO Auto-generated method stub return cooperativeDao.findAll(); } @Transactional public Cooperative create(CooperativeDTO cooperative) { Cooperative newCooperative=new Cooperative(); newCooperative.setAdresseActuelle(cooperative.getAdresseActuelle()); newCooperative.setIdSecteur(secteurDao.findBySecteur(cooperative.getSecteur())); newCooperative.setBranche(brancheDao.findByBranche(cooperative.getBranche())); java.util.Date date =new java.util.Date(); newCooperative.setDateCreation(cooperative.getDateCreation()); newCooperative.setDatedeclaration(date); newCooperative.setFax(cooperative.getFax()); newCooperative.setIdPresident(userDao.findByuserName(jwtRequestFilter.getUsername())); newCooperative.setTelephone(cooperative.getTelephone()); newCooperative.setNom(cooperative.getNom()); newCooperative.setNombreAdherents(cooperative.getNombreAdherents()); newCooperative.setProvince(provinceDao.findByProvince(cooperative.getProvince())); newCooperative.setRegion(regionDao.findByRegion(cooperative.getRegion())); newCooperative.setNumerotpi(cooperative.getNumerotpi()); //newCooperative.setIdCooperative(56555); return cooperativeDao.save(newCooperative); } public Cooperative read(Double id) { // TODO Auto-generated method stub return null; } public void delete(long id) { // TODO Auto-generated method stub } @Override public Cooperative read(long id) { // TODO Auto-generated method stub return null; } public Cooperative update(long id, Cooperative cooperative) { // TODO Auto-generated method stub return null; } public ArrayList<Object[]> CooperativeParSecteur() { TypedQuery<Object[]> query = em.createQuery( "select COUNT(c) ,c.idSecteur.secteur from Cooperative c group by c.idSecteur", Object[].class); return (ArrayList<Object[]>) query.getResultList(); } public List<Object[]> CooperativeParRegion() { TypedQuery<Object[]> query = em .createQuery("select count(c), c.region.region from Cooperative c GROUP BY c.region", Object[].class); List<Object[]> results = query.getResultList(); return results; } public List<Object[]> CooperativeParBranche() { TypedQuery<Object[]> query = em.createQuery( "select count(c), c.branche.branche from Cooperative c GROUP BY c.branche", Object[].class); List<Object[]> results = query.getResultList(); return results; } public List<Object[]> NombreAdherentsParSecteur() { TypedQuery<Object[]> query = em.createQuery( "select SUM(c.nombreAdherents), c.idSecteur.secteur from Cooperative c GROUP BY c.idSecteur", Object[].class); List<Object[]> results = query.getResultList(); return results; } public List<Object[]> NombreAdherentsParRegion() { TypedQuery<Object[]> query = em.createQuery( "select SUM(c.nombreAdherents), c.region.region from Cooperative c GROUP BY c.region", Object[].class); List<Object[]> results = query.getResultList(); return results; } public List<Object[]> NombreAdherentsParBranche() { TypedQuery<Object[]> query = em.createQuery( "select SUM(c.nombreAdherents), c.branche.branche from Cooperative c GROUP BY c.branche", Object[].class); List<Object[]> results = query.getResultList(); return results; } public List<Object[]> CapitalParSecteur() { TypedQuery<Object[]> query = em.createQuery( "select SUM(b.capitalActuel), b.idCooperative.idSecteur.secteur from Bilan b GROUP BY b.idCooperative.idSecteur", Object[].class); List<Object[]> results = query.getResultList(); return results; } public List<Object[]> CapitalParRegion() { TypedQuery<Object[]> query = em.createQuery( "select SUM(b.capitalActuel), b.idCooperative.region.region from Bilan b GROUP BY b.idCooperative.region", Object[].class); List<Object[]> results = query.getResultList(); return results; } public List<Object[]> EvolutionCreationParRegion(int year) { TypedQuery<Object[]> query = em.createQuery( "select count(c), c.region.region from Cooperative c WHERE YEAR(c.dateCreation) = ?1 GROUP BY c.region", Object[].class); query.setParameter(1, year); List<Object[]> results = query.getResultList(); return results; } public List<Object[]> EvolutionCreationParSecteur(int year) { TypedQuery<Object[]> query = em.createQuery( "select count(c), c.idSecteur.secteur from Cooperative c WHERE YEAR(c.dateCreation) = ?1 GROUP BY c.idSecteur", Object[].class); query.setParameter(1, year); List<Object[]> results = query.getResultList(); return results; } public List<Object[]> EvolutionCreationParRegion(int year, int month) { TypedQuery<Object[]> query = em.createQuery( "select count(c), c.region.region from Cooperative c WHERE YEAR(c.dateCreation) = ?1 AND MONTH(c.dateCreation)= ?2 GROUP BY c.region", Object[].class); query.setParameter(1, year); query.setParameter(2,month); List<Object[]> results = query.getResultList(); return results; } public List<Object[]> EvolutionCreationParSecteur(int year, int month) { TypedQuery<Object[]> query = em.createQuery( "select count(c), c.idSecteur.secteur from Cooperative c WHERE YEAR(c.dateCreation) = ?1 AND MONTH(c.dateCreation)= ?2 GROUP BY c.idSecteur", Object[].class); query.setParameter(1, year); query.setParameter(2,month); List<Object[]> results = query.getResultList(); return results; } public List<Object[]> NombreCooperativesParRegion(int year) { TypedQuery<Object[]> query = em.createQuery( "select count(c), c.region.region from Cooperative c WHERE YEAR(c.dateCreation)<= ?1 GROUP BY c.Region", Object[].class); query.setParameter(1, year); List<Object[]> results = query.getResultList(); return results; } public List<Object[]> NombreCooperativesParSecteur(int year) { TypedQuery<Object[]> query = em.createQuery( "select count(c), c.idSecteur.secteur from Cooperative c WHERE YEAR(c.dateCreation)<= ?1 GROUP BY c.idSecteur", Object[].class); query.setParameter(1, year); List<Object[]> results = query.getResultList(); return results; } public List<Object[]> NombreCooperativesParRegion(int year, int month) { // TODO Auto-generated method stub return null; } public List<Object[]> NombreCooperativesParSecteur(int year, int month) { // TODO Auto-generated method stub return null; } }
true
5c6bd75757cca8738ff8ad09fc68b277c9506d39
Java
changsha136/testAdminManager
/src/main/java/admin/web/google/GoogleController.java
UTF-8
5,058
2.109375
2
[]
no_license
package admin.web.google; import admin.domains.content.biz.AdminUserService; import admin.domains.content.dao.AdminUserDao; import admin.domains.content.entity.AdminUser; import admin.web.WUC; import admin.web.WebJSONObject; import admin.web.helper.AbstractActionController; import com.warrenstrange.googleauth.GoogleAuthenticatorKey; import com.warrenstrange.googleauth.GoogleAuthenticatorQRGenerator; import javautils.StringUtil; import javautils.encrypt.PasswordUtil; import javautils.http.HttpUtil; import lottery.domains.pool.LotteryDataFactory; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @Controller public class GoogleController extends AbstractActionController{ @Autowired private AdminUserDao adminUserDao; @Autowired private AdminUserService adminUserService; @Autowired private LotteryDataFactory dataFactory; /** * 绑定方法 * 1.首先验证用户要登录后台 * 2.点击绑定谷歌身份验证器器 * 3.判断用户是否已经绑定过认证器,如果已经绑定并且通过验证(isValidate == 1),则不允许重复绑定 * 4.未绑定的用户或者未通过验证的用户,生成二维码和秘钥,传递到前端让用户进行身份绑定 * 5.把绑定信息保存到后台数据库,并且状态为未通过验证(isValidate == 0) * 6.绑定完成后,输入 谷歌校验码 进行身份的验证,通过验证后,更新数据库改变isValidte 为 1。 * 7.提示用户绑定成功 */ /** * 登录校验方法 * 如果已经绑定了google身份验证,并且验证成功的用户,在登录的时候,需要输入动态密码来进行登录验证 * @param response */ @RequestMapping(value = WUC.GOOGLE_AUTH_BIND, method = RequestMethod.POST) @ResponseBody public void GOOGLE_AUTH_BIND(HttpSession session, HttpServletRequest request, HttpServletResponse response) { AdminUser uEntity = super.getGoogleBindUser(session); WebJSONObject json = new WebJSONObject(super.getAdminDataFactory()); if (uEntity == null) { json.set(1, "1-5"); HttpUtil.write(response, json.toString(), HttpUtil.json); return; } if(StringUtils.isEmpty(uEntity.getSecretKey()) || uEntity.getIsValidate() == 0){ GoogleAuthenticatorKey credentials = adminUserService.createCredentialsForUser(uEntity.getUsername()); String otpAuthURL = GoogleAuthenticatorQRGenerator.getOtpAuthURL("", uEntity.getUsername(), credentials); uEntity.setSecretKey(credentials.getKey()); super.setGoogleBindUser(session, uEntity); json.accumulate("qr", otpAuthURL); json.accumulate("secret", credentials.getKey()); json.set(0, "0-5"); }else{ json.set(2, "2-25"); } HttpUtil.write(response, json.toString(), HttpUtil.json); } @RequestMapping(value = WUC.GOOGLE_AUTH_AUTHROIZE, method = RequestMethod.POST) @ResponseBody public void GOOGLE_AUTH_AUTHROIZE(HttpSession session, HttpServletRequest request, HttpServletResponse response) { AdminUser uEntity = super.getGoogleBindUser(session); WebJSONObject json = new WebJSONObject(super.getAdminDataFactory()); if (uEntity == null) { json.set(1, "1-5"); HttpUtil.write(response, json.toString(), HttpUtil.json); return; } int verificationCode = HttpUtil.getIntParameter(request, "vCode"); // 这个是用户输入的 String loginPwd = request.getParameter("loginPwd"); String token = getDisposableToken(session, request); boolean authorize = adminUserService.authoriseUser(uEntity.getUsername(), verificationCode); boolean isValidPwd = PasswordUtil.validatePassword(uEntity.getPassword(), token, loginPwd); if(authorize && isValidPwd){ uEntity.setIsValidate(1); adminUserDao.update(uEntity); super.clearGoogleBindUser(session); json.set(0, "0-5"); } if(!isValidPwd){ json.set(2, "2-5"); }else if(!authorize){ json.set(2, "2-24"); } HttpUtil.write(response, json.toString(), HttpUtil.json); } @RequestMapping(value = WUC.GOOGLE_AUTH_ISBIND, method = RequestMethod.POST) @ResponseBody public void GOOGLE_AUTH_ISBIND(HttpSession session, HttpServletRequest request, HttpServletResponse response) { if (dataFactory.getAdminGoogleConfig().isLoginStatus()) { String username = request.getParameter("username"); if(StringUtil.isNotNull(username)){ AdminUser user = adminUserDao.getByUsername(username); if(user != null && StringUtils.isNotEmpty(user.getSecretKey()) && user.getIsValidate() == 1){ HttpUtil.write(response, Boolean.toString(true)); }else{ HttpUtil.write(response, Boolean.toString(false)); } } } else { HttpUtil.write(response, Boolean.toString(false)); } } }
true
f8065e5a9ae59d62141abd15271eb6dbe70dfdcc
Java
galara/Toscana
/src/com/toscana/dao/implementations/DataSystemCashCountDAOImplementation.java
UTF-8
418
1.640625
2
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.toscana.dao.implementations; import com.toscana.dao.interfaces.DataSystemCashCountDAO; import com.toscana.model.reports.sources.DataSystemCashCount; public class DataSystemCashCountDAOImplementation extends GeneralDAOImplementation<DataSystemCashCount, Integer> implements DataSystemCashCountDAO{ }
true
df91a96d2e9cd2b2dceb774a1c0aec8e34c644b2
Java
wangyu2008/HouseTradingPlatform
/SpringBoot RESTful/src/main/java/connector/DBconnection.java
UTF-8
28,643
2.59375
3
[ "MIT" ]
permissive
package connector; import entity.*; import org.springframework.stereotype.Component; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; public class DBconnection{ // 上传图片 public static String uploadImg(String path, String houseID,String fileName,String style){ if(path==null || houseID==null){ System.out.println("Image is null. Error."); return "null"; } String sql = "insert into house_pic(houseID,fileName,style,path) values('"+houseID+"','"+fileName+"','" +style+"','"+path+"');"; try { Connection connection = jdbcUtils.getConnect(); PreparedStatement preparedStatement = (PreparedStatement)connection.prepareStatement(sql); preparedStatement.executeUpdate(); //System.out.println("Image insert successfully."); preparedStatement.close(); connection.close(); return "success"; }catch (Exception e){ e.printStackTrace(); return "error"; } } // 返回图片列表 public static ArrayList<housePic> selectImg(String houseID){ ArrayList<housePic> bases = new ArrayList<>(); String sql = "select * from house_pic where houseID='"+houseID+"';"; try { Connection connection = jdbcUtils.getConnect(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()){ String houseid= resultSet.getString("houseID"); String fileName = resultSet.getString("fileName"); String style = resultSet.getString("style"); String path = resultSet.getString("path"); bases.add(new housePic(houseid,fileName,style,path)); } //System.out.println("Img return successfully"); statement.close(); resultSet.close(); connection.close(); }catch (Exception e){ e.printStackTrace(); } return bases; } // 删除图片 public static String delImg(String houseID,String fileName){ String sql = "delete from house_pic where houseID='"+houseID+"' and fileName='"+fileName+"';"; try { Connection connection = jdbcUtils.getConnect(); PreparedStatement preparedStatement = (PreparedStatement)connection.prepareStatement(sql); preparedStatement.executeUpdate(); //System.out.println("Image delete successfully."); preparedStatement.close(); connection.close(); return "success"; }catch (Exception e){ e.printStackTrace(); return "error"; } } //上传请求 public static String addRequests(Request request){ if(request==null){ System.out.println("com.company.Request null, can't insert."); return "null"; } String senderID = request.getSenderID(); String receiverID = request.getReceiverID(); String houseID = request.getHouseID(); String phone = request.getPhone(); String location = request.getLocation(); String date = request.getDate(); String time = request.getTime(); String sendTime = request.getSendTime(); String status = request.getStatus(); //System.out.println(date+" "+time); String sql="insert into requests(senderID,receiverID,houseID,phone,location,date,time,sendTime,status) " + "values('"+senderID+"','"+receiverID+"','"+houseID+"','"+phone+"','"+location+"','"+date+"','"+time+"','"+sendTime+"','"+status+"');"; try { Connection connection = jdbcUtils.getConnect(); PreparedStatement preparedStatement = (PreparedStatement)connection.prepareStatement(sql); preparedStatement.executeUpdate(); //System.out.println("Request insert successfully."); preparedStatement.close(); connection.close(); return "success"; }catch (Exception e){ e.printStackTrace(); return "error"; } } //下传请求 返回列表 public static ArrayList<Request> selectRequests(User user){ String recID = user.getPhone(); String type = user.getType(); String sql = ""; if(type=="seller"){ sql = "select * from requests where receiverID='"+recID+"'"; }else if(type=="buyer"){ sql = "select * from requests where senderID='"+recID+"'"; }else{ System.out.println("error, no user type."); return null; } ArrayList<Request> requests = new ArrayList<Request>(); try { Connection connection = jdbcUtils.getConnect(); //System.out.println(connection); Statement statement = (Statement)connection.createStatement(); ResultSet resultSet = (ResultSet)statement.executeQuery(sql); while (resultSet.next()){ String senderID = resultSet.getString("senderID"); String receiverID = resultSet.getString("receiverID"); String houseID = resultSet.getString("houseID"); String date = resultSet.getString("date"); String time = resultSet.getString("time"); String phone = resultSet.getString("phone"); String location = resultSet.getString("location"); String sendTime = resultSet.getString("sendTime"); String status = resultSet.getString("status"); requests.add(new Request(houseID,senderID,receiverID,date,time,sendTime,phone,location,status)); } statement.close(); resultSet.close(); connection.close(); //System.out.println("Return requests successfully."); }catch (Exception e){ e.printStackTrace(); } Collections.sort(requests,new sortReq()); return requests; } //更改请求--未定义 //查询请求 public static String selectRequest(Request request){ String send = request.getSenderID(); String receive = request.getReceiverID(); String houseid = request.getHouseID(); String status = request.getStatus(); String sql = "select * from requests where senderID='"+send+"' and receiverID='"+receive+"' and houseID='" +houseid+"';"; try { Connection connection = jdbcUtils.getConnect(); Statement statement = (Statement)connection.createStatement(); ResultSet resultSet = (ResultSet)statement.executeQuery(sql); while (resultSet.next()){ String senderID = resultSet.getString("senderID"); String receiverID = resultSet.getString("receiverID"); String houseID = resultSet.getString("houseID"); String sta = resultSet.getString("status"); //System.out.println(senderID+" "+send); //System.out.println(receiverID+" "+receive); //System.out.println(houseID+" "+houseid); if (send.equals(senderID) && receive.equals(receiverID) && houseid.equals(houseID) && sta.equals(status)){ return "exist"; }if (send.equals(senderID) && receive.equals(receiverID) && houseid.equals(houseID) && sta.equals("2")){ return "exist"; } } statement.close(); resultSet.close(); connection.close(); //System.out.println("Search requests successfully."); }catch (Exception e){ e.printStackTrace(); return "exist"; } return "new"; } //更改状态 public static String changeRequestStatus(String senderID,String receiverID,String houseID, String choice){ String sql = "update requests set status='"+choice+"' where senderID='"+senderID+"' and receiverID='"+receiverID+"' and houseID='"+houseID+"'"; try { Connection connection = jdbcUtils.getConnect(); PreparedStatement preparedStatement = (PreparedStatement)connection.prepareStatement(sql); preparedStatement.executeUpdate(); //System.out.println("Request status changed successfully."); preparedStatement.close(); connection.close(); }catch (Exception e){ e.printStackTrace(); return "fail"; } return "success"; } //删除请求 public static String delRequests(Request request){ String houseID = request.getHouseID(); String senderID = request.getSenderID(); String receiverID = request.getReceiverID(); String date = request.getDate(); String time = request.getTime(); String sql = "delete from requests where senderID='"+senderID+"'\n" + "and receiverID='"+receiverID+"' and houseID='"+houseID+"' and date='"+date+"' and time='"+time+"';"; try { Connection connection = jdbcUtils.getConnect(); PreparedStatement preparedStatement = (PreparedStatement)connection.prepareStatement(sql); preparedStatement.executeUpdate(); //System.out.println("Delete request successfully."); preparedStatement.close(); connection.close(); return "success"; }catch (Exception e){ e.printStackTrace(); return "fail"; } } //查询用户--登录校验--根据phone和password返回user对象 public static User selectUser(String ph, String pass){ if(ph==null){ System.out.println("error, ID is null."); return null; } String sql = "select * from users where phone='"+ph+"' and password='"+pass+"'"; User user = new User(); try { Connection connection = jdbcUtils.getConnect(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql); String username="", id="", realname="",password="",type="",phone=""; while (resultSet.next()){ username = resultSet.getString("username"); password = resultSet.getString("password"); realname = resultSet.getString("realname"); id = resultSet.getString("id"); phone = resultSet.getString("phone"); type = resultSet.getString("type"); } //System.out.println(phone+" read."); statement.close(); resultSet.close(); connection.close(); user = new User(username,password,realname,id,phone,type); }catch (Exception e){ e.printStackTrace(); } return user; } //查询用户--类中生成临时对象使用 public static User selectUser(String ID){ if(ID==null){ System.out.println("error, ID is null."); return null; } String sql = "select * from users where phone='"+ID+"'"; User user = new User(); try { Connection connection = jdbcUtils.getConnect(); //System.out.println(connection); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql); String username="", id="", realname="",password="",type="",phone=""; while (resultSet.next()){ username = resultSet.getString("username"); password = resultSet.getString("password"); realname = resultSet.getString("realname"); id = resultSet.getString("id"); phone = resultSet.getString("phone"); type = resultSet.getString("type"); } //System.out.println("MySQL read user "+phone); user = new User(username,password,realname,id,phone,type); statement.close(); resultSet.close(); connection.close(); }catch (Exception e){ e.printStackTrace(); } return user; } //上传评价 public static String addComments(Comment comment){ if(comment==null){ return "null"; } String authorID = comment.getAuthorID(); String houseID = comment.getHouseID(); String content = comment.getContent(); String date = comment.getDate(); float score = comment.getScore(); String sql = "insert into comments(authorID,houseID,content,date,score) values('"+authorID+"','"+houseID+"','"+content+"','"+date+"','"+score+"')"; try { Connection connection = jdbcUtils.getConnect(); PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.executeUpdate(); //System.out.println("Comments add successfully."); preparedStatement.close(); connection.close(); return "success"; }catch (Exception e){ e.printStackTrace(); return "error"; } finally{ HouseDBconnection p = new HouseDBconnection(); p.changeScore(houseID); } } //下传评价至房源 public static ArrayList<Comment> selectComments(House house){ String id = house.getHouseID(); String sql = "select * from comments where houseID='"+id+"'"; ArrayList<Comment> comments = new ArrayList<Comment>(); try { Connection connection = jdbcUtils.getConnect(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()){ String authorID = resultSet.getString("authorID"); String houseID = resultSet.getString("houseID"); String content = resultSet.getString("content"); String date = resultSet.getString("date"); String score = resultSet.getString("score"); comments.add(new Comment(authorID,date,houseID,content,score)); } //System.out.println("Return comments to house successfully."); statement.close(); resultSet.close(); connection.close(); }catch (Exception e){ e.printStackTrace(); } Collections.sort(comments,new sortCom()); return comments; } //下传评价至用户 public static ArrayList<Comment> selectComments(Buyer buyer){ String id = buyer.getPhone(); String sql = "select * from comments where authorID='"+id+"'"; ArrayList<Comment> comments = new ArrayList<Comment>(); try { Connection connection = jdbcUtils.getConnect(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()){ String authorID = resultSet.getString("authorID"); String houseID = resultSet.getString("houseID"); String content = resultSet.getString("content"); String date = resultSet.getString("date"); String score = resultSet.getString("score"); comments.add(new Comment(authorID,date,houseID,content,score)); } statement.close(); resultSet.close(); connection.close(); }catch (Exception e){ e.printStackTrace(); } Collections.sort(comments,new sortCom()); return comments; } //删除评价 public static String delComments(Comment comment){ String authorID = comment.getAuthorID(); String houseID = comment.getHouseID(); String content = comment.getContent(); String date = comment.getDate(); String sql = "delete from comments where authorID='"+authorID+"' and houseID='"+houseID+"' and content='"+content+"' and date='"+date+"'"; try { Connection connection = jdbcUtils.getConnect(); PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.executeUpdate(); //System.out.println("Delete comment successfully."); preparedStatement.close(); connection.close(); return "success"; }catch (Exception e){ e.printStackTrace(); return "error"; } } //返回评价数 public static int countComments(String houseID){ String sql = "select count(*) as num from comments where houseID='"+houseID+"';"; int result = 0; try { Connection connection = jdbcUtils.getConnect(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()){ String num = resultSet.getString("num"); result = Integer.parseInt(num); } statement.close(); resultSet.close(); connection.close(); }catch (Exception e){ e.printStackTrace(); } return result; } //返回评价总分 public static float sumComments(String houseID){ String sql = "select sum(score) as sum from comments where houseID='"+houseID+"';"; float result = 0; try { Connection connection = jdbcUtils.getConnect(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()){ float sum = resultSet.getFloat("sum"); result = sum; } statement.close(); resultSet.close(); connection.close(); }catch (Exception e){ e.printStackTrace(); } return result; } //上传消息 public static String addMessages(Message message){ if(message==null){ return "null"; } String name = message.getName(); String content = message.getContent(); String senderID = message.getSenderID(); String receiverID = message.getReceiverID(); String date = message.getDate(); String read = message.getRead(); String sql = "insert into messages(name,senderID,receiverID,content,date,status) values('"+name+"','"+senderID+"','"+receiverID+"','" +content+"','"+date+"','"+read+"')"; try { Connection connection = jdbcUtils.getConnect(); PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.executeUpdate(); //System.out.println("Message upload successfully."); preparedStatement.close(); connection.close(); return "success"; }catch (Exception e){ e.printStackTrace(); return "error"; } } //下传消息 public static ArrayList<Message> selectMessages(User u1, User u2){ if(u1==null || u2==null){ System.out.println("error, no user."); return null; } String id1 = u1.getPhone(); String id2 = u2.getPhone(); String sql = "select * from htpbase.messages\n" + "where (senderID='"+id1+"' and receiverID='"+id2+"') or (senderID='"+id2+"' and receiverID='"+id1+"');"; ArrayList<Message> messages = new ArrayList(); try { Connection connection = jdbcUtils.getConnect(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()){ String name = resultSet.getString("name"); String senderID = resultSet.getString("senderID"); String receiverID = resultSet.getString("receiverID"); String content = resultSet.getString("content"); String date = resultSet.getString("date"); String read = resultSet.getString("status"); messages.add(new Message(name,senderID,receiverID,content,date,read)); } //System.out.println("Return messages successfully."); statement.close(); resultSet.close(); connection.close(); }catch (Exception e){ e.printStackTrace(); } Collections.sort(messages,new sortMessage()); return messages; } //修改状态 public static String changeMessageStatus(Message message,String status){ String senderID = message.getSenderID(); String receiverID = message.getReceiverID(); String content = message.getContent(); String date = message.getDate(); String sql = "update messages set status='"+status+"' where senderID='"+senderID+"' and receiverID='"+ receiverID+"' and content='"+content+"' and date='"+date+"';"; try { Connection connection = jdbcUtils.getConnect(); PreparedStatement preparedStatement = (PreparedStatement)connection.prepareStatement(sql); preparedStatement.executeUpdate(); //System.out.println("Message status changed successfully."); preparedStatement.close(); connection.close(); }catch (Exception e){ e.printStackTrace(); return "error"; } return "success"; } //删除消息 public static String delMessage(Message message){ String send = message.getSenderID(); String receive = message.getReceiverID(); String content = message.getContent(); String date = message.getDate(); String sql = "delete from messages where senderID='"+send+"' and receiverID='"+receive+"' and content='" +content+"' and date='"+date+"';"; try { Connection connection = jdbcUtils.getConnect(); PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.executeUpdate(); //System.out.println("Delete message successfully."); preparedStatement.close(); connection.close(); return "success"; }catch (Exception e){ e.printStackTrace(); return "error"; } } //返回会话 public static ArrayList<Conversation> selectConversation(User u){ String id = u.getPhone(); String sql = "select * from messages where senderID='"+id+"' or receiverID='"+id+"';"; ArrayList<Conversation> list = new ArrayList<>(); try { Connection connection = jdbcUtils.getConnect(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql); HashSet<String> index = new HashSet<>(); ArrayList<Message> messages = new ArrayList<>(); index.add(id); while (resultSet.next()){ String name = resultSet.getString("name"); String senderID = resultSet.getString("senderID"); String receiverID = resultSet.getString("receiverID"); String content = resultSet.getString("content"); String date = resultSet.getString("date"); String read = resultSet.getString("status"); messages.add(new Message(name,senderID,receiverID,content,date,read)); /*if(index.add(senderID)){ list.add(new Conversation(senderID,name,date,content,read)); } else if(index.add(receiverID)){ list.add(new Conversation(receiverID,name,date,content,read)); }*/ } Collections.sort(messages, new sortMessage()); for(int i=0;i<messages.size();i++){ String senderID = messages.get(i).getSenderID(); String receiverID = messages.get(i).getReceiverID(); if(index.add(senderID)){ String name = messages.get(i).getName(); String date = messages.get(i).getDate(); String read = messages.get(i).getRead(); String content = messages.get(i).getContent(); list.add(new Conversation(senderID,name,date,content,read)); } else if(index.add(receiverID)){ String name = messages.get(i).getName(); String date = messages.get(i).getDate(); String read = messages.get(i).getRead(); String content = messages.get(i).getContent(); list.add(new Conversation(receiverID,name,date,content,read)); } } System.out.println("Return conversations successfully."); statement.close(); resultSet.close(); connection.close(); }catch (Exception e){ e.printStackTrace(); } Collections.sort(list,new sortConser()); return list; } } class sortMessage implements Comparator { public int compare(Object o1, Object o2) { //倒序,日期最靠前的在最前 SimpleDateFormat format = new SimpleDateFormat("yyyy-M-d HH:mm:ss"); Message m1 = (Message)o1; Message m2 = (Message)o2; Date d1,d2; try { d1 = format.parse(m1.getDate()); d2 = format.parse(m2.getDate()); } catch (ParseException e) { // 解析出错,则不进行排序 System.out.println("ComparatorDate--compare--SimpleDateFormat.parse--error"); return 0; } if (d1.before(d2)) { return 1; } else { return -1; } } } class sortConser implements Comparator { public int compare(Object o1, Object o2) { //倒序,日期最靠前的在最前 SimpleDateFormat format = new SimpleDateFormat("yyyy-M-d HH:mm:ss"); Conversation m1 = (Conversation)o1; Conversation m2 = (Conversation)o2; Date d1,d2; try { d1 = format.parse(m1.getDate()); d2 = format.parse(m2.getDate()); } catch (ParseException e) { // 解析出错,则不进行排序 System.out.println("ComparatorDate--compare--SimpleDateFormat.parse--error"); return 0; } if (d1.before(d2)) { return 1; } else { return -1; } } } class sortCom implements Comparator { public int compare(Object o1, Object o2) { //倒序,日期最靠前的在最前 SimpleDateFormat format = new SimpleDateFormat("yyyy-M-d HH:mm:ss"); Comment m1 = (Comment)o1; Comment m2 = (Comment)o2; Date d1,d2; try { d1 = format.parse(m1.getDate()); d2 = format.parse(m2.getDate()); } catch (ParseException e) { // 解析出错,则不进行排序 System.out.println("ComparatorDate--compare--SimpleDateFormat.parse--error"); return 0; } if (d1.before(d2)) { return 1; } else { return -1; } } } class sortReq implements Comparator { public int compare(Object o1, Object o2) { //倒序,日期最靠前的在最前 SimpleDateFormat format = new SimpleDateFormat("yyyy-M-d"); Request m1 = (Request)o1; Request m2 = (Request)o2; Date d1,d2; try { d1 = format.parse(m1.getDate()); d2 = format.parse(m2.getDate()); } catch (ParseException e) { // 解析出错,则不进行排序 System.out.println("ComparatorDate--compare--SimpleDateFormat.parse--error"); return 0; } if (d1.before(d2)) { return 1; } else { return -1; } } }
true
e15dd9d55f94f7725df3e296bdece15f875145d1
Java
Deathnerd/JavaTwig
/src/main/java/com/deathnerd/JavaTwig/LogicException.java
UTF-8
198
2.171875
2
[]
no_license
package com.deathnerd.JavaTwig; /** * Created by Wes Gilleland on 1/11/2017. */ public class LogicException extends Exception { public LogicException(String s) { super(s); } }
true
bfc93b979bdb6411762eec68e2cb387fbea8d95c
Java
Ativelox/ProjectF
/src/de/cormag/projectf/main/Game.java
UTF-8
5,900
2.328125
2
[]
no_license
package de.cormag.projectf.main; import java.awt.Graphics; import java.awt.image.BufferStrategy; import java.util.Iterator; import javax.swing.JOptionPane; import de.cormag.projectf.display.Display; import de.cormag.projectf.entities.Entity; import de.cormag.projectf.entities.properties.IUpdateable; import de.cormag.projectf.gfx.Assets; import de.cormag.projectf.gfx.GameCamera; import de.cormag.projectf.input.KeyManager; import de.cormag.projectf.saves.SaveGameManager; import de.cormag.projectf.saves.SavedGame; import de.cormag.projectf.states.GameState; import de.cormag.projectf.states.MenuState; import de.cormag.projectf.states.StateManager; import de.cormag.projectf.utils.time.GameTime; import de.cormag.projectf.utils.time.Time; import de.cormag.projectf.worlds.World; public class Game implements Runnable, IUpdateable { private Display display; public String title; private boolean running = false; private Thread thread; private BufferStrategy bs; private Graphics g; private long lastTime, now; private int currentFPS; // States private StateManager stateManager; // Input private KeyManager keyManager; // Camera private GameCamera gameCamera; // Handler private Handler handler; public static final int WIDTH = 1000, HEIGHT = 700; public Game(String title) { this.title = title; keyManager = new KeyManager(); currentFPS = 0; } private void init() { display = new Display(title, WIDTH, HEIGHT, this); display.getFrame().addKeyListener(keyManager); Assets.init(); handler = new Handler(this); stateManager = new StateManager(); MenuState menuState = new MenuState(handler); stateManager.push(menuState); } private void reInit(SavedGame savedGame) { keyManager.resetKeys(); Assets.init(); handler = new Handler(this); gameCamera = new GameCamera(handler, savedGame.getXOffset(), savedGame.getYOffset()); stateManager = new StateManager(); GameState gameState = new GameState(handler, savedGame); stateManager.push(gameState); gameState.createHUD(); Iterator<World> worldIterator = gameState.getWorldIterator(); while (worldIterator.hasNext()) { World w = worldIterator.next(); w.setHandler(handler); w.getEntityManager().setHandler(handler); w.applyResources(); Iterator<Entity> entityIterator = w.getEntityManager().getEntities(); while (entityIterator.hasNext()) { Entity e = entityIterator.next(); e.setHandler(handler); e.applyResources(); } } } /* * (non-Javadoc) * * @see de.cormag.projectf.entities.properties.IUpdateable#update() */ @Override public void update(final GameTime gameTime) { keyManager.update(gameTime); if (keyManager.s && keyManager.ctrl) { String name = JOptionPane.showInputDialog("Enter name for the save file"); resetFPSLock(); if (name != null) { SaveGameManager.saveGame(name, this, handler); } keyManager.resetKeys(); } else if (keyManager.l && keyManager.ctrl) { String name = JOptionPane.showInputDialog("Enter name of the file loaded"); resetFPSLock(); if (name != null) { SavedGame savedGame = SaveGameManager.loadSavedGame(name); reInit(savedGame); } keyManager.resetKeys(); return; } stateManager.update(gameTime); } private void render(GameTime gameTime) { bs = display.getCanvas().getBufferStrategy(); if (bs == null) { display.getCanvas().createBufferStrategy(3); return; } g = bs.getDrawGraphics(); // Clear Screen g.clearRect(0, 0, WIDTH, HEIGHT); // Draw Here! stateManager.render(g, gameTime); // End Drawing! bs.show(); g.dispose(); } public void run() { init(); int fps = 60; double timePerTick = 1_000_000_000 / fps; double ticksToProcess = 0; int ticksProcessed = 0; int timer = 0; lastTime = System.nanoTime(); GameTime gameTime = null; Time lastUpdateEndTime = null; while (running) { now = System.nanoTime(); ticksToProcess += (now - lastTime) / timePerTick; timer += now - lastTime; lastTime = now; if (ticksToProcess >= 1) { if (gameTime == null) { // This indicates the initial first update cycle gameTime = GameTime.createInitialGameTimeSnapshot(); } else { // Create a game time snapshot using the object from the // last update cycle gameTime = GameTime.createGameTimeSnapshotFromLast(gameTime, lastUpdateEndTime); } update(gameTime); lastUpdateEndTime = Time.now(); ticksProcessed++; render(gameTime); ticksToProcess--; } if (timer > 1_000_000_000) { currentFPS = ticksProcessed; ticksProcessed = 0; timer = 0; } } stop(); } public void stopGame() { running = false; } public int getCurrentFPS() { return this.currentFPS; } private void resetFPSLock() { lastTime = System.nanoTime(); now = System.nanoTime(); } public StateManager getStateManager() { return stateManager; } public KeyManager getKeyManager() { return keyManager; } public GameCamera getGameCamera() { return gameCamera; } public Display getDisplay() { return display; } public Handler getHandler() { return handler; } public int getWidth() { return display.getWidth(); } public int getHeight() { return display.getHeight(); } public synchronized void start() { if (running) return; running = true; thread = new Thread(this); thread.start(); } public synchronized void stop() { if (!running) return; running = false; try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } }
true
607c434e376be12dbbb630c9b8ece486b5294907
Java
artir3/compcal-backend
/src/main/java/com/arma/inz/compcal/printer/JasperController.java
UTF-8
582
1.632813
2
[]
no_license
package com.arma.inz.compcal.printer; import com.arma.inz.compcal.kpir.dto.KpirFilterDTO; import com.arma.inz.compcal.users.BaseUser; import org.springframework.core.io.Resource; import java.io.File; public interface JasperController { void compileFile(JasperEnum file); Resource getKpirResource(BaseUser baseUser, KpirFilterDTO kpirFilterDTO); byte[] getKpirBytes(BaseUser baseUser, KpirFilterDTO kpirFilterDTO); File getKpirFile(BaseUser baseUser, KpirFilterDTO kpirFilterDTO); void sendKpirPdftoMail(BaseUser baseUser, KpirFilterDTO kpirFilterDTO); }
true
14bf9ba1b691dbf8c76f23f7bc9b66fcc560c1ad
Java
jamcnaughton/synergynet3
/synergynet3-parent/synergynet3-appsystem-core/src/main/java/synergynet3/additionalitems/interfaces/IActionOnVideoEndListener.java
UTF-8
123
1.679688
2
[ "BSD-3-Clause" ]
permissive
package synergynet3.additionalitems.interfaces; public interface IActionOnVideoEndListener { public void onVideoEnd(); }
true
717b791c6b8f3331a3c18bb9e082a91f6fdf57e2
Java
OFRF/BladeRush
/gameserver/src/main/java/ru/l2/gameserver/data/dao/EffectsDAO.java
UTF-8
6,551
2.21875
2
[]
no_license
package ru.l2.gameserver.data.dao; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.l2.commons.dbutils.DbUtils; import ru.l2.commons.dbutils.SqlBatch; import ru.l2.gameserver.database.DatabaseFactory; import ru.l2.gameserver.model.Effect; import ru.l2.gameserver.model.Player; import ru.l2.gameserver.model.Skill; import ru.l2.gameserver.skills.EffectType; import ru.l2.gameserver.skills.effects.EffectTemplate; import ru.l2.gameserver.stats.Env; import ru.l2.gameserver.tables.SkillTable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.List; public class EffectsDAO { private static final int SUMMON_SKILL_OFFSET = 100000; private static final Logger LOGGER = LoggerFactory.getLogger(EffectsDAO.class); public static EffectsDAO getInstance() { return LazyHolder.INSTANCE; } public void restoreEffects(final Player player) { int objectId = player.getObjectId(); int id = player.getActiveClassId(); Connection con = null; PreparedStatement statement; ResultSet rset; try { con = DatabaseFactory.getInstance().getConnection(); statement = con.prepareStatement("SELECT `skill_id`,`skill_level`,`effect_count`,`effect_cur_time`,`duration` FROM `character_effects_save` WHERE `object_id`=? AND `id`=? ORDER BY `order` ASC"); statement.setInt(1, objectId); statement.setInt(2, id); rset = statement.executeQuery(); while (rset.next()) { final int skillId = rset.getInt("skill_id"); final int skillLvl = rset.getInt("skill_level"); final int effectCount = rset.getInt("effect_count"); final long effectCurTime = rset.getLong("effect_cur_time"); final long duration = rset.getLong("duration"); final Skill skill = SkillTable.getInstance().getInfo(skillId, skillLvl); if (skill == null) { continue; } for (final EffectTemplate et : skill.getEffectTemplates()) { if (et != null) { final Env env = new Env(player, player, skill); final Effect effect = et.getEffect(env); if (effect != null) { if (!effect.isOneTime()) { effect.setCount(effectCount); effect.setPeriod((effectCount == 1) ? (duration - effectCurTime) : duration); player.getEffectList().addEffect(effect); } } } } } DbUtils.closeQuietly(statement, rset); statement = con.prepareStatement("DELETE FROM character_effects_save WHERE object_id = ? AND id=?"); statement.setInt(1, objectId); statement.setInt(2, id); statement.execute(); DbUtils.close(statement); } catch (Exception e) { LOGGER.error("Could not restore active effects data!", e); } finally { DbUtils.closeQuietly(con); } } public void deleteEffects(final int objectId, final int skillId) { Connection con = null; PreparedStatement statement = null; try { con = DatabaseFactory.getInstance().getConnection(); statement = con.prepareStatement("DELETE FROM character_effects_save WHERE object_id = ? AND id=?"); statement.setInt(1, objectId); statement.setInt(2, SUMMON_SKILL_OFFSET + skillId); statement.execute(); } catch (Exception e) { LOGGER.error("Could not delete effects active effects data!" + e, e); } finally { DbUtils.closeQuietly(con, statement); } } public void insert(final Player player) { int objectId = player.getObjectId(); int id = player.getActiveClassId(); final List<Effect> effects = player.getEffectList().getAllEffects(); if (effects.isEmpty()) { return; } Connection con = null; Statement statement = null; try { con = DatabaseFactory.getInstance().getConnection(); statement = con.createStatement(); int order = 0; final SqlBatch b = new SqlBatch("INSERT IGNORE INTO `character_effects_save` (`object_id`,`skill_id`,`skill_level`,`effect_count`,`effect_cur_time`,`duration`,`order`,`id`) VALUES"); for (Effect effect : effects) { if (effect != null && effect.isInUse() && !effect.getSkill().isToggle() && effect.getEffectType() != EffectType.HealOverTime && effect.getEffectType() != EffectType.CombatPointHealOverTime) { if (effect.isSaveable()) { String sb = "(" + objectId + "," + effect.getSkill().getId() + "," + effect.getSkill().getLevel() + "," + effect.getCount() + "," + effect.getTime() + "," + effect.getPeriod() + "," + order + "," + id + ")"; b.write(sb); } while ((effect = effect.getNext()) != null && effect.isSaveable()) { String sb = "(" + objectId + "," + effect.getSkill().getId() + "," + effect.getSkill().getLevel() + "," + effect.getCount() + "," + effect.getTime() + "," + effect.getPeriod() + "," + order + "," + id + ")"; b.write(sb); } ++order; } } if (!b.isEmpty()) { statement.executeUpdate(b.close()); } } catch (Exception e) { LOGGER.error("Could not store active effects data!", e); } finally { DbUtils.closeQuietly(con, statement); } } private static class LazyHolder { private static final EffectsDAO INSTANCE = new EffectsDAO(); } }
true
2049aeaf3128d43bbc177960986bcc43d749d61d
Java
PuTongGithub/MurderGame
/src/main/java/cn/mysterygame/entity/GameVote.java
UTF-8
993
2.34375
2
[]
no_license
package cn.mysterygame.entity; public class GameVote { private Integer gameVoteId; private Integer gameId; private Integer userId; private Integer voteUserId; private Integer voteRound; public Integer getGameVoteId() { return gameVoteId; } public void setGameVoteId(Integer gameVoteId) { this.gameVoteId = gameVoteId; } public Integer getGameId() { return gameId; } public void setGameId(Integer gameId) { this.gameId = gameId; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public Integer getVoteUserId() { return voteUserId; } public void setVoteUserId(Integer voteUserId) { this.voteUserId = voteUserId; } public Integer getVoteRound() { return voteRound; } public void setVoteRound(Integer voteRound) { this.voteRound = voteRound; } }
true
ebfe9b8d16adb3ef902faf828c1ebaec9680c5d9
Java
Roye7777777/westfriesland
/vlaamsbrabant/src/main/java/nl/roy/vlaamsbrabant/model/Users.java
UTF-8
2,712
2.3125
2
[]
no_license
package nl.roy.vlaamsbrabant.model; import java.security.Principal; import java.util.List; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotEmpty; import org.mongodb.morphia.annotations.Entity; @Entity(value = "users") // noClassnameStored = true moet weg - morphia vindt 't kut public class Users extends EntityModel implements Principal { @NotEmpty private String username; @NotEmpty @Length(min = 3, max = 10) private String password; @NotEmpty private String first_name; @NotEmpty private String last_name; @NotEmpty private int age; @NotEmpty private String gender; private double weight; private double length; private List<String> roles; private List<Exercise_Diaries> exercise_diaries; private List<Food_Diaries> food_diaries; private List<Scores> scores; public String getName() { return username; } public void setName( String username ) { this.username = username; } public String getPassword() { return password; } public void setPassword( String password ) { this.password = password; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } public double getLength() { return length; } public void setLength(double length) { this.length = length; } public boolean hasRole(String role) { return roles.contains(role); } public List<String> getRoles() { return roles; } public void setRoles(List<String> roles) { this.roles = roles; } public List<Exercise_Diaries> getExercise_diaries() { return exercise_diaries; } public void setExercise_diary(List<Exercise_Diaries> exercise_diaries) { this.exercise_diaries = exercise_diaries; } public List<Food_Diaries> getFood_diaries() { return food_diaries; } public void setFood_diary(List<Food_Diaries> food_diaries) { this.food_diaries = food_diaries; } public List<Scores> getScores() { return scores; } public void setScores(List<Scores> scores) { this.scores = scores; } }
true
fdcc56f53f55c96b53b973be3d504003b5b44bb8
Java
velianarie/PaperRockScissorsGame
/src/main/java/com/game/prs/orchestrator/InteractiveHumanVsComputerGamemaster.java
UTF-8
2,685
3.28125
3
[]
no_license
package com.game.prs.orchestrator; import com.game.prs.move.MoveSelection; import com.game.prs.player.Computer; import com.game.prs.player.Human; import com.game.prs.result.TwoPlayerResult; import com.game.prs.move.Move; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class InteractiveHumanVsComputerGamemaster extends ConsoleTwoPlayerGamemaster { private final Human human; private final Computer computer; private final TwoPlayerJudge judge; private final List<TwoPlayerResult> gameResults; public InteractiveHumanVsComputerGamemaster(Human human, Computer computer, TwoPlayerJudge judge) { this.human = human; this.computer = computer; this.judge = judge; this.gameResults = new ArrayList<>(); } @Override public String startGame() { StringBuilder roundAndGameSummary = new StringBuilder(); Scanner scanner = new Scanner(System.in); String pattern = "^P$|^p$|^R$|^r$|^S$|^s$"; boolean isTerminated = false; int round = 1; while (!isTerminated) { System.out.print("Please enter [P]aper, [R]ock or [S]cissors or type FINISH to finish entering move: "); String line = scanner.nextLine(); if (line.matches(pattern)) { Move validMove = parse(line); human.setMove(validMove); TwoPlayerResult roundResult = judge.judgeFromFirstPlayerPointOfView(human, computer); gameResults.add(roundResult); String roundSummary = buildRoundSummary(round, human.getName(), computer.getName(), roundResult); roundAndGameSummary.append(roundSummary); System.out.println(roundSummary); round++; } else if (line.toUpperCase().matches("FINISH")) { isTerminated = true; System.out.println("Thanks for playing. See game summary below:"); } else { System.out.println("'" + line + "' is invalid."); } } String gameSummary = buildGameSummary(human.getName(), computer.getName(), gameResults); roundAndGameSummary.append(gameSummary); System.out.println(gameSummary); return roundAndGameSummary.toString(); } public Move parse(String input) { return switch (input.toUpperCase()) { case "P" -> MoveSelection.PAPER; case "R" -> MoveSelection.ROCK; case "S" -> MoveSelection.SCISSORS; default -> throw new IllegalStateException("Cannot parse '" + input + "' to a valid Move"); }; } }
true
0786e6a821c0615a238bbf4397b6b751d8b58cf5
Java
DigVijayWa/spotify-api-java
/src/main/java/MenuPanel.java
UTF-8
8,691
2.671875
3
[]
no_license
import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import org.json.JSONArray; import org.json.JSONObject; public class MenuPanel extends JPanel implements ActionListener { private JTextField searchBar; private JButton searchButton; private JRadioButton songRadio; private JRadioButton artistRadio; private JRadioButton albumRadio; private JRadioButton playlistRadio; GuiApplication guiApplication; private ButtonGroup buttonGroup; private static String typeSong = "track"; public MenuPanel(GuiApplication guiApplication) { this.guiApplication = guiApplication; //construct components searchBar = new JTextField(5); searchButton = new JButton("Search"); songRadio = new JRadioButton("Songs"); artistRadio = new JRadioButton("Artist"); albumRadio = new JRadioButton("Album"); playlistRadio = new JRadioButton("Playlist"); buttonGroup = new ButtonGroup(); buttonGroup.add(songRadio); buttonGroup.add(artistRadio); buttonGroup.add(albumRadio); buttonGroup.add(playlistRadio); //adjust size and set layout setPreferredSize(new Dimension(944, 150)); setLayout(null); searchButton.addActionListener(this); songRadio.addActionListener(this); artistRadio.addActionListener(this); albumRadio.addActionListener(this); playlistRadio.addActionListener(this); //add components add(searchBar); add(searchButton); add(songRadio); add(artistRadio); add(albumRadio); add(playlistRadio); //set component bounds (only needed by Absolute Positioning) searchBar.setBounds(675, 10, 170, 30); searchButton.setBounds(860, 10, 80, 30); songRadio.setBounds(140, 85, 160, 40); artistRadio.setBounds(340, 75, 185, 65); albumRadio.setBounds(570, 80, 165, 55); playlistRadio.setBounds(775, 80, 145, 50); } //to populate Song object list on JSON response public ArrayList<SongObject> mapSongObjectWithJsonObject(JSONObject jsonObject) { ArrayList<SongObject> songObjectList = new ArrayList<>(); Map trackItems = ((JSONObject) jsonObject.get(typeSong + "s")).toMap(); ArrayList<JSONObject> jsonArrayItems = (ArrayList<JSONObject>) trackItems.get("items"); for (int i = 0; i < jsonArrayItems.size(); i++) { Map jsonItem = (Map<String, Object>) jsonArrayItems.get(i); Map jsonObjectAlbum = (Map<String, Object>) jsonItem.get("album"); ArrayList<JSONObject> jsonArrayArtists = (ArrayList<JSONObject>) jsonObjectAlbum .get("artists"); ArrayList<JSONObject> jsonArrayImages = (ArrayList<JSONObject>) jsonObjectAlbum.get("images"); //extracting the date String date = (String) jsonObjectAlbum.get("release_date"); //extracting the image Map image = (Map<String, Object>) (jsonArrayImages.get(jsonArrayImages.size() - 1)); String imageUrl = (String) image.get("url"); //extracting the id String songId = (String) jsonObjectAlbum.get("id"); //extracting the name of the artist Map artist = (Map<String, Object>) (jsonArrayArtists.get(0)); String artistName = (String) artist.get("name"); //extracting the name of the song : String songName = (String) jsonItem.get("name"); songObjectList.add(new SongObject(songId, songName, artistName, date, imageUrl)); } System.out.print(songObjectList.size()); return songObjectList; } //to populate Artist object list on JSON response //due to json response is different for different queries need to make different methods. public ArrayList<Artist> mapArtistObjectWithJsonObject(JSONObject jsonObject) { ArrayList<Artist> artistArrayList = new ArrayList<>(); Map trackItems = ((JSONObject) jsonObject.get(typeSong + "s")).toMap(); ArrayList<JSONObject> jsonArrayItems = (ArrayList<JSONObject>) trackItems.get("items"); for (int i = 0; i < jsonArrayItems.size(); i++) { Map jsonItem = (Map<String, Object>) jsonArrayItems.get(i); String id = (String) jsonItem.get("id"); String name = (String) jsonItem.get("name"); Map jsonItemFollower = (Map<String, Object>) jsonItem.get("followers"); String followers = "" + ((Integer) jsonItemFollower.get("total")); ArrayList<JSONObject> jsonArrayImages = (ArrayList<JSONObject>) jsonItem.get("images"); Map image = null; String imageUrl = ""; if (jsonArrayImages.size() > 0) { image = (Map<String, Object>) (jsonArrayImages.get(jsonArrayImages.size() - 1)); imageUrl = (String) image.get("url"); } else { image = new HashMap(); imageUrl = "https://i.scdn.co/image/ed213a32e1327f3f2d7b2539eb1db57f55b68dbb"; } artistArrayList.add(new Artist(id, name, followers, imageUrl)); } System.out.print(artistArrayList.size()); return artistArrayList; } public ArrayList<Album> mapAlbumObjectWithJsonObject(JSONObject jsonObject) { ArrayList<Album> artistArrayList = new ArrayList<>(); Map trackItems = ((JSONObject) jsonObject.get(typeSong + "s")).toMap(); ArrayList<JSONObject> jsonArrayItems = (ArrayList<JSONObject>) trackItems.get("items"); for (int i = 0; i < jsonArrayItems.size(); i++) { Map jsonItem = (Map<String, Object>) jsonArrayItems.get(i); String id = (String) jsonItem.get("id"); String name = (String) jsonItem.get("name"); ArrayList<JSONObject> jsonArrayArtists = (ArrayList<JSONObject>) jsonItem.get("artists"); ArrayList<JSONObject> jsonArrayImages = (ArrayList<JSONObject>) jsonItem.get("images"); Map image = null; String imageUrl = ""; if (jsonArrayImages.size() > 0) { image = (Map<String, Object>) (jsonArrayImages.get(jsonArrayImages.size() - 1)); imageUrl = (String) image.get("url"); } else { image = new HashMap(); imageUrl = "https://i.scdn.co/image/ed213a32e1327f3f2d7b2539eb1db57f55b68dbb"; } String artistName = ""; Map artist = null; if (jsonArrayArtists.size() > 0) { artist = (Map<String, Object>) (jsonArrayArtists.get(0)); artistName = (String) artist.get("name"); } else { artist = new HashMap(); artistName = "UNKNOWN ARTIST"; } String relaeaseDate = (String) jsonItem.get("release_date"); artistArrayList.add(new Album(id, name, relaeaseDate, imageUrl, artistName)); } System.out.print(artistArrayList.size()); return artistArrayList; } public void actionPerformed(ActionEvent e) { if (e.getSource() == searchButton && App.readyForApiCalls) { System.out.print("\n Search is pressed\n"); String search = searchBar.getText(); search = getFormattedText(search); System.out.print("\n Search : " + search + "\n"); String query = "?q=" + search + "&type=" + typeSong; JSONObject jsonObject = AjaxService .callSearch(query, App.getAccessToken(), App.getTokenType()); if (typeSong == "track") { ArrayList<SongObject> songObjectList = mapSongObjectWithJsonObject(jsonObject); System.out.print("\n 2 : " + songObjectList.size()); guiApplication.getContentPanel().updateContentPanelSong(songObjectList); } else if (typeSong == "artist") { ArrayList<Artist> artistList = mapArtistObjectWithJsonObject(jsonObject); System.out.print("\n 2 : " + artistList.size()); guiApplication.getContentPanel().updateContentPanelArtist(artistList); } else if (typeSong == "album") { ArrayList<Album> artistList = mapAlbumObjectWithJsonObject(jsonObject); System.out.print("\n 2 : " + artistList.size()); guiApplication.getContentPanel().updateContentPanelAlbum(artistList); } } else if (e.getSource() == albumRadio) { typeSong = "album"; System.out.print("\n albumRadio is typed\n"); } else if (e.getSource() == songRadio) { typeSong = "track"; System.out.print("\n songRadio is typed\n"); } else if (e.getSource() == artistRadio) { typeSong = "artist"; System.out.print("\n artistRadio is typed\n"); } else if (e.getSource() == playlistRadio) { System.out.print("\n playlistRadio is typed\n"); } } public String getFormattedText(String text) { text = text.trim(); text = text.replaceAll("\\s", "%20"); return text; } }
true
f0fa888f9f5645396cfc341b0374d05fbe618b83
Java
a7chax/sekolah
/src/sekolah/Sekolah.java
UTF-8
510
1.75
2
[]
no_license
/* * 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 sekolah; /** * * @author Idris Mochamad */ public class Sekolah { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Koneksi konek = new Koneksi(); konek.getKoneksi(); } }
true
6415da05955e766b3bc9586a042359d1f36f99fc
Java
KhosroPakmanesh/EquityMarketSoftwareEcosystem
/project/src/main/java/emSeco/brokerUnit/core/services/infrastructureServices/databases/brokerUnitRepositories/interfaces/repositories/ITradeRepository.java
UTF-8
372
1.984375
2
[ "BSD-3-Clause" ]
permissive
package emSeco.brokerUnit.core.services.infrastructureServices.databases.brokerUnitRepositories.interfaces.repositories; import emSeco.brokerUnit.core.entities.trade.Trade; import java.util.List; import java.util.UUID; public interface ITradeRepository { void add(List<Trade> trades); List<Trade> get(UUID orderId); List<Trade> getInstitutionalTrades(); }
true
d053fc0b82eb2aacba93fda542b310f60850c1d0
Java
raulastu/NetBeans_Projects
/PKU/src/Coreis_A.java
UTF-8
2,138
2.890625
3
[]
no_license
import java.util.*; import java.util.ArrayList; import java.util.regex.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.lang.Integer.*; import static java.lang.Double.*; import static java.util.Collections.*; import java.util.Scanner; public class Coreis_A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = parseInt(sc.nextLine()); int c = 0; int ll[] = new int[10000000]; fill(ll, -1); ArrayList<Integer> al = new ArrayList<Integer>(); ArrayList<Integer> al2 = new ArrayList<Integer>(); while (c++ < n) { int nn = parseInt(sc.nextLine()); al.add(nn); al2.add(nn); } sort(al, Collections.reverseOrder()); int nn = al.get(0); long r = 0; for (int x = 0; x * x <= nn; x++) { for (int y = 0; x * x + y * y <= nn; y++) { for (int z = 0; x * x + y * y + z * z <= nn; z++) { for (int w = 0; x * x + y * y + z * z + w * w <= nn; w++) { // if (x * x + y * y + z * z + w * w == nn) { // r++; // } ll[x * x + y * y + z * z + w * w]++; } } } } // sort(al); for (int i = 0; i < al2.size(); i++) { System.out.println(ll[al2.get(i)] + 1); } } private static void print(Object... rs) { print("", rs); } private static void print(String msg, Object... rs) { String x = deepToString(rs); if (x.indexOf("[[") == 0) { x = x.substring(1, x.length() - 1); } System.err.println(msg + " " + x); } private static void printm(String[] a) { for (int i = 0; i < a.length; i++) { System.err.println("[" + a[i] + "]"); } } private static void printm(char[][] a) { for (int i = 0; i < a.length; i++) { System.err.println("[" + new String(a[i]) + "]"); } } }
true
eaedc50d6842c92ba531ce5794ac4168b739b762
Java
1aleksandaraleksic/student-service
/src/main/java/it/engineering/faculty/dto/TitleDto.java
UTF-8
731
2.546875
3
[]
no_license
package it.engineering.faculty.dto; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class TitleDto { @NotNull private Long id; @NotNull @Size(max = 30) private String tileName; public TitleDto() { } public TitleDto(@NotNull Long id, @NotNull @Size(max = 30) String tileName) { super(); this.id = id; this.tileName = tileName; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitleName() { return tileName; } public void setTitleName(String tileName) { this.tileName = tileName; } @Override public String toString() { return "TitleDto [id=" + id + ", tileName=" + tileName + "]"; } }
true
b71604211edd67da48a8f424cc1aafbadf764759
Java
micomitja/P2-201920
/src/predavanje06/TestOrodja.java
UTF-8
493
3.359375
3
[]
no_license
package predavanje06; /** * To je razred za testiranje razreda Orodja. * @author tomaz **/ public class TestOrodja { /** * Metoda main, v kateri kličemo metodo sredina. * @param args */ public static void main(String[] args) { double a=7; // spr. a double x=9; // spr. b // klic metode iz drugega razreda. Ker je razred Orodja v // istem paketu kot razred TestOrodja, import ni potreben. double c = Orodja.sredina(a,x); System.out.println(c); } }
true
191c73f2a4086aa8b5df5b777b9f0a02bc2ee1c1
Java
NeilUrquhart/NapierGeowareTools
/NapierGeoTools.TfL/NapierGeoTools.PublicTransport/src/edu/napier/geo/publicTransport/ResponseTfL/ValidityPeriod.java
UTF-8
596
2.046875
2
[]
no_license
package edu.napier.geo.publicTransport.ResponseTfL; import java.io.Serializable; public class ValidityPeriod implements Serializable { /** * */ private static final long serialVersionUID = -1618769253513354475L; private String fromDate; private String toDate; private boolean isNow; public ValidityPeriod(String fromDate, String toDate, boolean isNow) { this.fromDate = fromDate; this.toDate = toDate; this.isNow = isNow; } public String getFromDate() { return fromDate; } public String getToDate() { return toDate; } public boolean isNow() { return isNow; } }
true
ba98a596c6d26a83495fd991fb658fb52b1ee131
Java
wangfeng351/micro-service
/back-end/user-center/src/main/java/com/soft1851/spring/cloud/domain/dto/UserRespDTO.java
UTF-8
633
1.703125
2
[]
no_license
package com.soft1851.spring.cloud.domain.dto; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.omg.CORBA.PRIVATE_MEMBER; /** * @Description TODO * @Author wf * @Date 2020/10/13 * @Version 1.0 */ @Builder @Data @NoArgsConstructor @AllArgsConstructor public class UserRespDTO { /** * id */ private Integer id; /** * 头像地址 */ private String avatarUrl; /** * 积分 */ private Integer bonus; /** * 微信昵称 */ private String wxNickname; }
true
4d92bb9b605783673ad63459085126934231694b
Java
MozeeB/CRUDBiodataMVP
/app/src/main/java/com/mozeeb/crudmvp/GlobalClass.java
UTF-8
392
1.632813
2
[]
no_license
package com.mozeeb.crudmvp; import android.app.Application; import com.androidnetworking.AndroidNetworking; public class GlobalClass extends Application { public static final String BASE_URL = "http://192.168.70.148/api_rpla/index.php/Api/"; @Override public void onCreate() { super.onCreate(); AndroidNetworking.initialize(getApplicationContext()); } }
true
3ed22db48832707ffdfc8f787479c41da56b46fc
Java
yregaieg/peltas-core
/src/main/java/io/peltas/core/config/BasicPeltasConfiguration.java
UTF-8
2,663
1.640625
2
[]
no_license
/** * Copyright 2019 Pleo Soft d.o.o. (pleosoft.com) * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.peltas.core.config; import javax.sql.DataSource; import org.springframework.beans.factory.BeanFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ResourceLoader; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.integration.config.EnableIntegration; import org.springframework.messaging.core.GenericMessagingTemplate; import org.springframework.transaction.annotation.EnableTransactionManagement; import io.peltas.core.repository.PeltasTimestamp; import io.peltas.core.repository.PeltasTimestampRepository; @Configuration @EnableJpaRepositories(basePackageClasses = PeltasTimestampRepository.class) @EntityScan(basePackageClasses = PeltasTimestamp.class) @EnableIntegration @EnableTransactionManagement public class BasicPeltasConfiguration { @Bean public PeltasDatasourceProperties peltasDatasourceProperties() { return new PeltasDatasourceProperties(); } @Bean public PeltasDatasourceInitializer peltasDatasourceInitializer(DataSource dataSource, ResourceLoader resourceLoader) { return new PeltasDatasourceInitializer(dataSource, resourceLoader, peltasDatasourceProperties()); } @Bean public CustomDatasourceProperties customDatasourceProperties() { return new CustomDatasourceProperties(); } @Bean @ConditionalOnProperty("peltas.custom.datasource.enabled") public CustomDatasourceInitializer customDatasourceInitializer(DataSource dataSource, ResourceLoader resourceLoader) { return new CustomDatasourceInitializer(dataSource, resourceLoader, customDatasourceProperties()); } @Bean public GenericMessagingTemplate messagingTemplate(BeanFactory beanFactory) { GenericMessagingTemplate template = new GenericMessagingTemplate(); template.setBeanFactory(beanFactory); return template; } }
true
3863128556314c48a15e1c1ea621da67c2e042f8
Java
ZaharDementiev/Zodiac
/app/src/main/java/com/example/zodiac/Chat/Message.java
UTF-8
1,355
2.546875
3
[]
no_license
package com.example.zodiac.Chat; public class Message { private long id; private long chatId; private String text; private String imageUrl; private long senderId; private String senderName; public Message() {} public Message(long chatId, String text, String imageUrl, long senderId, String senderName) { this.chatId = chatId; this.text = text; this.imageUrl = imageUrl; this.senderId = senderId; this.senderName = senderName; } public long getId() { return id; } public void setId(long id) { this.id = id; } public long getChatId() { return chatId; } public void setChatId(long chatId) { this.chatId = chatId; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUtl) { this.imageUrl = imageUtl; } public long getSenderId() { return senderId; } public void setSenderId(long senderId) { this.senderId = senderId; } public String getSenderName() { return senderName; } public void setSenderName(String senderName) { this.senderName = senderName; } }
true
3bda1f3cc794f67ffcda4d1479018af45568ebe3
Java
JichengSong/flink-boot
/flink-groovy/src/main/java/com/intsmaze/flink/groovy/bean/ScriptCacheMapping.java
UTF-8
1,161
2.453125
2
[ "BSD-3-Clause" ]
permissive
package com.intsmaze.flink.groovy.bean; import com.google.common.collect.Maps; import groovy.lang.Script; import org.apache.commons.lang3.tuple.Pair; import java.io.Serializable; import java.util.concurrent.ConcurrentMap; public class ScriptCacheMapping implements Serializable { private static ConcurrentMap<Long, Pair<String, Script>> scriptCache = Maps.newConcurrentMap(); public ConcurrentMap<Long, Pair<String, Script>> getScriptCache() { return scriptCache; } public void addScript(Long id, String hash, Script obj) { scriptCache.put(id, Pair.of(hash, obj)); } public boolean contains(Long id) { return scriptCache.containsKey(id); } public boolean isDifference(Long id, String hash) { if (!contains(id)) { return false; } return scriptCache.get(id).getLeft().equals(hash); } public Script getScript(Long id) { if (!contains(id)) { return null; } return scriptCache.get(id).getRight(); } public void remove(Long id) { if (contains(id)) { scriptCache.remove(id); } } }
true
7fa917fa7045053b1f827578753c0109d2efbc48
Java
joannatrojak/BankApplicationAdvancedJava
/src/test/java/pl/lodz/uni/math/BankApplication/User/UserServiceTest.java
UTF-8
1,140
2.5625
3
[]
no_license
package pl.lodz.uni.math.BankApplication.User; import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; import static org.junit.jupiter.api.Assertions.*; class UserServiceTest { private final UserService userTester = new UserService(); @Test void checkIfClientWasCreated() throws Exception { userTester.createNewUser("client"); assertThat(userTester.getUserToBeCreated(), instanceOf(Client.class)); } @Test void checkIfEmployeeWasCreated() throws Exception{ userTester.createNewUser("employee"); assertThat(userTester.getUserToBeCreated(), instanceOf(Employee.class)); } @Test void checkIfDirectorWasCreated() throws Exception{ userTester.createNewUser("director"); assertThat(userTester.getUserToBeCreated(), instanceOf(Director.class)); } @Test void checkIfListOfClientsIsNotEmpty() throws Exception { userTester.createNewUser("client"); userTester.addNewClientToTheListOfClients(); assertEquals(1, userTester.listOfClients.size()); } }
true
b4e6e704913258535736fb34c8b3a8cf02dc7a27
Java
liupeng330/hibernate_learn
/src/main/java/pengliu/me/hibernate_relation/many_to_many/main.java
UTF-8
2,630
2.71875
3
[]
no_license
package pengliu.me.hibernate_relation.many_to_many; import org.hibernate.Session; import org.hibernate.Transaction; import pengliu.me.hibernate_relation.HibernateUtil; import pengliu.me.hibernate_relation.domain.Category; import pengliu.me.hibernate_relation.domain.StockDailyRecordEntity; import pengliu.me.hibernate_relation.domain.StockEntity; import java.sql.Timestamp; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; public class main { public static void main(String[] args) throws Exception { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tx = null; try { tx = session.beginTransaction(); Category category1 = new Category(); category1.setDesc("haha"); category1.setName("my name"); Category category2 = new Category(); category2.setDesc("2 cat"); category2.setName("my 2"); Set<Category> categories = new HashSet<Category>(); categories.add(category1); categories.add(category2); StockEntity stock = new StockEntity(); stock.setCategories(categories); stock.setStockName("my new stock"); stock.setStockCode("my codes"); session.save(stock); StockDailyRecordEntity stockDailyRecordEntity1 = new StockDailyRecordEntity(); stockDailyRecordEntity1.setDate(new Timestamp(new Date().getTime())); stockDailyRecordEntity1.setPriceChange("12334.3"); stockDailyRecordEntity1.setPriceOpen("123ahah"); stockDailyRecordEntity1.setPriceClose("123close"); stockDailyRecordEntity1.setVolume("123volume"); stockDailyRecordEntity1.setStock(stock); session.save(stockDailyRecordEntity1); StockDailyRecordEntity stockDailyRecordEntity2 = new StockDailyRecordEntity(); stockDailyRecordEntity2.setDate(new Timestamp(new Date().getTime())); stockDailyRecordEntity2.setPriceChange("a12334.3"); stockDailyRecordEntity2.setPriceOpen("a123ahah"); stockDailyRecordEntity2.setPriceClose("a123close"); stockDailyRecordEntity2.setVolume("a123volume"); stockDailyRecordEntity2.setStock(stock); session.save(stockDailyRecordEntity2); tx.commit(); } catch (Exception e) { if (tx!=null) tx.rollback(); throw e; } finally { session.close(); } } }
true
a6b91b86c6b53ef9a086a2fb4fba7e57c371b174
Java
caraeppes/PassionBy5dot0
/EduWaiterAppServer/src/main/java/com/caraeppes/EduWaiterAppServer/services/AdminAccountService.java
UTF-8
2,163
2.265625
2
[]
no_license
package com.caraeppes.EduWaiterAppServer.services; import com.caraeppes.EduWaiterAppServer.models.AdminAccount; import com.caraeppes.EduWaiterAppServer.models.Restaurant; import com.caraeppes.EduWaiterAppServer.repositories.AdminAccountRepository; import com.caraeppes.EduWaiterAppServer.repositories.RestaurantRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class AdminAccountService { private AdminAccountRepository adminAccountRepository; private RestaurantRepository restaurantRepository; @Autowired public AdminAccountService(AdminAccountRepository adminAccountRepository, RestaurantRepository restaurantRepository) { this.adminAccountRepository = adminAccountRepository; this.restaurantRepository = restaurantRepository; } public AdminAccount create(AdminAccount adminAccount) { return adminAccountRepository.save(adminAccount); } public AdminAccount findById(Long id) { return adminAccountRepository.getOne(id); } public List<AdminAccount> findAll() { return adminAccountRepository.findAll(); } public AdminAccount findByUsername(String username) { return adminAccountRepository.findAdminAccountByUsername(username); } public AdminAccount update(AdminAccount adminAccount, Long id) { AdminAccount original = adminAccountRepository.getOne(id); original.setFirstName(adminAccount.getFirstName()); original.setLastName(adminAccount.getLastName()); original.setRestaurant(adminAccount.getRestaurant()); return adminAccountRepository.save(original); } public AdminAccount updateRestaurant(Long restaurantId, Long id) { AdminAccount original = adminAccountRepository.getOne(id); Restaurant restaurant = restaurantRepository.getOne(restaurantId); original.setRestaurant(restaurant); return adminAccountRepository.save(original); } public Boolean deleteById(Long id) { adminAccountRepository.deleteById(id); return true; } }
true
71b1b1fee9f35bbe57ab24e5e7004b43a4faae70
Java
rashidjes/prueba_practica
/spring-boot-prueba-practica/src/main/java/com/pruebapractica/api/controllers/TipoActivoController.java
UTF-8
1,043
2.25
2
[]
no_license
package com.pruebapractica.api.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.pruebapractica.api.entities.TipoActivo; import com.pruebapractica.api.exceptions.NotFoundException; import com.pruebapractica.api.services.TipoActivoService; @CrossOrigin @RestController @RequestMapping("/api") public class TipoActivoController { @Autowired private TipoActivoService tipoActivoService; @GetMapping("/obtener-todos-tipos-activos") public List<TipoActivo> obtenerTodosTiposActivos() { List<TipoActivo> lTiposActivos = tipoActivoService.getAllTiposActivos(); if (lTiposActivos.size() == 0) throw new NotFoundException("No se encontró ningún tipo de activo"); return lTiposActivos; } }
true
2a4be0a29135983a81ea8a1ef6a1efa0a7ffdfe2
Java
KaProjects/Accountant
/desktop/src/main/java/org/kaleta/accountant/service/ProceduresService.java
UTF-8
4,976
2.703125
3
[]
no_license
package org.kaleta.accountant.service; import org.kaleta.accountant.Initializer; import org.kaleta.accountant.backend.manager.Manager; import org.kaleta.accountant.backend.manager.ManagerException; import org.kaleta.accountant.backend.manager.ProceduresManager; import org.kaleta.accountant.backend.model.ProceduresModel; import org.kaleta.accountant.common.ErrorHandler; import java.util.ArrayList; import java.util.List; /** * Provides access to data source which is related to procedures. */ public class ProceduresService { private ProceduresModel proceduresModel; ProceduresService(){ // package-private } private ProceduresModel getModel(String year) throws ManagerException { if (proceduresModel == null) { proceduresModel = new ProceduresManager(year).retrieve(); } if (!proceduresModel.getYear().equals(year)) { proceduresModel = new ProceduresManager(year).retrieve(); } return new ProceduresModel(proceduresModel); } public void invalidateModel(){ proceduresModel = null; } /** * Returns list of procedure groups. */ public List<ProceduresModel.Group> getProcedureGroupList(String year) { try { return getModel(year).getGroup(); } catch (ManagerException e){ Initializer.LOG.severe(ErrorHandler.getThrowableStackTrace(e)); throw new ServiceFailureException(e); } } /** * Returns list of procedure group names. */ public List<String> getProcedureGroupNameList(String year) { try { List<String> names = new ArrayList<>(); for (ProceduresModel.Group group : getModel(year).getGroup()){ names.add(group.getName()); } return names; } catch (ManagerException e){ Initializer.LOG.severe(ErrorHandler.getThrowableStackTrace(e)); throw new ServiceFailureException(e); } } /** * Creates procedure according to specified values. */ public void createProcedure(String year, String name, String groupName, List<ProceduresModel.Group.Procedure.Transaction> transactions){ try { Manager<ProceduresModel> manager = new ProceduresManager(year); ProceduresModel model = manager.retrieve(); ProceduresModel.Group group = null; for (ProceduresModel.Group groupModel : model.getGroup()){ if (groupModel.getName().equals(groupName)) group = groupModel; } if (group == null) { ProceduresModel.Group newGroup = new ProceduresModel.Group(); newGroup.setName(groupName); model.getGroup().add(newGroup); group = newGroup; } ProceduresModel.Group.Procedure procedure = new ProceduresModel.Group.Procedure(); procedure.setName(name); procedure.setId(String.valueOf(group.getProcedure().size())); procedure.getTransaction().addAll(transactions); group.getProcedure().add(procedure); manager.update(model); Initializer.LOG.info("Procedure created: group=" + groupName + " id=" + procedure.getId() + " name='" + procedure.getName() + "'"); invalidateModel(); } catch (ManagerException e){ Initializer.LOG.severe(ErrorHandler.getThrowableStackTrace(e)); throw new ServiceFailureException(e); } } /** * Updates procedure specified by 'id' and 'type' according to new values. */ public void updateProcedure(String year, String id, String newName, String groupName, List<ProceduresModel.Group.Procedure.Transaction> newTransactions){ try { Manager<ProceduresModel> manager = new ProceduresManager(year); ProceduresModel model = manager.retrieve(); ProceduresModel.Group group = null; for (ProceduresModel.Group groupModel : model.getGroup()){ if (groupModel.getName().equals(groupName)) group = groupModel; } if (group == null) { throw new ManagerException("Group '" + groupName + "' not found!"); } for (ProceduresModel.Group.Procedure procedure : group.getProcedure()){ if (procedure.getId().equals(id)){ procedure.setName(newName); procedure.getTransaction().clear(); procedure.getTransaction().addAll(newTransactions); } } manager.update(model); Initializer.LOG.info("Procedure updated: id=" + id + " name='" + newName + "'"); invalidateModel(); } catch (ManagerException e){ Initializer.LOG.severe(ErrorHandler.getThrowableStackTrace(e)); throw new ServiceFailureException(e); } } }
true
73686f1312d9695bfbad9bba069fa50aae56bc14
Java
JuniorDurand/Paradigmas
/TrabalhoParadigmas_03/src/formas/Cilindro.java
UTF-8
646
3.15625
3
[]
no_license
package formas; public class Cilindro extends Circulo{ protected double h; public Cilindro(double x, double y, double r, double h) { super(x, y, r); this.h = h; } public double getAltura() { return h; } public void setAltura(double h) { this.h = h; } public double calcArea() { return 2*super.calcArea() + h*super.calcCirc(); } public double calcVolume() { return h*super.calcArea(); } @Override public String toString() { return "Cilindro [Altura = " + h + ", Raio = " + r + ", x = " + x + ", y = " + y + ", Area = " + calcArea() + ", Volume = " + calcVolume() + "]"; } }
true
2fd537fc0d8f4ae326624a1a3bdfdbd493b38a09
Java
chenlei7/hospital
/hospital/src/main/java/com/sxxy/hospital/equipment/service/EquipmentService.java
UTF-8
332
1.8125
2
[]
no_license
package com.sxxy.hospital.equipment.service; import com.sxxy.hospital.equipment.entity.Equipment; import java.util.List; public interface EquipmentService { //修改器材现状 int editequipmentNowState(String equipmentState, List<String> editNum); //增加器材 Equipment addEquipment(Equipment equipment); }
true
21db1adcd9541195e1e59757dbb82706004b53a5
Java
disiol/SQLCmd
/src/main/java/ua/com/denisimusIT/SQLCmd/controller/command/UpdateColumVaulue.java
UTF-8
1,539
2.5
2
[]
no_license
package ua.com.denisimusIT.SQLCmd.controller.command; public class UpdateColumVaulue implements Command{ @Override public boolean canProcess(String command) { return false; } @Override public void process(String command) { } @Override public String description() { return null; } @Override public String format() { return null; } // TODO•Команда обновит запись, установив значение column2 = value2, длякоторой соблюдается условие column1 = value1 //•Формат: ua.com.denisimusIT.SQLCmd.controller.command.update | tableName | column1 | value1 | column2 | value2 //•где: tableName - имя таблицы //•column1 - имя столбца записи которое проверяется //•value1 - значение которому должен соответствовать столбец column1 для обновляемой записи //•column2 - имя обновляемого столбца записи //•value2 - значение обновляемого столбца записи //•columnN - имя n-го обновляемого столбца записи //•valueN - значение n-го обновляемого столбца записи //•Формат вывода: табличный, как при ua.com.denisimusIT.SQLCmd.controller.command.find со старыми значениями обновленных записей. }
true
cf6cce13cc80c91ec85317fd10de991bb6476f7a
Java
Nekoshido/ImageViewer
/src/edu/ub/prog2/OrdonezVivancosHector/model/DadesVisor.java
UTF-8
10,011
2.6875
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.ub.prog2.OrdonezVivancosHector.model; import edu.ub.prog2.utils.model.*; import java.io.*; import java.util.*; /** * *@author Hector Ordonez * *Classe usada com a distribuidor dins del paquet model * */ public class DadesVisor implements Serializable { private int contadorID = 0; private LlistaImatges biblioteca; private ArrayList<Album> llistaAlbums; private boolean aleatori; /** * Constructor de la classe DadesVisor on es crea un LlistaFile * */ public DadesVisor(){ biblioteca = new LlistaImatges(); llistaAlbums = new ArrayList<Album>(); aleatori = false; } /** * Funcio que elimina un fitxer segons la id. * *@param int i, es la id de la imatge a borrar */ public void eliminarImatge(int idima){ Iterator itrLlistaAlbum = llistaAlbums.iterator(); Album alb = null; while(itrLlistaAlbum.hasNext()){ alb = (Album) itrLlistaAlbum.next(); alb.eliminarImatge(idima); } biblioteca.eliminarImatge(idima); } /** * Funcio que afegeix un fitxer a la llista amb el atribut f i una id. * *@param File f, es passa el fitxer per afegirlo * * @return: retorna un int que es a id */ public int afegirImatge(File f){ biblioteca.afegirImatge(f, contadorID); int x1 = contadorID; contadorID++; return x1; } /** * Funcio que busca el fitxer amb la mateixa id a la llista i afegeix el que falta * *@param IFitxer fil, es passa el fitxer per afegir el que queda *@param int i, es passa la id */ public void afegiFitxer(FitxerImatge fil, int i){ biblioteca.afegiFitxer(fil, i); } /** * Funcio que guarda en un fitxer el DadesVisor * *@param String nomarxiu, adreça on es vol guardar l'arxiu * *@throws: FileNotFoundException, en cas de no trobar l'arxiu i IOException, en cas d'error IO */ public void guardarFitxer(String nomarxiu) throws FileNotFoundException, IOException{ File Llistfitxer = new File(nomarxiu); //F:\\PII\\Laboratori\\Visor\\Fitxers\\Fitxer.txt FileOutputStream fout= new FileOutputStream(Llistfitxer); ObjectOutputStream oos = new ObjectOutputStream(fout); oos.writeObject(this); fout.close(); /**oos.close(); */ } /** * Funcio que recupera d'un fitxer un el DadesVisor * *@param String nomarxiu, adreça on es vol recuperar l'arxiu * *@throws: FileNotFoundException, en cas de no trobar l'arxiu i IOException, en cas d'error IO */ public DadesVisor recuperarFitxer(String nomarxiu) throws FileNotFoundException, IOException, ClassNotFoundException{ // F:\\PII\\Laboratori\\Visor\\Fitxers\\Fitxer.txt File Llistfitxer = new File(nomarxiu); FileInputStream fin=new FileInputStream(Llistfitxer); ObjectInputStream ois = new ObjectInputStream(fin); DadesVisor noudadesvisor = (DadesVisor) ois.readObject(); fin.close(); return noudadesvisor; } /** * Funcio que crea un nou album i lafageix a la llista * *@param String nom, que es el nom de lalbum * */ public void crearAlbum(String nom){ Album noualbum = new Album(nom); llistaAlbums.add(noualbum); } /** * Funcio que afegeix una imatge a lalbum * *@param String nomalbum, que es el nom de lalbum, * *@param int idimatge que es la id de la imatge */ public void afegirImatgeAlbum(String nomalbum, int idimatge){ FitxerImatge imatge_a_afegir = biblioteca.getImatgeperid(idimatge); Album album_on_safegeix = getAlbumperNom(nomalbum); if (album_on_safegeix != null){ if(imatge_a_afegir != null){ album_on_safegeix.afegirFitxerImatge(imatge_a_afegir); } } } /** * Funcio que crea lalbum complet amb tots els parametres * *@param String nom, que es el nom de lalbum, * *@param String autor es el nom de lautor *@param String lloc es el nom del lloc *@param String tema es el tema de lalbum *@param String tipus es el tipus de lalbum */ public void crearAlbumComplet(String nom, String autor, String lloc, String tema, String tipus){ Iterator<Album> itrAlbums = llistaAlbums.iterator(); while(itrAlbums.hasNext()){ Album albumdintre = (Album) itrAlbums.next(); if(albumdintre.getNom().equals(nom)){ albumdintre.setAutor(autor); albumdintre.setLloc(lloc); albumdintre.setTipus(tipus); albumdintre.setTema(tema); albumdintre.setData(Calendar.getInstance().getTime()); } } } /** * Metode que retorna la LListaImatges * @return biblioteca * */ public LlistaImatges getBiblioteca() { return biblioteca; } /** * Metode que guarda una LlistaImatges * @param LlistaImatges biblioteca * */ public void setBiblioteca(LlistaImatges biblioteca) { this.biblioteca = biblioteca; } /** * Metode que retorna l'array t'albums * @return ArrayList<Album> llistaAlbums * */ public ArrayList<Album> getArrayAlbums() { return llistaAlbums; } /** * Metode que retorna la el contador de les ID * @return int contadorID * */ public int getContadorID() { return contadorID; } /** * Metode que guarda el contador de les ID * @param int contadorID * */ public void setContadorID(int contadorID) { this.contadorID = contadorID; } /** *Metode que retorna un Fitxer passant-li la ID * @return FitxerImatge amb la mateixa id * */ public FitxerImatge getFitxerperID(int fitxerid){ return biblioteca.getImatgeperid(fitxerid); } /** *Metode que retorna un Fitxer passant-li el nom * @return FitxerImatge amb el mateix nom * */ public FitxerImatge getImatgeperNom(String fitxernom){ return biblioteca.getImatgeperNom(fitxernom); } /** * Metode que guarda si l aleatoriesta activat * @param boolean noualeatori * */ public void setAleatori(boolean noualeatori){ this.aleatori = noualeatori; } /** *Metode que retorna si l aleatori esta activat * @return aleatori * */ public boolean getAleatori(){ return this.aleatori; } /** * Metode que guarda una array d'Albums * @param ArrayList<Album> llistaAlbums * */ public void setLlistaAlbums(ArrayList<Album> llistaAlbums) { this.llistaAlbums = llistaAlbums; } /** * Metode que retorna luna llista de Ifitxers * @return IFitxer[] * */ public IFitxer[] getLlistaFotos(){ return biblioteca.getLlistaFotos(); } /** * Funcio que agafa lalbum passantli un nom * *@param String nomalbum, que es el nom de lalbum *@return: retorna un album */ public Album getAlbumperNom(String nomalbum){ Album alb; Iterator itrAlbum = llistaAlbums.iterator(); while(itrAlbum.hasNext()){ alb = (Album) itrAlbum.next(); if(alb.getNom().equals(nomalbum)){ return alb; } } return null; } /** * Funcio que elimina lalbum amb el nom que li passes * *@param String nomaborrar, que es el nom de lalbum a borrar */ public void eliminarAlbum(String nomaborrar){ Iterator itrAlbum = llistaAlbums.iterator(); Album italbum; int cnt = 0; Boolean trobat = false; while(itrAlbum.hasNext() && !trobat){ italbum = (Album) itrAlbum.next(); if(italbum.getNom().equals(nomaborrar)){ trobat = true; } else{ cnt++; } } if(trobat){ llistaAlbums.remove(cnt); } } /** * Funcio que agafa tots els noms dels albums * *@return: linia que es on es guarden els noms dels albums */ public String mostrarNomAlbums(){ String linia = ""; Iterator itrAlbum = llistaAlbums.iterator(); Album italbum; while(itrAlbum.hasNext()){ italbum = (Album) itrAlbum.next(); linia = linia + italbum.getNom()+ "\n"; } return linia; } /** * Funcio que retorna una llista de Strings amb els noms dels albums * *@return: linia que es on es guarden els noms dels albums */ public String[] getLlistaAlbums(){ String[] linia = new String[llistaAlbums.size()]; Iterator itrAlbum = llistaAlbums.iterator(); Album italbum; int i = 0; while(itrAlbum.hasNext()){ italbum = (Album) itrAlbum.next(); linia[i] = italbum.getNom(); i++; } return linia; } /** * Funcio que elimina una imatge de lalbum * *@param String nomaalbum, que es el nom de lalbum don vols borrar *@param int idalbum, es la ide de la imatge a eliminar */ public void eliminarImatgeAlbum(String nomalbum, int idalbum){ Album nou = getAlbumperNom(nomalbum); nou.eliminarImatge(idalbum); } }
true
67a1233ff9a13fa7e12f9ab926a65bb8a3b31139
Java
chenlixin11/demo
/rxt-bsb-rest/src/main/java/rxt/bsb/rest/web/RoleController.java
UTF-8
2,525
2.046875
2
[]
no_license
package rxt.bsb.rest.web; import com.github.pagehelper.Page; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import rxt.bsb.rest.common.Enums.ResultCode; import rxt.bsb.rest.common.page.PageInfo; import rxt.bsb.rest.po.Permiss; import rxt.bsb.rest.po.Role; import rxt.bsb.rest.service.PermissService; import rxt.bsb.rest.service.RoleService; import javax.servlet.http.HttpServletRequest; import java.util.List; @RestController @RequestMapping("/role") public class RoleController { private final static Logger logger = LoggerFactory.getLogger(RoleController.class); @Autowired private RoleService roleService; @Autowired private PermissService permissService; /** * 角色数据分页查询 * @param request * @param pageNo * @param pageSize * @return */ @GetMapping( value = "page") Object queryRolePage(HttpServletRequest request, @RequestParam(name = "pageNo" ,defaultValue = "1") int pageNo , @RequestParam(name = "pageSize" ,defaultValue = "10")int pageSize ){ Page<Role> page = roleService.queryRolePage(pageNo,pageSize); PageInfo<Role> pageInfo= new PageInfo<>(page); return pageInfo; } /** * 获取角色集合 * @param request * @return */ @GetMapping( value = "list" ) Object queryRoleList(HttpServletRequest request ){ return roleService.roleList(); } /** * 保存角色 * @param r * @return */ @PostMapping( value = "save" ) public Object saveRoler(Role r) { return roleService.saveRole( r) == 1 ? ResultCode.SUCCESS : ResultCode.ERROR; } /** * 更新 * @param r * @return */ @PostMapping( value = "update" ) public Object updateRole(Role r ) { return roleService.updateRole( r) == 1 ? ResultCode.SUCCESS : ResultCode.ERROR; } /** * 删除 * @param r * @return */ @DeleteMapping( value = "rm/{id}" ) public Object rmRole(Role r ) { return roleService.rmRole( r ) == 1 ? ResultCode.SUCCESS : ResultCode.ERROR; } /** * 查询菜单集合 * @param request * @return */ @GetMapping( value = "/permiss" ) public Object cacheOfList(HttpServletRequest request){ List<Permiss> permAll = permissService.queryPermissList(); return permAll; } /** * 添加菜单信息 * @param request * @param pdata * @return */ @PostMapping( value = "/permiss/save") public Object save(HttpServletRequest request, String pdata){ return permissService.save( pdata ); } }
true
a6df22045d031c283d01863a409152443e47a34a
Java
FilipeGods/Java_training
/TEST/src/test.java
UTF-8
206
2.109375
2
[]
no_license
public class test { public static void main(String[]args) { //GUI g = new GUI(); //g.setVisible(true); int x=0; System.out.println(++x); x=0; System.out.println(x-=1); } }
true
0dbbb6705ec4d8003f5006cd78c3968958b47ff4
Java
tonystarsoon/DeepStatus
/SearchListView-master/app/src/main/java/vivian/com/searchlistview/widget/SearchListViewNoText.java
UTF-8
22,088
1.695313
2
[ "MIT", "Apache-2.0" ]
permissive
package vivian.com.searchlistview.widget; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.animation.DecelerateInterpolator; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.Scroller; import java.text.SimpleDateFormat; import java.util.Locale; import vivian.com.searchlistview.R; /** * * ,%%%%%%%%, * ,%%/\%%%%/\%% * ,%%%\c "" J/%%% * %. %%%%/ o o \%%% * `%%. %%%% _ |%%% * `%% `%%%%(__Y__)%%' * // ;%%%%`\-/%%%' * (( / `%%%%%%%' * \\ .' | * \\ / \ | | * \\/ ) | | * \ /_ | |__ * (___________))))))) 攻城湿 * * * _ _ * __ _(_)_ _(_) __ _ _ __ * \ \ / / \ \ / / |/ _` | '_ \ * \ V /| |\ V /| | (_| | | | | * \_/ |_| \_/ |_|\__,_|_| |_| * * * @author vivian:the girl who is in love with 7heaven deeply * create at 15/11/23 17:10 */ //纯动画,没有文字的版本 public class SearchListViewNoText extends ListView implements OnScrollListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, AdapterView.OnItemSelectedListener { private static final String TAG = "listview"; private final static int SCROLL_DURATION = 200; // scroll back duration private final static float OFFSET_RADIO = 2.5f; // support iOS like pull 2.5f /** * 状态 **/ private int state = TOUCH_STATE_DONE; /** * 完成 **/ private final static int TOUCH_STATE_DONE = 0; /** * 松开更新 **/ private final static int TOUCH_STATE_RELEASE_TO_REFRESH = 1; /** * 下拉更新 **/ private final static int TOUCH_STATE_PULL_TO_REFRESH = 2; /** * 正在刷新 **/ private final static int TOUCH_STATE_REFRESHING = 3; /** * 已加载全部 */ private final static int LOAD_ALL = 4; /** * 标识查看更多状态 **/ private boolean isMore = false; private Scroller scroller; /** * 头部刷新的布局 **/ private View viewHeader; /** * 尾部加载更多的布局 **/ private View viewFooter; private int headerContentHeight; // 记录头部的高度 /** * 头部显示下拉刷新等的控件 **/ private RelativeLayout headContentLayout; private ProgressBar progressBarHeader; /** * Footer 刷新控件 */ private ProgressBar progressBarFooter; /** * 内容显示 **/ private RelativeLayout layoutContent; /** * 头部高度 **/ private int headHeight; /** * 第一次记录的Y轴坐标 **/ private float firstY; /** * 最后一次记录的Y轴坐标 **/ private float lastY; /** * 总的item个数 */ private int totalItemCount; /** * 是否要使用下拉刷新功能 **/ public boolean enablePullRefresh = true; /** * 是否自动获取更多 */ private boolean isAutoFetchMore = false; /** * 是否需要刷新功能,默认有刷新功能 */ private boolean isEnableRefresh = true; private OnItemClickListener onItemClickListener; private OnItemLongClickListener onItemLongClickListener; private OnItemSelectedListener onItemSelectedListener; private OnRefreshListener onRefreshListener; private OnLastItemVisibleListener onLastItemVisibleListener; public SearchListViewNoText(Context context) { super(context); init(); } public SearchListViewNoText(Context context, AttributeSet attrs) { super(context, attrs); init(); } public SearchListViewNoText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { scroller = new Scroller(getContext(), new DecelerateInterpolator()); measureView(getHeaderView()); headHeight = getHeaderView().getMeasuredHeight(); getHeaderView().setPadding(0, -1 * headHeight, 0, 0); getHeaderView().invalidate(); // this.setBackgroundResource(R.color.stand_default_bg_color); //添加头部视图 super.addHeaderView(getHeaderView(), null, false); setOnScrollListener(this); super.setOnItemClickListener(this); super.setOnItemLongClickListener(this); super.setOnItemSelectedListener(this); } /** * 获取头部视图 * * @return View */ private View getHeaderView() { if (viewHeader == null) { viewHeader = LayoutInflater.from(getContext()).inflate(R.layout.model_pull_listview_head_no_text, null); headContentLayout = (RelativeLayout) viewHeader.findViewById(R.id.head_contentLayout); progressBarHeader = (ProgressBar) viewHeader.findViewById(R.id.pulldown_footer_loading); layoutContent = (RelativeLayout) viewHeader.findViewById(R.id.layoutContent); final ViewConfiguration configuration = ViewConfiguration.get(getContext()); mTouchSlop = configuration.getScaledTouchSlop(); } if (!isEnableRefresh) { headContentLayout.setVisibility(View.GONE); } return viewHeader; } /** * 获取尾部视图 * * @return View */ private View getFooterView() { if (viewFooter == null) { viewFooter = LayoutInflater.from(getContext()).inflate(R.layout.model_pull_listview_footer_no_text, null); progressBarFooter = (ProgressBar) viewFooter.findViewById(R.id.pulldown_footer_loading); viewFooter.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!isMore) { isMore = true; progressBarFooter.setVisibility(View.VISIBLE); if (onLastItemVisibleListener != null) { onLastItemVisibleListener.onLastItemVisible(); } } } }); } return viewFooter; } /** * 添加头部的view 与下拉刷新不冲突 * * @param header 视图 */ public void addHeaderView(View header) { if (null == header) { return; } if (!isEnableRefresh) { layoutContent.removeView(getHeaderView()); headHeight = getHeaderView().getMeasuredHeight(); } layoutContent.addView(header); measureView(header); headerContentHeight = header.getMeasuredHeight(); headHeight += headerContentHeight; getHeaderView().setPadding(0, -1 * headHeight, 0, 0); } /** * 移除头部自定义添加内容 */ public void removeHeader() { layoutContent.removeAllViews(); measureView(getHeaderView()); //防止多次添加导致高度计算失误 headHeight = getHeaderView().getMeasuredHeight(); } @Override public void setOnItemClickListener(OnItemClickListener listener) { this.onItemClickListener = listener; } @Override public void setOnItemLongClickListener(OnItemLongClickListener listener) { this.onItemLongClickListener = listener; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (onItemClickListener == null) { return; } if (state != TOUCH_STATE_REFRESHING&&state!=TOUCH_STATE_PULL_TO_REFRESH) onItemClickListener.onItemClick(parent, view, position > 0 ? position - 1 : 0, id); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (onItemSelectedListener == null) { return; } onItemSelectedListener.onItemSelected(parent, view, position > 0 ? position - 1 : 0, id); } @Override public void onNothingSelected(AdapterView<?> parent) { } @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { return onItemLongClickListener != null && onItemLongClickListener.onItemLongClick(parent, view, position > 0 ? position - 1 : 0, id); } @Override public void setOnItemSelectedListener(OnItemSelectedListener listener) { this.onItemSelectedListener = listener; } public Object getItemAtPosition(int position) { return super.getItemAtPosition(position + 1); } public long getItemIdAtPosition(int position) { return super.getItemIdAtPosition(position + 1); } /** * 设置是否可用下拉刷新 * * @param enable boolean */ public void pullRefreshEnable(boolean enable) { enablePullRefresh = enable; } /** * 设置是否开启刷新功能,上拉下拉均包括。设为 false 的话,刷新功能均不可用,为普通列表 * * @param enable */ public void setEnableRefresh(boolean enable) { isEnableRefresh = enable; } /** * 是否开启自动获取更多 自动获取更多,将会隐藏footer,并在到达底部的时候自动刷新 */ public void setAutoFetchMore(boolean enable) { isAutoFetchMore = enable; if (viewFooter == null) { return; } progressBarFooter.setVisibility(View.GONE); } private final int TOUCH_STATE_REST = 0; private final int TOUCH_STATE_HORIZONTAL_SCROLLING = 1; private final int TOUCH_STATE_VERTICAL_SCROLLING = -1; private int mTouchState = TOUCH_STATE_REST; private int mTouchSlop; private float mLastMotionX; private float mLastMotionY; /** * 触摸事件的处理 */ public boolean onTouchEvent(MotionEvent ev) { final int action = ev.getAction(); cancelLongPress(); switch (action) { case MotionEvent.ACTION_DOWN: // 按下的时候 if (!scroller.isFinished()) { scroller.abortAnimation(); } firstY = ev.getRawY(); lastY = firstY; Log.v(TAG, "在down时候记录当前位置: X: " + ev.getX() + " Y: " + ev.getRawY()); break; case MotionEvent.ACTION_MOVE: // 手指正在移动的时候 if (!enablePullRefresh) { // return super.onTouchEvent(ev); break; } if (firstY == -1) { firstY = ev.getRawY(); lastY = firstY; } final float deltaY = ev.getRawY() - lastY; lastY = ev.getRawY(); if (getFirstVisiblePosition() == 0 && (Math.abs(getHeaderView().getPaddingTop()) < headHeight || deltaY > 0)) { final int paddingTop = getHeaderView().getPaddingTop(); // change paddingTop with the movement of the finger getHeaderView().setPadding(0, (int) (paddingTop + deltaY / OFFSET_RADIO), 0, 0); if (getHeaderView().getPaddingTop() > 0) { if (state != TOUCH_STATE_RELEASE_TO_REFRESH && state != TOUCH_STATE_REFRESHING) { state = TOUCH_STATE_RELEASE_TO_REFRESH; changeHeaderViewByState(); } } else { if (state != TOUCH_STATE_PULL_TO_REFRESH && state != TOUCH_STATE_REFRESHING) { state = TOUCH_STATE_PULL_TO_REFRESH; changeHeaderViewByState(); } } return true; } else if (getLastVisiblePosition() == totalItemCount - 1 && deltaY < 0) { Log.i(TAG, "Footer" + String.valueOf(-deltaY / OFFSET_RADIO)); return true; } break; case MotionEvent.ACTION_UP: // 手指抬起来的时候 if (getFirstVisiblePosition() == 0 || getFirstVisiblePosition() == 1) { if (enablePullRefresh) { final int paddingTop = getHeaderView().getPaddingTop(); switch (state) { case TOUCH_STATE_REFRESHING: scroller.startScroll(0, paddingTop, 0, -paddingTop, SCROLL_DURATION); state = TOUCH_STATE_DONE; break; case TOUCH_STATE_PULL_TO_REFRESH: if (paddingTop + headHeight > headHeight * 0.75) { //高过搜索框0.75的 那么显示搜索框 scroller.startScroll(0, paddingTop, 0, -(paddingTop), SCROLL_DURATION); } else if (paddingTop + headHeight > 0 && paddingTop + headHeight < headHeight * 0.25) { if (firstY - lastY < 0) {//向下 scroller.startScroll(0, paddingTop, 0, -(headHeight - headerContentHeight + paddingTop), SCROLL_DURATION); } else {//向上 scroller.startScroll(0, paddingTop, 0, (headHeight - headerContentHeight + paddingTop), SCROLL_DURATION); } } else if (firstY - lastY < 0) {//向下 scroller.startScroll(0, paddingTop, 0, -(headHeight - headerContentHeight + paddingTop)); } else {//向上 scroller.startScroll(0, paddingTop, 0, -(headHeight + paddingTop)); } state = TOUCH_STATE_DONE; break; case TOUCH_STATE_RELEASE_TO_REFRESH: state = TOUCH_STATE_REFRESHING; //将进度切换到正在刷新 changeHeaderViewByState(); scroller.startScroll(0, paddingTop, 0, -paddingTop, SCROLL_DURATION); if (onRefreshListener != null) { onRefreshListener.onRefresh(); } break; default: break; } } } else if (getLastVisiblePosition() == totalItemCount - 1) { // 数量充满屏幕才触发 if (isAutoFetchMore && !isMore && onLastItemVisibleListener != null /*&& isFillScreenItem()*/ && viewFooter != null) { progressBarFooter.setVisibility(View.VISIBLE); isMore = true; onLastItemVisibleListener.onLastItemVisible(); return true; } } else { //这里只是为了方便计算 //不在第一个和最后一个的时候 隐藏头部 //不需要处理动画效果 getHeaderView().setPadding(0, -1 * headHeight, 0, 0); } Log.i(TAG, "up:" + getLastVisiblePosition() + " " + (totalItemCount - 1)); firstY = -1; lastY = -1; // reset break; } return super.onTouchEvent(ev); } /** * 条目是否填满整个屏幕 */ private boolean isFillScreenItem() { final int firstVisiblePosition = getFirstVisiblePosition(); final int lastVisiblePostion = getLastVisiblePosition() - getFooterViewsCount(); final int visibleItemCount = lastVisiblePostion - firstVisiblePosition + 1; final int totalItemCount = getCount() - getFooterViewsCount(); return (visibleItemCount < totalItemCount); } @Override public void computeScroll() { if (scroller.computeScrollOffset()) { getHeaderView().setPadding(0, scroller.getCurrY(), 0, 0); postInvalidate(); } } /** * 自动刷新,显示头部 * * @param show boolean */ public void showHeader(boolean show) { int paddingTop = getHeaderView().getPaddingTop(); if (show) { scroller.startScroll(0, paddingTop, 0, -paddingTop, SCROLL_DURATION); } } @Override public void onScroll(AbsListView view, int firstVisiableItem, int visibleItemCount, int totalItemCount) { this.totalItemCount = totalItemCount; if (getLastVisiblePosition() == totalItemCount - 1) { // 数量充满屏幕才触发 if (isAutoFetchMore && !isMore && onLastItemVisibleListener != null /*&& isFillScreenItem()*/ && viewFooter != null) { progressBarFooter.setVisibility(View.VISIBLE); isMore = true; onLastItemVisibleListener.onLastItemVisible(); } } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } /** * 计算view的宽高 * * @param child View */ private void measureView(View child) { ViewGroup.LayoutParams lp = child.getLayoutParams(); if (lp == null) { lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0, lp.width); int lpHeight = lp.height; int childHeightSpec; if (lpHeight > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); } SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss", Locale.getDefault()); public void onRefreshComplete() { state = TOUCH_STATE_DONE; changeHeaderViewByState(); final int paddingTop = getHeaderView().getPaddingTop(); scroller.startScroll(0, paddingTop, 0, -(headHeight + paddingTop), SCROLL_DURATION); invalidate(); isMore = false; if (viewFooter == null) { return; } progressBarFooter.setVisibility(View.GONE); // getFooterView().setVisibility(View.GONE); } public void setLoadAll() { state = LOAD_ALL; changeHeaderViewByState(); pullRefreshEnable(false); } // 当状态改变时候,调用该方法,以更新界面 private void changeHeaderViewByState() { if (isEnableRefresh) { switch (state) { case TOUCH_STATE_RELEASE_TO_REFRESH: Log.v(TAG, "当前状态,松开刷新"); progressBarHeader.setVisibility(View.GONE); break; case TOUCH_STATE_PULL_TO_REFRESH: Log.v(TAG, "当前状态,下拉刷新"); progressBarHeader.setVisibility(View.GONE); break; case TOUCH_STATE_REFRESHING: Log.v(TAG, "当前状态,正在刷新..."); progressBarHeader.setVisibility(View.VISIBLE); break; case TOUCH_STATE_DONE: Log.v(TAG, "当前状态,done"); progressBarHeader.setVisibility(View.GONE); break; case LOAD_ALL: Log.v(TAG, "当前状态,load all"); progressBarFooter.setVisibility(View.GONE); break; } } } /** * 下拉刷新监听事件 * * @param listener OnRefreshListener */ public void setOnRefreshListener(OnRefreshListener listener) { this.onRefreshListener = listener; } /** * 获取更多监听事件 * * @param listener OnLastItemVisibleListener */ public void setOnLastItemVisibleListener(OnLastItemVisibleListener listener) { this.onLastItemVisibleListener = listener; if (listener == null) { removeFooterView(getFooterView()); viewFooter = null; progressBarFooter = null; } else { if (isEnableRefresh && viewFooter == null) { addFooterView(getFooterView()); } } if (viewFooter == null) { return; } progressBarFooter.setVisibility(View.GONE); } /** * 刷新事件接口 */ public interface OnRefreshListener { /** * 刷新事件接口 这里要注意的是获取更多完 要关闭 刷新的进度条onRefreshComplete() **/ void onRefresh(); } /** * 获取更多事件接口 */ public interface OnLastItemVisibleListener { /** * 刷新事件接口 这里要注意的是获取更多完 要关闭 更多的进度条 onRefreshComplete() **/ void onLastItemVisible(); } }
true
e19e7dc448b972cb9e7d615cefa14b22d0acf675
Java
zzzzata/school-admin
/src/main/java/io/renren/controller/ExaminationResultController.java
UTF-8
4,643
1.898438
2
[]
no_license
package io.renren.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; 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.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import io.renren.entity.ExaminationResultEntity; import io.renren.entity.SysUserEntity; import io.renren.pojo.ExaminationResultPOJO; import io.renren.service.ExaminationResultService; import io.renren.utils.PageUtils; import io.renren.utils.R; /** * 统考成绩 * * @author hq * @email hq@hq.com * @date 2018-08-07 09:21:13 */ @Controller @RequestMapping("examinationresult") public class ExaminationResultController extends AbstractController { @Autowired private ExaminationResultService examinationResultService; @RequestMapping("/examinationresult.html") public String list(){ return "examinationresult/examinationresult.html"; } /** * 列表 */ @ResponseBody @RequestMapping("/list") // @RequiresPermissions("examinationresult:list") public R list(HttpServletRequest request){ Map<String, Object> map = getMapPage(request); stringQuery(map, request, "id"); stringQuery(map, request, "userId"); stringQuery(map, request, "nickName"); stringQuery(map, request, "mobile"); stringQuery(map, request, "examType"); stringQuery(map, request, "sysUserId"); //查询列表数据 List<ExaminationResultPOJO> examinationResultList = examinationResultService.queryList(map); int total = examinationResultService.queryTotal(map); PageUtils pageUtil = new PageUtils(examinationResultList, total , request); return R.ok().put(pageUtil); } /** * 信息 */ @ResponseBody @RequestMapping("/info/{id}") @RequiresPermissions("examinationresult:info") public R info(@PathVariable("id") Long id , HttpServletRequest request){ Map<String, Object> map = getMap(request); longQuery(map, request, "id"); ExaminationResultPOJO examinationResult = examinationResultService.queryObject(map); return R.ok().put(examinationResult); } /** * 保存 */ @ResponseBody @RequestMapping("/save") @RequiresPermissions("examinationresult:save") public R save(@RequestBody ExaminationResultEntity examinationResult , HttpServletRequest request){ SysUserEntity userInfo = getUser(); if(userInfo.getUserId() != null){ examinationResult.setCreater(userInfo.getUserId()); } Map<String,Object> map = new HashMap<>(); map.put("registrationId", examinationResult.getRegistrationId()); int num = examinationResultService.getRegistrationNum(map); if(num == 1){ examinationResult.setExamType(0); }else if(num > 1){ examinationResult.setExamType(1); } //保存 examinationResultService.save(examinationResult); return R.ok(); } /** * 修改 */ @ResponseBody @RequestMapping("/update") @RequiresPermissions("examinationresult:update") public R update(@RequestBody ExaminationResultEntity examinationResult , HttpServletRequest request){ // //平台ID // examinationResult.setSchoolId(SchoolIdUtils.getSchoolId(request)); //修改 examinationResultService.update(examinationResult); return R.ok(); } /** * 删除 */ @ResponseBody @RequestMapping("/delete") @RequiresPermissions("examinationresult:delete") public R delete(@RequestBody Long[] ids , HttpServletRequest request){ Map<String, Object> map = getMap(request); map.put("ids",ids); examinationResultService.deleteBatch(map); return R.ok(); } /** * 导入 */ @ResponseBody @RequestMapping(value = "/importData" , method = RequestMethod.POST) @RequiresPermissions("examinationresult:import") @Transactional public R importData(HttpServletRequest request){ MultipartHttpServletRequest mpReq = (MultipartHttpServletRequest) request; MultipartFile file = mpReq.getFile("file_data"); int result = 0; try { result = examinationResultService.importData(file,getUser()); } catch (Exception e) { e.printStackTrace(); return R.ok(e.getMessage()); } return R.ok("成功导入 " + result + " 条数据"); } }
true
bc661545db9766ec5978d019136b64a7a8b4a947
Java
jonghyunchoe/python-for-coding-test
/Chapter13/CityDistance.java
UTF-8
525
3.0625
3
[]
no_license
import java.util.Scanner; public class CityDistance { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int M = sc.nextInt(); int K = sc.nextInt(); int X = sc.nextInt(); int[] A = new int[M]; int[] B = new int[M]; for (int i=0; i<M; i++) { A[i] = sc.nextInt(); B[i] = sc.nextInt(); } // Calculate minimum distance to each city // Print cities } }
true
1c9d4ca00b3372d0c745ebf08e8c5e62debda75f
Java
MKrishtop/PromOrderFeed
/app/src/main/java/com/mikhailkrishtop/promorderfeed/data/database/mapper/CursorToOderMapper.java
UTF-8
481
2.234375
2
[]
no_license
package com.mikhailkrishtop.promorderfeed.data.database.mapper; import android.database.Cursor; import com.mikhailkrishtop.promorderfeed.data.entity.Order; import rx.functions.Func1; /** * Created by mykhailo on 4/11/15. */ public class CursorToOderMapper implements Func1<Cursor, Order> { @Override public Order call(Cursor cursor) { Order order = new Order(); order.id = cursor.getInt(cursor.getColumnIndex("id")); return order; } }
true
7463219f71d8980ea112e4449967ed18bc8edd9c
Java
apache/airavata
/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/impl/RabbitMQProcessLaunchPublisher.java
UTF-8
4,405
1.953125
2
[ "Apache-2.0", "Plexus", "BSD-3-Clause", "LicenseRef-scancode-jdom", "BSD-2-Clause" ]
permissive
/** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ ///* // * // * Licensed to the Apache Software Foundation (ASF) under one // * or more contributor license agreements. See the NOTICE file // * distributed with this work for additional information // * regarding copyright ownership. The ASF licenses this file // * to you under the Apache License, Version 2.0 (the // * "License"); you may not use this file except in compliance // * with the License. You may obtain a copy of the License at // * // * http://www.apache.org/licenses/LICENSE-2.0 // * // * Unless required by applicable law or agreed to in writing, // * software distributed under the License is distributed on an // * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // * KIND, either express or implied. See the License for the // * specific language governing permissions and limitations // * under the License. // * //*/ //package org.apache.airavata.messaging.core.impl; // //import org.apache.airavata.common.exception.AiravataException; //import org.apache.airavata.common.exception.ApplicationSettingsException; //import org.apache.airavata.common.utils.ServerSettings; //import org.apache.airavata.common.utils.ThriftUtils; //import org.apache.airavata.messaging.core.MessageContext; //import org.apache.airavata.messaging.core.MessagingConstants; //import org.apache.airavata.messaging.core.Publisher; //import org.apache.airavata.model.messaging.event.*; //import org.apache.thrift.TException; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; // //public class RabbitMQProcessLaunchPublisher implements Publisher{ // private final static Logger log = LoggerFactory.getLogger(RabbitMQProcessLaunchPublisher.class); // private String launchTask; // // private RabbitMQProducer rabbitMQProducer; // // public RabbitMQProcessLaunchPublisher() throws Exception { // String brokerUrl; // try { // brokerUrl = ServerSettings.getSetting(MessagingConstants.RABBITMQ_BROKER_URL); // launchTask = ServerSettings.getRabbitmqProcessLaunchQueueName(); // } catch (ApplicationSettingsException e) { // String message = "Failed to get read the required properties from airavata to initialize rabbitmq"; // log.error(message, e); // throw new AiravataException(message, e); // } // rabbitMQProducer = new RabbitMQProducer(brokerUrl, null,null); // rabbitMQProducer.open(); // } // // public void publish(MessageContext msgCtx) throws AiravataException { // try { // log.info("Publishing to launch queue ..."); // byte[] body = ThriftUtils.serializeThriftObject(msgCtx.getEvent()); // Message message = new Message(); // message.setEvent(body); // message.setMessageId(msgCtx.getMessageId()); // message.setMessageType(msgCtx.getType()); // message.setUpdatedTime(msgCtx.getUpdatedTime().getTime()); // String routingKey = launchTask; // byte[] messageBody = ThriftUtils.serializeThriftObject(message); // rabbitMQProducer.sendToWorkerQueue(messageBody, routingKey); // log.info("Successfully published to launch queue ..."); // } catch (TException e) { // String msg = "Error while deserializing the object"; // log.error(msg, e); // throw new AiravataException(msg, e); // } catch (Exception e) { // String msg = "Error while sending to rabbitmq"; // log.error(msg, e); // throw new AiravataException(msg, e); // } // } //}
true
8f9a79ec3fd3f4a8b0e02ccc3c316185ffb48b90
Java
yufenfei/tcp-proxy
/source/src/test/java/io/mycat/mycat2/ymlTest/MySQL.java
UTF-8
1,642
2.375
2
[]
no_license
package io.mycat.mycat2.ymlTest; /** * Desc: * * @date: 09/09/2017 * @author: gaozhiwen */ public class MySQL { private String hostName; private String ip; private int port; private String user; private String password; private int minCon; private int maxCon; public String getHostName() { return hostName; } public void setHostName(String hostName) { this.hostName = hostName; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getMinCon() { return minCon; } public void setMinCon(int minCon) { this.minCon = minCon; } public int getMaxCon() { return maxCon; } public void setMaxCon(int maxCon) { this.maxCon = maxCon; } @Override public String toString() { return "MySQL{" + "hostName='" + hostName + '\'' + ", ip='" + ip + '\'' + ", port=" + port + ", user='" + user + '\'' + ", password='" + password + '\'' + ", minCon=" + minCon + ", maxCon=" + maxCon + '}'; } }
true
4a742c648fe25bbc9e80b8b0b47b7ff8f359bca7
Java
syx19930307/Share
/Share/Share/src/main/java/com/lzm/test/UserTest.java
WINDOWS-1252
818
1.8125
2
[]
no_license
package com.lzm.test; import com.lzm.mapper.UserMapper; import com.lzm.pojo.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/applicationContext.xml") public class UserTest { @Autowired private UserMapper userMapper; /** * @author * @date 2019-07-02 09:03 */ @Test public void UsersTest() { User user = userMapper.selectByPrimaryKey(1); System.out.println(user.toString()); } }
true
107a5f47e020a9283c9abd0600750a83877b1449
Java
Marcelo639/estudos-p2p-git
/java-orientado-a-objeto/bytebank/_10-Metodos-com-retorno/TesteReferencias.java
UTF-8
837
3.84375
4
[]
no_license
public class TesteReferencias { public static void main(String[] args) { Conta primeiraConta = new Conta(); primeiraConta.saldo = 300; System.out.println("saldo da primeira: " + primeiraConta.saldo); Conta segundaConta = primeiraConta;// Clone de objetos(segundaConta -> primeiraConta) System.out.println("saldo da segunda conta: " + segundaConta.saldo); segundaConta.saldo += 100; System.out.println("saldo da segunda conta: " + segundaConta.saldo); System.out.println("saldo da primeira conta: " + primeiraConta.saldo); if (primeiraConta == segundaConta) { System.out.println("são a mesmissima conta!"); } System.out.println(primeiraConta);// Objetos sem mostrar os atributos com contas iguais. System.out.println(segundaConta);// Objetos sem mostrar os atributos com contas iguais. } }
true
02cb54ad5afcd113e9220696b884ca09086922cd
Java
tranleminh/StepAnalyzer
/app/src/main/java/com/functionality/stepanalyzer/DailyStepService.java
UTF-8
10,951
2.140625
2
[]
no_license
package com.functionality.stepanalyzer; import android.annotation.TargetApi; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.content.SharedPreferences; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.net.Uri; import android.os.Build; import android.os.IBinder; import android.os.PowerManager; import android.util.Log; import android.widget.Toast; import androidx.core.app.NotificationCompat; import com.google.android.gms.tasks.Continuation; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Calendar; import java.util.Date; public class DailyStepService extends Service implements SensorEventListener { /****************Attributes and global variables declared here*****************/ /***SensorManager and Sensor declaration***/ private SensorManager sensorManager; private Sensor sensor; private StorageReference mStorageRef; /***Variables for step counting here***/ private int nbStep = 0; private String lines = ""; private long moment = -1; private long delta = 0; private String ID; /***Shared Preferences called to get user ID from MainActivity***/ private SharedPreferences prefs; /***Variables used for broadcast purpose, with an Intent and broadcast tag***/ Intent intentBR; /**WakeLock declared here to keep app working**/ PowerManager powerManager; PowerManager.WakeLock wakeLock; /** * Create a .csv file and automatically upload it to the Firebase server * @param username * @param year * @param month * @param day * @param hour * @param lines */ private void createTextFile(String username, String year, String month, String day, String hour, String lines) { /***Initialize file name here***/ String name = ParametersCollection.FILE_NAME + "_" + hour + ParametersCollection.EXTENSION; /***File manipulation here***/ FileOutputStream fos = null; try { fos = openFileOutput(name, MODE_PRIVATE); fos.write(ParametersCollection.FIRST_LINE.getBytes()); fos.write(lines.getBytes()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fos != null) { try { /***After completed editing file, close it and upload it to the Firebase server***/ fos.close(); Uri file = Uri.fromFile(new File(getFilesDir(), name)); StorageReference fileRef = mStorageRef.child(username + "/" + year + "/" + month + "/" + day + "/" + name); Toast.makeText(this, name + " created !", Toast.LENGTH_LONG).show(); /***The putFile() method used for file uploading***/ fileRef.putFile(file) .continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() { @Override public Task<Uri> then(Task<UploadTask.TaskSnapshot> task) throws Exception { if (!task.isSuccessful()) { throw task.getException(); } return mStorageRef.getDownloadUrl(); } }).addOnCompleteListener(new OnCompleteListener<Uri>() { @Override public void onComplete(Task<Uri> task) { if (task.isSuccessful()) { Toast.makeText(getApplicationContext(), "Upload complete!" , Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Upload failed: " + task.getException().getMessage(), Toast.LENGTH_LONG).show(); } } }); /***After uploaded the file, delete it***/ getApplicationContext().deleteFile(name); } catch (IOException e) { e.printStackTrace(); } } } } /** * Send number of steps to MainActivity for display purpose */ private void broadcastValue() { intentBR.putExtra("Nb_Steps", nbStep); sendBroadcast(intentBR); } /** * Notification Channel used for Android Version 8 or higher */ private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel serviceChannel = new NotificationChannel( ParametersCollection.CHANNEL_ID, "Foreground Service Channel", NotificationManager.IMPORTANCE_DEFAULT ); NotificationManager manager = getSystemService(NotificationManager.class); manager.createNotificationChannel(serviceChannel); } } /** * Overridden method that binds Service with MainActivity * @param intent * @return */ @Override public IBinder onBind(Intent intent) { return null; } /** * Service initiated here */ @Override public void onCreate() { /**Wakelock instantiated**/ powerManager = (PowerManager) getSystemService(POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyApp::MyWakelockTag"); /***Sensor is instantiated here***/ sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); sensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR); Log.d("service", "Service Created"); /***Instantiate the broadcast intent***/ intentBR = new Intent(ParametersCollection.ACTION_CUSTOM_BROADCAST); /***Instantiate the Firebase Cloud Storage***/ mStorageRef = FirebaseStorage.getInstance().getReference(); /***Instantiate the Shared Preference and get the user ID from it***/ prefs = getSharedPreferences(ParametersCollection.sharedPrefFile, MODE_PRIVATE); ID = prefs.getString("ID", ID); } /** * Overridden method that tell the Service to start AppCloseReceiver when destroyed */ @Override public void onDestroy() { Log.d("service", "destroy"); super.onDestroy(); /*****Create intent for AppCloseReceiver then send it*****/ Intent broadcastIntent = new Intent(this, AppCloseReceiver.class); sendBroadcast(broadcastIntent); /**Release wakelock on destroy**/ wakeLock.release(); /*****Unregister step sensor when Service destroyed*****/ this.sensorManager.unregisterListener(this); } /** * Overridden method where the main algorithm is executed * @param intent * @param flags * @param startId * @return */ @TargetApi(Build.VERSION_CODES.KITKAT) @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "Step Analyzer Service Launched !", Toast.LENGTH_LONG).show(); /***Register the step sensor listener so it starts to count steps, featuring SENSOR_DELAY_NORMAL as sampling frequency and maximal report latency/delay set to 0***/ this.sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL, ParametersCollection.ZERO_REPORT_LATENCY); /**Acquire wakelock so it stays working even in Doze mode**/ wakeLock.acquire(); /***Create notification channel here, for Foreground Service purpose***/ String input = intent.getStringExtra("inputExtra"); createNotificationChannel(); Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); Notification notification = new NotificationCompat.Builder(this, ParametersCollection.CHANNEL_ID) .setContentTitle("Foreground Service") .setContentText(input) .setContentIntent(pendingIntent) .build(); /***Foreground service started here, with created notification channel***/ startForeground(1, notification); /**Return START_STICKY in order to keep the service even when app is killed**/ return START_STICKY; } /** * Overridden method that listen for step sensor's change so as to update the counter and put lines into text file content * @param sensorEvent */ @Override public void onSensorChanged(SensorEvent sensorEvent) { if (sensorEvent.sensor.getType() == Sensor.TYPE_STEP_DETECTOR) { /***If a change event is detected with step sensor, increase counter by one***/ nbStep++; /***Save the event timestamp (initially in nanoseconds) and convert it to milliseconds, then calculate duration between 2 detected steps***/ long timestamp = sensorEvent.timestamp/1000000; if (moment != -1) { delta = (timestamp - moment); } moment = timestamp; } /***Send the steps number with broadcastValue()***/ broadcastValue(); /***The lines are updated only when the time limit does not exceed a time threshold***/ if (delta < ParametersCollection.TIME_LIMIT_MS) { lines += ParametersCollection.df2.format(Calendar.getInstance().getTime()) + "; " + delta + "\n "; } /***If user stops walking for TIME_LIMIT_MS, all counters are reset and a text file is created and uploaded to the server***/ else { Date now = Calendar.getInstance().getTime(); createTextFile(ID, ParametersCollection.dfYear.format(now), ParametersCollection.dfMonth.format(now), ParametersCollection.dfDay.format(now), ParametersCollection.dfHour.format(now) , lines); lines = ""; nbStep = 0; moment = -1; delta = 0; } } @Override public void onAccuracyChanged(Sensor sensor, int i) { } }
true
0b74d1035a20c41f7fda66e13d578707e2538c59
Java
kvv1/kvvmaps
/androidutils/aplayer/src/kvv/aplayer/player/Player0.java
UTF-8
4,306
2.265625
2
[]
no_license
package kvv.aplayer.player; import java.util.ArrayList; import java.util.Collections; import java.util.List; import kvv.aplayer.service.FileDescriptor; import kvv.aplayer.service.Folder; import android.content.Context; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; public abstract class Player0 extends Player { private Folders folders; private int curFile = 0; public Player0(Context context, final List<Folder> _folders) { super(context); this.folders = new Folders(_folders, -1); setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp1) { System.out.println("onCompletion"); Integer next = getNext(); if (next == null) { Folder folder = folders.getFolder(); if (folder.seed != null) { folder.seed = Shuffle.shuffle(folder.filesToPlay); for (PlayerListener listener : listeners) listener.folderChanged(); } Integer idx = skipFw(folder.filesToPlay, 0); curFile = idx == null ? 0 : idx; playFile(folder.filesToPlay.get(curFile).path, 0, false); } else { toFile(next); } } }); } public Folders getFolders() { return folders; } public Files getFiles() { Folder folder = folders.getFolder(); if (folder == null) return new Files(Collections.<FileDescriptor> emptyList(), -1); return new Files(folder.filesToPlay, curFile); } public void toFolder(int folderIdx, int file, int curPos, Long seed, boolean play) { Folder folder = folders.getFolder(); if (folder != null) folder.filesToPlay = null; folders.curFolder = folderIdx; folder = folders.getFolder(); folder.filesToPlay = getAllFiles(); folder.seed = seed; if (folder.seed != null) Shuffle.shuffle(folder.filesToPlay, folder.seed); for (PlayerListener listener : listeners) listener.folderChanged(); curFile = 0; toFile(file, curPos, play); } public void setRandom() { Folder folder = folders.getFolder(); if (folder == null) return; folder.filesToPlay = getAllFiles(); if (folder.seed == null) { folder.seed = Shuffle.shuffle(folder.filesToPlay); } else { folder.seed = null; } for (PlayerListener listener : listeners) listener.folderChanged(); toFile(0, 0, true); } private List<FileDescriptor> getAllFiles() { Folder folder = folders.getFolder(); List<FileDescriptor> files = new ArrayList<FileDescriptor>(); files.addAll(folder._files); for (int i = folders.curFolder + 1; i < folders.folders.size(); i++) { Folder f = folders.folders.get(i); if (f.indent <= folder.indent) break; files.addAll(f._files); } return files; } private void toFile(int idx, int pos, boolean play) { Folder folder = folders.getFolder(); if (folder == null) return; if (idx >= folder.filesToPlay.size()) curFile = 0; else curFile = idx; if (folder.filesToPlay.size() > curFile) playFile(folder.filesToPlay.get(curFile).path, pos, play); } public void toFile(int idx) { toFile(idx, 0, true); } public void prev() { int cur = getCurrentPosition(); Integer prev = getPrev(); if (cur < 3000 && prev != null) toFile(prev); else seekTo(0); } private Integer getPrev() { Folder folder = folders.getFolder(); if (folder == null) return null; return skipBw(folder.filesToPlay, curFile - 1); } private Integer getNext() { Folder folder = folders.getFolder(); if (folder == null) return null; return skipFw(folder.filesToPlay, curFile + 1); } public boolean hasNext() { return getNext() != null; } public void next() { Integer next = getNext(); if (next == null) return; toFile(next); } private Integer skipFw(List<FileDescriptor> files, int pos) { for (int i = pos; i < files.size(); i++) if (!isBadSong(files.get(i).path)) return i; return null; } private Integer skipBw(List<FileDescriptor> files, int pos) { for (int i = pos; i >= 0; i--) if (!isBadSong(files.get(i).path)) return i; return null; } protected boolean isBadSong(String path) { return false; } }
true
d9fa3737f02425eb2995961d61409877c22d1874
Java
suyashgaikwad31/InvoiceService
/src/test/java/InvoiceServiceTest.java
UTF-8
1,202
2.703125
3
[]
no_license
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class InvoiceServiceTest { @Test public void givenDistanceAndTime_ShouldReturnTotalFare() { InvoiceGenerator invoiceGenerator = new InvoiceGenerator(); double distance = 2.0; int time = 5; double fare = invoiceGenerator.calculateFare(distance, time); Assertions.assertEquals(25,fare,0.0); } @Test public void givenLessDistanceOrTime_ShouldReturnMinFare() { InvoiceGenerator invoiceGenerator = new InvoiceGenerator(); double distance = 0.1; int time = 1; double fare = invoiceGenerator.calculateFare(distance, time); Assertions.assertEquals(5,fare,0.0); } @Test public void givenMultipleRides_ShouldReturnInvoiceSummary() { InvoiceGenerator invoiceGenerator = new InvoiceGenerator(); Ride [] rides = {new Ride(2.0, 5), new Ride(0.1, 1), }; InvoiceSummary summary = invoiceGenerator.calculateFare(rides); InvoiceSummary expectedinvoiceSummary = new InvoiceSummary(2, 30.0); Assertions.assertEquals(expectedinvoiceSummary, summary); } }
true
753372d4b5c36a3e4fa73c30a115d7b1ac962de2
Java
prestodb/presto
/presto-main/src/main/java/com/facebook/presto/server/RequestErrorTracker.java
UTF-8
7,202
1.648438
2
[ "Apache-2.0" ]
permissive
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.server; import com.facebook.airlift.event.client.ServiceUnavailableException; import com.facebook.airlift.log.Logger; import com.facebook.presto.execution.TaskId; import com.facebook.presto.server.remotetask.Backoff; import com.facebook.presto.spi.ErrorCodeSupplier; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.PrestoTransportException; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFutureTask; import io.airlift.units.Duration; import javax.annotation.concurrent.ThreadSafe; import java.io.EOFException; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URI; import java.util.Queue; import java.util.concurrent.CancellationException; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeoutException; import static com.facebook.presto.spi.HostAddress.fromUri; import static com.facebook.presto.spi.StandardErrorCode.REMOTE_TASK_ERROR; import static com.facebook.presto.spi.StandardErrorCode.TOO_MANY_REQUESTS_FAILED; import static com.facebook.presto.util.Failures.WORKER_NODE_ERROR; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; @ThreadSafe public class RequestErrorTracker { private static final Logger log = Logger.get(RequestErrorTracker.class); private final Object id; private final URI uri; private ErrorCodeSupplier errorCode; private String nodeErrorMessage; private final ScheduledExecutorService scheduledExecutor; private final String jobDescription; private final Backoff backoff; private final Queue<Throwable> errorsSinceLastSuccess = new ConcurrentLinkedQueue<>(); public RequestErrorTracker(Object id, URI uri, ErrorCodeSupplier errorCode, String nodeErrorMessage, Duration maxErrorDuration, ScheduledExecutorService scheduledExecutor, String jobDescription) { this.id = requireNonNull(id, "id is null"); this.uri = requireNonNull(uri, "uri is null"); this.errorCode = requireNonNull(errorCode, "errorCode is null"); this.nodeErrorMessage = requireNonNull(nodeErrorMessage, "nodeErrorMessage is null"); this.scheduledExecutor = requireNonNull(scheduledExecutor, "scheduledExecutor is null"); this.backoff = new Backoff(requireNonNull(maxErrorDuration, "maxErrorDuration is null")); this.jobDescription = requireNonNull(jobDescription, "jobDescription is null"); } public static RequestErrorTracker taskRequestErrorTracker(TaskId taskId, URI taskUri, Duration maxErrorDuration, ScheduledExecutorService scheduledExecutor, String jobDescription) { return new RequestErrorTracker(taskId, taskUri, REMOTE_TASK_ERROR, WORKER_NODE_ERROR, maxErrorDuration, scheduledExecutor, jobDescription); } public ListenableFuture<?> acquireRequestPermit() { long delayNanos = backoff.getBackoffDelayNanos(); if (delayNanos == 0) { return Futures.immediateFuture(null); } ListenableFutureTask<Object> futureTask = ListenableFutureTask.create(() -> null); scheduledExecutor.schedule(futureTask, delayNanos, NANOSECONDS); return futureTask; } public void startRequest() { // before scheduling a new request clear the error timer // we consider a request to be "new" if there are no current failures if (backoff.getFailureCount() == 0) { requestSucceeded(); } backoff.startRequest(); } public void requestSucceeded() { backoff.success(); errorsSinceLastSuccess.clear(); } public void requestFailed(Throwable reason) throws PrestoException { // cancellation is not a failure if (reason instanceof CancellationException) { return; } if (reason instanceof RejectedExecutionException) { if (reason.getMessage() == null) { throw new PrestoException(errorCode, reason); } // We want to do exponential backoff to allow OOT killer to kill queries and not fail immediately. if (!reason.getMessage().contains("Max requests queued per destination")) { throw new PrestoException(errorCode, reason); } } // log failure message if (isExpectedError(reason)) { // don't print a stack for a known errors log.warn("Error " + jobDescription + " %s: %s: %s", id, reason.getMessage(), uri); } else { log.warn(reason, "Error " + jobDescription + " %s: %s", id, uri); } // remember the first 10 errors if (errorsSinceLastSuccess.size() < 10) { errorsSinceLastSuccess.add(reason); } // fail the operation, if we have more than X failures in a row and more than Y seconds have passed since the last request if (backoff.failure()) { // it is weird to mark the task failed locally and then cancel the remote task, but there is no way to tell a remote task that it is failed PrestoException exception = new PrestoTransportException(TOO_MANY_REQUESTS_FAILED, fromUri(uri), format("%s (%s %s - %s failures, failure duration %s, total failed request time %s)", nodeErrorMessage, jobDescription, uri, backoff.getFailureCount(), backoff.getFailureDuration().convertTo(SECONDS), backoff.getFailureRequestTimeTotal().convertTo(SECONDS))); errorsSinceLastSuccess.forEach(exception::addSuppressed); throw exception; } } public static boolean isExpectedError(Throwable t) { while (t != null) { if ((t instanceof SocketException) || (t instanceof SocketTimeoutException) || (t instanceof EOFException) || (t instanceof TimeoutException) || (t instanceof ServiceUnavailableException)) { return true; } t = t.getCause(); } return false; } }
true
1e5a2a52b4bf61bf20565b69bd76b52aef765561
Java
506boris/boombony
/core/src/by/vit/boombony/gameworld/ActType.java
UTF-8
150
1.710938
2
[]
no_license
package by.vit.boombony.gameworld; /** * Все, кто будет ходить по очереди */ public enum ActType { HERO, ENEMY }
true
6f3a948a2af1c87ed17f1a583b6bb63867509724
Java
ZayneLiu/PSIC-BookingSystem
/src/main/java/zayne/psic_booking_system/utils/Report.java
UTF-8
755
2.515625
3
[ "MIT" ]
permissive
package zayne.psic_booking_system.utils; import zayne.psic_booking_system.models.Appointment; import zayne.psic_booking_system.models.Patient; import zayne.psic_booking_system.models.Physician; import java.util.ArrayList; import java.util.Calendar; public class Report { public static ArrayList<Appointment> getReportAllAppointments() { var time = Calendar.getInstance(); time.set(2021, Calendar.MAY, 11, 10, 0,0); var app = new Appointment( time, Physician.getPhysicians().get(0), Patient.getPatients().get(0), Physician.Treatment.MASSAGE); app.book(); for (var item : Appointment.appointments) { System.out.println(item); } return new ArrayList<>(); } }
true
4acd1993e536f20bac1e1d1ca9b0bec030ab7f39
Java
Ju1ietta/com.epam.course.jf.task
/homework02/test/task01.java
UTF-8
1,449
3.15625
3
[ "Apache-2.0" ]
permissive
import org.junit.Test; import task01.Colour; import task01.Pen; import task01.Type; import static junit.framework.Assert.assertEquals; import static junit.framework.TestCase.assertFalse; import static junit.framework.TestCase.assertTrue; public class task01 { @Test public void testTask01() { Pen ballpointPen = new Pen(Colour.BLACK, Type.BALLPOINT, 100, "Spb"); Pen fountainPen = new Pen(Colour.RED, Type.FOUNTAIN, 100, "Moscow"); Pen felt_tipPen = new Pen(Colour.GREEN, Type.FELT_TIP, 100, "London"); Pen ballpointPen2 = new Pen(Colour.BLACK, Type.BALLPOINT, 100, "Spb"); //check equals method assertFalse("Are equal ballpointPen to fountainPen? - ", ballpointPen.equals(fountainPen)); assertTrue("Are equal ballpointPen to ballpointPen2? - ", ballpointPen.equals(ballpointPen2)); assertTrue("Check the reflexive property. Is equal felt_tipPen to itself? - ", felt_tipPen.equals(felt_tipPen)); assertTrue("Check the symmetric property: ", (ballpointPen.equals(ballpointPen2) == ballpointPen2.equals(ballpointPen))); //check hashCode() method assertTrue("HashCode of ballpointPen equals to ballpointPen2", ballpointPen.hashCode() == ballpointPen2.hashCode()); //check toString() method assertEquals("ToString of felt_tipPen: ", "colourInk = GREEN; type = FELT_TIP; price = 100; producer = London", felt_tipPen.toString()); } }
true
1a929db17928464e91f89d6f5e4ed0e47ef6a28e
Java
gutsolksenia/type-theory
/src/main/java/ru/itmo/gutsol/tt/Homework3.java
UTF-8
576
2.5
2
[]
no_license
package ru.itmo.gutsol.tt; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.PrintStream; import java.io.PrintWriter; import java.util.Scanner; public class Homework3 { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new FileInputStream("task3.in")); PrintWriter out = new PrintWriter(new PrintStream("task3.out")); String s = in.nextLine(); String res = Homework2.getResult(s); out.println(res); in.close(); out.close(); } }
true
4ecdc8b6cede202b0e9ca943990ccde2683f0289
Java
m24ishizuka/java-tips
/src/main/java/jp/m24i/javatips/H2DatabaseExample.java
UTF-8
3,347
2.921875
3
[ "MIT" ]
permissive
package jp.m24i.javatips; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; public class H2DatabaseExample { private static final String CATALOG_NAME = "JAVATIPS"; private static final String SCHEMA_NAME = "RINGO"; private static final String TABLE_NAME ="MAKERS"; private static final String JDBC_URL = String.format("jdbc:h2:./%s", CATALOG_NAME); public static void main(String[] args) throws Exception { Connection connection = null; try { connection = DriverManager.getConnection(JDBC_URL); connection.setAutoCommit(false); createAndDrop(connection); insert(connection); connection.commit(); DatabaseMetaData dbMetaData = connection.getMetaData(); output("schemas", dbMetaData.getSchemas(CATALOG_NAME, SCHEMA_NAME)); output("tables", dbMetaData.getTables(CATALOG_NAME, SCHEMA_NAME, null, null)); select(connection); } catch (SQLException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } } private static void createAndDrop(Connection connection) throws Exception { try ( Statement statement = connection.createStatement(); ) { String[] sqls = { String.format("DROP SCHEMA IF EXISTS %s CASCADE", SCHEMA_NAME), String.format("CREATE SCHEMA %s", SCHEMA_NAME), String.format("CREATE TABLE %s.%s(id INT, name VARCHAR(10))", SCHEMA_NAME, TABLE_NAME) }; for (String sql : sqls) { statement.addBatch(sql); } statement.executeBatch(); } } private static void insert(Connection connection) throws Exception { String sql = String.format("INSERT INTO %s.%s VALUES(?, ?)", SCHEMA_NAME, TABLE_NAME); try ( PreparedStatement ps = connection.prepareStatement(sql); ) { String[] values = { "honda", "yamaha", "kawasaki", "suzuki" }; for (int i = 0; i < values.length; i++) { int id = i + 1; String value = values[i]; ps.setInt(1, id); ps.setString(2, value); ps.addBatch(); } ps.executeBatch(); } } private static void select(Connection con) throws Exception { try ( Statement stmt = con.createStatement(); ) { String sql = String.format("SELECT * FROM %s.%s", SCHEMA_NAME, TABLE_NAME); output("table:makers", stmt.executeQuery(sql)); } } private static void output(String name, ResultSet rs) throws Exception { try { System.out.println("[" + name + "]"); ResultSetMetaData rsMetaData = rs.getMetaData(); int columnCount = rsMetaData.getColumnCount(); // column name for (int i = 1; i <= columnCount; i++) { System.out.print(rsMetaData.getColumnName(i) + "\t"); } System.out.println(); // value while (rs.next()) { for (int i = 1; i <= columnCount; i++) { System.out.print(rs.getString(i) + "\t"); } System.out.println(); } } finally { rs.close(); } } }
true
2a35f7c6766fa4861a73dde2f45d21efde208943
Java
SjoerdvanderHeijden/endless-ql
/piotr/org.uva.sc.piotr.ql/src/main/java/ql/gui/model/ValidatorsHandler.java
UTF-8
779
2.421875
2
[]
no_license
package ql.gui.model; import ql.gui.view.ErrorMessageView; import ql.gui.view.WindowView; public final class ValidatorsHandler { public static boolean execute(WindowView windowView, ql.logic.validators.Validator[] validators) { // validating for (ql.logic.validators.Validator validator : validators) { if (!validator.validate()) { if (validator.criticalErrorOccurred()) { ErrorMessageView.showErrorDialog(windowView, "Validation error", validator.getMessage()); return false; } else { ErrorMessageView.showWarningDialog(windowView, "Validation warning", validator.getMessage()); } } } return true; } }
true