text
stringlengths
10
2.72M
package item.repository; import item.domain.Dispenser; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface DispenserRepository extends CrudRepository<Dispenser, Integer > { }
import java.util.Scanner; public class bj2675 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); for(int i=0;i<n;i++){ String str= new String(); StringBuilder strb= new StringBuilder(); int num=in.nextInt(); str=in.next(); for(int j=0;j<str.length();j++){ for(int s=0;s<num;s++){ strb.append((str.charAt(j))); } } System.out.println(strb.toString()); } } }
/* * Class wrappers of primitive types offer static service methods. * converting digit numbers from String to numeric primitive type. * String class offers another way around, converting number to string. */ package NumberWraper; /** * * @author YNZ */ public class UserNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { double d = Double.parseDouble("20.456"); double a = Double.parseDouble("10.461"); double sum = a + d; System.out.printf("%f + %f = %f \n ", d, a, sum); //converting from numeric to string. String aStr = String.valueOf(d); String dStr = String.valueOf(a); //valueOf returns wrapper type Double e = Double.valueOf(dStr); System.out.println(e.toString()); } }
package com.kangyonggan.app.simconf.controller.web; import com.alibaba.fastjson.JSON; import com.kangyonggan.app.simconf.config.Config; import com.kangyonggan.app.simconf.model.Conf; import com.kangyonggan.app.simconf.service.ConfService; import com.kangyonggan.app.simconf.util.CryptoUtil; import com.kangyonggan.app.simconf.util.SecretUtil; import lombok.extern.log4j.Log4j2; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.OutputStream; import java.security.PrivateKey; import java.security.PublicKey; import java.util.List; /** * @author kangyonggan * @since 2017/2/20 */ @Controller @RequestMapping("conf") @Log4j2 public class ConfController { @Autowired private ConfService confService; /** * 查找项目配置 * * @param request * @param response */ @RequestMapping(method = RequestMethod.POST) public void getProjConfs(HttpServletRequest request, HttpServletResponse response) { // 读取报文头 ServletInputStream inputStream; byte bytes[] = new byte[35]; int len; try { inputStream = request.getInputStream(); len = inputStream.read(bytes, 0, 35); if (len != 35) { return; } } catch (Exception e) { log.warn("非法请求", e); return; } int totalLen; int signLen; try { // 报文头(总长度8+项目代码15+环境码8+签名长度4)= 35位 String header = new String(bytes, 0, len); log.info("请求报文头:" + header); // 总长度,0~8位 totalLen = Integer.parseInt(new String(bytes, 0, 8)) + 8; log.info("请求报文总长度:" + totalLen); // 从消息头中获取签名长度,用于读取签名 String signLenStr = new String(bytes, 31, 4);// 签名长度,最后四位31~35 signLen = Integer.parseInt(signLenStr); log.info("请求报文签名长度:" + signLen); } catch (Exception e) { log.warn("非法请求数据", e); return; } // 计算加密后报文体的长度,用于读取报文体(总长-头-签=密) int encryptedBytesLen = totalLen - 35 - signLen; log.info("请求报文密文长度:" + encryptedBytesLen); // 项目代码 String projCode; try { projCode = new String(bytes, 8, 15).trim(); log.info("请求报文项目代码:{}", projCode); } catch (Exception e) { log.warn("非法项目", e); return; } // 环境 String env; try { env = new String(bytes, 23, 8).trim(); log.info("请求报文环境代码:{}", env); } catch (Exception e) { log.warn("非法环境", e); return; } // 加载秘钥 PrivateKey privateKey; PublicKey publicKey; try { Config config = new Config(projCode + File.separator + env); privateKey = SecretUtil.getPrivateKey(config.getPrivateKeyPath()); publicKey = SecretUtil.getPublicKey(config.getPublicKeyPath()); } catch (Exception e) { log.warn("服务端没有配置秘钥", e); return; } // 验签 boolean isValid = isValid(inputStream, signLen, encryptedBytesLen, privateKey, publicKey); String data; if (isValid) { // 查库 List<Conf> confs = confService.findConfsByProjCodeAndEnv(projCode, env); data = JSON.toJSONString(confs); } else { data = "{\"simErrCo\":\"1001\", \"simErrMsg\":\"验签失败\"}"; } ServletOutputStream outputStream = null; try { outputStream = response.getOutputStream(); push(outputStream, data, privateKey, publicKey); } catch (Exception e) { log.error("推送失败", e); } try { if (outputStream != null) { outputStream.close(); } if (inputStream != null) { inputStream.close(); } } catch (Exception e) { log.error(e); } } /** * 验签 * * @param in * @param signLen * @param encryptedBytesLen * @param privateKey * @param publicKey * @return */ private boolean isValid(ServletInputStream in, int signLen, int encryptedBytesLen, PrivateKey privateKey, PublicKey publicKey) { byte bytes[] = new byte[9999]; try { // 签名 in.read(bytes, 0, signLen); byte signBytes[] = ArrayUtils.subarray(bytes, 0, signLen); log.info("请求报文签名:signBytes.length={}", signBytes.length); // 密文 byte encryptedBytes[] = new byte[encryptedBytesLen]; in.read(encryptedBytes, 0, encryptedBytesLen); log.info("请求报文密文:encryptedBytes.length={}", encryptedBytes.length); // 解密 byte xmlBytes[] = CryptoUtil.decrypt(encryptedBytes, privateKey, 2048, 11, "RSA/ECB/PKCS1Padding"); String xml = new String(xmlBytes, "UTF-8"); log.info("请求报文内容:" + xml); // 验签 boolean isValid = CryptoUtil.verifyDigitalSign(xmlBytes, signBytes, publicKey, "SHA1WithRSA");// 验签 log.info("请求报文验签结果:{}", isValid); return isValid; } catch (Exception e) { log.error("验签异常", e); } return false; } /** * 推送配置 * * @param out * @param data * @param privateKey * @param publicKey * @return */ private boolean push(OutputStream out, String data, PrivateKey privateKey, PublicKey publicKey) { try { log.info("响应报文原文:{}", data); // 响应报文 byte plainBytes[] = data.getBytes("UTF-8"); log.info("响应报文:plainBytes.length={}", plainBytes.length); // 签名 byte[] signBytes = CryptoUtil.digitalSign(plainBytes, privateKey, "SHA1WithRSA"); log.info("响应报文签名:signBytes.length={}", signBytes.length); // 加密 byte[] encryptedBytes = CryptoUtil.encrypt(plainBytes, publicKey, 2048, 11, "RSA/ECB/PKCS1Padding"); log.info("响应报文密文:encryptedBytes.length={}", encryptedBytes.length); StringBuilder sb = new StringBuilder(); sb.append(StringUtils.leftPad(String.valueOf(12 + signBytes.length + encryptedBytes.length), 8, "0")); sb.append(StringUtils.leftPad(String.valueOf(signBytes.length), 4, "0")); log.info("响应报文头:{}", sb.toString()); byte[] bytes = null; bytes = ArrayUtils.addAll(bytes, sb.toString().getBytes("UTF-8")); bytes = ArrayUtils.addAll(bytes, signBytes); bytes = ArrayUtils.addAll(bytes, encryptedBytes); log.info("响应报文最终返回:bytes.length={}", bytes.length); // 写响应 out.write(bytes); out.flush(); log.info("推送配置完成!"); return true; } catch (Exception e) { log.error("推送配置失败", e); return false; } } }
package com.najasoftware.fdv.dao; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.support.annotation.NonNull; import com.najasoftware.fdv.model.Item; import com.najasoftware.fdv.model.Pedido; import java.util.ArrayList; import java.util.List; /** * Created by Lemoel on 09/03/2016. */ public class ItemDAO extends BancoDAO { private final String TABLE = "ITENS"; private final String ID = "_id"; private final String NOME = "NOME"; private final String PEDIDO_ID = "PEDIDO_ID"; private final String PRODUTO_ID = "PRODUTO_ID"; private final String PRECO_SUGERIDO = "PRECO_SUGERIDO"; private final String DESCONTO = "DESCONTO"; private final String QTDE = "QTDE"; private final String TOTAL_SEM_DESCONTO = "TOTAL_SEM_DESCONTO"; private final String TOTAL_COM_DESCONTO = "TOTAL_COM_DESCONTO"; private Context context; public ItemDAO(Context context) { super(context); this.context = context; } /* Busca todos os itens de um determinado pedido @param Pedido pedido que queremos os itens @author Lemoel Marques Vieira lemoel@gmail.com */ public List<Item> getItens(Pedido pedido) { String sql = "SELECT * FROM " + TABLE + " WHERE " + PEDIDO_ID + " = ?;"; String args[] = new String[]{pedido.getId().toString()}; try { Cursor c = getDb().rawQuery(sql, args); List<Item> itens = toList(c); c.close(); return itens; } finally { getDb().close(); } } public List<Item> getItens(Long pedidoId) throws SQLiteException { String where = " PEDIDO_ID = ?"; String args[] = new String[]{pedidoId.toString()}; List<Item> itens = new ArrayList<>(); try { Cursor c = getDb().query("ITENS", null, where, args, null, null, null); itens = toList(c); c.close(); return itens; } finally { getDb().close(); } } public void excluir(Item itemExcluir) { String[] params = {itemExcluir.getId().toString()}; try { getDb().delete(TABLE, ID + " = ?", params); } finally { getDb().close(); } } /* * Busca em toda a tabela de item por uma string qualquer de um pedido * @param String a string que será buscada nos itens do pedido * @param Pedido o pedido em que será feira a busca dos itens * @author Lemoel Marques Vieira lemoel@gmail.com */ public List<Item> buscalAll(String query, Pedido pedido) { query = "%" + query + "%"; String where = " pedido_id = " + pedido.getId().toString() + " " + " AND (nome LIKE ? " + "or produto_id LIKE ? )"; String args[] = new String[]{query,query}; try { Cursor c = getDb().query(TABLE, null, where, args, null, null, null); List<Item> itens = toList(c); c.close(); return itens; } finally { getDb().close(); } } /* * Percorre o cursor e grava os dados dentro de uma lista de itens * @param Cursor * @author Lemoel Marques Vieira lemoel@gmail.com */ private List<Item> toList(Cursor c) { List<Item> itens = new ArrayList<>(); if (c.moveToNext()) { do { Item item = new Item(); item.setId(c.getLong(c.getColumnIndex(ID))); //item.setPedido(new PedidoDAO(context).getPedido(c.getLong(c.getColumnIndex(PEDIDO_ID)))); item.setPedido(new Pedido(c.getLong(c.getColumnIndex(PEDIDO_ID)))); item.setNome(c.getString(c.getColumnIndex("NOME"))); item.setProduto(new ProdutoDAO(context).getProduto(c.getLong(c.getColumnIndex("PRODUTO_ID")))); item.setPrecoSugerido(c.getDouble(c.getColumnIndex("PRECO_SUGERIDO"))); item.setQtde(c.getDouble(c.getColumnIndex("QTDE"))); item.setTotalComDesconto(c.getDouble(c.getColumnIndex("TOTAL_COM_DESCONTO"))); item.setTotalSemDesconto(c.getDouble(c.getColumnIndex("TOTAL_SEM_DESCONTO"))); item.setDesconto(c.getDouble(c.getColumnIndex("DESCONTO"))); itens.add(item); } while (c.moveToNext()); } return itens; } @NonNull private ContentValues pegaDadosItem(Item item) { ContentValues dados = new ContentValues(); if (item.getId() != null) dados.put(ID, item.getId()); dados.put(NOME, item.getNome().toString().trim()); dados.put(PEDIDO_ID, item.getPedido().getId()); dados.put(PRODUTO_ID, item.getProduto().getId().toString().trim()); dados.put(PRECO_SUGERIDO, item.getPrecoSugerido().toString().trim()); dados.put(QTDE, item.getQtde().toString().trim()); dados.put(TOTAL_SEM_DESCONTO, item.getTotalSemDesconto().toString().trim()); dados.put(TOTAL_COM_DESCONTO, item.getTotalComDesconto().toString().trim()); dados.put(DESCONTO, item.getDesconto().toString().trim()); return dados; } public Long gravar(Item item) { ContentValues dados = new ContentValues(); dados = pegaDadosItem(item); Long id = getDb().insert(TABLE, null, dados); return id; } public void update(Item item) { ContentValues dadosItem = new ContentValues(); dadosItem = pegaDadosItem(item); getDb().update(TABLE,dadosItem, ID + " = ? ", new String[]{String.valueOf(item.getId())}); } }
package org.jinku.sync.application.server.comet; import com.alibaba.fastjson.JSON; import com.google.common.base.Preconditions; import io.netty.channel.ChannelHandlerContext; import org.apache.commons.lang3.StringUtils; import org.jinku.sync.domain.repository.UserSessionRepository; import org.jinku.sync.application.ao.ResultAo; import org.jinku.sync.application.param.UserDeviceParam; import org.jinku.sync.domain.types.ReqType; import org.springframework.stereotype.Component; import javax.annotation.Resource; @Component public class SignInReqHandler implements ReqHandler { @Resource private UserSessionRepository userSessionRepository; @Override public ReqType getReqType() { return ReqType.SIGN_IN; } @Override public ResultAo handleReq(String reqData, ChannelHandlerContext ctx) { UserDeviceParam userDevice = JSON.parseObject(reqData, UserDeviceParam.class); Preconditions.checkNotNull(userDevice, "用户设备签入信息非法: userDevice:{%s}", userDevice); Preconditions.checkArgument(StringUtils.isNotBlank(userDevice.getUserId()) && StringUtils.isNotBlank(userDevice.getDeviceId()), "用户设备签入信息非法: userDevice:{%s}", userDevice); // 用户设备签入 userSessionRepository.userSignIn(userDevice.getUserId(), ctx.channel()); // 返回签入成功 return ResultAo.success(); } }
import javafx.scene.control.Button; import javafx.scene.control.MenuButton; import javafx.scene.image.ImageView; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; /** * @author sufu */ public class GardenDesignView { private GridPane gridPane; /** * 初始化页面 * Gets the display of the current view */ public VBox dogardendesignView() { return this.initView(); } private VBox initView() { VBox vBox = new VBox(); vBox.setPrefWidth(1200); vBox.setPrefHeight(600); HBox hBox = new HBox(); hBox.setPrefWidth(250); hBox.setPrefHeight(150); hBox.setStyle("-fx-padding: 0 0 0 0"); gridPane = new GridPane(); gridPane.setStyle("-fx-padding: 0 0 0 0"); updateGridPane("Boxelder"); hBox.getChildren().addAll(gridPane); vBox.getChildren().add(hBox); MenuButton button = new MenuButton(); button.setText("Your Choice"); return vBox; } private void updateGridPane(String key) { VBox paneVBox = new VBox(); paneVBox.setPrefWidth(1200); paneVBox.setPrefHeight(600); ImageView imageView = new ImageView("file:src/main/resources/gardenback/garden.png"); imageView.setFitHeight(600); imageView.setFitWidth(1200); paneVBox.getChildren().addAll(imageView); gridPane.add(paneVBox, 1, 0); gridPane.add(new Button("save"), 0, 0); } }
package com.minoon.disco.sample; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.minoon.disco.Logger; import butterknife.ButterKnife; import butterknife.OnClick; public class TopActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.a_top); ButterKnife.bind(this); Logger.setLoggable(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_top, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @OnClick(R.id.a_top_btn_simple) public void onClickSimple(View view) { SimpleActivity.startActivity(this); } @OnClick(R.id.a_top_btn_collapsing_header) public void onCliclCollapsingHeader(View view) { CollapsingHeaderSampleActivity.startActivity(this); } }
package com.hhdb.csadmin.plugin.table_open.ui; import java.awt.Color; import java.awt.Component; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; public class HHTableColumnCellRenderer extends DefaultTableCellRenderer { /** * */ private static final long serialVersionUID = 1L; public HHTableColumnCellRenderer(){ } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if(column == 0){ this.setBackground(Color.LIGHT_GRAY); this.setForeground(Color.BLACK); this.setHorizontalAlignment(JLabel.CENTER); } return comp; } }
package org.sinhro.ForeignLanguageCourses.service; import lombok.Getter; import org.sinhro.ForeignLanguageCourses.domain.Language; import org.sinhro.ForeignLanguageCourses.domain.Listener; import org.sinhro.ForeignLanguageCourses.domain.Statistic; import org.sinhro.ForeignLanguageCourses.repository.ListenerRepository; import org.sinhro.ForeignLanguageCourses.repository.StatisticRepository; import org.sinhro.ForeignLanguageCourses.service.incomeCalculator.IIncomeCalculator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class StatisticService { private Logger log = LoggerFactory.getLogger(StatisticService.class); @Autowired private StatisticRepository statisticRepository; @Autowired private IIncomeCalculator incomeCalculator; @Autowired private ListenerRepository listenerRepository; @Getter private Integer currentWeek; public void startNewWeek() { Statistic stat = statisticRepository.lastStatistic(); if (stat == null) this.currentWeek = 1; else this.currentWeek = stat.getWeekNumber() + 1; } public void endWeek() { Integer weekIncome = 0; List<Listener> listenersComeForACurrentWeek = listenerRepository.findListenersByBeginWeek(currentWeek); List<Listener> allListeners = listenerRepository.findAll(); for (Listener listener : allListeners) { Language language = listener.getGroup().getCourse().getLanguage(); weekIncome += incomeCalculator.calculate(language, false); } log.info("Выручка за текущий период " + weekIncome); Statistic newStat = new Statistic( null, currentWeek, weekIncome, listenersComeForACurrentWeek.size() ); statisticRepository.save(newStat); } }
package io.projekat.predmet; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.springframework.stereotype.Service; @Service public class PredmetService { private List<Smer> smerovi = new ArrayList<>(Arrays.asList(new Smer("1","Racunarska tehnika i softverkos inzenjerstvo"))); //private List<Smer> private List<Profesor> profesori = new ArrayList<>(Arrays.asList(new Profesor(1,"Aleksandar Peulic","profesor",smerovi),new Profesor(2,"Vladimir Milovanovic","profesor",smerovi))); private List<Profesor> prof = new ArrayList<>(Arrays.asList(new Profesor(1,"Aleksandar Peulic","profesor",smerovi))); private List<Predmet> predmeti = new ArrayList<>(Arrays.asList(new Predmet("1","Osnovi računarske tehnike",smerovi,profesori) ,new Predmet("2","Osnovi računarske tehnike 2",smerovi,profesori), new Predmet("3","Arhitektura računarskih sistema",smerovi,profesori), new Predmet("4","Objektno-orijentisano programiranje",smerovi,profesori))); //Predmet p = new Predmet(2,"Osnovi računarske tehnike 2",smerovi); public List<Predmet> getPredmeti(){ return predmeti; } }
public class MovieNetflixQueue { public static void main(String[] args) { NetflixQueue a = new NetflixQueue(); Movie b= new Movie("A dogs journey", 8 ); Movie c= new Movie("End game", 10); Movie d= new Movie("Avengers", 9); a.addMovie(b); a.addMovie(c); a.addMovie(d); a.printMovies(); System.out.println("the best movie is"+a.getBestMovie()); System.out.println("the second best movie"+a.getSecondBestMovie() ); } }
package com.yun.android.util; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Vector; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Paint; import android.net.Uri; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.util.Log; public class AndroidUtil { public static boolean getSoundPreference(Activity activity) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity); return sharedPreferences.getBoolean("SOUND_ON", true); } public static String submitPost(String url, List<NameValuePair> nameValuePairs) throws Exception { StringBuffer sb = new StringBuffer(); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = client.execute(post); int stateCode = response.getStatusLine().getStatusCode(); if (stateCode == HttpStatus.SC_OK) { HttpEntity result = response.getEntity(); if (result != null) { InputStream is = result.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String tempLine; while ((tempLine = br.readLine()) != null) { sb.append(tempLine); } } } post.abort(); return sb.toString(); } public static String getUriPath(Activity activity, Uri uri) { String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = activity.managedQuery(uri, projection, null, null, null); activity.startManagingCursor(cursor); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } // 计算图片的缩放值 public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; } // 根据路径获得图片并压缩,返回bitmap用于显示 public static Bitmap getSmallBitmap(String filePath) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, 480, 800); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(filePath, options); } public static void writeSmallBitmap(String oldPath, String newPath){ Bitmap bitmap = getSmallBitmap(oldPath); if (bitmap != null) { try { // build directory File file = new File(newPath); File path = new File(file.getParent()); if (file.getParent() != null && !path.isDirectory()) { path.mkdirs(); } // output image to file FileOutputStream fos = new FileOutputStream(newPath); bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos); fos.close(); } catch (Exception e) { e.printStackTrace(); } } } public static String readFile(Activity activity, int bookId, String encode) { InputStream inputStream = activity.getResources().openRawResource(bookId); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(inputStream, encode));// 注意编码 } catch (UnsupportedEncodingException e1) { Log.e("debug", e1.toString()); } StringBuffer sb = new StringBuffer(""); String line; try { while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\n"); } reader.close(); inputStream.close(); } catch (IOException e) { Log.e("debug", e.toString()); } return sb.toString(); } public static List<String> readFileToList(Activity activity, int bookId, String encode) { InputStream inputStream = activity.getResources().openRawResource(bookId); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(inputStream, encode)); } catch (UnsupportedEncodingException e1) { Log.e("debug", e1.toString()); } List<String> list = new ArrayList<String>(); String line; try { while ((line = reader.readLine()) != null) { list.add(line); } reader.close(); inputStream.close(); } catch (IOException e) { Log.e("debug", e.toString()); } return list; } public static String[] readFileToArray(Activity activity, int bookId, String encode, Paint paint, int displayWidth) { String text = readFile(activity, bookId, encode); if(text == null) return null; paint.setTextSize(25); int stringsWidth = 0; Vector<String> vector = new Vector<String>(); int beginIndex = 0, endIndex = 0; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == '\n') { // 遇见换行符自动换行 endIndex = i; vector.addElement(text.substring(beginIndex, endIndex)); beginIndex = i + 1; stringsWidth = 0; } else if (stringsWidth > displayWidth) { endIndex = --i; vector.addElement(text.substring(beginIndex, endIndex)); beginIndex = i; stringsWidth = 0; i--; } else { // 累加单个字符宽度与要求的显示宽度比较 float[] widths = new float[1]; String srt = String.valueOf(text.charAt(i)); paint.getTextWidths(srt, widths); stringsWidth += widths[0]; } if (i == text.length() - 1) { if (stringsWidth > displayWidth) { endIndex = i; vector.addElement(text.substring(beginIndex, endIndex)); beginIndex = i; stringsWidth = 0; } } } // 最后剩余的字体也要放进去 if (beginIndex != text.length() - 1) { vector.addElement(text.substring(beginIndex, text.length())); } else if (beginIndex == text.length() - 1) { vector.addElement(text.substring(beginIndex)); } String strings[] = new String[vector.size()]; for (int i = 0; i < strings.length; i++) { strings[i] = (String) vector.elementAt(i); } return strings; } public static byte[] getBytes(InputStream is) throws Exception{ ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while((len = is.read(buffer))!=-1){ bos.write(buffer, 0, len); } is.close(); bos.flush(); byte[] result = bos.toByteArray(); return result; } public static Bitmap getImage(String address) throws Exception{ //通过代码 模拟器浏览器访问图片的流程 URL url = new URL(address); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); //获取服务器返回回来的流 InputStream is = conn.getInputStream(); byte[] imagebytes = getBytes(is); Bitmap bitmap = BitmapFactory.decodeByteArray(imagebytes, 0, imagebytes.length); return bitmap; } }
package FlowerGirl; import org.w3c.dom.ranges.Range; import java.util.*; public class Bouquet { private final Set<Flower> flowerSet = new HashSet<>(); private final Set<Accessory> accessoriesSet = new HashSet<>(); private Comparator<Flower> flowerComparator = (x, y) -> x.level.compareTo(y.level); public void setFlowerComparator(Comparator<Flower> flowerComparator) { this.flowerComparator = flowerComparator; } enum Accessory { tape(3), packing(5); int price; Accessory(int price) { this.price = price; } } public void addToBouquet(Flower... flowers) { for (Flower temp : flowers) { flowerSet.add(temp); } } public void addAccessory(Accessory... accessories) { for (Accessory temp : accessories) { accessoriesSet.add(temp); } } public int getBouquetPrice() { int result = 0; for (Flower tempFlowers : flowerSet) { result += tempFlowers.price; } for (Accessory tempAccessory : accessoriesSet) { result += tempAccessory.price; } return result; } public Set<Flower> findByStalkLength(int beginRange, int endRange) { Set<Flower> result = new HashSet<>(); int currentStart = beginRange > endRange ? endRange : beginRange; int currentEnd = beginRange > endRange ? beginRange : endRange; for (Flower tempFlowers : flowerSet) { if (tempFlowers.stalkLength > currentStart && tempFlowers.stalkLength < currentEnd) { result.add(tempFlowers); } } return result; } public void view() { flowerSet.stream().sorted(flowerComparator).forEach(System.out::println); } }
package com.siss.web.delegate.mae; import com.siss.entity.mae.Funcionario; import com.siss.exception.EntityException; import com.siss.ifacade.mae.FuncionariosFacadeRemote; import com.siss.web.resource.WebConstants; import com.siss.web.Util; import com.siss.web.util.locator.ServiceLocator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.naming.NamingException; /** * * @author hmoya */ public class FuncionariosDelegate { private ServiceLocator servicio; private FuncionariosFacadeRemote funcFacade; private static FuncionariosDelegate me; static { me = new FuncionariosDelegate(); } /** * */ public FuncionariosDelegate() { try { servicio = ServiceLocator.getInstance(); funcFacade = (FuncionariosFacadeRemote) servicio.getRemoteHome(WebConstants.FACADE_FUNCIONARIOS, FuncionariosFacadeRemote.class); } catch (NamingException ex) { Logger.getLogger(FuncionariosDelegate.class.getName()).log(Level.SEVERE, Util.getText(ex)); } } /** * * @return */ public static FuncionariosDelegate getInstance() { return me; } /***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** FACADE MAE FUNCIONARIOS ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** *****/ /** * Retorna un esquema de Funcionario a partir del nombre de usuario LDAP. * @param usuario nombre del usuario LDAP. * @see com.siss.entity.mae.Funcionario * @see com.siss.ifacade.mae.FuncionariosFacadeRemote * @return El ID del {@link com.siss.entity.mae.Funcionario Funcionario} */ public Integer getUsuarioId(String usuario) throws EntityException { Integer id = null; Funcionario user = funcFacade.getFuncionarioByLdap(usuario); if (user != null) { id = user.getFuncionarioId(); } return id; } /** * Obtiene la lista con los {@link com.siss.entity.mae.Funcionario Funcionario} que pueden ser fiscalizadores. * @see com.siss.entity.mae.Funcionario * @see com.siss.ifacade.mae.FuncionariosFacadeRemote * @return Lista con {@link com.siss.entity.mae.Funcionario Funcionario} que pueden ser fiscalizadores. */ public List<Funcionario> getFuncionariosFiscalizadores() { return funcFacade.getFuncionariosFiscalizadores(); } }
package filippov.vitaliy.poibms3_8.ui.tools; import android.content.Context; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import filippov.vitaliy.poibms3_8.Data.Events.CalendarEvents; import filippov.vitaliy.poibms3_8.Data.Events.Event; public class ToolsViewModel extends ViewModel { public static int currentEventPos = 0; private MutableLiveData<Event[]> mText; public ToolsViewModel() { mText = new MutableLiveData<>(); } public LiveData<Event[]> getText(Context context) { Event[] e = CalendarEvents.getEvents().toArray(new Event[]{}); mText.setValue(e); return mText; } }
package com.pronix.android.apssaataudit.Dal; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import com.pronix.android.apssaataudit.common.Constants; import com.pronix.android.apssaataudit.common.SqliteConstants; import com.pronix.android.apssaataudit.common.Utils; import com.pronix.android.apssaataudit.db.DBManager; import com.pronix.android.apssaataudit.models.DistrictDO; import com.pronix.android.apssaataudit.models.PanchayatDO; import com.pronix.android.apssaataudit.models.Worker; import com.pronix.android.apssaataudit.pojo.Habitations; import com.pronix.android.apssaataudit.pojo.Villages; import java.util.ArrayList; /** * Created by ravi on 1/2/2018. */ public class DalDoorToDoorDetails { public void insertOrUpdateDoorToDoorData(String[] data) { long res = -1; String strWhereClauseValues = ""; try { ContentValues newTaskValue = new ContentValues(); newTaskValue.put("district_code", data[0]); newTaskValue.put("mandal_code", data[1]); newTaskValue.put("panchayat_code", data[2]); newTaskValue.put("village_code", data[3]); newTaskValue.put("habitation_code", data[4]); newTaskValue.put("ssaat_code", data[5]); newTaskValue.put("household_code", data[6]); newTaskValue.put("worker_code", data[7]); newTaskValue.put("surname", data[8]); newTaskValue.put("telugu_surname", data[9]); newTaskValue.put("name", data[10]); newTaskValue.put("telugu_name", data[11]); newTaskValue.put("account_no", data[12]); newTaskValue.put("work_code", data[13]); newTaskValue.put("work_name", data[14]); newTaskValue.put("work_name_telugu", data[15]); newTaskValue.put("work_location", data[16]); newTaskValue.put("work_location_telugu", data[17]); newTaskValue.put("work_progress_code", data[18]); newTaskValue.put("from_date", data[19]); newTaskValue.put("to_date", data[20]); newTaskValue.put("days_worked", data[21]); newTaskValue.put("amount_paid", data[22]); newTaskValue.put("payment_date", data[23]); newTaskValue.put("audit_payslip_date", data[24]); newTaskValue.put("audit_is_passbook_avail", data[25]); newTaskValue.put("audit_is_payslip_issuing", data[26]); newTaskValue.put("audit_is_jobcard_avail", data[27]); newTaskValue.put("audit_days_worked", data[28]); newTaskValue.put("audit_amount_rec", data[29]); newTaskValue.put("audit_remarks", data[30]); newTaskValue.put("status", data[31]); newTaskValue.put("sent_file_name", data[32]); newTaskValue.put("sent_date", data[33]); newTaskValue.put("resp_filename", data[34]); newTaskValue.put("resp_date", data[35]); newTaskValue.put("created_date", data[36]); newTaskValue.put("department", data[37]); newTaskValue.put("muster_id", data[38]); strWhereClauseValues = data[6] + "," + data[7] + "," + data[13] + "," + data[19] + "," + data[20] + "," + data[38]; res = DBManager.getInstance().updateRecord("employees", newTaskValue, "household_code=? " + "AND worker_code=? AND work_code=? AND from_date=? AND to_date=? AND muster_id=?", strWhereClauseValues); if (res == 0) { res = DBManager.getInstance().insertRecord("employees", newTaskValue); } } catch (Exception e) { } // database.update("worksite", ) } public void insertOrUpdateDoorToDoorDetails(String districCode, String mandalCode, String panchayatCode, String villageCode, String habitationCode, String ssaatCode, String householdCode, String workerCode, String surname, String teluguSurName, String name, String teluguName, String accountNo, String workCode, String workName, String workNameTelugu, String workLocation, String workLocationTelugu, String workProgressCode, String fromDate, String toDate, String daysWorked, String amountPaid, String paymentDate, String auditPayslipDate, String auditIsPassbookAvail, String auditIsPayslipIssuing, String auditIsJobCardAvail, String auditDaysWorked, String audiAmtRec, String auditRemarks, String status, String sentFileName, String sentDate, String resFileName, String resDate, String creratedDate, String department, String musterId, String panchayatName, String villageName, String habitationName) { long res = -1; String strWhereClauseValues = ""; try { ContentValues newTaskValue = new ContentValues(); newTaskValue.put("district_code", districCode); newTaskValue.put("mandal_code", mandalCode); newTaskValue.put("panchayat_code", panchayatCode); newTaskValue.put("village_code", villageCode); newTaskValue.put("habitation_code", habitationCode); newTaskValue.put("ssaat_code", ssaatCode); newTaskValue.put("household_code", householdCode); newTaskValue.put("worker_code", workerCode); newTaskValue.put("surname", surname); newTaskValue.put("telugu_surname", teluguSurName); newTaskValue.put("name", name); newTaskValue.put("telugu_name", teluguName); newTaskValue.put("account_no", accountNo); newTaskValue.put("work_code", workCode); newTaskValue.put("work_name", workName); newTaskValue.put("work_name_telugu", workNameTelugu); newTaskValue.put("work_location", workLocation); newTaskValue.put("work_location_telugu", workLocationTelugu); newTaskValue.put("work_progress_code", workProgressCode); newTaskValue.put("from_date", fromDate); newTaskValue.put("to_date", toDate); newTaskValue.put("days_worked", daysWorked); newTaskValue.put("amount_paid", amountPaid); newTaskValue.put("payment_date", paymentDate); newTaskValue.put("audit_payslip_date", auditPayslipDate); newTaskValue.put("audit_is_passbook_avail", auditIsPassbookAvail); newTaskValue.put("audit_is_payslip_issuing", auditIsPayslipIssuing); newTaskValue.put("audit_is_jobcard_avail", auditIsJobCardAvail); newTaskValue.put("audit_days_worked", auditDaysWorked); newTaskValue.put("audit_amount_rec", audiAmtRec); newTaskValue.put("audit_remarks", auditRemarks); newTaskValue.put("status", status); newTaskValue.put("sent_file_name", sentFileName); newTaskValue.put("sent_date", sentDate); newTaskValue.put("resp_filename", resFileName); newTaskValue.put("resp_date", resDate); newTaskValue.put("created_date", creratedDate); newTaskValue.put("department", department); newTaskValue.put("muster_id", musterId); newTaskValue.put("panchayat_name", panchayatName); newTaskValue.put("village_name", villageName); newTaskValue.put("habitation_name", habitationName); strWhereClauseValues = householdCode + "," + workerCode + "," + workCode + "," + fromDate + "," + toDate + "," + musterId; res = DBManager.getInstance().updateRecord("employees", newTaskValue, "household_code=? " + "AND worker_code=? AND work_code=? AND from_date=? AND to_date=? AND muster_id=?", strWhereClauseValues); if (res == 0) { res = DBManager.getInstance().insertRecord("employees", newTaskValue); } } catch (Exception e) { } // database.update("worksite", ) } public int updateRecord(SQLiteDatabase database, String tableName, ContentValues contentValues, String whereClause, String whereArgs) { int iResult = 0; String[] strWhereArgs = whereArgs.split(","); try { try { iResult = database.update(tableName, contentValues, whereClause, strWhereArgs); } catch (Exception e) { // AndroidUtils.logMsg("DBManager.updateRecord(): TableName: " + tableName + " " + e.getMessage()); } } catch (SQLiteException e) { // AndroidUtils.logMsg("DBManager.getScalar(): " + e.getMessage()); } return iResult; } public ArrayList<Worker> getDoorToDoorDetails(String householdCode) { ArrayList<Worker> arrayList = new ArrayList<>(); Cursor cursorEmployees = null; String query = "SELECT EM.id, EM.district_code, EM.mandal_code, EM.panchayat_code, EM.village_code, EM.habitation_code, \n" + "EM.ssaat_code, EM.household_code, EM.worker_code, EM.surname,EM.telugu_surname, EM.name, EM.telugu_name, EM.account_no,\n" + "EM.work_code, EM.work_name, EM.work_name_telugu, EM.work_location, EM.work_location_telugu, EM.work_progress_code, \n" + "EM.from_date, EM.to_date, EM.days_worked, EM.amount_paid, EM.payment_date, EM.audit_payslip_date, \n" + "EM.audit_is_passbook_avail, EM.audit_is_payslip_issuing, EM.audit_is_jobcard_avail, EM.audit_days_worked, \n" + "EM.audit_amount_rec, EM.audit_remarks, EM.status, EM.sent_file_name, EM.sent_date, EM.resp_filename, EM.resp_date, EM.created_date, EM.department, EM.muster_id,\n" + "IFNULL(f4a.actualWorkedDays,''), IFNULL(f4a.actualAmtPaid,''), IFNULL(f4a.differenceInAmt,''), IFNULL(f4a.isJobCardAvail,''), IFNULL(f4a.isPassbookAvail,''), IFNULL(f4a.isPayslipIssued,''),\n" + "IFNULL(f4a.respPersonName,''), IFNULL(f4a.respPersonDesig,''), IFNULL(f4a.categoryone,''), IFNULL(f4a.categorytwo,''), " + "IFNULL(f4a.categorythree,''), IFNULL(f4a.comments,''), IFNULL(f4a.serverflag,'') \n" + " FROM employees AS EM LEFT OUTER JOIN format4A AS f4a ON EM.household_code = IFNULL(f4a.wageSeekerId,'') \n" + " AND EM.muster_id = IFNULL(f4a.musterId,'') WHERE EM.household_code IN ('" + householdCode + "')"; cursorEmployees = DBManager.getInstance().getRawQuery(query); arrayList.clear(); int count = 1; if (cursorEmployees.moveToFirst()) { do { arrayList.add(new Worker( String.valueOf(count++), cursorEmployees.getString(1), cursorEmployees.getString(2), cursorEmployees.getString(3), cursorEmployees.getString(4), cursorEmployees.getString(5), cursorEmployees.getString(6), cursorEmployees.getString(7), cursorEmployees.getString(8), cursorEmployees.getString(9), cursorEmployees.getString(11), cursorEmployees.getString(13), cursorEmployees.getString(14), cursorEmployees.getString(15), cursorEmployees.getString(17), cursorEmployees.getString(19), cursorEmployees.getString(20), cursorEmployees.getString(21), cursorEmployees.getString(22), cursorEmployees.getString(23), cursorEmployees.getString(24), cursorEmployees.getString(25), cursorEmployees.getString(39), cursorEmployees.getString(40), cursorEmployees.getString(41), cursorEmployees.getString(42), cursorEmployees.getString(43), cursorEmployees.getString(44), cursorEmployees.getString(45), cursorEmployees.getString(46), cursorEmployees.getString(47), cursorEmployees.getString(48), cursorEmployees.getString(49), cursorEmployees.getString(50), cursorEmployees.getString(51), cursorEmployees.getString(52))); } while (cursorEmployees.moveToNext()); } return arrayList; } public ArrayList<PanchayatDO> getDownloadedPanchayats() { Cursor c = null; ArrayList<PanchayatDO> arrayList = new ArrayList<>(); PanchayatDO panchayatDO; String query = "SELECT DISTINCT (panchayat_code), panchayat_name, mandal_code, district_code FROM employees"; c = DBManager.getInstance().getRawQuery(query); if (c.moveToFirst()) { do { panchayatDO = new PanchayatDO(); panchayatDO.setPanchayatCode(c.getInt(0)); panchayatDO.setPanchayatName(c.getString(1)); panchayatDO.setMandalCode(c.getInt(2)); panchayatDO.setDistrictCode(c.getInt(3)); arrayList.add(panchayatDO); } while (c.moveToNext()); } return arrayList; } public ArrayList<Villages> getVillages(String panchayatCode) { Cursor c = null; ArrayList<Villages> arrayList = new ArrayList<>(); Villages villages; String query = "SELECT DISTINCT(village_code), village_name FROM " + SqliteConstants.TABLE_FORMAT4A + " WHERE panchayat_code = " + Utils.getQuotedString(panchayatCode); c = DBManager.getInstance().getRawQuery(query); if (c.moveToFirst()) { do { villages = new Villages(); villages.setVillageCode(c.getString(0)); villages.setVillageName(c.getString(1)); arrayList.add(villages); } while (c.moveToNext()); } return arrayList; } public ArrayList<Habitations> getHabitations(String villageCode) { Cursor c = null; ArrayList<Habitations> arrayList = new ArrayList<>(); Habitations habitations; String query = "SELECT DISTINCT(habitation_code), mandal_code, district_code, habitation_name FROM " + SqliteConstants.TABLE_FORMAT4A + " WHERE village_code = " + Utils.getQuotedString(villageCode); c = DBManager.getInstance().getRawQuery(query); if (c.moveToFirst()) { do { habitations = new Habitations(); habitations.setHabitationCode(c.getString(0)); habitations.setMandalCode(c.getString(1)); habitations.setDistrictCode(c.getString(2)); habitations.setHabitationName(c.getString(3)); arrayList.add(habitations); } while (c.moveToNext()); } return arrayList; } public ArrayList<String> getHouseholdCodes(String villageCode, String habitationCode, String panchayatCode) { ArrayList<String> arrayList = new ArrayList<>(); Cursor c = null; String householdCode = ""; String query = "SELECT DISTINCT(household_code) FROM " + SqliteConstants.TABLE_FORMAT4A + " WHERE village_code = " + Utils.getQuotedString(villageCode) + " AND habitation_code = " + Utils.getQuotedString(habitationCode) + " AND panchayat_code = " + Utils.getQuotedString(panchayatCode); c = DBManager.getInstance().getRawQuery(query); if(c.moveToFirst()) { do { householdCode = c.getString(0); arrayList.add(householdCode.substring(householdCode.length()-4, householdCode.length())); }while (c.moveToNext()); } return arrayList; } public String[] getTotalRecords(String panchayatCode) { String[] value = new String[2]; Cursor c = null; String query = "SELECT count(1) FROM " + SqliteConstants.TABLE_FORMAT4A + " WHERE panchayat_code = " + Utils.getQuotedString(panchayatCode) + " UNION ALL " + " SELECT count(1) FROM format4A WHERE panchayat_code = " + Utils.getQuotedString(panchayatCode); c = DBManager.getInstance().getRawQuery(query); int i = 0; if(c.moveToFirst()) { do { value[i++] = c.getString(0); }while (c.moveToNext()); } return value; } public String[] getVillageWiseTotalRecords(String villageCode) { String[] value = new String[2]; Cursor c = null; String query = "SELECT count(1) FROM " + SqliteConstants.TABLE_FORMAT4A + " WHERE village_code = " + Utils.getQuotedString(villageCode) + " UNION ALL " + " SELECT count(1) FROM format4A AS F4A, "+SqliteConstants.TABLE_FORMAT4A +" AS Emp WHERE F4A.wageSeekerId = Emp.household_code AND " + " F4A.panchayat_code = Emp.panchayat_code AND Emp.village_code = " + Utils.getQuotedString(villageCode) + " AND F4A.musterId = Emp.muster_id "; c = DBManager.getInstance().getRawQuery(query); int i = 0; if(c.moveToFirst()) { do { value[i++] = c.getString(0); }while (c.moveToNext()); } return value; } public String[] getHabitationWiseTotalRecords(String habitationCode, String villageCode) { String[] value = new String[2]; Cursor c = null; String query = "SELECT count(1) FROM " + SqliteConstants.TABLE_FORMAT4A + " WHERE habitation_code = " + Utils.getQuotedString(habitationCode) + " AND village_code = " + Utils.getQuotedString(villageCode) + " UNION ALL " + " SELECT count(1) FROM format4A AS F4A, "+SqliteConstants.TABLE_FORMAT4A +" AS Emp WHERE F4A.wageSeekerId = Emp.household_code AND " + " F4A.panchayat_code = Emp.panchayat_code AND Emp.habitation_code = " + Utils.getQuotedString(habitationCode) + " AND Emp.village_code = " + Utils.getQuotedString(villageCode) + " AND F4A.musterId = Emp.muster_id "; c = DBManager.getInstance().getRawQuery(query); int i = 0; if(c.moveToFirst()) { do { value[i++] = c.getString(0); }while (c.moveToNext()); } return value; } public String getHouseholdCode(String districtCode, String mandalCode, String panchayatCode) { Cursor c = null; String householdCode = ""; String query = "SELECT household_code FROM " + SqliteConstants.TABLE_FORMAT4A + " WHERE district_code = " + Utils.getQuotedString(districtCode) + " AND mandal_code = " + Utils.getQuotedString(mandalCode) + " AND panchayat_code = " + Utils.getQuotedString(panchayatCode) + " LIMIT 1"; c = DBManager.getInstance().getRawQuery(query); if(c.moveToFirst()) { householdCode = c.getString(0); householdCode = householdCode.substring(2, 5); } return householdCode; } }
package by.bytechs.xml.entity.cashStatus; import javax.xml.bind.annotation.*; /** * @author Romanovich Andrei */ @XmlAccessorType(value = XmlAccessType.FIELD) @XmlType(name = "PhysicalCUListXml", propOrder = {"physicalCUElm"}) @XmlRootElement(name = "physicalCUList") public class PhysicalCUListXml { @XmlElement(name = "PhysicalCU") private PhysicalCUXml physicalCUElm; public PhysicalCUXml getPhysicalCUElm() { return physicalCUElm; } public void setPhysicalCUElm(PhysicalCUXml physicalCUElm) { this.physicalCUElm = physicalCUElm; } }
package chess; import chess.board.*; import javafx.application.Application; import javafx.geometry.*; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.input.MouseEvent; import javafx.scene.layout.*; import javafx.stage.Stage; public class Chessboard extends Application { private Board board = new Board(); private Image boardImg = new Image("file:resources/chess_board.png"); private int selectedCol = -1; private int selectedRow = -1; public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { BackgroundSize backgroundSize = new BackgroundSize(100, 100, true, true, true, false); BackgroundImage backgroundImage = new BackgroundImage(boardImg, BackgroundRepeat.REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, backgroundSize); Background background = new Background(backgroundImage); GridPane grid = new GridPane(); grid.setAlignment(Pos.CENTER); grid.setBackground(background); for (int i = 0; i < 8; i++) { grid.getColumnConstraints().add(new ColumnConstraints(101)); } for (int i = 0; i < 8; i++) { grid.getRowConstraints().add(new RowConstraints(101)); } board.initBoard(); board.drawBoard(grid); grid.addEventHandler(MouseEvent.MOUSE_CLICKED, e -> { int col = (int)e.getX() / 101; int row = (int)e.getY() / 101; doClick(grid, col, row); }); Scene scene = new Scene(grid, 800, 800); primaryStage.setTitle("Chess"); primaryStage.setScene(scene); primaryStage.setResizable(false); primaryStage.show(); } public void doClick(GridPane grid, int col, int row) { System.out.println("1"); if (selectedCol < 0) { System.out.println("2"); selectedCol = col; selectedRow = row; } else { System.out.println("3"); board.move(selectedCol, selectedRow, col, row); selectedCol = -1; selectedRow = -1; } board.drawBoard(grid); board.highlightSelectedPiece(grid, col, row); //board.highlightPossibleMoves(grid, col, row); } }
package com.lab4; import java.util.Scanner; public class demo1 { public static void main(String[] args) { int n , sum = 0 ,temp; Scanner scanner = new Scanner(System.in); do { System.out.println("Nhap so phan tu mang :"); n = scanner.nextInt(); } while (n<0); // Khoi tao mang int arry[] = new int[n]; System.out.println("Nhap cac phan tu cho mang :"); for(int i = 0 ;i<n;i++) { System.out.println("Nhap phan tu thu :"+i); arry[i] = scanner.nextInt(); } // Hien thi mang vua nhap System.out.println("Hien thi mang vua nhap"); for(int i = 0 ; i < n ; i++) { System.out.print(arry[i]+"\t" +"\n"); } // Hien thi tong cac phan tu trong mang for(int i = 0 ; i < n ; i++) { sum += arry[i]; } System.out.println("Tổng các phần tử trong mảng :"+sum); // sắp xếp theo thứ tự giảm dần for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j <= n - 1; j++) { if (arry[i] < arry[j]) { temp = arry[i]; arry[i] = arry[j]; arry[j] = temp; } } } System.out.println("Mảng sau khi sắp xếp là: "); for (int i = 0; i < n; i++) { System.out.print(arry[i] + "\t"); } // tìm phần tử nhỏ nhất // sau khi sắp xếp theo thứ tự giảm dần // thì phần tử nhỏ nhất là phần tử cuối cùng trong mảng System.out.println("\nPhần tử nhỏ nhất trong mảng là " + arry[n - 1]); } }
/* * Created on Sep 7, 2004 */ package craterstudio.text; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.Random; import java.util.Set; import craterstudio.data.ByteList; import craterstudio.data.tuples.Pair; public class Text { public static boolean isNullOrEmpty(String value) { return (value==null) || value.isEmpty(); } // public static String trimToNull(String value) { if (value == null) return null; value = value.trim(); if (value.isEmpty()) return null; return value; } public static String nullToEmpty(String value) { return (value == null) ? "" : value; } public static String concat(String... args) { int len = 0; for (int i = 0; i < args.length; i++) len += (args[i] = (args[i] == null ? "null" : args[i])).length(); char[] chars = new char[len]; for (int i = 0, p = 0; i < args.length; i++) for (int k = 0; k < args[i].length(); k++) chars[p++] = args[i].charAt(k); return new String(chars); } private static final char[] table = "0123456789abcdef".toCharArray(); public static String hashAsHex(byte[] hash) { char[] table = Text.table; char[] digits = new char[hash.length << 1]; for (int k = 0; k < hash.length; k++) { int h = hash[k]; digits[(k << 1) | 1] = table[h & 0x0F]; digits[k << 1] = table[(h & 0xF0) >> 4]; } return new String(digits); } // private static final char[] generatecode_default_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890".toCharArray(); public static String generateRandomCode(int len) { return generateRandomCode(len, generatecode_default_chars); } public static String generateRandomCode(int len, char[] chars) { return generateRandomCode(len, chars, new SecureRandom()); } public static String generateRandomCode(int len, char[] chars, Random r) { char[] dst = new char[len]; for (int i = 0; i < dst.length; i++) dst[i] = chars[r.nextInt(chars.length)]; return new String(dst); } private static final int UUID_LENGTH = 16; private static final int UUID_MAX_ELEMENTS = 1024; private static Set<String> UUID_SET = new HashSet<String>(); private static LinkedList<String> UUID_LIST = new LinkedList<String>(); public static final synchronized String generateUniqueId() { // generate new UUID String uuid; do { uuid = Text.generateRandomCode(UUID_LENGTH); } while (!UUID_SET.add(uuid)); // clean up oldest UUID UUID_LIST.addLast(uuid); if (UUID_LIST.size() > UUID_MAX_ELEMENTS) UUID_SET.remove(UUID_LIST.removeFirst()); // return return uuid; } /** * ALIGN STRING */ public static final int ALIGN_LEFT = 0; public static final int ALIGN_CENTER = 1; public static final int ALIGN_RIGHT = 2; public static final String formatString(String text, int length) { return Text.formatString(text, length, ALIGN_LEFT, ' '); } public static final String formatString(String text, int length, char c) { return Text.formatString(text, length, ALIGN_LEFT, c); } public static final String formatString(String text, int length, int type) { return Text.formatString(text, length, type, ' '); } public static final String formatString(String text, int length, int type, char c) { if (text.length() > length) { if (text.length() >= 3) return text.substring(0, length - 3) + "..."; return "<?>"; } final char[] array = new char[length]; if (type == Text.ALIGN_LEFT) { int split = text.length(); for (int i = 0; i < split; i++) array[i] = text.charAt(i); for (int i = split; i < length; i++) array[i] = c; } if (type == Text.ALIGN_CENTER) throw new UnsupportedOperationException(); if (type == Text.ALIGN_RIGHT) { int split = length - text.length(); for (int i = 0; i < split; i++) array[i] = c; for (int i = split; i < length; i++) array[i] = text.charAt(i - split); } return new String(array); } /** * */ public static final boolean onlyNumbers(String val) { char[] arr = val.toCharArray(); for (int i = 0; i < arr.length; i++) { char c = arr[i]; if (c < '0' || c > '9') return false; } return true; } public static final boolean onlyLetters(String val) { char[] arr = val.toCharArray(); for (int i = 0; i < arr.length; i++) { char c = arr[i]; if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) return false; } return true; } /** * CONVERT */ public static final String ascii(byte[] raw, int off, int len) { char[] str = new char[len]; for (int i = 0; i < len; i++) str[i] = (char) raw[off + i]; return new String(str); } public static final String ascii(byte[] raw) { char[] str = new char[raw.length]; for (int i = 0; i < str.length; i++) str[i] = (char) raw[i]; return new String(str); } public static final byte[] ascii(String str) { byte[] raw = new byte[str.length()]; for (int i = 0; i < raw.length; i++) raw[i] = (byte) str.charAt(i); return raw; } public static final void ascii(OutputStream out, byte[] tmp, String str) throws IOException { int pos = 0; for (int i = 0; i < str.length(); i++) { tmp[pos++] = (byte) str.charAt(i); if (pos == tmp.length) { out.write(tmp, 0, pos); pos = 0; } } out.write(tmp, 0, pos); } public static String toLower(String s) { char[] ca = s.toCharArray(); for (int i = 0; i < ca.length; i++) { ca[i] = toLower(ca[i]); } return new String(ca); } public static String toUpper(String s) { char[] ca = s.toCharArray(); for (int i = 0; i < ca.length; i++) { ca[i] = toUpper(ca[i]); } return new String(ca); } public static char toLower(char c) { return (c >= 'A' && c <= 'Z') ? (char) (c + ('a' - 'A')) : c; } public static char toUpper(char c) { return (c >= 'a' && c <= 'z') ? (char) (c - ('a' - 'A')) : c; } // public static final String utf8(byte[] raw) { return Text.utf8(raw, 0, raw.length); } public static final String utf8(byte[] raw, int off, int len) { try { return new String(raw, off, len, "UTF-8"); } catch (UnsupportedEncodingException exc) { throw new IllegalStateException(); } } public static final byte[] utf8(String str) { try { return str.getBytes("UTF-8"); } catch (UnsupportedEncodingException exc) { throw new IllegalStateException(); } } // private static final String encoding = "ISO-8859-1"; // "UTF-8"; public static final String convert(byte[] data) { return convert(data, encoding); } public static final String convert(byte[] data, String encoding) { try { return new String(data, encoding); } catch (Exception exc) { return null; } } public static final String convert(byte[] data, int offset, int length) { try { return new String(data, offset, length, encoding); } catch (Exception exc) { return null; } } public static final byte[] convert(String value) { try { return value.getBytes(encoding); } catch (Exception exc) { return null; } } /** * CHOP LAST */ public static String chopLast(String value, int chars) { if (chars < 0 || chars > value.length()) throw new IllegalArgumentException("invalid chars: " + chars + " / " + value.length()); return value.substring(0, value.length() - chars); } public static StringBuilder chopLast(StringBuilder value, int chars) { if (chars < 0 || chars > value.length()) throw new IllegalArgumentException("invalid chars: " + chars + " / " + value.length()); value.setLength(value.length() - chars); return value; } /** * FLIP */ public static final String flip(String value) { char[] arr = value.toCharArray(); int half = arr.length / 2; int end = arr.length - 1; for (int i = 0; i < half; i++) { char c = arr[i]; arr[i] = arr[end - i]; arr[end - i] = c; } return String.valueOf(arr); } public static String firstOccurence(String text, String... finds) { int min = Integer.MAX_VALUE; String first = null; for (String find : finds) { int i = text.indexOf(find); if (i != -1 && i < min) { min = i; first = find; } } return first; } public static Pair<String, Integer> firstOccurenceWithIndex(String text, String... finds) { int min = Integer.MAX_VALUE; String first = null; for (String find : finds) { int i = text.indexOf(find); if (i != -1 && i < min) { min = i; first = find; } } if (first == null) return null; return new Pair<String, Integer>(first, Integer.valueOf(min)); } /** * SPLIT */ public static final String[] depthAwareSplit(String value, char split, char open, char close) { List<String> list = new ArrayList<String>(); int depth = 0; int lastStart = 0; for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (c == open) { depth++; continue; } if (c == close) { depth--; continue; } if (c != split || depth != 0) { continue; } list.add(value.substring(lastStart, i)); lastStart = i + 1; } if (lastStart != value.length()) list.add(value.substring(lastStart)); return list.toArray(new String[list.size()]); } public static final String normalizeLinebreaks(String value) { value = Text.replace(value, "\r\n", "\n"); value = Text.replace(value, '\r', '\n'); return value; } public static final String[] splitOnLines(String value) { return Text.split(normalizeLinebreaks(value), '\n'); } public static final String[] split(String value, char d) { String[] buf = new String[count(value, d) + 1]; split(value, d, buf); return buf; } public static final String[] splitOnUnicodeWhitespace(String value) { List<String> parts = new ArrayList<String>(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < value.length(); i++) { if (Character.isWhitespace(value.charAt(i))) { parts.add(sb.toString()); sb.setLength(0); } else { sb.append(value.charAt(i)); } } parts.add(sb.toString()); sb.setLength(0); return parts.toArray(new String[parts.size()]); } public static final String[] split(String value, String d) { List<String> parts = new ArrayList<String>(); String[] buf = new String[2]; String[] pair; while ((pair = splitPair(value, d, buf)) != null) { parts.add(pair[0]); value = pair[1]; } parts.add(value); return parts.toArray(new String[parts.size()]); } public static final int split(String value, char d, String[] buf) { int count = 0, n = value.length(), lastSplit = 0; for (int i = 0; i < n; i++) { if (value.charAt(i) == d) { buf[count++] = value.substring(lastSplit, i); lastSplit = i + 1; } } buf[count++] = value.substring(lastSplit, n); return count; } /** * PAIR */ public static final String[] splitPair(String pair, char d) { return Text.splitPair(pair, d, new String[2]); } public static final String[] splitPair(String pair, String d) { return Text.splitPair(pair, d, new String[2]); } public static final String[] splitPair(String pair, char d, String[] result) { int split = pair.indexOf(d); if (split == -1) return null; result[0] = pair.substring(0, split); result[1] = pair.substring(split + 1); return result; } public static final String[] splitPair(String pair, String d, String[] result) { int split = pair.indexOf(d); if (split == -1) return null; result[0] = pair.substring(0, split); result[1] = pair.substring(split + d.length()); return result; } public static final String[] splitOnUppercase(String input) { StringBuilder part = new StringBuilder(); List<String> parts = new ArrayList<String>(); for (char c : input.toCharArray()) { if (Character.isUpperCase(c)) { if (part.length() > 0) parts.add(part.toString()); part.setLength(0); } part.append(c); } if (part.length() > 0) parts.add(part.toString()); return parts.toArray(new String[parts.size()]); } /** * CHOP */ public static final String[] chop(String value, int size) { int fullParts = value.length() / size; int extra = ((value.length() % size) != 0) ? 1 : 0; String[] part = new String[fullParts + extra]; for (int i = 0; i < fullParts; i++) part[i] = value.substring(i * size, (i + 1) * size); if (extra != 0) part[fullParts] = value.substring(fullParts * size); return part; } /** * JOIN */ public static final String join(String[] value) { return Text.join(value, 0, value.length); } public static final String join(String[] value, char c) { return Text.join(value, 0, value.length, c); } public static final String join(String[] value, String s) { return Text.join(value, 0, value.length, s); } public static final String join(String[] value, int off, int len) { StringBuilder buffer = new StringBuilder(); for (int i = 0; i < len; i++) buffer.append(value[off + i]); return buffer.toString(); } public static final String join(String[] value, int off, int len, char c) { StringBuilder buffer = new StringBuilder(); for (int i = 0; i < len; i++) { buffer.append(value[off + i]); if (i != len - 1) buffer.append(c); } return buffer.toString(); } public static final String join(String[] value, int off, int len, String s) { StringBuilder buffer = new StringBuilder(); for (int i = 0; i < len; i++) { buffer.append(value[off + i]); if (i != len - 1) buffer.append(s); } return buffer.toString(); } public static final String[] multiSplit(String value, char... cs) { int[] in = new int[cs.length]; int or = 0; for (int i = 0; i < in.length; i++) if ((or |= in[i] = value.indexOf(cs[i], i == 0 ? 0 : in[i - 1] + 1)) < 0) return null; String[] parts = new String[cs.length + 1]; for (int i = 0; i < parts.length - 1; i++) parts[i] = value.substring(i == 0 ? 0 : in[i - 1] + 1, in[i]); parts[parts.length - 1] = value.substring(in[in.length - 1] + 1); return parts; } // INPUT: "abc def_ghi jkl_mno pqr" & [" ","_"] // OUTPUT: ["abc","def","ghi","jkl","mno pqr"] public static final String[] multiSplit(String value, String... ss) { int[] in = new int[ss.length]; int or = 0; for (int i = 0; i < ss.length; i++) if ((or |= in[i] = value.indexOf(ss[i], i == 0 ? 0 : in[i - 1] + ss[i - 1].length())) < 0) return null; String[] parts = new String[ss.length + 1]; for (int i = 0; i < parts.length - 1; i++) parts[i] = value.substring(i == 0 ? 0 : in[i - 1] + ss[i - 1].length(), in[i]); parts[parts.length - 1] = value.substring(in[in.length - 1] + ss[ss.length - 1].length()); return parts; } public static final String[] multiSplitAll(String value, char... cs) { List<String> results = new ArrayList<String>(); while (value != null) { String[] result = Text.multiSplit(value, cs); if (result == null) { results.add(value); value = null; } else { for (int i = 0; i < result.length - 1; i++) results.add(result[i]); value = result[result.length - 1]; } } return results.toArray(new String[results.size()]); } public static final String[] multiSplitLoop_bugged(String value, char... cs) { List<String> results = new ArrayList<String>(); while (value != null) { String[] result = Text.multiSplit(value, cs); if (result == null) { results.add(value); value = null; } else { for (int i = 0; i < result.length - 1; i++) results.add(result[i]); value = result[result.length - 1]; } } return results.toArray(new String[results.size()]); } public static final String[] multiSplitLoop_bugged(String value, String... ss) { List<String> results = new ArrayList<String>(); while (value != null) { String[] result = Text.multiSplit(value, ss); if (result == null) { results.add(value); value = null; } else { for (int i = 0; i < result.length - 1; i++) results.add(result[i]); value = result[result.length - 1]; } } return results.toArray(new String[results.size()]); } /** * BEFORE / AFTER / BETWEEN */ public static String before(String text, char find) { int offset = text.indexOf(find); if (offset == -1) return null; return text.substring(0, offset); } public static String before(String text, String find) { int offset = text.indexOf(find); if (offset == -1) return null; return text.substring(0, offset); } public static String beforeLast(String text, char find) { int offset = text.lastIndexOf(find); if (offset == -1) return null; return text.substring(0, offset); } public static String beforeLast(String text, String find) { int offset = text.lastIndexOf(find); if (offset == -1) return null; return text.substring(0, offset); } // public static String after(String text, char find) { int offset = text.indexOf(find); if (offset == -1) return null; return text.substring(offset + 1); } public static String after(String text, String find) { int offset = text.indexOf(find); if (offset == -1) return null; return text.substring(offset + find.length()); } public static String afterLast(String text, char find) { int offset = text.lastIndexOf(find); if (offset == -1) return null; return text.substring(offset + 1); } public static String afterLast(String text, String find) { int offset = text.lastIndexOf(find); if (offset == -1) return null; return text.substring(offset + find.length()); } // public static String betweenOuter(String text, char start, char end) { String after = Text.after(text, start); if (after == null) return null; return Text.beforeLast(after, end); } public static String betweenOuter(String text, String start, String end) { String after = Text.after(text, start); if (after == null) return null; return Text.beforeLast(after, end); } // public static String between(String text, char start, char end) { String after = Text.after(text, start); if (after == null) return null; return Text.before(after, end); } public static String between(String text, String start, String end) { String after = Text.after(text, start); if (after == null) return null; return Text.before(after, end); } public static String between(String text, char start, char end, String def) { return Text.replaceOnNull(Text.between(text, start, end), def); } public static String between(String text, String start, String end, String def) { return Text.replaceOnNull(Text.between(text, start, end), def); } public static String[] multiBetween(String text, String start, String end) { List<String> matches = new ArrayList<String>(); while (true) { String afterStart = Text.after(text, start); if (afterStart == null) break; String[] matchAndNext = Text.splitPair(afterStart, end); if (matchAndNext == null) break; matches.add(matchAndNext[0]); text = matchAndNext[1]; } return matches.toArray(new String[matches.size()]); } // private static String replaceOnNull(String text, String replace) { return (text == null) ? replace : text; } // public static String beforeIfAny(String text, char find) { return Text.replaceOnNull(Text.before(text, find), text); } public static String beforeIfAny(String text, String find) { return Text.replaceOnNull(Text.before(text, find), text); } public static String beforeLastIfAny(String text, char find) { return Text.replaceOnNull(Text.beforeLast(text, find), text); } public static String beforeLastIfAny(String text, String find) { return Text.replaceOnNull(Text.beforeLast(text, find), text); } // public static String afterIfAny(String text, char find) { return Text.replaceOnNull(Text.after(text, find), text); } public static String afterIfAny(String text, String find) { return Text.replaceOnNull(Text.after(text, find), text); } public static String afterLastIfAny(String text, char find) { return Text.replaceOnNull(Text.afterLast(text, find), text); } public static String afterLastIfAny(String text, String find) { return Text.replaceOnNull(Text.afterLast(text, find), text); } // public static String before(String text, char find, String def) { return Text.replaceOnNull(Text.before(text, find), def); } public static String before(String text, String find, String def) { return Text.replaceOnNull(Text.before(text, find), def); } public static String beforeLast(String text, char find, String def) { return Text.replaceOnNull(Text.beforeLast(text, find), def); } public static String beforeLast(String text, String find, String def) { return Text.replaceOnNull(Text.beforeLast(text, find), def); } public static String after(String text, char find, String def) { return Text.replaceOnNull(Text.after(text, find), def); } public static String after(String text, String find, String def) { return Text.replaceOnNull(Text.after(text, find), def); } public static String afterLast(String text, char find, String def) { return Text.replaceOnNull(Text.afterLast(text, find), def); } public static String afterLast(String text, String find, String def) { return Text.replaceOnNull(Text.afterLast(text, find), def); } /** * */ public static final int[] indicesOf(String s, char c) { int[] p = new int[Text.count(s, c)]; for (int i = 0, j = 0; i < s.length(); i++) if (s.charAt(i) == c) p[j++] = i; return p; } public static final int[] indicesOf(String s, String m) { if (m.length() == 0) throw new IllegalArgumentException("empty match"); int[] p = new int[Text.count(s, m)]; int i = 0; int offset = 0; while (true) { int off = s.indexOf(m, offset); if (off == -1) break; p[i++] = off; offset = off + m.length(); } return p; } /** * COUNT */ public static final int count(String s, char d) { int n = s.length(), x = 0; for (int i = 0; i < n; i++) if (s.charAt(i) == d) x++; return x; } public static final int count(String s, String d) { int count = 0, offset = 0; while (true) { int off = s.indexOf(d, offset); if (off == -1) break; count++; offset = off + d.length(); } return count; } public static String repeat(String s, int count) { if (count < 0) throw new IllegalArgumentException(); if (count == 0) return ""; if (count == 1) return s; StringBuilder sb = new StringBuilder(); for (int i = 0; i < count; i++) sb.append(s); return sb.toString(); } public static String repeat(char c, int count) { if (count < 0) throw new IllegalArgumentException(); if (count == 0) return ""; if (count == 1) return String.valueOf(c); char[] cs = new char[count]; for (int i = 0; i < count; i++) cs[i] = c; return new String(cs); } /** * REPLACE */ public static final String replaceBetweenIfAny(String s, String open, String close, String replaceWith) { int i = s.indexOf(open); if (i == -1 || s.indexOf(close, i + open.length()) == -1) return s; // early escape String a = Text.before(s, open); if (a == null) return s; // not so early escape String b = Text.after(Text.after(s, open), close); if (b == null) return s; return a + open + replaceWith + close + b; } public static final String replaceAllBetween(String s, String open, String close, String replaceWith) { if (s.indexOf(open) == -1 || s.indexOf(close) == -1) return s; // early escape String remaining = s; StringBuilder done = new StringBuilder(); while (true) { int indexOfOpen = remaining.indexOf(open); if (indexOfOpen == -1) break; int indexOfClose = remaining.indexOf(close, indexOfOpen + open.length()); if (indexOfClose == -1) break; String before = remaining.substring(0, indexOfOpen); done.append(before); if (replaceWith != null) done.append(replaceWith); remaining = remaining.substring(indexOfClose + close.length()); } return done.append(remaining).toString(); } public static final String replace(String s, char a, char b) { if (s.indexOf(a) == -1) return s; // early escape char[] array = s.toCharArray(); for (int i = 0; i < array.length; i++) if (array[i] == a) array[i] = b; return new String(array); } public static final String replace(String s, String a, String b) { if (s.indexOf(a) == -1) return s; // early escape StringBuilder sb = new StringBuilder(); int len = a.length(); int off = 0; while (true) { int found = s.indexOf(a, off); if (found == -1) { sb.append(s.substring(Math.min(off, s.length()))); break; } sb.append(s.substring(off, found)); sb.append(b); off += (found - off) + len; } return sb.toString(); } public static final String replaceIfEquals(String s, String a, String b) { if (s == null) return (a == null) ? b : s; return s.equals(a) ? b : s; } /** * REMOVE */ public static final String removeInnerIfAny(String s, String open, String close) { String a = Text.before(s, open); if (a == null) return s; String b = Text.after(s, open); if (b.startsWith(close)) return s; String c = Text.after(b, close); if (c == null) return s; return a + open + close + c; } public static final String removeOuterIfAny(String s, String open, String close) { String a = Text.before(s, open); if (a == null) return s; String b = Text.after(Text.after(s, open), close); if (b == null) return s; return a + b; } public static final String removeAllInner(String s, String open, String close) { while (true) { String replaced = Text.removeInnerIfAny(s, open, close); if (replaced == s) break; s = replaced; } return s; } public static final String removeAllOuter(String s, String open, String close) { while (true) { String replaced = Text.removeOuterIfAny(s, open, close); if (replaced == s) break; s = replaced; } return s; } public static final String remove(String s, char c) { int count = Text.count(s, c); if (count == 0) return s; char[] curr = s.toCharArray(); char[] next = new char[curr.length - count]; for (int i = 0, j = 0; i < curr.length; i++) if (curr[i] != c) next[j++] = curr[i]; return new String(next); } public static final String remove(String s, char... cs) { int count = 0; for (char c : cs) count += Text.count(s, c); if (count == 0) return s; char[] curr = s.toCharArray(); char[] next = new char[curr.length - count]; outer: for (int i = 0, j = 0; i < curr.length; i++) { for (int k = 0; k < cs.length; k++) if (curr[i] == cs[k]) continue outer; next[j++] = curr[i]; } return new String(next); } public static final String remove(String s, String find) { return Text.replace(s, find, ""); } public static final String convertWhiteSpaceTo(String s, char c) { char[] cs = s.toCharArray(); for (int i = 0; i < cs.length; i++) if (cs[i] <= ' ') cs[i] = c; return new String(cs); } // public static final int indexOfWhiteSpace(String s) { for (int i = 0; i < s.length(); i++) if (s.charAt(i) <= ' ') return i; return -1; } public static final int lastIndexOfWhiteSpace(String s) { for (int i = s.length() - 1; i >= 0; i--) if (s.charAt(i) <= ' ') return i; return -1; } public static final String[] splitOnWhiteSpace(String s) { s = Text.convertWhiteSpaceTo(s, ' '); s = Text.removeDuplicates(s, ' '); return Text.split(s, ' '); } public static final String[] splitPairOnWhiteSpace(String s) { s = Text.convertWhiteSpaceTo(s, ' '); s = Text.removeDuplicates(s, ' '); return Text.splitPair(s, ' '); } public static final String trimBefore(String s) { for (int i = 0; i < s.length(); i++) if (s.charAt(i) > ' ') return s.substring(i); return ""; } public static final String removeDuplicates(String s, char c) { if (s.indexOf(c) == -1) return s; // early escape if (s.indexOf(c) == s.lastIndexOf(c)) return s; // early escape char[] array = s.toCharArray(); StringBuilder buffer = new StringBuilder(); boolean duplicate = false; for (int i = 0; i < array.length; i++) { if (array[i] != c) { buffer.append(array[i]); duplicate = false; continue; } if (duplicate) continue; buffer.append(array[i]); duplicate = true; } return buffer.toString(); } /** * CONTAINS */ public static final boolean contains(String[] array, String search) { if (search == null) { for (String s : array) if (s == null) return true; } else { for (String s : array) if (search.equals(s)) return true; } return false; } /** * CAPITALIZE */ public static final String capitalize(String value) { if (value.length() == 0) return value; if (value.length() == 1) return value.toUpperCase(); return value.substring(0, 1).toUpperCase() + value.substring(1); } public static final String decapitalize(String value) { if (value.length() == 0) return value; if (value.length() == 1) return value.toLowerCase(); return value.substring(0, 1).toLowerCase() + value.substring(1); } /** * ARGS */ public static final Map<String, String> parseProperties(String value) { Map<String, String> map = new HashMap<String, String>(); String[] lines = Text.splitOnLines(value); for (String line : lines) { line = Text.beforeIfAny(line, '#'); line = line.trim(); if (line.length() == 0) continue; String[] pair = Text.splitPair(line, '='); if (pair == null) continue; String key = pair[0].trim(); String val = pair[1].trim(); map.put(key, val); } return map; } public static final Map<String, String> parseArgs(String value, String sep, String split) { String[] pairs = Text.split(value, sep); String[] part = new String[2]; Map<String, String> map = new HashMap<String, String>(); for (String pair : pairs) { if (!pair.contains(String.valueOf(split))) continue; Text.splitPair(pair, split, part); map.put(part[0], part[1]); } return map; } public static final Map<String, String> parseArgs(String value, char sep, char split) { String[] pairs = Text.split(value, sep); String[] pair = new String[2]; Map<String, String> map = new HashMap<String, String>(); for (String p : pairs) { if (Text.splitPair(p, split, pair) == null) map.put(p, ""); else map.put(pair[0], pair[1]); } return map; } public static final String joinArgs(Map<String, String> map, String sep, String split) { StringBuilder sb = new StringBuilder(); for (String key : map.keySet()) { sb.append(key); sb.append(split); sb.append(map.get(key)); sb.append(sep); } if (sb.length() > 0) { sb.setLength(sb.length() - 1); } return sb.toString(); } public static final String joinArgs(Map<String, String> map, char sep, char split) { StringBuilder sb = new StringBuilder(); for (String key : map.keySet()) { sb.append(key); sb.append(split); sb.append(map.get(key)); sb.append(sep); } if (sb.length() > 0) { sb.setLength(sb.length() - 1); } return sb.toString(); } /** * DECODE URL */ public static final String decodeURL(String encoded, String charset) { return Text.decodeURL(encoded, charset, true); } public static final String decodeURL(String encoded, String charset, boolean decodePlus) { if (decodePlus) { encoded = Text.replace(encoded, '+', ' '); } StringBuilder chars = new StringBuilder(); ByteList hex = new ByteList(); Charset decoder = Charset.forName(charset); String[] parts = Text.split(encoded, '%'); for (int i = 0; i < parts.length; i++) { String part = parts[i]; if (i == 0) chars.append(part); else if (part.isEmpty()) continue; else if (part.startsWith("u")) { if (hex.size() > 0) { chars.append(decoder.decode(ByteBuffer.wrap(hex.toArray())).toString()); hex.clear(); } try { int unicode = 0; unicode |= chr2oct(part.charAt(1)) << 12; unicode |= chr2oct(part.charAt(2)) << 8; unicode |= chr2oct(part.charAt(3)) << 4; unicode |= chr2oct(part.charAt(4)) << 0; chars.append((char) unicode); chars.append(part.substring(5)); } catch (IllegalStateException exc) { chars.append(part); } } else { try { int unicode = 0; unicode |= chr2oct(part.charAt(0)) << 4; unicode |= chr2oct(part.charAt(1)) << 0; hex.add((byte) unicode); if (part.length() == 2) continue; } catch (IllegalStateException exc) { chars.append(part); } if (hex.size() > 0) { chars.append(Charset.forName(charset).decode(ByteBuffer.wrap(hex.toArray())).toString()); hex.clear(); } chars.append(part.substring(2)); } } if (hex.size() > 0) { chars.append(Charset.forName(charset).decode(ByteBuffer.wrap(hex.toArray())).toString()); hex.clear(); } return chars.toString(); } private static int chr2oct(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return 10 + c - 'a'; if (c >= 'A' && c <= 'F') return 10 + c - 'A'; throw new IllegalStateException(); } /** * */ public static final void mainArgsLookup(String[] args, Map<String, String> params) { for (String key : params.keySet()) { String val = Text.mainArgsLookup(args, key); if (val == null) { if (params.get(key) == null) throw new IllegalStateException("parameter for -" + key + " not found, and no default value"); } else { params.put(key, val); } } } public static final String mainArgsLookup(String[] args, String key) { return Text.mainArgsLookup(args, key, null); } public static final String mainArgsLookup(String[] args, String key, String def) { return Text.mainArgsLookup(args, key, def, 0); } public static final List<String> mainArgsLookups(String[] args, String key) { key = "-" + key; List<String> matches = new ArrayList<String>(); for (int i = 0; i < args.length - 1; i++) if (args[i].equals(key)) matches.add(args[i += 1]); return matches; } public static final String mainArgsLookup(String[] args, String key, String def, int skip) { key = "-" + key; for (int i = 0; i < args.length - 1; i++) if (args[i].equals(key) && (skip-- == 0)) return args[i + 1]; return def; } public static boolean areCharsAt(String s, char c, int off1, int off2) { if (s.charAt(off1) == c) if (s.charAt(off2) == c) return true; return false; } public static boolean areDigits(String s, int off, int len) { int end = off + len; for (int i = off; i < end; i++) if (s.charAt(i) < '0' || s.charAt(i) > '9') return false; return true; } /** * ROMAN */ public static final String rot13(String input) { char[] out = input.toCharArray(); int i = 0; for (char c : out) { if (c >= 'a' && c <= 'z') { c -= 'a'; c += 13; c %= 26; c += 'a'; } else if (c >= 'A' && c <= 'Z') { c -= 'A'; c += 13; c %= 26; c += 'A'; } else if (c >= '0' && c <= '9') { c -= '0'; c += 5; c %= 10; c += '0'; } out[i++] = c; } return new String(out); } // public static String traverse(String input, String[] delimiters, int[] maxLengths, TextTransformer transformer) { // if (maxLengths.length + 1 != delimiters.length) // throw new IllegalStateException(); // String[] matches = new String[maxLengths.length]; // // StringBuilder rewritten = null; // // int offset = 0; // // outer: while (!input.isEmpty()) { // int[] ios = new int[delimiters.length]; // // for (int i = 0; i < delimiters.length; i++) { // int off = (i == 0) ? offset : (ios[i - 1] + delimiters[i - 1].length()); // ios[i] = input.indexOf(delimiters[i], off); // if (ios[i] == -1) { // // not found // break outer; // } // // if (i == 0) { // continue; // } // // String ps = delimiters[i - 1]; // int pio = ios[i - 1]; // // // too long? // int len = (ios[i] - pio) - ps.length(); // if (len > maxLengths[i - 1]) { // // advance // offset = ios[0] + 1; // continue outer; // } // // matches[i - 1] = input.substring(pio + ps.length(), ios[i]); // } // // // match! // // if (rewritten == null) // rewritten = new StringBuilder(); // // // merge! // String[] merged = new String[(matches.length << 1) + 1]; // for (int i = 0; i < merged.length; i++) // merged[i] = ((i & 1) == 0) ? delimiters[i >> 1] : matches[i >> 1]; // transformer.transform(merged); // // rewritten.append(input.substring(0, ios[0])); // rewritten.append(join(merged)); // input = input.substring(ios[ios.length - 1] + delimiters[ios.length - 1].length()); // offset = 0; // } // // if (rewritten != null) { // input = rewritten.append(input).toString(); // } // // return input; // } }
package com.me.interview.services; import com.me.interview.api.TransactionResponse; import reactor.core.publisher.Mono; public interface ITransactionsServices { Mono<TransactionResponse> getTransactions(String accountID, String fromDate, String toDate); }
package 数据结构.线性结构.线性表; /** * Created by Yingjie.Lu on 2018/8/30. */ /** * @Title: 通过顺序存储实现的线性表 * @Date: 2018/8/30 9:21 */ public class MyArrayList { private Object[] arr = new Object[10];//默认初始化数组大小为10个 private int size=0;//记录数组里面的个数 public int size(){ return size; } /** * @Title: 添加一个元素 * @Date: 2018/8/30 9:51 */ public void add(Object o){ if(size==arr.length){ Object[] buff=new Object[size*2]; System.arraycopy(arr,0,buff,0,size); arr=buff; } arr[size]=o; size++; } /** * @Title: 判断数组是否为空 * @Date: 2018/8/30 9:51 */ public boolean isEmpty(){ if(size==0){ return true; }else{ return false; } } /** * @Title: 删除一个元素 * @Date: 2018/8/30 9:51 */ public void remove(int index){ System.arraycopy(arr,index,arr,index-1,size-index); size--; } /** * @Title: 通过下标获取一个元素 * @Date: 2018/8/30 9:52 */ public Object get(int index){ return arr[index]; } /** * @Title: 通过下标修改一个元素 * @Date: 2018/8/30 9:52 */ public void update(int index,Object o){ arr[index]=o; } public static void main(String[] args) { MyArrayList list=new MyArrayList(); for(int i=0;i<12;i++){ list.add(i); } list.remove(6); list.update(2,4); for(int i=0;i<list.size;i++){ System.out.println(list.get(i)); } } }
package com.eshop.service.impl; import com.eshop.dao.OrderDao; import com.eshop.dao.impl.OrderDaoImpl; import com.eshop.domain.Basket; import com.eshop.domain.Order; import com.eshop.domain.Product; import org.junit.Before; import org.junit.Test; import java.time.LocalDate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.mockito.Mockito.*; import static org.junit.Assert.*; public class OrderServiceImplTest { private Basket basketMock = mock(Basket.class); private Product productMock = mock(Product.class); private OrderServiceImpl service = new OrderServiceImpl(); private LocalDate start = LocalDate.of(2019, 1, 1); private LocalDate finish = LocalDate.of(2019, 2, 1); private Order orderMock = mock(Order.class); private List<Order> orders = new ArrayList<>(); private OrderDao daoMock = mock(OrderDaoImpl.class); @Before public void prepare() { service.setDao(daoMock); Map<Product, Integer> productsInBasketMock = new HashMap<>(); when(productMock.getProductPrice()).thenReturn(10000.0); productsInBasketMock.put(productMock, 1); basketMock.setProductsInBasket(productsInBasketMock); List<Order> orders = new ArrayList<>(); when(daoMock.getOrdersPerPeriod(start, finish)).thenReturn(orders); } @Test public void sumOfOrder() { assertEquals(service.sumOfOrder(basketMock), 10000.0, 10000.0); } @Test public void getTotalAmountOfOrdersPerPeriod() { orders.add(orderMock); when(service.getOrdersPerPeriod(start, finish)).thenReturn(orders); assertEquals(service.getTotalAmountOfOrdersPerPeriod(start, finish), 1); } @Test public void getTotalSumOfAllOrdersPerPeriod() { orders.add(orderMock); when(orderMock.getSumOfOrder()).thenReturn(10000.0); assertEquals(service.getTotalAmountOfOrdersPerPeriod(start, finish), 10000.0, 10000.0); } }
package com.yhkx.core.storage.dao.entity; import org.hibernate.validator.constraints.Length; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * ${remark} * * @author LiSs */ @Table(name = "TB_EMP_DATA") public class TbEmpData implements Serializable { @Length(max = 10, message = "PLAN_RPT_FLT_NO 长度不能超过10") @Column(name = "PLAN_RPT_FLT_NO") private String planRptFltNo; @Length(max = 50, message = "CONTACT 长度不能超过50") @Column(name = "CONTACT") private String contact; @Column(name = "DUTY_EXPR_DATE") private Date dutyExprDate; @Length(max = 32, message = "PRFTNL_TYPE 长度不能超过32") @Column(name = "PRFTNL_TYPE") private String prftnlType; @Length(max = 20, message = "PLAN_RPT_DATE 长度不能超过20") @Column(name = "PLAN_RPT_DATE") private String planRptDate; @Length(max = 100, message = "IN_DUTY_DOCNO 长度不能超过100") @Column(name = "IN_DUTY_DOCNO") private String inDutyDocno; @Length(max = 10, message = "JOB_TIME 长度不能超过10") @Column(name = "JOB_TIME") private String jobTime; @Column(name = "PARTY_ENTR_DATE") private Date partyEntrDate; @Length(max = 20, message = "SPCL_MEMO 长度不能超过20") @Column(name = "SPCL_MEMO") private String spclMemo; @Column(name = "ENTR_MF_DATE") private Date entrMfDate; @Length(max = 20, message = "HOUSE_BOOK 长度不能超过20") @Column(name = "HOUSE_BOOK") private String houseBook; @Column(name = "RE_WORK_DATE") private Date reWorkDate; @Length(max = 6, message = "ARCH_ID 长度不能超过6") @Column(name = "ARCH_ID") private String archId; @NotNull(message = "EMP_SID not allow null") @Column(name = "EMP_SID") private BigDecimal empSid; @Length(max = 20, message = "NATIVE_PLACE 长度不能超过20") @Column(name = "NATIVE_PLACE") private String nativePlace; @Length(max = 20, message = "CERT_NO 长度不能超过20") @Column(name = "CERT_NO") private String certNo; @Length(max = 20, message = "CTRCT_PLACE 长度不能超过20") @Column(name = "CTRCT_PLACE") private String ctrctPlace; @Length(max = 80, message = "DEP_NAME 长度不能超过80") @Column(name = "DEP_NAME") private String depName; @Column(name = "BIRTHDAY") private Date birthday; @Length(max = 500, message = "MEMO 长度不能超过500") @Column(name = "MEMO") private String memo; @Length(max = 32, message = "DIPLOMA_TYPE 长度不能超过32") @Column(name = "DIPLOMA_TYPE") private String diplomaType; @Length(max = 20, message = "E0122 长度不能超过20") @Column(name = "E0122") private String e0122; @Length(max = 20, message = "MGMT_LEVEL 长度不能超过20") @Column(name = "MGMT_LEVEL") private String mgmtLevel; @Length(max = 50, message = "EMP_TYPE 长度不能超过50") @Column(name = "EMP_TYPE") private String empType; @Length(max = 12, message = "WHEN_IN_DUTY 长度不能超过12") @Column(name = "WHEN_IN_DUTY") private String whenInDuty; @Length(max = 4, message = "PLAN_ID 长度不能超过4") @Column(name = "PLAN_ID") private String planId; @Length(max = 20, message = "DORM_ADDR 长度不能超过20") @Column(name = "DORM_ADDR") private String dormAddr; @Length(max = 20, message = "MGMT_LEVEL_NO 长度不能超过20") @Column(name = "MGMT_LEVEL_NO") private String mgmtLevelNo; @Length(max = 8, message = "TYPEID 长度不能超过8") @Column(name = "TYPEID") private String typeid; @Length(max = 50, message = "SPCL_ORIENTATION 长度不能超过50") @Column(name = "SPCL_ORIENTATION") private String spclOrientation; @Length(max = 100, message = "SMPL_NAME 长度不能超过100") @Column(name = "SMPL_NAME") private String smplName; @Length(max = 16, message = "CATALOG_TYPE 长度不能超过16") @Column(name = "CATALOG_TYPE") private String catalogType; @Length(max = 20, message = "JOB_TYPE 长度不能超过20") @Column(name = "JOB_TYPE") private String jobType; @Length(max = 150, message = "POST_ALL 长度不能超过150") @Column(name = "POST_ALL") private String postAll; @Length(max = 32, message = "DEGREE 长度不能超过32") @Column(name = "DEGREE") private String degree; @Length(max = 100, message = "RPT_PROGRESS_MEMO 长度不能超过100") @Column(name = "RPT_PROGRESS_MEMO") private String rptProgressMemo; @Length(max = 18, message = "ID_CARD 长度不能超过18") @Column(name = "ID_CARD") private String idCard; @Length(max = 16, message = "NATIONALITY 长度不能超过16") @Column(name = "NATIONALITY") private String nationality; @Length(max = 10, message = "QA_JOB_LEVEL 长度不能超过10") @Column(name = "QA_JOB_LEVEL") private String qaJobLevel; @Length(max = 20, message = "PLAN_RPT_CITY 长度不能超过20") @Column(name = "PLAN_RPT_CITY") private String planRptCity; @Column(name = "CTRCT_FROM_DATE") private Date ctrctFromDate; @Column(name = "DUTY_DATE") private Date dutyDate; @Length(max = 20, message = "ABORNAL_MEMO 长度不能超过20") @Column(name = "ABORNAL_MEMO") private String abornalMemo; @Length(max = 100, message = "TRAINING_STATUS 长度不能超过100") @Column(name = "TRAINING_STATUS") private String trainingStatus; @Length(max = 40, message = "POST_TYPE 长度不能超过40") @Column(name = "POST_TYPE") private String postType; @Length(max = 40, message = "QA_IN_DUTY 长度不能超过40") @Column(name = "QA_IN_DUTY") private String qaInDuty; @Length(max = 40, message = "JOB_WAIT_ID 长度不能超过40") @Column(name = "JOB_WAIT_ID") private String jobWaitId; @Length(max = 40, message = "RECRUIT_TYPE_MEMO 长度不能超过40") @Column(name = "RECRUIT_TYPE_MEMO") private String recruitTypeMemo; @Column(name = "WORK_DATE") private Date workDate; @Length(max = 40, message = "PRFTNL_NAME 长度不能超过40") @Column(name = "PRFTNL_NAME") private String prftnlName; @Length(max = 8, message = "PARTY_TYPE 长度不能超过8") @Column(name = "PARTY_TYPE") private String partyType; @Length(max = 800, message = "UNIT_NAME 长度不能超过800") @Column(name = "UNIT_NAME") private String unitName; @Length(max = 200, message = "WORK_POST 长度不能超过200") @Column(name = "WORK_POST") private String workPost; @Length(max = 200, message = "FULL_NAME 长度不能超过200") @Column(name = "FULL_NAME") private String fullName; @Column(name = "PLAN_RPT_FLT_DATE") private Date planRptFltDate; @Length(max = 8, message = "GENDER 长度不能超过8") @Column(name = "GENDER") private String gender; @Length(max = 70, message = "GRADUTE_SCHOOL 长度不能超过70") @Column(name = "GRADUTE_SCHOOL") private String graduteSchool; @Length(max = 16, message = "BONUS_CARD_PLACE 长度不能超过16") @Column(name = "BONUS_CARD_PLACE") private String bonusCardPlace; @Column(name = "RETIRE_DATE") private Date retireDate; @Length(max = 200, message = "OFFICE_NAME 长度不能超过200") @Column(name = "OFFICE_NAME") private String officeName; @Length(max = 20, message = "STU_ORIGIN 长度不能超过20") @Column(name = "STU_ORIGIN") private String stuOrigin; @Column(name = "QUIT_DATE") private Date quitDate; @Length(max = 5, message = "MF_ID 长度不能超过5") @NotNull(message = "MF_ID not allow null") @Id @Column(name = "MF_ID") private String mfId; @Column(name = "AGE") private BigDecimal age; @Length(max = 8, message = "POST_ID 长度不能超过8") @Column(name = "POST_ID") private String postId; @Length(max = 32, message = "STUDY_TYPE 长度不能超过32") @Column(name = "STUDY_TYPE") private String studyType; @Column(name = "CTRCT_EXPR_DATE") private Date ctrctExprDate; @Column(name = "QA_DATE") private Date qaDate; @Length(max = 100, message = "CN_NAME 长度不能超过100") @Column(name = "CN_NAME") private String cnName; @Length(max = 20, message = "QA_JOB_TYPE 长度不能超过20") @Column(name = "QA_JOB_TYPE") private String qaJobType; @Length(max = 100, message = "EKP_MAIN 长度不能超过100") @Column(name = "EKP_MAIN") private String ekpMain; @Length(max = 16, message = "ARMS_SPCL 长度不能超过16") @Column(name = "ARMS_SPCL") private String armsSpcl; @Length(max = 20, message = "CTRCT_TYPE 长度不能超过20") @Column(name = "CTRCT_TYPE") private String ctrctType; @Length(max = 80, message = "DUTY_NAME 长度不能超过80") @Column(name = "DUTY_NAME") private String dutyName; @Length(max = 20, message = "RECRUIT_POST 长度不能超过20") @Column(name = "RECRUIT_POST") private String recruitPost; @Length(max = 20, message = "ENROLL_FROM 长度不能超过20") @Column(name = "ENROLL_FROM") private String enrollFrom; @Length(max = 16, message = "HOUSE_BOOOK_TYPE 长度不能超过16") @Column(name = "HOUSE_BOOOK_TYPE") private String houseBoookType; @Length(max = 10, message = "PRFTNL_SERIAL 长度不能超过10") @Column(name = "PRFTNL_SERIAL") private String prftnlSerial; @Column(name = "PRFTNL_DATE") private Date prftnlDate; @Column(name = "GRADUATE_DATE") private Date graduateDate; public String getPlanRptFltNo() { return planRptFltNo; } public void setPlanRptFltNo(String planRptFltNo) { this.planRptFltNo = planRptFltNo; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public Date getDutyExprDate() { return dutyExprDate; } public void setDutyExprDate(Date dutyExprDate) { this.dutyExprDate = dutyExprDate; } public String getPrftnlType() { return prftnlType; } public void setPrftnlType(String prftnlType) { this.prftnlType = prftnlType; } public String getPlanRptDate() { return planRptDate; } public void setPlanRptDate(String planRptDate) { this.planRptDate = planRptDate; } public String getInDutyDocno() { return inDutyDocno; } public void setInDutyDocno(String inDutyDocno) { this.inDutyDocno = inDutyDocno; } public String getJobTime() { return jobTime; } public void setJobTime(String jobTime) { this.jobTime = jobTime; } public Date getPartyEntrDate() { return partyEntrDate; } public void setPartyEntrDate(Date partyEntrDate) { this.partyEntrDate = partyEntrDate; } public String getSpclMemo() { return spclMemo; } public void setSpclMemo(String spclMemo) { this.spclMemo = spclMemo; } public Date getEntrMfDate() { return entrMfDate; } public void setEntrMfDate(Date entrMfDate) { this.entrMfDate = entrMfDate; } public String getHouseBook() { return houseBook; } public void setHouseBook(String houseBook) { this.houseBook = houseBook; } public Date getReWorkDate() { return reWorkDate; } public void setReWorkDate(Date reWorkDate) { this.reWorkDate = reWorkDate; } public String getArchId() { return archId; } public void setArchId(String archId) { this.archId = archId; } public BigDecimal getEmpSid() { return empSid; } public void setEmpSid(BigDecimal empSid) { this.empSid = empSid; } public String getNativePlace() { return nativePlace; } public void setNativePlace(String nativePlace) { this.nativePlace = nativePlace; } public String getCertNo() { return certNo; } public void setCertNo(String certNo) { this.certNo = certNo; } public String getCtrctPlace() { return ctrctPlace; } public void setCtrctPlace(String ctrctPlace) { this.ctrctPlace = ctrctPlace; } public String getDepName() { return depName; } public void setDepName(String depName) { this.depName = depName; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } public String getDiplomaType() { return diplomaType; } public void setDiplomaType(String diplomaType) { this.diplomaType = diplomaType; } public String getE0122() { return e0122; } public void setE0122(String e0122) { this.e0122 = e0122; } public String getMgmtLevel() { return mgmtLevel; } public void setMgmtLevel(String mgmtLevel) { this.mgmtLevel = mgmtLevel; } public String getEmpType() { return empType; } public void setEmpType(String empType) { this.empType = empType; } public String getWhenInDuty() { return whenInDuty; } public void setWhenInDuty(String whenInDuty) { this.whenInDuty = whenInDuty; } public String getPlanId() { return planId; } public void setPlanId(String planId) { this.planId = planId; } public String getDormAddr() { return dormAddr; } public void setDormAddr(String dormAddr) { this.dormAddr = dormAddr; } public String getMgmtLevelNo() { return mgmtLevelNo; } public void setMgmtLevelNo(String mgmtLevelNo) { this.mgmtLevelNo = mgmtLevelNo; } public String getTypeid() { return typeid; } public void setTypeid(String typeid) { this.typeid = typeid; } public String getSpclOrientation() { return spclOrientation; } public void setSpclOrientation(String spclOrientation) { this.spclOrientation = spclOrientation; } public String getSmplName() { return smplName; } public void setSmplName(String smplName) { this.smplName = smplName; } public String getCatalogType() { return catalogType; } public void setCatalogType(String catalogType) { this.catalogType = catalogType; } public String getJobType() { return jobType; } public void setJobType(String jobType) { this.jobType = jobType; } public String getPostAll() { return postAll; } public void setPostAll(String postAll) { this.postAll = postAll; } public String getDegree() { return degree; } public void setDegree(String degree) { this.degree = degree; } public String getRptProgressMemo() { return rptProgressMemo; } public void setRptProgressMemo(String rptProgressMemo) { this.rptProgressMemo = rptProgressMemo; } public String getIdCard() { return idCard; } public void setIdCard(String idCard) { this.idCard = idCard; } public String getNationality() { return nationality; } public void setNationality(String nationality) { this.nationality = nationality; } public String getQaJobLevel() { return qaJobLevel; } public void setQaJobLevel(String qaJobLevel) { this.qaJobLevel = qaJobLevel; } public String getPlanRptCity() { return planRptCity; } public void setPlanRptCity(String planRptCity) { this.planRptCity = planRptCity; } public Date getCtrctFromDate() { return ctrctFromDate; } public void setCtrctFromDate(Date ctrctFromDate) { this.ctrctFromDate = ctrctFromDate; } public Date getDutyDate() { return dutyDate; } public void setDutyDate(Date dutyDate) { this.dutyDate = dutyDate; } public String getAbornalMemo() { return abornalMemo; } public void setAbornalMemo(String abornalMemo) { this.abornalMemo = abornalMemo; } public String getTrainingStatus() { return trainingStatus; } public void setTrainingStatus(String trainingStatus) { this.trainingStatus = trainingStatus; } public String getPostType() { return postType; } public void setPostType(String postType) { this.postType = postType; } public String getQaInDuty() { return qaInDuty; } public void setQaInDuty(String qaInDuty) { this.qaInDuty = qaInDuty; } public String getJobWaitId() { return jobWaitId; } public void setJobWaitId(String jobWaitId) { this.jobWaitId = jobWaitId; } public String getRecruitTypeMemo() { return recruitTypeMemo; } public void setRecruitTypeMemo(String recruitTypeMemo) { this.recruitTypeMemo = recruitTypeMemo; } public Date getWorkDate() { return workDate; } public void setWorkDate(Date workDate) { this.workDate = workDate; } public String getPrftnlName() { return prftnlName; } public void setPrftnlName(String prftnlName) { this.prftnlName = prftnlName; } public String getPartyType() { return partyType; } public void setPartyType(String partyType) { this.partyType = partyType; } public String getUnitName() { return unitName; } public void setUnitName(String unitName) { this.unitName = unitName; } public String getWorkPost() { return workPost; } public void setWorkPost(String workPost) { this.workPost = workPost; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public Date getPlanRptFltDate() { return planRptFltDate; } public void setPlanRptFltDate(Date planRptFltDate) { this.planRptFltDate = planRptFltDate; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getGraduteSchool() { return graduteSchool; } public void setGraduteSchool(String graduteSchool) { this.graduteSchool = graduteSchool; } public String getBonusCardPlace() { return bonusCardPlace; } public void setBonusCardPlace(String bonusCardPlace) { this.bonusCardPlace = bonusCardPlace; } public Date getRetireDate() { return retireDate; } public void setRetireDate(Date retireDate) { this.retireDate = retireDate; } public String getOfficeName() { return officeName; } public void setOfficeName(String officeName) { this.officeName = officeName; } public String getStuOrigin() { return stuOrigin; } public void setStuOrigin(String stuOrigin) { this.stuOrigin = stuOrigin; } public Date getQuitDate() { return quitDate; } public void setQuitDate(Date quitDate) { this.quitDate = quitDate; } public String getMfId() { return mfId; } public void setMfId(String mfId) { this.mfId = mfId; } public BigDecimal getAge() { return age; } public void setAge(BigDecimal age) { this.age = age; } public String getPostId() { return postId; } public void setPostId(String postId) { this.postId = postId; } public String getStudyType() { return studyType; } public void setStudyType(String studyType) { this.studyType = studyType; } public Date getCtrctExprDate() { return ctrctExprDate; } public void setCtrctExprDate(Date ctrctExprDate) { this.ctrctExprDate = ctrctExprDate; } public Date getQaDate() { return qaDate; } public void setQaDate(Date qaDate) { this.qaDate = qaDate; } public String getCnName() { return cnName; } public void setCnName(String cnName) { this.cnName = cnName; } public String getQaJobType() { return qaJobType; } public void setQaJobType(String qaJobType) { this.qaJobType = qaJobType; } public String getEkpMain() { return ekpMain; } public void setEkpMain(String ekpMain) { this.ekpMain = ekpMain; } public String getArmsSpcl() { return armsSpcl; } public void setArmsSpcl(String armsSpcl) { this.armsSpcl = armsSpcl; } public String getCtrctType() { return ctrctType; } public void setCtrctType(String ctrctType) { this.ctrctType = ctrctType; } public String getDutyName() { return dutyName; } public void setDutyName(String dutyName) { this.dutyName = dutyName; } public String getRecruitPost() { return recruitPost; } public void setRecruitPost(String recruitPost) { this.recruitPost = recruitPost; } public String getEnrollFrom() { return enrollFrom; } public void setEnrollFrom(String enrollFrom) { this.enrollFrom = enrollFrom; } public String getHouseBoookType() { return houseBoookType; } public void setHouseBoookType(String houseBoookType) { this.houseBoookType = houseBoookType; } public String getPrftnlSerial() { return prftnlSerial; } public void setPrftnlSerial(String prftnlSerial) { this.prftnlSerial = prftnlSerial; } public Date getPrftnlDate() { return prftnlDate; } public void setPrftnlDate(Date prftnlDate) { this.prftnlDate = prftnlDate; } public Date getGraduateDate() { return graduateDate; } public void setGraduateDate(Date graduateDate) { this.graduateDate = graduateDate; } }
package dataAccess.abstracts; import java.util.List; import entities.concretes.Course; public interface CourseDao extends EntityRepository<Course>{ List<Course> getByCourseName(String courseName); List<Course> getByTeacherName(String teacherName); }
package dataobject; public class Product { private int id; private String pCode; private String pName; private Category category; private Brand brand; private UnitOfMeasure unitofmeasure; private double pPrice; private String description; public Product(){ id = 0; pCode = null; pName = null; category = null; brand = null; unitofmeasure = null; pPrice = 0; description = null; } public Product(int id, String pCode, String pName, Category category, Brand brand, UnitOfMeasure unitofmeasure, double pPrice, String description) { super(); this.id = id; this.pCode = pCode; this.pName = pName; this.category = category; this.brand = brand; this.unitofmeasure = unitofmeasure; this.pPrice = pPrice; this.description = description; } @Override public String toString() { return "Product [id=" + id + ", pCode=" + pCode + ", pName=" + pName + ", category=" + category + ", brand=" + brand + ", unitofmeasure=" + unitofmeasure + ", pPrice=" + pPrice + ", description=" + description + "]"; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getpCode() { return pCode; } public void setpCode(String pCode) { this.pCode = pCode; } public String getpName() { return pName; } public void setpName(String pName) { this.pName = pName; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } public Brand getBrand() { return brand; } public void setBrand(Brand brand) { this.brand = brand; } public UnitOfMeasure getUnitofmeasure() { return unitofmeasure; } public void setUnitofmeasure(UnitOfMeasure unitofmeasure) { this.unitofmeasure = unitofmeasure; } public double getpPrice() { return pPrice; } public void setpPrice(double pPrice) { this.pPrice = pPrice; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
package com.beadhouse.in; public class NotifyParam extends BasicIn { private String token; private int notifyType; public String getToken() { return token; } public void setToken(String token) { this.token = token; } public int getNotifyType() { return notifyType; } public void setNotifyType(int notifyType) { this.notifyType = notifyType; } }
package domain; import java.io.Serializable; /** * Created by rodrique on 4/19/2018. */ public class MainCourse extends Menu{ String mainID; String foodItem; public MainCourse() { } public MainCourse(String mainID, String foodItem) { this.mainID = mainID; this.foodItem = foodItem; } public String getMainID() { return mainID; } public void setMainID(String mainID) { this.mainID = mainID; } public String getFoodItem() { return foodItem; } public void setFoodItem(String foodItem) { this.foodItem = foodItem; } @Override public String toString() { return "MainCourse{" + "foodItem='" + foodItem + '\'' + ", mainID='" + mainID + '\'' + '}'; } }
package com.lenovohit.ssm.payment.support.bankPay.model.builder; import com.lenovohit.core.utils.StringUtils; /** * Created by zyus */ /** * @author lenovo * */ public class BankDownloadRequestBuilder extends BankRequestBuilder { private String checkDate; //对账日期 字符(8)YYYYMMDD 必输 private String syncType; //同步对账文件方式 private String filePath; //对账文件路径 @Override public boolean validate() { if (StringUtils.isEmpty(checkDate)) { throw new NullPointerException("checkDate should not be NULL!"); } return true; } @Override public String toString() { StringBuilder sb = new StringBuilder(""); sb.append(super.toString()); sb.append(String.format("%8s",checkDate)); return sb.toString(); } @Override public byte[] getContentBytes(String charset) { byte[] bs = new byte[26]; System.arraycopy(super.getContentBytes(charset), 0, bs, 0, 18); System.arraycopy(getFillerBytes(charset, 8, (byte)32, "right", checkDate), 0, bs, 18, 8); return bs; } @Override public BankDownloadRequestBuilder setLength(String length) { super.setLength(length); return this; } @Override public BankDownloadRequestBuilder setCode(String code) { super.setCode(code); return this; } @Override public BankDownloadRequestBuilder setHisCode(String hisCode) { super.setHisCode(hisCode); return this; } @Override public BankDownloadRequestBuilder setBankCode(String bankCode) { super.setBankCode(bankCode); return this; } public String getCheckDate() { return checkDate; } public BankDownloadRequestBuilder setCheckDate(String checkDate) { this.checkDate = checkDate; return this; } public String getSyncType() { return syncType; } public BankDownloadRequestBuilder setSyncType(String syncType) { this.syncType = syncType; return this; } public String getFilePath() { return filePath; } public BankDownloadRequestBuilder setFilePath(String filePath) { this.filePath = filePath; return this; } }
/* $Id$ */ package djudge.judge.interfaces; import djudge.judge.JudgeTaskResult; public interface Submitter { void submitResult(JudgeTaskResult result); }
package ch.ethz.geco.t4j.internal.json; /** * Represents a json stream object. */ public class StreamObject { public Long id; public String name; public String url; public String language; }
package controller; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.stage.Stage; import model.Appointment; import util.CustomException; import util.TimeConverter; import java.io.IOException; import java.net.URL; import java.sql.*; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; public class AddAppointment implements Initializable { @FXML Button cancelButton; @FXML Button addButton; @FXML TextField startBox; @FXML TextField endBox; @FXML TextField typeBox; List<Appointment> compareList = new ArrayList<>(); List<Appointment> appointmentList = new ArrayList<>(); private final ObservableList<Appointment> appointmentObservableList = FXCollections.observableList(appointmentList); public TableView<Appointment> customerTable; public TableColumn nameColumn; /** * Returns to the appointment menu * @throws IOException */ public void cancelButtonClicked() throws IOException { Stage stage; Parent root; FXMLLoader loader = new FXMLLoader(getClass().getResource("../view/appointment.fxml")); stage = (Stage) cancelButton.getScene().getWindow(); root = loader.load(); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } /** * Attempts to add a new appointment to the Database. Will throw exceptions if time overlaps or if * time is an invalid format * @throws Exception * @throws CustomException */ public void onClickAddAppointment() throws Exception, CustomException { TimeConverter time = new TimeConverter(); try { for (int i = 0; i < compareList.size(); i++) time.isOverlap(startBox.getText(), endBox.getText(), compareList.get(i).getStartTime(), compareList.get(i).getEndTime()); Statement statement; Appointment selectedAppointment = new Appointment(); selectedAppointment = customerTable.getSelectionModel().getSelectedItem(); time.isValidDate(startBox.getText()); time.isValidDate(endBox.getText()); time.isBusinessHours(startBox.getText()); time.isBusinessHours(endBox.getText()); Connection connection = DriverManager.getConnection("jdbc:mysql://3.227.166.251/U0600d", "U0600d", "53688664081"); statement = connection.createStatement(); statement.execute("INSERT INTO appointment(customerId, userId, type, start, end, createDate, createdBy, lastUpdate, lastUpdateBy, title, description, location, contact, url)\n" + "VALUES(" + selectedAppointment.getCustomerId() + ", " + AppointmentController.userData.getUserId() + ", '" + typeBox.getText() + "', '" + startBox.getText() + "', '" + endBox.getText() + "', '" + time.getUtcTime() + "', '" + AppointmentController.userData + "', '" + time.getUtcTime() + "', '" + AppointmentController.userData + "', '" + "blank" + "', '" + "blank" + "', '" + "blank" + "', '" + "blank" + "', '" + "blank" + "');"); cancelButtonClicked(); } catch (ParseException | CustomException e) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Overlapping Time"); alert.setHeaderText("Start Time Overlaps With Existing appointment"); alert.setContentText("Please enter a valid time and try again"); alert.showAndWait(); } } /** * populates customer table to be used when creating appointment * @param location * @param resources */ @Override public void initialize(URL location, ResourceBundle resources) { Statement statement; ResultSet result; Connection connection = null; try { connection = DriverManager.getConnection("jdbc:mysql://3.227.166.251/U0600d", "U0600d", "53688664081"); statement = connection.createStatement(); result = statement.executeQuery("SELECT * " + "FROM customer"); while (result.next()) { Appointment appointment = new Appointment(); appointment.setName(result.getString("customerName")); appointment.setCustomerId(result.getInt("customerId")); appointmentList.add(appointment); } connection.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } nameColumn.setCellValueFactory(new PropertyValueFactory<>("name")); customerTable.setItems(appointmentObservableList); } /** * used to set the comparison list for overlapping times * @param appointments */ public void setCompareList(List<Appointment> appointments) { compareList.addAll(appointments); } }
package com.example.converter; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class ModelConverter { @Autowired private ModelMapper mapper; public <T, K> T toDTO(K entity, Class<T> dtoClass) { T dto = mapper.map(entity, dtoClass); return dto; } public <T, K> T toEntity(K dto, Class<T> entityClass) { T entity = mapper.map(dto, entityClass); mapper.map(dto, dto); return entity; } public <T, K> T toEntity(K dto, T entity) { mapper.map(dto, entity); return entity; } }
package com.cts.model; import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.Table; @Entity //@DiscriminatorValue("mang") //@Table(name="mgrs") @Table(name="mgrs_Only") public class Manager extends Emp { @Column(name="allowence") private double allowence; public Manager(long eid, String ename, double basic, double allowence) { super(eid, ename, basic); this.allowence = allowence; } public Manager() { } public double getAllowence() { return allowence; } public void setAllowence(double allowence) { this.allowence = allowence; } @Override public String toString() { return "Manager [allowence=" + allowence + ", getAllowence()=" + getAllowence() + ", getEid()=" + getEid() + ", getEname()=" + getEname() + ", getBasic()=" + getBasic() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]"; } }
package com.codecool.shop.controller; import com.codecool.shop.Utils; import com.codecool.shop.dao.ProductCategoryDao; import com.codecool.shop.dao.implementation.Db.ProductCategoryDaoJdbc; import com.codecool.shop.dao.implementation.Db.SupplierDaoJdbc; import com.codecool.shop.dao.implementation.Mem.ProductCategoryDaoMem; import com.codecool.shop.dao.implementation.Mem.ProductDaoMem; import com.codecool.shop.model.*; import spark.Request; import spark.Response; import java.util.*; public class ProductController { public static String renderProducts(Request req, Response res) { UserController.ensureUserIsLoggedIn(req, res); ProductCategoryDao productCategoryDataStore = ProductCategoryDaoMem.getInstance(); SupplierDaoJdbc supplierDataStore = SupplierDaoJdbc.getInstance(); int supplierId = 1; Supplier targetSupplier = supplierDataStore.find(supplierId); List products = targetSupplier.getProducts(); List<Map> productsResponse = ModelBuilder.productModel(products); Map<String, Object> data = new HashMap<>(); data.put("username", req.session().attribute("username")); data.put("categories", productCategoryDataStore.getAll()); data.put("suppliers", supplierDataStore.getAll()); data.put("collectionName", targetSupplier.getName()); data.put("collection", productsResponse); return Utils.renderTemplate(data, "product/index"); } public static String getProductsBySupplier(Request request, Response response) { int supplierId = Integer.parseInt(request.params("id")); SupplierDaoJdbc supplierDataStore = SupplierDaoJdbc.getInstance(); Supplier targetSupplier = supplierDataStore.find(supplierId); List<Product> products = targetSupplier.getProducts(); List<Map> collection = ModelBuilder.productModel(products); Map<String, Object> data = new HashMap<>(); data.put("collection", collection); data.put("collectionName", targetSupplier.getName()); return Utils.toJson(data); } public static String getProductsByCategory(Request request, Response response) { int categoryId = Integer.parseInt(request.params("id")); ProductCategoryDao productCategoryDataStore = ProductCategoryDaoJdbc.getInstance(); ProductCategory targetCategory = productCategoryDataStore.find(categoryId); List<Product> products = targetCategory.getProducts(); List<Map> collection = ModelBuilder.productModel(products); Map<String, Object> data = new HashMap<>(); data.put("collection", collection); data.put("collectionName", targetCategory.getName()); return Utils.toJson(data); } public static String handleOrder(Request req, Response res) { int productId = Integer.parseInt(req.params("id")); Product targetItem = ProductDaoMem.getInstance().find(productId); if (!isLineItem(targetItem)) { LineItem newLineItem = new LineItem(targetItem, targetItem.getDefaultPrice()); Order.getCurrentOrder().add(newLineItem); } Map<String, Object> response = getShoppingCartData(); return Utils.toJson(response); } public static String addUserData(Request request, Response response) { Map<String, String> userData = Utils.parseJson(request); Order.getCurrentOrder().setUserData(userData); String res = "order updated with user data"; return Utils.toJson(res); } public static String addPaymentData(Request request, Response response) { Map<String, String> userData = Utils.parseJson(request); Order.getCurrentOrder().setPaymentData(userData); String res = "order updated with payment data"; new Order(); return Utils.toJson(res); } private static boolean isLineItem(Product targetItem) { for (LineItem lineItem : Order.getCurrentOrder().getAddedItems()) { if (lineItem.getItem().equals(targetItem)) { lineItem.incrementQuantity(); return true; } } return false; } public static String changeQuantity(Request req, Response res) { Map<String, String> data = Utils.parseJson(req); List<LineItem> lineItems = Order.getCurrentOrder().getAddedItems(); LineItem targetLineItem = null; for (LineItem lineItem : lineItems) { if (lineItem.getItem().getId() == Integer.parseInt(data.get("Id"))) { targetLineItem = lineItem; break; } } if (Objects.equals(data.get("change"), "plus")) { if (targetLineItem != null) { targetLineItem.incrementQuantity(); } Order.getCurrentOrder().changeTotalPrice(); } else { if (targetLineItem != null && targetLineItem.getQuantity() > 0) { targetLineItem.decrementQuantity(); if (targetLineItem.getQuantity() == 0) { Order.getCurrentOrder().getAddedItems().remove(targetLineItem); } } Order.getCurrentOrder().changeTotalPrice(); } Map<String, Object> response = getShoppingCartData(); return Utils.toJson(response); } private static Map<String, Object> getShoppingCartData() { List<LineItem> orderItems = Order.getCurrentOrder().getAddedItems(); List<Map> orders = ModelBuilder.lineItemModel(orderItems); Map<String, Object> response = new HashMap<>(); response.put("itemsNumber", Integer.toString(Order.getCurrentOrder().getTotalSize())); response.put("totalPrice", Float.toString(Order.getCurrentOrder().getTotalPrice())); response.put("shoppingCart", orders); return response; } }
package com.santosh; public class Main { public static void main(String[] args) { int count = 1; while (count != 6) { System.out.println("count = " + count); count++; } System.out.println("resetting the count..."); count = 1; while (true) { if(count == 6) { break; } System.out.println("Count = " + count); count++; } System.out.println("resetting the count..."); count = 1; do { System.out.println("count was: " + count); count++; if (count > 100) { break; } } while(count != 200); int number = 5; int finish = 10; int countEven = 0; while ( number <= finish) { number++; if(!isEven(number)) { continue; } countEven++; System.out.println("even number: " + number); if ( countEven == 5) { break; } } System.out.println("Total even numbers: " + countEven); } public static boolean isEven(int number) { if (number % 2 == 0) { return true; } else { return false; } } }
/* * SingleMessageCodec.java * ********************************************************************** Copyright (c) 2013 - 2014 netty-apns ***********************************************************************/ package apns.netty.codec; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.CompositeByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageCodec; import io.netty.util.CharsetUtil; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import apns.netty.connpool.ConnectionPoolManagerFactory; import apns.netty.exceptions.InvalidDeviceTokenFormatException; import apns.netty.exceptions.MoreDataThanExpectedException; import apns.netty.model.impl.ApnsMessage; import apns.netty.model.impl.ApnsResponse; import apns.netty.model.impl.ItemType; import apns.netty.queues.single.SingleMessageQueue; /** * The Class SingleMessageCodec. * @author arung */ @Component @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class SingleMessageCodec extends ByteToMessageCodec<ApnsMessage> { /** The Constant logger. */ private static final Logger logger = Logger .getLogger(SingleMessageCodec.class); /** The Constant ALL_MESSAGES_WRITTEN_TO_CHANNEL_BY_ENCODER. */ private static final String ALL_MESSAGES_WRITTEN_TO_CHANNEL_BY_ENCODER = "All messages written to channel by encoder:"; /** The Constant CONSTRUCTED_FINAL_BUFFER. */ private static final String CONSTRUCTED_FINAL_BUFFER = "Constructed final buffer:"; /** The Constant COLON. */ private static final String COLON = ":"; /** The Constant FRAME_DATA_LENGTH. */ private static final String FRAME_DATA_LENGTH = "frameDataLength="; /** The Constant PRIO_LENGTH. */ private static final String PRIO_LENGTH = "PRIO length:"; /** The Constant EXP_DATE_LENGTH. */ private static final String EXP_DATE_LENGTH = "EXP_DATE length:"; /** The Constant NOT_ID_LENGTH. */ private static final String NOT_ID_LENGTH = "NOT_ID length:"; /** The Constant PAYLOAD_LENGTH. */ private static final String PAYLOAD_LENGTH = "PAYLOAD length:"; /** The Constant DEV_TOKEN_LENGTH. */ private static final String DEV_TOKEN_LENGTH = "DEV_TOKEN length:"; /** The Constant ITEMTYPE_IS. */ private static final String ITEMTYPE_IS = "Itemtype is :"; /** The Constant logger. */ /** The Constant IDENTIFIER2. */ private static final String IDENTIFIER2 = "identifier - "; /** The Constant STATUS2. */ private static final String STATUS2 = " status-"; /** The Constant COMMAND2. */ private static final String COMMAND2 = "Command-"; /** The Constant SINGLE_DECODE_PROTOCOL_SIZE. */ private static final int SINGLE_DECODE_PROTOCOL_SIZE = 6; /** The single message queue. */ @Autowired private SingleMessageQueue singleMessageQueue; /** The connection pool manager factory. */ @Autowired private ConnectionPoolManagerFactory connectionPoolManagerFactory; /** The Constant COMMAND_BYTE. */ private static final byte COMMAND_BYTE = 2; /** The apns message. */ private ApnsMessage apnsMessage; /* * (non-Javadoc) * @see io.netty.handler.codec.MessageToByteEncoder#encode(io.netty.channel. * ChannelHandlerContext, java.lang.Object, io.netty.buffer.ByteBuf) */ /** * Encode. * @param ctx * the ctx * @param msg * the msg * @param out * the out * @throws Exception * the exception */ @Override protected void encode(final ChannelHandlerContext ctx, final ApnsMessage msg, final ByteBuf out) throws Exception { setApnsMessage(msg); validate(msg); int frameDataLength = 0; final ByteBufAllocator allocator2 = ctx.alloc(); final CompositeByteBuf buf = allocator2.compositeDirectBuffer(); buf.writeByte(SingleMessageCodec.COMMAND_BYTE);// #1 final ByteBuf items = allocator2.directBuffer(); for (final ItemType itType : ItemType.values()) { SingleMessageCodec.logger.trace(SingleMessageCodec.ITEMTYPE_IS + itType); final int itemSize = itType.getSize(); final byte itemId = itType.getId(); final Object obj = msg.getObject(itType); items.writeByte(itemId); frameDataLength += 3; switch (itType) { // DEV_TOKEN(1,32), PAYLOAD(2,256), NOT_ID(3,4), EXP_DATE(4,4), // PRIO(5,1); case DEV_TOKEN: final String deviceToken = (String) obj; final byte[] deviceTokenAsBytes = getDevTokenAsBytes(deviceToken); if (deviceTokenAsBytes.length != itemSize) { throw new MoreDataThanExpectedException(); } items.writeShort((short) itemSize); // items.writeBytes(SingleConnectionEncoder // .intTo2ByteArray(itemSize)); items.writeBytes(deviceTokenAsBytes); SingleMessageCodec.logger .trace(SingleMessageCodec.DEV_TOKEN_LENGTH + deviceTokenAsBytes.length); frameDataLength += itemSize; break; case PAYLOAD: final byte[] payLoad = ((String) obj) .getBytes(CharsetUtil.UTF_8); if (payLoad.length > itemSize) { throw new MoreDataThanExpectedException(); } items.writeShort((short) payLoad.length); items.writeBytes(payLoad); SingleMessageCodec.logger .trace(SingleMessageCodec.PAYLOAD_LENGTH + payLoad.length); frameDataLength += payLoad.length; break; case NOT_ID: items.writeShort((short) itemSize); items.writeInt((Integer) obj); SingleMessageCodec.logger .trace(SingleMessageCodec.NOT_ID_LENGTH + itemSize); frameDataLength += itemSize; break; case EXP_DATE: items.writeShort((short) itemSize); items.writeInt((Integer) obj); SingleMessageCodec.logger .trace(SingleMessageCodec.EXP_DATE_LENGTH + itemSize); frameDataLength += itemSize; break; case PRIO: items.writeShort((short) itemSize); items.writeByte((byte) obj); SingleMessageCodec.logger .trace(SingleMessageCodec.PRIO_LENGTH + itemSize); frameDataLength += itemSize; break; } } SingleMessageCodec.logger.trace(SingleMessageCodec.FRAME_DATA_LENGTH + frameDataLength + SingleMessageCodec.COLON); buf.writeInt(frameDataLength); buf.writeBytes(items); SingleMessageCodec.logger .trace(SingleMessageCodec.CONSTRUCTED_FINAL_BUFFER + buf.order() + SingleMessageCodec.COLON + items.order() + SingleMessageCodec.COLON + out.order()); out.writeBytes(buf); SingleMessageCodec.logger .trace(SingleMessageCodec.ALL_MESSAGES_WRITTEN_TO_CHANNEL_BY_ENCODER); items.release(); buf.release(); } /* * (non-Javadoc) * @see io.netty.handler.codec.ByteToMessageDecoder#decode(io.netty.channel. * ChannelHandlerContext, io.netty.buffer.ByteBuf, java.util.List) */ /** * Decode. * @param ctx * the ctx * @param in * the in * @param out * the out * @throws Exception * the exception */ @Override protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws Exception { if (in.readableBytes() < SingleMessageCodec.SINGLE_DECODE_PROTOCOL_SIZE) { return; } final byte command = in.readByte(); final byte status = in.readByte(); final int identifier = in.readInt(); final ApnsResponse response = new ApnsResponse(); response.setCommand(command); response.setId(identifier); response.setStatus(status); out.add(response); SingleMessageCodec.logger.trace(SingleMessageCodec.COMMAND2 + command + SingleMessageCodec.STATUS2 + status + SingleMessageCodec.IDENTIFIER2 + identifier); ctx.close(); connectionPoolManagerFactory.getSingleConnection().bootstrap(); } /** * Gets the dev token as bytes. * @param deviceToken * the device token * @return the dev token as bytes * @throws InvalidDeviceTokenFormatException * the invalid device token format exception */ private byte[] getDevTokenAsBytes(String deviceToken) throws apns.netty.exceptions.InvalidDeviceTokenFormatException { final byte[] deviceTokenAsBytes = new byte[deviceToken.length() / 2]; deviceToken = deviceToken.toUpperCase(); int j = 0; try { for (int i = 0; i < deviceToken.length(); i += 2) { final String t = deviceToken.substring(i, i + 2); final int tmp = Integer.parseInt(t, 16); deviceTokenAsBytes[j++] = (byte) tmp; } } catch (final NumberFormatException e1) { throw new apns.netty.exceptions.InvalidDeviceTokenFormatException( deviceToken, e1.getMessage()); } return deviceTokenAsBytes; } /** * Validate. * @param msg * the msg */ private void validate(final ApnsMessage msg) { } /** * Gets the apns message. * @return the apns message */ public ApnsMessage getApnsMessage() { return apnsMessage; } /** * Sets the apns message. * @param apnsMessage * the new apns message */ public void setApnsMessage(final ApnsMessage apnsMessage) { this.apnsMessage = apnsMessage; } }
package com.needii.dashboard.model; import java.io.Serializable; import javax.persistence.*; import java.util.Date; /** * The persistent class for the currency database table. * */ @Entity @NamedQuery(name="Currency.findAll", query="SELECT c FROM Currency c") public class Currency implements Serializable { private static final long serialVersionUID = 1L; @Id private int id; @Temporal(TemporalType.TIMESTAMP) @Column(name="created_at") private Date createdAt; private String name; private float rate; private String unit; @Column(name="unit_symbol") private String unitSymbol; //bi-directional many-to-one association to Language @ManyToOne private Language language; public Currency() { } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public Date getCreatedAt() { return this.createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public float getRate() { return this.rate; } public void setRate(float rate) { this.rate = rate; } public String getUnit() { return this.unit; } public void setUnit(String unit) { this.unit = unit; } public String getUnitSymbol() { return this.unitSymbol; } public void setUnitSymbol(String unitSymbol) { this.unitSymbol = unitSymbol; } public Language getLanguage() { return this.language; } public void setLanguage(Language language) { this.language = language; } }
package com.github.andlyticsproject.admob; public class AdmobAccountRemovedException extends Exception { private static final long serialVersionUID = 1L; private String accountName; public AdmobAccountRemovedException(String string, String accountName) { super(string); this.setAccountName(accountName); } public void setAccountName(String accountName) { this.accountName = accountName; } public String getAccountName() { return accountName; } }
package com.nisira.view.Activity; import android.animation.ObjectAnimator; import android.graphics.Color; import android.os.Bundle; import android.support.design.widget.TextInputEditText; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.transition.Slide; import android.transition.TransitionInflater; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import com.getbase.floatingactionbutton.FloatingActionButton; import com.getbase.floatingactionbutton.FloatingActionsMenu; import com.github.aakira.expandablelayout.ExpandableLayout; import com.github.aakira.expandablelayout.ExpandableLayoutListenerAdapter; import com.github.aakira.expandablelayout.ExpandableLinearLayout; import com.github.aakira.expandablelayout.Utils; import com.nisira.core.dao.DordenservicioclienteDao; import com.nisira.core.entity.Dordenserviciocliente; import com.nisira.core.entity.Ordenserviciocliente; import com.nisira.core.interfaces.FragmentNisira; import com.nisira.gcalderon.policesecurity.R; import com.nisira.view.Adapter.Adapter_edt_DOrdenServicio; import com.nisira.view.Adapter.Adapter_edt_DOrdenServicio_vehiculo; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; public class edt_OrdenServicio2_Fragment extends FragmentNisira { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String OPCION = "param1"; private static final String ANTERIOR = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private TextInputEditText txt_documento; private TextInputEditText txt_cliente; private TextInputEditText txt_nromanual; private TextInputEditText txt_nrocont; private TextInputEditText txt_nroprecinto; private TextInputEditText txt_nroservicio; private TextView txt_fecha; private TextView txt_estado; private FloatingActionsMenu multiple_fab; private FloatingActionButton fab_modificar; List<Dordenserviciocliente> lstordenserviciocliente = new ArrayList<>(); DordenservicioclienteDao DordenservicioclienteDao; private RecyclerView recyclerView; private RecyclerView.Adapter adapter; private RecyclerView.LayoutManager lManager; private Ordenserviciocliente ordenserviciocliente; public ExpandableLinearLayout expandableLayout; private RelativeLayout button; public edt_OrdenServicio2_Fragment() { // Required empty public constructor } // TODO: Rename and change types and number of parameters public static edt_OrdenServicio2_Fragment newInstance(String param1, String param2) { edt_OrdenServicio2_Fragment fragment = new edt_OrdenServicio2_Fragment(); Bundle args = new Bundle(); args.putString(OPCION, param1); args.putString(ANTERIOR, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(OPCION); mParam2 = getArguments().getString(ANTERIOR); ordenserviciocliente = (Ordenserviciocliente) getArguments().getSerializable("OrdenServicio"); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_edt__dorden_servicio2, container, false); animacionEntrada(); txt_documento = (TextInputEditText)view.findViewById(R.id.txt_documento); txt_cliente = (TextInputEditText)view.findViewById(R.id.txt_ordenservicio); txt_nrocont = (TextInputEditText)view.findViewById(R.id.txt_nrocont); txt_nromanual = (TextInputEditText)view.findViewById(R.id.txt_nromanual); txt_nroprecinto = (TextInputEditText)view.findViewById(R.id.txt_nroprecinto); txt_nroservicio = (TextInputEditText)view.findViewById(R.id.txt_nroservicio); txt_fecha = (TextView)view.findViewById(R.id.txt_fecha); txt_estado = (TextView)view.findViewById(R.id.txt_estado); multiple_fab = (FloatingActionsMenu) view.findViewById(R.id.multiple_fab); fab_modificar = (FloatingActionButton)view.findViewById(R.id.fab_modificar); button = (RelativeLayout)view.findViewById(R.id.button); expandableLayout = (ExpandableLinearLayout)view.findViewById(R.id.expandableLayout); //expandableLayout = (ExpandableLayout)view.findViewById(R.id.expandableLayout); //View hView = expandableLayout.getContentLayout(); recyclerView = (RecyclerView)view.findViewById(R.id.recycler_os); LlenarCampos(); Listeners(); return view; } public void animacionEntrada(){ Slide slide = null; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { slide = (Slide) TransitionInflater.from(getContext()).inflateTransition(R.transition.activity_slide); setExitTransition(slide); setEnterTransition(slide); } } public void LlenarCampos(){ TextView view = (TextView) getActivity().findViewById(R.id.campo_titulo2); view.setText(getString(R.string.edt_OrdenServicio)); txt_nrocont.setText(ordenserviciocliente.getNrocontenedor()); txt_nromanual.setText(ordenserviciocliente.getNromanual()); txt_nroprecinto.setText(ordenserviciocliente.getNroprecinto()); txt_nroservicio.setText(ordenserviciocliente.getNro_oservicio()); txt_documento.setText(ordenserviciocliente.getIddocumento()+"-"+ ordenserviciocliente.getSerie()+ "-"+ ordenserviciocliente.getNumero()); txt_documento.setHint("Documento: "); txt_cliente.setText(ordenserviciocliente.getCliente()); txt_cliente.setHint("Cliente:"); SimpleDateFormat sm = new SimpleDateFormat("MM-dd-yyyy"); String strDate = sm.format(ordenserviciocliente.getFecha()); txt_fecha.setText(strDate); String estado = ordenserviciocliente.getIdestado(); if(estado.equals("PE")){ txt_estado.setText("Pendiente"); } recyclerView.setHasFixedSize(true); lManager = new LinearLayoutManager(getContext()); recyclerView.setLayoutManager(lManager); DordenservicioclienteDao = new DordenservicioclienteDao(); try { lstordenserviciocliente = DordenservicioclienteDao.ListarxOrdenServicio(ordenserviciocliente); switch (mParam1){ case "Asignacion Personal": case "Registro Hora": adapter = new Adapter_edt_DOrdenServicio(mParam1,lstordenserviciocliente,getFragmentManager(),ordenserviciocliente); recyclerView.setAdapter(adapter); multiple_fab.setVisibility(View.GONE); break; case "Registro Vehiculo": adapter = new Adapter_edt_DOrdenServicio_vehiculo(mParam1,lstordenserviciocliente,getFragmentManager(),ordenserviciocliente); recyclerView.setAdapter(adapter); multiple_fab.setVisibility(View.VISIBLE); break; } } catch (Exception e) { e.printStackTrace(); } expandableLayout.setInRecyclerView(true); expandableLayout.setListener(new ExpandableLayoutListenerAdapter() { @Override public void onPreOpen() { createRotateAnimator(button, 0f, 180f).start(); } @Override public void onPreClose() { createRotateAnimator(button, 180f, 0f).start(); } }); button.setRotation(0f); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { onClickButton(expandableLayout); } }); } private void onClickButton(final ExpandableLayout expandableLayout) { expandableLayout.toggle(); } public ObjectAnimator createRotateAnimator(final View target, final float from, final float to) { ObjectAnimator animator = ObjectAnimator.ofFloat(target, "rotation", from, to); animator.setDuration(200); animator.setInterpolator(Utils.createInterpolator(Utils.LINEAR_INTERPOLATOR)); return animator; } public void Listeners(){ fab_modificar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for (int i = 0; i < lstordenserviciocliente.size(); i++) { if (lstordenserviciocliente.get(i).isSeleccion()) { Fragment fragment = mnt_DOrdenServicio_Fragment.newInstance(OPCION, "Modificar"); Bundle bundle = fragment.getArguments(); bundle.putSerializable("OrdenServicio", ordenserviciocliente); bundle.putSerializable("DOrdenServicio",lstordenserviciocliente.get(i)); fragment.setArguments(bundle); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.main_content, fragment, "NewFragmentTag"); ft.addToBackStack(null); ft.commit(); } } } }); } }
//TetrisT.java public class TetrisT extends TetrisPiece { public TetrisT() { filledSquares[0][0][1] = true; filledSquares[0][0][2] = true; filledSquares[0][0][3] = true; filledSquares[0][1][2] = true; filledSquares[1][0][3] = true; filledSquares[1][1][2] = true; filledSquares[1][1][3] = true; filledSquares[1][2][3] = true; filledSquares[2][2][1] = true; filledSquares[2][1][2] = true; filledSquares[2][2][2] = true; filledSquares[2][2][3] = true; filledSquares[3][0][1] = true; filledSquares[3][1][1] = true; filledSquares[3][1][2] = true; filledSquares[3][2][1] = true; } //public void test4(int i){ // for( int j = 0; j< filledSquares[i].length; j++) // { //for(int k = 0; k< filledSquares[i][j].length; k++) // { //System.out.print(filledSquares[i][j][k]); //System.out.print( " " ); //if( k == 3) // { //System.out.print("\n"); // } //} // } //} }
/* * Copyright 2018 Neil Lee <cnneillee@163.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.neillee.bilisocialize.utils; /** * @author NeilLee * @since 2018/3/19 17:16 */ public class StringUtils { public static String stringToJSON(String strJson) { // 计数tab的个数 int tabNum = 0; StringBuilder jsonFormat = new StringBuilder(); int length = strJson.length(); char last = 0; for (int i = 0; i < length; i++) { char c = strJson.charAt(i); if (c == '{') { tabNum++; jsonFormat.append(c).append("\n"); jsonFormat.append(getSpaceOrTab(tabNum)); } else if (c == '}') { tabNum--; jsonFormat.append("\n"); jsonFormat.append(getSpaceOrTab(tabNum)); jsonFormat.append(c); } else if (c == ',') { jsonFormat.append(c).append("\n"); jsonFormat.append(getSpaceOrTab(tabNum)); } else if (c == ':') { jsonFormat.append(c).append(" "); } else if (c == '[') { tabNum++; char next = strJson.charAt(i + 1); if (next == ']') { jsonFormat.append(c); } else { jsonFormat.append(c).append("\n"); jsonFormat.append(getSpaceOrTab(tabNum)); } } else if (c == ']') { tabNum--; if (last == '[') { jsonFormat.append(c); } else { jsonFormat.append("\n").append(getSpaceOrTab(tabNum)).append(c); } } else { jsonFormat.append(c); } last = c; } return jsonFormat.toString(); } // 是空格还是tab private static String getSpaceOrTab(int tabNum) { StringBuffer sbTab = new StringBuffer(); for (int i = 0; i < tabNum; i++) { sbTab.append('\t'); } return sbTab.toString(); } }
package com.microsoft.bingads.v11.api.test.entities.ad_extension.review; import com.microsoft.bingads.v11.api.test.entities.PerformanceDataTestHelper; import com.microsoft.bingads.v11.bulk.entities.BulkAdGroupReviewAdExtension; import org.junit.Test; public class BulkAdGroupReviewAdExtensionReadWriteTest { @Test public void bulkAdGroupReviewAdExtension_ReadPerfData_WriteToFile() { PerformanceDataTestHelper.testPerformanceDataReadWrite(new BulkAdGroupReviewAdExtension()); } }
CoffeeMachineInterface.java public interface CoffeeMachineInterface { void chooseFirstSelection(); void chooseSecondSelection(); } ~~~~~~~~~~~~~~~~ Submit OldCoffeeMachine.java here public class CoffeeTouchscreenAdapter implements CoffeeMachineInterface { OldCofffeeMachine theMachine; public void selectA() { System.out.println(“A - Selected”); } Public void selectB() { System.out.println(“B - Selected”); } } ~~~~~~~~~~~~~~~~ Submit CoffeeTouchscreenAdapter.java here OldCofffeeMachine theMachine; public CoffeeTouchscreenAdapter(OldCoffeeMachine newMachine) { theMachine = newMachine; } public void chooseFirstSelection() { theMachine.selectA(); } public void chooseSecondSelection() { theMachine.selectB(); } } ~~~~~~~~~~~~~~~~ Assignment 2 Submit IComponent.java here public interface Icomponent{ void play(); void setPlaybackSpeed(float speed); String getName(); } ~~~~~~~~~~~~~~~~ Submit Playlist.java here public class Playlist Implements Icomponent { public String playlistName; public Arrarylist<IComponent> playlist = new ArrayList(); public Playlist(String playlistName) { this.playlistName = playlistName; } public void add(IComponent component) { playlist.add(component); } public void remove(IComponent component) { playlist.remove(component); } public void play() { for(IComponent component : playlist) { component.play(); } } public void setPlaybackSpeed(float speed) { for(IComponent component: this.playlist) { } } public String getName() { return this.playlistName; } } ~~~~~~~~~~~~~~~ Submit Song.java here public class Song implements IComponent{ public String songName public String artist; public float speed = 1; public Song(String songName, String artist) { this.songName=songName; this.artist = artist; } public void play() { } public void setPlayBackSpeed(float speed) { this.speed = speed; } }
package com.san.field; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; import java.util.ArrayList; import java.util.List; @Service public class FieldService { @Autowired private FieldRepository fieldRepository; public List<Field> getAll() { List<Field> records = new ArrayList<>(); fieldRepository.findAll().forEach(records::add); return records; } public Field getOne(Integer id) { return fieldRepository.findOne(id); } public void add(Field field) { fieldRepository.save(field); } public void update(Field field) { // if exists updates otherwise inserts fieldRepository.save(field); } public void delete(Integer id) { fieldRepository.delete(id); } }
import java.util.LinkedList; import java.util.List; import java.util.Stack; /* * @lc app=leetcode.cn id=32 lang=java * * [32] 最长有效括号 * 使用栈 * * 两种case需要入栈: * 匹配到( ; * 一、入栈条件为1.栈为空 2.当前字符是'(' 3.栈顶符号位')',因为三种条件都没办法消去成对的括号。 * 二、计算结果:符合消去成对括号时,拿当前下标减去栈顶下标即可 * * */ // @lc code=start class Solution { class Solution { public int longestValidParentheses(String s) { int result = 0; Stack<Integer> stack = new Stack<Integer>(); char[] charArray = s.toCharArray(); for (int i = 0; i < charArray.length; i++) { char c = charArray[i]; if(stack.isEmpty() || charArray[stack.peek()] == ')' || c=='('){ stack.push(i); }else{ stack.pop(); if(stack.isEmpty()){ result = Math.max(result, i + 1); }else{ result = Math.max(result, i - stack.peek()); } } } return result; } } } // @lc code=end
import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; public class xmlToZip { public static void main(String[] args) throws Exception { String string = "test" + "dsfdsfsf\r\n" + "dsfdsfdsf"; System.out.println("after compress:"); byte[] compressed = compress(string); System.out.println(compressed); System.out.println("after decompress:"); String decomp = decompress(compressed); System.out.println(decomp); } public static byte[] compress(String str) throws Exception { if (str == null || str.length() == 0) { return null; } System.out.println("String length : " + str.length()); ByteArrayOutputStream obj=new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(obj); gzip.write(str.getBytes(StandardCharsets.UTF_8)); gzip.close(); return obj.toByteArray(); } public static String decompress(byte[] str) throws Exception { if (str == null ) { return null; } GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(str)); BufferedReader bf = new BufferedReader(new InputStreamReader(gis, StandardCharsets.UTF_8)); StringBuilder outStr = new StringBuilder(); String line; while ((line=bf.readLine())!=null) { outStr.append(line); } System.out.println("Output String lenght : " + outStr.length()); return outStr.toString(); } }
package cc.ipotato.reflect; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class GetMethodTest { public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, ClassNotFoundException { Class<?> cls = Class.forName("cc.ipotato.reflect.Person"); // Method[] met = cls.getMethods(); // for(Method m: met){ // System.out.println(m); // } String attribute = "name"; String value = "haohao"; Object obj = cls.newInstance(); Method setMethod = cls.getMethod("setName", String.class); setMethod.invoke(obj, value); Method getMethod = cls.getMethod("getName"); Object result = getMethod.invoke(obj); System.out.println(result); } }
package Client; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.*; public class Client { private String clientName = "defaultName"; private Socket socket; private Client(String adress, int port) { try { socket = new Socket(InetAddress.getByName(adress), port); } catch (Exception e) { e.getStackTrace(); } } private void getMessage() { try { BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String fromserver; while (true) { fromserver = in.readLine(); if(fromserver == null) continue; if(fromserver.compareTo("@exit") == 0){ break; } System.out.println(fromserver); } } catch (IOException e) { e.getStackTrace(); } } private void sendMessage() { try { PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader inu = new BufferedReader(new InputStreamReader(System.in)); String fuser; while (true) { fuser = inu.readLine(); if (fuser.equals("exit")) { break; } out.println(fuser); } } catch (IOException e) { e.getStackTrace(); } } public void setName(String string) { clientName = string; } public String getName() { return clientName; } public static void main(String[] args) { Client client = new Client("localhost", 9000); System.out.println("Client.Client started"); new Thread(new Runnable() { @Override public void run() { client.sendMessage(); } }).start(); System.out.println(); System.out.println(); new Thread(new Runnable() { @Override public void run() { client.getMessage(); } }).start(); } }
package com.jobnotes.com.jobnotes.models; /** * Created by edwardbenzenberg on 5/17/17. */ import java.util.Date; /** * @author edwardbenzenberg * */ public class Notes { int id; String jobName; String note; String dateAdded; Date dateFinished; String status; public Notes(){ } public Notes(String note, int id, String status){ this.note = note; this.id = id; this.status = status; } public Notes(String note, int id,String jobName, String status){ this.note = note; this.id = id; this.jobName = jobName; this.status = status; } public Notes(int id,String jobName, String note, String dateAdded, String status) { this.id = id; this.jobName = jobName; this.note = note; this.dateAdded = dateAdded; this.dateFinished = dateFinished; this.status = status; } public int getId() { return id; } public void setId(int id) { this.id = id; } /** * getter method for jobName */ public String getJobName() { return jobName; } /** * setter method for jobName */ public void setJobName(String jobName) { this.jobName = jobName; } /** * getter method for note */ public String getNote() { return note; } /** * setter method for note */ public void setNote(String note) { this.note = note; } /** * getter method for dateAdded */ public String getDateAdded() { return dateAdded; } /** * setter method for dateAdded */ public void setDateAdded(String dateAdded) { this.dateAdded = dateAdded; } /** * getter method for dateFinished */ public Date getDateFinished() { return dateFinished; } /** * setter method for dateFinished */ public void setDateFinished(Date dateFinished) { this.dateFinished = dateFinished; } /** * getter method for finished */ public String getStatus() { return status; } /** * setter method for finished */ public void setstatus(String status) { this.status = status; } }
package cn.edu.zju.gd.r; /* * https://leetcode.com/problems/reverse-string/#/description * * 344 Reverse String * * example: Given s = "hello", return "olleh". * */ public class ReverseString { public static void main(String[] args) { String s = "hello"; System.out.println(reverseString(s)); } public static String reverseString(String s) { if(s == null) return null; char[] chars = s.toCharArray(); StringBuffer stemp = new StringBuffer(); for(int i = chars.length-1 ; i>=0; i--) { stemp.append(chars[i]); } return stemp.toString(); } }
package render; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import org.newdawn.slick.SpriteSheet; import org.newdawn.slick.geom.Shape; import actors.Effect; import actors.Status; /* Uses a spriteSheet and an actor's status to draw it. */ public class ActorRenderer extends Renderer{ private static int STAND = 0; private static int WALK1 = 1; private static int WALK2 = 2; private static int WALK3 = 0; private static int INTERACT = 3; private static int SPRITEWIDTHPIXELS = 32; private static int SPRITEHEIGHTPIXELS = 32; private static int SPRITESPACINGINPIXELS = 4; protected SpriteSheet spriteSheet; private Status status; private int currentActorDirection = 0; private int currentActorAction = 0; private int walkSpriteDuration = 5; private int walkSpriteCounter = 0; public ActorRenderer(String spriteSheetFileName, Status status) throws SlickException{ Image img = new Image(spriteSheetFileName); int w = SPRITEWIDTHPIXELS-SPRITESPACINGINPIXELS; int h = SPRITEHEIGHTPIXELS - SPRITESPACINGINPIXELS; spriteSheet = new SpriteSheet(img, w, h,SPRITESPACINGINPIXELS); this.status = status; } public void render(Graphics g, int offsetX, int offsetY) { // renderShape( g, renderX, renderY); determineCurrentActorDirection(); determineCurrentActorAction(); Shape shape = status.getRect(); float x = shape.getX(); float y = shape.getY(); spriteSheet.getSubImage(currentActorAction,currentActorDirection ).draw(x-offsetX, y-offsetY); } @SuppressWarnings("unused") private void renderShape(Graphics g, int renderX, int renderY) { Shape shape = status.getRect(); float x = shape.getX(); float y = shape.getY(); shape.setX(x - renderX); shape.setY(y -renderY); g.draw(shape); shape.setX(x); shape.setY(y); } private void determineCurrentActorAction(){ boolean isWalking = status.hasEffects(Effect.EFFECTS_AMBULATING); boolean isInteracting = status.hasEffect(Effect.EFFECT_INTERACTING); if (isInteracting){ currentActorAction = ActorRenderer.INTERACT; return; } if (isWalking){ walkSpriteCounter =(1 + walkSpriteCounter)%walkSpriteDuration; if (walkSpriteCounter == 0){ if (currentActorAction == WALK1){ currentActorAction = WALK2; }else if (currentActorAction == WALK2){ currentActorAction = WALK3; }else if (currentActorAction == WALK3){ currentActorAction = WALK1; }else{ currentActorAction = WALK1;} } return; } currentActorAction = ActorRenderer.STAND; } private void determineCurrentActorDirection(){ float [] faceDirection = status.getFacingDirection(); double facingAngle = Math.atan2(faceDirection[1], faceDirection[0]) ; //Output of atan2 is from -pi to pi. Need to translate to 0 to 2 pi if (facingAngle<0){ facingAngle = facingAngle + 2*Math.PI;} //Assign actor direction according to octants, but we need to translate by a 16th of a rotation int dir = (int) Math.floor(16*facingAngle/(2*Math.PI)); dir = (dir+1) %16; currentActorDirection = dir/2; return; } }
package com.android.myvirtualnutritionist.ui.diary.nutrition; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; public class CaloriesViewModel extends ViewModel { private MutableLiveData<String> totalCalories; private MutableLiveData<String> netCalories; private MutableLiveData<String> goal; public CaloriesViewModel() { totalCalories = new MutableLiveData<>(); totalCalories.setValue("0"); netCalories = new MutableLiveData<>(); netCalories.setValue("0"); goal = new MutableLiveData<>(); goal.setValue("2070"); } public LiveData<String> getTotalCalories() { return totalCalories; } public LiveData<String> getNetCalories() { return netCalories; } public LiveData<String> getGoal() { return goal; } }
package Lector13.Task7; public class GetIntThree { public static String getIntTree (int num){ Long m = System.nanoTime(); String str =""; if (num > 9999999999l) { str = "0000000000"; } else { if (num < 10) { str = str.concat("000000000" + num); } else if (num > 9 && num < 100) { str = str.concat("00000000" + num); } else if (num > 99 && num < 1000) { str = str.concat("0000000" + num); } else if (num > 999 && num < 10000) { str = str.concat("000000" + num); } else if (num > 9999 && num < 100000) { str = str.concat("00000" + num); } else if (num > 99999 && num < 1000000) { str = str.concat("0000" + num); } else if (num > 999999 && num < 10000000) { str = str.concat("000" + num); } else if (num > 9999999 && num < 100000000) { str = str.concat("00" + num); } else if (num > 99999999 && num < 1000000000) { str = str.concat("0" + num); } else if (num > 999999999 && num < 10000000000L) { str = str.concat("" + num); } } m = System.nanoTime() - m; System.out.printf("Функция выполнялось %,9.3f ms\n", m / 1_000_000.0); return str; } }
public class BucketSortDemo { public static void main(String[] args) { int[] array = { 23, 24, 22, 21, 26, 25, 27, 28, 21, 21 }; BucketSort m = new BucketSort(array, 20, 30); m.sort(); for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } } }
package com.zc.schedule.product.scheduleRule.dao; import java.util.List; import java.util.Map; import com.zc.base.orm.mybatis.annotation.MyBatisRepository; import org.springframework.stereotype.Repository; import com.zc.schedule.common.base.NormalDao; @MyBatisRepository(value = "groupDao") public interface GroupDao<GroupBean> extends NormalDao<GroupBean> { /** * * 查询分组信息 * * @param map * @return List */ public List<GroupBean> getGroupInfo(Map<String, Object> map); /** * * 查询分组与班次的关联信息 * * @param groupBean * @return List */ public List<GroupBean> getWorkInfo(GroupBean groupBean); /** * * 新增分组与班次关联信息 * * @param groupBean * @return Integer */ Integer addGroupWork(GroupBean groupBean); /** * 删除分组与班次关联信息 * * @param groupBean * @return Integer */ Integer deleteGroupWork(GroupBean groupBean); }
package com.test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.test.base.Solution; public class SolutionB implements Solution { @Override public int maxProfit(int[] prices) { if (null == prices || prices.length < 2) { return 0; } List<Point> dataList = new ArrayList<>(); int minValue = prices[0]; int lastValue = prices[0]; for (int i = 1; i < prices.length; i++) { if (prices[i] > lastValue) { lastValue = prices[i]; } else { if (lastValue > minValue) { dataList.add(new Point(minValue, lastValue)); } minValue = prices[i]; lastValue = prices[i]; } } if (lastValue > minValue) // 最后一个 { dataList.add(new Point(minValue, lastValue)); } if (dataList.isEmpty()) { return 0; } else if (dataList.size() == 1) { return dataList.get(0).max - dataList.get(0).min; } else if (dataList.size() == 2) { return (dataList.get(0).max - dataList.get(0).min) + (dataList.get(1).max - dataList.get(1).min); } else { HashMap<Integer, Integer> hashMap = new HashMap<>(); final int endIndex = dataList.size() - 1; int profit = 0; for (int i = 0; i < endIndex; i++) { int preMax = dfs(dataList, 0, i, hashMap); int postMax = dfs(dataList, i + 1, endIndex, hashMap); profit = Math.max(profit, preMax + postMax); } return profit; } } /** * 计算 start - end中的最大值 * 这里可以使用,hashMap优化 */ private int dfs(List<Point> data, int start, int end, HashMap<Integer, Integer> hashMap) { int key = start * data.size() + end; if (hashMap.containsKey(key)) { return hashMap.get(key); } if (start == end) { return data.get(start).max - data.get(start).min; } int preMax = dfs(data, start, end - 1, hashMap); int postMax = data.get(end).max - data.get(end).min; for (int i = end; i >= start; i--) { postMax = Math.max(postMax, data.get(end).max - data.get(i).min); } int result = Math.max(preMax, postMax); hashMap.put(key, result); return result; } private static class Point { public int min; public int max; private Point(int min, int max) { this.min = min; this.max = max; } } private void log(List<Point> dataList) { System.out.println("---------------------------"); for (int i = 0; i < dataList.size(); i++) { Point point = dataList.get(i); System.out.println("min = " + point.min + ", max = " + point.max); } } }
package com.metoo.foundation.dao; import org.springframework.stereotype.Repository; import com.metoo.core.base.GenericDAO; import com.metoo.foundation.domain.FootPoint; @Repository("footPointDAO") public class FootPointDAO extends GenericDAO<FootPoint> { }
class TestGit{ ///666 }
package com.company.polygon; import com.company.pixel.PixelDrawer; import com.company.line.LineDrawer; import com.company.polygon.drawer.RegularPolygonDrawer; import com.company.screen_conversion.RealPoint; import com.company.screen_conversion.ScreenPoint; import java.awt.*; public class PolygonDrawerLine implements PolygonDrawer, RegularPolygonDrawer { private PixelDrawer pd; private Color c; private LineDrawer ld; public PolygonDrawerLine(PixelDrawer pd) { this.pd = pd; this.c = Color.BLACK; } @Override public void drawPolygon(ScreenPoint[] screenPoints) { for(int i = 0; i < screenPoints.length - 1; i++){ ld.drawLine(screenPoints[i], screenPoints[i + 1]); } ld.drawLine(screenPoints[screenPoints.length - 1], screenPoints[0]); } @Override public void setLineDrawer(LineDrawer ld) { this.ld = ld; } @Override public LineDrawer getLineDrawer() { return ld; } @Override public Color getColor() { return c; } @Override public void setColor(Color c) { this.c = c; } @Override public RealPoint[] getVertexes(RegularPolygon polygon) { int size = polygon.getSideCount(); RealPoint[] vertexes = new RealPoint[size]; int i = 0; double stepAngle = 2 * Math.PI / size; for (double currAngle = polygon.getAngle(); i < size; currAngle += stepAngle, i++) { double x = polygon.getCenter().getX() + Math.cos(currAngle) * polygon.getRadius(); double y = polygon.getCenter().getY() + Math.sin(currAngle) * polygon.getRadius(); vertexes[i] = new RealPoint(x, y); } return vertexes; } }
package jsonparser; import java.util.HashMap; import java.util.Set; public class DictObject extends JsonObject { HashMap<String, JsonObject> dict; public DictObject() { dict = new HashMap<>(); } public Set<String> keySet() { return dict.keySet(); } public JsonObject get(String key) { return dict.get(key); } public void set(String key, Integer value) { dict.put(key, new IntObject(value)); } public void set(String key, Double obj) { dict.put(key, new DoubleObject(obj)); } public void set(String key, String obj) { dict.put(key, new StringObject(obj)); } public void set(String key, JsonObject obj) { dict.put(key, obj); } @Override public String toString() { StringBuilder sb = new StringBuilder("{"); int i = 0; for (String key : dict.keySet()) { if(i++ != 0) sb.append(","); sb.append("\"").append(key).append("\":").append(dict.get(key)); } sb.append("}"); return sb.toString(); } @Override public JsonType getType() { return JsonType.ObjectType; } @Override public Object getValue() { return this; } }
package com.openfarmanager.android.core.network.mediafire; import android.database.Cursor; import com.mediafire.sdk.MFApiException; import com.mediafire.sdk.MFException; import com.mediafire.sdk.MediaFire; import com.mediafire.sdk.api.FileApi; import com.mediafire.sdk.api.FolderApi; import com.mediafire.sdk.api.responses.FileDeleteResponse; import com.mediafire.sdk.api.responses.FileGetInfoResponse; import com.mediafire.sdk.api.responses.FileUpdateResponse; import com.mediafire.sdk.api.responses.FolderCreateResponse; import com.mediafire.sdk.api.responses.FolderDeleteResponse; import com.mediafire.sdk.api.responses.FolderGetContentsResponse; import com.mediafire.sdk.api.responses.FolderUpdateResponse; import com.mediafire.sdk.api.responses.data_models.File; import com.mediafire.sdk.api.responses.data_models.Folder; import com.openfarmanager.android.App; import com.openfarmanager.android.R; import com.openfarmanager.android.core.DataStorageHelper; import com.openfarmanager.android.core.dbadapters.NetworkAccountDbAdapter; import com.openfarmanager.android.core.network.NetworkApi; import com.openfarmanager.android.filesystem.FileProxy; import com.openfarmanager.android.filesystem.MediaFireFile; import com.openfarmanager.android.model.NetworkAccount; import com.openfarmanager.android.model.NetworkEnum; import com.openfarmanager.android.model.exeptions.NetworkException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; /** * @author Vlad Namashko */ public class MediaFireApi implements NetworkApi { public static final String APP_ID = "46558"; public static final String APP_KEY = "r3s0keye2wi0uucarqnuqerk4cw76h746gh3ernj"; public final static String VERSION = "1.4"; private MediaFire mMediaFire; private MediaFireAccount mCurrentAccount; public MediaFireApi() { mMediaFire = new MediaFire(MediaFireApi.APP_ID, MediaFireApi.APP_KEY); } public void startNewSession(String userName, String password) throws MFApiException, MFException { mMediaFire.startSessionWithEmail(userName, password, null); mCurrentAccount = new MediaFireAccount(saveAccount(userName, password), userName, password); } public void startSession(MediaFireAccount account) throws MFApiException, MFException { mMediaFire.startSessionWithEmail(account.getUserName(), account.getPassword(), null); mCurrentAccount = account; } public void endSession() { mMediaFire.endSession(); } @Override public int getAuthorizedAccountsCount() { return NetworkAccountDbAdapter.count(NetworkEnum.MediaFire.ordinal()); } @Override public List<NetworkAccount> getAuthorizedAccounts() { List<NetworkAccount> accounts = new ArrayList<>(); Cursor cursor = NetworkAccountDbAdapter.getAccounts(NetworkEnum.MediaFire.ordinal()); if (cursor == null) { return accounts; } try { int idxId = cursor.getColumnIndex(NetworkAccountDbAdapter.Columns.ID); int idxUserName = cursor.getColumnIndex(NetworkAccountDbAdapter.Columns.USER_NAME); int idxAuthData = cursor.getColumnIndex(NetworkAccountDbAdapter.Columns.AUTH_DATA); while (cursor.moveToNext()) { MediaFireAccount account = new MediaFireAccount(cursor.getLong(idxId), cursor.getString(idxUserName), cursor.getString(idxAuthData)); accounts.add(account); } } finally { cursor.close(); DataStorageHelper.closeDatabase(); } return accounts; } public List<FileProxy> openDirectory(String path) { return openDirectory(path, null); } public List<FileProxy> openDirectory(String path, String parentPath) { List<FileProxy> files = new ArrayList<>(); LinkedHashMap<String, Object> query = new LinkedHashMap<>(); query.put("response_format", "json"); query.put("content_type", "folders"); query.put("chunk_size", 1000); if (!path.equals("/")) { query.put("folder_key", path); } try { FolderGetContentsResponse response = FolderApi.getContent(mMediaFire, query, VERSION, FolderGetContentsResponse.class); for (Folder folder : response.getFolderContents().folders) { files.add(new MediaFireFile(folder, path, parentPath)); } query.put("content_type", "files"); response = FolderApi.getContent(mMediaFire, query, VERSION, FolderGetContentsResponse.class); for (File file : response.getFolderContents().files) { files.add(new MediaFireFile(file, path, parentPath)); } } catch (Exception ignore) { ignore.printStackTrace(); } return files; } @Override public NetworkAccount newAccount() { return new MediaFireAccount(-1, App.sInstance.getResources().getString(R.string.btn_new), null); } @Override public NetworkAccount getCurrentNetworkAccount() { return mCurrentAccount; } @Override public void delete(FileProxy file) throws Exception { boolean isDirectory = file.isDirectory(); LinkedHashMap<String, Object> query = new LinkedHashMap<>(); query.put(isDirectory ? "folder_key" : "quick_key", file.getId()); if (isDirectory) { FolderApi.delete(mMediaFire, query, VERSION, FolderDeleteResponse.class); } else { FileApi.delete(mMediaFire, query, VERSION, FileDeleteResponse.class); } } @Override public String createDirectory(String baseDirectory, String newDirectoryName) throws Exception { LinkedHashMap<String, Object> query = new LinkedHashMap<>(); query.put("foldername", newDirectoryName); query.put("parent_key", baseDirectory); FolderCreateResponse response = FolderApi.create(mMediaFire, query, VERSION, FolderCreateResponse.class); return response.getFolderKey(); } @Override public Observable<FileProxy> search(String path, String query) { return null; } public MediaFire getMediaFire() { return mMediaFire; } @Override public boolean rename(FileProxy file, String newPath) throws Exception { boolean isDirectory = file.isDirectory(); String name = newPath.substring(newPath.lastIndexOf("/") + 1, newPath.length()); LinkedHashMap<String, Object> query = new LinkedHashMap<>(); query.put(isDirectory ? "folder_key" : "quick_key", file.getId()); query.put(isDirectory ? "foldername" : "filename", name); if (isDirectory) { FolderApi.update(mMediaFire, query, VERSION, FolderUpdateResponse.class); } else { FileApi.update(mMediaFire, query, VERSION, FileUpdateResponse.class); } return true; } public FileProxy getFileInfo(String id) { LinkedHashMap<String, Object> query = new LinkedHashMap<>(); query.put("quick_key", id); try { FileGetInfoResponse response = FileApi.getInfo(mMediaFire, query, VERSION, FileGetInfoResponse.class); return new MediaFireFile(response.getFileInfo()); } catch (Exception e) { throw NetworkException.handleNetworkException(e); } } public long saveAccount(String userName, String password) { return NetworkAccountDbAdapter.insert(userName, NetworkEnum.MediaFire.ordinal(), password); } public static class MediaFireAccount extends NetworkAccount { private String mPassword; public MediaFireAccount(long id, String userName, String password) { mId = id; mUserName = userName; mPassword = password; } public String getPassword() { return mPassword; } @Override public NetworkEnum getNetworkType() { return NetworkEnum.MediaFire; } } }
package cn.t.server.dnsserver.protocol; import cn.t.server.dnsserver.constants.RecordClass; import cn.t.server.dnsserver.constants.RecordType; /** * @author yj * @since 2020-01-01 10:45 **/ public class Request { private Header header; private String domain; private byte labelCount; private RecordType type; private RecordClass clazz; public Header getHeader() { return header; } public void setHeader(Header header) { this.header = header; } public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = domain; } public byte getLabelCount() { return labelCount; } public void setLabelCount(byte labelCount) { this.labelCount = labelCount; } public RecordType getType() { return type; } public void setType(RecordType type) { this.type = type; } public RecordClass getClazz() { return clazz; } public void setClazz(RecordClass clazz) { this.clazz = clazz; } }
import game.Gamer; import game.Memento; /** * Created by kilo on 2018/8/24. * 进行游戏的类 * 事先保存Memento的实例,之后根据需要恢复Gamer的状态 * 决定何时拍照,何时撤销以及保存Memento角色 */ public class Main { public static void main(String[] args) { Gamer gamer = new Gamer(100);//最初持有金钱数为100 Memento memento = gamer.createMemento();//保存最初的状态 for (int i = 0; i < 100; i++) { System.out.println("==== " + i); System.out.println("当前状态:" + gamer); gamer.bet();//进行游戏 System.out.println("所持金钱为" + gamer.getMoney() + "元。"); //决定如何处理Memento if (gamer.getMoney() > memento.getMoney()) { System.out.println("(所持金钱增加了许多,因此保存游戏当前的状态)"); } else if (gamer.getMoney() < memento.getMoney() / 2) { System.out.println("(所持金钱减少了许多,因此将游戏恢复至以前的状态)"); gamer.restoreMemento(memento); } //等待一段时间 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(""); } } }
package pinno.demo.hackernews.screen.collection.viewholder; import android.support.annotation.NonNull; import android.view.View; import pinno.demo.hackernews.base.BaseViewHolder; import pinno.demo.hackernews.base.ListItem; public class LoadingViewHolder extends BaseViewHolder<ListItem> { private final int viewType; public LoadingViewHolder(@NonNull final View itemView, final int viewType) { super(itemView); this.viewType = viewType; } @Override public void bindTo(@NonNull ListItem aVoid) { //no-op } @Override public int viewType() { return viewType; } }
/* * (C) Mississippi State University 2009 * * The WebTOP employs two licenses for its source code, based on the intended use. The core license for WebTOP applications is * a Creative Commons GNU General Public License as described in http://*creativecommons.org/licenses/GPL/2.0/. WebTOP libraries * and wapplets are licensed under the Creative Commons GNU Lesser General Public License as described in * http://creativecommons.org/licenses/*LGPL/2.1/. Additionally, WebTOP uses the same licenses as the licenses used by Xj3D in * all of its implementations of Xj3D. Those terms are available at http://www.xj3d.org/licenses/license.html. */ //UnknownLens.java //Declares a ThinLens subclass with random focal length. //Peter Gilbert //Created July 29 2004 //Updated July 29 2004 //Version 0.01 package org.webtop.module.geometrical; import java.awt.*; import java.awt.event.*; import javax.swing.*; //import vrml.external.field.*; //import vrml.external.exception.*; import org.sdl.gui.numberbox.*; import org.webtop.util.*; import org.web3d.x3d.sai.*; //import webtop.vrml.*; //import webtop.wsl.script.*; //import webtop.wsl.client.*; //import webtop.wsl.event.*; import org.sdl.gui.numberbox.FloatBox; import org.sdl.math.FPRound; class UnknownLens extends CircularElement { public static final float MIN_FOCUS = -100, MAX_FOCUS = 100, DEF_FOCUS = 0; private static final float[] fValues = new float[] {10, 20, 25, 40, 50, -12, -24, -36, -48, -80}; private static final String[] letters = new String[] {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"}; //private float focus = (float)(FPRound.toFixVal(Math.random()*100,1)); private float focus; private int index; private String letterIdent; private FloatBox fbFocus; private SFFloat set_radius, set_focus; private SFFloat radius_changed, focus_changed; public static final int FOCUS = getNextEventID(); //An object of this type will listen to each element's position box. private class FocusFieldListener extends NumberBox.Adapter { public void numChanged(NumberBox src, Number newVal) { //WSLPlayer wslPlayer = getWSLPlayer(); clearWarning(); float guess = newVal.floatValue(); if (guess == 0.0f) { return; } if (Math.abs((focus - guess) / focus) <= .01f) { help = "Correct. f = " + focus; fbFocus.setValue(focus); } else { help = "Incorrect f value of " + guess; fbFocus.setValue(0.0f); } appletUpdate(FOCUS); //wslPlayer.recordActionPerformed(getName(),"focus",String.valueOf(newVal)); //if(!draggingWidget() && !applet.isAddingElement()) // wslPlayer.recordActionPerformed(getName(),"position",String.valueOf(newVal)); } public void invalidEntry(NumberBox src, Number badVal) { setWarning("f must be between " + MIN_FOCUS + " and " + MAX_FOCUS + " cm."); } }; public UnknownLens(Geometrical main, float position, int place, String vrmlString) { super(main, "UnknownLens", vrmlString, position, "To guess f, type in the 'Unknown f' input box."); //set_focus = (EventInSFFloat) getEAI().getEI(getNode(),"set_focalLength"); index = place; focus = fValues[index]; letterIdent = letters[index]; //The indices put this box between the position and diameter boxen add(new JLabel("Unknown f:", Label.RIGHT), 3); add(fbFocus = makeFocusBox(), 4); add(new JLabel("cm"), 5); fbFocus.addNumberListener(new FocusFieldListener()); validate(); //EAI.Try eaitry=new EAI.Try(this); //focus_changed = (EventOutSFFloat) getEAI().getEO(getNode(),"focalLength_changed",eaitry,new Integer(FOCUS)); } public void setFields() { //vrmlString } public float getFocalLength() { return focus; } public String getHelp() { //return help + getApplet().computeDistances(getID()); getApplet().computeDistances(getID()); return help; } protected FloatBox makeFocusBox() { return new FloatBox(MIN_FOCUS, MAX_FOCUS, 0, 3); } public void process(RayList rays) { RayList previous = rays; rays = rays.next; while (rays != null) { rays.xv -= rays.x / getFocalLength(); rays.yv -= rays.y / getFocalLength(); rays = rays.next; } } public String getName() { return getNamePrefix() + letterIdent; } public String getLetter() { return letterIdent; } public int getIndex() { return index; } protected String getNamePrefix() { return "UnknownLens"; } public void guessFocus(float focus) { //focus=focus0; fbFocus.setValue(focus); //set_focus.setValue(focus); } public String toString() { try { return getClass().getName() + "[#" + getID() + ",pos=" + getPosition() + ",d=" + getDiameter() + ",f=" + getFocalLength() + ']'; } catch (NullPointerException e) { //not set up yet return super.toString(); } } /*public WSLNode toWSLNode() { //Assuming that the prefix is the same as the WSL node name except for case: WSLNode node=new WSLNode(getNamePrefix().toLowerCase()); final WSLAttributeList atts=node.getAttributes(); atts.add("id", String.valueOf(getID())); atts.add("name", String.valueOf(getName())); atts.add("diameter", String.valueOf(getDiameter())); atts.add("focus", String.valueOf(focus)); atts.add("position", String.valueOf(getPosition())); atts.add("index", String.valueOf(getIndex())); return node; }*/ }
package gamePackage; import gamePackage.myFrame; import java.awt.Dimension; import java.awt.Color; import java.awt.Font; import javax.swing.JLabel; import javax.swing.JPanel; public class gameNumberPanel { private gameStateSingleton StateGame = gameStateSingleton.getInstance(); public gameNumberPanel(JPanel topPanel) { JLabel myLabel = null; Font police = new Font("Tahoma", Font.BOLD, 30); if(StateGame.idPlayer == 0) { myLabel = new JLabel("Joueur 1"); myLabel.setFont(police); myLabel.setForeground(Color.GREEN); } else { myLabel = new JLabel("Joueur 2"); myLabel.setFont(police); myLabel.setForeground(Color.RED); } topPanel.add(myLabel); } }
package com.it306.test; /** * The property class. Extends Cell and adds method to store * Player object reference. * @author Amith Kini * */ public class Property extends Cell{ private Player powner; public Property(String name, int pos, int value, String colourGroup){ setName(name); setPosition(pos); setValue(value); setRent(value/10); setColourGroup(colourGroup); } public Player getPowner() { return powner; } public void setPowner(Player powner) { this.powner = powner; } }
package arcs.android.demo.service; import arcs.api.UiRenderer; import arcs.demo.services.AlertService; import arcs.demo.services.ClipboardService; import dagger.Binds; import dagger.Module; import dagger.Provides; import dagger.multibindings.IntoMap; import dagger.multibindings.StringKey; @Module public abstract class AndroidDemoServiceModule { @Binds public abstract ClipboardService provideClipboardSurface(AndroidClipboardService impl); @Binds public abstract AlertService provideAlertSurface(AndroidToastAlertService impl); @Provides @IntoMap @StringKey("notification") static UiRenderer provideNotificationRenderer(NotificationRenderer notificationRenderer) { return notificationRenderer; } @Provides @IntoMap @StringKey("autofill") static UiRenderer provideAutofillRenderer(AutofillRenderer autofillRenderer) { return autofillRenderer; } }
package org.odk.collect.android.activities; import java.io.IOException; import java.net.URISyntaxException; import org.apache.http.client.ClientProtocolException; import org.json.JSONArray; import com.mpower.database.feedbackdatabase; import com.mpower.model.Querydata; import com.mpower.util.HttpRequest; import android.app.Service; import android.content.Intent; import android.os.AsyncTask; import android.os.IBinder; public class poll_feedback_service extends Service { @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { (new AsyncTask(){ @Override protected Object doInBackground(Object... params) { // TODO Auto-generated method stub String status_url = "http://ongeza.ap01.aws.af.cm/index.php/ongezacontroller/getfarmerquery"; try { String result_data = HttpRequest.GetText(HttpRequest .getInputStreamForGetRequest(status_url)); JSONArray jsonarray = new JSONArray(result_data); for(int i = 0;i<jsonarray.length();i++){ Querydata qd = Querydata.create_obj_from_json(jsonarray.getJSONObject(i).toString()); feedbackdatabase fdb = new feedbackdatabase(poll_feedback_service.this); fdb.checkandinsert(qd); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(Object result) { // TODO Auto-generated method stub feedbackdatabase fdb = new feedbackdatabase(poll_feedback_service.this); if(fdb.returnunshownmessages()>0){ sendBroadcast(new Intent(poll_feedback_service.this, notificationreceiver.class)); fdb.updateshown(); } super.onPostExecute(result); } }).execute(); return startId; }; }
package com.mycompany.gaviao.service; import com.mycompany.gaviao.model.Cliente; import com.mycompany.gaviao.model.ClienteEndereco; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Restrictions; import java.awt.geom.RectangularShape; import java.util.ArrayList; import java.util.List; public class ClienteDAO { protected Session session; protected static SessionFactory sessionFactory; protected Session getSession() throws Exception { try { if(sessionFactory == null) { sessionFactory = new Configuration().configure().buildSessionFactory(); } return sessionFactory.openSession(); } catch (Exception ex) { throw new Exception("Erro ao abrir sessão com o banco!", ex); } } public void create(Cliente cliente) throws Exception { cliente.setAtivo(1); try { session = getSession(); session.beginTransaction(); session.save(cliente); session.getTransaction().commit(); System.out.println("Cliente salvo"); }catch(Exception ex){ throw new Exception("Erro ao criar novo cliente!",ex); } finally { session.close(); } } public List retreaveAll() throws Exception { try { session = getSession(); session.beginTransaction(); return session.createCriteria(Cliente.class, "cliente") .add(Restrictions.eq("cliente.ativo", 1)) .list(); }catch (Exception ex){ throw new Exception("Erro ao pesquisar todos os clientes!", ex); }finally { session.close(); } } public Object retreaveById(Long id) throws Exception { try { session = getSession(); session.beginTransaction(); Cliente cliente = (Cliente) session.createCriteria(Cliente.class, "cliente") .add(Restrictions.eq("cliente.ativo", 1)) .add(Restrictions.eq("cliente.id", id)) .uniqueResult(); cliente.setEnderecos(carregarClienteEnderecoList(cliente.getId())); return cliente; // Query query = session.createQuery("from Cliente where id =" + id); // Cliente cliente = (Cliente) query.uniqueResult(); // return cliente; }catch (Exception ex){ throw new Exception("Erro ao pesquisar cliente pelo id!", ex); }finally { session.close(); } } public List<ClienteEndereco> carregarClienteEnderecoList(Long clienteId) throws Exception { try{ ClienteEnderecoDAO enderecoDAO = new ClienteEnderecoDAO(); List<ClienteEndereco> clienteEnderecoList = clienteEnderecoList = enderecoDAO.retreaveByClienteId(clienteId); return clienteEnderecoList; } catch (Exception e){ throw new Exception("Erro ao Carregar Lista de Cliente Endereço", e); } } public List<Cliente> retreaveByNome(String nome) throws Exception { try { session = getSession(); session.beginTransaction(); return session.createCriteria(Cliente.class, "cliente") .add(Restrictions.eq("cliente.ativo", 1)) .add(Restrictions.like("nome", nome + "%")) .list(); // Query query = session.createQuery("from Cliente where nome LIKE '" + nome + "%'"); // List resultList = query.list(); // return resultList; }catch (Exception ex){ throw new Exception("Erro ao pesquisar cliente pelo nome!", ex); }finally { session.close(); } } public void update(Cliente cliente) throws Exception { try { session = getSession(); session.beginTransaction(); session.saveOrUpdate(cliente); // Query query = session.createQuery("update Cliente set nome = :NOME, cpf = :CPF, rg = :RG where id =" + cliente.getId()); // query.setParameter("NOME", cliente.getNome()); // query.setParameter("CPF", cliente.getCpf()); // query.setParameter("RG", cliente.getRg()); // int result = query.executeUpdate(); session.getTransaction().commit(); }catch (Exception ex){ throw new Exception("Erro ao alterar cliente", ex); }finally { session.close(); } } public void delete(Cliente cliente) throws Exception { cliente.setAtivo(0); try { session = getSession(); session.beginTransaction(); session.saveOrUpdate(cliente); // Query query = session.createQuery("delete Cliente where id =" + id); // query.executeUpdate(); session.getTransaction().commit(); }catch (Exception ex){ throw new Exception("Erro ao deletar cliente!", ex); }finally { session.close(); } } }
package pl.rakowiecki; import java.util.Scanner; public class Main extends NumberFormatException { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Wpisz zdanie: "); String sentence = scanner.nextLine(); int leftBracket = 0; int rightBracket = 0; for (int i = 0; i < sentence.length(); i++) { if(sentence.charAt(i) == '('){ leftBracket++; } else if(sentence.charAt(i) == ')'){ rightBracket++; } } if(rightBracket == leftBracket){ System.out.println("Ilość nawiasów z zdaniu jest poprawna"); } else{ System.out.println("Ilość nawiasow w zdaniu jest niepoprawna"); } System.out.println("Porawiony tekst\"Koljena poprawka\""); } }
package PACKAGE_NAME;public class VipUser { }
package jp.ac.it_college.std.s14011.pdp.mediator; /** * Created by s14011 on 15/06/16. */ public class Main { static public void main(String args[]) { new LoginFrame("Meditor Sample"); } }
package com.sparta.malik.model; import com.sparta.malik.util.Printer; import java.time.LocalDate; public class EmployeeDTO { private int id; private String prefix; private String firstName; private char middleInitial; private String lastName; private char gender; private String email; private LocalDate dateofBirth; private LocalDate dateofJoining; private float salary = 0f; public EmployeeDTO(int id, String prefix, String firstName, char middleInitial, String lastName, char gender, String email, LocalDate dateofBirth, LocalDate dateofJoining, float salary ) { this.id = id; this.prefix = prefix; this.firstName = firstName; this.middleInitial = middleInitial; this.lastName = lastName; this.gender = gender; this.email = email; this.dateofBirth = dateofBirth; this.dateofJoining = dateofJoining; setSalary(salary); } public int getId() { return id; } public void setId(int empID) { this.id = empID; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public char getMiddleInitial() { return middleInitial; } public void setMiddleInitial(char middleInitial) { this.middleInitial = middleInitial; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public char getGender() { return gender; } public void setGender(char gender) { this.gender = gender; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public LocalDate getDateofBirth() { return dateofBirth; } public void setDateofBirth(LocalDate dateofBirth) { this.dateofBirth = dateofBirth; } public LocalDate getDateofJoining() { return dateofJoining; } public void setDateofJoining(LocalDate dateofJoining) { this.dateofJoining = dateofJoining; } public float getSalary() { return salary; } public void setSalary(float salary) { if (salary < 0) { Printer.printErrorMessage(new Exception("Cannot give an employee less then no money!")); } this.salary = 0; } public boolean equals(Object obj) { if (obj instanceof EmployeeDTO) { EmployeeDTO temp = (EmployeeDTO) obj; return temp.prefix.equals(this.prefix) && temp.firstName.equals(this.firstName) && temp.middleInitial == this.middleInitial && temp.lastName.equals(this.lastName) && temp.gender == this.gender && temp.email.equals(this.email) && temp.dateofBirth == this.dateofBirth && temp.dateofJoining == this.dateofJoining && temp.salary == this.salary; } else { return super.equals(obj); } } @Override public String toString() { return "id=" + id + ", prefix='" + prefix + '\'' + ", firstName='" + firstName + '\'' + ", middleInitial='" + middleInitial + '\'' + ", lastName='" + lastName + '\'' + ", gender='" + gender + '\'' + ", email='" + email + '\'' + ", dateofBirth='" + dateofBirth + '\'' + ", dateofJoining='" + dateofJoining + '\'' + ", salary=" + salary; } }
package cn.cndoppler.newsandshopping.fragment; import android.view.View; import cn.cndoppler.newsandshopping.R; import cn.cndoppler.newsandshopping.comment.BaseFragment; public class LeftMenuFragment extends BaseFragment { private View view; @Override public View initView() { view = View.inflate(context, R.layout.fragment_left_menu,null); return view; } @Override public void initData() { } }
package com.pooyaco.person.web.bundle; import com.pooyaco.gazelle.web.bundle.GazelleResourceEnum; public enum PersonResources implements GazelleResourceEnum { PERSON_LIST("ليست افراد"), FIRST_NAME("نام"), LAST_NAME("نام خانوادگي"), BIRTHDAY("تاريخ تولد"), PERSON_INFO("مشخصات افراد"), CITY("شهر"), PROVINCE("استان"), ORGANIZATIONAL_UNIT("واحد سازمانی"), ORGANIZATIONAL_UNIT_LIST("ليست واحدهای سازمانی"), ORG_UNIT_NAME("نام"), ORG_UNIT_CODE("کد"), ORG_UNIT_DEPARTMENT_CODE("کد حسابگري"); private String value; private PersonResources(String value) { this.value = value; } public String value() { return value; } }
package com.xinhua.xdcb; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>nuclearVO complex type�� Java �ࡣ * * <p>����ģʽƬ��ָ�������ڴ����е�Ԥ�����ݡ� * * <pre> * &lt;complexType name="nuclearVO"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="magnumSend" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="manageCom" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="operator" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "nuclearVO", propOrder = { "magnumSend", "manageCom", "operator" }) public class NuclearVO { protected String magnumSend; protected String manageCom; protected String operator; /** * ��ȡmagnumSend���Ե�ֵ�� * * @return * possible object is * {@link String } * */ public String getMagnumSend() { return magnumSend; } /** * ����magnumSend���Ե�ֵ�� * * @param value * allowed object is * {@link String } * */ public void setMagnumSend(String value) { this.magnumSend = value; } /** * ��ȡmanageCom���Ե�ֵ�� * * @return * possible object is * {@link String } * */ public String getManageCom() { return manageCom; } /** * ����manageCom���Ե�ֵ�� * * @param value * allowed object is * {@link String } * */ public void setManageCom(String value) { this.manageCom = value; } /** * ��ȡoperator���Ե�ֵ�� * * @return * possible object is * {@link String } * */ public String getOperator() { return operator; } /** * ����operator���Ե�ֵ�� * * @param value * allowed object is * {@link String } * */ public void setOperator(String value) { this.operator = value; } }
package com.test; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; public class ListComparisonInJava8 { public static void test() { List<String> nameList1 = Stream.of("birendra", "raoushni", "bijay", "rakesh", "rahul", "radha") .collect(Collectors.toList()); List<String> nameList2 = Stream.of("radha", "rani", "raoushni", "kavita").collect(Collectors.toList()); /** * will filter first matching data. */ Optional<String> optional = nameList1.stream().filter(nameList2::contains).findFirst(); if (optional.isPresent()) System.out.println("----match found----- : data is: "+optional.get()); else System.out.println("----match not found-----"); } public static void main(String[] args) { test(); } }
package cookie_session; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class SessionServlet */ public class SessionServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public SessionServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession sess = request.getSession(); String sessId = sess.getId(); System.out.println("JSESSIONID: " + sessId); sess.setAttribute("name", "xxx"); // SESS持久化,手动创建一个存储JSESSIONID的cookie Cookie c = new Cookie("JSESSIONID", sessId); c.setPath(request.getContextPath()); c.setMaxAge(60*60*24); response.addCookie(c); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package pkgbinternal; public class InternalBHelper { public String doIt() { return "from pkgbinternal.InternalBHelper"; } }
/* * Copyright 2018 Rundeck, Inc. (http://rundeck.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.rundeck.client.tool.commands.repository; import org.rundeck.client.api.RundeckApi; import org.rundeck.client.api.model.repository.RepositoryArtifacts; import org.rundeck.client.tool.InputError; import org.rundeck.client.tool.extension.BaseCommand; import picocli.CommandLine; import java.io.IOException; import java.util.List; @CommandLine.Command(name = "plugins", description = "Manage Rundeck plugins", subcommands = { UploadPlugin.class, InstallPlugin.class, UninstallPlugin.class }) public class Plugins extends BaseCommand { @CommandLine.Command(name = "list", description = "List plugins") public void list() throws InputError, IOException { List<RepositoryArtifacts> repos = getRdTool().apiCall(RundeckApi::listPlugins); repos.forEach(repo -> { getRdOutput().output("==" + repo.getRepositoryName() + " Repository=="); repo.getResults().forEach(plugin -> { if (plugin.getInstallId() != null && !plugin.getInstallId().isEmpty()) { String updateable = ""; if (plugin.isUpdatable()) { updateable = " (Updatable to " + plugin.getCurrentVersion() + ")"; } getRdOutput().output(String.format( "%s : %s : %s (%sinstalled) %s", plugin.getInstallId(), plugin.getName(), plugin.isInstalled() ? plugin.getInstalledVersion() : plugin.getCurrentVersion(), plugin.isInstalled() ? "" : "not ", updateable )); } }); }); } }
/* * Copyright (C) 2017 Philippe GENOUD - Université Grenoble Alpes - Lab LIG-Steamer * * 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 m2cci.pi01.cybertheatre.ctrlers; import java.io.IOException; import java.sql.SQLException; import java.time.LocalDate; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import javax.annotation.Resource; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.sql.DataSource; import m2cci.pi01.cybertheatre.DAO.ProgrammationDAO; import m2cci.pi01.cybertheatremodel.Representation; /** * Fourni la liste des spectacles enregistrés dans la BD et redirige sur la vue * /WEB-INF/spectacles.jsp. * * L'url associée à cette servlet est "/listespectacles". * * C'est la page d'accueil du site (voir l'élément <welcome-file> dans le * fichier de déploiement de l'application défini dans WEB-INF/web.xml. * * <welcome-file-list> * <welcome-file>listespectacles</welcome-file> * </welcome-file-list> * * La servlet construit une liste de Spectacles placée en attribut de la requête * transmise à la vue. Les nom de cette liste est "spectacles" * * @author Emilie Sirot, Philémon Giraud */ @WebServlet(name = "ChoixPlacesCtrl", urlPatterns = {"/ChoixPlacesCtrl"}) public class ChoixPlacesCtrl extends HttpServlet { @Resource(name = "jdbc/CyberTheatre") private DataSource bdSQL; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // String nomSpectacle = request.getParameter("spectacle"); DateTimeFormatter formatDate = DateTimeFormatter.ofPattern("yyyy-MM-dd"); DateTimeFormatter formatHeure = DateTimeFormatter.ofPattern("HH:mm"); LocalDate date = LocalDate.parse(request.getParameter("date"), formatDate); LocalTime heure = LocalTime.parse(request.getParameter("heure"), formatHeure); try { Representation representation = ProgrammationDAO.getRepresentation(bdSQL, date, heure); // stocke la représentation en session pour qu'il puisse être utilisé lors des prochaines requêtes HttpSession session = request.getSession(); session.setAttribute("representation", representation); request.setAttribute("representation", representation); request.getRequestDispatcher("/WEB-INF/choixPlaces.jsp").forward(request, response); } catch (SQLException ex) { System.out.println(ex.getMessage()); throw new ServletException(ex.getMessage(), ex); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
package com.spreadtrum.android.eng; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.widget.TextView; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.nio.charset.Charset; public class TextInfo extends Activity { private String mATResponse; private String mATline; private engfetch mEf; Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 0: TextInfo.this.mTextView.setText("ERROR"); return; case 1: TextInfo.this.mTextView.setText("NULL"); return; case 2: TextInfo.this.mTextView.setText(TextInfo.this.mATResponse); return; default: return; } } }; private int mSocketID; private int mStartN; private TextView mTextView; private ByteArrayOutputStream outputBuffer; private DataOutputStream outputBufferStream; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.textinfo); this.mTextView = (TextView) findViewById(R.id.text_view); this.mEf = new engfetch(); this.mStartN = getIntent().getIntExtra("text_info", 0); switch (this.mStartN) { case 1: setTitle(R.string.sim_forbid_plmn); this.mSocketID = this.mEf.engopen(); break; case 2: setTitle(R.string.sim_equal_plmn); this.mSocketID = this.mEf.engopen(); break; default: Log.e("TextInfo", "mStartN:" + this.mStartN); break; } getDisplayText(); } private void getDisplayText() { new Thread(new Runnable() { public void run() { TextInfo.this.outputBuffer = new ByteArrayOutputStream(); TextInfo.this.outputBufferStream = new DataOutputStream(TextInfo.this.outputBuffer); switch (TextInfo.this.mStartN) { case 1: TextInfo.this.mATline = 111 + "," + 0; break; case 2: TextInfo.this.mATline = 112 + "," + 0; break; default: TextInfo.this.mHandler.sendEmptyMessage(0); break; } Log.d("TextInfo", "mATline :" + TextInfo.this.mATline); try { TextInfo.this.outputBufferStream.writeBytes(TextInfo.this.mATline); } catch (IOException e) { Log.e("TextInfo", "writeBytes() error!"); TextInfo.this.mHandler.sendEmptyMessage(0); } TextInfo.this.mEf.engwrite(TextInfo.this.mSocketID, TextInfo.this.outputBuffer.toByteArray(), TextInfo.this.outputBuffer.toByteArray().length); byte[] inputBytes = new byte[512]; TextInfo.this.mATResponse = new String(inputBytes, 0, TextInfo.this.mEf.engread(TextInfo.this.mSocketID, inputBytes, 512), Charset.defaultCharset()); if (TextInfo.this.mATResponse.length() >= 10) { TextInfo.this.mATResponse = TextInfo.this.mATResponse.substring(10); } Log.e("TextInfo", "mATResponse:" + TextInfo.this.mATResponse); if (TextInfo.this.mATResponse.length() > 0) { TextInfo.this.mHandler.sendEmptyMessage(2); } else { TextInfo.this.mHandler.sendEmptyMessage(1); } } }).start(); } }
package com.example.demo; import com.example.demo.bean.req.CreditCardReq; import com.example.demo.entity.CreditCard; import com.example.demo.repository.CreditCardRepository; import com.example.demo.service.CreditCardService; import org.junit.Assert; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @RunWith(SpringRunner.class) @SpringBootTest(classes= {DemoApplication.class}, webEnvironment = WebEnvironment.RANDOM_PORT) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Transactional(propagation = Propagation.NOT_SUPPORTED) public class TestCreditCard { @Autowired CreditCardRepository creditCardRepository; @Autowired CreditCardService creditCardService; @Test(expected = Exception.class) public void test1CreditCardNull() throws Exception { creditCardService.addCard(null); } @Test(expected = Exception.class) public void test2CreditCardNoFail() throws Exception { CreditCardReq creditCardReq = new CreditCardReq(); creditCardReq.setCreditCardNo(""); creditCardService.addCard(creditCardReq); } @Test(expected = Exception.class) public void test3CreditCardNoFail() throws Exception { CreditCardReq creditCardReq = new CreditCardReq(); creditCardReq.setCreditCardNo("asdasdasdasdasda"); creditCardService.addCard(creditCardReq); } @Test(expected = Exception.class) public void test4CreditCardHolderFail() throws Exception { CreditCardReq creditCardReq = new CreditCardReq(); creditCardReq.setCreditCardNo("1234567891234567"); creditCardReq.setCardHolder(""); creditCardService.addCard(creditCardReq); } @Test(expected = Exception.class) public void test5CreditCardExpireEmpty() throws Exception { CreditCardReq creditCardReq = new CreditCardReq(); creditCardReq.setCreditCardNo("1234567891234567"); creditCardReq.setCardHolder("aaaaaa"); creditCardReq.setCardExpireDate(""); creditCardService.addCard(creditCardReq); } @Test(expected = Exception.class) public void test6CreditCardExpireFail() throws Exception { CreditCardReq creditCardReq = new CreditCardReq(); creditCardReq.setCreditCardNo("1234567891234567"); creditCardReq.setCardHolder("aaaaaa"); creditCardReq.setCardExpireDate("111"); creditCardService.addCard(creditCardReq); } @Test public void test7CreditCardSuccess() throws Exception { CreditCardReq creditCardReq = new CreditCardReq(); creditCardReq.setCreditCardNo("1234567891234567"); creditCardReq.setCardHolder("aaaaaa"); creditCardReq.setCardExpireDate("05/18"); CreditCard creditCard = creditCardService.addCard(creditCardReq); Assert.assertNotNull("creditCard should not be null", creditCard); } @Test public void test8FormatCardExpire() throws Exception { boolean result = "01/18".matches("([0-9]{2})/([0-9]{2})"); System.out.println("result= " + result); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.jearl.ejb.model; import java.io.Serializable; /** * * @author bamasyali */ public interface BaseEntity<PRIMARY> extends Serializable { PRIMARY getPrimayKey(); Integer getPrimayKeyAsInteger(); }
package database; public class ViewPet { }
package tree; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /**TODO 待优化 * 501. 二叉搜索树中的众数 给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。 * * 假定 BST 有如下定义: * * 结点左子树中所含结点的值小于等于当前结点的值 结点右子树中所含结点的值大于等于当前结点的值 左子树和右子树都是二叉搜索树 */ public class C501 { public static void main(String[] args) { TreeNode root = new TreeNode(1); root.right = new TreeNode(2); root.right.left = new TreeNode(2); Solution_1 solution = new Solution_1(); int [] res= solution.findMode(root); for(int i:res) { System.out.println(i); } } /** 未考虑BST的情况*/ static class Solution_1 { public int[] findMode(TreeNode root) { List<Integer> ll = new ArrayList<>(); Map<Integer, Integer> map = new HashMap<>(); allNode(root, map); Collection<Integer> count = map.values(); int max = 0; for (Integer c : count) { max = Math.max(max, c); } for (Integer key : map.keySet()) { if (map.get(key).equals(max)) { ll.add(key); } } int[] res = new int[ll.size()]; for (int i =0;i<ll.size();i++) { res[i]=ll.get(i); } return res; } public void allNode(TreeNode node, Map<Integer, Integer> map) { if (node == null) { return; } if (map.containsKey(node.val)) { map.put(node.val, map.get(node.val) + 1); } else { map.put(node.val, 1); } allNode(node.left, map); allNode(node.right, map); } } // static class Solution_2 { // public int[] findMode(TreeNode root) { // // } }
package ui; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import control.ClientContext; public class JTableFrame extends JFrame { private static final long serialVersionUID = 6611755870052213054L; JTable table = null; DefaultTableModel tableModel = null; String[] title = { "编号", "姓名", "成绩","考试类型","时间" }; Object[][] userInfo = null; ClientContext clientContext; public void setClientContext(ClientContext clientContext) { this.clientContext = clientContext; } public JTableFrame() { super("考试记录"); this.setSize(700, 400); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setLocationRelativeTo(null); this.setContentPane(createContentPane()); } private JPanel createContentPane() { JPanel p = new JPanel(new BorderLayout()); ImageIcon ico=new ImageIcon(this.getClass().getResource("/image/title.png")); JLabel lab=new JLabel(ico); p.add(lab,BorderLayout.NORTH); p.add(JTablePane(),BorderLayout.CENTER); p.add(createBtnPane(),BorderLayout.SOUTH); return p; } private JPanel JTablePane() { JPanel p = new JPanel(new BorderLayout()); this.tableModel = new DefaultTableModel(this.userInfo, this.title); this.table = new JTable(this.tableModel); JScrollPane scr = new JScrollPane(); scr.getViewport().add(this.table); JPanel toolBar = new JPanel(); p.add(toolBar, BorderLayout.NORTH); p.add(scr, BorderLayout.CENTER); return p; } private JPanel createBtnPane() { JPanel p = new JPanel(); JButton btn = new JButton("返回"); p.add(btn); btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { clientContext.showRecodeFrame(false); } }); return p; } /** * 设置考试记录 * */ public void setInfo(Object[][] userInfo){ this.userInfo=userInfo; for (int i = 0; i < tableModel.getRowCount(); i++) { this.tableModel.removeRow(i); } for (int i = 0; i < userInfo.length; i++) { if(userInfo[i]==null) continue; this.tableModel.addRow(userInfo[i]); } } }
package yinq.situation.fragments; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RadioGroup; import com.yinq.cherrydialyrecord.R; /** * A simple {@link Fragment} subclass. */ public class SituationStartFragment extends Fragment { FragmentManager fragmentManager; SituationMealFragment mealFragment; SituationSleepFragment sleepFragment; SituationInterestFragment interestFragment; public SituationStartFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_situation_start, container, false); initSwitchTab(view); createFragments(); return view; } protected void initSwitchTab(View view){ RadioGroup radioGroup = view.findViewById(R.id.situation_switch_tab_radio_group); radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { FragmentTransaction transaction = fragmentManager.beginTransaction(); hideAllFragments(transaction); switch (i){ case R.id.situation_switch_tab_radio_meal:{ transaction.show(mealFragment); break; } case R.id.situation_switch_tab_radio_sleep:{ transaction.show(sleepFragment); break; } case R.id.situation_switch_tab_radio_interest: { transaction.show(interestFragment); break; } } transaction.commit(); } }); } protected void createFragments(){ fragmentManager = getFragmentManager(); mealFragment = new SituationMealFragment(); sleepFragment = new SituationSleepFragment(); interestFragment = new SituationInterestFragment(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.add(R.id.situation_content_fragmetn, mealFragment); transaction.add(R.id.situation_content_fragmetn, sleepFragment); transaction.add(R.id.situation_content_fragmetn, interestFragment); hideAllFragments(transaction); transaction.show(mealFragment); transaction.commit(); } private void hideAllFragments(FragmentTransaction transaction){ transaction.hide(mealFragment); transaction.hide(sleepFragment); transaction.hide(interestFragment); } }
package com.jxtb.test.service; import com.jxtb.test.entity.Test; import java.util.List; /** * Created with IntelliJ IDEA. * User: Administrator * Date: 17-3-24 * Time: 下午5:11 * To change this template use File | Settings | File Templates. */ public interface ISessionService { public List<Test> findAllTest(); public int addAllTest(Test test); public int deleteAllTest(Test test); public int updateAllTest(Test test); public Test findTestById(String id); }
package binary.tree.max.path.sum; /** * Created by yebingxu on 8/22/15. */ class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } } class Flag { boolean isValid; public Flag(boolean valid) { isValid = valid; } } public class Solution { private int max = Integer.MIN_VALUE; private Flag maxValid = new Flag(false); public int maxPathSum(TreeNode root) { if (root == null) { return 0; } Flag lValid = new Flag(true); Flag rValid = new Flag(true); int lSum = maxPathSumCore(root.left, lValid); int rSum = maxPathSumCore(root.right, rValid); max = findMax(lSum, lValid, rSum, rValid, max, root.val); // set max to the bigger one of lSum and rSum, it may be overwrite by other bigger number return max; } private int findMax(int lSum, Flag lValid, int rSum, Flag rValid, int max, int rootVal) { int retMax = max; if (lValid.isValid) { retMax = Math.max(retMax, lSum); maxValid.isValid = true; } if (rValid.isValid) { retMax = Math.max(retMax, rSum); maxValid.isValid = true; } if (maxValid.isValid) { retMax = Math.max(retMax, retMax+rootVal); retMax = Math.max(retMax, rootVal); } else { retMax = rootVal; maxValid.isValid = true; } return retMax; } private int maxPathSumCore(TreeNode root, Flag valid) { if (root == null) { valid.isValid = false; return 0; } Flag lValid = new Flag(true); Flag rValid = new Flag(true); int lSum = maxPathSumCore(root.left, lValid); int rSum = maxPathSumCore(root.right, rValid); max = findMax(lSum, lValid, rSum, rValid, max, root.val); // set max to the bigger one of lSum and rSum, it may be overwrite by other bigger number int lPlusRoot = root.val; if (lValid.isValid) { lPlusRoot = lSum + root.val; } int rPlusRoot = root.val; if (rValid.isValid) { rPlusRoot = rSum + root.val; } return Math.max(lPlusRoot, rPlusRoot); } public static void main(String[] args) { Solution s = new Solution(); TreeNode root = new TreeNode(-3); s.maxPathSum(root); } }
package com.generator; import java.util.Random; import com.vehicles.Bus; import com.vehicles.Car; import com.vehicles.Truck; import com.vehicles.Vehicle; import com.vignett.BusVignett; import com.vignett.CarVignett; import com.vignett.TruckVignett; import com.vignett.Vignett; import com.vignettTaskExeptions.InvalidDriverDataException; import com.vignettTaskExeptions.InvalidVehicleException; import com.vignettTaskExeptions.InvalidVignettException; public class Generator { private static final Random generator = new Random(); public static Vignett gnerateRandomVignetts() throws InvalidVignettException { Vignett temp = null; int randomNumber = generator.nextInt(3) + 1; switch (randomNumber) { case 1: temp = new CarVignett(typeGenerator()); break; case 2: temp = new TruckVignett(typeGenerator()); break; case 3: temp = new BusVignett(typeGenerator()); break; default: throw new InvalidVignettException(); } return temp; } private static String typeGenerator() { String type = ""; int x = generator.nextInt(3) + 1; switch (x) { case 1: type = "yearly"; break; case 2: type = "monthly"; break; case 3: type = "dayly"; break; default: System.out.println("Something went wrong!"); break; } return type; } public static String generateRandomDriverName() throws InvalidDriverDataException { String firstName = ""; String secondName = ""; int x = generator.nextInt(5) + 1; switch (x) { case 1: firstName = "Gosho"; break; case 2: firstName = "Ivan"; break; case 3: firstName = "Petkan"; break; case 4: firstName = "Petrocvet"; break; case 5: firstName = "Jivko"; break; default: throw new InvalidDriverDataException(); } int y = generator.nextInt(5) + 1; switch (y) { case 1: secondName = "Ihtimanov"; break; case 2: secondName = "Georgiev"; break; case 3: secondName = "Cvetanov"; break; case 4: secondName = "Deonisiev"; break; case 5: secondName = "Djibrev"; break; default: throw new InvalidDriverDataException(); } String fullName = firstName + " " + secondName; return fullName; } public static double generateRandomDriverMoney() throws InvalidDriverDataException { int randomNumber = generator.nextInt(3) + 1; double money = 0.0; switch (randomNumber) { case 1: money = 5000.0; break; case 2: money = 7500.0; break; case 3: money = 15000.0; break; default: throw new InvalidDriverDataException(); } return money; } public static Vehicle generateRandomVehicle() throws InvalidVehicleException { Vehicle temp = null; int randomNumber = generator.nextInt(3) + 1; switch (randomNumber) { case 1: temp = new Car(generateRandomCarModel(), generator.nextInt(27) + 1990); break; case 2: temp = new Truck(generateRandomTruckModel(), generator.nextInt(27) + 1990); break; case 3: temp = new Bus(generateRandomBusModel(), generator.nextInt(27) + 1990); break; default: throw new InvalidVehicleException(); } return temp; } private static String generateRandomCarModel() throws InvalidVehicleException { String model = ""; int randomNumber = generator.nextInt(3) + 1; switch (randomNumber) { case 1: model = "Ferrari"; break; case 2: model = "Lamborghini"; break; case 3: model = "Pagani"; break; default: throw new InvalidVehicleException(); } return model; } private static String generateRandomTruckModel() throws InvalidVehicleException { String model = ""; int randomNumber = generator.nextInt(3) + 1; switch (randomNumber) { case 1: model = "MAN"; break; case 2: model = "Volvo"; break; case 3: model = "Mercedes"; break; default: throw new InvalidVehicleException(); } return model; } private static String generateRandomBusModel() throws InvalidVehicleException { String model = ""; int randomNumber = generator.nextInt(3) + 1; switch (randomNumber) { case 1: model = "Ikarus"; break; case 2: model = "Chavdar"; break; case 3: model = "Solaris"; break; default: throw new InvalidVehicleException(); } return model; } }
package de.varylab.discreteconformal.unwrapper; import static de.varylab.discreteconformal.util.CuttingUtility.cutManifoldToDisk; import static de.varylab.discreteconformal.util.CuttingUtility.cutToSimplyConnected; import static de.varylab.discreteconformal.util.CuttingUtility.cutTorusToDisk; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import no.uib.cipr.matrix.DenseVector; import no.uib.cipr.matrix.Vector; import de.jreality.geometry.IndexedFaceSetUtility; import de.jreality.math.Matrix; import de.jreality.math.MatrixBuilder; import de.jreality.math.Pn; import de.jreality.math.Rn; import de.jreality.scene.IndexedFaceSet; import de.jreality.scene.data.Attribute; import de.jreality.scene.data.DataList; import de.jreality.scene.data.DoubleArrayArray; import de.jtem.halfedge.util.HalfEdgeUtils; import de.jtem.halfedgetools.adapter.AdapterSet; import de.jtem.halfedgetools.adapter.type.generic.TexturePosition4d; import de.jtem.halfedgetools.algorithm.triangulation.Triangulator; import de.jtem.halfedgetools.jreality.ConverterJR2Heds; import de.jtem.jpetsc.InsertMode; import de.jtem.jpetsc.Mat; import de.jtem.jpetsc.Vec; import de.jtem.jtao.Tao; import de.jtem.jtao.Tao.GetSolutionStatusResult; import de.varylab.discreteconformal.adapter.EuclideanLengthWeightAdapter; import de.varylab.discreteconformal.functional.ConformalFunctional; import de.varylab.discreteconformal.heds.CoEdge; import de.varylab.discreteconformal.heds.CoFace; import de.varylab.discreteconformal.heds.CoHDS; import de.varylab.discreteconformal.heds.CoVertex; import de.varylab.discreteconformal.heds.CustomEdgeInfo; import de.varylab.discreteconformal.heds.CustomVertexInfo; import de.varylab.discreteconformal.heds.adapter.CoPositionAdapter; import de.varylab.discreteconformal.heds.adapter.CoTexturePositionAdapter; import de.varylab.discreteconformal.unwrapper.numerics.CEuclideanApplication; import de.varylab.discreteconformal.unwrapper.numerics.MTJDomain; import de.varylab.discreteconformal.util.CuttingUtility; import de.varylab.discreteconformal.util.CuttingUtility.CuttingInfo; import de.varylab.discreteconformal.util.Search.WeightAdapter; import de.varylab.discreteconformal.util.UnwrapUtility; public class EuclideanUnwrapperPETSc implements Unwrapper { private Logger log = Logger.getLogger(getClass().getName()); private QuantizationMode conesMode = QuantizationMode.AllAngles, boundaryQuantMode = QuantizationMode.AllAngles; private BoundaryMode boundaryMode = BoundaryMode.Isometric; private int maxIterations = 150, numCones = 0; private double gradTolerance = 1E-8; private boolean cutAndLayout = true; public static double lastGNorm = 0; private Collection<CoVertex> cones = new HashSet<CoVertex>(); private CoVertex layoutRoot = null; private CoVertex cutRoot = null; private Set<CoEdge> cutGraph = null; private CuttingInfo<CoVertex, CoEdge, CoFace> cutInfo = null; private Map<CoEdge, Double> lengthMap = null; private Vector uVec = null; private CEuclideanApplication app = null; static { Tao.Initialize(); } public EuclideanUnwrapperPETSc() { super(); } public EuclideanUnwrapperPETSc(boolean cutAndLayout) { super(); this.cutAndLayout = cutAndLayout; } @Override public void unwrap(CoHDS surface, int genus, AdapterSet aSet) throws Exception { app = new CEuclideanApplication(surface); double[] uValues = calculateConformalFactors(surface, aSet, app); uVec = new DenseVector(uValues); WeightAdapter<CoEdge> weights = new EuclideanLengthWeightAdapter(uVec); if (cutAndLayout) { CoVertex root = surface.getVertex(0); if (cutRoot != null) { root = cutRoot; } if (cutGraph != null) { cutInfo = new CuttingInfo<CoVertex, CoEdge, CoFace>(); cutInfo.cutRoot = root; CuttingUtility.cutAtEdges(cutInfo, cutGraph); } else { switch (genus) { case 0: cutInfo = ConesUtility.cutMesh(surface); cutToSimplyConnected(surface, root, cutInfo); break; case 1: cutInfo = cutTorusToDisk(surface, root, weights); break; default: cutInfo = cutManifoldToDisk(surface, root, weights); } } lengthMap = EuclideanLayout.getLengthMap(surface, app.getFunctional(), uVec); layoutRoot = EuclideanLayout.doLayout(surface, app.getFunctional(), uVec); } } public Map<CoVertex, Double> calculateConformalFactors(CoHDS surface, AdapterSet aSet) throws UnwrapException { app = new CEuclideanApplication(surface); double[] u = calculateConformalFactors(surface, aSet, app); DenseVector uVec = new DenseVector(u); MTJDomain uDomain = new MTJDomain(uVec); Map<CoVertex, Double> result = new LinkedHashMap<CoVertex, Double>(); for (CoVertex v : surface.getVertices()) { Double uVal = app.getFunctional().getVertexU(v, uDomain); result.put(v, uVal); } return result; } private synchronized double[] calculateConformalFactors(CoHDS surface, AdapterSet aSet, CEuclideanApplication app) throws UnwrapException { UnwrapUtility.prepareInvariantDataEuclidean(app.getFunctional(), surface, boundaryMode, boundaryQuantMode, aSet); // cones cones = ConesUtility.setUpCones(surface, numCones); // optimization Vec u; Tao optimizer; int n = app.getDomainDimension(); u = new Vec(n); // set variable lambda start values for (CoEdge e : surface.getPositiveEdges()) { if (e.getSolverIndex() >= 0) { u.setValue(e.getSolverIndex(), e.getLambda(), InsertMode.INSERT_VALUES); } } app.setInitialSolutionVec(u); Mat H = app.getHessianTemplate(); app.setHessianMat(H, H); optimizer = new Tao(Tao.Method.NTR); optimizer.setApplication(app); optimizer.setTolerances(0, 0, 0, 0); optimizer.setGradientTolerances(gradTolerance, gradTolerance, gradTolerance); optimizer.setMaximumIterates(maxIterations); optimizer.solve(); GetSolutionStatusResult status = optimizer.getSolutionStatus(); lastGNorm = status.gnorm; if (status.reason.cvalue() < 0) { throw new UnwrapException("Optimization did not succeed: " + status); } UnwrapUtility.logSolutionStatus(optimizer, log); if (!cones.isEmpty()) { if (conesMode != QuantizationMode.AllAngles) { log.info("performing cone angle quantization"); cones = ConesUtility.quantizeCones(surface, cones, conesMode); CEuclideanApplication app2 = new CEuclideanApplication(surface); n = app2.getDomainDimension(); u = new Vec(n); H = app.getHessianTemplate(); app2.setInitialSolutionVec(u); app2.setHessianMat(H, H); optimizer.setApplication(app2); optimizer.solve(); status = optimizer.getSolutionStatus(); if (status.reason.cvalue() < 0) { log.warning("Cone quantization did not succeed: " + status); } else { UnwrapUtility.logSolutionStatus(optimizer, log); } } } double [] uValues = u.getArray(); u.restoreArray(); return uValues; } public Collection<CoVertex> getCones() { return cones; } public void setNumCones(int numCones) { this.numCones = numCones; } public void setConeMode(QuantizationMode quantizationMode) { this.conesMode = quantizationMode; } @Override public void setGradientTolerance(double tol) { gradTolerance = tol; } @Override public void setMaxIterations(int maxIterations) { this.maxIterations = maxIterations; } public void setBoundaryQuantMode(QuantizationMode boundaryQuantMode) { this.boundaryQuantMode = boundaryQuantMode; } public void setBoundaryMode(BoundaryMode boundaryMode) { this.boundaryMode = boundaryMode; } @Override public void setCutRoot(CoVertex root) { this.cutRoot = root; } public Vector getUResult() { return uVec; } public boolean isCutAndLayout() { return cutAndLayout; } public void setCutAndLayout(boolean cutAndLayout) { this.cutAndLayout = cutAndLayout; } @Override public CuttingInfo<CoVertex, CoEdge, CoFace> getCutInfo() { return cutInfo; } @Override public Map<CoEdge, Double> getlengthMap() { return lengthMap; } @Override public CoVertex getLayoutRoot() { return layoutRoot; } public ConformalFunctional<CoVertex, CoEdge, CoFace> getFunctional() { return app.getFunctional(); } /** * Unwraps a surface with specified boundary angles and circular * boundaries defined by a vertex per boundary component * @param ifs * @param layoutRoot * @param boundaryAngles * @param circularEdges */ public static void unwrapcg(IndexedFaceSet ifs, int layoutRoot, Map<Integer, Double> boundaryAngles, List<Integer> circularVerts, double tol) { IndexedFaceSetUtility.makeConsistentOrientation(ifs); CoHDS hds = new CoHDS(); AdapterSet a = AdapterSet.createGenericAdapters(); a.add(new CoPositionAdapter()); a.add(new CoTexturePositionAdapter()); ConverterJR2Heds cTo = new ConverterJR2Heds(); cTo.ifs2heds(ifs, hds, a); CircleDomainUnwrapper.flipAtEars(hds, a); // set boundary conditions for (CoVertex v : HalfEdgeUtils.boundaryVertices(hds)) { if (boundaryAngles.containsKey(v.getIndex())) { Double angle = boundaryAngles.get(v.getIndex()); v.info = new CustomVertexInfo(); v.info.useCustomTheta = true; v.info.theta = angle; } } if (circularVerts != null) { prepareCircularHoles(hds, circularVerts, a); } double[][] texArr = unwrap(layoutRoot, hds, a); DataList newTexCoords = new DoubleArrayArray.Array(texArr); ifs.setVertexAttributes(Attribute.TEXTURE_COORDINATES, null); ifs.setVertexAttributes(Attribute.TEXTURE_COORDINATES, newTexCoords); } public static void prepareCircularHoles(CoHDS hds, List<Integer> circularVerts, AdapterSet a) { // find the boundary components associated to each vertex in the list of circular vertices List<CoEdge> circularEdges = new LinkedList<CoEdge>(); for (int vIndex : circularVerts) { // System.err.println("Processing circ vertex "+vIndex); CoVertex v1 = hds.getVertex(vIndex); List<CoEdge> edges = HalfEdgeUtils.incomingEdges(v1); CoEdge bedge = null; for (CoEdge e : edges) { // System.err.println("Start vertex = "+e.getStartVertex().getIndex()); if (HalfEdgeUtils.isBoundaryEdge(e)) { bedge = e; break; } } if (bedge == null) { throw new IllegalStateException("No boundary edge on vertex "+vIndex); } CoFace filler = HalfEdgeUtils.fillHole(bedge); // int n = circularEdges.size(); // weird error message when I try to assign the triangulateFace() call to local variable! circularEdges.addAll(Triangulator.triangulateByCuttingCorners(filler, a)); // int m = circularEdges.size(); // System.err.println("Added "+(m-n)+" edges"); } for (CoEdge ce : circularEdges) { // CoVertex v2 = hds.getVertex(eIndex[1]); // CoEdge ce = HalfEdgeUtils.findEdgeBetweenVertices(v1, v2); // if (ce == null) throw new RuntimeException("could not find circular edge between vertex " + v1 + " and " + v2); CoEdge ceOpp = ce.getOppositeEdge(); ce.info = new CustomEdgeInfo(); ce.info.circularHoleEdge = true; ceOpp.info = new CustomEdgeInfo(); ceOpp.info.circularHoleEdge = true; } } /** * unwraps a surface with specified boundary angles and circular edges; * @param ifs * @param layoutRoot * @param boundaryAngles * @param circularEdges */ public static void unwrap(IndexedFaceSet ifs, int layoutRoot, Map<Integer, Double> boundaryAngles, List<int[]> circularEdges, List<Double> circularAngleSums) { IndexedFaceSetUtility.makeConsistentOrientation(ifs); CoHDS hds = new CoHDS(); AdapterSet a = AdapterSet.createGenericAdapters(); a.add(new CoPositionAdapter()); a.add(new CoTexturePositionAdapter()); ConverterJR2Heds cTo = new ConverterJR2Heds(); cTo.ifs2heds(ifs, hds, a); CircleDomainUnwrapper.flipAtEars(hds, a); // set boundary conditions for (CoVertex v : HalfEdgeUtils.boundaryVertices(hds)) { if (boundaryAngles.containsKey(v.getIndex())) { Double angle = boundaryAngles.get(v.getIndex()); v.info = new CustomVertexInfo(); v.info.useCustomTheta = true; v.info.theta = angle; } } // find circular edges if (circularEdges != null) { if (circularAngleSums != null && circularEdges.size() != circularAngleSums.size()) { throw new RuntimeException("circular edges and angle sums do not match"); } for (int i = 0; i < circularEdges.size(); i++) { int[] eIndex = circularEdges.get(i); CoVertex v1 = hds.getVertex(eIndex[0]); CoVertex v2 = hds.getVertex(eIndex[1]); CoEdge ce = HalfEdgeUtils.findEdgeBetweenVertices(v1, v2); if (ce == null) throw new RuntimeException("could not find circular edge between vertex " + v1 + " and " + v2); CoEdge ceOpp = ce.getOppositeEdge(); ce.info = new CustomEdgeInfo(); ce.info.circularHoleEdge = true; ceOpp.info = new CustomEdgeInfo(); ceOpp.info.circularHoleEdge = true; if (circularAngleSums != null) { Double phi = circularAngleSums.get(i); ce.info.phi = phi; ceOpp.info.phi = phi; } } } double[][] texArr = unwrap(layoutRoot, hds, a); DataList newTexCoords = new DoubleArrayArray.Array(texArr); ifs.setVertexAttributes(Attribute.TEXTURE_COORDINATES, null); ifs.setVertexAttributes(Attribute.TEXTURE_COORDINATES, newTexCoords); } /** * Calculate flat texture coordinates for a Euclidean structure * @param layoutRoot * @param hds * @param a * @return */ private static double[][] unwrap(int layoutRoot, CoHDS hds, AdapterSet a) { EuclideanUnwrapperPETSc unwrap = new EuclideanUnwrapperPETSc(); unwrap.setBoundaryQuantMode(QuantizationMode.Straight); unwrap.setBoundaryMode(BoundaryMode.QuantizedAngles); unwrap.setGradientTolerance(1E-12); unwrap.setMaxIterations(50); try { unwrap.unwrap(hds, 0, a); } catch (Exception e) { e.printStackTrace(); } double[][] texArr = new double[hds.numVertices()][]; for (int i = 0; i < texArr.length; i++) { CoVertex v = hds.getVertex(i); texArr[i] = a.getD(TexturePosition4d.class, v); } CoVertex layoutRootVertex = hds.getVertex(layoutRoot); CoEdge bdIn = layoutRootVertex.getIncomingEdge(); // find a boundary edge if there is any for (CoEdge e : HalfEdgeUtils.incomingEdges(layoutRootVertex)) { if (e.getLeftFace() == null) { bdIn = e; break; } } CoVertex nearVertex = bdIn.getStartVertex(); int nearIndex = nearVertex.getIndex(); double[] t = Pn.dehomogenize(null, texArr[layoutRoot]); double[] t2 = Pn.dehomogenize(null, texArr[nearIndex]); double angle = Math.atan2(t2[1] - t[1], t2[0] - t[0]); MatrixBuilder bT = MatrixBuilder.euclidean(); bT.rotate(-angle, 0, 0, 1); bT.translate(-t[0], -t[1], 0); Matrix T = bT.getMatrix(); for (int i = 0; i < texArr.length; i++) { double[] tc = texArr[i]; double e = tc[3]; Pn.dehomogenize(tc, tc); T.transformVector(tc); Rn.times(tc, e, tc); } return texArr; } @Override public void setCutGraph(Set<CoEdge> cutEdges) { this.cutGraph = cutEdges; } }
package com.project.phase2; import com.project.Crew; public class Quest { private String name; private Crew givenBy; private boolean accepted =false; public Quest(String name, Crew givenBy) { this.name = name; this.givenBy = givenBy; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Crew getGivenBy() { return givenBy; } public void setGivenBy(Crew givenBy) { this.givenBy = givenBy; } public boolean isAccepted() { return accepted; } public void setAccepted(boolean accepted) { this.accepted = accepted; } }
package com.bestone.dao; import com.bestone.model.*; import java.util.List; public interface ArticleDao22 { //新建社区文章 void save(ArticleModel22 article22); //根据用户查询文章列表 List<UserArticle22> findShequByUser(UserModel user); //查询所有的社区文章(不区分作者) List<UserArticle22> findAllShequArticle(); //查询单个社区文章 UserArticle22 findShequArticleById(ArticleModel22 article22); }
package com.example.bob.health_helper.Community.contract; import com.example.bob.health_helper.Base.BaseMvpContract; public interface AddQuestionContract extends BaseMvpContract{ interface View extends BaseView { void onPublishQuestionSuccess(); void onPublishQuestionFailed(); } interface Presenter extends BasePresenter<View>{ void publishQuestion(String title,String description,String uid); } }
package com.tripper.db.relationships; import androidx.room.Embedded; import androidx.room.Entity; import androidx.room.Relation; import com.tripper.db.entities.Day; import com.tripper.db.entities.DaySegment; import java.util.List; public class DayWithSegmentsAndEvents { @Embedded public Day day; @Relation( entity = DaySegment.class, parentColumn = "id", entityColumn = "day_id" ) public List<DaySegmentWithEvents> daySegments; }
package com.example.graduation.fragment; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.example.graduation.PracticesActivity; import com.example.graduation.R; import com.example.graduation.java.HttpUtil; import org.jetbrains.annotations.NotNull; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.RequestBody; import okhttp3.Response; public class PracticeFragment extends Fragment implements View.OnClickListener { private EditText editSize; private SharedPreferences sp; private String uid; private Button butGetSize; private String Url = "http://47.106.112.29:8080/work/getWork"; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.practicefragment_layout,container,false); initView(view); return view; } private void initView(View view){ editSize = view.findViewById(R.id.practicefragment_edit_size); butGetSize = view.findViewById(R.id.practicefragment_but_getsize); butGetSize.setOnClickListener(this); sp = getActivity().getSharedPreferences("user", Context.MODE_PRIVATE); uid = sp.getString("uid",""); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.practicefragment_but_getsize: sendSize(Url); break; } } private void sendSize(String url){ RequestBody body = new FormBody.Builder() .add("id",uid) .add("size",editSize.getText().toString()) .build(); HttpUtil.sendJsonOkhttpRequest(url, body, new Callback() { @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { } @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try { String data = response.body().string(); JSONObject jsonObject = new JSONObject(data); if (jsonObject.optInt("ec") == 200){ Intent intent = new Intent(getActivity(), PracticesActivity.class); Bundle bundle = new Bundle(); bundle.putString("result",data); intent.putExtras(bundle); startActivity(intent); } } catch (JSONException e) { e.printStackTrace(); } } }); } }