text
stringlengths
10
2.72M
package DataStructures.arrays; public class MaxProfit { public static int maxProfit(int[] a) { if (a == null || a.length == 0) return 0; int maxProfit = 0; for (int i = 1; i < a.length; i = i+2) maxProfit = Math.max(maxProfit, maxProfit + (a[i] - a[i - 1])); return maxProfit; } public static void main(String a[]) { } }
package ContactCreator; public class Address { private String streetName; private int streetNumber; private String city; private String province; private String postalCode; private String country; public Address(){}; public Address(String streetName, int streetNumber, String city, String province, String postalCode, String country){ this.streetName=streetName; this.streetNumber=streetNumber; this.city=city; this.province=province; this.postalCode=postalCode; this.country=country; } public Address createAddress(){ Application app= new Application(); String streetName= app.requestRetrieveString("enter streetName"); int streetNumber= app.requestRetrieveInt("enter street number"); String city= app.requestRetrieveString("enter city"); String province= app.requestRetrieveString("enter province"); String postalCode= app.requestRetrieveString("enter postal code"); String country= app.requestRetrieveString("enter country"); Address newAddress= new Address(streetName,streetNumber,city,province,postalCode,country); return newAddress; } public String getStreetName() { return streetName; } public void setStreetName(String streetName) { this.streetName = streetName; } public int getStreetNumber() { return streetNumber; } public void setStreetNumber(int streetNumber) { this.streetNumber = streetNumber; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String toString(){ return "address "+streetNumber+" "+streetName+"\nCity "+ city; } }
package com.meehoo.biz.core.basic.domain.security; import com.meehoo.biz.core.basic.annotation.SetBySystem; import com.meehoo.biz.core.basic.domain.IdEntity; import com.meehoo.biz.core.basic.domain.TimeEntity; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import java.util.Date; /** * 角色对象 * Created by CZ on 2017/10/19. */ @Entity @Table(name = "sec_role_inv") @DynamicInsert @DynamicUpdate @Getter @Setter @Accessors(chain = true) public class Role extends TimeEntity { public static final int STATUS_FORBID = 0; public static final int STATUS_ENABLE = 1; public static final int ISPUBLIC_NO = 0; public static final int ISPUBLIC_YES = 1; public static final int SYSTEMDEFAUFT_NO = 0; public static final int SYSTEMDEFAUFT_YES = 1; /** * 备注 */ @Column(length = 255) private String remark; /** * 状态值(STATUS_FORBID禁用;STATUS_ENABLE启用) */ @Column private int status = STATUS_ENABLE; /** * 是否系统预设 */ @Column private int systemDefault = STATUS_ENABLE; /** * 用户类型 * 0 管理员 * 1 用户 */ @Column(columnDefinition = "INT default 0") private Integer roleType; }
package com.ytf.zk.constant; /** * Created by yutianfang * DATE: 17/4/23星期日. */ public interface ClientBase { int CONNECTION_TIMEOUT = 10000; }
package com.mega.swipeit.UI; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import com.mega.swipeit.Adapter.FollowingListAdapter; import com.mega.swipeit.databinding.ActivityFollowingBinding; public class FollowingActivity extends AppCompatActivity { ActivityFollowingBinding binding; private RecyclerView mRecyclerView; private FollowingListAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding= ActivityFollowingBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); mRecyclerView=binding.rcvFliaRecyclerView; mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); adapter= new FollowingListAdapter(this); mRecyclerView.setAdapter(adapter); } }
package com.siscom.dao.mapper; import com.siscom.service.model.ItemVenda; import com.siscom.service.model.Produto; import org.springframework.jdbc.core.RowMapper; import java.sql.ResultSet; import java.sql.SQLException; public class ItemVendaRowMapper implements RowMapper<ItemVenda> { @Override public ItemVenda mapRow(ResultSet rs, int rowNum) throws SQLException { ItemVenda itemVenda = new ItemVenda(); itemVenda.setCodProduto(rs.getInt("CODIGO_PRODUTO")); itemVenda.setQuantVenda(rs.getInt("QUANTIDADE")); itemVenda.setValorVenda(rs.getDouble("VALOR_UNITARIO")); return itemVenda; } }
package Models; import java.awt.*; import java.awt.print.*; import static java.awt.print.Printable.NO_SUCH_PAGE; import static java.awt.print.Printable.PAGE_EXISTS; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; public class ObjetoDeImpresionReparacion implements Printable{ private Reparacion reparacion; private Cliente cliente; public ObjetoDeImpresionReparacion(Reparacion reparacion, Cliente cliente) { this.reparacion = reparacion; this.cliente = cliente; } public Cliente getCliente() { return cliente; } public void setCliente(Cliente cliente) { this.cliente = cliente; } public Reparacion getReparacion() { return reparacion; } public void setReparacion(Reparacion reparacion) { this.reparacion = reparacion; } public int print(Graphics g, PageFormat f, int pageIndex){ if(pageIndex == 0){ DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); Font font = g.getFont(); g.setFont(new Font(font.getFontName(),font.getStyle(), 11)); g.drawString("El Mundo del Calzado II", 90, 18); g.drawString("Santiago de Puriscal", 96, 36); g.drawString("Telef: 2416-65-56", 18, 54); g.drawString("Factura por Reparacion", 18, 72); g.drawString("N° Factura: " + Integer.toString(this.getReparacion().getCodigoReparacion()), 18, 90); if(this.getReparacion().getTipoPago() == 1){ g.drawString("Pago en Efectivo", 18, 108); }else{ g.drawString("Pago por Tarjeta", 18, 108); } g.drawString("Fecha: " + df.format(this.getReparacion().getFecha()), 18, 124); int y = 142; if(!this.getCliente().getNombre().equals("")){ g.drawString("Cliente: " + this.getCliente().getNombre(), 18, y); y+=18; } if(!this.getCliente().getNumero().equals("")){ g.drawString("Telefono: " + this.getCliente().getNumero(), 18, y); y+=18; } g.setFont(new Font(font.getFontName(),font.getStyle(), 10)); g.drawString("Artículo", 18, y); y+=7; g.drawString("____________________________________________", 15, y); y+=15; int y2 = y; ArrayList<String> articulo = Division(this.getReparacion().getArticulo(),33); for(int j = 0; j < articulo.size(); j++){ g.drawString(articulo.get(j), 19, y2); y2+=15; } y2 = y; y+=5; g.drawString("____________________________________________", 15, y); y+=15; g.setFont(new Font(font.getFontName(),font.getStyle(), 11)); g.drawString("Total a Pagar: " + String.valueOf(this.getReparacion().getMontoTotal()), 18, y); y+=21; g.drawString("Total Pagado: " + String.valueOf(this.getReparacion().getMontoPagado()), 18, y); y+=18; g.drawString("Faltante: " + String.valueOf(this.getReparacion().getMontoTotal() - this.getReparacion().getMontoPagado()), 18, y); y+=18; y+=5; g.drawString("Para cambios 8 días con factura", 18, y); y+=18; g.drawString("Regimen simplificado según", 18, y); y+=18; g.drawString("DGTD Oficio #4641001009626 23-07-2013", 18, y); return PAGE_EXISTS; }else{ return NO_SUCH_PAGE; } } private ArrayList<String> Division(String dato, int letras){ ArrayList<String> datos = new ArrayList<>(); if(dato.length() > letras){ String subDato = dato; while(subDato.length() != 0){ int blanco = 0; if(subDato.length() > letras){ blanco = Espacio(subDato.substring(0,letras)); }else{ blanco = Espacio(subDato); } if(blanco != 0){ datos.add(subDato.substring(0, blanco)); subDato = subDato.substring(blanco+1, subDato.length()); }else{ if(subDato.length() > letras){ datos.add(subDato.substring(0, letras) + "-"); subDato = subDato.substring(letras, subDato.length()); }else{ datos.add(subDato.substring(0, subDato.length())); subDato = ""; } } } }else{ datos.add(dato); } return datos; } private int Espacio(String dato){ for(int i = dato.length()-1; i >= 0; i--){ if(dato.charAt(i) == ' '){ return i; } } return 0; } }
package TEST; public class Singleton { //static 객체 생성 private static int num; private static Singleton singleton = new Singleton(); // private 는 이 클래스에서만 사용가능 private Singleton() { } static Singleton getInstance() { return singleton; } void getNum(int a) { this.num = a; } int gteNum() { return num; } }
/* * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jms.config; import org.springframework.jms.listener.MessageListenerContainer; /** * Model for a JMS listener endpoint. Can be used against a * {@link org.springframework.jms.annotation.JmsListenerConfigurer * JmsListenerConfigurer} to register endpoints programmatically. * * @author Stephane Nicoll * @since 4.1 */ public interface JmsListenerEndpoint { /** * Return the id of this endpoint. */ String getId(); /** * Set up the specified message listener container with the model * defined by this endpoint. * <p>This endpoint must provide the requested missing option(s) of * the specified container to make it usable. Usually, this is about * setting the {@code destination} and the {@code messageListener} to * use but an implementation may override any default setting that * was already set. * @param listenerContainer the listener container to configure */ void setupListenerContainer(MessageListenerContainer listenerContainer); }
package com.test.filters;// Created by on 14.10.2017. import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.IOException; public class CountEntering extends GenericFilter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpSession session = request.getSession(false); if (session == null) { session = request.getSession(); session.setAttribute("login", 0); session.setAttribute("logout", 0); session.setAttribute("profile", 0); } String path = request.getRequestURI(); if (path.endsWith("login-page.jsp") || path.endsWith("LoginServlet")) { Integer curCount = (Integer) session.getAttribute("login"); session.setAttribute("login", curCount + 1); } else if (path.endsWith("LogoutServlet")) { Integer curCount = (Integer) session.getAttribute("logout"); session.setAttribute("logout", curCount + 1); } else if (path.endsWith("ProfileServlet")) { Integer curCount = (Integer) session.getAttribute("profile"); session.setAttribute("profile", curCount + 1); } filterChain.doFilter(servletRequest, servletResponse); } }
package org.gtbank.rw.mvisa.service; import java.util.List; import org.gtbank.rw.mvisa.domain.MVisaUser; public interface MVisaUserService { public void saveMVisaUser(MVisaUser mVisaUser); public MVisaUser getMVisaUser(int mVisaUser); public void updateMVisaUser(); public List<MVisaUser> listMVisaUsers(); public void deleteMVisaUser(int mVisaUserId); public MVisaUser getMVisaUserByAccountNumber(String consumerAccountNumber); }
package com.luthfi.taxcalculator.common.calculator; import com.luthfi.taxcalculator.common.model.Tax; public class EntertainmentTaxCalculator implements TaxCalculator { @Override public Long calculate(Tax tax, Long price) { System.out.println(" from EntertainmentTaxCalculator "); return tax.getTaxRate() * (price - 100); } }
package ebay; import java.io.*; import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class loadimage { File image; public File getImage() { return image; } public void setImage(File image) { this.image = image; } public int getItem_id() { return item_id; } public void setItem_id(int item_id) { this.item_id = item_id; } int item_id; public String execute() throws Exception { Connect c = new Connect(); Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jebay", "root", ""); PreparedStatement ps = con.prepareStatement("insert into image_details(image_item_id,image_blob) values(?,?)"); ps.setInt(1, item_id); FileInputStream fis = new FileInputStream(image); ps.setBinaryStream(2, fis, (int) image.length()); ps.executeUpdate(); return "success"; } }
package com.zzping.fix.model; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; /** * 提交报修表单Model */ public class FixFormModel extends BaseModel{ private String fixType; private String userType; private String campus; private String campusPalce; private String communityNo; private String communityName; private String buildingNo; private String dormNo; private String label; private String labelDetail; private String title; private String detail; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") private Date appointStartTime; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") private Date appointEndTime; private String filePath; private String fileId; private String vedioPath; private String vedioId; private String fixerUserId; private String fixerUserNo; private String fixerUserName; private String score; private String orderNum ; private String userNo; private String userId; private String userName; private String orderType; private String appointUserId; private Date appointStartTime1; private Date appointStartTime2; private String createTime; private String comment; private String fixId; public String getFixId() { return fixId; } public void setFixId(String fixId) { this.fixId = fixId; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public Date getAppointStartTime1() { return appointStartTime1; } public void setAppointStartTime1(Date appointStartTime1) { this.appointStartTime1 = appointStartTime1; } public Date getAppointStartTime2() { return appointStartTime2; } public void setAppointStartTime2(Date appointStartTime2) { this.appointStartTime2 = appointStartTime2; } public String getLabelDetail() { return labelDetail; } public void setLabelDetail(String labelDetail) { this.labelDetail = labelDetail; } public String getAppointUserId() { return appointUserId; } public void setAppointUserId(String appointUserId) { this.appointUserId = appointUserId; } public String getOrderType() { return orderType; } public void setOrderType(String orderType) { this.orderType = orderType; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserNo() { return userNo; } public void setUserNo(String userNo) { this.userNo = userNo; } public String getFixType() { return fixType; } public void setFixType(String fixType) { this.fixType = fixType; } public String getCampus() { return campus; } public void setCampus(String campus) { this.campus = campus; } public String getCommunityNo() { return communityNo; } public void setCommunityNo(String communityNo) { this.communityNo = communityNo; } public String getCommunityName() { return communityName; } public void setCommunityName(String communityName) { this.communityName = communityName; } public String getBuildingNo() { return buildingNo; } public void setBuildingNo(String buildingNo) { this.buildingNo = buildingNo; } public String getDormNo() { return dormNo; } public void setDormNo(String dormNo) { this.dormNo = dormNo; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } public Date getAppointStartTime() { return appointStartTime; } public void setAppointStartTime(Date appointStartTime) { this.appointStartTime = appointStartTime; } public Date getAppointEndTime() { return appointEndTime; } public void setAppointEndTime(Date appointEndTime) { this.appointEndTime = appointEndTime; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public String getFileId() { return fileId; } public void setFileId(String fileId) { this.fileId = fileId; } public String getVedioPath() { return vedioPath; } public void setVedioPath(String vedioPath) { this.vedioPath = vedioPath; } public String getVedioId() { return vedioId; } public void setVedioId(String vedioId) { this.vedioId = vedioId; } public String getFixerUserId() { return fixerUserId; } public void setFixerUserId(String fixerUserId) { this.fixerUserId = fixerUserId; } public String getFixerUserNo() { return fixerUserNo; } public void setFixerUserNo(String fixerUserNo) { this.fixerUserNo = fixerUserNo; } public String getFixerUserName() { return fixerUserName; } public void setFixerUserName(String fixerUserName) { this.fixerUserName = fixerUserName; } public String getCampusPalce() { return campusPalce; } public void setCampusPalce(String campusPalce) { this.campusPalce = campusPalce; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } public String getScore() { return score; } public void setScore(String score) { this.score = score; } public String getOrderNum() { return orderNum; } public void setOrderNum(String orderNum) { this.orderNum = orderNum; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } }
package ch06; public class TicTacToe { private String[][] board; private static final int ROWS = 3; private static final int COLUMNS = 3; public TicTacToe() { board = new String[ROWS][COLUMNS]; for (int i = 0; i < ROWS; i ++) { for (int j = 0; j < COLUMNS; j ++) { board[i][j] = " "; } } } public void setField(int i, int j, String player) { if(board[i][j].equals(" ")) { board[i][j] = player; } } public String toString() { String r = ""; for(int i = 0; i < ROWS; i ++) { r = r + "|"; for(int j = 0; j < COLUMNS; j ++) { r = r + board[i][j]; } r = r + "|\n"; } return r; } }
package ankang.springcloud.homework.gateway; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Bean; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.session.data.redis.RedisIndexedSessionRepository; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; /** * @author: ankang * @email: dreedisgood@qq.com * @create: 2021-01-17 */ @SpringBootApplication @EnableDiscoveryClient @EnableRedisHttpSession public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class , args); } @Bean public RedisIndexedSessionRepository createRedisIndexedSessionRepository() { final RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); return new RedisIndexedSessionRepository(redisTemplate); } }
package com.product.entity; import lombok.Data; import java.util.Date; /** * 产品信息 * @author 陈舰 */ @Data public class Product { /** 主键 */ private Integer id; /** 产品编号 */ private String productNum; /** 名称 */ private String productName; /** 出发城市 */ private String cityName; /** 出发时间 */ private Date departureTime; /** 出发时间字符状态 */ private String departureTimeStr; /** 产品价格 */ private double productPrice; /** 产品描述 */ private String productDesc; /** 状态 0:关闭 1:开启 */ private Integer productStatus; /** 状态码字符状态 */ private String productStatusStr; }
package com.dongh.funplus.view.main; import com.dongh.funplus.base.mvp.BaseModel; import com.dongh.funplus.bean.LoginBean; import com.dongh.funplus.bean.WeatherInfo; import com.dongh.funplus.di.scope.ActivityScope; import com.dongh.funplus.http.HostType; import com.dongh.funplus.http.RetrofitHelper; import com.dongh.funplus.http.RetrofitManager; import com.dongh.funplus.http.cache.CacheProvider; import com.dongh.funplus.http.service.RetrofitService; import org.reactivestreams.Publisher; import javax.inject.Inject; import io.reactivex.Flowable; import io.reactivex.functions.Function; import io.rx_cache2.DynamicKey; import io.rx_cache2.EvictDynamicKey; import io.rx_cache2.Reply; /** * Created by chenxz on 2017/12/2. */ @ActivityScope public class MainModel extends BaseModel implements MainContract.Model { private RetrofitHelper mRetrofitHelper; @Inject public MainModel() { mRetrofitHelper = RetrofitHelper.getInstance(); } @Override public Flowable<WeatherInfo> loadWeatherData(String cityId) { return RetrofitManager.getInstance(HostType.WEATHER_INFO).getWeatherInfoObservable(cityId); } @Override public Flowable<WeatherInfo> loadWeatherData(final String cityId, final boolean isUpdate) { return Flowable.just(mRetrofitHelper.obtainRetrofitService(RetrofitService.class).getWeatherInfoWitchCache(cityId)) .flatMap(new Function<Flowable<WeatherInfo>, Publisher<WeatherInfo>>() { @Override public Publisher<WeatherInfo> apply(Flowable<WeatherInfo> weatherInfoFlowable) throws Exception { return mRetrofitHelper.obtainCacheService(CacheProvider.class) .getWeatherWithCache(weatherInfoFlowable, new DynamicKey(cityId), new EvictDynamicKey(isUpdate)) .map(new Function<Reply<WeatherInfo>, WeatherInfo>() { @Override public WeatherInfo apply(Reply<WeatherInfo> weatherInfoReply) throws Exception { return weatherInfoReply.getData(); } }); } }); } @Override public Flowable<LoginBean> login(String username, String password) { return RetrofitManager.getInstance(HostType.WEATHER_INFO).loginObservable(username, password); } }
package com.operacloud.pages; import java.io.IOException; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.ExpectedConditions; import com.aventstack.extentreports.ExtentTest; import com.operacloud.selenium.actions.extensions.OperaCloudSeleniumActions; public class OperaCloud_ValidateReports extends OperaCloudSeleniumActions { public OperaCloud_ValidateReports(ChromeDriver driver, ExtentTest node) { //to do, verify title of the home page this.driver=driver; this.node=node; initPage(); } public OperaCloud_HomePage goBackToHomePage() throws InterruptedException, IOException { try { reportStep("you are on home page of Operacloud", "pass"); } catch(Exception e) { reportStep("you are not on home page of operacloud", "fail"); } return new OperaCloud_HomePage(driver, node); } }
package com.karya.bean; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; public class TrialBalanceBean { private int id; @NotNull @NotEmpty(message = "Please Enter Account.") private String account; @Min(value=1) @NotNull(message= "Please enter Opening(CR)") private int openingcr; @Min(value=1) @NotNull(message= "Please enter Opening(DR)") private int openingdr; @Min(value=1) @NotNull(message= "Please enter Credit") private int credit; @Min(value=1) @NotNull(message= "Please enter Debit") private int debit; @Min(value=1) @NotNull(message= "Please enter Closing(DR)") private int closingdr; @Min(value=1) @NotNull(message= "Please enter Closing(CR)") private int closingcr; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public int getOpeningcr() { return openingcr; } public void setOpeningcr(int openingcr) { this.openingcr = openingcr; } public int getOpeningdr() { return openingdr; } public void setOpeningdr(int openingdr) { this.openingdr = openingdr; } public int getCredit() { return credit; } public void setCredit(int credit) { this.credit = credit; } public int getDebit() { return debit; } public void setDebit(int debit) { this.debit = debit; } public int getClosingdr() { return closingdr; } public void setClosingdr(int closingdr) { this.closingdr = closingdr; } public int getClosingcr() { return closingcr; } public void setClosingcr(int closingcr) { this.closingcr = closingcr; } }
package com.wuc.jetpackppjoke; import android.app.Application; import com.wuc.libnetwork.ApiService; /** * @author: wuchao * @date: 2020-02-13 22:17 * @desciption: 皮皮虾项目在线Api文档地址:http://123.56.232.18:8080/serverdemo/swagger-ui.html#/ * * <p> * * 同学们有需要的话,可以按照:https://git.imooc.com/Chubby/jetpack_ppjoke/src/master/%e6%9c%8d%e5%8a%a1%e5%99%a8%e7%8e%af%e5%a2%83%e6%90%ad%e5%bb%ba.md * * 来搭建本地服务器 */ public class JokeApplication extends Application { @Override public void onCreate() { super.onCreate(); //http://123.56.232.18:8080/serverdemo/swagger-ui.html#/ ApiService.init("http://123.56.232.18:8080/serverdemo", null); } }
package payment.domain.repository; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import lombok.NonNull; import org.springframework.stereotype.Component; import payment.domain.model.Payment; /** * @author claudioed on 26/06/17. Project docker-aws-devry */ @Component public class PaymentRepository { private final DynamoDBMapper dynamoDBMapper; public PaymentRepository(DynamoDBMapper dynamoDBMapper) { this.dynamoDBMapper = dynamoDBMapper; } public void save(@NonNull Payment payment){ this.dynamoDBMapper.save(payment); } public Payment payment(@NonNull String id){ return this.dynamoDBMapper.load(Payment.class,id); } }
import com.sun.tools.doclets.internal.toolkit.util.DocFinder; /** * Created by dobatake on 4/14/16. */ public class OutputWriterTest { public static void main(String[] args) { OutputWriter ow = new OutputWriter(); ow.initStore(); ow.constructHTML(); } }
package org.edwith.webbe.securityexam.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableWebMvc @ComponentScan(basePackages = {"org.edwith.webbe.securityexam.controller"}) public class MvcConfig implements WebMvcConfigurer{ // default servlet 핸들러 설정 // 원래 서블릿은 모든 요청을 처리하는 default servlet을 제공 => spring에서 설정한 path는 스프링이 처리하고, // 나머지 경로에 대한 처리는 default servlet가 처리 @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } // spring MVC에서 jsp view가 위치하는 경로 설정 @Override public void configureViewResolvers(ViewResolverRegistry registry) { registry.jsp("/WEB-INF/view", ".jsp"); } // /로 요청이 들어오면 /main 으로 redirect @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addRedirectViewController("/", "/main"); } // /resources에 있는 경로들을 /resources/**로 접근하게 함 @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } }
package beehive.controller; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Vector; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import beehive.bean.*; import beehive.dao.ReportDao; import beehive.dao.UserDao; public class SaveAction extends HttpServlet { /** * */ private UserDao userDao = new UserDao(); private ReportDao reportDao = new ReportDao(); public SaveAction() { super(); } public void destroy() { super.destroy(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { request.setCharacterEncoding("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // Read report data from <form> String keys[] = { "pho", "co1", "tem", "hum", "noi", "ult" }; Vector<String> values = new Vector<String>(); for(String key: keys) values.add( request.getParameter(key) ); // If user phone not exist, return String phone = values.get(0); if(!userDao.has(phone)) return; // Initiate a Report object Date timestamp = new Date(); Report report = new Report(phone, timestamp, Float.parseFloat(values.get(1)), Float.parseFloat(values.get(2)), Float.parseFloat(values.get(3)), Float.parseFloat(values.get(4)), Float.parseFloat(values.get(5)) ); // Call ReportDao to save the object reportDao.save(report); } public void init() throws ServletException { // Put your code here } }
import java.util.LinkedList; /** NSdlst.java * * Author: Greg Choice c9311718@uon.edu.au * * Created: * Updated: 28/09/2018 * * Description: * STNode sub-class for NSDLST rule * */ public class NSdlst extends STNode { public NSdlst(LinkedList<Token> tokenList, SymbolTable table) { super(NID.NSDLST); setRight(processSdlst(tokenList, table)); } }
package com.ex.musicdb.service.impl; import com.ex.musicdb.model.entities.LikeEntity; import com.ex.musicdb.repository.ArticleRepository; import com.ex.musicdb.repository.LikeRepository; import com.ex.musicdb.repository.UserRepository; import com.ex.musicdb.service.LikeService; import org.modelmapper.ModelMapper; import org.springframework.stereotype.Service; @Service public class LikeServiceImpl implements LikeService { private final LikeRepository likeRepository; private final UserRepository userRepository; private final ModelMapper modelMapper; private final ArticleRepository articleRepository; public LikeServiceImpl(LikeRepository likeRepository, UserRepository userRepository, ModelMapper modelMapper, ArticleRepository articleRepository) { this.likeRepository = likeRepository; this.userRepository = userRepository; this.modelMapper = modelMapper; this.articleRepository = articleRepository; } @Override public void likeById(Long id, String username) { LikeEntity likeEntity = new LikeEntity(); likeEntity.setUser(userRepository.findByUsername(username).orElse(null)); likeEntity.setArticleEntity(articleRepository.getOne(id)); if (likeEntity.getLikes() == null) { likeEntity.setLikes(0); } likeEntity.setLikes(likeEntity.getLikes() + 1); likeRepository.save(likeEntity); } }
package com.montran.main; import java.util.Scanner; import com.montran.pojo.Assignment1; public class Assignment1_main { public static void main(String[] args) { Assignment1 assignment1 = new Assignment1(); Scanner scanner = new Scanner(System.in); Assignment1 book = null; book.input(01, "xyz", 150); int a = scanner.nextInt(); System.out.println("Enter The Number of Copies"); int n = scanner.nextInt(); if(n > 0) System.out.println("Total Amount To Be Paid is :" + book.purchase(n)); else System.out.println("Please Enter Valid Number Of Copies"); } }
package cn.com.hzzc.industrial.pro; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONObject; import android.app.AlertDialog; import android.app.Dialog; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import cn.com.hzzc.industrial.pro.adapter.QuestionItemAdapter; import cn.com.hzzc.industrial.pro.cons.SystemConst; import cn.com.hzzc.industrial.pro.entity.CheckItem; import cn.com.hzzc.industrial.pro.entity.ItemOption; import cn.com.hzzc.industrial.pro.opsinterface.IQuestionItemOperator; import cn.com.hzzc.industrial.pro.util.ActUtils; import com.lidroid.xutils.exception.HttpException; import com.lidroid.xutils.http.ResponseInfo; import com.lidroid.xutils.http.callback.RequestCallBack; /** * @todo 统计问卷 * @author pang * */ public class ActivityTypeThreeFragment extends ParentActFragment implements OnClickListener, IQuestionItemOperator { private Button type_2_add, question_btn; private EditText stat_info, stat_item_1, stat_item_2, stat_item_3, stat_item_4, stat_item_5; Dialog dialog; private ListView item_lv; private List<CheckItem> ds = new ArrayList<CheckItem>(); private QuestionItemAdapter adapter = null; View diaView; public ActivityTypeThreeFragment(String dId) { this.dId = dId; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LayoutInflater inflater = getActivity().getLayoutInflater(); mMainView = inflater.inflate( R.layout.activity_type_three_fragment, (ViewGroup) getActivity().findViewById( R.id.act_fragment_parent_viewpager), false); init(); initListView(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); ViewGroup p = (ViewGroup) mMainView.getParent(); if (p != null) { p.removeAllViewsInLayout(); } return mMainView; } /** * @user:pang * @data:2015年10月20日 * @todo:初始化按钮 * @return:void */ private void init() { // 获取按钮 type_2_add = (Button) mMainView.findViewById(R.id.type_2_add); type_2_add.setOnClickListener(this); // 获取对话框 diaView = View.inflate(getActivity(), R.layout.act_statistics_dialog, null); dialog = new AlertDialog.Builder(getActivity()).setView(diaView) .create(); question_btn = (Button) diaView.findViewById(R.id.question_btn); question_btn.setOnClickListener(this); stat_info = (EditText) diaView.findViewById(R.id.stat_info); stat_item_1 = (EditText) diaView.findViewById(R.id.stat_item_1); stat_item_2 = (EditText) diaView.findViewById(R.id.stat_item_2); stat_item_3 = (EditText) diaView.findViewById(R.id.stat_item_3); stat_item_4 = (EditText) diaView.findViewById(R.id.stat_item_4); stat_item_5 = (EditText) diaView.findViewById(R.id.stat_item_5); } /** * @user:pang * @data:2015年10月20日 * @todo:初始化listview * @return:void */ private void initListView() { item_lv = (ListView) mMainView.findViewById(R.id.item_lv); adapter = new QuestionItemAdapter(getActivity(), ds, ActivityTypeThreeFragment.this); item_lv.setAdapter(adapter); loadData(); } /** * @user:pang * @data:2015年10月20日 * @todo:加载数据 * @return:void */ private void loadData() { ds.clear(); String url = SystemConst.server_url + SystemConst.Type3Url.queryActivityStatisticItemByStatisticId; try { JSONObject d = new JSONObject(); d.put("statisticId", dId); RequestCallBack<String> rcb = new RequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String> responseInfo) { String data = responseInfo.result; List<CheckItem> lst = ActUtils.getStatItems(data); ds.addAll(lst); adapter.notifyDataSetChanged(); } @Override public void onFailure(HttpException error, String msg) { } }; Map map = new HashMap(); map.put("para", d.toString()); send_normal_request(url, map, rcb); } catch (Exception e) { e.printStackTrace(); } } @Override public void onClick(View v) { if (v.getId() == R.id.type_2_add) { dialog.show(); } else if (v.getId() == R.id.question_btn) {// 保存或者修改 Toast.makeText(getActivity(), stat_info.getText().toString(), Toast.LENGTH_SHORT).show(); dialog.dismiss(); String opt = stat_info.getText().toString(); stat_info.setText(""); if (editId != null && !"".equals(editId)) {// 修改 realEdit(editId, opt); } else {// 新增 realAdd(opt); } editId = ""; } } private String editId; @Override public void edit(int index, String id) { editId = id; stat_info.setText(ds.get(index).getItemName()); stat_item_1.setText(""); stat_item_2.setText(""); stat_item_3.setText(""); stat_item_4.setText(""); stat_item_5.setText(""); getOptionByItemId(editId); } /** * * @param editId * @user:pang * @data:2015年10月21日 * @todo:编辑之前根据itemID获取所有的option * @return:void */ private void getOptionByItemId(String id) { String url = SystemConst.server_url + SystemConst.Type3Url.queryActivityStatisticItemOptionByStatisticItemId; try { JSONObject d = new JSONObject(); d.put("statisticItemId", id); RequestCallBack<String> rcb = new RequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String> responseInfo) { String data = responseInfo.result; List<ItemOption> lst = ActUtils.getStatItemOptions(data); if (lst != null && !lst.isEmpty()) { for (int i = 0; i < lst.size(); i++) { ItemOption io = lst.get(i); String option = io.getOption(); if (i == 0) { stat_item_1.setText(option); } else if (i == 1) { stat_item_2.setText(option); } else if (i == 2) { stat_item_3.setText(option); } else if (i == 3) { stat_item_4.setText(option); } else if (i == 4) { stat_item_5.setText(option); } } } dialog.show(); } @Override public void onFailure(HttpException error, String msg) { Toast.makeText(getActivity(), "删除失败请重试", Toast.LENGTH_SHORT) .show(); } }; Map map = new HashMap(); map.put("para", d.toString()); send_normal_request(url, map, rcb); } catch (Exception e) { e.printStackTrace(); } } /** * 删除 */ @Override public void del(final int index, String id) { String url = SystemConst.server_url + SystemConst.Type3Url.delActivityStatisticItemAndOptions; try { JSONObject d = new JSONObject(); d.put("Id", id); RequestCallBack<String> rcb = new RequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String> responseInfo) { String data = responseInfo.result; // 删除成功刷新列表 ds.remove(index); adapter.notifyDataSetChanged(); } @Override public void onFailure(HttpException error, String msg) { Toast.makeText(getActivity(), "删除失败请重试", Toast.LENGTH_SHORT) .show(); } }; Map map = new HashMap(); map.put("para", d.toString()); send_normal_request(url, map, rcb); } catch (Exception e) { e.printStackTrace(); } } public void realEdit(String id, String question) { String url = SystemConst.server_url + SystemConst.Type3Url.editActivityStatisticItem; String opt1 = stat_item_1.getText().toString(); String opt2 = stat_item_2.getText().toString(); String opt3 = stat_item_3.getText().toString(); String opt4 = stat_item_4.getText().toString(); String opt5 = stat_item_5.getText().toString(); try { JSONObject d = new JSONObject(); d.put("Id", id); d.put("statisticId", dId); d.put("content", question); JSONArray array = new JSONArray(); if (opt1 != null && !"".equals(opt1)) { JSONObject i = new JSONObject(); i.put("option", opt1); array.put(i); } if (opt2 != null && !"".equals(opt2)) { JSONObject i = new JSONObject(); i.put("option", opt2); array.put(i); } if (opt3 != null && !"".equals(opt3)) { JSONObject i = new JSONObject(); i.put("option", opt3); array.put(i); } if (opt4 != null && !"".equals(opt4)) { JSONObject i = new JSONObject(); i.put("option", opt4); array.put(i); } if (opt5 != null && !"".equals(opt5)) { JSONObject i = new JSONObject(); i.put("option", opt5); array.put(i); } d.put("options", array); RequestCallBack<String> rcb = new RequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String> responseInfo) { String data = responseInfo.result; // 删除成功刷新列表 loadData(); } @Override public void onFailure(HttpException error, String msg) { Toast.makeText(getActivity(), "删除失败请重试", Toast.LENGTH_SHORT) .show(); } }; Map map = new HashMap(); map.put("para", d.toString()); send_normal_request(url, map, rcb); } catch (Exception e) { e.printStackTrace(); } } public void realAdd(String question) { String url = SystemConst.server_url + SystemConst.Type3Url.addActivityStatisticItem; String opt1 = stat_item_1.getText().toString(); String opt2 = stat_item_2.getText().toString(); String opt3 = stat_item_3.getText().toString(); String opt4 = stat_item_4.getText().toString(); String opt5 = stat_item_5.getText().toString(); try { JSONObject d = new JSONObject(); d.put("statisticId", dId); d.put("content", question); JSONArray array = new JSONArray(); if (opt1 != null && !"".equals(opt1)) { JSONObject i = new JSONObject(); i.put("option", opt1); array.put(i); } if (opt2 != null && !"".equals(opt2)) { JSONObject i = new JSONObject(); i.put("option", opt2); array.put(i); } if (opt3 != null && !"".equals(opt3)) { JSONObject i = new JSONObject(); i.put("option", opt3); array.put(i); } if (opt4 != null && !"".equals(opt4)) { JSONObject i = new JSONObject(); i.put("option", opt4); array.put(i); } if (opt5 != null && !"".equals(opt5)) { JSONObject i = new JSONObject(); i.put("option", opt5); array.put(i); } d.put("options", array); RequestCallBack<String> rcb = new RequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String> responseInfo) { String data = responseInfo.result; loadData(); } @Override public void onFailure(HttpException error, String msg) { Toast.makeText(getActivity(), "删除失败请重试", Toast.LENGTH_SHORT) .show(); error.printStackTrace(); } }; Map map = new HashMap(); map.put("para", d.toString()); send_normal_request(url, map, rcb); } catch (Exception e) { e.printStackTrace(); } } }
/** * All rights Reserved, Designed By www.tydic.com * @Title: ContentServiceImpl.java * @Package com.taotao.service.impl * @Description: TODO(用一句话描述该文件做什么) * @author: axin * @date: 2018年12月23日 下午9:57:08 * @version V1.0 * @Copyright: 2018 www.hao456.top Inc. All rights reserved. */ package com.taotao.service.impl; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.taotao.common.pojo.DataGridResult; import com.taotao.common.pojo.TaotaoResult; import com.taotao.common.utils.HttpClientUtil; import com.taotao.mapper.TbContentMapper; import com.taotao.pojo.TbContent; import com.taotao.pojo.TbContentExample; import com.taotao.service.ContentService; /** * @Description: TODO * @ClassName: ContentServiceImpl * @author: Axin * @date: 2018年12月23日 下午9:57:08 * @Copyright: 2018 www.hao456.top Inc. All rights reserved. */ @Service public class ContentServiceImpl implements ContentService { @Autowired private TbContentMapper contentMapper; @Value("${REST_BASE_URL}") private String REST_BASE_URL; @Value("${REST_CONTENT_SYNC_URL}") private String REST_CONTENT_SYNC_URL; /* (non-Javadoc) * @see com.taotao.service.ContentService#getContentList(java.lang.Long, java.lang.Integer, java.lang.Integer) */ @Override public DataGridResult getContentList(Long categoryId, Integer page, Integer rows) { TbContentExample example = new TbContentExample(); example.createCriteria().andCategoryIdEqualTo(categoryId); PageHelper.startPage(page, rows); List<TbContent> list = this.contentMapper.selectByExample(example); PageInfo<TbContent> pageInfo = new PageInfo<TbContent>(list); long total = pageInfo.getTotal(); DataGridResult result = new DataGridResult(); result.setRows(list); result.setTotal(total); return result; } /* (non-Javadoc) * @see com.taotao.service.ContentService#insertContent(com.taotao.pojo.TbContent) */ @Override public TaotaoResult insertContent(TbContent content) { content.setCreated(new Date()); content.setUpdated(new Date()); this.contentMapper.insert(content); try { //添加缓存同步逻辑 HttpClientUtil.doGet(REST_BASE_URL+REST_CONTENT_SYNC_URL+content.getCategoryId()); } catch (Exception e) { e.printStackTrace(); } return TaotaoResult.ok(); } }
package leetCode.copy.Tree; import leetCode.copy.common.TreeNode; import java.util.ArrayDeque; import java.util.Collection; import java.util.Deque; import java.util.Iterator; /** * 297. 二叉树的序列化与反序列化 * * 序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。 * * 请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。 * * 提示: 输入输出格式与 LeetCode 目前使用的方式一致,详情请参阅 LeetCode 序列化二叉树的格式。你并非必须采取这种方式,你也可以采用其他的方法解决这个问题。 * * 示例 1: * 输入:root = [1,2,3,null,null,4,5] * 输出:[1,2,3,null,null,4,5] * * 示例 2: * 输入:root = [] * 输出:[] * * 示例 3: * 输入:root = [1] * 输出:[1] * * 示例 4: * 输入:root = [1,2] * 输出:[1,2] * * 提示: * 树中结点数在范围 [0, 10^4] 内 * -1000 <= Node.val <= 1000 * * 链接:https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree * */ public class no297_serialize_and_deserialize_binary_tree { public String serialize(TreeNode root) { if (root == null) return ""; StringBuilder strBuilder = new StringBuilder(); ArrayDeque<TreeNode> queue = new ArrayDeque<TreeNode>(); queue.add(root); while (!queue.isEmpty()) { TreeNode p = queue.pollFirst(); if (strBuilder.length() == 0) { strBuilder.append("" + p.val); } else { strBuilder.append(":" + p.val); } if (p.val == 6666) continue; if (p.left != null) { queue.addLast(p.left); } else { queue.addLast(new TreeNode(6666)); } if (p.right != null) { queue.addLast(p.right); } else { queue.addLast(new TreeNode(6666)); } } return strBuilder.toString(); } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { if (data == null || data.isEmpty()) return null; String[] dataArray = data.split(":"); int index = 0; TreeNode root = new TreeNode(Integer.valueOf(dataArray[index++])); Deque<TreeNode> queue = new ArrayDeque<TreeNode>(); queue.add(root); while (!queue.isEmpty()) { TreeNode p = queue.remove(); if (p.val == 6666) { continue; } int element = Integer.valueOf(dataArray[index++]); if (element != 6666) { p.left = new TreeNode(element); queue.add(p.left); } element = Integer.valueOf(dataArray[index++]); if (element != 6666) { p.right = new TreeNode(element); queue.add(p.right); } } return root; } public static void main(String args[]){ no297_serialize_and_deserialize_binary_tree obj = new no297_serialize_and_deserialize_binary_tree(); String data = obj.serialize(null); System.out.println(data); obj.deserialize(data); data = obj.serialize(new TreeNode(1)); System.out.println(data); TreeNode result = obj.deserialize(data); TreeNode root = new TreeNode(1); root.right = new TreeNode(3); data = obj.serialize(root); System.out.println(data); result = obj.deserialize(data); } }
package com.example.edvisor; import java.io.Serializable; import java.time.LocalDateTime; public class Booking implements Serializable { public int id; public int expert_id; public int customer_id; public boolean current_status; public String description; LocalDateTime startTime; LocalDateTime endTime; public String getcontent() { String customer=new String(); String worker=new String(); if (id==1) { worker="Bilal"; } else if(id==123) { worker="arsalan"; } else { worker="Umer"; } return "Booking id:"+id + " Expert name: "+worker+" ( "+expert_id + ")"; } }
package f.star.iota.milk.ui.more; import android.content.Intent; import android.net.Uri; import android.os.SystemClock; import android.support.v7.widget.SwitchCompat; import android.view.View; import android.widget.CompoundButton; import butterknife.BindView; import butterknife.OnClick; import f.star.iota.milk.Net; import f.star.iota.milk.R; import f.star.iota.milk.base.BaseActivity; import f.star.iota.milk.config.OtherConfig; import f.star.iota.milk.util.MessageBar; import moe.feng.alipay.zerosdk.AlipayZeroSdk; public class MoreActivity extends BaseActivity { private final long[] mHints = new long[5]; @BindView(R.id.switch_compat_r) SwitchCompat mSwitchCompatR; @OnClick({R.id.linear_layout_donation_alipay, R.id.linear_layout_donation_qq, R.id.linear_layout_donation_wechat, R.id.text_view_hitokoto_loli, R.id.text_view_hitokoto_ad, R.id.text_view_yiju, R.id.linear_layout_grade, R.id.text_view_juzi, R.id.linear_layout_r}) public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_VIEW); switch (view.getId()) { case R.id.linear_layout_donation_qq: intent.setData(Uri.parse(mContext.getString(R.string.qq_pay_code))); break; case R.id.linear_layout_donation_wechat: intent.setData(Uri.parse(mContext.getString(R.string.wechat_pay_code))); break; case R.id.text_view_juzi: intent.setData(Uri.parse(Net.HITOKOTO_BILIBILIJJ_BASE)); break; case R.id.text_view_yiju: intent.setData(Uri.parse(Net.YIJU_BASE)); break; case R.id.text_view_hitokoto_ad: intent.setData(Uri.parse(Net.HITOKOTO_IMJAD_BASE)); break; case R.id.text_view_hitokoto_loli: intent.setData(Uri.parse(Net.HITOKOTO_LOLI_BASE)); break; case R.id.linear_layout_grade: intent.setData(Uri.parse("market://details?id=" + mContext.getPackageName())); break; case R.id.linear_layout_r: System.arraycopy(mHints, 1, mHints, 0, mHints.length - 1); mHints[mHints.length - 1] = SystemClock.uptimeMillis(); if (SystemClock.uptimeMillis() - mHints[0] <= 800) { MessageBar.create(mContext, ((int) (Math.random() * 2)) == 1 ? "令人窒息的操作" : "还有这种操作?"); if (mSwitchCompatR.getVisibility() == View.GONE) { mSwitchCompatR.setVisibility(View.VISIBLE); } } return; case R.id.linear_layout_donation_alipay: if (AlipayZeroSdk.hasInstalledAlipayClient(mContext)) { AlipayZeroSdk.startAlipayClient(this, getResources().getString(R.string.alipay_code)); } else { MessageBar.create(mContext, "你可能没有安装支付宝"); } return; } if (intent.getData() != null) { startActivity(intent); } } @Override protected void init() { setTitle(null); if (OtherConfig.getR(aContext)) { mSwitchCompatR.setChecked(true); } else { mSwitchCompatR.setChecked(false); } mSwitchCompatR.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { OtherConfig.saveR(aContext, true); MessageBar.create(mContext, "好好学习,天天向上"); } else { OtherConfig.saveR(aContext, false); MessageBar.create(mContext, "飙车了"); } } }); } @Override protected int getContentViewId() { return R.layout.activity_more; } }
package com.disco; import java.io.IOException; import java.util.List; import java.util.Random; import java.util.Scanner; import com.disco.dao.AlbumDao; import com.disco.dao.AlbumDaoImpl; import com.disco.dao.ArtistDao; import com.disco.dao.ArtistDaoImpl; import com.disco.dao.SacemDao; import com.disco.dao.SacemDaoImpl; import com.disco.model.Album; import com.disco.model.Artist; import com.disco.model.SacemRegistration; public class Entry { private static Scanner sc = new Scanner(System.in); private static SacemDao sacemDao = new SacemDaoImpl(); private static ArtistDao artistDao = new ArtistDaoImpl(); private static AlbumDao albumDao = new AlbumDaoImpl(); public static void main(String[] args) throws IOException { displayHello(); boolean exit = false; do { String choice = displayMainMenuAndGetChoice(); clearScreen(false); switch (choice) { case "lr": listArtist(); break; case "ll": listAlbums(); break; case "cr": createArtist(); break; case "s": selectAndEnterArtist(); break; case "del": deleteArtist(); break; case "exit": exit = true; break; default: break; } }while(!exit); System.out.println("**************************************************"); System.out.println(" For those about to rock, we salute you! "); System.out.println("**************************************************"); } private static void selectAndEnterArtist() { System.out.print("Band Name to edit>"); String bandName = sc.nextLine(); Artist a = artistDao.findByKey(bandName); if(a != null) { showAlbumLoop(a); }else { System.out.println("Unknow input... try harder"); } } private static void showAlbumLoop(Artist a) { boolean exitalbum = false; do { String choiceAlbum = displayArtistMenuAndGetChoice(a); clearScreen(false); switch (choiceAlbum) { case "s": System.out.println("EDIT TO DO"); break; case "cr": createAlbum(a); break; case "ll": listAlbums(a); break; case "del": deleteAlbum(); case "exit": exitalbum = true; break; default: break; } }while(!exitalbum); } private static void deleteAlbum() { System.out.print("Album ID to delete>"); Long id = sc.nextLong(); albumDao.deleteByKey(id); System.out.println("Done"); } private static void createAlbum(Artist a) { System.out.print("Title>"); String title = sc.nextLine(); System.out.print("Release Year>"); int releaseYear = sc.nextInt(); Album album = new Album(title, releaseYear, a); albumDao.insert(album); System.out.print("Album ADD: OK"); } private static void listArtist() { System.out.println("List Artist"); for(Artist a : artistDao.findAll()) { System.out.println(a.getBandName()+":"+a.getFirstName()+" "+a.getLastName()); } clearScreen(true); } private static void listAlbums() { System.out.println("List Albums"); for(Album a : albumDao.findAll()) { System.out.println(a.getId() + ":" + a.getTitle()+":"+a.getReleaseYear()); } clearScreen(true); } private static void listAlbums(Artist artist) { System.out.println("List Albums"); for(Album a : albumDao.findAllByArtist(artist)) { System.out.println(a.getTitle()+":"+a.getReleaseYear()); } clearScreen(true); } private static void deleteArtist() throws IOException { System.out.print("Band Name to delete>"); String bandName = sc.nextLine(); Artist artist = artistDao.findByKey(bandName); if(artist == null) { System.out.println("Artiste inconnu"); clearScreen(true); return; } albumDao.deleteByArtiste(artist); SacemRegistration sacemReg = sacemDao.getByArtist(artist); artistDao.deleteByKey(bandName); sacemDao.deleteByKey(sacemReg.getReference()); clearScreen(true); } private static void createArtist() throws IOException { System.out.print("Band Name>"); String bandName = sc.nextLine(); System.out.print("First Name>"); String firstName = sc.nextLine(); System.out.print("Last Name>"); String lastName = sc.nextLine(); System.out.print("Registration Number>"); String registrationNumber = sc.nextLine(); SacemRegistration sacemReg = new SacemRegistration(registrationNumber); sacemDao.insert(sacemReg); Artist artist = new Artist(bandName, firstName, lastName); artist.setSacemRegistration(sacemReg); artistDao.insert(artist); clearScreen(true); } private static String displayMainMenuAndGetChoice() { System.out.println("> Make a choice"); System.out.println("*************"); System.out.println("(lr) List all artists"); System.out.println("(ll) List all albums"); System.out.println("(cr) Create an artist"); System.out.println("(s) Select and artist and go to album managment"); System.out.println("(del) Delete an artist"); System.out.println("(exit) exit"); System.out.print("Your choice ? >"); return sc.nextLine(); } private static String displayArtistMenuAndGetChoice(Artist artist) { System.out.println("> What do you want to to for artist :"+artist.getBandName()); System.out.println("***************************"); System.out.println("(s) Edit informations"); System.out.println("(cr) create an album"); System.out.println("(ll) List all albums for this artist"); System.out.println("(s) Delete an album"); System.out.println("(s) Edit an album"); System.out.println("(exit) exit to main menu"); System.out.print("Your choice ? >"); return sc.nextLine(); } private static void displayHello() { System.out.println("**********************************"); System.out.println("* Welcome to *"); System.out.println("* SuperDiscographie *"); System.out.println("**********************************"); System.out.println(""); System.out.println(""); } private static void test() { Random rand = new Random(); // TEST SACEM SacemDao sacemDao = new SacemDaoImpl(); SacemRegistration sacemreg = new SacemRegistration(""+rand.nextInt(500000)); sacemDao.insert(sacemreg); List<SacemRegistration> listSacem = sacemDao.findAll(); System.out.println(listSacem.size()); SacemRegistration sacemRegistration = listSacem.get(0); sacemRegistration.setReference("AAA"); sacemDao.update(sacemRegistration); listSacem = sacemDao.findAll(); System.out.println(sacemDao.findAll().get(0)); System.out.println(listSacem.size()); sacemDao.deleteByKey(listSacem.get(listSacem.size()-1).getReference()); listSacem = sacemDao.findAll(); System.out.println(listSacem.size()); sacemreg = new SacemRegistration(""+rand.nextInt(500000)); sacemDao.insert(sacemreg); listSacem = sacemDao.findAll(); System.out.println(sacemDao.findByKey(listSacem.get(0).getReference())); // TEST ARTIST ArtistDao artistDao = new ArtistDaoImpl(); Artist artistreg = new Artist(""+rand.nextInt(500000),"jean","mouloud"); artistreg.setSacemRegistration(listSacem.get(listSacem.size() - 1)); artistDao.insert(artistreg); List<Artist> listArtist = artistDao.findAll(); System.out.println(listArtist.size()); System.out.println(listArtist.get(0)); Artist artist = listArtist.get(0); artist.setFirstName("Michel"); artistDao.update(artist); listArtist = artistDao.findAll(); System.out.println(artistDao.findAll().get(0)); System.out.println(listArtist.size()); artistDao.deleteByKey(listArtist.get(listArtist.size()-1).getBandName()); listArtist = artistDao.findAll(); System.out.println(listArtist.size()); artistreg = new Artist("ABC"+""+rand.nextInt(500000),"jean","mouloud"); artistreg.setSacemRegistration(listSacem.get(0)); artistDao.insert(artistreg); listArtist = artistDao.findAll(); System.out.println(artistDao.findByKey(listArtist.get(0).getBandName())); // TEST ALBUM AlbumDao albumDao = new AlbumDaoImpl(); Album albumreg = new Album("Reign in blood",2019, listArtist.get(0)); albumreg.setArtist(listArtist.get(0)); albumDao.insert(albumreg); List<Album> listAlbum = albumDao.findAll(); System.out.println(listAlbum.size()); System.out.println(listAlbum.get(0)); Album album = listAlbum.get(0); album.setTitle("The link"); albumDao.update(album); listAlbum = albumDao.findAll(); System.out.println(albumDao.findAll().get(0)); System.out.println(listAlbum.size()); albumDao.deleteByKey(listAlbum.get(listAlbum.size()-1).getId()); listAlbum = albumDao.findAll(); System.out.println(listAlbum.size()); albumreg = new Album("Rust in peace",1946, listArtist.get(0)); albumreg.setArtist(listArtist.get(0)); albumDao.insert(albumreg); listAlbum = albumDao.findAll(); System.out.println(albumDao.findByKey(listAlbum.get(0).getId())); } public static void clearScreen(boolean askForKey) { if(askForKey) { System.out.println("Press enter to continue"); try { System.in.read(); } catch (IOException e) { e.printStackTrace(); } } System.out.print("\033[H\033[2J"); System.out.flush(); } }
package br.senac.rn.agenda.controller; import br.senac.rn.agenda.model.Contato; import br.senac.rn.agenda.services.ContatoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.List; @Controller @RequestMapping("/contatos") public class ContatoController { @Autowired private ContatoService service; @GetMapping public String listaTodos(Model model){ //lista todos Contato contato = new Contato(); model.addAttribute("contato", contato); List<Contato>contatos = service.listaTodos(); model.addAttribute("contatos",contatos); return "contatos"; } @PostMapping public String salva(Contato contato){ //salva service.salva(contato); return "redirect:/contatos"; } @GetMapping("/{id}/remove") // o @DeleteMapping é so para casa eu esteja usando uma API public String removerPorId(@PathVariable("id") Long id){ // deleta por id service.removePorId(id); return "redirect:/contatos"; } @GetMapping("/{id}/edita") public String edita(@PathVariable("id") Long id, Model model){ Contato contato = service.listaPorId(id); model.addAttribute("contato", contato); List<Contato> contatos = service.listaTodos(); model.addAttribute("contatos", contatos); return "contatos"; } }
import java.util.*; import java.math.BigDecimal; public class PriceSearch { private boolean[] visited; private BigDecimal price; public ArrayList<String> routes; public PriceSearch(Graph map, BigDecimal price) { this.visited = new boolean[map.length + 1]; this.routes = new ArrayList<String>(); this.price = price; for (int i = 1; i <= map.length; i++) { String cityName = map.getCity(i).name; visit(map, i, cityName, new BigDecimal(0)); } } private void visit(Graph map, int city, String cityList, BigDecimal price) { // Base case: city already visited if (visited[city]) { return; } // Base case: cost exceeded if (price.compareTo(this.price) > 0) { return; } if (price.compareTo(new BigDecimal(0)) > 0) { routes.add(cityList + " (" + price.toString() + ")"); } // Mark it as visited visited[city] = true; Iterator<Edge> neighbors = map.flightsFor(city).iterator(); while(neighbors.hasNext()) { Edge neighbor = neighbors.next(); visit(map, neighbor.id, cityList + " --> " + map.getCity(neighbor.id).name, price.add(neighbor.price)); } // Un-visit before returning visited[city] = false; } }
package it.com.atlassian.bitbucket.jenkins.internal.trigger; import com.atlassian.bitbucket.jenkins.internal.model.BitbucketUser; import com.atlassian.bitbucket.jenkins.internal.trigger.BitbucketWebhookTriggerImpl; import com.atlassian.bitbucket.jenkins.internal.trigger.BitbucketWebhookTriggerRequest; import hudson.FilePath; import hudson.Launcher; import hudson.model.*; import hudson.scm.NullSCM; import hudson.scm.PollingResult; import hudson.scm.SCMRevisionState; import hudson.util.RunList; import it.com.atlassian.bitbucket.jenkins.internal.util.AsyncTestUtils; import it.com.atlassian.bitbucket.jenkins.internal.util.SingleExecutorRule; import it.com.atlassian.bitbucket.jenkins.internal.util.WaitConditionFailure; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.rules.RuleChain; import org.junit.rules.TestRule; import org.jvnet.hudson.test.JenkinsRule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.Queue; import static com.google.common.base.Objects.firstNonNull; import static java.util.Optional.empty; import static java.util.Optional.of; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; public class BitbucketWebhookTriggerImplTest { public static final JenkinsRule jenkinsRule = new JenkinsRule(); private static final Logger LOGGER = LoggerFactory.getLogger(BitbucketWebhookTriggerImplTest.class); @ClassRule public static TestRule chain = RuleChain.outerRule(jenkinsRule).around(new SingleExecutorRule()); private FreeStyleProject project; private TestScm scm; private BitbucketWebhookTriggerImpl trigger; @Before public void setup() throws Exception { project = jenkinsRule.createFreeStyleProject(); scm = new TestScm(); project.setScm(scm); trigger = new BitbucketWebhookTriggerImpl(); trigger.start(project, true); } @After public void tearDown() throws IOException, InterruptedException { project.delete(); } @Test public void testTriggerPollingInitialBuild() { // The initial build actually doesn't call out to the SCM to get the poll result, it just // assumes it should build because there are no previous results trigger.trigger( BitbucketWebhookTriggerRequest.builder() .actor(new BitbucketUser("username", "me@example.com", "me")) .build()); RunList<FreeStyleBuild> builds = waitForBuild(); FreeStyleBuild lastBuild = builds.getLastBuild(); assertThat("The last build should not be null", lastBuild, not(nullValue())); List<Cause> causes = lastBuild.getCauses(); assertThat("The last build should have exactly one cause", causes, hasSize(1)); Cause cause = causes.get(0); assertThat("The cause should not be null", cause, not(nullValue())); String description = cause.getShortDescription(); assertThat( "The description should be from the trigger", description, equalTo("Triggered by Bitbucket webhook due to changes by me.")); } @Test public void testTriggerPollingSubsequentBuildNoChanges() { trigger.trigger( BitbucketWebhookTriggerRequest.builder() .actor(new BitbucketUser("me", "me@me.com", "Me")) .build()); waitForBuild(); scm.addPollingResult(PollingResult.NO_CHANGES); trigger.trigger( BitbucketWebhookTriggerRequest.builder() .actor(new BitbucketUser("you", "you@you.com", "You")) .build()); try { RunList<FreeStyleBuild> builds = waitForBuild(2); fail("Expected there to be only 1 build triggered, but there were 2: " + builds); } catch (WaitConditionFailure e) { assertThat( "Only one build should have been triggered because the second build had no changes after polling.", e.getMessage(), equalTo("There are only 1 builds for the project, but we need 2")); } } @Test public void testTriggerPollingSubsequentBuildNow() { trigger.trigger( BitbucketWebhookTriggerRequest.builder() .actor(new BitbucketUser("me", "me@me.com", "Me")) .build()); waitForBuild(); scm.addPollingResult(PollingResult.BUILD_NOW); trigger.trigger( BitbucketWebhookTriggerRequest.builder() .actor(new BitbucketUser("you", "you@you.com", "You")) .build()); RunList<FreeStyleBuild> builds = waitForBuild(2); FreeStyleBuild lastBuild = builds.getLastBuild(); assertThat("The last build should not be null", lastBuild, not(nullValue())); List<Cause> causes = lastBuild.getCauses(); assertThat("The last build should have exactly one cause", causes, hasSize(1)); Cause cause = causes.get(0); assertThat("The cause should not be null", cause, not(nullValue())); String description = cause.getShortDescription(); assertThat( "The description should be from the trigger", description, equalTo("Triggered by Bitbucket webhook due to changes by You.")); } @Test public void testTriggerPollingSubsequentBuildSignificantChanges() { trigger.trigger( BitbucketWebhookTriggerRequest.builder() .actor(new BitbucketUser("me", "me@me.com", "Me")) .build()); waitForBuild(); scm.addPollingResult(PollingResult.SIGNIFICANT); trigger.trigger( BitbucketWebhookTriggerRequest.builder() .actor(new BitbucketUser("you", "you@you.com", "You")) .build()); RunList<FreeStyleBuild> builds = waitForBuild(2); FreeStyleBuild lastBuild = builds.getLastBuild(); assertThat("The last build should not be null", lastBuild, not(nullValue())); List<Cause> causes = lastBuild.getCauses(); assertThat("The last build should have exactly one cause", causes, hasSize(1)); Cause cause = causes.get(0); assertThat("The cause should not be null", cause, not(nullValue())); String description = cause.getShortDescription(); assertThat( "The description should be from the trigger", description, equalTo("Triggered by Bitbucket webhook due to changes by You.")); } private RunList<FreeStyleBuild> waitForBuild() { return waitForBuild(1); } private RunList<FreeStyleBuild> waitForBuild(int count) { AsyncTestUtils.waitFor( () -> { RunList<FreeStyleBuild> builds = project.getBuilds(); LOGGER.info("The current builds are: " + builds); if (builds.size() < count) { return of( "There are only " + builds.size() + " builds for the project, but we need " + count); } return empty(); }, 30000); return project.getBuilds(); } private class TestScm extends NullSCM { Queue<PollingResult> pollingResults = new LinkedList<>(); public void addPollingResult(PollingResult result) { pollingResults.add(result); } @Override public PollingResult compareRemoteRevisionWith( Job<?, ?> project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState baseline) throws IOException, InterruptedException { return firstNonNull(pollingResults.poll(), PollingResult.NO_CHANGES); } @Override public boolean requiresWorkspaceForPolling() { return false; } } }
package com.role.game.manager; import com.role.game.menu.interfaces.Battle; import com.role.game.menu.interfaces.BattleConfirmation; import com.role.game.menu.interfaces.GameExploration; import com.role.game.menu.interfaces.StartMenu; public class GameMenus { private final StartMenu startMenu; private final GameExploration gameExploration; private final BattleConfirmation battleConfirmation; private final Battle battle; public GameMenus(StartMenu startMenu, GameExploration gameExploration, BattleConfirmation battleConfirmation, Battle battle) { this.startMenu = startMenu; this.gameExploration = gameExploration; this.battleConfirmation = battleConfirmation; this.battle = battle; } public StartMenu getStartMenu() { return startMenu; } public GameExploration getGameExploration() { return gameExploration; } public BattleConfirmation getBattleConfirmation() { return battleConfirmation; } public Battle getBattle() { return battle; } }
package org.unbapp; public class Contact { private String title; private String numbers; private int numOfNumbers; private String separator= " \\| "; public Contact(String title, String numbers){ super(); this.title = title; this.numbers = numbers; this.numOfNumbers = this.calculateNumOfNumbers(numbers); } public int calculateNumOfNumbers(String numbers) { return numbers.split(this.separator).length; } public String getTitle() { return title; } public String getNumbers() { return numbers; } public String[] getNumbersArray() { return numbers.split(this.separator); } public int getNumOfNumbers() { return numOfNumbers; } }
package com.pettypal.domain; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.validation.constraints.Digits; @Entity(name="payment_history") public class PaymentHistory extends BaseEntityAudit { /** * */ private static final long serialVersionUID = 7166895796187552326L; @OneToOne(fetch=FetchType.EAGER, cascade= CascadeType.ALL) @JoinColumn(name="user_id", referencedColumnName = "id") private User user; @OneToOne(fetch=FetchType.EAGER, cascade= CascadeType.ALL) @JoinColumn(name="payment_id", referencedColumnName = "id") private Payment payment; @Digits(integer=15,fraction=2) private Double amount; @Enumerated(EnumType.STRING) private PaymentType type; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Payment getPayment() { return payment; } public void setPayment(Payment payment) { this.payment = payment; } public Double getAmount() { return amount; } public void setAmount(Double amount) { this.amount = amount; } public PaymentType getType() { return type; } public void setType(PaymentType type) { this.type = type; } }
package edu.gyaneshm.ebay_product_search.listeners; public interface DataFetchingListener { void dataSuccessFullyFetched(); }
package ru.vi.diskqueue; import java.io.*; import java.nio.ByteBuffer; import java.nio.file.Files; /** * Unsafe * * User: arevkov * Date: 3/18/13 * Time: 4:38 PM */ class ReadOnly implements Segment { /** File with data */ private final File file; /** Size of segment */ private final long size; /** lazy init. */ private BufferedInputStream in; private int readPosition; ReadOnly(File file, int readPosition) throws IOException { this.file = file; this.size = file.exists() ? file.length() : 0; this.readPosition = readPosition; } private void init() throws IOException { in = new BufferedInputStream(new FileInputStream(file)); readPosition = (int) in.skip(readPosition); if (DiskQueue.log.isDebugEnabled()) DiskQueue.log.debug("{} read_pos={} write_pos=(read_only)", file.getName(), readPosition); } public File getFile() { return file; } @Override public long size() { return size; } @Override public void load(ByteBuffer bb) throws Exception { if (in == null) init(); int len = Utils.readRawVarInt32(in); if (len == 0) throw new EOFException(); byte[] arr = new byte[len]; try { in.read(arr); } catch (EOFException e) { throw new IllegalStateException("unexpected journey"); } bb.put(arr); readPosition += len + Utils.len(len); } @Override public void store(ByteBuffer bb) throws Exception { throw new UnsupportedOperationException(); } @Override public void close() throws IOException { if (in != null) in.close(); in = null; } @Override public void delete() throws IOException { close(); try { Files.deleteIfExists(file.toPath()); } catch (IOException e) { // for Windows: file.deleteOnExit(); } } @Override public boolean isEmpty() { throw new UnsupportedOperationException(); } @Override public int getReadPosition() { return readPosition; } @Override public int getWritePosition() { throw new UnsupportedOperationException(); } }
package com.suntek.timesheet; public class ViewMapping { private int employeeSeq; private String employeeName; private String location; public int getEmployeeSeq() { return employeeSeq; } public void setEmployeeSeq(int employeeSeq) { this.employeeSeq = employeeSeq; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } }
package com.innovaciones.reporte.model; import javax.persistence.*; import java.io.Serializable; import java.util.Date; import java.util.Objects; @Entity @Table(name = "reclamos_garantias") public class ReclamoGarantia implements Serializable { private int id; private String contacto; private MotivoReclamoGarantia motivoReclamo; private SolucionReclamoGarantia solucionReclamo; private GarantiaAsignada garantiaAsignada; private Date fecha; @Id @Column(name = "id") public int getId() { return id; } public void setId(int id) { this.id = id; } @Basic @Column(name = "contacto") public String getContacto() { return contacto; } public void setContacto(String contacto) { this.contacto = contacto; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ReclamoGarantia that = (ReclamoGarantia) o; return id == that.id && Objects.equals(contacto, that.contacto); } @Override public int hashCode() { return Objects.hash(id, contacto); } @ManyToOne @JoinColumn(name = "motivo", referencedColumnName = "id") public MotivoReclamoGarantia getMotivoReclamo() { return motivoReclamo; } public void setMotivoReclamo(MotivoReclamoGarantia motivoReclamo) { this.motivoReclamo = motivoReclamo; } @ManyToOne @JoinColumn(name = "solucion", referencedColumnName = "id") public SolucionReclamoGarantia getSolucionReclamo() { return solucionReclamo; } public void setSolucionReclamo(SolucionReclamoGarantia solucionReclamo) { this.solucionReclamo = solucionReclamo; } @ManyToOne @JoinColumn(name = "garantia_asignada", referencedColumnName = "id") public GarantiaAsignada getGarantiaAsignada() { return garantiaAsignada; } public void setGarantiaAsignada(GarantiaAsignada garantiaAsignada) { this.garantiaAsignada = garantiaAsignada; } @Basic @Column(name = "fecha") public Date getFecha() { return fecha; } public void setFecha(Date fecha) { this.fecha = fecha; } }
package kata1_ade; import java.util.Calendar; import java.util.GregorianCalendar; public class Person { private final String name; private final Calendar birthdate; public Person(String name, Calendar birthdate) { this.name = name; this.birthdate = birthdate; } public String getName() { return name; } int getAge() { Calendar now = GregorianCalendar.getInstance(); return millisecondsToYears(now.getTimeInMillis() - birthdate.getTimeInMillis()); } private int millisecondsToYears(long milliseconds) { long MillisecondsPerYear = (long) (365.25*24*60*60*1000); return (int) (milliseconds/MillisecondsPerYear); } }
package com.dragonforest.demo.app_java; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import com.dragonforest.demo.app_java.util.PreUtil; public class ThirdActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_third); initView(); } private void initView() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } @Override protected void onResume() { super.onResume(); String name ="james"; String passwd = "heheheh"; name = PreUtil.INSTANCE.getString(this, PreValues.USER_NAME); passwd = PreUtil.INSTANCE.getString(this, PreValues.USER_PASSWD); TextView tv_name = findViewById(R.id.tv_name); TextView tv_passwd = findViewById(R.id.tv_passwd); tv_name.setText(name); tv_passwd.setText(passwd); } }
package gen; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.util.Random; import javax.imageio.ImageIO; public class World { /* * Contains all data for a World from the Generator class * Responsible for writing out a biome RGB image */ //FloatMaps for height and moisture values private FloatMap heightMap, moistureMap; //2-dimensional biome array of the world private Biome[][] tileMap; //World size and world seed private int size, seed; //World constructor, defined with size and seed public World(int size, int seed) { this.size = size; this.seed = seed; this.tileMap = new Biome[size][size]; } //Write out a PNG image of the biome array //String fname = file name of the outputted file //File will be written to the current working directory public void writeImage(String fName) { //Create a new image BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { // Debug any missing tiles if (tileMap[x][y] == null) { System.out.println("no biome @ (" + x + ", " + y + "), val=(" + heightMap.get(x, y) + ", " + moistureMap.get(x, y)); } //Set the RGB of the current pixel to the matching biome color image.setRGB(x, y, tileMap[x][y].getColor().getRGB()); } } try { //Write created image to the disk in the PNG format ImageIO.write(image, "png", new File(fName)); } catch (Exception e) { e.printStackTrace(); } } //Calculates out the biomes if the height and moisture FloatMaps have data public void calculateBiomes() { for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { for (Biome b : Biome.values()) { for (Range r : b.getRange()) { if (r.inRange(heightMap.get(x, y), moistureMap.get(x, y))) { this.getBiomeMap()[x][y] = b; } } } } } } //Returns height map public FloatMap getHeightMap() { return heightMap; } //Returns moisture map public FloatMap getMoistureMap() { return moistureMap; } //Returns biome map public Biome[][] getBiomeMap() { return tileMap; } //Returns the biome at a certain x and y public Biome getBiomeAt(int x, int y) { return tileMap[x][y]; } //Returns the biome at a certain point (x, y) public Biome getBiomeAt(Point p) { return tileMap[p.getX()][p.getY()]; } //Returns the world size public int getSize() { return size; } //Returns the world seed public int getSeed() { return seed; } //Set the height FloatMap public void setHeightMap(FloatMap mp) { this.heightMap = mp; } //Set the moisture FloatMap public void setMoistureMap(FloatMap mp) { this.moistureMap = mp; } }
// ASM: a very small and fast Java bytecode manipulation framework // Copyright (c) 2000-2011 INRIA, France Telecom // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holders nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. package org.springframework.asm; /** * An {@link AnnotationVisitor} that generates a corresponding 'annotation' or 'type_annotation' * structure, as defined in the Java Virtual Machine Specification (JVMS). AnnotationWriter * instances can be chained in a doubly linked list, from which Runtime[In]Visible[Type]Annotations * attributes can be generated with the {@link #putAnnotations} method. Similarly, arrays of such * lists can be used to generate Runtime[In]VisibleParameterAnnotations attributes. * * @see <a href="https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.16">JVMS * 4.7.16</a> * @see <a href="https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.20">JVMS * 4.7.20</a> * @author Eric Bruneton * @author Eugene Kuleshov */ final class AnnotationWriter extends AnnotationVisitor { /** Where the constants used in this AnnotationWriter must be stored. */ private final SymbolTable symbolTable; /** * Whether values are named or not. AnnotationWriter instances used for annotation default and * annotation arrays use unnamed values (i.e. they generate an 'element_value' structure for each * value, instead of an element_name_index followed by an element_value). */ private final boolean useNamedValues; /** * The 'annotation' or 'type_annotation' JVMS structure corresponding to the annotation values * visited so far. All the fields of these structures, except the last one - the * element_value_pairs array, must be set before this ByteVector is passed to the constructor * (num_element_value_pairs can be set to 0, it is reset to the correct value in {@link * #visitEnd()}). The element_value_pairs array is filled incrementally in the various visit() * methods. * * <p>Note: as an exception to the above rules, for AnnotationDefault attributes (which contain a * single element_value by definition), this ByteVector is initially empty when passed to the * constructor, and {@link #numElementValuePairsOffset} is set to -1. */ private final ByteVector annotation; /** * The offset in {@link #annotation} where {@link #numElementValuePairs} must be stored (or -1 for * the case of AnnotationDefault attributes). */ private final int numElementValuePairsOffset; /** The number of element value pairs visited so far. */ private int numElementValuePairs; /** * The previous AnnotationWriter. This field is used to store the list of annotations of a * Runtime[In]Visible[Type]Annotations attribute. It is unused for nested or array annotations * (annotation values of annotation type), or for AnnotationDefault attributes. */ private final AnnotationWriter previousAnnotation; /** * The next AnnotationWriter. This field is used to store the list of annotations of a * Runtime[In]Visible[Type]Annotations attribute. It is unused for nested or array annotations * (annotation values of annotation type), or for AnnotationDefault attributes. */ private AnnotationWriter nextAnnotation; // ----------------------------------------------------------------------------------------------- // Constructors and factories // ----------------------------------------------------------------------------------------------- /** * Constructs a new {@link AnnotationWriter}. * * @param symbolTable where the constants used in this AnnotationWriter must be stored. * @param useNamedValues whether values are named or not. AnnotationDefault and annotation arrays * use unnamed values. * @param annotation where the 'annotation' or 'type_annotation' JVMS structure corresponding to * the visited content must be stored. This ByteVector must already contain all the fields of * the structure except the last one (the element_value_pairs array). * @param previousAnnotation the previously visited annotation of the * Runtime[In]Visible[Type]Annotations attribute to which this annotation belongs, or * {@literal null} in other cases (e.g. nested or array annotations). */ AnnotationWriter( final SymbolTable symbolTable, final boolean useNamedValues, final ByteVector annotation, final AnnotationWriter previousAnnotation) { super(/* latest api = */ Opcodes.ASM9); this.symbolTable = symbolTable; this.useNamedValues = useNamedValues; this.annotation = annotation; // By hypothesis, num_element_value_pairs is stored in the last unsigned short of 'annotation'. this.numElementValuePairsOffset = annotation.length == 0 ? -1 : annotation.length - 2; this.previousAnnotation = previousAnnotation; if (previousAnnotation != null) { previousAnnotation.nextAnnotation = this; } } /** * Creates a new {@link AnnotationWriter} using named values. * * @param symbolTable where the constants used in this AnnotationWriter must be stored. * @param descriptor the class descriptor of the annotation class. * @param previousAnnotation the previously visited annotation of the * Runtime[In]Visible[Type]Annotations attribute to which this annotation belongs, or * {@literal null} in other cases (e.g. nested or array annotations). * @return a new {@link AnnotationWriter} for the given annotation descriptor. */ static AnnotationWriter create( final SymbolTable symbolTable, final String descriptor, final AnnotationWriter previousAnnotation) { // Create a ByteVector to hold an 'annotation' JVMS structure. // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.16. ByteVector annotation = new ByteVector(); // Write type_index and reserve space for num_element_value_pairs. annotation.putShort(symbolTable.addConstantUtf8(descriptor)).putShort(0); return new AnnotationWriter( symbolTable, /* useNamedValues = */ true, annotation, previousAnnotation); } /** * Creates a new {@link AnnotationWriter} using named values. * * @param symbolTable where the constants used in this AnnotationWriter must be stored. * @param typeRef a reference to the annotated type. The sort of this type reference must be * {@link TypeReference#CLASS_TYPE_PARAMETER}, {@link * TypeReference#CLASS_TYPE_PARAMETER_BOUND} or {@link TypeReference#CLASS_EXTENDS}. See * {@link TypeReference}. * @param typePath the path to the annotated type argument, wildcard bound, array element type, or * static inner type within 'typeRef'. May be {@literal null} if the annotation targets * 'typeRef' as a whole. * @param descriptor the class descriptor of the annotation class. * @param previousAnnotation the previously visited annotation of the * Runtime[In]Visible[Type]Annotations attribute to which this annotation belongs, or * {@literal null} in other cases (e.g. nested or array annotations). * @return a new {@link AnnotationWriter} for the given type annotation reference and descriptor. */ static AnnotationWriter create( final SymbolTable symbolTable, final int typeRef, final TypePath typePath, final String descriptor, final AnnotationWriter previousAnnotation) { // Create a ByteVector to hold a 'type_annotation' JVMS structure. // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.20. ByteVector typeAnnotation = new ByteVector(); // Write target_type, target_info, and target_path. TypeReference.putTarget(typeRef, typeAnnotation); TypePath.put(typePath, typeAnnotation); // Write type_index and reserve space for num_element_value_pairs. typeAnnotation.putShort(symbolTable.addConstantUtf8(descriptor)).putShort(0); return new AnnotationWriter( symbolTable, /* useNamedValues = */ true, typeAnnotation, previousAnnotation); } // ----------------------------------------------------------------------------------------------- // Implementation of the AnnotationVisitor abstract class // ----------------------------------------------------------------------------------------------- @Override public void visit(final String name, final Object value) { // Case of an element_value with a const_value_index, class_info_index or array_index field. // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.16.1. ++numElementValuePairs; if (useNamedValues) { annotation.putShort(symbolTable.addConstantUtf8(name)); } if (value instanceof String) { annotation.put12('s', symbolTable.addConstantUtf8((String) value)); } else if (value instanceof Byte) { annotation.put12('B', symbolTable.addConstantInteger(((Byte) value).byteValue()).index); } else if (value instanceof Boolean) { int booleanValue = ((Boolean) value).booleanValue() ? 1 : 0; annotation.put12('Z', symbolTable.addConstantInteger(booleanValue).index); } else if (value instanceof Character) { annotation.put12('C', symbolTable.addConstantInteger(((Character) value).charValue()).index); } else if (value instanceof Short) { annotation.put12('S', symbolTable.addConstantInteger(((Short) value).shortValue()).index); } else if (value instanceof Type) { annotation.put12('c', symbolTable.addConstantUtf8(((Type) value).getDescriptor())); } else if (value instanceof byte[]) { byte[] byteArray = (byte[]) value; annotation.put12('[', byteArray.length); for (byte byteValue : byteArray) { annotation.put12('B', symbolTable.addConstantInteger(byteValue).index); } } else if (value instanceof boolean[]) { boolean[] booleanArray = (boolean[]) value; annotation.put12('[', booleanArray.length); for (boolean booleanValue : booleanArray) { annotation.put12('Z', symbolTable.addConstantInteger(booleanValue ? 1 : 0).index); } } else if (value instanceof short[]) { short[] shortArray = (short[]) value; annotation.put12('[', shortArray.length); for (short shortValue : shortArray) { annotation.put12('S', symbolTable.addConstantInteger(shortValue).index); } } else if (value instanceof char[]) { char[] charArray = (char[]) value; annotation.put12('[', charArray.length); for (char charValue : charArray) { annotation.put12('C', symbolTable.addConstantInteger(charValue).index); } } else if (value instanceof int[]) { int[] intArray = (int[]) value; annotation.put12('[', intArray.length); for (int intValue : intArray) { annotation.put12('I', symbolTable.addConstantInteger(intValue).index); } } else if (value instanceof long[]) { long[] longArray = (long[]) value; annotation.put12('[', longArray.length); for (long longValue : longArray) { annotation.put12('J', symbolTable.addConstantLong(longValue).index); } } else if (value instanceof float[]) { float[] floatArray = (float[]) value; annotation.put12('[', floatArray.length); for (float floatValue : floatArray) { annotation.put12('F', symbolTable.addConstantFloat(floatValue).index); } } else if (value instanceof double[]) { double[] doubleArray = (double[]) value; annotation.put12('[', doubleArray.length); for (double doubleValue : doubleArray) { annotation.put12('D', symbolTable.addConstantDouble(doubleValue).index); } } else { Symbol symbol = symbolTable.addConstant(value); annotation.put12(".s.IFJDCS".charAt(symbol.tag), symbol.index); } } @Override public void visitEnum(final String name, final String descriptor, final String value) { // Case of an element_value with an enum_const_value field. // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.16.1. ++numElementValuePairs; if (useNamedValues) { annotation.putShort(symbolTable.addConstantUtf8(name)); } annotation .put12('e', symbolTable.addConstantUtf8(descriptor)) .putShort(symbolTable.addConstantUtf8(value)); } @Override public AnnotationVisitor visitAnnotation(final String name, final String descriptor) { // Case of an element_value with an annotation_value field. // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.16.1. ++numElementValuePairs; if (useNamedValues) { annotation.putShort(symbolTable.addConstantUtf8(name)); } // Write tag and type_index, and reserve 2 bytes for num_element_value_pairs. annotation.put12('@', symbolTable.addConstantUtf8(descriptor)).putShort(0); return new AnnotationWriter(symbolTable, /* useNamedValues = */ true, annotation, null); } @Override public AnnotationVisitor visitArray(final String name) { // Case of an element_value with an array_value field. // https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.16.1 ++numElementValuePairs; if (useNamedValues) { annotation.putShort(symbolTable.addConstantUtf8(name)); } // Write tag, and reserve 2 bytes for num_values. Here we take advantage of the fact that the // end of an element_value of array type is similar to the end of an 'annotation' structure: an // unsigned short num_values followed by num_values element_value, versus an unsigned short // num_element_value_pairs, followed by num_element_value_pairs { element_name_index, // element_value } tuples. This allows us to use an AnnotationWriter with unnamed values to // visit the array elements. Its num_element_value_pairs will correspond to the number of array // elements and will be stored in what is in fact num_values. annotation.put12('[', 0); return new AnnotationWriter(symbolTable, /* useNamedValues = */ false, annotation, null); } @Override public void visitEnd() { if (numElementValuePairsOffset != -1) { byte[] data = annotation.data; data[numElementValuePairsOffset] = (byte) (numElementValuePairs >>> 8); data[numElementValuePairsOffset + 1] = (byte) numElementValuePairs; } } // ----------------------------------------------------------------------------------------------- // Utility methods // ----------------------------------------------------------------------------------------------- /** * Returns the size of a Runtime[In]Visible[Type]Annotations attribute containing this annotation * and all its <i>predecessors</i> (see {@link #previousAnnotation}. Also adds the attribute name * to the constant pool of the class (if not null). * * @param attributeName one of "Runtime[In]Visible[Type]Annotations", or {@literal null}. * @return the size in bytes of a Runtime[In]Visible[Type]Annotations attribute containing this * annotation and all its predecessors. This includes the size of the attribute_name_index and * attribute_length fields. */ int computeAnnotationsSize(final String attributeName) { if (attributeName != null) { symbolTable.addConstantUtf8(attributeName); } // The attribute_name_index, attribute_length and num_annotations fields use 8 bytes. int attributeSize = 8; AnnotationWriter annotationWriter = this; while (annotationWriter != null) { attributeSize += annotationWriter.annotation.length; annotationWriter = annotationWriter.previousAnnotation; } return attributeSize; } /** * Returns the size of the Runtime[In]Visible[Type]Annotations attributes containing the given * annotations and all their <i>predecessors</i> (see {@link #previousAnnotation}. Also adds the * attribute names to the constant pool of the class (if not null). * * @param lastRuntimeVisibleAnnotation The last runtime visible annotation of a field, method or * class. The previous ones can be accessed with the {@link #previousAnnotation} field. May be * {@literal null}. * @param lastRuntimeInvisibleAnnotation The last runtime invisible annotation of this a field, * method or class. The previous ones can be accessed with the {@link #previousAnnotation} * field. May be {@literal null}. * @param lastRuntimeVisibleTypeAnnotation The last runtime visible type annotation of this a * field, method or class. The previous ones can be accessed with the {@link * #previousAnnotation} field. May be {@literal null}. * @param lastRuntimeInvisibleTypeAnnotation The last runtime invisible type annotation of a * field, method or class field. The previous ones can be accessed with the {@link * #previousAnnotation} field. May be {@literal null}. * @return the size in bytes of a Runtime[In]Visible[Type]Annotations attribute containing the * given annotations and all their predecessors. This includes the size of the * attribute_name_index and attribute_length fields. */ static int computeAnnotationsSize( final AnnotationWriter lastRuntimeVisibleAnnotation, final AnnotationWriter lastRuntimeInvisibleAnnotation, final AnnotationWriter lastRuntimeVisibleTypeAnnotation, final AnnotationWriter lastRuntimeInvisibleTypeAnnotation) { int size = 0; if (lastRuntimeVisibleAnnotation != null) { size += lastRuntimeVisibleAnnotation.computeAnnotationsSize( Constants.RUNTIME_VISIBLE_ANNOTATIONS); } if (lastRuntimeInvisibleAnnotation != null) { size += lastRuntimeInvisibleAnnotation.computeAnnotationsSize( Constants.RUNTIME_INVISIBLE_ANNOTATIONS); } if (lastRuntimeVisibleTypeAnnotation != null) { size += lastRuntimeVisibleTypeAnnotation.computeAnnotationsSize( Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS); } if (lastRuntimeInvisibleTypeAnnotation != null) { size += lastRuntimeInvisibleTypeAnnotation.computeAnnotationsSize( Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS); } return size; } /** * Puts a Runtime[In]Visible[Type]Annotations attribute containing this annotations and all its * <i>predecessors</i> (see {@link #previousAnnotation} in the given ByteVector. Annotations are * put in the same order they have been visited. * * @param attributeNameIndex the constant pool index of the attribute name (one of * "Runtime[In]Visible[Type]Annotations"). * @param output where the attribute must be put. */ void putAnnotations(final int attributeNameIndex, final ByteVector output) { int attributeLength = 2; // For num_annotations. int numAnnotations = 0; AnnotationWriter annotationWriter = this; AnnotationWriter firstAnnotation = null; while (annotationWriter != null) { // In case the user forgot to call visitEnd(). annotationWriter.visitEnd(); attributeLength += annotationWriter.annotation.length; numAnnotations++; firstAnnotation = annotationWriter; annotationWriter = annotationWriter.previousAnnotation; } output.putShort(attributeNameIndex); output.putInt(attributeLength); output.putShort(numAnnotations); annotationWriter = firstAnnotation; while (annotationWriter != null) { output.putByteArray(annotationWriter.annotation.data, 0, annotationWriter.annotation.length); annotationWriter = annotationWriter.nextAnnotation; } } /** * Puts the Runtime[In]Visible[Type]Annotations attributes containing the given annotations and * all their <i>predecessors</i> (see {@link #previousAnnotation} in the given ByteVector. * Annotations are put in the same order they have been visited. * * @param symbolTable where the constants used in the AnnotationWriter instances are stored. * @param lastRuntimeVisibleAnnotation The last runtime visible annotation of a field, method or * class. The previous ones can be accessed with the {@link #previousAnnotation} field. May be * {@literal null}. * @param lastRuntimeInvisibleAnnotation The last runtime invisible annotation of this a field, * method or class. The previous ones can be accessed with the {@link #previousAnnotation} * field. May be {@literal null}. * @param lastRuntimeVisibleTypeAnnotation The last runtime visible type annotation of this a * field, method or class. The previous ones can be accessed with the {@link * #previousAnnotation} field. May be {@literal null}. * @param lastRuntimeInvisibleTypeAnnotation The last runtime invisible type annotation of a * field, method or class field. The previous ones can be accessed with the {@link * #previousAnnotation} field. May be {@literal null}. * @param output where the attributes must be put. */ static void putAnnotations( final SymbolTable symbolTable, final AnnotationWriter lastRuntimeVisibleAnnotation, final AnnotationWriter lastRuntimeInvisibleAnnotation, final AnnotationWriter lastRuntimeVisibleTypeAnnotation, final AnnotationWriter lastRuntimeInvisibleTypeAnnotation, final ByteVector output) { if (lastRuntimeVisibleAnnotation != null) { lastRuntimeVisibleAnnotation.putAnnotations( symbolTable.addConstantUtf8(Constants.RUNTIME_VISIBLE_ANNOTATIONS), output); } if (lastRuntimeInvisibleAnnotation != null) { lastRuntimeInvisibleAnnotation.putAnnotations( symbolTable.addConstantUtf8(Constants.RUNTIME_INVISIBLE_ANNOTATIONS), output); } if (lastRuntimeVisibleTypeAnnotation != null) { lastRuntimeVisibleTypeAnnotation.putAnnotations( symbolTable.addConstantUtf8(Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS), output); } if (lastRuntimeInvisibleTypeAnnotation != null) { lastRuntimeInvisibleTypeAnnotation.putAnnotations( symbolTable.addConstantUtf8(Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS), output); } } /** * Returns the size of a Runtime[In]VisibleParameterAnnotations attribute containing all the * annotation lists from the given AnnotationWriter sub-array. Also adds the attribute name to the * constant pool of the class. * * @param attributeName one of "Runtime[In]VisibleParameterAnnotations". * @param annotationWriters an array of AnnotationWriter lists (designated by their <i>last</i> * element). * @param annotableParameterCount the number of elements in annotationWriters to take into account * (elements [0..annotableParameterCount[ are taken into account). * @return the size in bytes of a Runtime[In]VisibleParameterAnnotations attribute corresponding * to the given sub-array of AnnotationWriter lists. This includes the size of the * attribute_name_index and attribute_length fields. */ static int computeParameterAnnotationsSize( final String attributeName, final AnnotationWriter[] annotationWriters, final int annotableParameterCount) { // Note: attributeName is added to the constant pool by the call to computeAnnotationsSize // below. This assumes that there is at least one non-null element in the annotationWriters // sub-array (which is ensured by the lazy instantiation of this array in MethodWriter). // The attribute_name_index, attribute_length and num_parameters fields use 7 bytes, and each // element of the parameter_annotations array uses 2 bytes for its num_annotations field. int attributeSize = 7 + 2 * annotableParameterCount; for (int i = 0; i < annotableParameterCount; ++i) { AnnotationWriter annotationWriter = annotationWriters[i]; attributeSize += annotationWriter == null ? 0 : annotationWriter.computeAnnotationsSize(attributeName) - 8; } return attributeSize; } /** * Puts a Runtime[In]VisibleParameterAnnotations attribute containing all the annotation lists * from the given AnnotationWriter sub-array in the given ByteVector. * * @param attributeNameIndex constant pool index of the attribute name (one of * Runtime[In]VisibleParameterAnnotations). * @param annotationWriters an array of AnnotationWriter lists (designated by their <i>last</i> * element). * @param annotableParameterCount the number of elements in annotationWriters to put (elements * [0..annotableParameterCount[ are put). * @param output where the attribute must be put. */ static void putParameterAnnotations( final int attributeNameIndex, final AnnotationWriter[] annotationWriters, final int annotableParameterCount, final ByteVector output) { // The num_parameters field uses 1 byte, and each element of the parameter_annotations array // uses 2 bytes for its num_annotations field. int attributeLength = 1 + 2 * annotableParameterCount; for (int i = 0; i < annotableParameterCount; ++i) { AnnotationWriter annotationWriter = annotationWriters[i]; attributeLength += annotationWriter == null ? 0 : annotationWriter.computeAnnotationsSize(null) - 8; } output.putShort(attributeNameIndex); output.putInt(attributeLength); output.putByte(annotableParameterCount); for (int i = 0; i < annotableParameterCount; ++i) { AnnotationWriter annotationWriter = annotationWriters[i]; AnnotationWriter firstAnnotation = null; int numAnnotations = 0; while (annotationWriter != null) { // In case user the forgot to call visitEnd(). annotationWriter.visitEnd(); numAnnotations++; firstAnnotation = annotationWriter; annotationWriter = annotationWriter.previousAnnotation; } output.putShort(numAnnotations); annotationWriter = firstAnnotation; while (annotationWriter != null) { output.putByteArray( annotationWriter.annotation.data, 0, annotationWriter.annotation.length); annotationWriter = annotationWriter.nextAnnotation; } } } }
package kr.or.ddit.vo; public class MemberRateVO { private String mem_id; private String professional; private String communication; private String positiveness; private String satisfaction; private String compliance; private String professional_bef; private String communication_bef; private String positiveness_bef; private String satisfaction_bef; private String compliance_bef; public String getMem_id() { return mem_id; } public void setMem_id(String mem_id) { this.mem_id = mem_id; } public String getProfessional() { return professional; } public void setProfessional(String professional) { this.professional = professional; } public String getCommunication() { return communication; } public void setCommunication(String communication) { this.communication = communication; } public String getPositiveness() { return positiveness; } public void setPositiveness(String positiveness) { this.positiveness = positiveness; } public String getSatisfaction() { return satisfaction; } public void setSatisfaction(String satisfaction) { this.satisfaction = satisfaction; } public String getCompliance() { return compliance; } public void setCompliance(String compliance) { this.compliance = compliance; } public String getProfessional_bef() { return professional_bef; } public void setProfessional_bef(String professional_bef) { this.professional_bef = professional_bef; } public String getCommunication_bef() { return communication_bef; } public void setCommunication_bef(String communication_bef) { this.communication_bef = communication_bef; } public String getPositiveness_bef() { return positiveness_bef; } public void setPositiveness_bef(String positiveness_bef) { this.positiveness_bef = positiveness_bef; } public String getSatisfaction_bef() { return satisfaction_bef; } public void setSatisfaction_bef(String satisfaction_bef) { this.satisfaction_bef = satisfaction_bef; } public String getCompliance_bef() { return compliance_bef; } public void setCompliance_bef(String compliance_bef) { this.compliance_bef = compliance_bef; } }
/* * Copyright 2021 Vincenzo De Notaris * * 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.vdenotaris.spring.boot.security.saml.web; import org.springframework.mock.web.MockHttpSession; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.security.providers.ExpiringUsernameAuthenticationToken; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; import java.util.Collections; import java.util.List; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class CommonTestSupport { public static final String USER_NAME = "UserName"; public static final String USER_PASSWORD = "<abc123>"; public static final String USER_ROLE = "ROLE_USER"; public static final String ANONYMOUS_USER_KEY = "UserKey"; public static final String ANONYMOUS_USER_PRINCIPAL = "UserPrincipal"; public static final List<GrantedAuthority> AUTHORITIES = Collections.singletonList(new SimpleGrantedAuthority(USER_ROLE)); public static final User USER_DETAILS = new User(USER_NAME, USER_PASSWORD, AUTHORITIES); public MockHttpSession mockHttpSession(boolean secured) { MockHttpSession mockSession = new MockHttpSession(); SecurityContext mockSecurityContext = mock(SecurityContext.class); if (secured) { ExpiringUsernameAuthenticationToken principal = new ExpiringUsernameAuthenticationToken(null, USER_DETAILS, USER_NAME, AUTHORITIES); principal.setDetails(USER_DETAILS); when(mockSecurityContext.getAuthentication()).thenReturn(principal); } SecurityContextHolder.setContext(mockSecurityContext); mockSession.setAttribute( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, mockSecurityContext); return mockSession; } public MockHttpSession mockAnonymousHttpSession() { MockHttpSession mockSession = new MockHttpSession(); SecurityContext mockSecurityContext = mock(SecurityContext.class); AnonymousAuthenticationToken principal = new AnonymousAuthenticationToken( ANONYMOUS_USER_KEY, ANONYMOUS_USER_PRINCIPAL, AUTHORITIES); when(mockSecurityContext.getAuthentication()).thenReturn(principal); SecurityContextHolder.setContext(mockSecurityContext); mockSession.setAttribute( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, mockSecurityContext); return mockSession; } }
package cn.edu.wust.common.constant; /** * @Author: huhan * @Date: 2020/1/17 11:17 * @Description * @Version 1.0 */ public class OpType { public OpType(){} public static final String SELECT="查询"; public static final String INSERT="插入"; public static final String UPDATE="更新"; public static final String DELETE="删除"; }
package com.metoo.foundation.domain; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import com.iskyshop.core.domain.IdEntity; import com.metoo.core.constant.Globals; /** * <p> * Title: EnoughFree.java * </p> * * <p> * Description: 满包邮实体类--满包邮为店铺活动 * </p> * * * <p> * Company: metoo * </p> * * @author hk * * @data 2019-11-18 * */ @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @Entity @Table(name = Globals.DEFAULT_TABLE_SUFFIX + "enough_free") public class EnoughFree extends IdEntity{ private String eftitle;//活动标题 @Temporal(TemporalType.DATE) private Date efbegin_time;//活动开始时间 @Temporal(TemporalType.DATE) private Date efend_time;//活动结束时间 private int efsequence;//活动序号 @Column(columnDefinition = "int default 0") private int efstatus;//审核状态默认为0待审核 10为 审核通过 -10为审核未通过 20为已结束。5为提交审核,此时商家不能再修改 @Column(columnDefinition = "LongText") private String failed_reason;//请求失败的原因 @Column(columnDefinition = "LongText") private String efcontent;//活动说明 private String eftag;//活动标识 private String store_id;// 对应的店铺id private String store_name;// 对应的店铺名字 private int ef_type;// 满包邮类型,0为自营,1为商家 @Column(columnDefinition = "LongText") private String efgoods_ids_json;// 活动商品json @Column(precision = 12, scale = 2) private BigDecimal condition_amount;//满足满包邮条件金额 需要大于此金额才可满足满就送条件 private int ef_frequency;//满包邮价格调整次数 public String getEfgoods_ids_json() { return efgoods_ids_json; } public void setEfgoods_ids_json(String efgoods_ids_json) { this.efgoods_ids_json = efgoods_ids_json; } public int getEf_frequency() { return ef_frequency; } public void setEf_frequency(int ef_frequency) { this.ef_frequency = ef_frequency; } public String getEftitle() { return eftitle; } public void setEftitle(String eftitle) { this.eftitle = eftitle; } public Date getEfbegin_time() { return efbegin_time; } public void setEfbegin_time(Date efbegin_time) { this.efbegin_time = efbegin_time; } public Date getEfend_time() { return efend_time; } public void setEfend_time(Date efend_time) { this.efend_time = efend_time; } public int getEfsequence() { return efsequence; } public void setEfsequence(int efsequence) { this.efsequence = efsequence; } public int getEfstatus() { return efstatus; } public void setEfstatus(int efstatus) { this.efstatus = efstatus; } public String getFailed_reason() { return failed_reason; } public void setFailed_reason(String failed_reason) { this.failed_reason = failed_reason; } public String getEfcontent() { return efcontent; } public void setEfcontent(String efcontent) { this.efcontent = efcontent; } public String getEftag() { return eftag; } public void setEftag(String eftag) { this.eftag = eftag; } public String getStore_id() { return store_id; } public void setStore_id(String store_id) { this.store_id = store_id; } public String getStore_name() { return store_name; } public void setStore_name(String store_name) { this.store_name = store_name; } public int getEf_type() { return ef_type; } public void setEf_type(int ef_type) { this.ef_type = ef_type; } public BigDecimal getCondition_amount() { return condition_amount; } public void setCondition_amount(BigDecimal condition_amount) { this.condition_amount = condition_amount; } }
package com.java.hibernate.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.MapsId; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name = "t_imagecontent") public class ImageContent { @Id private int id; @OneToOne @Column(name = "image_id") @MapsId private Image image; @Column(name = "t_content") @Lob private byte[] content; public int getId() { return id; } public void setId(int id) { this.id = id; } public Image getImage() { return image; } public void setImage(Image image) { this.image = image; } public byte[] getContent() { return content; } public void setContent(byte[] content) { this.content = content; } }
package com.fanseptember.define; public enum AttitudeType { AGREE, DISAGREE; }
/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2010 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ package ti.modules.titanium.stream; import java.io.IOException; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollModule; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.annotations.Kroll; import org.appcelerator.titanium.TiBlob; import org.appcelerator.titanium.TiContext; import org.appcelerator.titanium.io.TiStream; import org.appcelerator.titanium.kroll.KrollCallback; import org.appcelerator.titanium.util.TiConfig; import ti.modules.titanium.BufferProxy; import ti.modules.titanium.TitaniumModule; @Kroll.module(parentModule=TitaniumModule.class) public class StreamModule extends KrollModule { @Kroll.constant public static final int MODE_READ = 0; @Kroll.constant public static final int MODE_WRITE = 1; @Kroll.constant public static final int MODE_APPEND = 2; private static final String LCAT = "StreamModule"; private static final boolean DBG = TiConfig.LOGD; public StreamModule(TiContext tiContext) { super(tiContext); } @Kroll.method public Object createStream(KrollDict params) //public Object createStream(Object container) { Object source = params.get("source"); Object rawMode = params.get("mode"); if (!(rawMode instanceof Double)) { throw new IllegalArgumentException("Unable to create stream, invalid mode"); } int mode = ((Double)rawMode).intValue(); if (source instanceof TiBlob) { if(mode != MODE_READ) { throw new IllegalArgumentException("Unable to create a blob stream in a mode other than read"); } return new BlobStreamProxy((TiBlob) source); } else if(source instanceof BufferProxy) { return new BufferStreamProxy((BufferProxy) source, mode); } else { throw new IllegalArgumentException("Unable to create a stream for the specified argument"); } } @Kroll.method //public void read(TiStream sourceStream, BufferProxy buffer, KrollCallback resultsCallback) //public void read(TiStream sourceStream, BufferProxy buffer, int offset, int length, KrollCallback resultsCallback) public void read(Object args[]) { TiStream sourceStream = null; BufferProxy buffer = null; int offset = 0; int length = 0; KrollCallback resultsCallback = null; if(args.length == 3 || args.length == 5) { if(args[0] instanceof TiStream) { sourceStream = (TiStream) args[0]; } else { throw new IllegalArgumentException("Invalid stream argument"); } if(args[1] instanceof BufferProxy) { buffer = (BufferProxy) args[1]; length = buffer.getLength(); } else { throw new IllegalArgumentException("Invalid buffer argument"); } if(args.length == 3) { if(args[2] instanceof KrollCallback) { resultsCallback = (KrollCallback) args[2]; } else { throw new IllegalArgumentException("Invalid callback argument"); } } else if(args.length == 5) { if(args[2] instanceof Double) { offset = ((Double)args[2]).intValue(); } else{ throw new IllegalArgumentException("Invalid offset argument"); } if(args[3] instanceof Double) { length = ((Double)args[3]).intValue(); } else { throw new IllegalArgumentException("Invalid length argument"); } if(args[4] instanceof KrollCallback) { resultsCallback = (KrollCallback) args[4]; } else { throw new IllegalArgumentException("Invalid callback argument"); } } } else { throw new IllegalArgumentException("Invalid number of arguments"); } final TiStream fsourceStream = sourceStream; final BufferProxy fbuffer = buffer; final int foffset = offset; final int flength = length; final KrollCallback fresultsCallback = resultsCallback; new Thread(new Runnable() { public void run() { int bytesRead = -1; int errorState = 0; String errorDescription = ""; try { bytesRead = fsourceStream.read(new Object[] {fbuffer, foffset, flength}); } catch (IOException e) { e.printStackTrace(); errorState = 1; errorDescription = e.getMessage(); } fresultsCallback.callAsync(buildRWCallbackArgs(fsourceStream, bytesRead, errorState, errorDescription)); } }) {}.start(); } @Kroll.method //public BufferProxy readAll(TiStream sourceStream) throws IOException //public void readAll(final TiStream sourceStream, final BufferProxy buffer, final KrollCallback resultsCallback) public Object readAll(Object args[]) throws IOException { TiStream sourceStream = null; BufferProxy bufferArg = null; KrollCallback resultsCallback = null; if(args.length == 1 || args.length == 3) { if(args[0] instanceof TiStream) { sourceStream = (TiStream) args[0]; } else { throw new IllegalArgumentException("Invalid stream argument"); } if(args.length == 3) { if(args[1] instanceof BufferProxy) { bufferArg = (BufferProxy) args[1]; } else { throw new IllegalArgumentException("Invalid buffer argument"); } if(args[2] instanceof KrollCallback) { resultsCallback = (KrollCallback) args[2]; } else { throw new IllegalArgumentException("Invalid callback argument"); } } } else { throw new IllegalArgumentException("Invalid number of arguments"); } if (args.length == 1) { BufferProxy buffer = new BufferProxy(context, 1024); int offset = 0; readAll(sourceStream, buffer, offset); return buffer; } else { final TiStream fsourceStream = sourceStream; final BufferProxy fbuffer = bufferArg; final KrollCallback fresultsCallback = resultsCallback; new Thread(new Runnable() { public void run() { int offset = 0; int errorState = 0; String errorDescription = ""; if(fbuffer.getLength() < 1024) { fbuffer.resize(1024); } try { readAll(fsourceStream, fbuffer, offset); } catch (IOException e) { errorState = 1; errorDescription = e.getMessage(); } fresultsCallback.callAsync(buildRWCallbackArgs(fsourceStream, fbuffer.getLength(), errorState, errorDescription)); } }) {}.start(); return KrollProxy.UNDEFINED; } } private void readAll(TiStream sourceStream, BufferProxy buffer, int offset) throws IOException { int totalBytesRead = 0; while(true) { int bytesRead = sourceStream.read(new Object[] {buffer, offset, 1024}); if(bytesRead == -1) { break; } totalBytesRead += bytesRead; buffer.resize(1024 + totalBytesRead); offset += bytesRead; } buffer.resize(totalBytesRead); } @Kroll.method //public void write(TiStream outputStream, BufferProxy buffer, KrollCallback resultsCallback) //public void write(TiStream outputStream, BufferProxy buffer, int offset, int length, KrollCallback resultsCallback) public void write(Object args[]) { TiStream outputStream = null; BufferProxy buffer = null; int offset = 0; int length = 0; KrollCallback resultsCallback = null; if(args.length == 3 || args.length == 5) { if(args[0] instanceof TiStream) { outputStream = (TiStream) args[0]; } else { throw new IllegalArgumentException("Invalid stream argument"); } if(args[1] instanceof BufferProxy) { buffer = (BufferProxy) args[1]; length = buffer.getLength(); } else { throw new IllegalArgumentException("Invalid buffer argument"); } if(args.length == 3) { if(args[2] instanceof KrollCallback) { resultsCallback = (KrollCallback) args[2]; } else { throw new IllegalArgumentException("Invalid callback argument"); } } else if(args.length == 5) { if(args[2] instanceof Double) { offset = ((Double)args[2]).intValue(); } else{ throw new IllegalArgumentException("Invalid offset argument"); } if(args[3] instanceof Double) { length = ((Double)args[3]).intValue(); } else { throw new IllegalArgumentException("Invalid length argument"); } if(args[4] instanceof KrollCallback) { resultsCallback = (KrollCallback) args[4]; } else { throw new IllegalArgumentException("Invalid callback argument"); } } } else { throw new IllegalArgumentException("Invalid number of arguments"); } final TiStream foutputStream = outputStream; final BufferProxy fbuffer = buffer; final int foffset = offset; final int flength = length; final KrollCallback fresultsCallback = resultsCallback; new Thread( new Runnable() { public void run() { int bytesWritten = -1; int errorState = 0; String errorDescription = ""; try { bytesWritten = foutputStream.write(new Object[] {fbuffer, foffset, flength}); } catch (IOException e) { e.printStackTrace(); errorState = 1; errorDescription = e.getMessage(); } fresultsCallback.callAsync(buildRWCallbackArgs(foutputStream, bytesWritten, errorState, errorDescription)); } } ) {}.start(); } @Kroll.method //public void writeStream(TiStream inputStream, TiStream outputStream, int maxChunkSize) throws IOException //public void writeStream(TiStream inputStream, TiStream outputStream, int maxChunkSize, KrollCallback resultsCallback) public int writeStream(Object args[]) throws IOException { TiStream inputStream = null; TiStream outputStream = null; int maxChunkSize = 0; KrollCallback resultsCallback = null; if(args.length == 3 || args.length == 4) { if(args[0] instanceof TiStream) { inputStream = (TiStream) args[0]; } else { throw new IllegalArgumentException("Invalid input stream argument"); } if(args[1] instanceof TiStream) { outputStream = (TiStream) args[1]; } else { throw new IllegalArgumentException("Invalid output stream argument"); } if(args[2] instanceof Double) { maxChunkSize = ((Double)args[2]).intValue(); } else{ throw new IllegalArgumentException("Invalid max chunk size argument"); } if(args.length == 4) { if(args[3] instanceof KrollCallback) { resultsCallback = (KrollCallback) args[3]; } else { throw new IllegalArgumentException("Invalid callback argument"); } } } else { throw new IllegalArgumentException("Invalid number of arguments"); } if (args.length == 3) { return writeStream(inputStream, outputStream, maxChunkSize); } else { final TiStream finputStream = inputStream; final TiStream foutputStream = outputStream; final int fmaxChunkSize = maxChunkSize; final KrollCallback fresultsCallback = resultsCallback; new Thread(new Runnable() { public void run() { int totalBytesWritten = 0; int errorState = 0; String errorDescription = ""; try { totalBytesWritten = writeStream(finputStream, foutputStream, fmaxChunkSize); } catch (IOException e) { errorState = 1; errorDescription = e.getMessage(); } fresultsCallback.callAsync(buildWriteStreamCallbackArgs(finputStream, foutputStream, totalBytesWritten, errorState, errorDescription)); } }) {}.start(); return 0; } } private int writeStream(TiStream inputStream, TiStream outputStream, int maxChunkSize) throws IOException { BufferProxy buffer = new BufferProxy(getTiContext(), maxChunkSize); int totalBytesWritten = 0; while(true) { int bytesRead = inputStream.read(new Object[] {buffer, 0, maxChunkSize}); if(bytesRead == -1) { break; } int bytesWritten = outputStream.write(new Object[] {buffer, 0, bytesRead}); totalBytesWritten += bytesWritten; buffer.clear(); } return totalBytesWritten; } @Kroll.method //public void pump(TiStream inputStream, KrollCallback handler, int maxChunkSize) //public void pump(TiStream inputStream, KrollCallback handler, int maxChunkSize, boolean isAsync) public void pump(Object args[]) { TiStream inputStream = null; KrollCallback handler = null; int maxChunkSize = 0; boolean isAsync = false; if(args.length == 3 || args.length == 4) { if(args[0] instanceof TiStream) { inputStream = (TiStream) args[0]; } else { throw new IllegalArgumentException("Invalid stream argument"); } if(args[1] instanceof KrollCallback) { handler = (KrollCallback) args[1]; } else { throw new IllegalArgumentException("Invalid handler argument"); } if(args[2] instanceof Double) { maxChunkSize = ((Double)args[2]).intValue(); } else{ throw new IllegalArgumentException("Invalid max chunk size argument"); } if(args.length == 4) { if(args[3] instanceof Boolean) { isAsync = ((Boolean) args[3]).booleanValue(); } else { throw new IllegalArgumentException("Invalid async flag argument"); } } } else { throw new IllegalArgumentException("Invalid number of arguments"); } if(isAsync) { final TiStream finputStream = inputStream; final KrollCallback fhandler = handler; final int fmaxChunkSize = maxChunkSize; new Thread( new Runnable() { public void run() { pump(finputStream, fhandler, fmaxChunkSize); } } ) {}.start(); } else { pump(inputStream, handler, maxChunkSize); } } private void pump(TiStream inputStream, KrollCallback handler, int maxChunkSize) { int totalBytesRead = 0; int errorState = 0; String errorDescription = ""; try { while(true) { BufferProxy buffer = new BufferProxy(getTiContext(), maxChunkSize); int bytesRead = inputStream.read(new Object[] {buffer, 0, maxChunkSize}); if(bytesRead != -1) { totalBytesRead += bytesRead; } if (bytesRead != buffer.getLength()) { if (bytesRead == -1) { buffer.resize(0); } else { buffer.resize(bytesRead); } } handler.callSync(buildPumpCallbackArgs(inputStream, buffer, bytesRead, totalBytesRead, errorState, errorDescription)); buffer = null; if (bytesRead == -1) { break; } } } catch (IOException e) { errorState = 1; errorDescription = e.getMessage(); handler.callSync(buildPumpCallbackArgs(inputStream, new BufferProxy(getTiContext()), 0, totalBytesRead, errorState, errorDescription)); } } private KrollDict buildRWCallbackArgs(TiStream sourceStream, int bytesProcessed, int errorState, String errorDescription) { KrollDict callbackArgs = new KrollDict(); callbackArgs.put("source", sourceStream); callbackArgs.put("bytesProcessed", bytesProcessed); callbackArgs.put("errorState", errorState); callbackArgs.put("errorDescription", errorDescription); return callbackArgs; } private KrollDict buildWriteStreamCallbackArgs(TiStream fromStream, TiStream toStream, int bytesProcessed, int errorState, String errorDescription) { KrollDict callbackArgs = new KrollDict(); callbackArgs.put("fromStream", fromStream); callbackArgs.put("toStream", toStream); callbackArgs.put("bytesProcessed", bytesProcessed); callbackArgs.put("errorState", errorState); callbackArgs.put("errorDescription", errorDescription); return callbackArgs; } private KrollDict buildPumpCallbackArgs(TiStream sourceStream, BufferProxy buffer, int bytesProcessed, int totalBytesProcessed, int errorState, String errorDescription) { KrollDict callbackArgs = new KrollDict(); callbackArgs.put("source", sourceStream); callbackArgs.put("buffer", buffer); callbackArgs.put("bytesProcessed", bytesProcessed); callbackArgs.put("totalBytesProcessed", totalBytesProcessed); callbackArgs.put("errorState", errorState); callbackArgs.put("errorDescription", errorDescription); return callbackArgs; } }
package dao; import model.bean.style.FontColor; import org.hibernate.Session; /** * * @author Andriy */ public class FontColorDAO extends DAO { public FontColorDAO(Session session) { super(session); } public FontColor insert(FontColor fontColor) { session.save(fontColor); return fontColor; } }
package jp.ne.test.dbconnector.dbutility; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Properties; import jp.ne.test.dbconnector.define.Const; public class DBPostgresSql extends DB { public DBPostgresSql() throws DBException { InitConnection(); } private String serverName; private String portNo; private String dbName; private String userName; private String password; private Connection con; private void InitConnection() throws DBException { Properties properties = new Properties(); String fileName = "DBConnection.properties"; try { InputStream inputStream = new FileInputStream(fileName); properties.load(inputStream); inputStream.close(); serverName = properties.getProperty(Const.PSQL_SERVER_NAME); portNo = properties.getProperty(Const.PSQL_PORT_NO); dbName = properties.getProperty(Const.PSQL_DB_NAME); userName = properties.getProperty(Const.PSQL_USER_NAME); password = properties.getProperty(Const.PSQL_PASSWORD); if (con != null) { con.close(); con = null; } con = DriverManager.getConnection("jdbc:postgresql://" + serverName + ":" + portNo + "/" + dbName, userName, password); } catch (IOException e) { throw new DBException(e); } catch (SQLException e) { throw new DBException(e); } } @Override public List<HashMap<String, Object>> selectSQL(String sql) throws DBException { List<HashMap<String, Object>> ret = new ArrayList<HashMap<String, Object>>(); try { Statement stmt = (Statement) con.createStatement(); ResultSet rs = stmt.executeQuery(sql); ResultSetMetaData rsmd = rs.getMetaData(); while (rs.next()) { HashMap<String, Object> row = new HashMap<String, Object>(); for (int i = 1; i <= rsmd.getColumnCount(); i++) { row.put(rsmd.getColumnLabel(i), rs.getObject(i)); } ret.add(row); } } catch (SQLException e) { throw new DBException(e); } return ret; } @Override public int startTransaction() { int ret; try { con.setAutoCommit(false); ret = TRANSACTION_SUCCESS; } catch (SQLException e) { e.printStackTrace(); ret = TRANSACTION_FAILUER; } return ret; } @Override public int commit() { int ret; try { con.commit(); ret = TRANSACTION_SUCCESS; } catch (SQLException e) { e.printStackTrace(); ret = TRANSACTION_FAILUER; } finally { try { con.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } } return ret; } @Override public int rollback() { int ret; try { con.rollback(); ret = TRANSACTION_SUCCESS; } catch (SQLException e) { e.printStackTrace(); ret = TRANSACTION_FAILUER; } finally { try { con.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } } return ret; } @Override public int updateSQL(String sql) throws DBException { int ret = 0; try { Statement stmt = (Statement) con.createStatement(); ret = stmt.executeUpdate(sql); } catch (SQLException e) { throw new DBException(e); } return ret; } @Override public void close() throws DBException { try { if (con != null) { con.close(); con = null; } } catch (SQLException e) { throw new DBException(e); } } }
/* * 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.dthebus.gymweb.presentation.rest; import com.dthebus.gymweb.domain.members.LimitedMember; import com.dthebus.gymweb.services.TotalLimitedMembersService; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; 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; /** * * @author darren */ @Controller @RequestMapping(value = "api/limited") public class LimitedMemberController { @Autowired TotalLimitedMembersService lms; @RequestMapping(value="all", method = RequestMethod.GET) @ResponseBody public List<LimitedMember> getall(){ return lms.getTotalPeople(); } @RequestMapping(value="under/{age}", method = RequestMethod.GET) @ResponseBody public List<LimitedMember> under(@PathVariable int age){ return lms.getTotalmembersUnderageof(age); } @RequestMapping(value = "create", method = RequestMethod.POST) @ResponseBody public String create(@RequestBody LimitedMember lm){ lms.persist(lm); return "department Created"; } }
package com.app.courseplan; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.recyclerview.widget.RecyclerView; import com.app.courseplan.model.Course; import java.util.List; public class CourseAdapter extends RecyclerView.Adapter<CourseAdapter.MyViewHolder> { private int colour = 0xFFFFFFFF; private Context context; private List<Course> mCourses; private final CourseAdapterOnClickHandler mClickHandler; public interface CourseAdapterOnClickHandler { void onClick(int position); } public CourseAdapter(Context context, List<Course> courses, CourseAdapterOnClickHandler clickHandler) { this.context = context; mCourses = courses; mClickHandler = clickHandler; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate(R.layout.my_row, parent, false); return new MyViewHolder(view); } @Override public void onBindViewHolder(@NonNull MyViewHolder holder, int position) { Course course = mCourses.get(position); //Instead of displaying ID, display num in list for current month holder.courseId.setText(String.valueOf(position + 1)); holder.courseTitle.setText(String.valueOf(course.getCourseName())); holder.courseUrl.setText(String.valueOf(course.getCourseUrl())); //LINK BUTTON CODE //Check if url is not set, if not disable button if (course.getCourseUrl().length() < 1) { //Hides the link button if no link holder.linkButton.setEnabled(false); holder.linkButton.setVisibility(View.GONE); } //If there is a link, then process it and set up click event else { //URL handler //Check if it has http:// at start String urlToCheck = String.valueOf(holder.courseUrl.getText()); if (!(urlToCheck.startsWith("http://") || urlToCheck.startsWith(("https://")))) { urlToCheck = "http://" + String.valueOf(holder.courseUrl.getText()); } else { urlToCheck = String.valueOf(holder.courseUrl.getText()); //quick hack to add http:// } final String urlToOpen = urlToCheck; //Set on click event holder.linkButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Open link in browser Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlToOpen)); context.startActivity(browserIntent); } }); } //Find colour if (course.getId() % 10 == 1 || course.getId() % 10 == 6) { colour = 0XFFFFA69E; } else if (course.getId() % 10 == 2 || course.getId() % 10 == 7) { colour = 0XFFFAF3DD; } else if (course.getId() % 10 == 3 || course.getId() % 10 == 8) { colour = 0XFFB8F2E6; } else if (course.getId() % 10 == 4 || course.getId() % 10 == 9) { colour = 0XFFAED9E0; } else if (course.getId() % 10 == 5 || course.getId() % 10 == 0) { colour = 0XFF5E6472; //Also set text colour holder.courseTitle.setTextColor(Color.WHITE); holder.courseId.setTextColor(Color.WHITE); holder.courseUrl.setTextColor(0xffeeeeee); } //Background colour //itemView.findViewById(R.id.constraint_course).setBackgroundColor(colour); holder.courseContainer.setBackgroundColor(colour); } @Override public int getItemCount() { //Added null pointer error handling if (mCourses != null) { return mCourses.size(); } else { return 0; } } public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private TextView courseId; private TextView courseTitle; private TextView courseUrl; private ImageButton linkButton; ConstraintLayout courseContainer; public MyViewHolder(@NonNull View itemView) { super(itemView); courseTitle = itemView.findViewById(R.id.course_title_txt); courseId = itemView.findViewById(R.id.course_id_txt); courseUrl = itemView.findViewById(R.id.course_url_txt); linkButton = itemView.findViewById(R.id.linkButton); courseContainer = itemView.findViewById(R.id.constraint_course); itemView.setOnClickListener(this); } @Override public void onClick(View view) { int adapterPosition = getAdapterPosition(); mClickHandler.onClick(adapterPosition); } } }
/* * This file is part of lambda, licensed under the MIT License. * * Copyright (c) 2018 KyoriPowered * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.kyori.lambda; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.NoSuchElementException; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; class MaybeTest { @Test void testNothing() { assertEquals(Maybe.nothing(), Maybe.nothing()); } @Test void testJust() { assertEquals(Maybe.just("foo"), Maybe.just("foo")); } @Test void testMaybe() { assertEquals(Maybe.nothing(), Maybe.maybe(null)); assertEquals(Maybe.just("foo"), Maybe.maybe("foo")); } @Test void testFrom() { assertEquals(Maybe.nothing(), Maybe.from(Optional.empty())); assertEquals(Maybe.just("foo"), Maybe.from(Optional.of("foo"))); } @Test void testIsEmpty() { assertTrue(Maybe.nothing().isEmpty()); assertFalse(Maybe.just("foo").isEmpty()); } @Test void testIsPopulated() { assertFalse(Maybe.nothing().isPopulated()); assertTrue(Maybe.just("foo").isPopulated()); } @Test void testGet() { assertThrows(NoSuchElementException.class, () -> Maybe.nothing().get()); assertEquals("foo", Maybe.just("foo").get()); } @Test void testGetOrDefault() { assertEquals("bar", Maybe.nothing().getOrDefault("bar")); assertEquals("foo", Maybe.just("foo").getOrDefault("bar")); } @Test void testGetOrGet() { assertEquals("bar", Maybe.nothing().getOrGet(() -> "bar")); assertEquals("foo", Maybe.just("foo").getOrGet(() -> "bar")); } @Test void testGetOrThrow() { assertThrows(Expected.class, () -> Maybe.nothing().getOrThrow(Expected::new)); assertEquals("foo", Maybe.just("foo").getOrThrow(Expected::new)); } @Test void testOr() { assertEquals(Maybe.nothing(), Maybe.nothing().or(Maybe.nothing())); assertEquals(Maybe.just("foo"), Maybe.just("foo").or(Maybe.just("bar"))); assertEquals(Maybe.just("foo"), Maybe.nothing().or(Maybe.just("foo"))); assertEquals(Maybe.nothing(), Maybe.nothing().or(Maybe::nothing)); assertEquals(Maybe.just("foo"), Maybe.just("foo").or(() -> Maybe.just("bar"))); assertEquals(Maybe.just("foo"), Maybe.nothing().or(() -> Maybe.just("foo"))); } @Test void testFilter() { assertTrue(Maybe.<String>nothing().filter(String::isEmpty).isEmpty()); assertTrue(Maybe.just("foo").filter(String::isEmpty).isEmpty()); } @Test void testMap() { assertTrue(Maybe.nothing().map(nothing -> "foo").isEmpty()); assertEquals("!foo!", Maybe.just("foo").map(string -> '!' + string + '!').get()); } @Test void testFlatMap() { assertTrue(Maybe.nothing().flatMap(nothing -> Maybe.just("foo")).isEmpty()); assertEquals("!foo!", Maybe.just("foo").flatMap(string -> Maybe.just('!' + string + '!')).get()); } @Test void testForEach() { final AtomicInteger nothing = new AtomicInteger(); Maybe.nothing().forEach(v -> nothing.incrementAndGet()); assertEquals(0, nothing.get()); final AtomicInteger just = new AtomicInteger(); Maybe.just("foo").forEach(v -> just.incrementAndGet()); assertEquals(1, just.get()); } @Test void testStream() { assertThat(Maybe.nothing().stream()).isEmpty(); assertThat(Maybe.just("foo").stream()).containsExactly("foo"); } @Test void testOptional() { assertEquals(Maybe.nothing().optional(), Maybe.nothing().optional()); assertEquals(Maybe.just("foo").optional(), Maybe.just("foo").optional()); } @Test void testIterator() { assertThat(Maybe.nothing()).isEmpty(); assertThat(Maybe.just("foo")).containsExactly("foo"); } @SuppressWarnings("ResultOfMethodCallIgnored") @Test void testCollector() { assertEquals(Maybe.nothing(), Stream.empty().collect(Maybe.collector())); assertEquals(Maybe.just("foo"), Stream.of("foo").collect(Maybe.collector())); assertThrows(AmbiguousElementException.class, () -> Stream.of("foo", "bar").collect(Maybe.collector())); } @Test void testFirst() { assertEquals(Maybe.nothing(), Maybe.first(Maybe.nothing(), Maybe.nothing())); assertEquals(Maybe.just("foo"), Maybe.first(Maybe.just("foo"), Maybe.just("bar"))); assertEquals(Maybe.nothing(), Maybe.first(Arrays.asList(Maybe.nothing(), Maybe.nothing()))); assertEquals(Maybe.just("foo"), Maybe.first(Arrays.asList(Maybe.just("foo"), Maybe.just("bar")))); } private static class Expected extends RuntimeException {} }
package com.example.biblioteca.Adapters; import android.app.Activity; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.example.biblioteca.Fragmentos.almacenamientoFragment; import com.example.biblioteca.R; import java.io.File; import java.util.ArrayList; public class favAdapter extends BaseAdapter { private final Activity context; private final ArrayList<String> files; /** * * @param context * @param files */ public favAdapter(Activity context, ArrayList<String> files) { this.context = context; this.files = files; } @Override public int getCount() { return files.size(); } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return i; } @Override public View getView(int position, View view, ViewGroup viewGroup) { view = context.getLayoutInflater().inflate(R.layout.custom_grid_fav, null); ImageView img = (ImageView) view.findViewById(R.id.imageFav); TextView nametx = (TextView) view.findViewById(R.id.textName); TextView pathtx = (TextView) view.findViewById(R.id.textPath); File file = new File(files.get(position)); nametx.setText(file.getName().trim()); pathtx.setText(file.getPath()); Log.d("fav", "getView: "+file.getPath()); almacenamientoFragment alm = new almacenamientoFragment(); img.setImageBitmap(alm.pdfToBitmap(file)); return view; }; }
package egovframework.svt.adm.prop.auto; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import egovframework.com.cmm.service.EgovFileMngUtil; import egovframework.com.cmm.service.EgovProperties; import egovframework.com.file.controller.FileController; @Controller public class AdminAutoMemberController { protected static final Log log = LogFactory.getLog(AdminAutoMemberController.class); @Autowired AdminAutoMemberService adminAutoMemberService; @RequestMapping(value="/adm/prop/autoMemberList.do") public String autoMemberList(HttpServletRequest request, Map<String, Object> commandMap, ModelMap model) throws Exception{ model.addAllAttributes(commandMap); List<?> autoMemberList = adminAutoMemberService.autoMemberList(commandMap); model.addAttribute("autoMemberList", autoMemberList); return "svt/adm/prop/autoMemberList"; } @RequestMapping(value="/adm/prop/insertAutoMember.do") public String insertAutoMember(HttpServletRequest request, Map<String, Object> commandMap, ModelMap model) throws Exception{ String strSavePath = EgovProperties.getProperty("Globals.fileStorePath") + "member/"; MultipartHttpServletRequest mptRequest = (MultipartHttpServletRequest)request; Iterator fileIter = mptRequest.getFileNames(); Map fileInfo = new HashMap(); while (fileIter.hasNext()) { MultipartFile mFile = mptRequest.getFile((String)fileIter.next()); if (mFile.getSize() > 0) { fileInfo = EgovFileMngUtil.uploadContentFile(mFile, strSavePath); log.info("/adm/prop/insertAutoMember.do"); log.info("자동승인 회원등록"); } } FileController file = new FileController(); List<Map<String, String>> excelDataList = file.getExcelDataList(String.valueOf(fileInfo.get("filePath")) + String.valueOf(fileInfo.get("uploadFileName"))); excelDataList.remove(0); // 타이틀 제거 // list set // parameter0: empGubun, parameter1: name, parameter2: nicePersonalNum, parameter3: birthDate List<Map<String, String>> autoMemberList = new ArrayList<Map<String,String>>(); for(Map<String, String> excelData: excelDataList) { Map<String, String> autoMember = new HashMap<String, String>(); autoMember.put("empGubun", excelData.get("parameter0").trim()); autoMember.put("name", excelData.get("parameter1").trim()); if(null != excelData.get("parameter2")) { autoMember.put("nicePersonalNum", excelData.get("parameter2").trim()); } if(null != excelData.get("parameter3")) { autoMember.put("birthDate", excelData.get("parameter3").trim()); } autoMemberList.add(autoMember); } model.addAllAttributes(adminAutoMemberService.insertAutoMember(autoMemberList, commandMap)); return "jsonView"; } }
package com.practice.employeemanagement; import java.util.List; import com.practice.util.AbstractDao; public class EmployeeManagementDao <T> extends AbstractDao <T> { private static final String STATEMENT_FIND = "com.practice.employeemanagement.dto.EmployeeManagementDto.find"; private static final String STATEMENT_SELECT = "com.practice.employeemanagement.dto.EmployeeManagementDto.select"; private static final String STATEMENT_INSERT = "com.practice.employeemanagement.dto.EmployeeManagementDto.insert"; private static final String STATEMENT_UPDATE = "com.practice.employeemanagement.dto.EmployeeManagementDto.update"; private static final String STATEMENT_DELETE = "com.practice.employeemanagement.dto.EmployeeManagementDto.delete"; public EmployeeManagementDao() { super(); } @Override public List<T> find(T param) { return sqlSession.selectList(STATEMENT_FIND, param); } @Override public List<T> select(T dto) { return sqlSession.selectList(STATEMENT_SELECT, dto); } @Override public void insert(T dto) { try { sqlSession.insert(STATEMENT_INSERT, dto); sqlSession.commit(); } catch (Exception e) { sqlSession.rollback(); } } @Override public void delete(T dto) { try { sqlSession.delete(STATEMENT_DELETE, dto); sqlSession.commit(); } catch (Exception e) { sqlSession.rollback(); } } @Override public void update(T dto) { try { sqlSession.update(STATEMENT_UPDATE, dto); sqlSession.commit(); } catch (Exception e) { sqlSession.rollback(); } } }
package me.ewriter.rxgank.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; import me.ewriter.rxgank.api.entity.GankItem; /** * Created by Zubin on 2016/8/16. */ public class SimpeFragmentAdapter extends RecyclerView.Adapter<SimpeFragmentAdapter.MyViewHolder> { private Context mContext; private List<GankItem> mTitleList; public SimpeFragmentAdapter(Context mContext, List<GankItem> title) { this.mContext = mContext; this.mTitleList = title; } @Override public SimpeFragmentAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new MyViewHolder(LayoutInflater.from(mContext).inflate(android.R.layout.simple_list_item_1, parent, false)); } @Override public void onBindViewHolder(SimpeFragmentAdapter.MyViewHolder holder, int position) { holder.textView.setText(mTitleList.get(position).getDesc()); } @Override public int getItemCount() { return mTitleList.size(); } class MyViewHolder extends RecyclerView.ViewHolder { TextView textView; public MyViewHolder(View itemView) { super(itemView); textView = (TextView)itemView; } } }
package br.com.cleitonkiper.hiperion.builders; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.docx4j.openpackaging.exceptions.Docx4JException; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart; import br.com.cleitonkiper.hiperion.Content; import br.com.cleitonkiper.hiperion.Cover; import br.com.cleitonkiper.hiperion.Project; import br.com.cleitonkiper.hiperion.Beans.ContentBean; import br.com.cleitonkiper.hiperion.interfaces.Builder; public class ProjectBuilder implements Builder<Project> { private Cover cover; private CoverBuilder coverBuilder; private InputStream template; private List<String> integrants = new ArrayList<String>(); private List<ContentBean> contents = new ArrayList<ContentBean>(); private String title; private String subtitle; private String institute; private String advisor; private String course; public ProjectBuilder withCover(Cover cover) { this.cover = cover; return this; } public ProjectBuilder withCover(CoverBuilder builder) throws FileNotFoundException { this.coverBuilder = builder; return this; } public ProjectBuilder withTitle(String title) { this.title = title; return this; } public ProjectBuilder withSubTitle(String subtitle) { this.subtitle = subtitle; return this; } public ProjectBuilder withInstitute(String institute) { this.institute = institute; return this; } public ProjectBuilder withAdvisor(String advisor) { this.advisor = advisor; return this; } public ProjectBuilder withIntegrantsList(List<String> integrats) { this.integrants.addAll(integrats); return this; } public ProjectBuilder addIntegrant(String name) { this.integrants.add(name); return this; } public ProjectBuilder withCourse(String course) { this.course = course; return this; } public ProjectBuilder withTemplate(InputStream template) { this.template = template; return this; } public ProjectBuilder withContents(List<ContentBean> contents) { this.contents.addAll(contents); return this; } @Override public Project build() throws Exception { return build(template); } @Override public Project build(InputStream template) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); this.cover = this.coverBuilder.withTitle(this.title) .withSubTitle(this.subtitle) .withAdvisor(this.advisor) .withCourse(this.course) .withIntegrantsList(this.integrants) .withTemplate(this.template) .build(); Content cont = new ContentBuilder(this.contents, new ByteArrayInputStream(cover.getStream().toByteArray())).build(); return new Project(this.title, cont.getStream()); } }
package seleniumEj; import java.io.File; import java.nio.file.Paths; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; public class MetodosSelenium2 { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub System.out.println("test");// //standar declarativo para indicarle a Sele el uso del drive String exePath = Paths.get("").toAbsolutePath().toString() + File.separator + "Drivers" + File.separator; System.setProperty("webdriver.chrome.driver", exePath + "chromedriver.exe"); //variable de control para el driver WebDriver driver = new ChromeDriver(); //uso general del driver para que ejecute a la primera driver.get("https://opensource-demo.orangehrmlive.com/"); driver.manage().window().maximize(); //Obteniendo objetos o WebElements //Declaracion WebElement userName = driver.findElement(By.id("txtUsername")); WebElement password = driver.findElement(By.id("txtPassword")); WebElement btnLogin = driver.findElement(By.id("btnLogin")); //interaccion con WebElementos //login userName.sendKeys("Admin"); Thread.sleep(2000); password.sendKeys("admin123"); Thread.sleep(2000); btnLogin.click(); Thread.sleep(5000); //Clic en boton de assign Level de la pagina de prueba WebElement assignLeave = driver.findElement(By.className("quickLinkText")); assignLeave.click(); Thread.sleep(3000); //llenar el textbox de employee name WebElement employeeName = driver.findElement(By.name("assignleave[txtEmployee][empName]")); employeeName.sendKeys("Alexandra"); Thread.sleep(3000); employeeName.clear(); //verificar elemento desplegado en pagina boolean assignBtn = driver.findElement(By.id("assignBtn")).isDisplayed(); if(assignBtn) { System.out.println("El boton assign esta desplegado"); } String welcomeMsj = driver.findElement(By.id("welcome")).getText(); System.out.println(welcomeMsj); boolean userMsj = welcomeMsj.contains("Paul"); if(userMsj) { System.out.println("El mensaje de welcome contiene el nombre de Paul"); }else { System.out.println("El mensaje No contiene el nombre de Paul"); } //interactuar con dropdown Select oSelect = new Select (driver.findElement(By.id("assignleave_txtLeaveType"))); oSelect.selectByVisibleText("US - FMLA"); Thread.sleep(3000); driver.quit(); } }
package com.example.demo.controller; import com.example.demo.model.Course; import com.example.demo.model.User; import com.example.demo.model.UserCourse; import com.example.demo.repository.CourseRepository; import com.example.demo.repository.UserCourseRepository; import com.example.demo.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; @Controller public class StudentController { @Autowired UserRepository userRepository; @Autowired CourseRepository courseRepository; @Autowired UserCourseRepository userCourseRepository; //Used to redirect from kea logo @GetMapping("/student") public String redirectTeacherMyCourses() { return "redirect:/student/myCourses"; } @GetMapping("/student/course") public String student(Model model) { User currentUser = userRepository.findByEmail(SecurityContextHolder.getContext().getAuthentication().getName()); return "student/course"; } @GetMapping("/student/course/{id}") public String course(Model model, @PathVariable Long id) { User currentUser = userRepository.findByEmail(SecurityContextHolder.getContext().getAuthentication().getName()); Course course = courseRepository.findCourse(id); model.addAttribute("course", course); List<User> teachers = CourseController.getCourseTeachers(course); List<User> students = CourseController.getCourseStudents(course); model.addAttribute("teachers", teachers); model.addAttribute("students", students); return "student/course"; } @PostMapping(value = "/teacher/course", params = "signUp") public String signUpCourse(@ModelAttribute Course course) { User currentUser = userRepository.findByEmail(SecurityContextHolder.getContext().getAuthentication().getName()); UserCourse testUserCourse = userCourseRepository.findAllByUserIdAndCourseId(currentUser.getId(), course.getId()); if (testUserCourse == null) { UserCourse userCourse = new UserCourse(); userCourse.setCourse(course); userCourse.setUser(currentUser); userCourse.setSignUpDate(LocalDateTime.now()); currentUser.userCourses.add(userCourse); course.userCourses.add(userCourse); try { userCourseRepository.save(userCourse); } catch (Exception e) { return "redirect:/student/course/" + course.getId() + "?error"; } } return "redirect:/student/myCourses"; } @GetMapping("/student/myCourses") public String myCourses(Model model) { User currentUser = userRepository.findByEmail(SecurityContextHolder.getContext().getAuthentication().getName()); List<UserCourse> userCourses = userCourseRepository.findAllUserCoursesByUserIdAndAccepted(currentUser.getId(), true); List<Course> courses = new ArrayList<>(); for (UserCourse userCourse : userCourses) { courses.add(userCourse.getCourse()); } model.addAttribute("courses", courses); return "student/my_courses"; } @GetMapping("/student/findCourses") public String findCourses(Model model) { User currentuser = userRepository.findByEmail(SecurityContextHolder.getContext().getAuthentication().getName()); model.addAttribute("courses", courseRepository.findAllByOrderByCourseNameInEnglish()); List<UserCourse> userCourses = userCourseRepository.findAllUserCoursesByUserIdAndAccepted(currentuser.getId(), false); return "student/find_courses"; } @GetMapping("/student/pendingCourses") public String pendingCourses(Model model) { User currentUser = userRepository.findByEmail(SecurityContextHolder.getContext().getAuthentication().getName()); List<UserCourse> userCourses = userCourseRepository.findAllUserCoursesByUserIdAndAcceptedOrderBySignUpDateDesc(currentUser.getId(), false); List<Course> courses = new ArrayList<>(); for (UserCourse userCourse : userCourses) { courses.add(userCourse.getCourse()); } model.addAttribute("courses", courses); model.addAttribute("userCourses", userCourses); return "student/pending_courses"; } }
/* * Copyright (C) 2015 Adrien Guille <adrien.guille@univ-lyon2.fr> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package main.java.fr.ericlab.sondy.core.text.index; import java.util.ArrayList; import java.util.HashMap; /** * * @author Adrien GUILLE, Laboratoire ERIC, Université Lumière Lyon 2 */ public class Analyzer extends Thread { int threadId; int from; int to; int fileCount; ArrayList<HashMap<String,Short>> mapList; ArrayList<String> vocabulary; public ArrayList<String> newVocabulary; public Analyzer(int id, int a, int b, ArrayList<HashMap<String,Short>> ml, ArrayList<String> voc, int fc){ from = a; to = b; threadId = id; mapList = ml; vocabulary = voc; fileCount = fc; } @Override public void run() { newVocabulary = new ArrayList<>(to-from+10); for(int j = from; j <= to; j++){ String word = vocabulary.get(j); int total = 0; for(int i = 0; i < fileCount-1; i++){ Short count = mapList.get(i).get(word); count = (count==null)?0:count; total += count; } if(total > 10){ newVocabulary.add(word); } } newVocabulary.trimToSize(); } }
package com.example.projet_pm.presentation.vue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import com.example.projet_pm.R; import java.util.List; import com.example.projet_pm.presentation.modele.Match; public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ViewHolder> { private List<Match> values; private OnItemClickListener listener; public interface OnItemClickListener { void onItemClick(Match item); } class ViewHolder extends RecyclerView.ViewHolder { // each data item is just a string in this case TextView txtHeader; TextView txtFooter; View layout; ViewHolder(View v) { super(v); layout = v; txtHeader = (TextView) v.findViewById(R.id.firstLine); txtFooter = (TextView) v.findViewById(R.id.secondLine); } } public void add(int position, Match item) { values.add(position, item); notifyItemInserted(position); } public void remove(int position) { values.remove(position); notifyItemRemoved(position); } // Provide a suitable constructor (depends on the kind of dataset) public ListAdapter(List<Match> myDataset, OnItemClickListener listener) { this.values = myDataset; this.listener = listener; } //Créer les cellules @Override public ListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View v = inflater.inflate(R.layout.row_layout, parent, false); // set the view's size, margins, paddings and layout parameters ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(ViewHolder holder, final int position) { final Match currentMatch = values.get(position); holder.txtHeader.setText(currentMatch.getTitle()); holder.txtFooter.setText("Compétition : " + currentMatch.getCompetition().getName()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.onItemClick(currentMatch); } }); } // Return the size of your dataset (invoked by the layout manager) @Override public int getItemCount() { return values.size(); } }
package denoflionsx.DenPipes.AddOns.Forestry.net; import cpw.mods.fml.common.network.PacketDispatcher; import cpw.mods.fml.common.network.Player; import denoflionsx.DenPipes.AddOns.Forestry.PluginForestryPipes; import denoflionsx.DenPipes.AddOns.Forestry.gui.ContainerForestryPipe; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.INetworkManager; import net.minecraft.network.packet.Packet250CustomPayload; public class PacketHandlerClient extends PacketHandler { @Override public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player player) { super.onPacketData(manager, packet, player); DataInputStream data = new DataInputStream(new ByteArrayInputStream(packet.data)); Packets.Wrapper pkt = new Packets.Wrapper(data); EntityPlayer p = (EntityPlayer) player; ContainerForestryPipe c = null; try { c = (ContainerForestryPipe) p.openContainer; } catch (Throwable t) { return; } int id = pkt.getPacketID(); if (id == Packets.packet_FakeSlotSpeciesChange) { Class[] decodeAs = {Integer.class, Integer.class, Integer.class}; Object[] packetReadout = Packets.Wrapper.readPacketData(data, decodeAs); c.logic.cards.get(PluginForestryPipes.keyMap.get((Integer) packetReadout[2]))[(Integer) packetReadout[0]] = PluginForestryPipes.getCard(PluginForestryPipes.keyMap.get((Integer) packetReadout[2]), (Integer) packetReadout[1]); } else if (id == Packets.packet_sync) { Class[] decodeAs = {Integer.class, Integer.class, Integer.class}; Object[] packetReadout = Packets.Wrapper.readPacketData(data, decodeAs); c.logic.cards.get(PluginForestryPipes.keyMap.get((Integer) packetReadout[0]))[(Integer) packetReadout[1]] = PluginForestryPipes.getCard(PluginForestryPipes.keyMap.get((Integer) packetReadout[0]), (Integer) packetReadout[2]); } else if (id == Packets.packet_lock) { Class[] decodeAs = {Boolean.class}; Object[] packetReadout = Packets.Wrapper.readPacketData(data, decodeAs); c.logic.lock.isLocked = (Boolean) packetReadout[0]; } else if (id == Packets.packet_clear) { Class[] decodeAs = {Integer.class, Integer.class, Integer.class, Boolean.class}; Object[] packetReadout = Packets.Wrapper.readPacketData(data, decodeAs); if ((Boolean) packetReadout[3]) { PacketDispatcher.sendPacketToServer(Packets.Wrapper.createPacket(Packets.packet_sync, new Object[]{(Integer) packetReadout[0], (Integer) packetReadout[1], (Integer) packetReadout[2], (Boolean) packetReadout[3]})); } } } }
package com.example.canalu.ui.rutes; import androidx.lifecycle.ViewModel; public class RoutesViewModel extends ViewModel { // TODO: Implement the ViewModel }
package fr.trainningSql.model; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; public class Film { private int film_id; private String title; private String description; private Timestamp release_year; private String film_category; private String language; private List<Acteur> listeActeur = new ArrayList<Acteur>(); public Film() { super(); } public int getFilm_id() { return film_id; } public void setFilm_id(int film_id) { this.film_id = film_id; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Timestamp getRelease_year() { return release_year; } public void setRelease_year(Timestamp release_year) { this.release_year = release_year; } public String getFilm_category() { return film_category; } public void setFilm_category(String film_category) { this.film_category = film_category; } public List<Acteur> getListeActeur() { return listeActeur; } public void setListeActeur(List<Acteur> listeActeur) { this.listeActeur = listeActeur; } public void ajouterActeur(Acteur acteur) { this.listeActeur.add(acteur); } @Override public String toString() { return "Film [film_id=" + film_id + ", title=" + title + ", description=" + description + ", release_year=" + release_year + ", film_category=" + film_category + "]"; } }
package pers.mine.scratchpad.other.zhihu; import org.junit.Test; public class P_27431652 { @Test public void test1() { int i = 1; int j = i++; if ((i == (++j)) && ((i++) == j)) { i += j; } System.out.println("i = " + i);// 5 } @Test public void test5() { int x = 10; double y = 20.2; long z = 10L; String str = "" + x + y * z; System.out.println(str);// 拼接会时优先算出+的每一块 String str1 = y + x + y * z + ""; System.out.println(str1); // 只有在碰到字符串才开始使用字符串拼接 } @Test public void test9() { int sum = 0; for (int x = 1; x < 10; x++) { sum += x; if (x % 3 == 0) { continue; } } System.out.println(sum);// 45 } @Test public void test10() { int sum = 0; for (int x = 0; x < 10; x++) { sum += x; if (x % 3 == 0) {// 0就跳出了 break; } } System.out.println(sum);// 0 } }
package com.openfarmanager.android.model.exeptions; import com.openfarmanager.android.App; import com.openfarmanager.android.R; import com.openfarmanager.android.core.network.smb.SmbAPI; import com.yandex.disk.client.exceptions.DuplicateFolderException; import com.yandex.disk.client.exceptions.IntermediateFolderNotExistException; import com.yandex.disk.client.exceptions.WebdavException; import com.yandex.disk.client.exceptions.WebdavFileNotFoundException; import com.yandex.disk.client.exceptions.WebdavForbiddenException; import com.yandex.disk.client.exceptions.WebdavNotAuthorizedException; import com.yandex.disk.client.exceptions.WebdavUserNotInitialized; import java.io.IOException; import java.net.SocketTimeoutException; import jcifs.smb.SmbAuthException; /** * @author Vlad Namashko */ public class NetworkException extends RuntimeException { private String mLocalizedError; private ErrorCause mErrorCause; public enum ErrorCause { Unlinked_Error, IO_Error, Cancel_Error, Server_error, Common_Error, FTP_Connection_Closed, Socket_Timeout, Access_Denied, Yandex_Disk_Error, Yandex_Disk_Not_Initialized_Error, Unknown_Error } public NetworkException() {} public NetworkException(String error, ErrorCause cause) { mLocalizedError = error; mErrorCause = cause; } public static NetworkException handleNetworkException(Exception e) { e.printStackTrace(); NetworkException exception = new NetworkException(); /*if (e instanceof DropboxUnlinkedException) { // happen either because you have not set an AccessTokenPair on your session, or because the user unlinked your app (revoked the access token pair). exception.mErrorCause = ErrorCause.Unlinked_Error; exception.mLocalizedError = getString(R.string.error_account_unlinked); } else if (e instanceof DropboxParseException || e instanceof DropboxIOException) { // 1) indicates there was trouble parsing a response from Dropbox. // 2) happens all the time, probably want to retry automatically. exception.mErrorCause = ErrorCause.IO_Error; exception.mLocalizedError = getString(R.string.error_io_error); } else if (e instanceof DropboxPartialFileException) { // canceled operation exception.mErrorCause = ErrorCause.Cancel_Error; exception.mLocalizedError = getString(R.string.error_canceled); } else if (e instanceof DropboxServerException) { DropboxServerException error = (DropboxServerException) e; // Server-side exception. These are examples of what could happen, // but we don't do anything special with them here. exception.mErrorCause = ErrorCause.Server_error; switch (error.error) { // case DropboxServerException._304_NOT_MODIFIED: // case DropboxServerException._401_UNAUTHORIZED: // case DropboxServerException._403_FORBIDDEN: // case DropboxServerException._404_NOT_FOUND: // case DropboxServerException._406_NOT_ACCEPTABLE: // case DropboxServerException._415_UNSUPPORTED_MEDIA: case DropboxServerException._507_INSUFFICIENT_STORAGE: exception.mLocalizedError = getString(R.string.error_network_quota); break; default: exception.mLocalizedError = error.reason; break; } } else if (e instanceof DropboxException) { exception.mErrorCause = ErrorCause.Common_Error; exception.mLocalizedError = e.getMessage(); } else */ if (e instanceof SocketTimeoutException) { exception.mErrorCause = ErrorCause.Socket_Timeout; exception.mLocalizedError = getString(R.string.error_socket_timeout_exception); } else if (e instanceof SmbAuthException) { if (SmbAPI.ACCESS_DENIED.equals(e.getMessage())) { exception.mErrorCause = ErrorCause.Access_Denied; exception.mLocalizedError = getString(R.string.error_access_denied); } } else if (e instanceof IOException && "FTPConnection closed".equals(e.getMessage())) { exception.mErrorCause = ErrorCause.FTP_Connection_Closed; exception.mLocalizedError = getString(R.string.error_ftp_connection_closed); } else if (e instanceof WebdavException) { exception.mErrorCause = ErrorCause.Yandex_Disk_Error; if (e instanceof WebdavFileNotFoundException) { exception.mLocalizedError = getString(R.string.error_file_not_found); } else if (e instanceof WebdavNotAuthorizedException) { exception.mErrorCause = ErrorCause.Yandex_Disk_Not_Initialized_Error; exception.mLocalizedError = getString(R.string.error_user_not_authorized); } else if (e instanceof WebdavUserNotInitialized) { exception.mErrorCause = ErrorCause.Yandex_Disk_Not_Initialized_Error; exception.mLocalizedError = getString(R.string.error_user_not_initialized); } else if (e instanceof WebdavForbiddenException) { exception.mLocalizedError = getString(R.string.error_forbidden); } else if (e instanceof DuplicateFolderException) { exception.mLocalizedError = getString(R.string.error_duplicated_folder); } else if (e instanceof IntermediateFolderNotExistException) { exception.mLocalizedError = getString(R.string.error_intermediate_folder_not_exist); } else { exception.mErrorCause = ErrorCause.Unknown_Error; exception.mLocalizedError = getString(R.string.error_unknown_unexpected_error); } } else { exception.mErrorCause = ErrorCause.Unknown_Error; exception.mLocalizedError = getString(R.string.error_unknown_unexpected_error); } return exception; } public String getLocalizedError() { return mLocalizedError; } public ErrorCause getErrorCause() { return mErrorCause; } private static String getString(int codeId) { return App.sInstance.getString(codeId); } }
package com.test.commonlibrary; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; /** * 积累 */ public class BaseActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_base); Log.e("NowActivity",this.getClass().getName()); } }
package ee.eerikmagi.testtasks.arvato.invoice_system.logic; import java.math.BigDecimal; import java.time.LocalDateTime; import java.time.YearMonth; import java.util.ArrayList; import java.util.List; import ee.eerikmagi.testtasks.arvato.invoice_system.model.Customer; import ee.eerikmagi.testtasks.arvato.invoice_system.model.Invoice; import ee.eerikmagi.testtasks.arvato.invoice_system.model.InvoiceEntry; import ee.eerikmagi.testtasks.arvato.invoice_system.model.InvoiceEntryType; import ee.eerikmagi.testtasks.arvato.invoice_system.model.InvoiceParking; import ee.eerikmagi.testtasks.arvato.invoice_system.model.Parking; /** * Abstract base class for customer payment logic. * * Contains logic that is shared between {@link RegularCustomerPaymentLogic} and {@link PremiumCustomerPaymentLogic} */ public abstract class AbstractCustomerPaymentLogic implements IPaymentLogic { private static final int HOUR_EXPENSIVE_TIME_END = 19; private static final int HOUR_EXPENSIVE_TIME_START = 7; private static final int TIMEUNIT_MINUTES = 30; @Override public Invoice calculateInvoice(Customer customer, List<Parking> parkings, YearMonth ym) { return calculateInvoice(customer, parkings, ym, LocalDateTime.now()); } @Override public Invoice calculateInvoice(Customer customer, List<Parking> parkings, YearMonth ym, LocalDateTime dt) { List<InvoiceEntry> entries = new ArrayList<>(); parkings.stream().forEach((p) -> entries.add(getParkingEntry(p))); BigDecimal total = entries.stream() .map((e) -> e.getCost()) .reduce(BigDecimal.ZERO, (tot, cost) -> tot.add(cost)); Invoice inv = new Invoice() .setEntries(entries) .setTotal(total) .setFinalSum(total) .setIncomplete(isCurrentMonth(dt, ym)); return inv; } /** * Creates an {@link InvoiceEntry} based on the provided {@link Parking} object. * Calculates the spans and costs of that parking. * * @param parking The parking object to handle. * @return The invoice entry for the given parking object. */ protected InvoiceEntry getParkingEntry(Parking parking) { List<InvoiceParking> parkings = new ArrayList<>(); LocalDateTime start = parking.getStartDateTime(); LocalDateTime end = parking.getEndDateTime(); LocalDateTime cursor = start; long ipTimeUnitsCount = 0; // go through the time difference in TIMEUNIT_MINUTES chunks and split it into spans if // the parking goes through a cheap-expensive time change while (cursor.isBefore(end)) { ipTimeUnitsCount++; LocalDateTime next = cursor.plusMinutes(TIMEUNIT_MINUTES); if (next.isBefore(end) && hasTimerangeChanged(cursor, next)) { parkings.add(createParkingSpan(parking, start, next, ipTimeUnitsCount)); ipTimeUnitsCount = 0; start = next; } cursor = next; } parkings.add(createParkingSpan(parking, start, end, ipTimeUnitsCount)); return new InvoiceEntry() .setParking(parking) .setParkingSpans(parkings) .setType(InvoiceEntryType.PARKING) .setCost(parkings.stream() .map((p) -> p.getCost()) .reduce(BigDecimal.ZERO, (tot, cost) -> tot.add(cost)) .setScale(2)); } protected boolean hasTimerangeChanged(LocalDateTime cursor, LocalDateTime next) { return isCheapTime(cursor) && !isCheapTime(next) || !isCheapTime(cursor) && isCheapTime(next); } protected InvoiceParking createParkingSpan(Parking p, LocalDateTime start, LocalDateTime end, long ipTimeUnitsCount) { BigDecimal timeUnitCost = getTimeUnitCost(start); return new InvoiceParking() .setParking(new Parking() .setStartDateTime(start) .setEndDateTime(end) .setParkingHouse(p.getParkingHouse()) ) .setTimeUnitMinutes(TIMEUNIT_MINUTES) .setTimeUnitsCount(ipTimeUnitsCount) .setTimeUnitCost(timeUnitCost) .setCost(timeUnitCost.multiply(BigDecimal.valueOf(ipTimeUnitsCount))); } protected boolean isCheapTime(LocalDateTime dt) { return dt.getHour() < HOUR_EXPENSIVE_TIME_START || dt.getHour() >= HOUR_EXPENSIVE_TIME_END; } protected boolean isCurrentMonth(LocalDateTime dt, YearMonth ym) { return YearMonth.from(dt).equals(ym); } /** * Returns the cost per time unit at the provided time. */ abstract protected BigDecimal getTimeUnitCost(LocalDateTime dateTime); }
package com.bankerguy.bankerguy; import java.util.List; /** * Created by nevin on 11/12/2017. */ public class User { private int userId; private List<CourseProgress> courseProgressList; }
package cn.test.demo02; public class test { public static void main(String[] args) { int a = 5; byte b = 98; char d = 'a'; int c = a + b; System.out.println(c);//byte自动转换为int int z = d ; System.out.println(z);//char自动换行为int /*char cc = b; System.out.println(cc); */ byte[] bys = new byte[]{97,98,99,100}; String s2 = new String(bys); System.out.println(s2); char[] chs = new char[]{'2','2'}; String s4 = new String(chs); System.out.println(s4); int ii = 98; char ccc = (char)ii; System.out.println(ccc); } }
/* * 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 hdfcraft; import java.awt.*; import java.io.File; import java.io.IOException; import java.util.Random; import static hdfcraft.minecraft.Constants.*; import static hdfcraft.Constants.*; import ucar.ma2.ArrayFloat; import ucar.nc2.dataset.NetcdfDataset; import ucar.nc2.Variable; /** * * @author Simon */ public class Hdfcraft { /** * @param args the command line arguments */ public static void main(String[] args) { System.out.println("HDFCRAFT version 0.0.1\n"); // Download and save HDF file at the top level project directory. // For example, C:\Users\hyoklee\Documents\GitHub\HDFCRAFT // String filename = "MOD14CM1.201401.005.01.hdf"; String filename = "Q20141722014263.L3m_SNSU_SCID_V3.0_SSS_1deg.h5"; ucar.nc2.NetcdfFile nc = null; // Use toolsUI to open an HDF file and // determine which variable that you want to use. float[][] data = new float[360][180]; try { nc = NetcdfDataset.openFile(filename, null); // Variable v = nc.findVariable("MeanCloudFraction"); Variable v = nc.findVariable("l3m_data"); long extent = v.getSize(); ArrayFloat.D2 presArray; presArray = (ArrayFloat.D2) v.read(); int[] shape1 = presArray.getShape(); System.out.println("Shape[0]="+shape1[0]); for (int i = 0; i < shape1[0]; i++) { for (int j = 0; j < shape1[1]; j++) { data[j][i] = presArray.get(i, j); } } } catch (IOException ioe) { System.out.println("Failed to open " + filename); } finally { if (null != nc) try { nc.close(); } catch (IOException ioe) { System.out.println("Failed to close " + filename); } } // Reduce random noise. // HeightMapTileFactory tileFactory = TileFactoryFactory.createNoiseTileFactory(new Random().nextLong(), HeightMapTileFactory tileFactory = TileFactoryFactory.createFlatTileFactory(new Random().nextLong(), Terrain.GRASS, DEFAULT_MAX_HEIGHT_2, 58, 62, false, true); World2 world = new World2(World2.DEFAULT_OCEAN_SEED, tileFactory, 256); world.setName("HDF"); world.setVersion(SUPPORTED_VERSION_2); // Select spawn point based on your point of interest. // world.setSpawnPoint(new Point(308, 53)); world.setSpawnPoint(new Point(95, 144)); // Creative mode so that you can check global map easily. world.setGameType(1); Generator generator = Generator.values()[1]; // Dimension dim0 = world.getDimension(0); world.setGenerator(generator); final Dimension dimension = world.getDimension(0); int offsetX = 0; int offsetY = 0; // See also WorldPainter's HeightMapImporter.java. // int worldWaterLevel = 0; // Sea Surface Salinity varies from 30.0 - 40.0 int worldWaterLevel = 30; int tileCount = 0; // Tile size is 128 x 128. // To cover 360 x 180, we need 3 x 2 tiles. for (int tileX = 0; tileX < 3; tileX++) { for (int tileY = 0; tileY < 2; tileY++) { final Tile tile = new Tile(tileX, tileY, 256); for (int x = 0; x < TILE_SIZE; x++) { for (int y = 0; y < TILE_SIZE; y++) { int lat = y+(tileY *TILE_SIZE); int lon = x+(tileX *TILE_SIZE); float val = 0.0f; System.out.println(val); if((lat < 180) && (lon < 360)) { if (data[lon][lat] > 0) val = data[lon][lat]; } // float scale = 3.0f; float level = 30.0f; if (val > 30.0 ) { level = (float) ((val - 30.0) / 10.0 * 128.0); } // System.out.println(level); final boolean void_; tile.setHeight(x, y, level); tile.setWaterLevel(x, y, worldWaterLevel); // tileFactory.applyTheme(tile, x, y); } } dimension.addTile(tile); tileCount++; } } System.out.println("done"); WorldExporter exporter = new WorldExporter(world); // Change hyoklee to your user'name. // For Mac, use ~/Library/Application Support/minecraft/saves/ File baseDir = new File("C:\\Users\\hyoklee\\AppData\\Roaming\\.minecraft\\saves"); String name = filename; File backupDir; try { backupDir = exporter.selectBackupDir(new File(baseDir, FileUtils.sanitiseName(name))); exporter.export(baseDir, name, backupDir); } catch (IOException e) { throw new RuntimeException("I/O error while exporting world", e); } } }
package com.basket.interview; public class BasketInterviewMain { public static void main(String[] args) { throw new UnsupportedOperationException("please implement"); } }
package Hw.Tz; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class Beans implements SuperEncoder { private static final long serialVersionUID = 1L; private String name; public void setName(String name) { this.name = name; } public String getName() { return this.name; } public Beans() { } @Override public byte[] serialize(Object anyBean) { byte[] date = null; ByteArrayOutputStream bos = null; ObjectOutputStream oos = null; try { bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bos); oos.writeObject(anyBean); oos.flush(); date = bos.toByteArray(); } catch (IOException var9) { var9.printStackTrace(); } finally { if (oos != null) { try { oos.close(); } catch (IOException e) { e.printStackTrace(); } } if (bos != null) { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } } return date; } @Override public Object deserialize(byte[] date) { Object anyBean = null; ByteArrayInputStream bis = null; ObjectInputStream ois = null; try { bis = new ByteArrayInputStream(date); ois = new ObjectInputStream(bis); try { anyBean = ois.readObject(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (ois != null) { try { ois.close(); } catch (IOException e) { e.printStackTrace(); } } } return anyBean; } public String toString(byte[] date) { return new String(date); } }
package com.jic.libin.leaderus.study002; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; /** * Created by andylee on 16/12/5. */ public class BinLeeStudy00201 { public static void main(String[] args) throws Exception { String s = "中国"; byte[] utf8Bytes = s.getBytes("UTF-8"); System.out.println("编码为UTF-8长度:"+utf8Bytes.length); for (int i = 0; i < utf8Bytes.length; i++) { System.out.print(Integer.toHexString(utf8Bytes[i]).substring(6).toUpperCase()); } System.out.println("转为编码为UTF-8:"+new String(utf8Bytes, "UTF-8")); byte[] gbkBytes = s.getBytes("GBK"); System.out.println("编码为GBK长度:"+gbkBytes.length); for (int i = 0; i < gbkBytes.length; i++) { System.out.print(Integer.toHexString(gbkBytes[i]).substring(6).toUpperCase()); } System.out.println("转为编码为GBK:"+new String(gbkBytes, "GBK")); byte[] isoBytes = s.getBytes("ISO-8859-1"); System.out.println("编码为ISO-8859-1长度:"+isoBytes.length); System.out.println("转为编码为ISO-8859-1:"+new String(isoBytes, "ISO-8859-1")); System.out.println("utf-8转为编码为gbk:"+new String(utf8Bytes, "GBK")); byte[] bytes = new byte[]{0x01}; System.out.println(new String(bytes, StandardCharsets.US_ASCII)); Files.write(Paths.get("/Users/andylee/temp.log"),bytes); } }
package eventtimeAndWaterMark; import entity.WaterSensor; import org.apache.flink.api.common.eventtime.*; import org.apache.flink.api.common.functions.MapFunction; import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction; import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows; import org.apache.flink.streaming.api.windowing.time.Time; import org.apache.flink.streaming.api.windowing.windows.TimeWindow; import org.apache.flink.util.Collector; /** * @author douglas * @create 2021-03-01 21:33 */ public class Flink11_Chapter07_Period { public static void main(String[] args) throws Exception { //创建流的执行环境 StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1); //封装为JavaBean SingleOutputStreamOperator<WaterSensor> stream = env .socketTextStream("hadoop102", 9999) .map(new MapFunction<String, WaterSensor>() { @Override public WaterSensor map(String s) throws Exception { String[] datas = s.split(","); return new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2])); } }); //创建水印生产策略 WatermarkStrategy<WaterSensor> myWms = new WatermarkStrategy<WaterSensor>() { @Override public WatermarkGenerator<WaterSensor> createWatermarkGenerator(WatermarkGeneratorSupplier.Context context) { System.out.println("createWatermarkGenertor..."); return new MyPeriod(3); } }.withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() { @Override public long extractTimestamp(WaterSensor waterSensor, long l) { System.out.println("recordTimestamp" + l); return waterSensor.getTs() * 1000; } }); stream .assignTimestampsAndWatermarks(myWms) .keyBy(WaterSensor::getId) .window(SlidingEventTimeWindows.of(Time.seconds(5),Time.seconds(5))) .process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() { @Override public void process(String key, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception { String msg = "当前key:"+key +"窗口:["+context.window().getStart()/1000+","+ context.window().getEnd()/1000+")一共有 " +elements.spliterator().estimateSize()+"条数据"; out.collect(context.window().toString()); out.collect(msg); } }) .print(); env.execute(); } public static class MyPeriod implements WatermarkGenerator<WaterSensor>{ private long maxTs=Long.MIN_VALUE; //允许的最大延迟时间 ms private final long maxDelay; public MyPeriod(long maxDelay) { this.maxDelay = maxDelay; this.maxTs=Long.MIN_VALUE+this.maxDelay+1; } //每收到一个元素,执行一次,用来生产waterMark中的时间戳 @Override public void onEvent(WaterSensor waterSensor, long l, WatermarkOutput watermarkOutput) { System.out.println("onEvent..."+l); //有了新的元素找到最大的时间戳 maxTs=Math.max(maxTs,l); System.out.println(maxTs); } //周期性的把WaterMark发射出去,默认周期是200ms @Override public void onPeriodicEmit(WatermarkOutput output) { //周期性的发射水印:相当于Flink把自己的始终调慢了一个最大延迟 output.emitWatermark(new Watermark(maxTs-maxDelay-1)); } } }
package com.sirma.itt.javacourse.inputoutput.task3.reverseTextFile; import java.io.FileNotFoundException; import org.apache.log4j.Logger; import com.sirma.itt.javacourse.InputUtils; import com.sirma.itt.javacourse.inputoutput.task2.consoleWritenFile.WriteFileFromConsole; /** * Class that runs the file reverser. * * @author simeon */ public class RunFileReverser { private static Logger log = Logger.getLogger(RunFileReverser.class.getName()); /** * Main method for FileReverser. * * @param args * arguments for the main method. */ public static void main(String[] args) { FileReverser reverser = new FileReverser(); WriteFileFromConsole writer = new WriteFileFromConsole(); try { InputUtils.printConsoleMessage("Input the name of the file you want to create and then reverse :"); String fileName = InputUtils.readLine(); writer.writeFile(fileName); reverser.reverseFileContent(WriteFileFromConsole.DIR_LOCALE + fileName); InputUtils.readFile(WriteFileFromConsole.DIR_LOCALE + fileName); } catch (FileNotFoundException e) { log.error("File coudn't be found", e); } } }
/** * Project: PipelineFramework * Package: org.sjsu.sidmishraw.examples.garbageband.core * File: DigitalComposer.java * * @author sidmishraw * Last modified: Apr 12, 2017 1:04:37 PM */ package org.sjsu.sidmishraw.examples.garbageband.core; import java.util.Random; import org.sjsu.sidmishraw.framework.pipeline.core.Pipe; import org.sjsu.sidmishraw.framework.pipeline.filters.Producer; /** * @author sidmishraw * * Qualified Name: * org.sjsu.sidmishraw.examples.garbageband.core.DigitalComposer * */ public class DigitalComposer extends Producer<Note> { private int noteCount = 0; /** * */ public DigitalComposer() { super(); } /** * @param inPipe * @param outPipe */ public DigitalComposer(Pipe<Note> inPipe, Pipe<Note> outPipe) { super(inPipe, outPipe); } /** * @return {@link Float} */ private final float generateFrequency() { Random random = new Random(); float frequency = random.nextFloat() * 1000; return frequency; } /** * @return {@link Float} */ private final float generateAmplitude() { Random random = new Random(); float amplitude = random.nextFloat() * 100; return amplitude; } /** * @return {@link Float} */ private final float generateDuration() { Random random = new Random(); float duration = random.nextFloat() * 1000; return duration; } /* * (non-Javadoc) * * @see org.sjsu.sidmishraw.framework.pipeline.filters.Producer#produce() */ @Override public Note produce() { float frequency = generateFrequency(); float amplitude = generateAmplitude(); float duration = generateDuration(); Note note = new Note(frequency, amplitude, duration); System.out.println("Composer: Produced note #" + noteCount + " having frequency=" + frequency + " amplitude=" + amplitude + " duration=" + duration); this.noteCount++; if (noteCount >= 100) { // need with the highest volume note.setAmplitude(Float.MAX_VALUE); this.shutdown(true); } return note; } }
package com.mibo.common.config; import com.alibaba.druid.wall.WallFilter; import com.jfinal.config.Constants; import com.jfinal.config.Handlers; import com.jfinal.config.Interceptors; import com.jfinal.config.JFinalConfig; import com.jfinal.config.Plugins; import com.jfinal.config.Routes; import com.jfinal.ext.handler.ContextPathHandler; import com.jfinal.json.MixedJsonFactory; import com.jfinal.kit.LogKit; import com.jfinal.kit.PathKit; import com.jfinal.kit.Prop; import com.jfinal.plugin.activerecord.ActiveRecordPlugin; import com.jfinal.plugin.druid.DruidPlugin; import com.jfinal.template.Engine; import com.mibo.common.constant.Global; import com.mibo.common.handler.NotFoundHandler; import com.mibo.common.interceptor.ErrorInterceptor; import com.mibo.common.route.AppRouter; import com.mibo.common.util.JedisUtil; import com.mibo.modules.data.model._MappingKit; public class SysConfig extends JFinalConfig { private static Prop p = Global.loadConfig(); public void configConstant(Constants me) { me.setJsonFactory(MixedJsonFactory.me()); me.setDevMode(p.getBoolean("devMode", Boolean.valueOf(false)).booleanValue()); me.setBaseUploadPath(p.get("uploadPath")); me.setMaxPostSize(104857600); me.setError404View("/common/404/404.html"); } public void configRoute(Routes me) { me.add(new AppRouter()); } public void configEngine(Engine me) { me.setDevMode(p.getBoolean("engineDevMode", Boolean.valueOf(false)).booleanValue()); } public static DruidPlugin createDruidPlugin() { return new DruidPlugin(p.get("jdbcUrl"), p.get("user"), p.get("password").trim()); } public void configPlugin(Plugins me) { DruidPlugin druidPlugin = createDruidPlugin(); WallFilter wallFilter = new WallFilter(); wallFilter.setDbType("mysql"); me.add(druidPlugin); ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin); arp.setBaseSqlTemplatePath(PathKit.getRootClassPath() + "/sql"); arp.addSqlTemplate("all.sql"); arp.setShowSql(p.getBoolean("showSql", Boolean.valueOf(false)).booleanValue()); _MappingKit.mapping(arp); me.add(arp); } public void configInterceptor(Interceptors me) { me.add(new ErrorInterceptor()); } public void configHandler(Handlers me) { me.add(new NotFoundHandler()); me.add(new ContextPathHandler("ctx")); } public void afterJFinalStart() { JedisUtil.del("RedisDevices"); LogKit.warn("执行清除所有设备key==========>"); } public void beforeJFinalStop() { } }
package com.develop.xdk.xl.nfc.attendacemachinergata.http.controller; import android.content.Context; import android.util.Log; import com.develop.xdk.xl.nfc.attendacemachinergata.MyService.myService; import com.develop.xdk.xl.nfc.attendacemachinergata.constant.C; import com.develop.xdk.xl.nfc.attendacemachinergata.entity.AccountidParam; import com.develop.xdk.xl.nfc.attendacemachinergata.entity.BaseParam; import com.develop.xdk.xl.nfc.attendacemachinergata.entity.CheckRecodParam; import com.develop.xdk.xl.nfc.attendacemachinergata.entity.ComsumeParam; import com.develop.xdk.xl.nfc.attendacemachinergata.entity.HttpResult; import com.develop.xdk.xl.nfc.attendacemachinergata.entity.PersonDossier; import com.develop.xdk.xl.nfc.attendacemachinergata.http.ApiException; import com.develop.xdk.xl.nfc.attendacemachinergata.http.HttpMethods; import com.develop.xdk.xl.nfc.attendacemachinergata.http.service.NfcService; import com.develop.xdk.xl.nfc.attendacemachinergata.http.subscribers.ProgressSubscriber; import com.develop.xdk.xl.nfc.attendacemachinergata.http.subscribers.SubscriberOnNextListener; import com.develop.xdk.xl.nfc.attendacemachinergata.utils.BeanUtil; import com.develop.xdk.xl.nfc.attendacemachinergata.utils.SharedPreferencesUtils; import com.develop.xdk.xl.nfc.attendacemachinergata.utils.SignUtil; import com.google.gson.Gson; import java.util.List; import java.util.SortedMap; import retrofit2.Retrofit; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; /** * Created by Administrator on 2018/6/11. */ public class RechargeController { private Retrofit retrofit; private NfcService NfcService; private RechargeController() { retrofit = HttpMethods.getInstance().getRetrofit(); NfcService = retrofit.create(NfcService.class); } //在访问HttpMethods时创建单例 private static class SingletonHolder { private static final RechargeController INSTANCE = new RechargeController(); } //获取单例 public static RechargeController getInstance() { return SingletonHolder.INSTANCE; } /** * 获取用户信息 * * @param onNextListener * @param context * @param cardid */ public void getUserinfo(SubscriberOnNextListener onNextListener, Context context, String cardid) throws ApiException { ProgressSubscriber subscriber = new ProgressSubscriber(onNextListener, context); BaseParam param = new BaseParam(); param.setCardid(cardid); param.setClientid((String) SharedPreferencesUtils.getParam(context, C.CLIENTID_NAME, C.CLIENTID)); param.setTimestamp(String.valueOf(System.currentTimeMillis())); SortedMap map = BeanUtil.ClassToMap(param); param.setSign(SignUtil.createSign(map, C.SIGN_KEY)); Observable observable = NfcService.getUserInfo(param) .map(new HttpResultFunc<PersonDossier>()); toSubscribe(observable, subscriber); Log.d("getUserinfo", new Gson().toJson(param)); } /** * 接收人员档案 * * @param onNextListener * @param context */ public void recepDossier(SubscriberOnNextListener onNextListener, Context context) { ProgressSubscriber subscriber = new ProgressSubscriber(onNextListener, context); ComsumeParam param = new ComsumeParam(); param.setComputer((String) SharedPreferencesUtils.getParam(context, C.COMPUTER_NAME, C.COMPUTER)); param.setClientid((String) SharedPreferencesUtils.getParam(context, C.CLIENTID_NAME, C.CLIENTID)); param.setWindowNumber((String) SharedPreferencesUtils.getParam(context, C.MACHINE_NAME, C.MACHINE)); param.setTimestamp(String.valueOf(System.currentTimeMillis())); SortedMap map = BeanUtil.ClassToMap(param); param.setSign(SignUtil.createSign(map, C.SIGN_KEY)); Observable observable = NfcService.recepDossior(param).map(new HttpResultFunc<List<PersonDossier>>()); toSubscribe(observable, subscriber); Log.d("recepDossier", "------------>" + new Gson().toJson(param)); } /** * 上传考勤记录 * * @param a_cardID 卡号 * @param a_attendMode 考勤模式 * @param a_inOrOutMode 进出放心 * @param at_data * @param subscriberOnNextListener 回调接口 * @param context */ public void updataAttends(String a_cardID, int a_attendMode, int a_inOrOutMode, String at_data, SubscriberOnNextListener subscriberOnNextListener, Context context) { ProgressSubscriber subscriber = new ProgressSubscriber(subscriberOnNextListener, context); String[] data = at_data.split("\\ "); String riqi = data[0]; String time = data[1]; CheckRecodParam param = new CheckRecodParam(); param.setCheckmac((String) SharedPreferencesUtils.getParam(context, C.CHECK_MAC_NAME, C.CHECK_MAC)); param.setChecktype(String.valueOf(a_attendMode)); param.setDate(riqi); param.setTime(time); param.setMactype(String.valueOf(C.MAC_TYPR)); param.setStyle(String.valueOf(a_inOrOutMode)); param.setCardid(a_cardID); param.setClientid((String) SharedPreferencesUtils.getParam(context, C.CLIENTID_NAME, C.CLIENTID)); param.setTimestamp(String.valueOf(System.currentTimeMillis())); SortedMap map = BeanUtil.ClassToMap(param); param.setSign(SignUtil.createSign(map, C.SIGN_KEY)); Observable observable = NfcService.updataAttends(param).map(new HttpResultFunc<PersonDossier>()); toSubscribe(observable, subscriber); Log.d("updataAttends", "------------>" + new Gson().toJson(param)); } /** * 获取用户头像 * * @param accountId * @param subscriberOnNextListener * @param context */ public void getHeadImage(String accountId, SubscriberOnNextListener subscriberOnNextListener, Context context) { ProgressSubscriber subscriber = new ProgressSubscriber(subscriberOnNextListener, context); AccountidParam param = new AccountidParam(); param.setAccountid(accountId); param.setClientid((String) SharedPreferencesUtils.getParam(context, C.CLIENTID_NAME, C.CLIENTID)); param.setTimestamp(String.valueOf(System.currentTimeMillis())); SortedMap map = BeanUtil.ClassToMap(param); param.setSign(SignUtil.createSign(map, C.SIGN_KEY)); Observable observable = NfcService.getHeadImage(param).map(new HttpResultFunc<String>()); toSubscribe(observable, subscriber); Log.d("getHeadImage", "--------------------->: " + new Gson().toJson(param)); } private <T> void toSubscribe(Observable<T> o, Subscriber<T> s) { o.subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(s); } /** * 用来统一处理Http的resultCode,并将HttpResult的Data部分剥离出来返回给subscriber * * @param <T> Subscriber真正需要的数据类型,也就是Data部分的数据类型 */ private class HttpResultFunc<T> implements Func1<HttpResult<T>, T> { @Override public T call(HttpResult<T> httpResult) { Log.e("result", new Gson().toJson(httpResult)); if (httpResult.getCode() == 0) { throw new ApiException(httpResult.getMsg()); } return httpResult.getData(); } } }
/** * -------------------------------------------------------------------------------------------------------------------- * <copyright company="Aspose Pty Ltd" file="SignImageOptions.java"> * Copyright (c) 2003-2023 Aspose Pty Ltd * </copyright> * <summary> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * </summary> * -------------------------------------------------------------------------------------------------------------------- */ package com.groupdocs.cloud.signature.model; import java.util.Objects; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.groupdocs.cloud.signature.model.BorderLine; import com.groupdocs.cloud.signature.model.Padding; import com.groupdocs.cloud.signature.model.PagesSetup; import com.groupdocs.cloud.signature.model.SignOptions; import com.groupdocs.cloud.signature.model.SignatureAppearance; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * Represents the Image sign options */ @ApiModel(description = "Represents the Image sign options") public class SignImageOptions extends SignOptions { @SerializedName("imageFilePath") private String imageFilePath = null; @SerializedName("left") private Integer left = null; @SerializedName("top") private Integer top = null; @SerializedName("width") private Integer width = null; @SerializedName("height") private Integer height = null; /** * Measure type (pixels or percent) for Left and Top properties */ @JsonAdapter(LocationMeasureTypeEnum.Adapter.class) public enum LocationMeasureTypeEnum { PIXELS("Pixels"), PERCENTS("Percents"), MILLIMETERS("Millimeters"); private String value; LocationMeasureTypeEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static LocationMeasureTypeEnum fromValue(String text) { for (LocationMeasureTypeEnum b : LocationMeasureTypeEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public static class Adapter extends TypeAdapter<LocationMeasureTypeEnum> { @Override public void write(final JsonWriter jsonWriter, final LocationMeasureTypeEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public LocationMeasureTypeEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return LocationMeasureTypeEnum.fromValue(String.valueOf(value)); } } } @SerializedName("locationMeasureType") private LocationMeasureTypeEnum locationMeasureType = null; /** * Measure type (pixels or percent) for Width and Height properties */ @JsonAdapter(SizeMeasureTypeEnum.Adapter.class) public enum SizeMeasureTypeEnum { PIXELS("Pixels"), PERCENTS("Percents"), MILLIMETERS("Millimeters"); private String value; SizeMeasureTypeEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static SizeMeasureTypeEnum fromValue(String text) { for (SizeMeasureTypeEnum b : SizeMeasureTypeEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public static class Adapter extends TypeAdapter<SizeMeasureTypeEnum> { @Override public void write(final JsonWriter jsonWriter, final SizeMeasureTypeEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public SizeMeasureTypeEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return SizeMeasureTypeEnum.fromValue(String.valueOf(value)); } } } @SerializedName("sizeMeasureType") private SizeMeasureTypeEnum sizeMeasureType = null; @SerializedName("rotationAngle") private Integer rotationAngle = null; /** * Horizontal alignment of signature on document page */ @JsonAdapter(HorizontalAlignmentEnum.Adapter.class) public enum HorizontalAlignmentEnum { NONE("None"), LEFT("Left"), CENTER("Center"), RIGHT("Right"); private String value; HorizontalAlignmentEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static HorizontalAlignmentEnum fromValue(String text) { for (HorizontalAlignmentEnum b : HorizontalAlignmentEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public static class Adapter extends TypeAdapter<HorizontalAlignmentEnum> { @Override public void write(final JsonWriter jsonWriter, final HorizontalAlignmentEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public HorizontalAlignmentEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return HorizontalAlignmentEnum.fromValue(String.valueOf(value)); } } } @SerializedName("horizontalAlignment") private HorizontalAlignmentEnum horizontalAlignment = null; /** * Vertical alignment of signature on document page */ @JsonAdapter(VerticalAlignmentEnum.Adapter.class) public enum VerticalAlignmentEnum { NONE("None"), TOP("Top"), CENTER("Center"), BOTTOM("Bottom"); private String value; VerticalAlignmentEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static VerticalAlignmentEnum fromValue(String text) { for (VerticalAlignmentEnum b : VerticalAlignmentEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public static class Adapter extends TypeAdapter<VerticalAlignmentEnum> { @Override public void write(final JsonWriter jsonWriter, final VerticalAlignmentEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public VerticalAlignmentEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return VerticalAlignmentEnum.fromValue(String.valueOf(value)); } } } @SerializedName("verticalAlignment") private VerticalAlignmentEnum verticalAlignment = null; @SerializedName("margin") private Padding margin = null; /** * Gets or sets the measure type (pixels or percent) for Margin */ @JsonAdapter(MarginMeasureTypeEnum.Adapter.class) public enum MarginMeasureTypeEnum { PIXELS("Pixels"), PERCENTS("Percents"), MILLIMETERS("Millimeters"); private String value; MarginMeasureTypeEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static MarginMeasureTypeEnum fromValue(String text) { for (MarginMeasureTypeEnum b : MarginMeasureTypeEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public static class Adapter extends TypeAdapter<MarginMeasureTypeEnum> { @Override public void write(final JsonWriter jsonWriter, final MarginMeasureTypeEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public MarginMeasureTypeEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return MarginMeasureTypeEnum.fromValue(String.valueOf(value)); } } } @SerializedName("marginMeasureType") private MarginMeasureTypeEnum marginMeasureType = null; @SerializedName("transparency") private Double transparency = null; @SerializedName("border") private BorderLine border = null; public SignImageOptions imageFilePath(String imageFilePath) { this.imageFilePath = imageFilePath; return this; } /** * Gets or sets the signature image file name. This property is used only if ImageStream is not specified * @return imageFilePath **/ @ApiModelProperty(value = "Gets or sets the signature image file name. This property is used only if ImageStream is not specified") public String getImageFilePath() { return imageFilePath; } public void setImageFilePath(String imageFilePath) { this.imageFilePath = imageFilePath; } public SignImageOptions left(Integer left) { this.left = left; return this; } /** * Left X position of Signature on Document Page in Measure values (pixels or percent see MeasureType LocationMeasureType). (works if horizontal alignment is not specified). For Spreadsheet documents this property is mutually exclusive with Column property. If Left property is set ColumnNumber will be reset to 0 * @return left **/ @ApiModelProperty(required = true, value = "Left X position of Signature on Document Page in Measure values (pixels or percent see MeasureType LocationMeasureType). (works if horizontal alignment is not specified). For Spreadsheet documents this property is mutually exclusive with Column property. If Left property is set ColumnNumber will be reset to 0") public Integer getLeft() { return left; } public void setLeft(Integer left) { this.left = left; } public SignImageOptions top(Integer top) { this.top = top; return this; } /** * Top Y Position of Signature on Document Page in Measure values (pixels or percent see MeasureType LocationMeasureType). (works if vertical alignment is not specified). For Spreadsheet documents this property is mutually exclusive with Row property. If Top property is set RowNumber will be reset to 0 * @return top **/ @ApiModelProperty(required = true, value = "Top Y Position of Signature on Document Page in Measure values (pixels or percent see MeasureType LocationMeasureType). (works if vertical alignment is not specified). For Spreadsheet documents this property is mutually exclusive with Row property. If Top property is set RowNumber will be reset to 0") public Integer getTop() { return top; } public void setTop(Integer top) { this.top = top; } public SignImageOptions width(Integer width) { this.width = width; return this; } /** * Width of Signature on Document Page in Measure values (pixels or percent see MeasureType SizeMeasureType) * @return width **/ @ApiModelProperty(required = true, value = "Width of Signature on Document Page in Measure values (pixels or percent see MeasureType SizeMeasureType)") public Integer getWidth() { return width; } public void setWidth(Integer width) { this.width = width; } public SignImageOptions height(Integer height) { this.height = height; return this; } /** * Height of Signature on Document Page in Measure values (pixels or percent see MeasureType SizeMeasureType) * @return height **/ @ApiModelProperty(required = true, value = "Height of Signature on Document Page in Measure values (pixels or percent see MeasureType SizeMeasureType)") public Integer getHeight() { return height; } public void setHeight(Integer height) { this.height = height; } public SignImageOptions locationMeasureType(LocationMeasureTypeEnum locationMeasureType) { this.locationMeasureType = locationMeasureType; return this; } /** * Measure type (pixels or percent) for Left and Top properties * @return locationMeasureType **/ @ApiModelProperty(required = true, value = "Measure type (pixels or percent) for Left and Top properties") public LocationMeasureTypeEnum getLocationMeasureType() { return locationMeasureType; } public void setLocationMeasureType(LocationMeasureTypeEnum locationMeasureType) { this.locationMeasureType = locationMeasureType; } public SignImageOptions sizeMeasureType(SizeMeasureTypeEnum sizeMeasureType) { this.sizeMeasureType = sizeMeasureType; return this; } /** * Measure type (pixels or percent) for Width and Height properties * @return sizeMeasureType **/ @ApiModelProperty(required = true, value = "Measure type (pixels or percent) for Width and Height properties") public SizeMeasureTypeEnum getSizeMeasureType() { return sizeMeasureType; } public void setSizeMeasureType(SizeMeasureTypeEnum sizeMeasureType) { this.sizeMeasureType = sizeMeasureType; } public SignImageOptions rotationAngle(Integer rotationAngle) { this.rotationAngle = rotationAngle; return this; } /** * Rotation angle of signature on document page (clockwise) * @return rotationAngle **/ @ApiModelProperty(required = true, value = "Rotation angle of signature on document page (clockwise)") public Integer getRotationAngle() { return rotationAngle; } public void setRotationAngle(Integer rotationAngle) { this.rotationAngle = rotationAngle; } public SignImageOptions horizontalAlignment(HorizontalAlignmentEnum horizontalAlignment) { this.horizontalAlignment = horizontalAlignment; return this; } /** * Horizontal alignment of signature on document page * @return horizontalAlignment **/ @ApiModelProperty(required = true, value = "Horizontal alignment of signature on document page") public HorizontalAlignmentEnum getHorizontalAlignment() { return horizontalAlignment; } public void setHorizontalAlignment(HorizontalAlignmentEnum horizontalAlignment) { this.horizontalAlignment = horizontalAlignment; } public SignImageOptions verticalAlignment(VerticalAlignmentEnum verticalAlignment) { this.verticalAlignment = verticalAlignment; return this; } /** * Vertical alignment of signature on document page * @return verticalAlignment **/ @ApiModelProperty(required = true, value = "Vertical alignment of signature on document page") public VerticalAlignmentEnum getVerticalAlignment() { return verticalAlignment; } public void setVerticalAlignment(VerticalAlignmentEnum verticalAlignment) { this.verticalAlignment = verticalAlignment; } public SignImageOptions margin(Padding margin) { this.margin = margin; return this; } /** * Gets or sets the space between Sign and Document edges (works ONLY if horizontal or vertical alignment are specified) * @return margin **/ @ApiModelProperty(value = "Gets or sets the space between Sign and Document edges (works ONLY if horizontal or vertical alignment are specified)") public Padding getMargin() { return margin; } public void setMargin(Padding margin) { this.margin = margin; } public SignImageOptions marginMeasureType(MarginMeasureTypeEnum marginMeasureType) { this.marginMeasureType = marginMeasureType; return this; } /** * Gets or sets the measure type (pixels or percent) for Margin * @return marginMeasureType **/ @ApiModelProperty(required = true, value = "Gets or sets the measure type (pixels or percent) for Margin") public MarginMeasureTypeEnum getMarginMeasureType() { return marginMeasureType; } public void setMarginMeasureType(MarginMeasureTypeEnum marginMeasureType) { this.marginMeasureType = marginMeasureType; } public SignImageOptions transparency(Double transparency) { this.transparency = transparency; return this; } /** * Gets or sets the signature transparency(value from 0.0 (opaque) through 1.0 (clear)). Default value is 0 (opaque). * @return transparency **/ @ApiModelProperty(required = true, value = "Gets or sets the signature transparency(value from 0.0 (opaque) through 1.0 (clear)). Default value is 0 (opaque).") public Double getTransparency() { return transparency; } public void setTransparency(Double transparency) { this.transparency = transparency; } public SignImageOptions border(BorderLine border) { this.border = border; return this; } /** * Gets or sets the signature border properties * @return border **/ @ApiModelProperty(value = "Gets or sets the signature border properties") public BorderLine getBorder() { return border; } public void setBorder(BorderLine border) { this.border = border; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SignImageOptions signImageOptions = (SignImageOptions) o; return Objects.equals(this.imageFilePath, signImageOptions.imageFilePath) && Objects.equals(this.left, signImageOptions.left) && Objects.equals(this.top, signImageOptions.top) && Objects.equals(this.width, signImageOptions.width) && Objects.equals(this.height, signImageOptions.height) && Objects.equals(this.locationMeasureType, signImageOptions.locationMeasureType) && Objects.equals(this.sizeMeasureType, signImageOptions.sizeMeasureType) && Objects.equals(this.rotationAngle, signImageOptions.rotationAngle) && Objects.equals(this.horizontalAlignment, signImageOptions.horizontalAlignment) && Objects.equals(this.verticalAlignment, signImageOptions.verticalAlignment) && Objects.equals(this.margin, signImageOptions.margin) && Objects.equals(this.marginMeasureType, signImageOptions.marginMeasureType) && Objects.equals(this.transparency, signImageOptions.transparency) && Objects.equals(this.border, signImageOptions.border) && super.equals(o); } @Override public int hashCode() { return Objects.hash(imageFilePath, left, top, width, height, locationMeasureType, sizeMeasureType, rotationAngle, horizontalAlignment, verticalAlignment, margin, marginMeasureType, transparency, border, super.hashCode()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class SignImageOptions {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" imageFilePath: ").append(toIndentedString(imageFilePath)).append("\n"); sb.append(" left: ").append(toIndentedString(left)).append("\n"); sb.append(" top: ").append(toIndentedString(top)).append("\n"); sb.append(" width: ").append(toIndentedString(width)).append("\n"); sb.append(" height: ").append(toIndentedString(height)).append("\n"); sb.append(" locationMeasureType: ").append(toIndentedString(locationMeasureType)).append("\n"); sb.append(" sizeMeasureType: ").append(toIndentedString(sizeMeasureType)).append("\n"); sb.append(" rotationAngle: ").append(toIndentedString(rotationAngle)).append("\n"); sb.append(" horizontalAlignment: ").append(toIndentedString(horizontalAlignment)).append("\n"); sb.append(" verticalAlignment: ").append(toIndentedString(verticalAlignment)).append("\n"); sb.append(" margin: ").append(toIndentedString(margin)).append("\n"); sb.append(" marginMeasureType: ").append(toIndentedString(marginMeasureType)).append("\n"); sb.append(" transparency: ").append(toIndentedString(transparency)).append("\n"); sb.append(" border: ").append(toIndentedString(border)).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 "); } }
package org.softRoad.models; import org.softRoad.models.query.QueryUtils; import javax.persistence.Table; @Table(name = "consultant_profile_tag") public class ConsultantProfileTag { public final static String CONSULTANT_ID = "consultant_id"; public final static String TAG_ID = "tag_id"; public static String fields(String fieldName, String ... fieldNames) { return QueryUtils.fields(ConsultantProfileTag.class, fieldName, fieldNames); } }
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.http; import java.io.IOException; import java.io.OutputStream; /** * Represents an HTTP output message that allows for setting a streaming body. * Note that such messages typically do not support {@link #getBody()} access. * * @author Arjen Poutsma * @since 4.0 * @see #setBody */ public interface StreamingHttpOutputMessage extends HttpOutputMessage { /** * Set the streaming body callback for this message. * @param body the streaming body callback */ void setBody(Body body); /** * Defines the contract for bodies that can be written directly to an * {@link OutputStream}. Useful with HTTP client libraries that provide * indirect access to an {@link OutputStream} via a callback mechanism. */ @FunctionalInterface interface Body { /** * Write this body to the given {@link OutputStream}. * @param outputStream the output stream to write to * @throws IOException in case of I/O errors */ void writeTo(OutputStream outputStream) throws IOException; } }
/* * 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.pmm.sdgc.model; import java.io.Serializable; import java.time.LocalDateTime; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.NotFound; import org.hibernate.annotations.NotFoundAction; /** * * @author ajuliano */ @Entity @Table(name = "requerimento_historico") public class RequerimentoHistorico implements Serializable { //VAR private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Integer id; @ManyToOne @JoinColumn(name = "id_requerimento", referencedColumnName = "id") @NotFound(action = NotFoundAction.IGNORE) private Requerimento requerimento; @ManyToOne @JoinColumn(name = "id_requerimento_status", referencedColumnName = "id") @NotFound(action = NotFoundAction.IGNORE) private RequerimentoStatus reqStatus; @Column(name = "datahora") private LocalDateTime data; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Requerimento getRequerimento() { return requerimento; } public void setRequerimento(Requerimento requerimento) { this.requerimento = requerimento; } public RequerimentoStatus getReqStatus() { return reqStatus; } public void setReqStatus(RequerimentoStatus reqStatus) { this.reqStatus = reqStatus; } public LocalDateTime getData() { return data; } public void setData(LocalDateTime data) { this.data = data; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + Objects.hashCode(this.id); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final RequerimentoHistorico other = (RequerimentoHistorico) obj; if (!Objects.equals(this.id, other.id)) { return false; } return true; } }
package heylichen.alg.graph.structure.weighted.mst; import heylichen.alg.graph.structure.weighted.WeightedEdge; /** * @author lichen * @date 2020/4/8 15:41 * @desc */ public interface MST { Iterable<WeightedEdge> edges(); double weight(); }
package com.ctt.web.service; import com.ctt.constant.UserStatusEnum; import com.ctt.mapper.UserMapper; import com.ctt.response.WebResBean; import com.ctt.utils.EncryptUtil; import com.alibaba.fastjson.JSONObject; import org.springframework.stereotype.Service; import org.springframework.web.HttpRequestMethodNotSupportedException; import javax.annotation.Resource; /** * @Description用户操作类 * @auther Administrator * @create 2020-03-05 上午 11:00 */ @Service public class UserService { @Resource private UserMapper userMapper; public WebResBean login(String userName,String pwd) throws HttpRequestMethodNotSupportedException { JSONObject js = userMapper.findUserByUserNameAndPwd(userName,pwd); WebResBean rsb = new WebResBean(); if(js == null){ rsb.setMessage(UserStatusEnum.S_5.getMessage()); } int status = js.getIntValue("status"); if(status == UserStatusEnum.S_2.getStatus()){ rsb.setMessage(UserStatusEnum.S_2.getMessage()); } rsb.setData(EncryptUtil.aesEncrypt(userName + ":" + pwd + ":" + EncryptUtil.getKey())); return rsb; } public WebResBean getInfo(String token){ WebResBean rsb = new WebResBean(); rsb.setData(userMapper.getInfo(EncryptUtil.getUserName(token))); return rsb; } }
package kr.co.people_gram.app; /** * Created by 광희 on 2015-10-02. */ public class PeopleData { static String people_uid = ""; static String people_mood = ""; static String people_type = ""; static String people_username = ""; static String people_gubun1 = ""; static String people_gubun2 = ""; static int people_speed = 0; static int people_control = 0; public void set_people_uid(String people_uid) { this.people_uid = people_uid; } public String get_people_uid() { return this.people_uid; } public void set_people_username(String people_username) { this.people_username = people_username; } public String get_people_username() { return this.people_username; } public void set_people_mood(String people_mood) { this.people_mood = people_mood; } public String get_people_mood() { return this.people_mood; } public void set_people_type(String people_type) { this.people_type = people_type; } public String get_people_type() { return this.people_type; } public void set_people_gubun1(String people_gubun1) { this.people_gubun1 = people_gubun1; } public String get_people_gubun1() { return this.people_gubun1; } public void set_people_gubun2(String people_gubun2) { this.people_gubun2 = people_gubun2; } public String get_people_gubun2() { return this.people_gubun2; } public void set_people_speed(int people_speed) { this.people_speed = people_speed; } public int get_people_speed() { return this.people_speed; } public void set_people_control(int people_control) { this.people_control = people_control; } public int get_people_control() { return this.people_control; } }
package br.edu.fsma.fiscalizacao.main.repository; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import br.edu.fsma.fiscalizacao.main.model.Bairro; import br.edu.fsma.fiscalizacao.main.model.Municipio; public interface BairroRepository extends JpaRepository<Bairro, String>{ Optional<Bairro> findByNome(String nome); Optional<Bairro> findByNomeAndMunicipio(String nome, Municipio Municipio); }
package david.socket_communication_rpi; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.net.Uri; import android.net.wifi.WifiManager; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.common.api.GoogleApiClient; import java.math.BigInteger; import java.net.*; import java.lang.*; import java.io.*; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import android.os.Vibrator; public class IP_Selection extends AppCompatActivity { private void saveToFile(String fname, String content) { FileOutputStream fos = null; Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); if (isSDPresent) { try { String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Festival-IP/"; File storageFile = new File(path); if (!storageFile.exists()) { storageFile.mkdirs(); } final File textFile = new File(storageFile, fname + ".txt"); if (!textFile.exists()) { textFile.createNewFile(); } fos = new FileOutputStream(textFile); fos.write(content.getBytes()); fos.close(); } catch (IOException e) { } } else { try { String file = fname + ".txt"; FileOutputStream fOut = openFileOutput(file, MODE_PRIVATE); fOut.write(content.getBytes()); fOut.close(); } catch (IOException e) { System.out.println("IOEXCEPTION"); } } } private void removeFile(String fname) { File file = new File(fname); file.delete(); } private String readFile(String fname) { Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); if (isSDPresent) { File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/Festival-IP/" + fname + ".txt"); StringBuilder text = new StringBuilder(); try { BufferedReader br = new BufferedReader(new FileReader(file)); String line; if ((line = br.readLine()) != null) { text.append(line); } br.close(); } catch (IOException e) { //You'll need to add proper error handling here return "none"; } return text.toString(); } else { StringBuilder text = new StringBuilder(); try { FileInputStream fin = openFileInput(fname + ".txt"); int c; String temp = ""; while ((c = fin.read()) != -1) { temp = temp + Character.toString((char) c); } fin.close(); return temp; } catch (IOException e) { } } return ""; } double abs(double a){ return a >= 0 ? a : -a; } double[] col = {0,0,0}; boolean recoloring = false; double r = 0; double g = 0; double b = 0; boolean shiftColor(double r, double g, double b, int thres, int velo){ if(thres < velo) thres = velo; int thres2 = velo+1; boolean diverging = false; double fr=1, fg=1, fb = 1; if(abs(r - col[0]) > thres2) fr *= velo; if(abs(g - col[1]) > thres2) fg *= velo; if(abs(b - col[2]) > thres2) fb *= velo; if(abs(r - col[0]) > thres & r - col[0] > 0){ col[0] += fr; diverging = true;} if(abs(r - col[0]) > thres & r - col[0] < 0){ col[0] -= fr; diverging = true;} if(abs(g - col[1]) > thres & g - col[1] > 0){ col[1] += fg; diverging = true;} if(abs(g - col[1]) > thres & g - col[1] < 0){ col[1] -= fg; diverging = true;} if(abs(b - col[2]) > thres & b - col[2] > 0){ col[2] += fb; diverging = true;} if(abs(b - col[2]) > thres & b - col[2] < 0){col[2] -= fb; diverging = true;} return diverging; } void recolor(TextView tView, double red, double green, double blue) { final IP_Selection here = this; final TextView there = tView; r = red; g = green; b = blue; //create a new gradient color final GradientDrawable rg = new GradientDrawable(); rg.setGradientType(GradientDrawable.RADIAL_GRADIENT); rg.setGradientRadius(800); new Thread(new Runnable() { @Override public void run() { if(!recoloring) { recoloring = true; while (shiftColor(r, g, b, 10, 5)) { here.runOnUiThread(new Runnable() { @Override public void run() { int combinedColor = (0xff << 24) + ((int) col[0] << 16) + ((int) col[1] << 8) + ((int) col[2]); int[] color = {combinedColor, Color.parseColor("#00000000")};//Color.parseColor(cString) float pos = (float)col[0] + (float)col[1] + (float)col[2]; pos = pos / 785.0f; rg.setGradientCenter(0.2f+(0.6f*pos), 0.2f+(0.6f*pos)); rg.setColors(color); there.setBackground(rg); } }); WAIT(10); } recoloring = false; } } }).start(); } private IP_Selection mainReference = this; private void WAIT(int millis) { try { Thread.sleep(millis); } catch (Exception e) { } } public static boolean validIP(String ip) { try { if (ip == null || ip.isEmpty()) { return false; } String[] parts = ip.split("\\."); if (parts.length != 4) { return false; } for (String s : parts) { int i = Integer.parseInt(s); if ((i < 0) || (i > 255)) { return false; } } if (ip.endsWith(".")) { return false; } return true; } catch (NumberFormatException nfe) { return false; } } protected String wifiIpAddress(Context context) { WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE); int ipAddress = wifiManager.getConnectionInfo().getIpAddress(); // Convert little-endian to big-endianif needed if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) { ipAddress = Integer.reverseBytes(ipAddress); } byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray(); String ipAddressString; try { ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress(); } catch (UnknownHostException ex) { Log.e("WIFIIP", "Unable to get host address."); ipAddressString = null; } return ipAddressString; } private GoogleApiClient client; @Override public void onConfigurationChanged(Configuration newConfig) { // ignore orientation change if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ip__selection); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); final EditText ipField = (EditText) findViewById(R.id.ip_text); ipField.bringToFront(); ipField.invalidate(); final TextView colorInd = (TextView) findViewById(R.id.color_indicator); final SeekBar redBar = (SeekBar) findViewById(R.id.red_slider); final SeekBar greenBar = (SeekBar) findViewById(R.id.green_slider); final SeekBar blueBar = (SeekBar) findViewById(R.id.blue_slider); redBar.setMax(255); greenBar.setMax(255); blueBar.setMax(255); redBar.setProgress(255 / 2); greenBar.setProgress(255 / 2); blueBar.setProgress(255/2); recolor(colorInd, 255/2,255/2,255/2); int actionBarTitleId = Resources.getSystem().getIdentifier("action_bar_title", "id", "android"); if (actionBarTitleId > 0) { TextView title = (TextView) findViewById(actionBarTitleId); if (title != null) { title.setTextColor(Color.BLACK); } } String savedIP = readFile("FestivalIP"); if (validIP(savedIP)) { ipField.setText(savedIP); } else{ ipField.setText("192.168.0.2"); } colorInd.setOnClickListener(new View.OnClickListener() { Context context = getApplicationContext(); @Override public void onClick(View v) { Vibrator vib = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE); vib.vibrate(30); } }); findViewById(R.id.start_btn).setOnClickListener(new View.OnClickListener() { Context context = getApplicationContext(); @Override public void onClick(View v) { Vibrator vib = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE); vib.vibrate(30); } }); redBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { recolor(colorInd, redBar.getProgress(), g, b); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); greenBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { recolor(colorInd, r, greenBar.getProgress(), b); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); blueBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { recolor(colorInd, r, g, blueBar.getProgress()); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); findViewById(R.id.save_btn).setOnClickListener(new View.OnClickListener() { Context context = getApplicationContext(); @Override public void onClick(View v) { if (validIP(ipField.getText().toString())) { removeFile(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Festival-IP/FestivalIP.txt"); saveToFile("FestivalIP", ipField.getText().toString()); Toast.makeText(context, "Gespeichert", Toast.LENGTH_SHORT).show(); Vibrator vib = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE); vib.vibrate(30); } else { Toast.makeText(context, "Please enter a valid IPv4-address", Toast.LENGTH_SHORT).show(); } } }); findViewById(R.id.remove_btn).setOnClickListener(new View.OnClickListener() { Context context = getApplicationContext(); @Override public void onClick(View v) { ipField.setText(""); Vibrator vib = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE); vib.vibrate(30); } }); client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); } @Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Farbauswahl", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://david.festival_color_selection/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); } @Override public void onStop() { super.onStop(); finish(); System.exit(0); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Farbauswahl", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://david.festival_color_selection/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); } }
import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class PassForFieldController { private int operNumb=0; Stage stage; @FXML Button button; @FXML TextField tf1; @FXML PasswordField tf2; private Main mainApp; public void setMainApp(Main mainApp) { this.mainApp = mainApp; } public int getOperNumb() { return operNumb; } public void setOperNumb(int operNumb) { this.operNumb = operNumb; } @FXML private void clickOk(ActionEvent event){ try { Passwords pass = new Passwords(); String currLogin = tf1.getText().toString(); String currPass = tf2.getText().toString(); if (operNumb == 1) { //1 Field if (currLogin.equals(pass.field1Login) && currPass.equals(pass.field1Pass)) { FXMLLoader loader = new FXMLLoader(getClass().getResource("AddDataFieldLayout.fxml")); AnchorPane PSF = (AnchorPane) loader.load(); AddDataFieldLayoutController addFieldController = loader.getController(); addFieldController.setMainApp(mainApp); addFieldController.setNumbField(1); Scene PSFScene = new Scene(PSF, 230, 100); Stage newWindow = new Stage(); newWindow.setTitle("Add data"); newWindow.setScene(PSFScene); newWindow.setHeight(300); newWindow.setWidth(550); newWindow.setX(mainApp.primaryStage.getX() + 200); newWindow.setY(mainApp.primaryStage.getY() + 100); newWindow.setResizable(false); newWindow.show(); closeStage(); } //2 Field else if (currLogin.equals(pass.field2Login) && currPass.equals(pass.field2Pass)) { FXMLLoader loader = new FXMLLoader(getClass().getResource("AddDataFieldLayout.fxml")); AnchorPane PSF = (AnchorPane) loader.load(); AddDataFieldLayoutController addFieldController = loader.getController(); addFieldController.setMainApp(mainApp); addFieldController.setNumbField(2); Scene PSFScene = new Scene(PSF, 230, 100); Stage newWindow = new Stage(); newWindow.setTitle("Add data"); newWindow.setScene(PSFScene); newWindow.setHeight(300); newWindow.setWidth(550); // Set position of second window, related to primary window. newWindow.setX(mainApp.primaryStage.getX() + 200); newWindow.setY(mainApp.primaryStage.getY() + 100); newWindow.setResizable(false); newWindow.show(); closeStage(); } //3 Field else if (currLogin.equals(pass.field3Login) && currPass.equals(pass.field3Pass)) { FXMLLoader loader = new FXMLLoader(getClass().getResource("AddDataFieldLayout.fxml")); AnchorPane PSF = (AnchorPane) loader.load(); AddDataFieldLayoutController addFieldController = loader.getController(); addFieldController.setMainApp(mainApp); addFieldController.setNumbField(3); Scene PSFScene = new Scene(PSF, 230, 100); Stage newWindow = new Stage(); newWindow.setTitle("Add data"); newWindow.setScene(PSFScene); newWindow.setHeight(300); newWindow.setWidth(550); // Set position of second window, related to primary window. newWindow.setX(mainApp.primaryStage.getX() + 200); newWindow.setY(mainApp.primaryStage.getY() + 100); newWindow.setResizable(false); newWindow.show(); closeStage(); } else { getIncorrectError(); } }else if (operNumb ==2 ){ if (currLogin.equals(pass.field1Login) && currPass.equals(pass.field1Pass)) { FXMLLoader loader = new FXMLLoader(getClass().getResource("MessageForBossLayout.fxml")); AnchorPane PSF = (AnchorPane) loader.load(); MessageForBossController MFBC = loader.getController(); MFBC.setMainApp(mainApp); MFBC.setNumbField(1); Scene PSFScene = new Scene(PSF, 230, 100); Stage newWindow = new Stage(); newWindow.setTitle("Add data"); newWindow.setScene(PSFScene); newWindow.setHeight(300); newWindow.setWidth(550); // Set position of second window, related to primary window. newWindow.setX(mainApp.primaryStage.getX() + 200); newWindow.setY(mainApp.primaryStage.getY() + 100); newWindow.setResizable(false); newWindow.show(); closeStage(); } //2 Field else if (currLogin.equals(pass.field2Login) && currPass.equals(pass.field2Pass)) { FXMLLoader loader = new FXMLLoader(getClass().getResource("MessageForBossLayout.fxml")); AnchorPane PSF = (AnchorPane) loader.load(); MessageForBossController MFBC = loader.getController(); MFBC.setMainApp(mainApp); MFBC.setNumbField(2); Scene PSFScene = new Scene(PSF, 230, 100); Stage newWindow = new Stage(); newWindow.setTitle("Add data"); newWindow.setScene(PSFScene); newWindow.setHeight(300); newWindow.setWidth(550); // Set position of second window, related to primary window. newWindow.setX(mainApp.primaryStage.getX() + 200); newWindow.setY(mainApp.primaryStage.getY() + 100); newWindow.setResizable(false); newWindow.show(); closeStage(); } //3 Field else if (currLogin.equals(pass.field3Login) && currPass.equals(pass.field3Pass)) { FXMLLoader loader = new FXMLLoader(getClass().getResource("MessageForBossLayout.fxml")); AnchorPane PSF = (AnchorPane) loader.load(); MessageForBossController MFBC = loader.getController(); MFBC.setMainApp(mainApp); MFBC.setNumbField(3); Scene PSFScene = new Scene(PSF, 230, 100); Stage newWindow = new Stage(); newWindow.setTitle("Add data"); newWindow.setScene(PSFScene); newWindow.setHeight(300); newWindow.setWidth(550); // Set position of second window, related to primary window. newWindow.setX(mainApp.primaryStage.getX() + 200); newWindow.setY(mainApp.primaryStage.getY() + 100); newWindow.setResizable(false); newWindow.show(); closeStage(); } else { getIncorrectError(); } } } catch (Exception ex){ System.out.println(ex.getMessage()); } } public void getIncorrectError(){ Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error alert"); alert.setHeaderText("Incorrect login or password"); VBox dialogPaneContent = new VBox(); alert.getDialogPane().setContent(dialogPaneContent); alert.showAndWait(); } public void closeStage(){ stage = (Stage) button.getScene().getWindow(); stage.close(); } }
package com.example.shivani.shivani; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.ArrayList; /** * Created by shivani on 8/7/17. */ public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> { interface ItemClickListener { void onClick(View view, int position, Users users); void deleteItem(Users user); void favourite(Users user); } private ItemClickListener clickListener; public void removeItem(int position, ArrayList<Users> userData) { Log.d("RecyclerViewAdapter", "in removeItem"); if (clickListener != null && userData != null && userData.size() > 0) { Users user = userData.get(position); clickListener.deleteItem(user); userData.remove(position); notifyItemRemoved(position); notifyDataSetChanged(); } } public void addToFavourite(int position, ArrayList<Users> userData) { Log.d("RecyclerViewAdapter", "in addToFavourite"); if (clickListener != null && userData != null && userData.size() > 0) { Users user = userData.get(position); clickListener.favourite(user); notifyDataSetChanged(); } } public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { // Your holder should contain a member variable // for any view that will be set as you render a row public ImageView imageView; public TextView textView; public ImageView thumbimage; Users user; // We also create a constructor that accepts the entire item row // and does the view lookups to find each subview public ViewHolder(View itemView) { // Stores the itemView in a public final member variable that can be used // to access the context from any ViewHolder instance. super(itemView); imageView = itemView.findViewById(R.id.thumbimage); textView = itemView.findViewById(R.id.title); thumbimage = itemView.findViewById(R.id.image); itemView.setClickable(true); itemView.setOnClickListener(this); } @Override public void onClick(View view) { if (clickListener != null) clickListener.onClick(view, getAdapterPosition(), user); } public void setuser(Users user) { this.user = user; } } private ArrayList<Users> mUsers; private Context mContext; public UserAdapter(Context context, ArrayList<Users> Users) { mUsers = Users; mContext = context; } private Context getContext() { return mContext; } @Override public UserAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Context context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); // Inflate the custom layout View contactView = inflater.inflate(R.layout.list_item, parent, false); // Return a new holder instance ViewHolder viewHolder = new ViewHolder(contactView); return viewHolder; } // Involves populating data into the item through holder @Override public void onBindViewHolder(UserAdapter.ViewHolder viewHolder, int position) { // Get the data model based on position viewHolder.setIsRecyclable(false); Users users = mUsers.get(position); // Set item views based on your views and data model viewHolder.setuser(users); viewHolder.textView.setText(users.getTitle()); Picasso.with(mContext) .load(users.getthumburl()) .into(viewHolder.imageView); } // Returns the total count of items in the list @Override public int getItemCount() { return mUsers.size(); } public void setClickListener(ItemClickListener itemClickListener) { this.clickListener = itemClickListener; } }
package com.huawei.myhealth.java.database.entity; import androidx.annotation.NonNull; import androidx.recyclerview.widget.DiffUtil; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; import java.util.Objects; /** * @author Huawei DTSE India * @since 2020 */ @Entity(tableName = "food_nutrients_insight") public class FoodNutrientsInsight { @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "food_id") private int foodId; @ColumnInfo(name = "food_name") private String foodName; @ColumnInfo(name = "food_portion_type") private String foodPortionType; @ColumnInfo(name = "food_portion") private int foodPortion; @ColumnInfo(name = "thumbnail") private String foodThumbnail; @ColumnInfo(name = "full_pic") private String foodFullPic; @ColumnInfo(name = "energy") // In Calorie private int energyKCal; @ColumnInfo(name = "protein") // In Grams private String protein; @ColumnInfo(name = "total_lipid_fat") //In Grams private String totalLipidFat; @ColumnInfo(name = "carbohydrate") //In Grams private String carbohydrate; @ColumnInfo(name = "fiber_total_dietary") //In Grams private String fiberTotalDietary; @ColumnInfo(name = "sugars_total_including_nlea") //In Grams private String sugarsTotalIncludingNLEA; @ColumnInfo(name = "calcium_ca") //In Milli Grams private String calciumCa; @ColumnInfo(name = "iron_fe") //In Milli Grams private String ironFe; @ColumnInfo(name = "sodium_na") //In Milli Grams private String sodiumNa; @ColumnInfo(name = "potassium_k") //In Milli Grams private String potassiumK; @ColumnInfo(name = "iodine_i") private String iodineI; @ColumnInfo(name = "zinc_zn") private String zincZn; @ColumnInfo(name = "magnesium_mg") private String magnesiumMg; @ColumnInfo(name = "cholesterol_mg") //In Milli Grams private String cholesterolMg; @ColumnInfo(name = "fatty_acid_saturated") //In Grams private String fattyAcidSaturated; @ColumnInfo(name = "fatty_acid_monounsaturated") //In Grams private String fattyAcidMonounsaturated; @ColumnInfo(name = "fatty_acid_polyunsaturated") //In Grams private String fattyAcidPolyunsaturated; @ColumnInfo(name = "fatty_acid_trans") //In Grams private String fattyAcidTrans; @ColumnInfo(name = "vitamin_a") private String vitaminA; @ColumnInfo(name = "vitamin_b") private String vitaminB; @ColumnInfo(name = "vitamin_b2") private String vitaminB2; @ColumnInfo(name = "vitamin_b3") private String vitaminB3; @ColumnInfo(name = "vitamin_b5") private String vitaminB5; @ColumnInfo(name = "vitamin_b6") private String vitaminB6; @ColumnInfo(name = "vitamin_b7") private String vitaminB7; @ColumnInfo(name = "vitamin_b9") private String vitaminB9; @ColumnInfo(name = "vitamin_b12") private String vitaminB12; @ColumnInfo(name = "vitamin_c") private String vitaminC; @ColumnInfo(name = "vitamin_d") private String vitaminD; @ColumnInfo(name = "vitamin_e") private String vitaminE; @ColumnInfo(name = "vitamin_k") private String vitaminK; @ColumnInfo(name = "caffeine") //In Milli Grams private String caffeine; public FoodNutrientsInsight(int foodId, String foodName, String foodPortionType, int foodPortion, String foodThumbnail, String foodFullPic, int energyKCal, String protein, String totalLipidFat, String carbohydrate, String fiberTotalDietary, String sugarsTotalIncludingNLEA, String calciumCa, String ironFe, String sodiumNa, String potassiumK, String iodineI, String zincZn, String magnesiumMg, String cholesterolMg, String fattyAcidSaturated, String fattyAcidMonounsaturated, String fattyAcidPolyunsaturated, String fattyAcidTrans, String vitaminA, String vitaminB, String vitaminB2, String vitaminB3, String vitaminB5, String vitaminB6, String vitaminB7, String vitaminB9, String vitaminB12, String vitaminC, String vitaminD, String vitaminE, String vitaminK, String caffeine) { this.foodId = foodId; this.foodName = foodName; this.foodPortionType = foodPortionType; this.foodPortion = foodPortion; this.foodThumbnail = foodThumbnail; this.foodFullPic = foodFullPic; this.energyKCal = energyKCal; this.protein = protein; this.totalLipidFat = totalLipidFat; this.carbohydrate = carbohydrate; this.fiberTotalDietary = fiberTotalDietary; this.sugarsTotalIncludingNLEA = sugarsTotalIncludingNLEA; this.calciumCa = calciumCa; this.ironFe = ironFe; this.sodiumNa = sodiumNa; this.potassiumK = potassiumK; this.iodineI = iodineI; this.zincZn = zincZn; this.magnesiumMg = magnesiumMg; this.cholesterolMg = cholesterolMg; this.fattyAcidSaturated = fattyAcidSaturated; this.fattyAcidMonounsaturated = fattyAcidMonounsaturated; this.fattyAcidPolyunsaturated = fattyAcidPolyunsaturated; this.fattyAcidTrans = fattyAcidTrans; this.vitaminA = vitaminA; this.vitaminB = vitaminB; this.vitaminB2 = vitaminB2; this.vitaminB3 = vitaminB3; this.vitaminB5 = vitaminB5; this.vitaminB6 = vitaminB6; this.vitaminB7 = vitaminB7; this.vitaminB9 = vitaminB9; this.vitaminB12 = vitaminB12; this.vitaminC = vitaminC; this.vitaminD = vitaminD; this.vitaminE = vitaminE; this.vitaminK = vitaminK; this.caffeine = caffeine; } public int getFoodId() { return foodId; } public void setFoodId(int foodId) { this.foodId = foodId; } public String getFoodName() { return foodName; } public void setFoodName(String foodName) { this.foodName = foodName; } public String getFoodPortionType() { return foodPortionType; } public void setFoodPortionType(String foodPortionType) { this.foodPortionType = foodPortionType; } public int getFoodPortion() { return foodPortion; } public void setFoodPortion(int foodPortion) { this.foodPortion = foodPortion; } public String getFoodThumbnail() { return foodThumbnail; } public void setFoodThumbnail(String foodThumbnail) { this.foodThumbnail = foodThumbnail; } public String getFoodFullPic() { return foodFullPic; } public void setFoodFullPic(String foodFullPic) { this.foodFullPic = foodFullPic; } public int getEnergyKCal() { return energyKCal; } public void setEnergyKCal(int energyKCal) { this.energyKCal = energyKCal; } public String getProtein() { return protein; } public void setProtein(String protein) { this.protein = protein; } public String getTotalLipidFat() { return totalLipidFat; } public void setTotalLipidFat(String totalLipidFat) { this.totalLipidFat = totalLipidFat; } public String getCarbohydrate() { return carbohydrate; } public void setCarbohydrate(String carbohydrate) { this.carbohydrate = carbohydrate; } public String getFiberTotalDietary() { return fiberTotalDietary; } public void setFiberTotalDietary(String fiberTotalDietary) { this.fiberTotalDietary = fiberTotalDietary; } public String getSugarsTotalIncludingNLEA() { return sugarsTotalIncludingNLEA; } public void setSugarsTotalIncludingNLEA(String sugarsTotalIncludingNLEA) { this.sugarsTotalIncludingNLEA = sugarsTotalIncludingNLEA; } public String getCalciumCa() { return calciumCa; } public void setCalciumCa(String calciumCa) { this.calciumCa = calciumCa; } public String getIronFe() { return ironFe; } public void setIronFe(String ironFe) { this.ironFe = ironFe; } public String getSodiumNa() { return sodiumNa; } public void setSodiumNa(String sodiumNa) { this.sodiumNa = sodiumNa; } public String getPotassiumK() { return potassiumK; } public void setPotassiumK(String potassiumK) { this.potassiumK = potassiumK; } public String getIodineI() { return iodineI; } public void setIodineI(String iodineI) { this.iodineI = iodineI; } public String getZincZn() { return zincZn; } public void setZincZn(String zincZn) { this.zincZn = zincZn; } public String getMagnesiumMg() { return magnesiumMg; } public void setMagnesiumMg(String magnesiumMg) { this.magnesiumMg = magnesiumMg; } public String getCholesterolMg() { return cholesterolMg; } public void setCholesterolMg(String cholesterolMg) { this.cholesterolMg = cholesterolMg; } public String getFattyAcidSaturated() { return fattyAcidSaturated; } public void setFattyAcidSaturated(String fattyAcidSaturated) { this.fattyAcidSaturated = fattyAcidSaturated; } public String getFattyAcidMonounsaturated() { return fattyAcidMonounsaturated; } public void setFattyAcidMonounsaturated(String fattyAcidMonounsaturated) { this.fattyAcidMonounsaturated = fattyAcidMonounsaturated; } public String getFattyAcidPolyunsaturated() { return fattyAcidPolyunsaturated; } public void setFattyAcidPolyunsaturated(String fattyAcidPolyunsaturated) { this.fattyAcidPolyunsaturated = fattyAcidPolyunsaturated; } public String getFattyAcidTrans() { return fattyAcidTrans; } public void setFattyAcidTrans(String fattyAcidTrans) { this.fattyAcidTrans = fattyAcidTrans; } public String getVitaminA() { return vitaminA; } public void setVitaminA(String vitaminA) { this.vitaminA = vitaminA; } public String getVitaminB() { return vitaminB; } public void setVitaminB(String vitaminB) { this.vitaminB = vitaminB; } public String getVitaminB2() { return vitaminB2; } public void setVitaminB2(String vitaminB2) { this.vitaminB2 = vitaminB2; } public String getVitaminB3() { return vitaminB3; } public void setVitaminB3(String vitaminB3) { this.vitaminB3 = vitaminB3; } public String getVitaminB5() { return vitaminB5; } public void setVitaminB5(String vitaminB5) { this.vitaminB5 = vitaminB5; } public String getVitaminB6() { return vitaminB6; } public void setVitaminB6(String vitaminB6) { this.vitaminB6 = vitaminB6; } public String getVitaminB7() { return vitaminB7; } public void setVitaminB7(String vitaminB7) { this.vitaminB7 = vitaminB7; } public String getVitaminB9() { return vitaminB9; } public void setVitaminB9(String vitaminB9) { this.vitaminB9 = vitaminB9; } public String getVitaminB12() { return vitaminB12; } public void setVitaminB12(String vitaminB12) { this.vitaminB12 = vitaminB12; } public String getVitaminC() { return vitaminC; } public void setVitaminC(String vitaminC) { this.vitaminC = vitaminC; } public String getVitaminD() { return vitaminD; } public void setVitaminD(String vitaminD) { this.vitaminD = vitaminD; } public String getVitaminE() { return vitaminE; } public void setVitaminE(String vitaminE) { this.vitaminE = vitaminE; } public String getVitaminK() { return vitaminK; } public void setVitaminK(String vitaminK) { this.vitaminK = vitaminK; } public String getCaffeine() { return caffeine; } public void setCaffeine(String caffeine) { this.caffeine = caffeine; } //============================================================================================== public static final DiffUtil.ItemCallback<FoodNutrientsInsight> DIFF_CALLBACK = new DiffUtil.ItemCallback<FoodNutrientsInsight>() { @Override public boolean areItemsTheSame(@NonNull FoodNutrientsInsight oldItem, @NonNull FoodNutrientsInsight newItem) { return oldItem.foodName.equals(newItem.foodName); } @Override public boolean areContentsTheSame(@NonNull FoodNutrientsInsight oldItem, @NonNull FoodNutrientsInsight newItem) { return oldItem.equals(newItem); } }; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FoodNutrientsInsight that = (FoodNutrientsInsight) o; return foodId == that.foodId && foodPortion == that.foodPortion && energyKCal == that.energyKCal && foodName.equals(that.foodName) && foodPortionType.equals(that.foodPortionType) && Objects.equals(foodThumbnail, that.foodThumbnail) && Objects.equals(foodFullPic, that.foodFullPic) && Objects.equals(protein, that.protein) && Objects.equals(totalLipidFat, that.totalLipidFat) && Objects.equals(carbohydrate, that.carbohydrate) && Objects.equals(fiberTotalDietary, that.fiberTotalDietary) && Objects.equals(sugarsTotalIncludingNLEA, that.sugarsTotalIncludingNLEA) && Objects.equals(calciumCa, that.calciumCa) && Objects.equals(ironFe, that.ironFe) && Objects.equals(sodiumNa, that.sodiumNa) && Objects.equals(potassiumK, that.potassiumK) && Objects.equals(iodineI, that.iodineI) && Objects.equals(zincZn, that.zincZn) && Objects.equals(magnesiumMg, that.magnesiumMg) && Objects.equals(cholesterolMg, that.cholesterolMg) && Objects.equals(fattyAcidSaturated, that.fattyAcidSaturated) && Objects.equals(fattyAcidMonounsaturated, that.fattyAcidMonounsaturated) && Objects.equals(fattyAcidPolyunsaturated, that.fattyAcidPolyunsaturated) && Objects.equals(fattyAcidTrans, that.fattyAcidTrans) && Objects.equals(vitaminA, that.vitaminA) && Objects.equals(vitaminB, that.vitaminB) && Objects.equals(vitaminB2, that.vitaminB2) && Objects.equals(vitaminB3, that.vitaminB3) && Objects.equals(vitaminB5, that.vitaminB5) && Objects.equals(vitaminB6, that.vitaminB6) && Objects.equals(vitaminB7, that.vitaminB7) && Objects.equals(vitaminB9, that.vitaminB9) && Objects.equals(vitaminB12, that.vitaminB12) && Objects.equals(vitaminC, that.vitaminC) && Objects.equals(vitaminD, that.vitaminD) && Objects.equals(vitaminE, that.vitaminE) && Objects.equals(vitaminK, that.vitaminK) && Objects.equals(caffeine, that.caffeine); } @Override public int hashCode() { return Objects.hash(foodId, foodName, foodPortionType, foodPortion, foodThumbnail, foodFullPic, energyKCal, protein, totalLipidFat, carbohydrate, fiberTotalDietary, sugarsTotalIncludingNLEA, calciumCa, ironFe, sodiumNa, potassiumK, iodineI, zincZn, magnesiumMg, cholesterolMg, fattyAcidSaturated, fattyAcidMonounsaturated, fattyAcidPolyunsaturated, fattyAcidTrans, vitaminA, vitaminB, vitaminB2, vitaminB3, vitaminB5, vitaminB6, vitaminB7, vitaminB9, vitaminB12, vitaminC, vitaminD, vitaminE, vitaminK, caffeine); } }
package com.karya.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="purorditemreceive001mb") public class PurItemsOrderReceived001MB implements Serializable{ private static final long serialVersionUID = -723583058586873479L; @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name = "poitrecId") private int poitrecId; @Column(name="puOrder") private String puOrder; @Column(name="date") private String date; @Column(name="reqbyDate") private String reqbyDate; @Column(name="supName") private String supName; @Column(name="projectName") private String projectName; @Column(name="quantity") private String quantity; @Column(name="receivedQty") private String receivedQty; @Column(name="qtytoReceive") private String qtytoReceive; @Column(name="warehouseName") private String warehouseName; @Column(name="itemCode") private String itemCode; @Column(name="description") private String description; @Column(name="brandName") private String brandName; @Column(name="company") private String company; public int getPoitrecId() { return poitrecId; } public void setPoitrecId(int poitrecId) { this.poitrecId = poitrecId; } public String getPuOrder() { return puOrder; } public void setPuOrder(String puOrder) { this.puOrder = puOrder; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getReqbyDate() { return reqbyDate; } public void setReqbyDate(String reqbyDate) { this.reqbyDate = reqbyDate; } public String getSupName() { return supName; } public void setSupName(String supName) { this.supName = supName; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public String getQuantity() { return quantity; } public void setQuantity(String quantity) { this.quantity = quantity; } public String getReceivedQty() { return receivedQty; } public void setReceivedQty(String receivedQty) { this.receivedQty = receivedQty; } public String getQtytoReceive() { return qtytoReceive; } public void setQtytoReceive(String qtytoReceive) { this.qtytoReceive = qtytoReceive; } public String getWarehouseName() { return warehouseName; } public void setWarehouseName(String warehouseName) { this.warehouseName = warehouseName; } public String getItemCode() { return itemCode; } public void setItemCode(String itemCode) { this.itemCode = itemCode; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getBrandName() { return brandName; } public void setBrandName(String brandName) { this.brandName = brandName; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public static long getSerialversionuid() { return serialVersionUID; } }