text
stringlengths
10
2.72M
package Algo; import Modeles.Trajet; public interface TSP { /** * @return true si chercheSolution() s'est terminee parce que la limite de temps avait ete atteinte, avant d'avoir pu explorer tout l'espace de recherche, */ public Boolean getTempsLimiteAtteint(); /** * Cherche un circuit de duree minimale passant par chaque sommet (compris entre 0 et nbSommets-1) * * @param tpsLimite : limite (en millisecondes) sur le temps d'execution de chercheSolution * @param nbSommets : nombre de sommets du graphe * @param cout : cout[i][j] = longueur pour aller de i a j, avec {@literal 0 <= i < nbSommets et 0 <= j < nbSommets} */ public void chercheSolution(int tpsLimite, int nbSommets, Trajet[][] cout); /** * * @return le sommet visite en i-eme position dans la solution calculee par chercheSolution */ public Integer[] getMeilleureSolution(); /** * @return la duree de la solution calculee par chercheSolution */ public Double getCoutMeilleureSolution(); }
/** * Created by gregorgololicic on 05/10/14. */ public interface HtmlTextParser { String parseHtml(String html); }
package com.pwq.sort; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @Author:WenqiangPu * @Description * @Date:Created in 20:14 2017/8/2 * @Modified By: */ public class ComparableTest { public static void main(String[] args) { User user1 = new User(); user1.setName("pwq"); user1.setOrder(2); User user2 = new User(); user2.setName("gwt"); user2.setOrder(3); List<User> list = new ArrayList(); list.add(user1); list.add(user2); Collections.sort(list); for(User u:list){ System.out.println(u.getName()); } } }
package org.valdi.entities.disguise; import java.util.Locale; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import de.robingrether.util.ObjectUtil; /** * Represents a disguise as a horse. * * @since 3.0.1 * @author RobinGrether */ public class HorseDisguise extends AgeableDisguise { private boolean saddled; private Armor armor; /** * Creates an instance. * * @since 5.5.1 * @param type the disguise type to use * @throws IllegalArgumentException the given disguise type is not some sort of horse */ public HorseDisguise(DisguiseType type) { this(type, true, false, Armor.NONE); } /** * Creates an instance. * * @since 5.5.1 * @param type the disguise type to use * @param adult whether the disguise shall appear as an adult or as a baby * @param saddled whether the disguise shall carry a saddle * @param armor the type of horse armor the disguise shall wear * @throws IllegalArgumentException the given disguise type is not some sort of horse */ public HorseDisguise(DisguiseType type, boolean adult, boolean saddled, Armor armor) { super(type, adult); if(!ObjectUtil.equals(type, DisguiseType.DONKEY, DisguiseType.HORSE, DisguiseType.MULE, DisguiseType.SKELETAL_HORSE, DisguiseType.UNDEAD_HORSE)) { throw new IllegalArgumentException(); } this.saddled = saddled; this.armor = armor; } /** * Gets whether the horse is saddled. * * @since 3.0.1 * @return <code>true</code> if it is saddled */ public boolean isSaddled() { return saddled; } /** * Sets whether the horse is saddled. * * @since 3.0.1 * @param saddled should the horse be saddled */ public void setSaddled(boolean saddled) { this.saddled = saddled; } /** * Gets the armor. * * @since 3.0.3 * @return the armor */ public Armor getArmor() { return armor; } /** * Sets the armor. * * @since 3.0.3 * @param armor the armor */ public void setArmor(Armor armor) { this.armor = armor; } /** * @since 5.5.1 */ public int getVariant() { switch(type) { case HORSE: return 0; case DONKEY: return 1; case MULE: return 2; case UNDEAD_HORSE: return 3; case SKELETAL_HORSE: return 4; default: return -1; } } /** * {@inheritDoc} */ public String toString() { return String.format("%s; %s; %s", super.toString(), saddled ? "saddled" : "not-saddled", armor.name().toLowerCase(Locale.ENGLISH).replace("none", "no-armor")); } static { Subtypes.registerSubtype(HorseDisguise.class, "setSaddled", true, "saddled"); Subtypes.registerSubtype(HorseDisguise.class, "setSaddled", false, "not-saddled"); for(Armor armor : Armor.values()) { Subtypes.registerSubtype(HorseDisguise.class, "setArmor", armor, armor.name().toLowerCase(Locale.ENGLISH).replace("none", "no-armor")); } } /** * Represents armor for a horse. * * @since 3.0.3 * @author RobinGrether */ public enum Armor { IRON("IRON_BARDING"), GOLD("GOLD_BARDING"), DIAMOND("DIAMOND_BARDING"), NONE(null); private String item; private Armor(String item) { this.item = item; } /** * Gets the associated Bukkit item stack. * * @since 3.0.3 * @return the associated item stack */ public ItemStack getItem() { return Material.getMaterial(item) == null ? null : new ItemStack(Material.getMaterial(item), 1); } } }
package com.example.afinally; import androidx.appcompat.app.AppCompatActivity; import android.content.pm.ActivityInfo; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.HttpURLConnection; import java.net.URL; import java.util.Timer; import java.util.TimerTask; public class SecondActivity extends AppCompatActivity { String ip_add; String ip_add1; String ip_add2; String po; String text; Button left; Button right; Button up; Button down; EditText ip_address; WebView myWebView; WebView myWebView1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); ip_add =getIntent().getExtras().getString("Value"); po=getIntent().getExtras().getString("Value1"); ip_add2="http://"+ip_add+":"+po+"/"+"video_feed"; ip_add1 ="http://"+ip_add+":"+po+"/"+"battery"; myWebView = (WebView) findViewById(R.id.webView); /*myWebView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);*/ myWebView.setInitialScale(1); myWebView.getSettings().setLoadWithOverviewMode(true); myWebView.getSettings().setUseWideViewPort(true); WebSettings webSettings = myWebView.getSettings(); myWebView.setWebViewClient(new WebViewClient()); webSettings.setJavaScriptEnabled(true); myWebView.loadUrl(ip_add2); // myWebView1.setBackgroundColor(Color.TRANSPARENT); myWebView1 = (WebView) findViewById(R.id.webView1); myWebView1.setWebViewClient(new WebViewClient()); WebSettings webSettings1 = myWebView1.getSettings(); webSettings1.setJavaScriptEnabled(true); myWebView1.setBackgroundColor(0x00FFFFFF); myWebView1.loadUrl(ip_add1); up = (Button) findViewById(R.id.up); down = (Button) findViewById(R.id.down); right = (Button) findViewById(R.id.right); left = (Button) findViewById(R.id.left); up.setOnClickListener(new senddatatoserver()); down.setOnClickListener(new senddatatoserver()); right.setOnClickListener(new senddatatoserver()); left.setOnClickListener(new senddatatoserver()); } public class senddatatoserver implements View.OnClickListener{ @Override public void onClick(View v) { switch (v.getId()){ case R.id.left: text = left.getText().toString(); // do your code break; case R.id.right: text = right.getText().toString(); // do your code break; case R.id.up: text = up.getText().toString(); // do your code break; case R.id.down: text = down.getText().toString(); // do your code break; } JSONObject post_dict = new JSONObject(); try { post_dict.put("text", text); } catch (JSONException e) { e.printStackTrace(); } if (post_dict.length() > 0) { new SendJsonDataToServer().execute(String.valueOf(post_dict)); } } } //add background inline class here class SendJsonDataToServer extends AsyncTask<String,String,String> { @Override protected String doInBackground(String... params) { String JsonResponse = null; String JsonDATA = params[0]; HttpURLConnection urlConnection = null; BufferedReader reader = null; try { URL url = new URL("http://"+ip_add+":"+po+"/button"); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoOutput(true); // is output buffer writter urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestProperty("Accept", "application/json"); //set headers and method Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8")); writer.write(JsonDATA); // json data writer.close(); InputStream inputStream = urlConnection.getInputStream(); //input stream StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String inputLine; while ((inputLine = reader.readLine()) != null) buffer.append(inputLine + "\n"); if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } JsonResponse = buffer.toString(); //response data Log.i("mytag", JsonResponse); } catch (IOException e) { e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e( "mytag", "Error closing stream", e); } } } return null; } @Override protected void onPostExecute(String s) { } } @Override public void onBackPressed() { if(myWebView.canGoBack()) { myWebView.goBack(); } else { super.onBackPressed(); } } @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_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
/* * Copyright 2010 Focus Technology, Co., Ltd. All rights reserved. */ package cn.auto.core.utils; import com.lowagie.text.DocumentException; import com.lowagie.text.pdf.BaseFont; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.xhtmlrenderer.pdf.ITextFontResolver; import org.xhtmlrenderer.pdf.ITextRenderer; import java.io.*; import java.util.Date; /** * PdfUtils.java */ public class PdfUtils { private static Log log = LogFactory.getLog(PdfUtils.class); private static Object lock = new Object(); public String createPdf(String inputFileName) { String ouputFilePath = null; String inputFile = inputFileName; String url; String outputFile = null; try { url = new File(inputFile).toURI().toURL().toString(); ouputFilePath = Thread.currentThread().getContextClassLoader().getResource("pdf/").getPath() + "/pdf/"; File file = new File(ouputFilePath); if (!file.exists()) { file.mkdir(); } outputFile = ouputFilePath + DateFormatUtils.format(new Date(), DateFormatUtils.ISO_DATE_NOSEP_FORMAT.getPattern()) + ".pdf"; OutputStream os = new FileOutputStream(outputFile); ITextRenderer renderer = new ITextRenderer(); renderer.setDocument(url); // 解决中文支持问题 ITextFontResolver fontResolver = renderer.getFontResolver(); fontResolver.addFont(Thread.currentThread().getContextClassLoader().getResource("pdf/fonts/").getPath() + "/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); // 解决图片的相对路径问题 renderer.getSharedContext().setBaseURL( "file:" + Thread.currentThread().getContextClassLoader().getResource("pdf/img/").getPath() + "/"); renderer.layout(); renderer.createPDF(os); os.close(); } catch (Exception e) { log.error(e.getMessage()); log.error(e.getStackTrace()); e.printStackTrace(); } return outputFile; } public String createPdfWithContent(String content) { String ouputFilePath = null; String outputFile = null; try { ouputFilePath = Thread.currentThread().getContextClassLoader().getResource("pdf/").getPath() + "/pdf/"; File file = new File(ouputFilePath); if (!file.exists()) { file.mkdir(); } outputFile = ouputFilePath + DateFormatUtils.format(new Date(), DateFormatUtils.ISO_DATE_NOSEP_FORMAT.getPattern()) + ".pdf"; // 增加字体样式,处理中文问题 content = htmlAddStyle(content); OutputStream os = new FileOutputStream(outputFile); ITextRenderer renderer = null; synchronized (lock) { renderer = new ITextRenderer(); } renderer.setDocumentFromString(content); // 解决中文支持问题 ITextFontResolver fontResolver = renderer.getFontResolver(); fontResolver.addFont(Thread.currentThread().getContextClassLoader().getResource("pdf/fonts/").getPath() + "/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); // 解决上传的html文件没有图片不显示中文问题 RDIS-5262 wuqinglong if (null != content && content.indexOf("<img") > -1) { // 解决图片的相对路径问题 renderer.getSharedContext().setBaseURL( "file:" + Thread.currentThread().getContextClassLoader().getResource("pdf/img/").getPath() + "/"); } renderer.layout(); renderer.createPDF(os); os.close(); } catch (Exception e) { log.error(e.getMessage()); log.error(e.getStackTrace()); e.printStackTrace(); } return outputFile; } public byte[] createPdfBytesWithContent(String content) { byte[] pdfContent = null; // try { // 增加字体样式,处理中文问题 content = htmlAddStyle(content); ByteArrayOutputStream os = new ByteArrayOutputStream(); ITextRenderer renderer = null; synchronized (lock) { renderer = new ITextRenderer(); } renderer.setDocumentFromString(content); // 解决中文支持问题 ITextFontResolver fontResolver = renderer.getFontResolver(); try { fontResolver.addFont(Thread.currentThread().getContextClassLoader().getResource("pdf/fonts").getPath() + "/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); // 解决上传的html文件没有图片不显示中文问题 RDIS-5262 wuqinglong if (null != content && content.indexOf("<img") > -1) { // 解决图片的相对路径问题 renderer.getSharedContext().setBaseURL( "file:" + Thread.currentThread().getContextClassLoader().getResource("pdf/img/").getPath() + "/"); } renderer.layout(); renderer.createPDF(os); pdfContent = os.toByteArray(); } catch (DocumentException de) { log.error("DocumentException:" + de.getMessage()); } catch (IOException ioe) { log.error("IOException" + ioe.getMessage()); } finally { try { os.close(); } catch (IOException ioe) { // ignore } } // } // catch (Exception e) { // log.error(e.getMessage()); // log.error(e.getStackTrace()); // e.printStackTrace(); // } return pdfContent; } public static String htmlAddStyle(String htmlStr) { if (htmlStr.indexOf("<head") > -1) { int startHtml = htmlStr.indexOf("</head"); String regex = "font-family[ ]*:[ ]* ['\"][^'\"]*['\"]"; String style = "font-family: 'SimSun'"; String styleStr = "<style type=\"text/css\">body {font-family: 'SimSun';}</style>"; htmlStr = htmlStr.substring(0, startHtml) + styleStr + htmlStr.substring(startHtml); htmlStr = htmlStr.replaceAll(regex, style); } else { int startHtml = htmlStr.indexOf("<html"); int endHtml = htmlStr.indexOf(">", startHtml + 5); String regex = "font-family[ ]*:[ ]* ['\"][^'\"]*['\"]"; String style = "font-family: 'SimSun'"; String styleStr = "<head><style type=\"text/css\">body {font-family: 'SimSun';}</style></head>"; htmlStr = htmlStr.substring(0, endHtml + 1) + styleStr + htmlStr.substring(endHtml + 1); htmlStr = htmlStr.replaceAll(regex, style); } return htmlStr; } // public static void main(String[] args){ // String s="<html xmlns=\"http://www.w3.org/1999/xhtml\">"+ // "<head><style type=\"text/css\">body {font-family: '宋体' }</style></head>"+ // "<body>的撒+86 10 64105728 <p>的萨芬的撒。</p><hr /><p>的萨芬的撒发送。</p><hr /><p>的萨芬的撒。</p>"+ // "<span><br/>的萨芬达到发Domestic Customer Service Hotlinedsaf 萨芬的撒800-820-5918<br/>的萨芬的萨芬的撒Issue Date: 2010-09-25<br/>"+ // "<a id=\"contactLnk\" href=\"http://www.xyz.cn&id=1\">的萨芬的萨芬的撒</a><br/><img src=\"\" /></span></body>"+ // "</html>"; // System.out.println(htmlAddStyle(s)); // String st="body {"+ // "font-family: '宋体'" + // "font-size:12px;"+ // "}"; // String reg="font-family[ ]*:[ ]* ['\"][^'\"]*['\"]"; // st=st.replaceAll(reg, "font-family: 'SimSun'"); // System.out.println(st); // } }
package com.lesports.albatross.json; import com.google.gson.FieldNamingStrategy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.annotations.SerializedName; import java.lang.reflect.Field; import java.lang.reflect.Type; /** * Created by andye * Thor Project * Updated by jiangjianxiong on 16/7/5. */ public class GsonHelper { private static final String DefaultDateFormatPattern = "yyyyMMddHHmmss"; private static Gson instance; private static Gson getInstance() { if (instance == null) { synchronized (Gson.class) { if (instance == null) { return instance = new GsonBuilder() .setFieldNamingStrategy(new FieldNamingStrategy() { @Override public String translateName(Field field) { JsonAttribute annotation = field.getAnnotation(JsonAttribute.class); if (annotation == null) { SerializedName serializedName = field.getAnnotation(SerializedName.class); if (serializedName == null) { return field.getName(); } else { return serializedName.value(); } } String jsonAttributeName = annotation.value(); return jsonAttributeName; } }) .setDateFormat(DefaultDateFormatPattern) // .registerTypeAdapter(Boolean.class, new NumericBooleanTypeAdapter()) // .registerTypeAdapter(MatchDetailEntity.MatchDetailStatus.class, new MatchDetailStatusAdapter()) .enableComplexMapKeySerialization() .create(); } } } return instance; } public static <T> Object fromJson(String json, Class<T> classOfT) { try { return getInstance().fromJson(json, (Type) classOfT); } catch (Exception e) { return null; } } public static <T> T fromJson(String json, Type typeOfT) { try { return getInstance().fromJson(json, typeOfT); } catch (Exception e) { return null; } } public static String toJson(Object object) { return getInstance().toJson(object); } }
package servlet; import dao.StudentDao; import model.Student; import util.Dbutil; 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 java.io.IOException; import java.sql.Connection; import java.sql.SQLException; @WebServlet("/student") public class StudentServlet extends HttpServlet { private Dbutil dbutil = new Dbutil(); private StudentDao studentDao = new StudentDao(); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); HttpSession session = request.getSession(); String studentId = request.getParameter("studentId"); String name = request.getParameter("name"); String password = request.getParameter("password"); String dormBuild = request.getParameter("dormBuild"); String dorm = request.getParameter("dorm"); String opType = request.getParameter("opType"); Connection con; try { con = dbutil.getCon(); Student student = null; if ("insert".equals(opType)) { student = new Student(studentId,name,password,dormBuild,dorm); studentDao.insert(con,student); session.setAttribute("studentMsg","添加成功!"); } else if ("modify".equals(opType)) { studentDao.modify(con,studentId,dormBuild,dorm); session.setAttribute("studentMsg","修改成功!"); }else{ studentDao.delete(con,studentId); session.setAttribute("studentMsg","删除成功!"); } request.getRequestDispatcher("studentMsg.jsp").forward(request,response); session.removeAttribute("studentMsg"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
import java.lang.reflect.Array; import java.util.ArrayList; public class Factory { private World world; private FieldOfView fov; public Factory(World world, FieldOfView fov){ this.world = world; this.fov = fov; } public Creature newBat(){ Creature bat = new Creature(world, 'b', AsciiPanel.yellow, 10, 2, 10, 10, "Cave bat", 50, 0); world.addAtEmptyLocation(bat); new BatAi(bat); return bat; } public Creature newGiantBat(){ Creature bat = new Creature(world, 'B', AsciiPanel.red, 10, 2, 30, 10, "Giant cave bat", 20, -30); world.addAtEmptyLocation(bat); new GiantBatAi(bat); return bat; } public Creature newPlayer(FieldOfView fov){ Creature player = new Creature(world, '@', AsciiPanel.brightWhite, 5, 0, 100, 10, "Player", 30, -20); world.addAtEmptyLocation(player); new PlayerAi(player, fov); return player; } public Creature newFungus(){ Creature fungus = new Creature(world, 'P', AsciiPanel.green, 10, 0, 10, 0, "Fungus plant", -100, -100); world.addAtEmptyLocation(fungus); new FungusAi(fungus); return fungus; } public Item newRock(){ Item rock = new Item(',', AsciiPanel.yellow, "rock", false, true, 10, 0, 20, 0, 100); world.addAtEmptyLocation(rock); return rock; } public Item newHat(){ Item rock = new Item('~', AsciiPanel.green, "hat", true, false, 0, 5, 0, 30, 100); world.addAtEmptyLocation(rock); return rock; } public Item newSpear(){ Item rock = new Item('-', AsciiPanel.cyan, "spear", false, true, 20, 0, 40, 0, 100); world.addAtEmptyLocation(rock); return rock; } public Item newCorpse(Creature creature){ Item corpse = new Item('%', creature.color(), creature.name() + " corpse", false, false, 0, 0, 0, 0, 100); corpse.setXY(creature.x, creature.y); world.items().add(corpse); return corpse; } }
package com.ros.employees.repositories; import org.springframework.data.repository.CrudRepository; import com.ros.employees.entities.Employee; public interface EmployeeJPADAO extends CrudRepository<Employee, Integer>{ }
package cn.vector.repository; import cn.vector.domain.Employee; import org.springframework.data.jpa.repository.JpaRepository; /** * @Author : Huang Vector ( hgw ) * @Date : 2018-6-4 15:29 */ public interface EmployeeJpaRepository extends JpaRepository<Employee, Integer>{ }
package com.xi.dateDemo; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; /** * Created by Administrator on 2016/3/15. */ public class GetLastDate { public static void main(String[] args) { Calendar c=Calendar.getInstance(); c.add(Calendar.DATE,-1); DateFormat df=new SimpleDateFormat("yyyy-MM-dd"); System.out.println(df.format(c.getTime())); } }
package jdbcprograms; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Scanner; public class JdbcSearch { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("enter id"); int id=sc.nextInt(); try { try { Class.forName("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/practice","root","root"); PreparedStatement ps=con.prepareStatement("select *from emp3 where id=?"); ps.setInt(1,id); ResultSet rs=ps.executeQuery(); Emp e=new Emp(); while(rs.next()) { e.setName(rs.getString("name")); e.setLocation(rs.getString("location")); e.setSalary(rs.getDouble("salary")); } System.out.println(e); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } } catch (SQLException e) { e.printStackTrace(); } } }
package com.exam.logic.actions.friends; import com.exam.logic.Action; import com.exam.logic.services.PhotoService; import com.exam.logic.services.UserService; import com.exam.models.Photo; import com.exam.models.User; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import static com.exam.logic.Constants.*; import static com.exam.servlets.ErrorHandler.ErrorCode.USER_NOT_FOUND; import static com.exam.util.NameNormalizer.normalize; public class SearchFriendsAction implements Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) { int offset = Optional.ofNullable(request.getParameter(OFFSET)) .map(Integer::parseInt) .orElse(0); int limit = Optional.ofNullable(request.getParameter(LIMIT)) .filter(s -> s.length() > 0) .map(Integer::parseInt) .orElse(DEFAULT_LIMIT); UserService userService = (UserService) request.getServletContext().getAttribute(USER_SERVICE); String[] names = Optional.ofNullable(request.getParameter("names")) // .map(NameNormalizer::multiNormalize) .map(n -> n.split(" ")) .orElse(new String[]{}); //names.map() List<User> userList = new ArrayList<>(); switch (names.length) { case 1: userList = userService.getByName(normalize(names[0]), offset, limit); request.setAttribute("userList", userList); break; case 2: userList = userService.getByNames(normalize(names[0]), normalize(names[1]), offset, limit); request.setAttribute("userList", userList); break; } PhotoService photoService = (PhotoService) request.getServletContext().getAttribute(PHOTO_SERVICE); Map<Long, String> minAvatars = userList.stream() .map(User::getId) .map(photoService::getUserAva) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toMap( Photo::getSender, Photo::getLinkOfMinPhoto)); request.setAttribute(MIN_AVATARS,minAvatars); if (names.length > 0 && userList.isEmpty()) { request.setAttribute(ERROR_MSG, USER_NOT_FOUND.getPropertyName()); } return "/WEB-INF/jsp/friends/search.jsp"; } }
package com.example.kyle.myapplication.Screens.CreateEdit; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.GridView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.example.kyle.myapplication.CustomControls.DataListGridAdapter; import com.example.kyle.myapplication.Database.Abstract.Abstract_Table; import com.example.kyle.myapplication.Database.IncidentLink.Tbl_IncidentLink; import com.example.kyle.myapplication.Database.IncidentLink.Tbl_IncidentLink_Manager; import com.example.kyle.myapplication.Database.SubmittedForms.Tbl_SubmittedForms; import com.example.kyle.myapplication.Database.Templates.Tbl_Templates; import com.example.kyle.myapplication.Database.Templates.Tbl_Templates_Manager; import com.example.kyle.myapplication.Helpers.LoggedInUser; import com.example.kyle.myapplication.R; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Created by Kyle on 4/5/2016. */ public class CreateEditSubmittedForms extends AppCompatActivity { private GridView gridView; private Button btnAdd, btnClear; private TextView lblSubmitForms; private EditText txtDescription, txtFileName; private Spinner cboTemplateDescription; private List<Abstract_Table> submittedForms; private Tbl_SubmittedForms toUpdate = null; public static long IncidentID; private int selectedGridPosition; private int selectedListPosition; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.content_createedit_submittedforms); gridView = (GridView) findViewById(R.id.gridView); btnAdd = (Button) findViewById(R.id.btnAdd); btnClear = (Button) findViewById(R.id.btnClear); lblSubmitForms = (TextView) findViewById(R.id.lblSubmitForms); txtDescription = (EditText) findViewById(R.id.txtDescription); txtFileName = (EditText) findViewById(R.id.txtFileName); cboTemplateDescription = (Spinner) findViewById(R.id.cboTemplateDescription); setSpinnerData(); submittedForms = new ArrayList<Abstract_Table>(CreateEditIncident.submittedForms); btnAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { selectFile(); } }); btnClear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { clear(); } }); showGrid(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { String path = data.getData().getPath(); String filename = path.substring(path.lastIndexOf("/") + 1).replace("primary:", ""); String saveFileLocation = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + filename;//uri.getLastPathSegment(); add(saveFileLocation); } } private void setSpinnerData() { Tbl_IncidentLink searchCriteria = new Tbl_IncidentLink(); searchCriteria.personnelID = LoggedInUser.User.personnelID; searchCriteria.incidentID = IncidentID; Tbl_IncidentLink incidentLink = Tbl_IncidentLink_Manager.current.Select(searchCriteria).get(0); List<Tbl_Templates> allTemplates = Tbl_Templates_Manager.current.Select(); List<Tbl_Templates> templateList = new ArrayList<Tbl_Templates>(); for (Tbl_Templates template : allTemplates) { if (template.roleID == incidentLink.roleID) { templateList.add(template); } } Collections.sort(templateList, new Comparator<Tbl_Templates>() { @Override public int compare(Tbl_Templates a, Tbl_Templates b) { return a.toString().compareToIgnoreCase(b.toString()); } }); templateList.add(0, new Tbl_Templates()); cboTemplateDescription.setAdapter(new ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, templateList)); } private void selectFile() { Intent chooseFile; Intent intent; chooseFile = new Intent(Intent.ACTION_GET_CONTENT); chooseFile.setType("*/*"); intent = Intent.createChooser(chooseFile, "Choose a file"); startActivityForResult(intent, 1); } private void add(String saveFileLocation) { Tbl_Templates template = (Tbl_Templates) cboTemplateDescription.getSelectedItem(); String description = txtDescription.getText().toString(); String fileName = txtFileName.getText().toString(); Calendar calendar = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss"); String timeSubmitted = sdf.format(calendar.getTime()); //note we are passing an incident id of 1 but this will get overwritten with whatever the current id is when we create the incident record Tbl_SubmittedForms toAdd = new Tbl_SubmittedForms(1, LoggedInUser.User, template, saveFileLocation, fileName, description, timeSubmitted); String anyErrors = toAdd.isValidRecord(); if (anyErrors.isEmpty()) { if (toUpdate != null) { toAdd.incidentID = toUpdate.incidentID; toAdd.submittedFormID = toUpdate.submittedFormID; toAdd.sqlMode = Abstract_Table.SQLMode.UPDATE; CreateEditIncident.submittedForms.set(selectedListPosition, toAdd); submittedForms.set(selectedGridPosition, toAdd); toUpdate = null; btnAdd.setText("Add"); btnClear.setText("Clear"); } else { toAdd.sqlMode = Abstract_Table.SQLMode.INSERT; CreateEditIncident.submittedForms.add(toAdd); submittedForms.add(toAdd); } gridView.invalidateViews(); showHideNoDataLabel(); clear(); } else { Toast.makeText(this, anyErrors, Toast.LENGTH_LONG).show(); } } private void clear() { if (toUpdate != null) { for (int i = 0; i < cboTemplateDescription.getCount(); i++) { String value = cboTemplateDescription.getItemAtPosition(i).toString(); if (value.equals(toUpdate.template.toString())) { cboTemplateDescription.setSelection(i); break; } } cboTemplateDescription.setEnabled(false); txtDescription.setText(toUpdate.description); txtFileName.setText(toUpdate.fileName); } else { cboTemplateDescription.setEnabled(true); cboTemplateDescription.setSelection(0); txtDescription.setText(""); txtFileName.setText(""); } } private void showGrid() { gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id) { if (toUpdate == null) {//don't allow the user to remove/edit a different row until they have finished updating selectedGridPosition = position; AlertDialog.Builder builder = new AlertDialog.Builder(CreateEditSubmittedForms.this); builder.setMessage("Choose an option below."); builder.setPositiveButton("Remove", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Tbl_SubmittedForms record = (Tbl_SubmittedForms) submittedForms.get(selectedGridPosition); record = CreateEditIncident.submittedForms.get(CreateEditIncident.submittedForms.indexOf(record)); if (record.submittedFormID == -1) { CreateEditIncident.submittedForms.remove(record); } else { record.sqlMode = Abstract_Table.SQLMode.DELETE; } submittedForms.remove(selectedGridPosition); gridView.invalidateViews(); showHideNoDataLabel(); } }); builder.setNegativeButton("Edit", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Tbl_SubmittedForms record = (Tbl_SubmittedForms) submittedForms.get(selectedGridPosition); selectedListPosition = CreateEditIncident.submittedForms.indexOf(record); toUpdate = CreateEditIncident.submittedForms.get(selectedListPosition); btnAdd.setText("Update"); btnClear.setText("Revert Changes"); clear(); } }); builder.show(); } } }); gridView.setAdapter(new DataListGridAdapter(CreateEditSubmittedForms.this, submittedForms, 15)); showHideNoDataLabel(); } private void showHideNoDataLabel() { if (submittedForms.size() == 0) { lblSubmitForms.setVisibility(View.VISIBLE); gridView.setVisibility(View.INVISIBLE); } else { lblSubmitForms.setVisibility(View.INVISIBLE); gridView.setVisibility(View.VISIBLE); } } }
package com.zs.common; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.content.res.AssetManager; import android.media.AudioAttributes; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Build; import com.huaiye.sdk.logger.Logger; import com.huaiye.sdk.media.player.sdk.params.base.VideoParams; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import com.zs.MCApp; import com.zs.dao.msgs.VssMessageBean; import com.zs.ui.chat.holder.ChatViewHolder; /** * 要注意AppAudioManager,start开始之后再使用AppAudioManager会造成状态混乱 */ public class AlarmMediaPlayerBackup { public static final int CALL_VOICE = 1; public static final int PTT_VOICE = 2; public static final int ALARM_VOICE = 3; public static final int ERROR_VOICE = 4; public static final int SOS_VOICE = 5; public static final int PERSON_VOICE = 6; public static final int ZHILLING_VOICE = 7; private MediaPlayer mMediaPlayer; private MediaPlayer mBroadcastPlayer; private Context mContext; private String TAG = AlarmMediaPlayerBackup.class.getSimpleName(); private static AlarmMediaPlayerBackup mInstance; private boolean isPlaying; private BroadcastListener broadcastListener; AudioManager mAudioManager ; private int previousMode; private boolean previousSpeakon; public static AlarmMediaPlayerBackup get() { if (mInstance == null) { synchronized (AlarmMediaPlayerBackup.class) { if (mInstance == null) { mInstance = new AlarmMediaPlayerBackup(MCApp.getInstance()); } } } return mInstance; } private AlarmMediaPlayerBackup(Context context) { this.mContext = context; mAudioManager = (AudioManager) MCApp.getInstance().getSystemService(Context.AUDIO_SERVICE); } public void play(int type) { Logger.log(TAG + " Play start " + type); if (mMediaPlayer == null) { Logger.log(TAG + " Play create " + type); mMediaPlayer = createPlayer(); } //多次播放只播放第一次,其他的不进行操作 if (mMediaPlayer.isPlaying() || isPlaying) { Logger.log(TAG + " Play isAlarmPlaying" + type); return; } Logger.log(TAG + " Play will play " + type); requestFocus(); try { setPlayerSource(mMediaPlayer, type); mMediaPlayer.prepare(); //每次都从头开始,这样提示音就是一致的 mMediaPlayer.seekTo(0); isPlaying = true; mMediaPlayer.start(); mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { Logger.log(TAG + " Play onCompletion"); stop(); mAudioManager.abandonAudioFocus(new AudioManager.OnAudioFocusChangeListener() { @Override public void onAudioFocusChange(int focusChange) { Logger.log(TAG + " mAudioManager abandonAudioFocus " + focusChange); } }); } }); } catch (IOException e) { Logger.log(TAG + " Play error " + e); e.printStackTrace(); } } /** * 播放暂停,每次都释放重新创建 */ public void stop() { isPlaying = false; if (mMediaPlayer != null) { releaseFocus(); Logger.log(TAG + " Play stop not null " + mMediaPlayer.isPlaying()); mMediaPlayer.pause(); mMediaPlayer.stop(); mMediaPlayer.reset(); mMediaPlayer.release(); mMediaPlayer = null; } } /** * 必须调用destroy来释放MediaPlayer */ public boolean isPlaying() { return mMediaPlayer != null && mMediaPlayer.isPlaying(); } private MediaPlayer createPlayer() { MediaPlayer player = new MediaPlayer(); //接通时前,音频播放走媒体音量 if (Build.VERSION.SDK_INT >= 21) { AudioAttributes.Builder builder = new AudioAttributes.Builder(); builder.setUsage(AudioAttributes.USAGE_MEDIA) .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC); player.setAudioAttributes(builder.build()); } else { player.setAudioStreamType(AudioManager.STREAM_MUSIC); } return player; } private void setPlayerSource(MediaPlayer player, int type) { AssetManager am = mContext.getAssets();//获得该应用的AssetManager AssetFileDescriptor afd = null; try { switch (type) { case CALL_VOICE: afd = am.openFd("call.wav"); player.setLooping(true); //循环播放 break; case SOS_VOICE: afd = am.openFd("sos.wav"); player.setLooping(true); break; case PERSON_VOICE: afd = am.openFd("person.wav"); player.setLooping(false); break; case ZHILLING_VOICE: afd = am.openFd("zhiling.wav"); player.setLooping(false); break; case ERROR_VOICE: afd = am.openFd("error.wav"); player.setLooping(false); break; case PTT_VOICE: afd = am.openFd("ptt.wav"); player.setLooping(false); break; case ALARM_VOICE: afd = am.openFd("alarm.wav"); player.setLooping(false); break; } player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); } catch (IOException e) { e.printStackTrace(); } } private VssMessageBean bean; private ChatViewHolder viewHolder; private VideoParams videoParams; private HashMap<String,Boolean> playMap = new HashMap<>(); public HashMap<String,Boolean> getPlayMap(){ return playMap; } public ChatViewHolder getViewHolder() { return viewHolder; } public void setLastState(VssMessageBean bean, ChatViewHolder viewHolder) { this.bean = bean; this.viewHolder = viewHolder; } public void setVideoParam(VideoParams videoParams){ this.videoParams=videoParams; } public VideoParams getVideoParam(){ return videoParams; } public VssMessageBean getLastVssMessageBean() { return bean; } public void setPlayBroadcastListener(BroadcastListener broadcastListener) { this.broadcastListener = broadcastListener; } public void playBroadcast(String soundFilePath) { Logger.log(TAG + " mBroadcastPlayer start " + soundFilePath); if (mBroadcastPlayer == null) { Logger.log(TAG + " mBroadcastPlayer create " + soundFilePath); mBroadcastPlayer = createPlayer(); } Logger.log(TAG + " mBroadcastPlayer will play " + soundFilePath); try { File file = new File(AppUtils.audiovideoPath + "/" + AppUtils.subPath(soundFilePath)); FileInputStream fis = new FileInputStream(file); mBroadcastPlayer.setDataSource(fis.getFD()); mBroadcastPlayer.prepare(); //每次都从头开始,这样提示音就是一致的 mBroadcastPlayer.seekTo(0); mBroadcastPlayer.start(); mBroadcastPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { Logger.log(TAG + " mBroadcastPlayer onCompletion"); if (broadcastListener != null) broadcastListener.completeListener(); } }); } catch (IOException e) { Logger.log(TAG + " mBroadcastPlayer error " + e); if (broadcastListener != null) broadcastListener.error(); e.printStackTrace(); } } private void requestFocus(){ mAudioManager.requestAudioFocus(new AudioManager.OnAudioFocusChangeListener() { @Override public void onAudioFocusChange(int focusChange) { Logger.log(TAG + " mAudioManager requestAudioFocus " + focusChange); } },AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN); previousMode = mAudioManager.getMode(); previousSpeakon = mAudioManager.isSpeakerphoneOn(); mAudioManager.setMode(AudioManager.MODE_RINGTONE); mAudioManager.setSpeakerphoneOn(true); } private void releaseFocus(){ mAudioManager.setMode(previousMode); mAudioManager.setSpeakerphoneOn(previousSpeakon); } public void stopBroadcast() { if (mBroadcastPlayer != null) { Logger.log(TAG + " mBroadcastPlayer stop not null " + mBroadcastPlayer.isPlaying()); mBroadcastPlayer.pause(); mBroadcastPlayer.stop(); mBroadcastPlayer.reset(); mBroadcastPlayer.release(); mBroadcastPlayer = null; } } public boolean isPlayingBroadcast() { if (mBroadcastPlayer != null) { return mBroadcastPlayer.isPlaying(); } else { return false; } } public interface BroadcastListener { void completeListener(); void error(); } }
//meaningless problem //imposible to achieve without extra space //only thing learn from this is: how to reverse a Integer public class Solution { public boolean isPalindrome(int x) { int sum = 0,target = x; while (x > 0) { int temp = x % 10; x /= 10; sum = sum * 10 + temp; } return sum == target; } }
package quiz.runner.ainchwar; import java.util.List; import quiz.model.QuizDataProvider; import quiz.model.Team; public class QuizRunner { private QuizRunner() { } public static void main(String[] args) { List<Team> teams = QuizDataProvider.getTeams(); System.out.println(teams); } }
/* * Created on 2005-6-7 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.aof.webapp.action.prm.payment; import java.io.FileInputStream; import java.sql.SQLException; import java.text.DateFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.hibernate.HibernateException; import net.sf.hibernate.Query; import net.sf.hibernate.Session; import net.sf.hibernate.Transaction; import org.apache.log4j.Logger; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.Region; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.util.MessageResources; import com.aof.component.crm.vendor.VendorProfile; import com.aof.component.domain.party.UserLogin; import com.aof.component.prm.Bill.TransacationDetail; import com.aof.component.prm.Bill.TransactionServices; import com.aof.component.prm.payment.PaymentInstructionService; import com.aof.component.prm.payment.PaymentTransactionDetail; import com.aof.component.prm.payment.ProjPaymentTransaction; import com.aof.component.prm.payment.ProjectPayment; import com.aof.component.prm.payment.ProjectPaymentMaster; import com.aof.component.prm.project.CurrencyType; import com.aof.component.prm.project.ProjectMaster; import com.aof.core.persistence.hibernate.Hibernate2Session; import com.aof.util.Constants; import com.aof.util.UtilDateTime; import com.aof.webapp.action.ActionErrorLog; import com.aof.webapp.action.prm.report.ReportBaseAction; import com.aof.webapp.form.prm.payment.EditPaymentDownpaymentInstructionForm; import com.aof.webapp.form.prm.payment.EditPaymentInstructionForm; /** * @author gus * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class EditPaymentDownpaymentInstructionAction extends ReportBaseAction { private Logger log = Logger.getLogger(EditPaymentDownpaymentInstructionAction.class); public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { Locale locale = getLocale(request); MessageResources messages = getResources(); Transaction transaction = null; try { EditPaymentDownpaymentInstructionForm ediForm = (EditPaymentDownpaymentInstructionForm)form; PaymentInstructionService payInstructionService = new PaymentInstructionService(); TransactionServices transactionServices = new TransactionServices(); if (ediForm.getFormAction().equals("view") || ediForm.getFormAction().equals("dialogView")) { ProjectPayment pp = payInstructionService.viewPaymentInstruction(ediForm.getPayId()); request.setAttribute("ProjectPayment", pp); if (pp != null && pp.getProject() != null) { TransacationDetail td = transactionServices.getInsertedRecord("PaymentTransactionDetail", pp.getId().longValue(), Constants.TRANSACATION_CATEGORY_CREDIT_DOWN_PAYMENT); request.setAttribute("CreidtDownpayment", td); } request.setAttribute("Currency", payInstructionService.getAllCurrency()); if (ediForm.getFormAction().equals("dialogView")) { return mapping.findForward("showDialog"); } } if (ediForm.getFormAction().equals("new")) { Session session = Hibernate2Session.currentSession(); transaction = session.beginTransaction(); ProjectPayment pp = convertFormToModel(payInstructionService, ediForm); //Currency CurrencyType ct = (CurrencyType)session.load(CurrencyType.class,"RMB"); //Create User UserLogin ul = (UserLogin)request.getSession().getAttribute(Constants.USERLOGIN_KEY); pp.setStatus(Constants.PAYMENT_STATUS_DRAFT); pp.setCreateUser(ul); pp.setCreateDate(UtilDateTime.nowTimestamp()); pp.setSettledAmount(new Double(0)); Long payId = (Long)session.save(pp); request.setAttribute("ProjectPayment", pp); TransactionServices tService = new TransactionServices(); PaymentTransactionDetail tr = (PaymentTransactionDetail)tService.getInsertedRecord( "PaymentTransactionDetail", payId.longValue(), Constants.TRANSACATION_CATEGORY_DOWN_PAYMENT); if (tr == null) { tr = new PaymentTransactionDetail(); tr.setTransactionCreateDate(UtilDateTime.nowTimestamp()); tr.setTransactionCreateUser(ul); } tr.setCurrency(ct); tr.setExchangeRate(new Double(1)); tr.setProject(pp.getProject()); tr.setTransactionCategory(Constants.TRANSACATION_CATEGORY_DOWN_PAYMENT); tr.setTransactionDate(UtilDateTime.nowTimestamp()); tr.setTransactionParty(pp.getPayAddress()); tr.setTransactionRecId(payId); tr.setTransactionUser(pp.getProject().getProjectManager()); tr.setDesc1(pp.getPaymentCode()); tr.setDesc2(pp.getNote()); tr.setAmount(ediForm.getDownAmount()); tr.setTransactionMaster(pp); pp.addDetail(tr); //save down payment session.saveOrUpdate(tr); //request.setAttribute("Downpayment", tr); tr = (PaymentTransactionDetail)tService.getInsertedRecord( "PaymentTransactionDetail", payId.longValue(), Constants.TRANSACATION_CATEGORY_CREDIT_DOWN_PAYMENT); if (ediForm.getCreditAmount().doubleValue() != 0L) { if (tr == null) { tr = new PaymentTransactionDetail(); tr.setTransactionCreateDate(UtilDateTime.nowTimestamp()); tr.setTransactionCreateUser(ul); } tr.setCurrency(ct); tr.setExchangeRate(new Double(1)); tr.setProject(pp.getProject()); tr.setTransactionCategory(Constants.TRANSACATION_CATEGORY_CREDIT_DOWN_PAYMENT); tr.setTransactionDate(UtilDateTime.nowTimestamp()); tr.setTransactionParty(pp.getPayAddress()); tr.setTransactionRecId(payId); tr.setTransactionUser(pp.getProject().getProjectManager()); tr.setDesc1(pp.getPaymentCode()); tr.setDesc2(pp.getNote()); tr.setAmount(ediForm.getCreditAmount()); //save credit down payment session.saveOrUpdate(tr); request.setAttribute("CreidtDownpayment", tr); } else { if (tr != null) { //if credit amount is zero, delete it session.delete(tr); } } session.flush(); transaction.commit(); } if (ediForm.getFormAction().equals("update")) { Session session = Hibernate2Session.currentSession(); transaction = session.beginTransaction(); ProjectPayment pp = convertFormToModel(payInstructionService, ediForm); session.update(pp); request.setAttribute("ProjectPayment", pp); Set set = pp.getDetails(); Iterator it = set.iterator(); PaymentTransactionDetail td = (PaymentTransactionDetail)it.next(); td.setAmount(ediForm.getDownAmount()); session.update(td); td = (PaymentTransactionDetail)transactionServices.getInsertedRecord( "PaymentTransactionDetail", pp.getId().longValue(), Constants.TRANSACATION_CATEGORY_CREDIT_DOWN_PAYMENT); if (td != null) { if (ediForm.getCreditAmount().doubleValue() != 0L) { td.setAmount(ediForm.getCreditAmount()); session.update(td); request.setAttribute("CreidtDownpayment", td); } else { //if credit amount is zero, delete it session.delete(td); } } else { if (ediForm.getCreditAmount().doubleValue() != 0L) { td = new PaymentTransactionDetail(); td.setTransactionCreateDate(UtilDateTime.nowTimestamp()); td.setTransactionCreateUser((UserLogin)request.getSession().getAttribute(Constants.USERLOGIN_KEY)); td.setCurrency((CurrencyType)session.load(CurrencyType.class,"RMB")); td.setExchangeRate(new Double(1)); td.setProject(pp.getProject()); td.setTransactionCategory(Constants.TRANSACATION_CATEGORY_CREDIT_DOWN_PAYMENT); td.setTransactionDate(UtilDateTime.nowTimestamp()); td.setTransactionParty(pp.getPayAddress()); td.setTransactionRecId(pp.getId()); td.setTransactionUser(pp.getProject().getProjectManager()); td.setDesc1(pp.getPaymentCode()); td.setDesc2(pp.getNote()); td.setAmount(ediForm.getCreditAmount()); request.setAttribute("CreidtDownpayment", td); } } session.flush(); transaction.commit(); } if (ediForm.getFormAction().equals("delete")) { Session session = Hibernate2Session.currentSession(); transaction = session.beginTransaction(); ProjectPayment pp = payInstructionService.viewPaymentInstruction(ediForm.getPayId()); if (pp != null) { Set set = pp.getDetails(); Iterator it = set.iterator(); TransacationDetail td = (TransacationDetail)it.next(); session.delete(td); td = (PaymentTransactionDetail)transactionServices.getInsertedRecord( "PaymentTransactionDetail", pp.getId().longValue(), Constants.TRANSACATION_CATEGORY_CREDIT_DOWN_PAYMENT); if (td != null) { session.delete(td); } session.delete(pp); session.flush(); } transaction.commit(); return mapping.findForward("list"); } //payment settlement if(ediForm.getFormAction().equals("removeSupplierInvoice")){ Session session = Hibernate2Session.currentSession(); removeSupplierInvoice(session, Long.parseLong(request.getParameter("paymentId"))); doView(session, request, String.valueOf(ediForm.getPayId())); } if(ediForm.getFormAction().equals("post")){ Session session = Hibernate2Session.currentSession(); String postIds[] = request.getParameterValues("chk"); postPaymentSettle(session, String.valueOf(ediForm.getPayId()), postIds); doView(session, request, String.valueOf(ediForm.getPayId())); } } catch (Exception e) { try { if (transaction != null) { transaction.rollback(); } } catch (HibernateException e1) { // TODO Auto-generated catch block log.error(e1.getMessage()); e1.printStackTrace(); } log.error(e.getMessage()); e.printStackTrace(); } finally { try { if (transaction != null) { transaction.commit(); } Hibernate2Session.closeSession(); } catch (HibernateException e1) { log.error(e1.getMessage()); e1.printStackTrace(); } catch (SQLException e1) { log.error(e1.getMessage()); e1.printStackTrace(); } } return mapping.findForward("success"); } private void doView(Session session, HttpServletRequest request, String payId) throws HibernateException { if (payId != null && payId.trim().length() != 0) { //show edit payment instruction page long id = Long.parseLong(payId); String payStatement = "from ProjectPayment as pp where pp.Id = ?"; Query query = session.createQuery(payStatement); query.setLong(0, id); List list = query.list(); if (list != null && list.size() > 0) { ProjectPayment payment = (ProjectPayment)list.get(0); //set payment instruction in request request.setAttribute("ProjectPayment", payment); //set transaction detail list that can be add to payment instruction in request String projectId = payment.getProject().getProjId(); TransactionServices ts = new TransactionServices(); /* if (category.equals(Constants.TRANSACATION_CATEGORY_EXPENSE)) { List tranExpenseList = ts.findPaymentTransactionList(projectId, Constants.TRANSACATION_CATEGORY_EXPENSE); //List tranCostList = ts.findBillingTransactionList(projectId, Constants.TRANSACATION_CATEGORY_OTHER_COST); if (tranExpenseList == null) { tranExpenseList = new ArrayList(); } //if (tranCostList != null) { // tranExpenseList.addAll(tranCostList); //} request.setAttribute("ExpenseTransactionList", tranExpenseList); } */ // for load trasaction, and invoice if (payment.getDetails() != null) { payment.getDetails().size(); } if (payment.getSettleRecords() != null) { payment.getSettleRecords().size(); } } } else { //show new payment instruction display page //it seems we shall do not do anything here!! } } private ProjectPayment convertFormToModel( PaymentInstructionService payInstructionService, EditPaymentDownpaymentInstructionForm ediForm) throws HibernateException { ProjectPayment pp = null; try { Session session = Hibernate2Session.currentSession(); if (ediForm.getPayId() != null && ediForm.getPayId().longValue() > 0L) { pp = payInstructionService.viewPaymentInstruction(ediForm.getPayId()); } else { pp = new ProjectPayment(); pp.setPaymentCode(payInstructionService.generatePaymentCode(ediForm.getProjId())); } pp.setType(Constants.PAYMENT_TYPE_DOWN_PAYMENT); pp.setCalAmount(ediForm.getDownAmount()); if (ediForm.getProjId() != null && ediForm.getProjId().trim().length() != 0) { ProjectMaster pm = (ProjectMaster)session.load(ProjectMaster.class, ediForm.getProjId()); pp.setProject(pm); } if (ediForm.getPayAddr() != null && ediForm.getPayAddr().trim().length() != 0) { VendorProfile vendor = (VendorProfile)session.load(VendorProfile.class, ediForm.getPayAddr()); pp.setPayAddress(vendor); } if (ediForm.getStatus() != null) { pp.setStatus(ediForm.getStatus()); } if (ediForm.getNote() != null) { pp.setNote(ediForm.getNote().trim()); } } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } return pp; } private ProjectPayment convertFormToPayment(Session session, EditPaymentInstructionForm epiForm, ProjectPayment pp) throws HibernateException { String projectId = epiForm.getProjId(); String payAddrId = epiForm.getPayAddr(); ProjectMaster project = null; com.aof.component.crm.vendor.VendorProfile vendor = null; if (projectId != null && projectId.trim().length() != 0) { project = (ProjectMaster)session.load(ProjectMaster.class, projectId); } if (payAddrId != null && payAddrId.trim().length() != 0) { vendor = (com.aof.component.crm.vendor.VendorProfile)session.load(com.aof.component.crm.vendor.VendorProfile.class, payAddrId); } //set payment id //if (epiForm.getBillId() != null && epiForm.getBillId().trim().length() != 0) { //Long id = new Long(epiForm.getBillId()); //pb.setId(id); //} //set payment code if (epiForm.getPayCode() != null && epiForm.getPayCode().trim().length() != 0) { pp.setPaymentCode(epiForm.getPayCode()); } //set payment type pp.setType(epiForm.getPayType()); //set project if (project != null) { pp.setProject(project); } //set payment address if (vendor != null) { pp.setPayAddress(vendor); } //set status if (epiForm.getStatus() != null) { pp.setStatus(epiForm.getStatus()); } //set note if (epiForm.getNote() != null) { pp.setNote(epiForm.getNote().trim()); } return pp; } private Long doNew(Session session, HttpServletRequest request, EditPaymentInstructionForm epiForm) throws HibernateException { ProjectPayment pp = new ProjectPayment(); convertFormToPayment(session, epiForm, pp); //set payment code if (pp.getPaymentCode() == null || pp.getPaymentCode().trim().length() == 0) { //if user not input the payment code, system would generate one for it PaymentInstructionService paymentInstructionService = new PaymentInstructionService(); pp.setPaymentCode(paymentInstructionService.generatePaymentCode(pp.getProject().getProjId())); } //set payment type pp.setType(Constants.PAYMENT_TYPE_NORMAL); //set payment status pp.setStatus(Constants.PAYMENT_STATUS_DRAFT); //set create date pp.setCreateDate(new Date()); //set create user pp.setCreateUser((UserLogin)request.getSession().getAttribute(Constants.USERLOGIN_KEY)); //set calculation amount pp.setCalAmount(new Double(0L)); //set settled amount pp.setSettledAmount(new Double(0L)); Long payId = (Long)session.save(pp); return payId; } private void doDelete(EditPaymentInstructionForm epiForm) throws HibernateException { Long payId = new Long(epiForm.getPayId()); PaymentInstructionService paymentInstructionService = new PaymentInstructionService(); paymentInstructionService.deletePaymentInstruction(payId); } private void doUpdateHead(Session session, EditPaymentInstructionForm epiForm) throws HibernateException { Long payId = new Long(epiForm.getPayId()); ProjectPayment pp = (ProjectPayment)session.load(ProjectPayment.class, payId); convertFormToPayment(session, epiForm, pp); session.update(pp); } private void doAddTransaction(Session session, EditPaymentInstructionForm epiForm) throws HibernateException { String[] transactionId = epiForm.getTransactionId(); Long payId = new Long(epiForm.getPayId()); ProjectPayment pp = (ProjectPayment)session.load(ProjectPayment.class, payId); PaymentInstructionService paymentInstructionService = new PaymentInstructionService(); for (int i0 =0; transactionId != null && i0 < transactionId.length; i0++) { long id = Long.parseLong(transactionId[i0]); paymentInstructionService.addPaymentTransaction(pp, id); } session.update(pp); } private void doRemoveTransaction(Session session, EditPaymentInstructionForm epiForm) throws HibernateException { Long payId = new Long(epiForm.getPayId()); String[] payDetailId = epiForm.getPayDetailId(); ProjectPayment pp = (ProjectPayment)session.load(ProjectPayment.class, payId); PaymentInstructionService paymentInstructionService = new PaymentInstructionService(); for (int i0 =0; payDetailId != null && i0 < payDetailId.length; i0++) { long id = Long.parseLong(payDetailId[i0]); paymentInstructionService.removePaymentTransaction(id); } session.update(pp); //reCalculatepaymentingAmount(session, payId); } private void doClose(Session session, EditPaymentInstructionForm epiForm) throws HibernateException { Long payId = new Long(epiForm.getPayId()); ProjectPayment pp = (ProjectPayment)session.load(ProjectPayment.class, payId); pp.setStatus(Constants.PAYMENT_STATUS_COMPLETED); session.update(pp); } private void removeSupplierInvoice(Session session, long id) throws HibernateException{ Long paymentId = new Long(id); ProjPaymentTransaction ppt = (ProjPaymentTransaction)session.load(ProjPaymentTransaction.class, paymentId); PaymentInstructionService paymentInstructionService = new PaymentInstructionService(); paymentInstructionService.removePaymentSettlement(ppt); } public void postPaymentSettle(Session session, String payId, String postIds[]) throws HibernateException{ Transaction transaction = null; try { transaction = session.beginTransaction(); ProjectPayment pp = (ProjectPayment)session.load(ProjectPayment.class, new Long(Long.parseLong(payId))); if (pp != null && pp.getSettleRecords() != null) { Iterator iterator = pp.getSettleRecords().iterator(); while (iterator.hasNext()) { ProjPaymentTransaction ppt = (ProjPaymentTransaction)iterator.next(); for (int i0 = 0; i0 < postIds.length; i0++) { if (ppt.getId().toString().equalsIgnoreCase(postIds[i0])) { ppt.setPostStatus(Constants.POST_PAYMENT_TRANSACTION_STATUS_POST); ppt.setPostDate(new Date()); session.update(ppt); } } } } session.flush(); } catch (Exception e) { try { transaction.rollback(); } catch (HibernateException e1) { e1.printStackTrace(); } e.printStackTrace(); } finally { try { transaction.commit(); } catch (HibernateException e1) { e1.printStackTrace(); } } } }
package mygame.control; import com.jme3.collision.CollisionResult; import com.jme3.collision.CollisionResults; import template.*; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.export.Savable; import com.jme3.math.Ray; import com.jme3.math.Vector3f; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.renderer.queue.RenderQueue; import com.jme3.renderer.queue.RenderQueue.ShadowMode; import com.jme3.scene.Geometry; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.scene.control.AbstractControl; import com.jme3.scene.control.Control; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static mygame.appstate.RunLevel.world; public class PhysicsControl extends AbstractControl implements Savable, Cloneable { final static float FRICTION = 0.4f; float jumpSpd = 0.1f; float vspd = 0.0f; float hspd = 0.0f; //Determines movement along the Z axis. float gravity = -0.25f; float acceleration = 80f; //80 units/s acceleration. float maxSpd = 10f; //Default max speed is 10. float modelHeight = 2.5f; float walkOffTime = 0.25f; //How long you can jump after becoming airborne. float airTime = 0.0f; //Amount of time in air. Geometry standingOn; public PhysicsControl(float jumpSpd, float gravity, float modelHeight){ this.jumpSpd=jumpSpd; this.gravity=gravity; this.modelHeight=modelHeight; } /** This method is called when the control is added to the spatial, * and when the control is removed from the spatial (setting a null value). * It can be used for both initialization and cleanup. */ @Override public void setSpatial(Spatial spatial) { super.setSpatial(spatial); spatial.setShadowMode(ShadowMode.CastAndReceive); //spatial.setUserData("Level", levelData); } /** Implement your spatial's behaviour here. * From here you can modify the scene graph and the spatial * (transform them, get and set userdata, etc). * This loop controls the spatial while the Control is enabled. */ @Override protected void controlUpdate(float tpf){ if (!isOnGround()) { vspd+=gravity*tpf; airTime+=tpf; } else { vspd=0; airTime=0; if (standingOn!=null && standingOn.getUserData("friction")!=null) { if (hspd<0) { hspd=Math.min(hspd+(float)standingOn.getUserData("friction"),0); } else { hspd=Math.max(hspd-(float)standingOn.getUserData("friction"),0); } } else { if (hspd<0) { hspd=Math.min(hspd+FRICTION,0); } else { hspd=Math.max(hspd-FRICTION,0); } } } spatial.move(0,vspd,hspd*tpf); } @Override public Control cloneForSpatial(Spatial spatial){ final PhysicsControl control = new PhysicsControl(jumpSpd,gravity,modelHeight); /* Optional: use setters to copy userdata into the cloned control */ // control.setIndex(i); // example control.setSpatial(spatial); return control; } @Override protected void controlRender(RenderManager rm, ViewPort vp){ /* Optional: rendering manipulation (for advanced users) */ } @Override public void read(JmeImporter im) throws IOException { super.read(im); // im.getCapsule(this).read(...); } @Override public void write(JmeExporter ex) throws IOException { super.write(ex); // ex.getCapsule(this).write(...); } private Node GetLevel() { return (Node)(spatial.getUserData("Level")); } void jump() { setVerticalSpeed(jumpSpd); } void setVerticalSpeed(float spd) { vspd = spd; } void addVerticalSpeed(float spd) { vspd += spd; } float getVerticalSpeed() { return vspd; } void addHorizontalSpeed(float spd) { hspd += spd; } void setHorizontalSpeed(float spd) { hspd = spd; } void setAcceleration(float value) { acceleration = value; } void setMaxSpd(float value) { maxSpd = value; } float getAcceleration() { return acceleration; } float getMaxSpd() { return maxSpd; } /*** * * @param positive Use false if we are accelerating in the -Z direction. (Left). Use true to say we are accelerating to the right. * @param tpf */ void accelerate(boolean right, float tpf) { if (right) { if (hspd+acceleration*tpf<maxSpd) { hspd += acceleration*tpf; } else { hspd = maxSpd; } } else { if (hspd-acceleration*tpf>-maxSpd) { hspd -= acceleration*tpf; } else { hspd = -maxSpd; } } } float getHorizontalSpeed() { return hspd; } boolean isOnGround() { if (vspd>0) { //System.out.println(vspd); return false; } CollisionResults results = new CollisionResults(); CollisionResults newResults = new CollisionResults(); Ray r = new Ray(spatial.getLocalTranslation().add(0,(modelHeight/2)-vspd,0),Vector3f.UNIT_Y.negate()); //world.updateGeometricState(); world.collideWith(r, results); //Get closest collision that doesn't include myself. List<CollisionResult> collisions = new ArrayList<>(); for (int i=0;i<results.size();i++) { if (results.getCollision(i).getGeometry()!=spatial) { newResults.addCollision(results.getCollision(i)); } } if (newResults.size()>0) { //System.out.println(newResults.getCollision(0)); if (newResults.getClosestCollision().getContactPoint().x!=0 || newResults.getClosestCollision().getContactPoint().y!=0 || newResults.getClosestCollision().getContactPoint().z!=0) { //System.out.println(newResults.getClosestCollision()); if (newResults.getClosestCollision().getDistance()<=(modelHeight/2)+0.1-vspd) { spatial.setLocalTranslation(newResults.getClosestCollision().getContactPoint()); standingOn = newResults.getClosestCollision().getGeometry(); return true; } else { return false; } } else { vspd=jumpSpd; //???Undefined behavior. } } /*if (results.size()>0) { System.out.println("Distance: "+results.getClosestCollision().getDistance()); //if (results.getClosestCollision().getDistance()<=5.0f) { //} }*/ return false; } }
import java.sql.*; import java.util.*; public class Table { /** Global Variables for the class */ private String name; private HashMap<String, Column> columns = new HashMap<>(); private boolean hasForeign = false; private ArrayList<String> refs = new ArrayList<>();; private DatabaseMetaData data; /** * Table constructor, wich creates all the columns in it * @param name The name of the table * @param metadata the data from the database * @throws SQLException */ public Table(String name, DatabaseMetaData data) throws SQLException { this.name = name; this.data = data; /** * generates the columns, the primary and foreing keys */ try { this.generateColumns(); this.generatePrimary(); this.generateForeign(); } catch (Exception e) { e.printStackTrace(); } } /** * Generates the columns of the give table and store them in hashmap * @throws SQLException */ public void generateColumns() throws SQLException { ResultSet columnData = data.getColumns(null, null, name, null); while (columnData.next()) { String columnName = columnData.getString("COLUMN_NAME"); Column column = new Column(columnData); columns.put(columnName, column); } } /** * Generates the Primary key of the table and place it in the Hash Map and set it to the column * @throws SQLException */ public void generatePrimary() throws SQLException { ResultSet primaryKeys = data.getPrimaryKeys(null, null, name); while (primaryKeys.next()) { String primaryKey = primaryKeys.getString("COLUMN_NAME"); if(columns.containsKey(primaryKey)) { columns.get(primaryKey).setPrimary(); } } } /** * Generates the foreign key of each column and set the reference table on the correct column * @throws SQLException */ public void generateForeign() throws SQLException { ResultSet foreignKeys = data.getImportedKeys(null, null, name); while(foreignKeys.next()) { String key = foreignKeys.getString("FKCOLUMN_NAME"); if(columns.containsKey(key)) { String foreignTable = foreignKeys.getString("PKTABLE_NAME"); String foreignKey = foreignKeys.getString("PKCOLUMN_NAME"); columns.get(key).setReference(foreignTable + "(" + foreignKey + ")"); refs.add(foreignTable); hasForeign = true; } } } /** * Method that returns the name of the table */ public String getName() { return name; } /** * Method taht returns the column of the table * @param column name * @return */ public Column getColumn(String column) { return columns.get(column); } /** * Returns if the table has a foreign key * @return */ public boolean hasForeignKey() { return hasForeign; } /** * Check if the column value can not be Null and return the string */ public String nullable(Column c) { if(c.isNullable()==false) { return " NOT NULL"; } else { return ""; } } /** * Create the tables as iterrating over the columns * @return string with the right data to create a table in SQL format */ public String getCreateTable() { String statement = "CREATE TABLE " + name; statement += " (\n"; // next line Collection<Column> columns = this.columns.values(); // add the name of the column the type and check if the value can't be NULL for(Column column : columns) { statement += " " + column.getName() + " " + column.getType() +this.nullable(column) + ",\n"; } // check for column with primary key Column[] array = new Column[columns.size()]; array = columns.toArray(array); statement += " PRIMARY KEY ("; for(int i = 0; i < columns.size(); i++) { Column column = array[i]; if(column.isPrimary()) { statement += column.getName() + ", "; } } statement = statement.substring(0, statement.lastIndexOf(", ")); // removing unwanded , statement += "),\n"; // next line // check for the foreign key and show the connection between the tables for(Column column : columns) { if(column.hasReference()) { statement += " FOREIGN KEY (" + column.getName() + ") REFERENCES " + column.getReference() + ",\n"; } } statement = statement.substring(0, statement.lastIndexOf(",")); // remove unwanted , statement += "\n);"; // next line return statement; // return the final string } /** * Method that returns array list of strings, that represents insert statements of the table * iterrating over the columns of each table to get the values, check for different types */ public ArrayList<String> getInsertSatements(Statement statement) throws SQLException { ResultSet data = statement.executeQuery("SELECT * FROM " + name); // executing the query to get the data from all columns Collection<Column> cols = columns.values(); // create a collection to get only the values from the hasmap ArrayList<String> statements = new ArrayList<>(); // list of statements while (data.next()) // iterrates over each column data { String insert = "INSERT INTO " + name + " VALUES ("; //iterrates over the columns for (Column column : cols) { if (column.getType().toLowerCase().contains("varchar")) //check for varchar { String value = data.getString(column.getName()); insert += ("'" + value + "', "); } else if (column.getType().toLowerCase().contains("int")) // check for integer { int value = data.getInt(column.getName()); insert += (value) + ", "; } } insert = insert.substring(0, insert.lastIndexOf(",")); //remove unwanted , insert += ");"; statements.add(insert); // add each statement to the array list } return statements; // return the final array list } /** * Get the reference tables that each column has * @return array list of strings */ public ArrayList<String> getrefs() { return refs; } @Override public String toString() { // toString method for the foreach loops String s = ""; Collection<Column> columns = this.columns.values(); for(Column column : columns) { s += column.toString() + "\n"; } return s; } }
package com.nisira.core.dao; import com.nisira.core.entity.*; import java.util.List; import android.database.sqlite.SQLiteDatabase; import com.nisira.core.database.DataBaseClass; import android.content.ContentValues; import android.database.Cursor; import com.nisira.core.util.ClaveMovil; import java.util.ArrayList; import java.util.LinkedList; import java.text.SimpleDateFormat; import java.util.Date; public class Cargos_personalDao extends BaseDao<Cargos_personal> { public Cargos_personalDao() { super(Cargos_personal.class); } public Cargos_personalDao(boolean usaCnBase) throws Exception { super(Cargos_personal.class, usaCnBase); } public void mezclarLocal(Cargos_personal obj)throws Exception{ if(obj !=null){ List<Cargos_personal> lst = listar("LTRIM(RTRIM(t0.IDEMPRESA)) =? AND LTRIM(RTRIM(t0.IDCARGO))=?",obj.getIdempresa().trim(),obj.getIdcargo().trim()); if(lst.isEmpty()) insertar(obj); else actualizar(obj); // update(obj,"IDEMPRESA='"+obj.getIdempresa()+"' AND IDCLIEPROV='"+obj.getIdclieprov()+"'"); } } public Boolean insert(Cargos_personal cargos_personal) { Boolean resultado = false; SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); try{ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ContentValues initialValues = new ContentValues(); initialValues.put("IDEMPRESA",cargos_personal.getIdempresa()); initialValues.put("IDCARGO",cargos_personal.getIdcargo()); initialValues.put("DESCRIPCION",cargos_personal.getDescripcion()); initialValues.put("IDACTIVIDAD",cargos_personal.getIdactividad()); initialValues.put("IDLABOR",cargos_personal.getIdlabor()); initialValues.put("SINCRONIZA",cargos_personal.getSincroniza()); initialValues.put("FECHACREACION",dateFormat.format(cargos_personal.getFechacreacion() ) ); initialValues.put("CODALTERNO",cargos_personal.getCodalterno()); initialValues.put("ES_GUARDIAN",cargos_personal.getEs_guardian()); initialValues.put("ES_PERS_AEREO",cargos_personal.getEs_pers_aereo()); initialValues.put("PRODUCCION_PESQUERA",cargos_personal.getProduccion_pesquera()); initialValues.put("CARGO_PESQUERA",cargos_personal.getCargo_pesquera()); initialValues.put("TIPO_TRABAJO",cargos_personal.getTipo_trabajo()); initialValues.put("IDAREA",cargos_personal.getIdarea()); initialValues.put("ES_JEFEDEAREA",cargos_personal.getEs_jefedearea()); initialValues.put("USA_SUBSECTOR",cargos_personal.getUsa_subsector()); initialValues.put("TIPO_CARGO",cargos_personal.getTipo_cargo()); initialValues.put("ES_CHOFER",cargos_personal.getEs_chofer()); resultado = mDb.insert("CARGOS_PERSONAL",null,initialValues)>0; } catch (Exception e) { }finally { mDb.close(); } return resultado; } public Boolean update(Cargos_personal cargos_personal,String where) { Boolean resultado = false; SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); try{ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ContentValues initialValues = new ContentValues(); initialValues.put("IDEMPRESA",cargos_personal.getIdempresa()) ; initialValues.put("IDCARGO",cargos_personal.getIdcargo()) ; initialValues.put("DESCRIPCION",cargos_personal.getDescripcion()) ; initialValues.put("IDACTIVIDAD",cargos_personal.getIdactividad()) ; initialValues.put("IDLABOR",cargos_personal.getIdlabor()) ; initialValues.put("SINCRONIZA",cargos_personal.getSincroniza()) ; initialValues.put("FECHACREACION",dateFormat.format(cargos_personal.getFechacreacion() ) ) ; initialValues.put("CODALTERNO",cargos_personal.getCodalterno()) ; initialValues.put("ES_GUARDIAN",cargos_personal.getEs_guardian()) ; initialValues.put("ES_PERS_AEREO",cargos_personal.getEs_pers_aereo()) ; initialValues.put("PRODUCCION_PESQUERA",cargos_personal.getProduccion_pesquera()) ; initialValues.put("CARGO_PESQUERA",cargos_personal.getCargo_pesquera()) ; initialValues.put("TIPO_TRABAJO",cargos_personal.getTipo_trabajo()) ; initialValues.put("IDAREA",cargos_personal.getIdarea()) ; initialValues.put("ES_JEFEDEAREA",cargos_personal.getEs_jefedearea()) ; initialValues.put("USA_SUBSECTOR",cargos_personal.getUsa_subsector()) ; initialValues.put("TIPO_CARGO",cargos_personal.getTipo_cargo()) ; initialValues.put("ES_CHOFER",cargos_personal.getEs_chofer()) ; resultado = mDb.update("CARGOS_PERSONAL",initialValues,where,null)>0; } catch (Exception e) { }finally { mDb.close(); } return resultado; } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public Boolean delete(String where) { Boolean resultado = false; SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); try{ resultado = mDb.delete("CARGOS_PERSONAL",where,null)>0; } catch (Exception e) { }finally { mDb.close(); } return resultado; } public ArrayList<Cargos_personal> listar(String where,String order,Integer limit) { if(limit == null){ limit =0; } ArrayList<Cargos_personal> lista = new ArrayList<Cargos_personal>(); SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); try{ Cursor cur = mDb.query("CARGOS_PERSONAL", new String[] { "IDEMPRESA" , "IDCARGO" , "DESCRIPCION" , "IDACTIVIDAD" , "IDLABOR" , "SINCRONIZA" , "FECHACREACION" , "CODALTERNO" , "ES_GUARDIAN" , "ES_PERS_AEREO" , "PRODUCCION_PESQUERA" , "CARGO_PESQUERA" , "TIPO_TRABAJO" , "IDAREA" , "ES_JEFEDEAREA" , "USA_SUBSECTOR" , "TIPO_CARGO" , "ES_CHOFER" }, where, null, null, null, order); if (cur!=null){ cur.moveToFirst(); int i=0; while (cur.isAfterLast() == false) { int j=0; Cargos_personal cargos_personal = new Cargos_personal() ; cargos_personal.setIdempresa(cur.getString(j++)); cargos_personal.setIdcargo(cur.getString(j++)); cargos_personal.setDescripcion(cur.getString(j++)); cargos_personal.setIdactividad(cur.getString(j++)); cargos_personal.setIdlabor(cur.getString(j++)); cargos_personal.setSincroniza(cur.getString(j++)); cargos_personal.setFechacreacion(dateFormat.parse(cur.getString(j++)) ); cargos_personal.setCodalterno(cur.getString(j++)); cargos_personal.setEs_guardian(cur.getInt(j++)); cargos_personal.setEs_pers_aereo(cur.getDouble(j++)); cargos_personal.setProduccion_pesquera(cur.getDouble(j++)); cargos_personal.setCargo_pesquera(cur.getString(j++)); cargos_personal.setTipo_trabajo(cur.getString(j++)); cargos_personal.setIdarea(cur.getString(j++)); cargos_personal.setEs_jefedearea(cur.getDouble(j++)); cargos_personal.setUsa_subsector(cur.getDouble(j++)); cargos_personal.setTipo_cargo(cur.getDouble(j++)); cargos_personal.setEs_chofer(cur.getDouble(j++)); lista.add(cargos_personal); i++; if(i == limit){ break; } cur.moveToNext(); } cur.close(); } } catch (Exception e) { }finally { mDb.close(); } return lista; } }
package com.t.core.cluster; import com.alibaba.fastjson.JSON; import com.t.core.domain.Job; import com.t.core.registry.NodeRegistryUtils; import lombok.Getter; import lombok.Setter; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * @author tb * @date 2018/12/17 14:25 */ @Getter @Setter public class Node { // 是否可用 private boolean available = true; private String clusterName; private NodeType nodeType; private String ip; private Integer port = 0; private String hostName; private String group; private Long createTime; // 线程个数 private Integer threads; // 唯一标识 private String identity; // 命令端口 private Integer httpCmdPort; // 自己关注的节点类型 private List<NodeType> listenNodeTypes; private String fullString; private Job job; public void addListenNodeType(NodeType nodeType) { if (this.listenNodeTypes == null) { this.listenNodeTypes = new ArrayList<>(); } this.listenNodeTypes.add(nodeType); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Node node = (Node) o; return Objects.equals(identity, node.identity); } @Override public int hashCode() { return identity != null ? identity.hashCode() : 0; } public String getAddress() { return ip + ":" + port; } public String toFullString() { if (fullString == null) { fullString = NodeRegistryUtils.getFullPath(this); } return fullString; } @Override public String toString() { return JSON.toJSONString(this); } }
/* Test 40: * * Il test controlla l' accesso a dati locali e campi di classi, siano essi * statici che non. */ package gimnasium; class s3 { int k; protected static float j; private static float z; void pippo() { } } class s2 extends s4 { int c; static float d; s3 p; void pluto() { if (super.x>10); } } class s1 { int x; void pippo() { int a,b; boolean p; s2 t; int dodo[]; s3 sss; if (!(a>b)); if (this.x>1); if (s2.c>2); // errore!!! rif. statico a un campo non statico. if (s2.d>2); if (t.c>2); if (t.p.k>10); if (s3.j>11); /* * j e' accessibile perche' s1 e' definita nello * stesso pacchetto di s3. */ if (s3.z>12); // errore!!! campo inaccessibile. if (dodo.length==1); if (sss.lk > 10); // errore!!! campo inesistente. if (sss.pippo > 12); } } class s4 { int x; }
package annotation; public class PasswordUtils { @UserCase(id=1, description="password must contains one number!") public boolean validate(String password){ return password.matches("\\w*\\D\\w*"); } @UserCase(id=2) public String encryptPwd(String password){ return new StringBuilder(password).reverse().toString(); } }
package nobile.riccardo.commercialista; public class Commercialista { private Cliente[] clienti; public Commercialista() { } public Commercialista(Cliente[] clienti) { this.clienti = clienti; } public int totaleIncasso() { int incasso = 0; for(Cliente c:clienti) { if(c instanceof CalcolaParcella) { incasso += c.calcolaParcella(); } } return incasso; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package diseño; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.table.DefaultTableModel; /** * * @author zabdy */ public class Productos extends javax.swing.JInternalFrame { /** * Creates new form Productos */ public Productos() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel6 = new javax.swing.JPanel(); BotonConsultar = new javax.swing.JButton(); jScrollPane7 = new javax.swing.JScrollPane(); tabla1 = new javax.swing.JTable(); txtCat_producto = new javax.swing.JTextField(); BuscarCat_producto = new javax.swing.JButton(); setClosable(true); setIconifiable(true); setMaximizable(true); setResizable(true); setTitle("Productos"); jPanel6.setBackground(new java.awt.Color(102, 102, 102)); BotonConsultar.setText("Consultar"); BotonConsultar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BotonConsultarActionPerformed(evt); } }); tabla1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); jScrollPane7.setViewportView(tabla1); txtCat_producto.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtCat_productoActionPerformed(evt); } }); BuscarCat_producto.setText("Buscar"); BuscarCat_producto.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BuscarCat_productoActionPerformed(evt); } }); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addComponent(txtCat_producto, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(BuscarCat_producto, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(BotonConsultar) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jScrollPane7, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 717, Short.MAX_VALUE)) .addContainerGap()) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane7, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtCat_producto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(BuscarCat_producto) .addComponent(BotonConsultar)) .addContainerGap(60, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 737, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 354, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txtCat_productoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCat_productoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtCat_productoActionPerformed private void BotonConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonConsultarActionPerformed // TODO add your handling code here: catalogoproduc(""); }//GEN-LAST:event_BotonConsultarActionPerformed private void BuscarCat_productoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BuscarCat_productoActionPerformed // TODO add your handling code here: catalogoproduc(txtCat_producto.getText()); }//GEN-LAST:event_BuscarCat_productoActionPerformed void catalogoproduc (String valor){ DefaultTableModel modelo= new DefaultTableModel(); modelo.addColumn("ID DEL PRODUCTO"); modelo.addColumn("DESCRIPCION DEL PRODUCTO"); modelo.addColumn("ID DE LA UNIDAD DE MEDIDA "); modelo.addColumn("CANTIDAD"); modelo.addColumn("PESO UNITARIO EN COMPRA"); modelo.addColumn("PESO UNITARIO EN VENTA"); modelo.addColumn("ID DEL DEPARTAMENTO"); modelo.addColumn("CANTIDAD MINIMA"); modelo.addColumn("IVA"); modelo.addColumn("PESO UNITARIO EN MAYOREO"); modelo.addColumn("PESO SUPERIOR EN MAYOREO"); tabla1.setModel(modelo); String sql=""; if(valor.equals("")) { sql="SELECT * FROM cat_productos"; } else{ sql="SELECT * FROM cat_productos WHERE ID_PRODUCTO='"+valor+"'"; } String []datos = new String [11]; try { Statement st = cn.createStatement(); ResultSet rs = st.executeQuery(sql); while(rs.next()){ datos[0]=rs.getString(1); datos[1]=rs.getString(2); datos[2]=rs.getString(3); datos[3]=rs.getString(4); datos[4]=rs.getString(5); datos[5]=rs.getString(6); datos[6]=rs.getString(7); datos[7]=rs.getString(8); datos[8]=rs.getString(9); datos[9]=rs.getString(10); datos[10]=rs.getString(11); modelo.addRow(datos); } tabla1.setModel(modelo); } catch (SQLException ex) { Logger.getLogger(COnsul.class.getName()).log(Level.SEVERE, null, ex); } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton BotonConsultar; private javax.swing.JButton BuscarCat_producto; private javax.swing.JPanel jPanel6; private javax.swing.JScrollPane jScrollPane7; private javax.swing.JTable tabla1; private javax.swing.JTextField txtCat_producto; // End of variables declaration//GEN-END:variables conecta cc=new conecta (); Connection cn=cc.conexion(); }
package com.example.jwtdemo2.services; import com.example.jwtdemo2.models.MovieRating; import com.example.jwtdemo2.models.TvRating; import com.example.jwtdemo2.repository.TvRatingRepository; import com.example.jwtdemo2.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class TvRatingService { @Autowired TvRatingRepository repository; @Autowired UserRepository userRepository; public int createTvRating(Long userId, Long id, TvRating rate){ return repository.insertTvRating(id,userId,rate.getComment(),rate.getRate()); } public List<TvRating> findRatingByTvId(Long tvId){ return repository.findRatingByTvId(tvId); } public int deleteTvRating(Integer id){ return repository.deleteRating(id); } public List<TvRating> findRatingById(Long id){ return repository.findRatingById(id); } }
package global.model; public class Office { private String o_id; private String d_id; private String o_name; public Office(String o_id, String d_id, String o_name) { super(); this.o_id = o_id; this.d_id = d_id; this.o_name = o_name; } public Office() { // TODO Auto-generated constructor stub } public String getO_id() { return o_id; } public void setO_id(String o_id) { this.o_id = o_id; } public String getD_id() { return d_id; } public void setD_id(String d_id) { this.d_id = d_id; } public String getO_name() { return o_name; } public void setO_name(String o_name) { this.o_name = o_name; } @Override public String toString() { return o_name; } public boolean equals(Object obj) { if (obj == null) return false; return this.o_name.equals(((Office) obj).o_name); } }
package com.codingbeer.hadoop.inverted.index; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; /** * Created by zemo on 02/04/15. */ public class InvertedIndexJob { static public void main(String[] arg) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "Inverted index"); job.setJarByClass(InvertedIndexJob.class); job.setMapperClass(InvertedIndexMapper.class); job.setReducerClass(InvertedIndexReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); FileInputFormat.addInputPath(job, new Path(arg[0])); FileOutputFormat.setOutputPath(job, new Path(arg[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } }
package uniandes.algorithms.coinchange; /** * Clase que modela VORAZ: DIVISION * @author David Hernandez y Leidy Romero */ public class CoinChangeGreedy implements CoinChangeAlgorithm{ private int[] monedas; public int[] calculateOptimalChange(int totalValue, int[] denominations) { monedas = new int[denominations.length]; calculate(denominations.length, totalValue, denominations); return monedas; } public void calculate(int i, int j, int[] denominaciones) { while(i>=0) { if(denominaciones[i]<=j) { monedas[i] = j/denominaciones[i]; j-=monedas[i]*denominaciones[i]; } i--; } } }
/* Copyright 2015 Alfio Zappala 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 co.runrightfast.commons.utils; import static co.runrightfast.commons.utils.ValidationUtils.notBlank; import co.runrightfast.exceptions.ShouldNeverHappenException; import java.lang.management.ManagementFactory; import java.net.URI; import java.net.URISyntaxException; /** * * @author alfio */ public interface AppUtils { String JVM_ID = ManagementFactory.getRuntimeMXBean().getName(); /** * * @param uri uri * @return normalized URI */ static URI uri(final String uri) { notBlank(uri); try { return new URI(uri).normalize(); } catch (final URISyntaxException ex) { throw new ShouldNeverHappenException(ex); } } }
/** * */ /** * @author 501pc00 * */ package com.biz.word;
package edu.cricket.api.cricketscores.rest.source.model; public class OutDetails { private String shortText; public String getShortText() { return shortText; } public void setShortText(String shortText) { this.shortText = shortText; } }
package com.gsccs.sme.solr.service; /** * 查询参数 * @author x.d zhang * */ public class QueryResult { private String siteId; private String keyword; private String cateId; private Integer minPrice; private Integer maxPrice; public String getSiteId() { return siteId; } public void setSiteId(String siteId) { this.siteId = siteId; } public String getKeyword() { return keyword; } public void setKeyword(String keyword) { this.keyword = keyword; } public String getCateId() { return cateId; } public void setCateId(String cateId) { this.cateId = cateId; } public Integer getMinPrice() { return minPrice; } public void setMinPrice(Integer minPrice) { this.minPrice = minPrice; } public Integer getMaxPrice() { return maxPrice; } public void setMaxPrice(Integer maxPrice) { this.maxPrice = maxPrice; } }
package main.java.constant; import main.java.main.Vector2; public final class Constants { // Resources public static final String styleSheetLocation = "main/resources/stylesheets/"; public static final String localizationLocation = "main/resources/localization/"; public static final String jsonOrderDirectory = "JsonOrders"; public static final String usbWebServer = System.getenv("ProgramFiles(X86)") + "/usbwebserver/usbwebserver.exe"; public static final String databaseName = "magazijn"; public static final String productTableName = "products"; public static final String orderTableName = "orders"; public static final String customerTableName = "customers"; public static final String receiptTableName = "receipts"; public static final String iconLocation = "main/resources/icons/"; public static final String shoppingCartImage = iconLocation + "shoppingcart.png"; public static final String xImage = iconLocation + "x.png"; public static final String ApplicationIcon = iconLocation + "ApplicatieLogo.png"; // Size of the grid public static final int drawnGridSize = (int) (665); public static final int baseWareHouseSize = 5; public static final int baseBoxSize = 10; // Back to main menu position and size public static final Vector2 backTMMBP = new Vector2(15, 15); public static final Vector2 backTMMBS = new Vector2(250, 50); }
package com.sise.internsystem.entity; import java.util.Date; public class Trainpath { private long id; private Date date; private String times; private String endtime; private String train; private String fromplace; private String toplace; public long getId() { return id; } public void setId(long id) { this.id = id; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getTimes() { return times; } public void setTimes(String times) { this.times = times; } public String getTrain() { return train; } public void setTrain(String train) { this.train = train; } public String getFromplace() { return fromplace; } public void setFromplace(String fromplace) { this.fromplace = fromplace; } public String getToplace() { return toplace; } public void setToplace(String toplace) { this.toplace = toplace; } public String getEndtime() { return endtime; } public void setEndtime(String endtime) { this.endtime = endtime; } }
package coffee.bean2; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; public class PayMentDataBean { private static PayMentDataBean INSTANCE = new PayMentDataBean(); public PayMentDataBean() { // TODO Auto-generated constructor stub } public static PayMentDataBean getINSTANCE() { return INSTANCE; } private Connection getConnection() throws Exception { // TODO Auto-generated method stub Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); DataSource ds = (DataSource) envCtx.lookup("jdbc/TestDB"); return ds.getConnection(); } private Timestamp getDate() { // TODO Auto-generated method stub Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String query = "select now()"; Timestamp now = null; try { conn = getConnection(); pstmt = conn.prepareStatement(query); rs = pstmt.executeQuery(); while (rs.next()) { now = rs.getTimestamp(1); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (conn != null) { conn.close(); } if (pstmt != null) pstmt.close(); if (rs != null) rs.close(); } catch (Exception e) { e.printStackTrace(); } } return now; } public int payMentInsertAction(int ptUsed, int pMoney, String cId, float pointMoney) { // TODO Auto-generated method stub Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; System.out.println("넘어 오는 고객 아이디 값 : " + cId); if (cId.equals("")) { cId = "customer"; } System.out.println("결제 인서트 부분"); Random r = new Random(); int random = r.nextInt(10000); String pCode = "c" + random; Timestamp pDate = getDate(); String query = "insert into payment values(?,?,?,?,?)"; int x = 0; try { conn = getConnection(); pstmt = conn.prepareStatement(query); pstmt.setString(1, pCode); pstmt.setTimestamp(2, pDate); pstmt.setInt(3, ptUsed); pstmt.setInt(4, pMoney); pstmt.setString(5, cId); x = pstmt.executeUpdate(); System.out.println("결제 행 : " + x); } catch (Exception e) { e.printStackTrace(); } finally { try { if (conn != null) { conn.close(); } if (pstmt != null) pstmt.close(); if (rs != null) rs.close(); } catch (Exception e) { e.printStackTrace(); } this.pointListAction(pCode, cId, pointMoney); // 호출 인서트 this.updateUserPoint(cId, pMoney, ptUsed, pointMoney); // 클라이언트 업데이트 } return x; } public void pointListAction(String pCode, String cId, float pointMoney) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; System.out.println("포인트 부분 넘어 오는 고객 아이디 값 : " + cId); System.out.println("고객 포인트 인서트 부분"); String query = "insert into pointlist values(?,?,?)"; int x = 0; if (cId.equals("")) { cId = "customer"; } try { conn = getConnection(); pstmt = conn.prepareStatement(query); pstmt.setString(1, pCode); pstmt.setString(2, cId); pstmt.setFloat(3, pointMoney); x = pstmt.executeUpdate(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (conn != null) { conn.close(); } if (pstmt != null) pstmt.close(); if (rs != null) rs.close(); } catch (Exception e) { e.printStackTrace(); } } } public void updateUserPoint(String cId, int pMoney, int ptUsed, float pointMoney) { // TODO Auto-generated method stub System.out.println("업데이트 유저 들어오니??"); Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; int[] array = getPointTotalPayMentMoney(cId); // select 해온다 . int cPointTemp = array[0]; // 포인트 금액 int totalPointTemp = array[1]; // 총 주문 금액 int cPoint = (int) (pointMoney + (cPointTemp - ptUsed)); int totalPoint = totalPointTemp + pMoney; System.out.println("업데이트 : cPoint = " + cPoint); System.out.println("업데이트 : totalPoint = " + totalPoint); String query = "update client set cPoint=?,totalPoint=? where cId=?"; try { conn = getConnection(); pstmt = conn.prepareStatement(query); pstmt.setInt(1, cPoint); pstmt.setInt(2, totalPoint); pstmt.setString(3, cId); pstmt.executeQuery(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (conn != null) { conn.close(); } if (pstmt != null) pstmt.close(); if (rs != null) rs.close(); } catch (Exception e) { e.printStackTrace(); } } System.out.println("업데이트 끝냈니"); } // 포인트 머니 , 총 주문 금액 넘겨주는 역활 private int[] getPointTotalPayMentMoney(String cId) { // TODO Auto-generated method stub Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String query = "select cPoint,totalPoint from client where cId = ?"; int[] forwardInt = new int[2]; try { conn = getConnection(); pstmt = conn.prepareStatement(query); pstmt.setString(1, cId); rs = pstmt.executeQuery(); int index = 0; while (rs.next()) { forwardInt[0] = rs.getInt(1); forwardInt[1] = rs.getInt(2); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (conn != null) { conn.close(); } if (pstmt != null) pstmt.close(); if (rs != null) rs.close(); } catch (Exception e) { e.printStackTrace(); } } System.out.println("넘어가는 인트갑 :" + Arrays.toString(forwardInt)); return forwardInt; } public int updatePercent(float percentP) { // TODO Auto-generated method stub Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String query = "update category set percentP =?"; int x = 0; try { conn = getConnection(); pstmt = conn.prepareStatement(query); pstmt.setFloat(1, percentP); x = pstmt.executeUpdate(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (conn != null) { conn.close(); } if (pstmt != null) pstmt.close(); if (rs != null) rs.close(); } catch (Exception e) { e.printStackTrace(); } } return x; } // 포인트 리스트 불러오기 public ArrayList<PayMent> getPointList(String cId) { // TODO Auto-generated method stub Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; PayMent object = null; ArrayList<PayMent> payMent = new ArrayList<PayMent>(); String query = "select pCode,pDate,pMoney,ptUsed from payment where cId = ? order by pDate desc"; try { conn = getConnection(); pstmt = conn.prepareStatement(query); pstmt.setString(1, cId); rs = pstmt.executeQuery(); while (rs.next()) { String pCode = rs.getString("pCode"); Timestamp pDate = rs.getTimestamp("pDate"); int pMoney = rs.getInt("pMoney"); int ptUsed = rs.getInt("ptUsed"); object = new PayMent(); object.setpCOde(pCode); object.setpDate(pDate); object.setpMoney(pMoney); object.setPtUsed(ptUsed); payMent.add(object); // payMent.add() } } catch (Exception e) { e.printStackTrace(); } finally { try { if (conn != null) { conn.close(); } if (pstmt != null) { pstmt.close(); } if (rs != null) { rs.close(); } } catch (Exception e) { e.printStackTrace(); } } return payMent; } }
package testniki; import org.testng.annotations.Test; public class TC28_VerifyCarRepair extends TestNiki{ //Testcase28-->To verify the Car Repair from Repairs under Local search. @Test public void testCase28_localSearch() throws InterruptedException { try{ driver.findElementByClassName("android.widget.EditText").sendKeys("Hi Niki"); driver.findElementById("com.techbins.niki.beta:id/btnSend").click(); appInd.waitFor(5000); driver.findElementByAndroidUIAutomator("text(\"Local Search\")").click(); System.out.println("Local Search option has been selected"); String outMsg1 = driver.findElementByXPath("//android.widget.Button[@text='Local Search']").getText(); if (outMsg1.equals("Local Search")) { System.out.println("Out going message confirmed as--> " + outMsg1); } appInd.waitFor(5000); driver.findElementByAndroidUIAutomator("text(\"Repairs\")").click(); System.out.println("Repairs option has been selected"); String outMsg2 = driver.findElementByXPath("//android.widget.Button[@text='Local Search']").getText(); if (outMsg2.equals("Repairs")) { System.out.println("Out going message confirmed as--> " + outMsg1); } appInd.waitFor(5000); driver.findElementByClassName("android.widget.EditText").sendKeys("Airtel"); System.out.println("Changing the network opertaor to Airtel"); driver.findElementById("com.techbins.niki.beta:id/btnSend").click(); appInd.waitFor(5000); String expectedMessage = "Picking your Operator as Airtel"; String actualMessage = driver.findElementByAndroidUIAutomator("new UiSelector().textContains(\"" + expectedMessage + "\")").getText(); //String expectedMessage=driver.findElementByXPath("//android.widget.TextView[contains(@text,'Picking your Operator as Airtel.']").getText(); if(actualMessage.contains("Airtel")) { System.out.println("Network operator has changed to Airtel successfully"); } else { System.out.println("Network operator has not changed to Airtel"); } }catch(Exception e) { System.out.println(e.getMessage()); } } }
package com.weather.love.db; import org.litepal.crud.DataSupport; /** * Created by Administrator on 2017/6/23. */ public class Family extends DataSupport { public String Name; public String Province; public String City; public String County; public int WeatherId; public int PhoneNumber; public String text1; public String text2; public String text3; public String text4; public String text5; }
package fr.franck; import java.util.Arrays; import java.util.List; public class CodeCracker { public static void main(String[] args) { } public static String[] crackingWord(String word) { String[] alphabet = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", }; String[] defaultKey = { "!", ")", "\"", "(", "£", "*", "%", "&", ">", "<", "@", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", }; List<String> alphabetList = Arrays.asList(alphabet); String[] letterOfWord = word.split(""); int[] positionOfLetter = new int[letterOfWord.length]; String[] codedWord = new String[letterOfWord.length]; for (int i = 0; i < letterOfWord.length; i++) { positionOfLetter[i] = alphabetList.indexOf(letterOfWord[i]); } for (int i = 0; i < letterOfWord.length; i++) { codedWord[i] = defaultKey[positionOfLetter[i]]; } return codedWord; } }
package tcss450.uw.edu.huskylist; import junit.framework.TestCase; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import tcss450.uw.edu.huskylist.model.ItemContent; /** * this class is to test JUnit test to ItemContent class in our model */ public class ItemContentTest extends TestCase { /** * This variable is ItemContent that hold the itemcontent */ private ItemContent mItemContent; /** * this method is to test the constructor */ @Test public void testConstructor(){ ItemContent itemContent = new ItemContent("sdendaa@uw.edu","Mobile Applications", "98.89", "used","this book is like new","UW Tacoma", "sdendaa@yahoo.com"); assertNotNull(itemContent); } /** * this method is to test the JarseJSON */ @Test public void testParseItemContentJSON() { String ItemContentJSON = "[{\"Seller_userName\":\"sdendaa@uw.edu\",\"Item_title\":\"Mobile Applications\",\"Item_price\":\"98.89\"," + "\"Item_condition\":\"used\",\"Item_descriptions\":\"this book is like new\",\"Seller_location\":\"UW Tacoma\"," + "\"Seller_contact\":\"sdendaa@yahoo.com\"},{\"Seller_userName\":\"sdendaa@uw.edu\",\"Item_title\":\"Data structure\"," + "\"Item_price\":\"988.97\", \"Item_condition\":\"new\",\"Item_descriptions\":\"never open the package\"," + "\"Seller_location\":\"UW Seattle\",\"Seller_contact\":\"sdendaa@yahoo.com\"}]"; String message = ItemContent.parseItemContentJSON(ItemContentJSON , new ArrayList<ItemContent>()); assertTrue("JSON With Valid String", message == null); } /** * this method is to setup the instrumental unit test before build unit test */ @Before public void setUp() { mItemContent = new ItemContent("sdendaa@uw.edu", "Mobile Applications", "98.89", "used", "this book is like new", "UW Tacoma","sdendaa@yahoo.com"); } /** * this method is to test item title null */ @Test public void testSetNullItemTitle() { try { mItemContent.setItemTitle(null); fail("Item Title can't be set to null"); } catch (IllegalArgumentException e) { } } /** * this method is to test item price null */ @Test public void testSetNullItemPrice() { try { mItemContent.setItemPrice(null); fail("Item price can't be set to null"); } catch (IllegalArgumentException e) { } } /** * this method is to test item condition null */ @Test public void testSetNullItemCondition() { try { mItemContent.setItemCondition(null); fail("seller condition can't be set to null"); } catch (IllegalArgumentException e) { } } /** * this method is to test the seller location null */ @Test public void testSetNullSellerLoaction() { try { mItemContent.setSellerLocation(null); fail("Sellere location can't be set to null"); } catch (IllegalArgumentException e) { } } /** * this method is to test seller contact null */ @Test public void testSetNullSellerContact() { try { mItemContent.setSellerContact(null); fail("seller contact can't be set to null"); } catch (IllegalArgumentException e) { } } /** * this method is to test user name null */ @Test public void testSetNullSellerUserName() { try { mItemContent.setSellerUserName(null); fail("seller username can't be set to null"); } catch (IllegalArgumentException e) { } } /** * this method to test the item title length */ @Test public void testSetLengthItemTitle() { try { mItemContent.setItemTitle("3"); fail("Item Title must be set to greater than or equal to 5 characters long"); } catch (IllegalArgumentException e) { } } /** * this method is to test the get item title method */ @Test public void testGetItemTitle() { assertEquals("Mobile Applications", mItemContent.getItemTitle()); } /** * this method is to test get item price method. */ @Test public void testGetItemPrice() { assertEquals("98.89", mItemContent.getItemPrice()); } /** * this method is to test get item condition method */ @Test public void testGetItemCondition() { assertEquals("used", mItemContent.getmItemCondtion()); } /** * this method is to test get item description method */ @Test public void testGetItemDesciption() { assertEquals("this book is like new", mItemContent.getItemDescription()); } /** * this method is to test get sellet loaction method */ @Test public void testGetSellereLoaction() { assertEquals("UW Tacoma", mItemContent.getSellerLocation()); } /** * this method is to test seller contact method */ @Test public void testGetSellereContact() { assertEquals("sdendaa@yahoo.com", mItemContent.getSellerContact()); } }
package com.badawy.carservice.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import androidx.recyclerview.widget.RecyclerView; import com.badawy.carservice.R; import com.badawy.carservice.fragment.DeliveryCarSpeedFixFragment; import com.badawy.carservice.models.SpeedFixCategoryModel; import java.util.ArrayList; public class SpeedFixCategoryAdapter extends RecyclerView.Adapter<SpeedFixCategoryAdapter.myViewHolder> { //Global Variables private ArrayList<SpeedFixCategoryModel> list; private Context context; private OnItemClickListener onItemClickListener; private int currentPosition; public interface OnItemClickListener { void onItemClick(int position); } public void setOnItemClickListener(OnItemClickListener listener) { onItemClickListener = listener; } //Constructor public SpeedFixCategoryAdapter(Context context, ArrayList<SpeedFixCategoryModel> list) { this.list = list; this.context = context; currentPosition = -1; } //return the layout of items ( How an item should look like ) @NonNull @Override public myViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemLayout = LayoutInflater.from(context).inflate(R.layout.item_speedfix_categories, parent, false); return new myViewHolder(itemLayout, onItemClickListener); } // put the data inside the views of an item @Override public void onBindViewHolder(@NonNull myViewHolder eachItem, final int position) { eachItem.categoryIcon.setImageResource(list.get(position).getCategoryImage()); eachItem.categoryName.setText(list.get(position).getCategoryName()); eachItem.categoryBackground.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { currentPosition = position; notifyDataSetChanged(); replaceFragment(v, new DeliveryCarSpeedFixFragment()); } }); if (currentPosition == position) { eachItem.categoryBackground.setBackgroundResource(R.color.grey_line); } else { eachItem.categoryBackground.setBackgroundResource(R.color.white); } } // return number of rows in the list @Override public int getItemCount() { return list.size(); } private void replaceFragment(View view, Fragment fragment) { AppCompatActivity activity = (AppCompatActivity) view.getContext(); activity.getSupportFragmentManager().beginTransaction() .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .replace(R.id.homepage_fragment_container, fragment) .addToBackStack("NavHomeFragment") .commit(); } // define the views of an item class myViewHolder extends RecyclerView.ViewHolder { // Global Variables ImageView categoryIcon; TextView categoryName; ConstraintLayout categoryBackground; // Constructor to initialize the views from the Layout myViewHolder(@NonNull View itemView, final OnItemClickListener listener) { super(itemView); // Views inside our layout categoryIcon = itemView.findViewById(R.id.item_speedFix_category_image); categoryName = itemView.findViewById(R.id.item_speedFix_category_name); categoryBackground = itemView.findViewById(R.id.item_speedFix_category_background); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (listener != null) { int position = getAdapterPosition(); if (position != RecyclerView.NO_POSITION) { listener.onItemClick(position); notifyDataSetChanged(); } } } }); } } }
package com.example.naleirbag.login; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; /** * Created by gabrielan on 10/28/2015. */ public class ProfileActivity extends AppCompatActivity implements View.OnClickListener { TextView name,country,usertype; Button logout; private SharedPreferences loginPref; private SharedPreferences.Editor loginEditor; private static String usr = "", pass = ""; private final static String USERNAME_KEY = "username"; private final static String SAVED_KEY = "saved"; private boolean isSaved = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); init(); isSaved = loginPref.getBoolean(SAVED_KEY,false); usr = loginPref.getString(USERNAME_KEY,""); logout.setOnClickListener(this); // logout clear fields } private void init(){ loginPref = getSharedPreferences("loginPrefs",MODE_PRIVATE); Log.e("LogPrefs", loginPref.getString(USERNAME_KEY, "") + ""); Log.e("LogPrefs", loginPref.getBoolean(SAVED_KEY, false) + ""); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_profile); setSupportActionBar(toolbar); logout = new Button(this); logout.setId(0); logout.setText("Logout"); logout.setBackgroundColor(Color.CYAN); ViewGroup.LayoutParams lp = new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT,Gravity.RIGHT); toolbar.addView(logout, lp); name=(TextView)findViewById(R.id.name); country=(TextView)findViewById(R.id.country); usertype=(TextView)findViewById(R.id.usertype); Intent intent = getIntent(); name.setText(intent.getStringExtra("username")); country.setText(intent.getStringExtra("country")); usertype.setText(intent.getStringExtra("usertype")); } @Override public void onClick(View view) { if(view.getId() == 0){ Toast.makeText( this.getApplicationContext(), "Button logout", Toast.LENGTH_LONG).show(); Intent inte =new Intent(getBaseContext(),LoginService.class); stopService(inte); Intent logoutIntent = new Intent(ProfileActivity.this,LoginWithSharedPreferences.class); startActivity(logoutIntent); finish(); } } }
/** * Created with IntelliJ IDEA. * User: dogeyes * Date: 13-1-11 * Time: 上午9:52 * To change this template use File | Settings | File Templates. */ public class TestRandomBits { public static void main(String[] args) { BinaryOut out = new BinaryOut("random.txt"); int num = StdIn.readInt(); for(int i = 0; i < num / 8; ++i) { out.write(StdRandom.uniform(num) & 0xff, 8); } out.close(); } }
package com.zjf.myself.codebase.activity.UILibrary; import android.os.Bundle; import com.zjf.myself.codebase.R; import com.zjf.myself.codebase.activity.BaseAct; /** * Created by Administrator on 2017/3/23. */ public class NowHwWeatherAct extends BaseAct{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.win_weather); } }
package Problem_1517; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { static int N; static long[] arr; static long[] brr; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); N = Integer.parseInt(br.readLine()); arr = new long[N]; brr = new long[N]; StringTokenizer st = new StringTokenizer(br.readLine()); for(int i = 0; i <N; i++) { arr[i]= Long.parseLong(st.nextToken()); } long answer = answer(0, N-1); System.out.println(answer); } public static long answer(int start, int end) { if(start == end) return 0l; int mid = (start + end) / 2; long ans = answer(start, mid) + answer(mid+1, end); int i = start; int j = mid+1; int k = 0; while(i<= mid || j <= end) { if(i <= mid && (j > end || arr[i] <= arr[j])) { brr[k++] = arr[i++]; } else { ans += (long)(mid-i+1); brr[k++] = arr[j++]; } } for(i = start; i<=end; i++) arr[i] = brr[i-start]; return ans; } }
package io.github.selchapp.api.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration public class UserDetailsServiceBasedAuthentificationConfig extends GlobalAuthenticationConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override public void init(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Bean public PasswordEncoder passwordEncoder() { PasswordEncoder encoder = new BCryptPasswordEncoder(11); return encoder; } }
package com.jd.myadapterlib.dinterface; import com.jd.myadapterlib.delegate.RecyViewHolder; public interface DOnItemConvertListener<T> { /** * @param viewHolder recyclerview viewholder * @param item Object data type * @param position click position */ void itemConvert(RecyViewHolder viewHolder, T item, int position); }
package asylumdev.adgresources.item; import asylumdev.adgresources.ADGResources; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class MetaItem extends Item { protected String name; protected int meta; public MetaItem(String name) { this.name = name; setUnlocalizedName(name); setRegistryName(name); setCreativeTab(ADGResources.resourcesTab); } @SideOnly(Side.CLIENT) public void initModel() { ModelLoader.setCustomModelResourceLocation(this, 0, new ModelResourceLocation(getRegistryName(), "inventory")); } @Override public MetaItem setCreativeTab(CreativeTabs tab){ super.setCreativeTab(tab); return this; } }
package com.zhongyp.concurrency.thread; import java.io.*; public class ThreadState { public static void main(String[] args) { // new Thread(new TimeWaiting(), "TimeWaitingThread").start(); // new Thread(new Waiting(),"Waiting").start(); // new Thread(new Blocked(),"BlockedThread-1").start(); // new Thread(new Blocked(),"BlockedThread-2").start(); Account account = new Account(); new Thread(()->{ account.getMoney(100); },"thread get").start(); new Thread(()->{ account.putMoney(100); }, "thread put").start(); //// new Thread(new IOState(), "IOState").start(); // Thread thread = new Thread(new IOState(), "IOState"); // thread.setPriority(Thread.MAX_PRIORITY); } // 该线程不断的进行睡眠 static class TimeWaiting implements Runnable{ @Override public void run() { SleepUtils.sleep(200000); } } // 该线程在Waiting.class实例上等待 static class Waiting implements Runnable{ @Override public void run() { while(true){ synchronized (Waiting.class){//锁死Waiting字节码 try { Waiting.class.wait(); }catch (Exception e){ e.printStackTrace(); } } } } } // 该线程在Blocked.class实例上加锁后,不会释放该锁 static class Blocked implements Runnable{ @Override public void run() { synchronized(Blocked.class){//锁死Blocked字节码 SleepUtils.sleep(100000); } } } // wait reenter Blocked static class Account{ private int money = 0; public synchronized void getMoney(int num){ if(money>=num){ money-=num; }else{ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized void putMoney(int num){ money+=num; notifyAll(); SleepUtils.sleep(1000000); } } // IO阻塞的线程状态 static class IOState implements Runnable{ @Override public void run() { try { InputStreamReader is_reader = new InputStreamReader(System.in); String str = new BufferedReader(is_reader).readLine(); System.out.printf(str); }catch (Exception e){ e.printStackTrace(); } } } }
package us.spring.dayary.controller; import org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import us.spring.dayary.common.exception.DayaryException; import us.spring.dayary.domain.Status; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; @Controller public class DayaryErrorController implements ErrorController { @GetMapping("/error") public String error(HttpServletRequest request) { Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE); if (status == null) { throw new DayaryException(Status.BAD); } HttpStatus httpStatus = HttpStatus.valueOf(Integer.valueOf(status.toString())); if (httpStatus == HttpStatus.NOT_FOUND) {//404 return "forward:/error/error_404.html"; } else { throw new DayaryException(Status.BAD); } } @Override public String getErrorPath() { return null; } }
package by.client.android.railwayapp; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import by.client.android.railwayapp.ui.page.scoreboard.ScoreboardActivityFragment; /** * Кланвая странциа приложения * * @author ROMAN PANTELEEV */ public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = new Intent(this, ScoreboardActivityFragment.class); startActivity(intent); } }
package game; import java.util.Arrays; public class Piece { private int color; private int[][] data = new int[4][4]; private int ID; private int x = 0; private int y = 0; private int length; private int width; public Piece(int color, int[][] data, int ID, int width, int length) { this.color = color; for(int i = 0; i < 4; i ++) { for(int j = 0; j < 4; j ++) { if(data[i][j] == 1) { this.data[i][j] = color; } else { this.data[i][j] = 0; } } } this.ID = ID; x = 5 - ((int)(width/2)); y = 0; this.width = width; this.length = length; } public void setLeft() { x = 0; } public void center() { x = 5 - ((int)(width/2)); } public Piece clone() { Piece retVal; retVal = new Piece(color, new int[4][4], ID, width, length); retVal.setData(this.data); return retVal; } public void setData(int[][] data) { for(int i = 0; i < data.length; i ++) { this.data[i] = Arrays.copyOf(data[i], data[i].length); } } public void reset() { x = 5 - (int)(width/2); y = 0; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public boolean isEmptyColumn() { return (data[0][0] != 0 | data[1][0] != 0 | data[2][0] != 0 | data[3][0] != 0); } public boolean isEmptyRow() { return (data[0][0] != 0 | data[0][1] != 0 | data[0][2] != 0 | data[0][3] != 0); } public int getX() { return x; } public void rotateCW() { data = this.rotateCW(data); int w = this.length; int l = this.width; this.width = w; this.length = l; while(!this.isEmptyColumn()) { for(int i = 0; i < 4; i ++) { int first = data[i][0]; data[i][0] = data[i][1]; data[i][1] = data[i][2]; data[i][2] = data[i][3]; data[i][3] = first; } } while(!this.isEmptyRow()) { for(int i = 0; i < 4; i ++) { int first = data[0][i]; data[0][i] = data[1][i]; data[1][i] = data[2][i]; data[2][i] = data[3][i]; data[3][i] = first; } } } public void rotateCCW() { rotateCW(); rotateCW(); rotateCW(); } public int[][] rotateCW(int[][] mat) { final int M = mat.length; final int N = mat[0].length; int[][] ret = new int[N][M]; for (int r = 0; r < M; r++) { for (int c = 0; c < N; c++) { ret[c][M-1-r] = mat[r][c]; } } return ret; } public int[][] rotateCCW(int[][] mat) { final int M = mat.length; final int N = mat[0].length; int[][] ret = new int[N][M]; for(int i = 0; i < 3; i ++) { for (int r = 0; r < M; r++) { for (int c = 0; c < N; c++) { ret[c][M-1-r] = mat[r][c]; } } mat = ret; } return ret; } public void setX(int x) { if(x > 10 - width) { this.x = 10 - width; } else if(x < 0) { this.x = 0; } else { this.x = x; } } public int getY() { return y; } public void setY(int y) { if(y > 22 - length) { this.y = 22 - length; } else if(y < 0) { this.y = 0; } else { this.y = y; } } public int getColor() { return color; } public void setColor(int color) { for(int i = 0; i < 4; i ++) { for(int j = 0; j < 4; j ++) { if(data[i][j] == this.color) { this.data[i][j] = color; } else { this.data[i][j] = 0; } } } this.color = color; } public int[][] getData() { int[][] retVal = new int[4][4]; for(int i = 0; i < 4; i ++) { retVal[i] = Arrays.copyOf(data[i], data[i].length); } return retVal; } public int getID() { return ID; } public void setID(int iD) { ID = iD; } }
/* * Welcome to use the TableGo Tools. * * http://vipbooks.iteye.com * http://blog.csdn.net/vipbooks * http://www.cnblogs.com/vipbooks * * Author:bianj * Email:edinsker@163.com * Version:5.8.0 */ package com.lenovohit.hwe.org.model; import javax.persistence.Column; import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorType; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.NotFound; import org.hibernate.annotations.NotFoundAction; import com.fasterxml.jackson.annotation.JsonIgnore; import com.lenovohit.bdrp.authority.model.AuthAccount; import com.lenovohit.bdrp.authority.model.impl.DefaultAuthAccount; import com.lenovohit.core.utils.BeanUtils; import com.lenovohit.hwe.base.model.AuditableModel; /** * HWE_ACCOUNT * * @author zyus * @version 1.0.0 2017-12-14 */ @Entity @Table(name = "HWE_ACCOUNT") @DiscriminatorColumn(name = "DTYPE", discriminatorType = DiscriminatorType.STRING, length = 50) @DiscriminatorValue("base") public class Account extends AuditableModel implements AuthModel,AuthAccount { public static final String TYPE_APP = "app"; public static final String TYPE_WX = "wx"; public static final String TYPE_ZFB = "zfb"; public static final String TYPE_WEB = "web"; /** 版本号 */ private static final long serialVersionUID = 7491212560223673047L; private String namespace = "hwe"; /** username */ private String username; /** passwrod */ private String password; /** name */ private String name; /** mobile */ private String mobile; /** email */ private String email; /** otherContactWay */ private String otherContactWay; /** type */ private String type; /** 1 - 正常 2 - 冻结 */ private String status; private String newPassword; //新密码 private User user; @Transient public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } /** * 获取username * * @return username */ @Column(name = "USERNAME", nullable = true, length = 100) public String getUsername() { return this.username; } /** * 设置username * * @param username */ public void setUsername(String username) { this.username = username; } /** * 获取password * * @return password */ @Column(name = "PASSWORD", nullable = true, length = 100) public String getPassword() { return this.password; } /** * 设置password * * @param password */ public void setPassword(String password) { this.password = password; } /** * 获取name * * @return name */ @Column(name = "NAME", nullable = true, length = 100) public String getName() { return this.name; } /** * 设置name * * @param name */ public void setName(String name) { this.name = name; } /** * 获取mobile * * @return mobile */ @Column(name = "MOBILE", nullable = true, length = 20) public String getMobile() { return this.mobile; } /** * 设置mobile * * @param mobile */ public void setMobile(String mobile) { this.mobile = mobile; } /** * 获取email * * @return email */ @Column(name = "EMAIL", nullable = true, length = 50) public String getEmail() { return this.email; } /** * 设置email * * @param email */ public void setEmail(String email) { this.email = email; } /** * 获取otherContactWay * * @return otherContactWay */ @Column(name = "OTHER_CONTACT_WAY", nullable = true, length = 100) public String getOtherContactWay() { return this.otherContactWay; } /** * 设置otherContactWay * * @param otherContactWay */ public void setOtherContactWay(String otherContactWay) { this.otherContactWay = otherContactWay; } /** * 获取type * * @return type */ @Column(name = "TYPE", nullable = true, length = 1) public String getType() { return this.type; } /** * 设置type * * @param type */ public void setType(String type) { this.type = type; } /** */ @Column(name = "STATUS", nullable = true, length = 1) public String getStatus() { return this.status; } /** */ public void setStatus(String status) { this.status = status; } @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name = "USER_ID") @NotFound(action=NotFoundAction.IGNORE) @JsonIgnore public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Transient public String getNewPassword() { return newPassword; } public void setNewPassword(String newPassword) { this.newPassword = newPassword; } @Override public AuthAccount clone() { try { Object clone = super.clone(); AuthAccount cloned = (AuthAccount)clone; return cloned; } catch (CloneNotSupportedException e) { DefaultAuthAccount target = new DefaultAuthAccount(); BeanUtils.copyProperties(this, target); return target; } } }
package com.corycharlton.bittrexapi.model; import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") public class Balance { @SerializedName("Available") private double _available; @SerializedName("Balance") private double _total; @SerializedName("CryptoAddress") private String _cryptoAddress; @SerializedName("Currency") private String _currency; @SerializedName("Pending") private double _pending; private Balance() {} // Cannot be instantiated public double available() { return _available; } public String cryptoAddress() { return _cryptoAddress; } public String currency() { return _currency; } public double pending() { return _pending; } public double reserved() { return _total - _available; } public double total() { return _total; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.jearl.ftp.sftp; import com.jcraft.jsch.*; import java.io.*; import java.util.List; import org.jearl.ftp.FtpConnector; import org.jearl.ftp.exception.FileAlreadyExistsException; import org.jearl.ftp.exception.FileDoesNotExistsException; import org.jearl.ftp.exception.FtpConnectionException; import org.jearl.ftp.model.FtpFile; import org.jearl.ftp.model.FtpPropertie; import org.jearl.log.Logger; import org.jearl.util.StreamUtils; /** * * @author PC */ public class SftpConnector implements FtpConnector { private final Integer bufferSize; public SftpConnector(Integer bufferSize) { this.bufferSize = bufferSize; } private class SftpConnection { private Session session; private Channel channel; private ChannelSftp channelSftp; private JSch jsch; private Boolean directoryExist; private Boolean directoryEmpty; private Boolean fileExist; private List files; public SftpConnection(FtpPropertie propertie, FtpFile file) throws JSchException, SftpException { this.jsch = new JSch(); this.session = jsch.getSession(propertie.getUser(), propertie.getHost(), propertie.getPort()); this.session.setPassword(propertie.getPassword()); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); channel = session.openChannel("sftp"); channel.connect(); channelSftp = (ChannelSftp) channel; String parentDirectory = getParentDirectory(file.getDirectory()); String directoryName = getDirectoryName(file.getDirectory()); this.getChannelSftp().cd(parentDirectory); this.directoryExist = false; this.fileExist = false; final List parentFiles = this.getChannelSftp().ls(parentDirectory); if (parentFiles.isEmpty()) { return; } for (int i = 0; i < parentFiles.size(); i++) { ChannelSftp.LsEntry lsEntry = (ChannelSftp.LsEntry) parentFiles.get(i); if (!lsEntry.getFilename().equals(".") && !lsEntry.getFilename().equals("..")) { if (lsEntry.getFilename().equals(directoryName)) { directoryExist = true; } } } this.getChannelSftp().cd(file.getDirectory()); files = this.getChannelSftp().ls(file.getDirectory()); if (files.isEmpty()) { this.directoryEmpty = true; return; } for (int i = 0; i < files.size(); i++) { ChannelSftp.LsEntry lsEntry = (ChannelSftp.LsEntry) files.get(i); if (!lsEntry.getFilename().equals(".") && !lsEntry.getFilename().equals("..") && lsEntry.getFilename().equals(file.getFileName())) { fileExist = true; } } } public final ChannelSftp getChannelSftp() { return channelSftp; } public Boolean getDirectoryExist() { return directoryExist; } public Boolean getDirectoryEmpty() { return directoryEmpty; } public Boolean getFileExist() { return fileExist; } public List getFiles() { return files; } public final void disconnect() { channel.disconnect(); channelSftp.disconnect(); session.disconnect(); } } @Override public void transfer(FtpPropertie propertie1, FtpFile file1, FtpPropertie propertie2, FtpFile file2, Boolean forceTransfer) throws FtpConnectionException, FileAlreadyExistsException, FileDoesNotExistsException { SftpConnection sftpConnection1 = null; SftpConnection sftpConnection2 = null; try { sftpConnection1 = new SftpConnection(propertie1, file1); sftpConnection2 = new SftpConnection(propertie2, file2); if (!sftpConnection1.getDirectoryExist()) { throw new FileDoesNotExistsException("Directory does not exist.."); } if (!sftpConnection1.getFileExist()) { throw new FileDoesNotExistsException("File does not exist.."); } if (!sftpConnection2.getDirectoryExist()) { throw new FileDoesNotExistsException("Directory does not exist.."); } if (sftpConnection2.getFileExist()) { if (forceTransfer) { InputStream is = sftpConnection1.getChannelSftp().get(file1.getFileName()); sftpConnection2.getChannelSftp().put(is, file2.getFileName()); } else { throw new FileAlreadyExistsException("File is already exist.."); } } else { InputStream is = sftpConnection1.getChannelSftp().get(file1.getFileName()); sftpConnection2.getChannelSftp().put(is, file2.getFileName()); } } catch (FileDoesNotExistsException e) { Logger.getLogger(SftpConnector.class).error(e, e); throw new FileDoesNotExistsException(e); } catch (FileAlreadyExistsException e) { Logger.getLogger(SftpConnector.class).error(e, e); throw new FileAlreadyExistsException(e); } catch (Exception e) { Logger.getLogger(SftpConnector.class).error(e, e); throw new FtpConnectionException(e); } finally { try { sftpConnection1.disconnect(); sftpConnection2.disconnect(); } catch (Exception ex) { throw new FtpConnectionException(ex); } } } @Override public void transfer(FtpPropertie propertie, FtpFile file1, File file2, Boolean forceTransfer) throws FtpConnectionException, FileAlreadyExistsException, FileDoesNotExistsException { SftpConnection sftpConnection = null; try { sftpConnection = new SftpConnection(propertie, file1); if (!sftpConnection.getDirectoryExist()) { throw new FileDoesNotExistsException("Directory does not exist.."); } if (!sftpConnection.getFileExist()) { throw new FileDoesNotExistsException("File does not exist.."); } if (file2.exists()) { if (forceTransfer) { InputStream is = sftpConnection.getChannelSftp().get(file1.getFileName()); OutputStream os = new FileOutputStream(file2); StreamUtils.transfer(is, os, bufferSize); } else { throw new FileAlreadyExistsException("file is already exist.."); } } else { InputStream is = sftpConnection.getChannelSftp().get(file1.getFileName()); OutputStream os = new FileOutputStream(file2); StreamUtils.transfer(is, os, bufferSize); } } catch (FileDoesNotExistsException e) { Logger.getLogger(SftpConnector.class).error(e, e); throw new FileDoesNotExistsException(e); } catch (FileAlreadyExistsException e) { Logger.getLogger(SftpConnector.class).error(e, e); throw new FileAlreadyExistsException(e); } catch (IOException e) { Logger.getLogger(SftpConnector.class).error(e, e); throw new FtpConnectionException(e); } catch (Exception e) { Logger.getLogger(SftpConnector.class).error(e, e); throw new FtpConnectionException(e); } finally { try { sftpConnection.disconnect(); } catch (Exception ex) { throw new FtpConnectionException(ex); } } } @Override public void transfer(File file1, FtpPropertie propertie, FtpFile file2, Boolean forceTransfer) throws FtpConnectionException, FileAlreadyExistsException, FileDoesNotExistsException { SftpConnection sftpConnection = null; try { sftpConnection = new SftpConnection(propertie, file2); if (!sftpConnection.getDirectoryExist()) { throw new FileDoesNotExistsException("Directory does not exist.."); } if (!sftpConnection.getFileExist()) { throw new FileDoesNotExistsException("File does not exist.."); } if (sftpConnection.getFileExist()) { if (forceTransfer) { sftpConnection.getChannelSftp().put(new FileInputStream(file1), file1.getName()); } else { throw new FileAlreadyExistsException("File is already exist.."); } } else { sftpConnection.getChannelSftp().put(new FileInputStream(file1), file1.getName()); } } catch (FileDoesNotExistsException e) { Logger.getLogger(SftpConnector.class).error(e, e); throw new FileDoesNotExistsException(e); } catch (FileAlreadyExistsException e) { Logger.getLogger(SftpConnector.class).error(e, e); throw new FileAlreadyExistsException(e); } catch (IOException e) { Logger.getLogger(SftpConnector.class).error(e, e); throw new FtpConnectionException(e); } catch (Exception e) { Logger.getLogger(SftpConnector.class).error(e, e); throw new FtpConnectionException(e); } finally { try { sftpConnection.disconnect(); } catch (Exception ex) { throw new FtpConnectionException(ex); } } } @Override public void removeFile(FtpPropertie propertie, FtpFile file) throws FtpConnectionException, FileDoesNotExistsException { SftpConnection sftpConnection = null; try { sftpConnection = new SftpConnection(propertie, file); if (!sftpConnection.getDirectoryExist()) { throw new FileDoesNotExistsException("Directory does not exist.."); } if (sftpConnection.getFileExist()) { sftpConnection.getChannelSftp().rm(file.getFileName()); } else { throw new FileDoesNotExistsException("File does not exist.."); } } catch (FileDoesNotExistsException e) { Logger.getLogger(SftpConnector.class).error(e, e); throw new FileDoesNotExistsException(e); } catch (Exception e) { Logger.getLogger(SftpConnector.class).error(e, e); throw new FtpConnectionException(e); } finally { try { sftpConnection.disconnect(); } catch (Exception ex) { throw new FtpConnectionException(ex); } } } @Override public void removeDirectory(FtpPropertie propertie, FtpFile file, Boolean deleteCascade) throws FtpConnectionException, FileDoesNotExistsException { SftpConnection sftpConnection = null; try { sftpConnection = new SftpConnection(propertie, file); if (!sftpConnection.getDirectoryExist()) { throw new FileDoesNotExistsException("Directory does not exist.."); } if (!sftpConnection.getDirectoryEmpty()) { List files = sftpConnection.getFiles(); if (deleteCascade) { Integer filesSize = files.size(); for (int i = 0; i < filesSize; i++) { ChannelSftp.LsEntry lsEntry = (ChannelSftp.LsEntry) files.get(i); if (!lsEntry.getFilename().equals(".") && !lsEntry.getFilename().equals("..")) { sftpConnection.getChannelSftp().rm(lsEntry.getFilename()); } } sftpConnection.getChannelSftp().rmdir(file.getDirectory()); } else { return; } } else { sftpConnection.getChannelSftp().rmdir(file.getDirectory()); } } catch (FileDoesNotExistsException e) { Logger.getLogger(SftpConnector.class).error(e, e); throw new FileDoesNotExistsException(e); } catch (Exception e) { Logger.getLogger(SftpConnector.class).error(e, e); throw new FtpConnectionException(e); } finally { try { sftpConnection.disconnect(); } catch (Exception ex) { throw new FtpConnectionException(ex); } } } @Override public void makeDirectory(FtpPropertie propertie, FtpFile file) throws FtpConnectionException, FileAlreadyExistsException { SftpConnection sftpConnection = null; try { sftpConnection = new SftpConnection(propertie, file); if (!sftpConnection.getDirectoryExist()) { sftpConnection.getChannelSftp().mkdir(file.getDirectory()); } else { throw new FileAlreadyExistsException("Directory does already exist.."); } } catch (FileAlreadyExistsException e) { Logger.getLogger(SftpConnector.class).error(e, e); throw new FileAlreadyExistsException(e); } catch (Exception e) { Logger.getLogger(SftpConnector.class).error(e, e); throw new FtpConnectionException(e); } finally { try { sftpConnection.disconnect(); } catch (Exception ex) { throw new FtpConnectionException(ex); } } } private String getParentDirectory(String directoryPath) { String path = directoryPath; String directoryName = path.substring(1, path.length() - 1); String pth = directoryName.substring(directoryName.lastIndexOf("/") + 1); int p = directoryName.length() - pth.length(); String parentPath = path.substring(0, p + 1); return parentPath; } private String getDirectoryName(String directoryPath) { String path = directoryPath; String directoryName = path.substring(1, path.length() - 1); String pth = directoryName.substring(directoryName.lastIndexOf("/") + 1); return pth; } }
package org.keycloak.authentication; import org.jboss.resteasy.spi.HttpRequest; import org.keycloak.ClientConnection; import org.keycloak.events.EventBuilder; import org.keycloak.models.ClientSessionModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; import org.keycloak.models.UserSessionModel; import org.keycloak.services.managers.ClientSessionCode; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; /** * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @version $Revision: 1 $ */ public class RequiredActionContextResult implements RequiredActionContext { protected UserSessionModel userSession; protected ClientSessionModel clientSession; protected RealmModel realm; protected EventBuilder eventBuilder; protected KeycloakSession session; protected Status status; protected Response challenge; protected HttpRequest httpRequest; protected UserModel user; public RequiredActionContextResult(UserSessionModel userSession, ClientSessionModel clientSession, RealmModel realm, EventBuilder eventBuilder, KeycloakSession session, HttpRequest httpRequest, UserModel user) { this.userSession = userSession; this.clientSession = clientSession; this.realm = realm; this.eventBuilder = eventBuilder; this.session = session; this.httpRequest = httpRequest; this.user = user; } @Override public EventBuilder getEvent() { return eventBuilder; } @Override public UserModel getUser() { return user; } @Override public RealmModel getRealm() { return realm; } @Override public ClientSessionModel getClientSession() { return clientSession; } @Override public UserSessionModel getUserSession() { return userSession; } @Override public ClientConnection getConnection() { return session.getContext().getConnection(); } @Override public UriInfo getUriInfo() { return session.getContext().getUri(); } @Override public KeycloakSession getSession() { return session; } @Override public HttpRequest getHttpRequest() { return httpRequest; } @Override public String generateAccessCode(String action) { ClientSessionCode code = new ClientSessionCode(getRealm(), getClientSession()); code.setAction(action); return code.getCode(); } @Override public Status getStatus() { return status; } @Override public void challenge(Response response) { status = Status.CHALLENGE; challenge = response; } @Override public void failure() { status = Status.FAILURE; } @Override public void success() { status = Status.SUCCESS; } @Override public void ignore() { status = Status.IGNORE; } public Response getChallenge() { return challenge; } }
package edu.upenn.cis350.androidapp; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import edu.upenn.cis350.androidapp.DataInteraction.Processing.UserProcessing.*; public class ForgotPasswordNewPasswordActivity extends AppCompatActivity { private String username; private EditText passwordInput; private EditText passwordVerifyInput; private AccountJSONProcessor processor = AccountJSONProcessor.getInstance(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_forgot_change_password); username = getIntent().getStringExtra("username"); } public void onChangePasswordButtonClick(View view) { passwordInput = findViewById(R.id.change_password); passwordVerifyInput = findViewById(R.id.change_password_verify); String password = passwordInput.getText().toString(); String passwordVerify = passwordVerifyInput.getText().toString(); if (!password.equals(passwordVerify)) { Toast.makeText(getApplicationContext(), "Passwords do not match.", Toast.LENGTH_LONG).show(); return; } if (!passwordWorks(password)) { Toast.makeText(getApplicationContext(), "Please enter a viable password.", Toast.LENGTH_LONG).show(); return; } // If everything works: processor.changePassword(processor.getIdFromUsername(username), password); Toast.makeText(getApplicationContext(), "Your password has been changed. You may now log in.", Toast.LENGTH_LONG).show(); Intent i = new Intent(this, LoginActivity.class); startActivity(i); } public boolean passwordWorks(String pass) { if (pass.length() < 6) { return false; } return true; } }
package au.gov.nsw.records.digitalarchive.struts.action; import gov.loc.repository.pairtree.Pairtree; import java.io.File; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DownloadAction; import au.gov.nsw.records.digitalarchive.ORM.UploadedFile; import au.gov.nsw.records.digitalarchive.service.FileService; import au.gov.nsw.records.digitalarchive.service.FileServiceImpl; public class FileDownloadAction extends DownloadAction{ @Override protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String id = request.getParameter("id"); Pairtree pt = new Pairtree(); UploadedFile uploadedFile = new UploadedFile(); FileService fs = new FileServiceImpl(); uploadedFile = fs.loadFile(Integer.parseInt(id)); //String filename= "c:/pairtree/" + pt.mapToPPath(uploadedFile.getUid().trim()) + "/" + uploadedFile.getFileName(); String filename= uploadedFile.getInboxUrl().trim(); System.out.println("File name:" + filename); response.setHeader("Content-disposition","attachment; filename=" + uploadedFile.getFileName().trim().replace(" ", "_")); String contentType = uploadedFile.getContentType(); return new FileStreamInfo(contentType, new File(filename)); } }
package designPatternCreational.observer; /** * Created by RENT on 2017-03-27. */ public class ObservatorMain { public static void main(String[] args) { Customer customer1 = new Customer("Adam Kowalski"); Customer customer2 = new Customer("Piotr Adamksi"); Shop shop = new Shop(); shop.registerObservator(customer1); shop.registerObservator(customer2); shop.discount(); } }
package app.prueba.caso_android.dropbox; import android.app.Activity; import android.util.Log; import app.prueba.caso_android.util.Constants; public class DBoxConnectionFactory { private static IDBoxConnection conn=null; /** * Metodo en el que llamamos a la interfaz de dropbox y la inicializamos * Para probar en test mode devolvemos un objeto TestDBox * @param applicationContext * @param login * @param pwd * @return */ public static IDBoxConnection initConnection (Activity applicationContext,String login, String pwd){ //Podemos implementar la aplicacion con otro interfaz que no sea dropbox si implementa IDBoxConnection //return new TestDBox(); try{ conn= new DBoxConnection(applicationContext,Constants.APP_KEY,Constants.APP_SECRET); }catch(Exception e){ Log.e("DBox", "No se pudo inicializar la conexion "+e.getMessage()); } return conn; } public static IDBoxConnection getConnection(){ return conn; } }
package com.imagsky.v81j.domain; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; import com.google.gson.annotations.Expose; import com.imagsky.v81j.domain.SysObject; @Entity @Table(name = "tb8_formfield") @Inheritance(strategy = InheritanceType.JOINED) @PrimaryKeyJoinColumn(name = "SYS_GUID", referencedColumnName = "SYS_GUID") public class FormField extends SysObject { private static final long serialVersionUID = 1L; //private Form form; @Column(name="FIELD_LABEL") @Expose private String formfield_label; @Column(name="FIELD_DISPLAY_ORDER") @Expose private Integer formfield_displayorder; @JoinColumn(name="FORM_ID") private ModForm form; @Column(name="FIELD_TYPE_CODE") @Expose private Integer formfield_type_code; public FormField(){} public FormField(String label, Integer displayOrder){ formfield_label = label; formfield_displayorder = displayOrder; } public String getFormfield_label() { return formfield_label; } public void setFormfield_label(String formfield_label) { this.formfield_label = formfield_label; } public Integer getFormfield_displayorder() { return formfield_displayorder; } public void setFormfield_displayorder(Integer formfield_displayorder) { this.formfield_displayorder = formfield_displayorder; } public Integer getFormfield_type_code() { return formfield_type_code; } public void setFormfield_type_code(Integer formfield_code) { this.formfield_type_code = formfield_code; } public ModForm getForm() { return form; } public void setForm(ModForm form) { this.form = form; } public static List getWildFields() { List returnList = new ArrayList(); returnList.add("FIELD_LABEL"); return returnList; } public static TreeMap<String, Object> getFields(Object thisObj) { TreeMap<String, Object> aHt = new TreeMap<String, Object>(); if (FormField.class.isInstance(thisObj)) { FormField obj = (FormField) thisObj; aHt.put("FIELD_LABEL", obj.formfield_label); aHt.put("FIELD_DISPLAY_ORDER", obj.formfield_displayorder); aHt.put("FORM_ID", obj.form); aHt.put("FIELD_TYPE_CODE", obj.formfield_type_code); aHt.putAll(SysObject.getSysFields(obj)); } return aHt; } }
package com.company.dao; import com.company.entities.Client; import java.io.IOException; import java.util.ArrayList; import java.util.List; public interface IClientDao { void saveClient(Client client); List<Client> getListOfClients() throws IOException; void update(Client client) throws Exception; }
package com.alibaba.druid.bvt.proxy; import java.sql.Connection; import java.sql.DriverManager; import java.util.Map; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.druid.proxy.jdbc.JdbcParameter; import com.alibaba.druid.proxy.jdbc.PreparedStatementProxy; import com.alibaba.druid.util.JdbcUtils; public class PreparedStatementProxyImplGetParametersTest extends TestCase { private String url = "jdbc:wrap-jdbc:filters=default:name=driverTest:jdbc:mock:xxx"; private Connection conn; protected void setUp() throws Exception { conn = DriverManager.getConnection(url); } protected void tearDown() throws Exception { JdbcUtils.close(conn); } public void test_get_parameters() throws Exception { final PreparedStatementProxy stmt = (PreparedStatementProxy) conn.prepareStatement("select 1"); { Map<Integer, JdbcParameter> paramMap = stmt.getParameters(); Assert.assertNotNull(paramMap); Assert.assertEquals(paramMap.size(), 0); } stmt.setInt(1, 1); { Map<Integer, JdbcParameter> paramMap1 = stmt.getParameters(); Assert.assertNotNull(paramMap1); Map<Integer, JdbcParameter> paramMap2 = stmt.getParameters(); Assert.assertNotNull(paramMap2); Assert.assertSame(paramMap1, paramMap2); Assert.assertEquals(paramMap1.size(), 1); } stmt.close(); } }
package com.example.storage; import com.example.model.Resume; import java.util.ArrayList; import java.util.List; public class ListStorage extends AbstractStorage { private static ArrayList<Resume> storage = new ArrayList<>(); @Override protected void doSave(Resume r, Object key) { storage.add(r); } @Override protected Resume doGet(Object key) { return storage.get((int) key); } @Override protected void doDelete(Object key) { storage.remove((int)key); } @Override protected void doUpdate(Resume resume, Object key) { storage.set((int)key, resume); } @Override protected boolean isExist(Object searchKey) { return (int) searchKey > -1; } @Override protected Object getSearchKey(String uuid) { for (int i = 0; i < storage.size(); i++) { if (storage.get(i).getUuid().equals(uuid)) { return i; } } return -1; } @Override public void clear() { storage.clear(); } @Override public List<Resume> getAll() { return storage; } @Override public int size() { return storage.size(); } }
package cn.bakon.connector; import static org.junit.Assert.*; import org.junit.Test; import cn.bakon.connector.Response.AlarmQuery; import cn.bakon.connector.Response.AlarmSetting; import cn.bakon.connector.Response.AlarmSwitch; import cn.bakon.connector.Response.GroundLevelQuery; import cn.bakon.connector.Response.Password; import cn.bakon.connector.Response.Voltage1Query; import cn.bakon.connector.Response.Voltage2Query; import cn.bakon.connector.Response.Voltage3Query; import io.netty.buffer.ByteBuf; public class ResponseTest { @Test public void AlarmSetting_test() { AlarmSetting response = new AlarmSetting(FeatureType.A, true, 100); ByteBuf buf = response.getBytes(); AlarmSetting response2 = (AlarmSetting) Response.parse(buf); assertEquals(response.getFeatureType(), response2.getFeatureType()); assertEquals(response.getError(), response2.getError()); assertEquals(response.getThreshold(), response2.getThreshold()); } @Test public void AlarmSwitch_test() { AlarmSwitch response = new AlarmSwitch(FeatureType.A, true, true); ByteBuf buf = response.getBytes(); AlarmSwitch response2 = (AlarmSwitch) Response.parse(buf); assertEquals(response.getFeatureType(), response2.getFeatureType()); assertEquals(response.getError(), response2.getError()); assertEquals(response.getEnabled(), response2.getEnabled()); } @Test public void Password_test() { Password response = new Password(FeatureType.A, true, 1, 2, 3); ByteBuf buf = response.getBytes(); Password response2 = (Password) Response.parse(buf); assertEquals(response.getFeatureType(), response2.getFeatureType()); assertEquals(response.getError(), response2.getError()); assertEquals(response.getNumber1(), response2.getNumber1()); assertEquals(response.getNumber2(), response2.getNumber2()); assertEquals(response.getNumber3(), response2.getNumber3()); } @Test public void GroundLevelQuery_test() { GroundLevelQuery response = new GroundLevelQuery(FeatureType.A, true, true); ByteBuf buf = response.getBytes(); GroundLevelQuery response2 = (GroundLevelQuery) Response.parse(buf); assertEquals(response.getFeatureType(), response2.getFeatureType()); assertEquals(response.getError(), response2.getError()); assertEquals(response.getHighOrLow(), response2.getHighOrLow()); } @Test public void AlarmQuery_test() { AlarmQuery response = new AlarmQuery(FeatureType.A, true, 1); ByteBuf buf = response.getBytes(); AlarmQuery response2 = (AlarmQuery) Response.parse(buf); assertEquals(response.getFeatureType(), response2.getFeatureType()); assertEquals(response.getError(), response2.getError()); assertEquals(response.getThreshold(), response2.getThreshold()); } @Test public void Voltage1Query_test() { Voltage1Query response = new Voltage1Query(FeatureType.A, true, false, false, 1000); ByteBuf buf = response.getBytes(); Voltage1Query response2 = (Voltage1Query) Response.parse(buf); assertEquals(response.getFeatureType(), response2.getFeatureType()); assertEquals(response.getError(), response2.getError()); assertEquals(response.getClosed(), response2.getClosed()); assertEquals(response.getNegative(), response2.getNegative()); assertEquals(response.getValue(), response2.getValue()); } @Test public void Voltage2Query_test() { Voltage2Query response = new Voltage2Query(FeatureType.A, true, false, true, 1000); ByteBuf buf = response.getBytes(); Voltage2Query response2 = (Voltage2Query) Response.parse(buf); assertEquals(response.getFeatureType(), response2.getFeatureType()); assertEquals(response.getError(), response2.getError()); assertEquals(response.getClosed(), response2.getClosed()); assertEquals(response.getNegative(), response2.getNegative()); assertEquals(response.getValue(), response2.getValue()); } @Test public void Voltage3Query_test() { Voltage3Query response = new Voltage3Query(FeatureType.A, false, true, false, 0); ByteBuf buf = response.getBytes(); Voltage3Query response2 = (Voltage3Query) Response.parse(buf); assertEquals(response.getFeatureType(), response2.getFeatureType()); assertEquals(response.getError(), response2.getError()); assertEquals(response.getClosed(), response2.getClosed()); assertEquals(response.getNegative(), response2.getNegative()); assertEquals(response.getValue(), response2.getValue()); } @Test public void bit_test() { System.out.println(((byte) 2) & 0x0F); byte b = (byte) ((8 << 4) | 9); System.out.println(b); System.out.println(b >> 4); System.out.println(b & 0x0F); System.out.println(0xf000); System.out.println(0x83E8 >> 15); System.out.println((0x83E8 & ~(1 << 15))); System.out.println(0x03E8 | (1 << 15)); System.out.println(100 | (1 << 15)); System.out.println(33768 >> 15); System.out.println((33768 & ~(1 << 15))); System.out.println((1000 | (1 << 15))); System.out.println((short) (-31768 & ~(1 << 15))); System.out.println((short) (1000 | (1 << 15))); System.out.println((int) -31768); } }
import java.util.*; class shaurya { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter the number of terms you want to print"); int n = sc.nextInt(); int x, f; for (x = 1; x <= n; x++) { f = (x * x * x) + (x * 2); System.out.print(f + ","); } } }
package com.raildeliveryservices.burnrubber.tasks; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; import com.raildeliveryservices.burnrubber.Constants; import com.raildeliveryservices.burnrubber.WebServiceConstants; import com.raildeliveryservices.burnrubber.data.Leg; import com.raildeliveryservices.burnrubber.data.LegExtra; import com.raildeliveryservices.burnrubber.data.Order; import com.raildeliveryservices.burnrubber.utils.Utils; import com.raildeliveryservices.burnrubber.utils.WebPost; import org.json.JSONArray; import org.json.JSONObject; import java.util.Date; public class DownloadOrdersServiceAsyncTask extends AsyncTask<Void, Void, Void> { private static final String LOG_TAG = DownloadOrdersServiceAsyncTask.class.getSimpleName(); private Context _context; private SharedPreferences _settings; public DownloadOrdersServiceAsyncTask(Context context) { _context = context; } @Override protected Void doInBackground(Void... arg0) { _settings = _context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); downloadOrders(); return null; } private void downloadOrders() { String lastUpdateDateTime = _settings.getString(Constants.SETTINGS_LAST_UPDATE_DATE_TIME_ORDERS + "-" + Utils.getDriverNo(_context), "2000-01-01 00:00:00.000"); try { JSONObject requestJson = new JSONObject(); requestJson.accumulate(WebServiceConstants.FIELD_DRIVER_NO, Utils.getDriverNo(_context)); requestJson.accumulate(WebServiceConstants.FIELD_LAST_UPDATE_DATE_TIME_ORDERS, lastUpdateDateTime); WebPost webPost = new WebPost(WebServiceConstants.URL_GET_ORDERS); webPost.setJson(requestJson.toString()); JSONObject responseJson = webPost.Post(); saveOrders(responseJson.getJSONArray("Orders")); String dateTime = Constants.ServerDateFormat.format(new Date()); _settings.edit().putString(Constants.SETTINGS_LAST_UPDATE_DATE_TIME_ORDERS + "-" + Utils.getDriverNo(_context), dateTime).commit(); Log.d(LOG_TAG, responseJson.toString()); } catch (Exception e) { Log.e(LOG_TAG, e.getMessage()); } } private void saveOrders(JSONArray orderArray) { Uri uri = Order.CONTENT_URI; for (int i = 0; i < orderArray.length(); i++) { try { JSONObject orderObject = orderArray.getJSONObject(i); ContentValues values = new ContentValues(); values.put(Order.Columns.FILE_NO, orderObject.getInt("FileNo")); values.put(Order.Columns.PARENT_FILE_NO, orderObject.getInt("ParentFileNo")); values.put(Order.Columns.DRIVER_NO, orderObject.getInt("DriverNo")); values.put(Order.Columns.VOYAGE_NO, orderObject.getString("VoyageNo")); values.put(Order.Columns.TRIP_NO, orderObject.getString("TripNo")); values.put(Order.Columns.HAZMAT_FLAG, orderObject.getBoolean("HazmatFlag")); // show only the date portion String tempDate = orderObject.getString("AppointmentDateTime").substring(0, 10); values.put(Order.Columns.APPT_DATE_TIME, tempDate); values.put(Order.Columns.APPT_TIME, orderObject.getString("AppointmentTime")); values.put(Order.Columns.MOVE_TYPE, orderObject.getString("MoveType")); values.put(Order.Columns.CONTAINER_NO, orderObject.getString("ContainerNo")); values.put(Order.Columns.CHASSIS_NO, orderObject.getString("ChassisNo")); values.put(Order.Columns.LUMPER_FLAG, orderObject.getBoolean("LumperFlag") ? 1 : 0); values.put(Order.Columns.SCALE_FLAG, orderObject.getBoolean("ScaleFlag") ? 1 : 0); values.put(Order.Columns.WEIGHT_FLAG, orderObject.getBoolean("WeightFlag") ? 1 : 0); values.put(Order.Columns.CONFIRMED_FLAG, 0); values.put(Order.Columns.STARTED_FLAG, 0); values.put(Order.Columns.COMPLETED_FLAG, 0); int fileNo = orderObject.getInt("FileNo"); long orderId = orderExists(fileNo); if (orderId > 0) { uri = Uri.withAppendedPath(uri, String.valueOf(orderId)); _context.getContentResolver().update(uri, values, null, null); } else { Uri returnUri = _context.getContentResolver().insert(uri, values); orderId = Long.parseLong(returnUri.getLastPathSegment()); } saveLegs(orderId, fileNo, orderObject.getJSONArray("Legs")); } catch (Exception e) { Log.e(LOG_TAG, e.getMessage()); } } } private void saveLegs(long orderId, int fileNo, JSONArray legArray) { Uri uri = Leg.CONTENT_URI; try { for (int i = 0; i < legArray.length(); i++) { JSONObject legObject = legArray.getJSONObject(i); int legNo = legObject.getInt("LegNo"); ContentValues values = new ContentValues(); values.put(Leg.Columns.FILE_NO, fileNo); values.put(Leg.Columns.LEG_NO, legNo); values.put(Leg.Columns.PARENT_LEG_NO, legObject.getInt("ParentLegNo")); values.put(Leg.Columns.COMPANY_NAME_FROM, legObject.getString("CompanyNameFrom")); values.put(Leg.Columns.ADDRESS_FROM, legObject.getString("AddressFrom")); values.put(Leg.Columns.CITY_FROM, legObject.getString("CityFrom")); values.put(Leg.Columns.STATE_FROM, legObject.getString("StateFrom")); values.put(Leg.Columns.ZIP_CODE_FROM, legObject.getString("ZipCodeFrom")); values.put(Leg.Columns.COMPANY_NAME_TO, legObject.getString("CompanyNameTo")); values.put(Leg.Columns.ADDRESS_TO, legObject.getString("AddressTo")); values.put(Leg.Columns.CITY_TO, legObject.getString("CityTo")); values.put(Leg.Columns.STATE_TO, legObject.getString("StateTo")); values.put(Leg.Columns.ZIP_CODE_TO, legObject.getString("ZipCodeTo")); values.put(Leg.Columns.COUNT_FLAG, legObject.getBoolean("CountFlag") ? 1 : 0); values.put(Leg.Columns.WEIGHT_FLAG, legObject.getBoolean("WeightFlag") ? 1 : 0); values.put(Leg.Columns.OUTBOUND_FLAG, legObject.getBoolean("OutboundFlag") ? 1 : 0); long legId = legExists(fileNo, legNo); if (legId > 0) { uri = Uri.withAppendedPath(uri, String.valueOf(legId)); _context.getContentResolver().update(uri, values, null, null); } else { values.put(Leg.Columns.ORDER_ID, orderId); values.put(Leg.Columns.COMPLETED_FLAG, 0); Uri returnUri = _context.getContentResolver().insert(uri, values); legId = Long.parseLong(returnUri.getLastPathSegment()); } saveLegExtras(legId, fileNo, legNo, legObject.getJSONArray("LegExtras")); } } catch (Exception e) { Log.e(LOG_TAG, e.getMessage()); } } private void saveLegExtras(long legId, int fileNo, int legNo, JSONArray legExtraArray) { deleteLegExtras(legId); Uri uri = LegExtra.CONTENT_URI; try { for (int i = 0; i < legExtraArray.length(); i++) { JSONObject legExtraObject = legExtraArray.getJSONObject(i); ContentValues values = new ContentValues(); values.put(LegExtra.Columns.LEG_ID, legId); values.put(LegExtra.Columns.FILE_NO, fileNo); values.put(LegExtra.Columns.LEG_NO, legNo); values.put(LegExtra.Columns.LEG_PART, legExtraObject.getString("LegPart")); values.put(LegExtra.Columns.EXTRA, legExtraObject.getString("Extra")); _context.getContentResolver().insert(uri, values); } } catch (Exception e) { Log.e(LOG_TAG, e.getMessage()); } } private long orderExists(int fileNo) { Uri uri = Order.CONTENT_URI; String[] projection = {Order.Columns._ID, Order.Columns.FILE_NO}; String selection = Order.Columns.FILE_NO + " = " + String.valueOf(fileNo); Cursor cursor = _context.getContentResolver().query(uri, projection, selection, null, null); if (cursor.getCount() > 0) { return cursor.getLong(cursor.getColumnIndex(Order.Columns._ID)); } else { return 0; } } private long legExists(int fileNo, int legNo) { Uri uri = Leg.CONTENT_URI; String[] projection = {Leg.Columns._ID}; String selection = Leg.Columns.FILE_NO + " = " + String.valueOf(fileNo) + " and " + Leg.Columns.LEG_NO + " = " + String.valueOf(legNo); Cursor cursor = _context.getContentResolver().query(uri, projection, selection, null, null); if (cursor.getCount() > 0) { return cursor.getLong(cursor.getColumnIndex(Leg.Columns._ID)); } else { return 0; } } private void deleteLegExtras(long legId) { Uri uri = LegExtra.CONTENT_URI; String where = LegExtra.Columns.LEG_ID + " = " + legId; _context.getContentResolver().delete(uri, where, null); } }
package com.atlassian.theplugin.jira.model; import com.atlassian.connector.cfg.ProjectCfgManager; import com.atlassian.connector.commons.jira.beans.JIRAProject; import com.atlassian.connector.commons.jira.beans.JIRASavedFilter; import com.atlassian.theplugin.commons.cfg.ServerId; import com.atlassian.theplugin.commons.jira.JiraServerData; import com.atlassian.theplugin.configuration.JiraWorkspaceConfiguration; import com.atlassian.theplugin.idea.IdeaHelper; import com.atlassian.theplugin.jira.model.presetfilters.AddedRecentlyPresetFilter; import com.atlassian.theplugin.jira.model.presetfilters.AssignedToMePresetFilter; import com.atlassian.theplugin.jira.model.presetfilters.MostImportantPresetFilter; import com.atlassian.theplugin.jira.model.presetfilters.OutstandingPresetFilter; import com.atlassian.theplugin.jira.model.presetfilters.ReportedByMePresetFilter; import com.atlassian.theplugin.jira.model.presetfilters.ResolvedRecentlyPresetFilter; import com.atlassian.theplugin.jira.model.presetfilters.UnscheduledPresetFilter; import com.atlassian.theplugin.jira.model.presetfilters.UpdatedRecentlyPresetFilter; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * User: pmaruszak */ public class JIRAFilterListModel implements FrozenModel { private final ProjectCfgManager projectCfgManager; public JIRAFilterListModel(ProjectCfgManager projectCfgManager) { this.projectCfgManager = projectCfgManager; } private Map<ServerId, JIRAServerFiltersBean> serversFilters = new HashMap<ServerId, JIRAServerFiltersBean>(); private List<JIRAFilterListModelListener> listeners = new ArrayList<JIRAFilterListModelListener>(); private List<FrozenModelListener> frozenModelListeners = new ArrayList<FrozenModelListener>(); private boolean modelFrozen = false; public void setSavedFilters(final JiraServerData jiraServerData, @NotNull final List<JIRASavedFilter> filters) { if (serversFilters.containsKey(jiraServerData.getServerId())) { serversFilters.get(jiraServerData.getServerId()).setSavedFilters(filters); } else { JIRAServerFiltersBean serverFilters = new JIRAServerFiltersBean(); serverFilters.setSavedFilters(filters); serversFilters.put(jiraServerData.getServerId(), serverFilters); } } public void clearManualFilter(final JiraServerData jiraServerData, final JiraCustomFilter filter) { if (serversFilters.containsKey(jiraServerData.getServerId()) && serversFilters.get(jiraServerData.getServerId()).getManualFilters().contains(filter)) { for (JiraCustomFilter f : serversFilters.get(jiraServerData.getServerId()).getManualFilters()) { if (filter.equals(f)) { f.getQueryFragments().clear(); } } } } public void addManualFilter(final JiraServerData jiraServerData, @NotNull final JiraCustomFilter filter) { if (serversFilters.containsKey(jiraServerData.getServerId())) { serversFilters.get(jiraServerData.getServerId()).getManualFilters().add(filter); } else { JIRAServerFiltersBean serverFilters = new JIRAServerFiltersBean(); serverFilters.getManualFilters().add(filter); serversFilters.put(jiraServerData.getServerId(), serverFilters); } } public List<JiraServerData> getJIRAServers() { List<JiraServerData> servers = new ArrayList<JiraServerData>(); if (projectCfgManager != null) { for (ServerId id : serversFilters.keySet()) { final JiraServerData jiraServer = projectCfgManager.getJiraServerr(id); if (jiraServer != null) { servers.add(jiraServer); } } } return servers; } public List<JIRASavedFilter> getSavedFilters(final JiraServerData jiraServerData) { if (serversFilters.containsKey(jiraServerData.getServerId())) { return serversFilters.get(jiraServerData.getServerId()).getSavedFilters(); } return null; } public Set<JiraCustomFilter> getManualFilters(final JiraServerData jiraServerData) { if (serversFilters.containsKey(jiraServerData.getServerId())) { return serversFilters.get(jiraServerData.getServerId()).getManualFilters(); } return null; } public Collection<JiraPresetFilter> getPresetFilters(Project project, JiraServerData jiraServer) { List<JiraPresetFilter> list = new ArrayList<JiraPresetFilter>(); final JiraWorkspaceConfiguration workspace = IdeaHelper.getJiraWorkspaceConfiguration(project); // list.add(new AllPresetFilter(projectCfgManager, jiraServer)); list.add(new OutstandingPresetFilter(projectCfgManager, jiraServer)); list.add(new UnscheduledPresetFilter(projectCfgManager, jiraServer)); list.add(new AssignedToMePresetFilter(projectCfgManager, jiraServer)); list.add(new ReportedByMePresetFilter(projectCfgManager, jiraServer)); list.add(new ResolvedRecentlyPresetFilter(projectCfgManager, jiraServer)); list.add(new AddedRecentlyPresetFilter(projectCfgManager, jiraServer)); list.add(new UpdatedRecentlyPresetFilter(projectCfgManager, jiraServer)); list.add(new MostImportantPresetFilter(projectCfgManager, jiraServer)); //set stored by user assigned project for each preset filter for (JiraPresetFilter filter : list) { if (workspace != null) { JIRAProject jiraProject = workspace.getPresetFilterProject(jiraServer, filter); if (jiraProject != null) { filter.setJiraProject(jiraProject); } } } return list; } public void fireModelChanged() { for (JIRAFilterListModelListener listener : listeners) { listener.modelChanged(this); } } public void fireServerRemoved() { for (JIRAFilterListModelListener listener : listeners) { listener.serverRemoved(this); } } public void fireServerAdded() { for (JIRAFilterListModelListener listener : listeners) { listener.serverAdded(this); } } public void fireServerNameChanged() { for (JIRAFilterListModelListener listener : listeners) { listener.serverNameChanged(this); } } public void fireManualFilterChanged(final JiraCustomFilter manualFilter, final JiraServerData jiraServerData) { for (JIRAFilterListModelListener listener : listeners) { listener.manualFilterChanged(manualFilter, jiraServerData); } } public void fireManualFilterAdded(final JiraCustomFilter filter, final JiraServerData jiraServerData) { for (JIRAFilterListModelListener listener : listeners) { listener.manualFilterAdded(this, filter, jiraServerData.getServerId()); } } public void fireManualFilterRemoved(final JiraCustomFilter filter, final JiraServerData jiraServer) { for (JIRAFilterListModelListener listener : listeners) { listener.manualFilterRemoved(this, filter, jiraServer.getServerId()); } } public void addModelListener(JIRAFilterListModelListener listener) { listeners.add(listener); } public void removeModelListener(JIRAFilterListModelListener listener) { listeners.remove(listener); } public void clearAllServerFilters() { serversFilters.clear(); } public boolean isModelFrozen() { return this.modelFrozen; } public void setModelFrozen(boolean frozen) { this.modelFrozen = frozen; fireModelFrozen(); } public void addFrozenModelListener(FrozenModelListener listener) { frozenModelListeners.add(listener); } public void removeFrozenModelListener(FrozenModelListener listener) { frozenModelListeners.remove(listener); } private void fireModelFrozen() { for (FrozenModelListener listener : frozenModelListeners) { listener.modelFrozen(this, this.modelFrozen); } } public void removeManualFilter(JiraServerData jiraServerData, JiraCustomFilter filter) { JiraCustomFilter filterToRemove = null; if (serversFilters.containsKey(jiraServerData.getServerId())) { serversFilters.get(jiraServerData.getServerId()).getManualFilters().remove(filter); } } public void setManualFilters(JiraServerData jiraServerData, Set<JiraCustomFilter> manualFilters) { for (JiraCustomFilter filter : manualFilters) { addManualFilter(jiraServerData, filter); } } }
package _11_stack_queue.convert_binary; import java.util.Scanner; import java.util.Stack; public class ConvertBinary { public String convertNumber(int decimal, int radix) { Stack<Integer> stack = new Stack<>(); while (decimal != 0) { stack.push(decimal % radix); decimal = decimal / radix; } String result = ""; while (!stack.isEmpty()) { if (radix == 16) { result += convertToHexa(stack.pop()); }else { result += stack.pop(); } } return result; } public String convertToHexa(int number) { String str = ""; if (number > 15) { str += number; } else { switch (number) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: str += number; break; case 10: str = "A"; break; case 11: str = "B"; break; case 12: str = "C"; break; case 13: str = "D"; break; case 14: str = "E"; break; case 15: str = "F"; break; } } return str; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap so nguyen: "); int inputDecimal = scanner.nextInt(); System.out.println(Integer.toBinaryString(inputDecimal)); System.out.println(Integer.toHexString(inputDecimal)); ConvertBinary convertBinary = new ConvertBinary(); System.out.println(convertBinary.convertNumber(inputDecimal, 2)); System.out.println(convertBinary.convertNumber(inputDecimal, 16)); } }
package br.com.ecommerceabc.aplicacao; import br.com.ecommerceabc.modelo.Pessoa; import br.com.ecommerceabc.modelo.Endereco; public class TesteCliente { public static void main(String[] args) { Pessoa cliente = new Pessoa(); cliente.setId(1); cliente.setNome("Xpto"); cliente.setEmail("xpto@gama.com.br"); Endereco endereco = new Endereco (); cliente.setEndereco(endereco); endereco.setLogradouro("Aenida Itaquera"); endereco.setBairro("Itaquera"); endereco.setCidade("São Paulo"); endereco.setCep("12345-123"); endereco.setComplemento("Viela 456"); endereco.setNumero("77"); endereco.setUf("SP"); System.out.println(cliente.toString()); } }
package com.wm.intro.type; public enum IndicatorTwoType { NONE, COLOR, SCALE, WORM, SLIDE, FILL, THIN_WORM, DROP, SWAP, SCALE_DOWN; public static IndicatorTwoType getType(String type) { switch (type) { case "COLOR": return COLOR; case "SCALE": return SCALE; case "WORM": return WORM; case "SLIDE": return SLIDE; case "FILL": return FILL; case "THIN_WORM": return THIN_WORM; case "DROP": return DROP; case "SWAP": return SWAP; case "SCALE_DOWN": return SCALE_DOWN; default: return NONE; } } }
package com.sunny.jmh.serializertest.bean; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; /** * <Description> <br> * * @author Sunny<br> * @version 1.0<br> * @taskId: <br> * @createDate 2018/12/05 0:30 <br> * @see com.sunny.jmh.serializertest.bean <br> */ @Data @NoArgsConstructor public class Person implements Serializable { private int age; private String name; public Person(int age, String name) { this.age = age; this.name = name; } }
package styleomega.cb006456.styleomega; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ListView; import java.util.ArrayList; import styleomega.cb006456.styleomega.Adapters.CartListAdapter; import styleomega.cb006456.styleomega.Adapters.ProductListAdapter; import styleomega.cb006456.styleomega.Model.Cart; import styleomega.cb006456.styleomega.Model.Product; public class CartActivity extends AppCompatActivity { SQLiteHelper sqLiteHelper; ListView list; private static String TAG = CartActivity.class.getSimpleName(); Cart cart; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cart); sqLiteHelper = new SQLiteHelper(this); list = (ListView) findViewById(R.id.cart_list); cart = sqLiteHelper.getCartData(getIntent().getStringExtra("emailholder")); if(cart.getProducts().size()>0)Log.d(TAG, "onCreate: " +cart.getProducts().keySet().size()+ ((Product)cart.getProducts().keySet().toArray()[0]).getName()); CartListAdapter ListAdpater = new CartListAdapter(this, R.layout.cart_list_item, cart); list.setAdapter(ListAdpater); } public void onCheckout(View view) { Intent intent = new Intent(this, CheckoutActivity.class); sqLiteHelper.removeAllFromCart(cart.getUsername()); intent.putExtra("total",cart.getTotal()); startActivity(intent); } }
package com.mabang.android.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.mabang.android.R; import com.mabang.android.entity.vo.BillboardInfo; import com.mabang.android.utils.AppUtils; import walke.base.tool.SpannableUtil; /** * Created by walke on 2018/2/3. * email:1032458982@qq.com */ public class AdDetailsView extends LinearLayout { private View lineBottom; private TextView tvAddress, tvAdManageCode,tvAdDetails,tvAdUniqueCode; private TextTextView ttvCompany,ttvDetailsAddress,ttvFacilitySituation,ttvAdSituation,ttvSpecification,ttvRemark; public AdDetailsView(Context context) { this(context,null); } public AdDetailsView(Context context, AttributeSet attrs) { this(context, attrs,0); } public AdDetailsView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); LayoutInflater.from(context).inflate(R.layout.view_ad_details, this); tvAddress = ((TextView) findViewById(R.id.vad_tvAddress));//头部地址 tvAdManageCode = ((TextView) findViewById(R.id.vad_tvAdManageCode));//编号行使用SpanableString tvAdUniqueCode = ((TextView) findViewById(R.id.vad_tvAdUniqueCode));//编号行使用SpanableString ttvCompany = ((TextTextView) findViewById(R.id.vad_ttvCompany));//广告使用 ttvDetailsAddress = ((TextTextView) findViewById(R.id.vad_ttvDetailsAddress));//详细地址 ttvFacilitySituation = ((TextTextView) findViewById(R.id.vad_ttvFacilitySituation));//雨棚材质 ttvAdSituation = ((TextTextView) findViewById(R.id.vad_ttvAdSituation));//广告状态 ttvSpecification = ((TextTextView) findViewById(R.id.vad_ttvSpecification));//规格 ttvRemark = ((TextTextView) findViewById(R.id.vad_ttvRemark));//备注 lineBottom = findViewById(R.id.vad_lineBottom); lineBottom.setVisibility(GONE); TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.AdDetailsView, defStyleAttr, 0); int n = a.getIndexCount(); for (int i = 0; i < n; i++) { int attr = a.getIndex(i); if (attr == R.styleable.AdDetailsView_showBottom) { boolean isShowBottom = a.getBoolean(attr, true); if (isShowBottom){ lineBottom.setVisibility(VISIBLE); }else { lineBottom.setVisibility(GONE); } } } a.recycle(); } public TextView getTvAddress() { return tvAddress; } public TextView getTvAdManageCode() { return tvAdManageCode; } public TextView getTvAdDetails() { return tvAdDetails; } public void setViewByData(BillboardInfo billboardInfo){ // tvAddress.setText(billboardInfo.getShortName()+""); tvAddress.setText(AppUtils.textReplace(billboardInfo.getShortName(),"")); // SpannableUtil.spannableTwoColor(tvAdManageCode, "管理编号:", billboardInfo.getManageCode()+"", " 唯一码:", billboardInfo.getUniqueCode()+"", "", Color.parseColor("#ffaaaaaa")); SpannableUtil.spannableOneColor(tvAdManageCode,"管理编号:", // billboardInfo.getManageCode()+"", AppUtils.textReplace(billboardInfo.getManageCode(),""), "",Color.parseColor("#ffaaaaaa")); SpannableUtil.spannableOneColor(tvAdUniqueCode,"唯一码:", // billboardInfo.getUniqueCode()+"", AppUtils.textReplace(billboardInfo.getUniqueCode(),""), "",Color.parseColor("#ffaaaaaa")); if (TextUtils.isEmpty(billboardInfo.getStatusDesc())){ ttvCompany.setVisibility(GONE); }else { ttvCompany.getTvDesc().setText(billboardInfo.getStatusDesc());//广告使用 } // ttvAdSituation.getTvDesc().setText(billboardInfo.getStatusText()+"");//广告状态 ttvAdSituation.getTvDesc().setText(AppUtils.textReplace(billboardInfo.getStatusText(),""));//广告状态 // ttvDetailsAddress.getTvDesc().setText(""+billboardInfo.getLongAddress());//详细地址 ttvDetailsAddress.getTvDesc().setText(AppUtils.textReplace(billboardInfo.getLongAddress(),""));//详细地址 // ttvFacilitySituation.getTvDesc().setText(""+billboardInfo.getShedMaterial());//雨棚材质 ttvFacilitySituation.getTvDesc().setText(AppUtils.textReplace(billboardInfo.getShedMaterial(),""));//雨棚材质 // ttvSpecification.getTvDesc().setText(""+billboardInfo.getSpec());//规格 ttvSpecification.getTvDesc().setText(AppUtils.textReplace(billboardInfo.getSpec(),""));//规格 ttvRemark.getTvDesc().setText(AppUtils.textReplace(billboardInfo.getOtherDescribe(),"无"));//备注 } }
package co.company.spring.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import co.company.spring.dao.Emp; import co.company.spring.dao.EmpMapper; import co.company.spring.dao.EmpSearch; @RestController public class EmpRestController { @Autowired EmpMapper dao; @RequestMapping("/ajax/empSelect") public List<Emp> empSelect(EmpSearch emp){ return dao.getEmpList(emp); } }
package model; import static org.junit.Assert.*; import java.awt.Image; import javax.swing.ImageIcon; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * Test class of the class Character * @author Pline * */ public class CharacterTest { final Character rockford = new Character(32, 32, 64, 128); @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } /** * test of getWidth() */ @Test public void testGetWidth() { final int expected = 32; assertEquals(expected, rockford.getWidth()); //fail("Not yet implemented"); } /** * test of setWidth() */ @Test public void testSetWidth() { final int expected =64; rockford.setWidth(expected);; assertEquals(expected, rockford.getWidth()); // fail("Not yet implemented"); } /** * test of getHeight() */ @Test public void testGetHeight() { final int expected = 32; assertEquals(expected, rockford.getHeight()); // fail("Not yet implemented"); } /** * test of setHeight() */ @Test public void testSetHeight() { final int expected =64; rockford.setHeight(expected); assertEquals(expected, rockford.getHeight()); // fail("Not yet implemented"); } /** * test of getX() */ @Test public void testGetX() { final int expected = 64; assertEquals(expected, rockford.getX()); // fail("Not yet implemented"); } /** * test of setX() */ @Test public void testSetX() { final int expected =64; rockford.setX(expected); assertEquals(expected, rockford.getX()); // fail("Not yet implemented"); } @Test public void testGetY() { final int expected = 128; assertEquals(expected, rockford.getY()); // fail("Not yet implemented"); } /** * test of setY() */ @Test public void testSetY() { final int expected =64; rockford.setY(expected); assertEquals(expected, rockford.getY()); } /** * tes of getImgChar */ @Test public void testGetImgChar() { String str = new String(); if(this.rockford.isMove()==false) {str="/images/persoface2.png";} if(this.rockford.isMove()==true) {str="/images/persoface.png";} final Image expected = new ImageIcon(getClass().getResource(str)).getImage(); assertEquals(expected, rockford.getImgChar()); } /** * tes of setImgChar() */ @Test public void testSetImgChar() { final Image expected = null; rockford.setImgChar(expected); assertEquals(expected, rockford.getImgChar()); } @Test public void testGetCounter() { fail("Not yet implemented"); } @Test public void testSetCounter() { fail("Not yet implemented"); } @Test public void testIsMove() { fail("Not yet implemented"); } /** * tes of the method setMove() */ @Test public void testSetMove() { boolean move = true; rockford.setMove(move); assertEquals(move, rockford.isMove()); } @Test public void testMove() { fail("Not yet implemented"); } }
/** This class loads the logging configuration from the xml defined in src/main/resources and uses the same configuration generated through programmatic configuration as defined in simple-configuration example. **/ package com.baeldung.logging.log4j2.xmlconfiguration; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; import org.junit.Test; public class XMLConfigLogTest { @Test public void simpleProgrammaticConfiguration() { Logger logger = LogManager.getLogger(); Marker markerContent = MarkerManager.getMarker("FLOW"); logger.debug(markerContent, "Debug log message"); logger.info(markerContent, "Info log message"); logger.error(markerContent, "Error log message"); } }
package com.company.exercise; import java.io.*; import java.util.ArrayList; public class Main { public static void main(String[] args) throws FileNotFoundException { readingFile(); printData(); } public static ArrayList<String> dataFromReading = new ArrayList<>(); public static ArrayList<Person> persons = new ArrayList<>(); public static ArrayList<Team> teams = new ArrayList<>(); public static ArrayList<CodecoolClass> classes = new ArrayList<CodecoolClass>(); public static void createObjects() { int i = 0; while (i < (dataFromReading.size())) { if (i%3 == 0) { for (CodecoolClass cclass : classes) { if (cclass.getName().equals(dataFromReading.get(i))) { break; } else { classes.add(new CodecoolClass(dataFromReading.get(i))); } } } else if (i%3 == 1) { for (Team actualteam : teams) { if ( actualteam.getName().equals(dataFromReading.get(i))) { break; } else { teams.add(new Team(dataFromReading.get(i))); } } } else if (i%3 == 2) { for (Person actualPerson : persons) { if (! actualPerson.getName().equals(dataFromReading.get(i))) { break; } else { teams.add(new Team(dataFromReading.get(i))); } } } } } public static void printData() { for (String stringy : dataFromReading) { System.out.println(stringy); } } private static void readingFile() throws FileNotFoundException { // Open the file FileInputStream fstream = null; fstream = new FileInputStream("names.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); String strLine; //Read File Line By Line try { while ((strLine = br.readLine()) != null) { //System.out.println (strLine); for (String retval: strLine.split("/")) { //System.out.println(retval); dataFromReading.add(retval); } } } catch (IOException e) { e.printStackTrace(); } //Close the input stream try { br.close(); } catch (IOException e) { e.printStackTrace(); } } public static void populateData() { Person A = new Person("A"); persons.add(A); Person B = new Person("B"); persons.add(B); Person C = new Person("C"); persons.add(C); Person D = new Person("D"); persons.add(D); Person E = new Person("A"); persons.add(E); Person F = new Person("B"); persons.add(F); Person G = new Person("C"); persons.add(G); Person H = new Person("D"); persons.add(H); Person I = new Person("A"); persons.add(I); Person J = new Person("B"); persons.add(J); Person K = new Person("C"); persons.add(K); Person L = new Person("D"); persons.add(L); Person M = new Person("A"); persons.add(M); Person N = new Person("B"); persons.add(N); Person O = new Person("C"); persons.add(O); Person P = new Person("D"); persons.add(P); Person Q = new Person("A"); persons.add(Q); Person R = new Person("B"); persons.add(R); Person S = new Person("C"); persons.add(S); Person T = new Person("D"); persons.add(T); Person V = new Person("A"); persons.add(V); Person W = new Person("B"); persons.add(W); Person X = new Person("C"); persons.add(X); Person Y = new Person("D"); persons.add(Y); Person Z = new Person("A"); persons.add(Z); Person ZA = new Person("B"); persons.add(ZA); } }
package cn.hrbcu.com.servlet.adminServlet; import cn.hrbcu.com.entity.Books; import cn.hrbcu.com.entity.Institution; import cn.hrbcu.com.service.AdminService; import cn.hrbcu.com.service.BooksService; import cn.hrbcu.com.service.impl.AdminServiceImpl; import cn.hrbcu.com.service.impl.BooksServiceImpl; import org.apache.commons.beanutils.BeanUtils; 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 java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Map; /** * @author: XuYi * @date: 2021/5/26 15:10 * @description: 处理培训机构管理数据的添加控制层 */ @WebServlet("/AddBooksServlet") public class AddBooksServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /*设置编码*/ req.setCharacterEncoding("utf-8"); /*获取参数*/ Map<String, String[]> map = req.getParameterMap(); /*封装对象*/ Books books = new Books(); try{ BeanUtils.populate(books,map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } /*调用服务*/ BooksService booksService = new BooksServiceImpl(); booksService.addBooks(books); /*设置跳转路径*/ String path =req.getContextPath()+"/BooksListServlet"; /*执行跳转*/ resp.sendRedirect(path); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } }
package com.example.caxidy.agendacontactos; import java.io.Serializable; public class Telefono implements Serializable { int idTel, idContacto; String telefono; public Telefono(){ idTel=0; idContacto=0; telefono=""; } public Telefono(int id, String tel, int idC){ idTel=id; idContacto=idC; telefono=tel; } public Telefono(String tel){ idTel=0; idContacto=0; telefono=tel; } public int getId(){return idTel;} public int getIdContacto(){return idContacto;} public String getTelefono(){return telefono;} }
package com.lirong.nacosconsumer.controller; import com.lirong.nacosconsumer.feign.ProviderFeign; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HiController { @Autowired private ProviderFeign providerFeign; @RequestMapping("hi") public String hi() { return "hi=="+providerFeign.hello(); } }
package com.example.lycutter.handlertest; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class InUIThread extends Activity implements View.OnClickListener { private Button btn_thread1; private Button btn_thread2; private Button btn_thread3; private Button btn_thread4; private TextView tv1; private TextView tv2; private TextView tv3; private TextView tv4; private CostumHandler mHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mHandler = new CostumHandler(); btn_thread1 = findViewById(R.id.btn_thread1); btn_thread2 = findViewById(R.id.btn_thread2); btn_thread3 = findViewById(R.id.btn_thread3); btn_thread4 = findViewById(R.id.btn_thread4); tv1 = findViewById(R.id.tv1); tv2 = findViewById(R.id.tv2); tv3 = findViewById(R.id.tv3); tv4 = findViewById(R.id.tv4); btn_thread1.setOnClickListener(this); btn_thread2.setOnClickListener(this); btn_thread3.setOnClickListener(this); btn_thread4.setOnClickListener(this); } // @Override // public void onClick(View v) { // int btn_id = v.getId(); // switch (btn_id) { // case R.id.btn_thread1: { // mHandler = new CostumHandler(); // Message msg = mHandler.obtainMessage(); // msg.what = 1; // msg.obj = new CostumObj("线程1"); // mHandler.sendMessage(msg); // // break; // } // case R.id.btn_thread2: { // mHandler = new CostumHandler(); // Message msg = mHandler.obtainMessage(); // msg.what = 2; // msg.obj = new CostumObj("线程2"); // mHandler.sendMessage(msg); // break; // } // case R.id.btn_thread3: { // mHandler = new CostumHandler(); // Message msg = mHandler.obtainMessage(); // msg.what = 3; // msg.obj = new CostumObj("线程3"); // mHandler.sendMessage(msg); // break; // } // case R.id.btn_thread4: { // mHandler = new CostumHandler(); // Message msg = mHandler.obtainMessage(); // msg.what = 4; // msg.obj = new CostumObj("线程4"); // mHandler.sendMessage(msg); // break; // } // // default: // break; // } // } @Override public void onClick(View v) { int btn_id = v.getId(); switch (btn_id) { case R.id.btn_thread1: { new Thread(new Runnable() { @Override public void run() { CostumObj obj = new CostumObj("线程1"); mHandler.obtainMessage(1, obj).sendToTarget(); System.out.println("主线程id == " + Looper.getMainLooper().getThread().getId()); System.out.println("本线程id == " + Thread.currentThread().getId()); } }).start(); break; } case R.id.btn_thread2: { new Thread(new Runnable() { @Override public void run() { CostumObj obj = new CostumObj("线程2"); mHandler.obtainMessage(2, obj).sendToTarget(); System.out.println("主线程id == " + Looper.getMainLooper().getThread().getId()); System.out.println("本线程id == " + Thread.currentThread().getId()); } }).start(); break; } case R.id.btn_thread3: { new Thread(new Runnable() { @Override public void run() { CostumObj obj = new CostumObj("线程3"); mHandler.obtainMessage(3, obj).sendToTarget(); System.out.println("主线程id == " + Looper.getMainLooper().getThread().getId()); System.out.println("本线程id == " + Thread.currentThread().getId()); } }).start(); break; } case R.id.btn_thread4: { new Thread(new Runnable() { @Override public void run() { CostumObj obj = new CostumObj("线程4"); mHandler.obtainMessage(4, obj).sendToTarget(); System.out.println("主线程id == " + Looper.getMainLooper().getThread().getId()); System.out.println("本线程id == " + Thread.currentThread().getId()); } }).start(); break; } default: break; } } public class CostumHandler extends Handler { @Override public void handleMessage(Message msg) { int what = msg.what; CostumObj costumObj = (CostumObj) msg.obj; String obj = costumObj.obj; switch (what) { case 1: { if (Looper.myLooper() == Looper.getMainLooper()) { System.out.println("myLooper正在UI线程..........."); } else { System.out.println("myLooper不在UI线程.........."); } if (Looper.getMainLooper().getThread().getId() == Thread.currentThread().getId()) { System.out.println("handler运行在主线程, 当前线程id === " + Thread.currentThread().getId() ); } else { System.out.println("handler不是运行在主线程, 当前线程id === " + Thread.currentThread().getId() ); } System.out.println("obj ===== " + obj); tv1.setText("通过Handler更新UI-1"); Toast.makeText(InUIThread.this, "更新线程1", Toast.LENGTH_SHORT).show(); break; } case 2: { if (Looper.myLooper() == Looper.getMainLooper()) { System.out.println("myLooper正在UI线程..........."); } else { System.out.println("myLooper不在UI线程.........."); } if (Looper.getMainLooper().getThread().getId() == Thread.currentThread().getId()) { System.out.println("handler运行在主线程, 当前线程id === " + Thread.currentThread().getId() ); } else { System.out.println("handler不是运行在主线程, 当前线程id === " + Thread.currentThread().getId() ); } System.out.println("obj ===== " + obj); tv2.setText("通过Handler更新UI-2"); Toast.makeText(InUIThread.this, "更新线程2", Toast.LENGTH_SHORT).show(); break; } case 3: { if (Looper.myLooper() == Looper.getMainLooper()) { System.out.println("myLooper正在UI线程..........."); } else { System.out.println("myLooper不在UI线程.........."); } if (Looper.getMainLooper().getThread().getId() == Thread.currentThread().getId()) { System.out.println("handler运行在主线程, 当前线程id === " + Thread.currentThread().getId() ); } else { System.out.println("handler不是运行在主线程, 当前线程id === " + Thread.currentThread().getId() ); } System.out.println("obj ===== " + obj); tv3.setText("通过Handler更新UI-3"); Toast.makeText(InUIThread.this, "更新线程3", Toast.LENGTH_SHORT).show(); break; } case 4: { if (Looper.myLooper() == Looper.getMainLooper()) { System.out.println("myLooper正在UI线程..........."); } else { System.out.println("myLooper不在UI线程.........."); } if (Looper.getMainLooper().getThread().getId() == Thread.currentThread().getId()) { System.out.println("handler运行在主线程, 当前线程id === " + Thread.currentThread().getId() ); } else { System.out.println("handler不是运行在主线程, 当前线程id === " + Thread.currentThread().getId() ); } System.out.println("obj ===== " + obj); tv4.setText("通过Handler更新UI-4"); Toast.makeText(InUIThread.this, "更新线程4", Toast.LENGTH_SHORT).show(); break; } default: break; } } } public class CostumObj { String obj; public CostumObj (String obj) { this.obj = obj; } } }
/** * Copyright (C) 2014-2017 Philip Helger (www.helger.com) * philip[at]helger[dot]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 com.helger.commons.aggregate; import java.util.Collection; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.helger.commons.ValueEnforcer; import com.helger.commons.collection.CollectionHelper; import com.helger.commons.collection.ext.CommonsArrayList; import com.helger.commons.functional.IFunction; import com.helger.commons.string.StringHelper; /** * Aggregate a list of input objects to a single output object (change n to 1). * * @author Philip Helger * @param <SRCTYPE> * The input type. * @param <DSTTYPE> * The output type. */ @FunctionalInterface public interface IAggregator <SRCTYPE, DSTTYPE> extends IFunction <Collection <SRCTYPE>, DSTTYPE> { /** * Aggregate a array of input objects to a single output object. * * @param aObjects * Source object array. May not be <code>null</code>. * @return The aggregated object. May be <code>null</code>. */ @Nullable @SuppressWarnings ("unchecked") // @SafeVarArgs does not work for default methods default DSTTYPE apply (@Nullable final SRCTYPE... aObjects) { return apply (new CommonsArrayList<> (aObjects)); } /** * @return A new aggregator that uses the first element from the provided * collection. Never <code>null</code>. */ @Nonnull static <SRCTYPE> IAggregator <SRCTYPE, SRCTYPE> createUseFirst () { return aCollection -> CollectionHelper.getFirstElement (aCollection); } /** * @return A new aggregator that uses the last element from the provided * collection. Never <code>null</code>. */ @Nonnull static <SRCTYPE> IAggregator <SRCTYPE, SRCTYPE> createUseLast () { return aCollection -> CollectionHelper.getLastElement (aCollection); } /** * @return A new aggregator that combines all input strings into a single * result string without any separator char. Never <code>null</code>. */ @Nonnull static IAggregator <String, String> createStringAll () { return aCollection -> StringHelper.getImploded (aCollection); } /** * @param cSep * the separator char to be used * @return A new aggregator that combines all input strings into a single * result string using the provided separator char. Never * <code>null</code>. */ @Nonnull static IAggregator <String, String> createStringAll (final char cSep) { return aCollection -> StringHelper.getImploded (cSep, aCollection); } /** * @param sSep * the separator string to be used. May not be <code>null</code>. * @return A new aggregator that combines all input strings into a single * result string using the provided separator string. Never * <code>null</code>. */ @Nonnull static IAggregator <String, String> createStringAll (@Nonnull final String sSep) { ValueEnforcer.notNull (sSep, "Separator"); return aCollection -> StringHelper.getImploded (sSep, aCollection); } /** * @return A new aggregator that combines all non-empty input strings into a * single result string without any separator char. Never * <code>null</code>. */ @Nonnull static IAggregator <String, String> createStringIgnoreEmpty () { return aCollection -> StringHelper.getImplodedNonEmpty (aCollection); } /** * @param cSep * the separator char to be used * @return A new aggregator that combines all non-empty input strings into a * single result string using the provided separator char. Never * <code>null</code>. */ @Nonnull static IAggregator <String, String> createStringIgnoreEmpty (final char cSep) { return aCollection -> StringHelper.getImplodedNonEmpty (cSep, aCollection); } /** * @param sSep * the separator string to be used. May not be <code>null</code>. * @return A new aggregator that combines all non-empty input strings into a * single result string using the provided separator string. Never * <code>null</code>. */ @Nonnull static IAggregator <String, String> createStringIgnoreEmpty (@Nonnull final String sSep) { ValueEnforcer.notNull (sSep, "Separator"); return aCollection -> StringHelper.getImplodedNonEmpty (sSep, aCollection); } }
/* Copyright (C) 2013-2014, Securifera, Inc All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Securifera, Inc nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================ Pwnbrew is provided under the 3-clause BSD license above. The copyright on this package is held by Securifera, Inc */ /* * HostMsg.java * */ package pwnbrew.network.control.messages; import java.io.UnsupportedEncodingException; import pwnbrew.MaltegoStub; import pwnbrew.functions.Function; import pwnbrew.manager.PortManager; import pwnbrew.misc.HostHandler; import pwnbrew.utilities.SocketUtilities; import pwnbrew.network.ControlOption; import pwnbrew.xml.maltego.custom.Host; /** * * */ public final class HostMsg extends MaltegoMessage{ private static final byte OPTION_HOSTNAME = 60; private static final byte OPTION_ARCH = 61; private static final byte OPTION_OS = 62; private static final byte OPTION_CONNECTED = 63; private static final byte OPTION_HOST_ID = 64; private static final byte OPTION_SLEEPABLE = 65; private static final byte OPTION_RELAY_PORT = 67; private static final byte OPTION_PID = 68; private boolean connected = false; private boolean sleepable = false; private int relayPort = -1; private String clientHostname = ""; private String os_name = ""; private String java_arch = ""; private String pid = ""; private int hostid = 0; public static final short MESSAGE_ID = 0x6d; //=========================================================================== /** * Constructor * * @param passedId */ public HostMsg( byte[] passedId ) { super(passedId); } //========================================================================= /** * Sets the variable in the message related to this TLV * * @param tempTlv * @return */ @Override public boolean setOption( ControlOption tempTlv ){ boolean retVal = true; try { byte[] theValue = tempTlv.getValue(); switch( tempTlv.getType()){ case OPTION_HOSTNAME: clientHostname = new String( theValue, "US-ASCII"); break; case OPTION_ARCH: java_arch = new String(theValue, "US-ASCII"); break; case OPTION_PID: pid = new String(theValue, "US-ASCII"); break; case OPTION_OS: os_name = new String(theValue, "US-ASCII"); break; case OPTION_HOST_ID: hostid = SocketUtilities.byteArrayToInt(theValue); break; case OPTION_CONNECTED: if( theValue.length > 0 ){ byte retByte = theValue[0]; if( retByte == 1 ) connected = true; } break; case OPTION_SLEEPABLE: if( theValue.length > 0 ){ byte retByte = theValue[0]; if( retByte == 1 ) sleepable = true; } break; case OPTION_RELAY_PORT: relayPort = SocketUtilities.byteArrayToInt(theValue); break; default: retVal = false; break; } } catch (UnsupportedEncodingException ex) { ex = null; } return retVal; } //=============================================================== /** * Performs the logic specific to the message. * * @param passedManager */ @Override public void evaluate( PortManager passedManager ) { if( passedManager instanceof MaltegoStub ){ MaltegoStub theStub = (MaltegoStub)passedManager; Function aFunction = theStub.getFunction(); if( aFunction instanceof HostHandler ){ HostHandler aHandler = (HostHandler)aFunction; //Add the host to the list Host aHost = new Host( connected, sleepable, relayPort, clientHostname, java_arch, pid, os_name, Integer.toString( hostid) ); aHandler.addHost( aHost ); } } } }
/* * Copyright Verizon Media, Licensed under the terms of the Apache License, Version 2.0. See LICENSE file in project root for terms. */ package com.yahoo.cubed.model.filter; import org.testng.Assert; import org.testng.annotations.Test; import java.util.ArrayList; /** * Test for PipelineLogicalRule. */ public class PipelineLogicalRuleTest { /** * toString test. * @throws Exception */ @Test public void toStringTest() throws Exception { PipelineLogicalRule tg = new PipelineLogicalRule(); tg.setRules(new ArrayList<>()); Assert.assertEquals(tg.toString(), "()"); PipelineLogicalRule subRule = new PipelineLogicalRule(); subRule.setRules(new ArrayList<>()); tg.addRule(subRule); Assert.assertEquals(tg.toString(), "()"); PipelineLogicalRule subRule2 = new PipelineLogicalRule(); subRule2.setRules(new ArrayList<>()); tg.addRule(subRule2); Assert.assertEquals(tg.toString(), "(() null ())"); } }
package cn.auto.core.utils.vm;///* // * Copyright 2010 Focus Technology, Co., Ltd. All rights reserved. // */ //package cn.auto.core.utils.vm; // //import org.apache.commons.lang3.StringUtils; //import org.apache.commons.logging.Log; //import org.apache.commons.logging.LogFactory; //import org.apache.velocity.app.VelocityEngine; //import org.apache.velocity.exception.VelocityException; //import org.apache.velocity.tools.generic.DateTool; //import org.apache.velocity.tools.generic.NumberTool; //import org.springframework.beans.factory.annotation.Autowired; // // //import java.io.IOException; //import java.io.StringWriter; //import java.util.Map; // ///** // * 基于volecity的邮件模板渲染组件 // * // * @author yuancaho // * // */ //public class VelocityTemplateUtils //{ // // 模板引擎工厂 // @Autowired // private VelocityEngineFactoryBean velocityEngineFactoty; // // 模板引擎工厂 // private VelocityEngine velocityEngine; // // 日志工具 // private static Log log= LogFactory.getLog(VelocityTemplateUtils.class); // //velocity-tool // private NumberTool numberTool; // // private DateTool dateTool; // /** // * 在容器启动时初始化模板引擎 // */ // public void initEngine() throws VelocityException, IOException // { // try // { // log.info("begin to init velocity engine !"); // velocityEngine= velocityEngineFactoty.createVelocityEngine(); // numberTool=new NumberTool(); // dateTool = new DateTool(); // log.info("init velocity engine successful !"); // } // catch (VelocityException e) // { // log.error("init velocity engine fail !", e); // throw e; // } // catch (IOException e) // { // log.error("init velocity engine fail !", e); // throw e; // } // } // /** // * // * @param templet 模板路径 // * @param map 模板中的参数 // * @return 模板内容 // * @throws IOException // * @throws VelocityException // */ // public String mergeMailTemplet(String template, Map<String, Object> map) // { // if (template != null && !"".equals((StringUtils.trimToEmpty(template)))) // { // map.put("number", numberTool); // map.put("date", dateTool); // return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, map); // } // else // { // return null; // } // } // /** // * // * @param templet 模板路径 // * @param encoding 模板内容采用的编码格式 // * @param map 模板中的参数 // * @return 模板内容 // * @throws IOException // * @throws VelocityException // */ // public String mergeMailTemplet(String template, String encoding, Map<String, Object> map) // { // if (template != null && !"".equals((StringUtils.trimToEmpty(template)))) // { // map.put("number", numberTool); // map.put("date", dateTool); // return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, encoding, map); // } // else // { // return null; // } // } // /**动态加载模板并替换参数 // * @param root // * @param template // * @param encoding // * @param map // * @return // */ // @SuppressWarnings("deprecation") // public String mergeDynamicTemplet(String root, String template, String encoding, Map<String, Object> map) // { // log.info("root:"+root+"template:"+template+"encoding:"+encoding+ "pinanAcceptTime:"+map.get("pinanAcceptTime")); // RuntimeInstance ri= new RuntimeInstance(); // ri.setProperty(Runtime.FILE_RESOURCE_LOADER_PATH, root); // Context context= new VelocityContext(map); // StringWriter sw= new StringWriter(); // try // { // Template temp= ri.getTemplate(template, encoding); // temp.merge(context, sw); // return sw.toString(); // } // catch (ResourceNotFoundException e) // { // log.error("merging template and varialbles failed.", e); // e.printStackTrace(); // } // catch (ParseErrorException e) // { // log.error("merging template and varialbles failed.", e); // e.printStackTrace(); // } // catch (Exception e) // { // log.error("merging template and varialbles failed.", e); // e.printStackTrace(); // } // log.info("生成结果:"+sw); // return null; // } // /** // * @return the velocityEngineFactoty // */ // public VelocityEngineFactoryBean getVelocityEngineFactoty() // { // return velocityEngineFactoty; // } // /** // * @param velocityEngineFactoty the velocityEngineFactoty to set // */ // public void setVelocityEngineFactoty(VelocityEngineFactoryBean velocityEngineFactoty) // { // this.velocityEngineFactoty= velocityEngineFactoty; // } //}
package lka.wine.dao; public class Location extends AbstractDao { private int locationId; private String locationName; private String locationCity; private String locationState; private int locationTypeId; private LocationType locationType; public int getLocationId() { return locationId; } public void setLocationId(int locationId) { this.locationId = locationId; } public String getLocationName() { return locationName; } public void setLocationName(String locationName) { this.locationName = locationName; } public String getLocationCity() { return locationCity; } public void setLocationCity(String locationCity) { this.locationCity = locationCity; } public String getLocationState() { return locationState; } public void setLocationState(String locationState) { this.locationState = locationState; } public int getLocationTypeId() { return locationTypeId; } public void setLocationTypeId(int locationTypeId) { this.locationTypeId = locationTypeId; } public LocationType getLocationType() { return locationType; } public void setLocationType(LocationType locationType) { this.locationType = locationType; } @Override public int getId() { return getLocationId(); } @Override public void setId(int id) { setLocationId(id); } }
/* * Copyright 2015 Zbynek Vyskovsky mailto:kvr000@gmail.com http://kvr.znj.cz/ http://github.com/kvr000/ * * 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 net.dryuf.bigio.iostream; import org.apache.commons.io.IOUtils; import org.testng.AssertJUnit; import org.testng.annotations.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.function.Supplier; public class LinedInputMultiStreamTest { private final static String BIG_MESSAGE = new Supplier<String>() { @Override public String get() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 4096; ++i) { sb.append("hello "); } return sb.toString(); } }.get(); @Test public void testSmallSingleLine() throws IOException { byte[] input = "hello\n".getBytes(StandardCharsets.UTF_8); try (MultiStream multiStream = new LinedInputMultiStream(new ByteArrayInputStream(input))) { try (InputStream stream = multiStream.nextStream()) { AssertJUnit.assertEquals("hello", IOUtils.toString(stream, StandardCharsets.UTF_8)); } AssertJUnit.assertNull(multiStream.nextStream()); } } @Test public void testSmallSingleLineUnfinished() throws IOException { byte[] input = "hello".getBytes(StandardCharsets.UTF_8); try (MultiStream multiStream = new LinedInputMultiStream(new ByteArrayInputStream(input))) { try (InputStream stream = multiStream.nextStream()) { AssertJUnit.assertEquals("hello", IOUtils.toString(stream, StandardCharsets.UTF_8)); } AssertJUnit.assertNull(multiStream.nextStream()); } } @Test public void testSmallMultiLines() throws IOException { byte[] input = "hello\nworld\n".getBytes(StandardCharsets.UTF_8); try (MultiStream multiStream = new LinedInputMultiStream(new ByteArrayInputStream(input))) { try (InputStream stream = multiStream.nextStream()) { AssertJUnit.assertEquals("hello", IOUtils.toString(stream, StandardCharsets.UTF_8)); } try (InputStream stream = multiStream.nextStream()) { AssertJUnit.assertEquals("world", IOUtils.toString(stream, StandardCharsets.UTF_8)); } AssertJUnit.assertNull(multiStream.nextStream()); } } @Test public void testSmallMultiLinesUnfinished() throws IOException { byte[] input = "hello\nworld".getBytes(StandardCharsets.UTF_8); try (MultiStream multiStream = new LinedInputMultiStream(new ByteArrayInputStream(input))) { try (InputStream stream = multiStream.nextStream()) { AssertJUnit.assertEquals("hello", IOUtils.toString(stream, StandardCharsets.UTF_8)); } try (InputStream stream = multiStream.nextStream()) { AssertJUnit.assertEquals("world", IOUtils.toString(stream, StandardCharsets.UTF_8)); } AssertJUnit.assertNull(multiStream.nextStream()); } } @Test public void testSmallPartial() throws IOException { byte[] input = ("hello\nworld\n").getBytes(StandardCharsets.UTF_8); try (MultiStream multiStream = new LinedInputMultiStream(new ByteArrayInputStream(input))) { try (InputStream stream = multiStream.nextStream()) { byte[] actual = new byte["hello".length()]; actual[0] = (byte)stream.read(); } try (InputStream stream = multiStream.nextStream()) { AssertJUnit.assertEquals("world", IOUtils.toString(stream, StandardCharsets.UTF_8)); } AssertJUnit.assertNull(multiStream.nextStream()); } } @Test public void testBigSingleLine() throws IOException { byte[] input = (BIG_MESSAGE+"\n").getBytes(StandardCharsets.UTF_8); try (MultiStream multiStream = new LinedInputMultiStream(new ByteArrayInputStream(input))) { try (InputStream stream = multiStream.nextStream()) { AssertJUnit.assertEquals(BIG_MESSAGE, IOUtils.toString(stream, StandardCharsets.UTF_8)); } AssertJUnit.assertNull(multiStream.nextStream()); } } @Test public void testBigSingleLineUnfinished() throws IOException { byte[] input = BIG_MESSAGE.getBytes(StandardCharsets.UTF_8); try (MultiStream multiStream = new LinedInputMultiStream(new ByteArrayInputStream(input))) { try (InputStream stream = multiStream.nextStream()) { AssertJUnit.assertEquals(BIG_MESSAGE, IOUtils.toString(stream, StandardCharsets.UTF_8)); } AssertJUnit.assertNull(multiStream.nextStream()); } } @Test public void testBigMultiLineUnfinished() throws IOException { byte[] input = (BIG_MESSAGE+"\n"+BIG_MESSAGE).getBytes(StandardCharsets.UTF_8); try (MultiStream multiStream = new LinedInputMultiStream(new ByteArrayInputStream(input))) { try (InputStream stream = multiStream.nextStream()) { AssertJUnit.assertEquals(BIG_MESSAGE, IOUtils.toString(stream, StandardCharsets.UTF_8)); } try (InputStream stream = multiStream.nextStream()) { AssertJUnit.assertEquals(BIG_MESSAGE, IOUtils.toString(stream, StandardCharsets.UTF_8)); } AssertJUnit.assertNull(multiStream.nextStream()); } } @Test public void testBigVariousReadMethods() throws IOException { byte[] input = (BIG_MESSAGE+"\n"+BIG_MESSAGE).getBytes(StandardCharsets.UTF_8); try (MultiStream multiStream = new LinedInputMultiStream(new ByteArrayInputStream(input))) { try (InputStream stream = multiStream.nextStream()) { byte[] actual = new byte[BIG_MESSAGE.length()]; actual[0] = (byte)stream.read(); IOUtils.readFully(stream, actual, 1, actual.length-1); AssertJUnit.assertEquals(BIG_MESSAGE, new String(actual, StandardCharsets.UTF_8)); } try (InputStream stream = multiStream.nextStream()) { AssertJUnit.assertEquals(BIG_MESSAGE, IOUtils.toString(stream, StandardCharsets.UTF_8)); } AssertJUnit.assertNull(multiStream.nextStream()); } } @Test public void testBigPartial() throws IOException { byte[] input = (BIG_MESSAGE+"\n"+BIG_MESSAGE).getBytes(StandardCharsets.UTF_8); try (MultiStream multiStream = new LinedInputMultiStream(new ByteArrayInputStream(input))) { try (InputStream stream = multiStream.nextStream()) { byte[] actual = new byte[BIG_MESSAGE.length()]; actual[0] = (byte)stream.read(); } try (InputStream stream = multiStream.nextStream()) { AssertJUnit.assertEquals(BIG_MESSAGE, IOUtils.toString(stream, StandardCharsets.UTF_8)); } AssertJUnit.assertNull(multiStream.nextStream()); } } }
/* * (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. */ package org.webtop.component; /** * <p>Title: X3DWebTOP</p> * * <p>Description: The X3D version of The Optics Project for the Web * (WebTOP)</p> * * <p>Copyright: Copyright (c) 2006</p> * * <p>Company: MSU Department of Physics and Astronomy</p> * * @author Paul Cleveland, Peter Gilbert * @version 0.0 */ import javax.swing.*; import java.awt.*; import java.awt.BorderLayout; public class WapplicationGuiTest extends JFrame{ public WapplicationGuiTest() { try { jbInit(); } catch (Exception ex) { ex.printStackTrace(); } } private void jbInit() throws Exception { this.getContentPane().setLayout(gridBagLayout1); jPanel1.setBackground(Color.orange); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jPanel2.setBackground(Color.red); this.getContentPane().add(jPanel2, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0 , GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 100, 50)); this.getContentPane().add(jPanel1, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0 , GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 480, 435)); } private GridBagLayout gridBagLayout1 = new GridBagLayout(); private JPanel jPanel1 = new JPanel(); private JPanel jPanel2 = new JPanel(); public static void main(String args[]) { WapplicationGuiTest test = new WapplicationGuiTest(); test.setSize(640,480); test.setVisible(true); } }
package com.joalib.controller; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.joalib.DAO.DAO; import com.joalib.DTO.ActionForward; import com.joalib.board.action.*; @WebServlet("*.bo") public class BoardContr extends javax.servlet.http.HttpServlet{ protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String RequestURI=request.getRequestURI(); String contextPath=request.getContextPath(); String command=RequestURI.substring(contextPath.length()); ActionForward forward=null; dbAction action=null; if(command.equals("/boardWritePro.bo")){ //�۾��� �������Է� �� �Ϸ��ư ������ ��, action = new BoardWriteProAction(); try { forward=action.execute(request, response ); } catch (Exception e) { e.printStackTrace(); } }else if(command.equals("/boardReadPage.bo")){ action = new BoardDetailAction(); try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } }else if(command.equals("/boardModifyForm.bo")){ action = new BoardModifyFormAction(); try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } }else if(command.equals("/boardModifyPro.bo")){ action = new BoardModifyProAction(); try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } }else if(command.equals("/boardDelete.bo")){ action = new BoardDeleteAction(); try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } }else if(command.equals("/commentWrite.bo")){ action = new CommentWriteAction(); try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } }else if(command.equals("/commentDelete.bo")){ action = new CommentDelAction(); try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } }else if(command.equals("/commentUpdate.bo")) { action = new CommentUpdateAction(); try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } }else if(command.equals("/boardHitUp.bo")) { action = new BoardPostHitupAction(); try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } }else if(command.equals("/smallCommentChange.bo")) { action = new SmallCommentChangeAction(); try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } }else if(command.equals("/smallCommentAdd.bo")) { action = new SmallCommentAddAction(); try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } }else if(command.equals("/smallCommentDel.bo")) { action = new SmallCommentDelAction(); try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } }else if(command.equals("/commentAlarmAdd.bo")) { action = new CommentAlramAddAction(); try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } }else if(command.equals("/smallCommentAlarmAdd.bo")) { action = new SamllCommentAlarmAction(); try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } } if(forward != null){ if(forward.isRedirect()){ response.sendRedirect(forward.getPath()); //��ȯ�ϴ� forward���� ������, 'forward.getPath()'���� �̵��Ѵ�. }else{ RequestDispatcher dispatcher= request.getRequestDispatcher(forward.getPath()); dispatcher.forward(request, response); } } //doProcess END } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doProcess(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doProcess(request,response); } }
package com.unicom.patrolDoor.entity; public class VoteLog { private Integer id; private Integer voteId; private Integer userId; private String opt; private String voteTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getVoteId() { return voteId; } public void setVoteId(Integer voteId) { this.voteId = voteId; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getOpt() { return opt; } public void setOpt(String opt) { this.opt = opt == null ? null : opt.trim(); } public String getVoteTime() { return voteTime; } public void setVoteTime(String voteTime) { this.voteTime = voteTime == null ? null : voteTime.trim(); } }
package com.yc.education.mapper.check; import com.yc.education.model.check.Timecard; import com.yc.education.util.MyMapper; import org.apache.ibatis.annotations.Param; import java.util.List; /** *@Description TODO 原始考勤资料 *@Author QuZhangJing *@Date 11:43 2019/2/18 *@Version 1.0 */ public interface TimecardMapper extends MyMapper<Timecard> { /** * 根据员工编号和考勤日期查询考勤员工 * @param startOrder 开始员工编号 * @param endOrder 结束员工编号 * @param startTime 开始考勤时间 * @param endTime 结束考勤时间 * @return */ List<Timecard> findTimecardByUserOrderAndTime(@Param("status")int status,@Param("startOrder")String startOrder,@Param("endOrder")String endOrder,@Param("startTime")String startTime ,@Param("endTime")String endTime); }
package juego; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import java.awt.Color; import java.awt.EventQueue; import java.awt.Font; import javax.swing.GroupLayout.Alignment; import javax.swing.GroupLayout; import javax.swing.LayoutStyle.ComponentPlacement; public class Principal extends JFrame{ // Variables private JButton jButton1; private JLabel jLabel1; private JLabel jLabel3; private JPanel jPanel1; private JPanel jPanel2; private JPanel jPanel3; private JTextField jTextField1; private Palabras juego; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Principal frame = new Principal(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public Principal() { getContentPane().setBackground(new Color(0, 0, 0)); initComponents(); Principal.this.setTitle("Ahorcado"); Principal.this.setLocationRelativeTo(null); //Teclado jPanel3.setLayout(new java.awt.GridLayout(5, 5)); for(int i=65; i<=90; i++){ JButton boton = new JButton(Character.toString ((char) i)); boton.setActionCommand(Character.toString ((char) i)); boton.setForeground(new Color(30, 144, 255)); boton.setBackground(Color.BLACK); boton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(juego!=null){ String str = arg0.getActionCommand(); juego.evaluar(str.charAt(0)); }else{ JOptionPane.showMessageDialog(null, "Presione \"Jugar\""); } } }); jPanel3.add(boton); } } //Interfaz @SuppressWarnings("unchecked") private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jPanel2.setBackground(new Color(0, 0, 0)); jLabel3 = new javax.swing.JLabel(); jLabel3.setFont(new Font("Showcard Gothic", Font.PLAIN, 30)); jLabel3.setForeground(new Color(30, 144, 255)); jTextField1 = new javax.swing.JTextField(); jPanel3 = new javax.swing.JPanel(); jPanel3.setBackground(new Color(0, 0, 0)); jButton1 = new javax.swing.JButton(); jButton1.setFont(new Font("Showcard Gothic", Font.PLAIN, 30)); jButton1.setForeground(new Color(30, 144, 255)); jButton1.setBackground(Color.BLACK); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel1.setLayout(new java.awt.BorderLayout()); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/ahorcado_5.jpg"))); // NOI18N jPanel1.add(jLabel1, java.awt.BorderLayout.CENTER); jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel2.setLayout(new java.awt.GridBagLayout()); jLabel3.setText("PALABRA"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(jLabel3, gridBagConstraints); jTextField1.setEditable(false); jTextField1.setBackground(new Color(30, 144, 255)); jTextField1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField1.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextField1.setPreferredSize(new java.awt.Dimension(300, 28)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(jTextField1, gridBagConstraints); jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 157, Short.MAX_VALUE) ); jButton1.setText("Jugar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); layout.setHorizontalGroup( layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGap(18) .addGroup(layout.createParallelGroup(Alignment.LEADING, false) .addComponent(jPanel2, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel3, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(layout.createSequentialGroup() .addPreferredGap(ComponentPlacement.RELATED) .addComponent(jButton1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(Alignment.TRAILING, false) .addGroup(layout.createSequentialGroup() .addComponent(jPanel2, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(jPanel3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGap(34) .addComponent(jButton1, GroupLayout.PREFERRED_SIZE, 56, GroupLayout.PREFERRED_SIZE) .addGap(142)) .addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addContainerGap(13, Short.MAX_VALUE)) ); getContentPane().setLayout(layout); pack(); } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { juego = new Palabras(jTextField1,jLabel1, jLabel1); } }
package tests; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import config.Setup; import pageObjects.AutomationPracticeHomePage; import pageObjects.CreateAccountPage; import pageObjects.SignInPage; import pageObjects.SignOutPage; import pageObjects.WomanPage; public class AutomationPracticeHomeAction extends Setup { @BeforeMethod public void clickCreateAccount() { SignInPage signIn=new SignInPage(driver); signIn.clickSignIn(); Assert.assertTrue(signIn.verifyCreateAccountTitle(), "something went wrong"); signIn.enterEmail("hcantu1@mail.com"); signIn.clickCreateAccountBtn(); } @AfterMethod public void signOut() { SignOutPage signout=new SignOutPage(driver); Assert.assertTrue(signout.verifyMyAccountPageTitle(),"My account"); signout.clickSignOut(); } @Test //@Parameters("email") public void testCase() throws InterruptedException{ AutomationPracticeHomePage automationPracticeHomePage= new AutomationPracticeHomePage(driver); automationPracticeHomePage.clickWomenLink(); WomanPage wp=new WomanPage(driver); Assert.assertEquals(wp.getSceneTextP1(), "You will find here all woman fashion collections."); Assert.assertEquals(wp.getSceneTextP2(), "This category includes all the basics of your wardrobe and much more:"); Assert.assertEquals(wp.getSceneTextP3(), "shoes, accessories, printed t-shirts, feminine dresses, women's jeans!"); wp.clickAnyLink("Sign in"); SignInPage signIn=new SignInPage(driver); signIn.clickSignIn(); Assert.assertTrue(signIn.verifyCreateAccountTitle(), "something went wrong"); signIn.enterEmail("hcantu@mail.com"); signIn.clickCreateAccountBtn(); /*CreateAccountPage createNewAccount=new CreateAccountPage(driver); Assert.assertTrue(createNewAccount.verifyPageTitle(), "Page create an account its not found"); createNewAccount.enterFirstName("jose"); createNewAccount.enterLastName("test lastname"); //createNewAccount.enterEmail(email); createNewAccount.enterPassword("12345678"); //createNewAccount.enterFirstName2("test1"); //createNewAccount.enterLastName2("test lastname"); createNewAccount.enterAddress("direccion de prueba 123"); createNewAccount.enterCity("ensenada"); createNewAccount.selectState("1"); createNewAccount.enterPostalcode("91911"); createNewAccount.enterCountry("21"); createNewAccount.enterPhone("6461234777"); createNewAccount.enterAlias("TEST1"); createNewAccount.clickCreateNewAccountBtn(); */ /*SignOutPage signout=new SignOutPage(driver); Assert.assertTrue(signout.verifyMyAccountPageTitle(),"My account"); signout.clickSignOut(); */ Thread.sleep(2000); } }
package au.gov.nsw.records.digitalarchive.ORM; import java.util.Date; public class Agencies implements java.io.Serializable { private Integer agencyNumber; private String agencyTitle; private String startDateQualifier; private Date startDate; private String endDateQualifier; private Date endDate; private String category; private String creation; private String abolition; private String administrativeHistoryNote; private String unregisteredPrecedingAgencies; private String unregisteredSucceedingAgencies; private String unregisteredSuperiorAgencies; private String unregisteredSubordinateAgencies; private String unregisteredRelatedAgencies; private String registeredBy; private Date registeredDate; private String amendments; private Date lastAmendmentDate; private String archivesNote; private String registrationStatus; private String relatedAgencies; private Date updatedDate; private String updatedUser; public Agencies() { } public Agencies(Integer agencyNumber, String agencyTitle, String startDateQualifier, Date startDate, String endDateQualifier, String category, String creation, String administrativeHistoryNote, String registeredBy, Date registeredDate, String amendments, String archivesNote, String registrationStatus, String relatedAgencies) { this.agencyNumber = agencyNumber; this.agencyTitle = agencyTitle; this.startDateQualifier = startDateQualifier; this.startDate = startDate; this.endDateQualifier = endDateQualifier; this.category = category; this.creation = creation; this.administrativeHistoryNote = administrativeHistoryNote; this.registeredBy = registeredBy; this.registeredDate = registeredDate; this.amendments = amendments; this.archivesNote = archivesNote; this.registrationStatus = registrationStatus; this.relatedAgencies = relatedAgencies; } public Agencies(Integer agencyNumber, String agencyTitle, String startDateQualifier, Date startDate, String endDateQualifier, Date endDate, String category, String creation, String abolition, String administrativeHistoryNote, String unregisteredPrecedingAgencies, String unregisteredSucceedingAgencies, String unregisteredSuperiorAgencies, String unregisteredSubordinateAgencies, String unregisteredRelatedAgencies, String registeredBy, Date registeredDate, String amendments, Date lastAmendmentDate, String archivesNote, String registrationStatus, String relatedAgencies, Date updatedDate, String updatedUser) { this.agencyNumber = agencyNumber; this.agencyTitle = agencyTitle; this.startDateQualifier = startDateQualifier; this.startDate = startDate; this.endDateQualifier = endDateQualifier; this.endDate = endDate; this.category = category; this.creation = creation; this.abolition = abolition; this.administrativeHistoryNote = administrativeHistoryNote; this.unregisteredPrecedingAgencies = unregisteredPrecedingAgencies; this.unregisteredSucceedingAgencies = unregisteredSucceedingAgencies; this.unregisteredSuperiorAgencies = unregisteredSuperiorAgencies; this.unregisteredSubordinateAgencies = unregisteredSubordinateAgencies; this.unregisteredRelatedAgencies = unregisteredRelatedAgencies; this.registeredBy = registeredBy; this.registeredDate = registeredDate; this.amendments = amendments; this.lastAmendmentDate = lastAmendmentDate; this.archivesNote = archivesNote; this.registrationStatus = registrationStatus; this.relatedAgencies = relatedAgencies; this.updatedDate = updatedDate; this.updatedUser = updatedUser; } public Integer getAgencyNumber() { return this.agencyNumber; } public void setAgencyNumber(Integer agencyNumber) { this.agencyNumber = agencyNumber; } public String getAgencyTitle() { return this.agencyTitle; } public void setAgencyTitle(String agencyTitle) { this.agencyTitle = agencyTitle; } public String getStartDateQualifier() { return this.startDateQualifier; } public void setStartDateQualifier(String startDateQualifier) { this.startDateQualifier = startDateQualifier; } public Date getStartDate() { return this.startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public String getEndDateQualifier() { return this.endDateQualifier; } public void setEndDateQualifier(String endDateQualifier) { this.endDateQualifier = endDateQualifier; } public Date getEndDate() { return this.endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public String getCategory() { return this.category; } public void setCategory(String category) { this.category = category; } public String getCreation() { return this.creation; } public void setCreation(String creation) { this.creation = creation; } public String getAbolition() { return this.abolition; } public void setAbolition(String abolition) { this.abolition = abolition; } public String getAdministrativeHistoryNote() { return this.administrativeHistoryNote; } public void setAdministrativeHistoryNote(String administrativeHistoryNote) { this.administrativeHistoryNote = administrativeHistoryNote; } public String getUnregisteredPrecedingAgencies() { return this.unregisteredPrecedingAgencies; } public void setUnregisteredPrecedingAgencies( String unregisteredPrecedingAgencies) { this.unregisteredPrecedingAgencies = unregisteredPrecedingAgencies; } public String getUnregisteredSucceedingAgencies() { return this.unregisteredSucceedingAgencies; } public void setUnregisteredSucceedingAgencies( String unregisteredSucceedingAgencies) { this.unregisteredSucceedingAgencies = unregisteredSucceedingAgencies; } public String getUnregisteredSuperiorAgencies() { return this.unregisteredSuperiorAgencies; } public void setUnregisteredSuperiorAgencies( String unregisteredSuperiorAgencies) { this.unregisteredSuperiorAgencies = unregisteredSuperiorAgencies; } public String getUnregisteredSubordinateAgencies() { return this.unregisteredSubordinateAgencies; } public void setUnregisteredSubordinateAgencies( String unregisteredSubordinateAgencies) { this.unregisteredSubordinateAgencies = unregisteredSubordinateAgencies; } public String getUnregisteredRelatedAgencies() { return this.unregisteredRelatedAgencies; } public void setUnregisteredRelatedAgencies( String unregisteredRelatedAgencies) { this.unregisteredRelatedAgencies = unregisteredRelatedAgencies; } public String getRegisteredBy() { return this.registeredBy; } public void setRegisteredBy(String registeredBy) { this.registeredBy = registeredBy; } public Date getRegisteredDate() { return this.registeredDate; } public void setRegisteredDate(Date registeredDate) { this.registeredDate = registeredDate; } public String getAmendments() { return this.amendments; } public void setAmendments(String amendments) { this.amendments = amendments; } public Date getLastAmendmentDate() { return this.lastAmendmentDate; } public void setLastAmendmentDate(Date lastAmendmentDate) { this.lastAmendmentDate = lastAmendmentDate; } public String getArchivesNote() { return this.archivesNote; } public void setArchivesNote(String archivesNote) { this.archivesNote = archivesNote; } public String getRegistrationStatus() { return this.registrationStatus; } public void setRegistrationStatus(String registrationStatus) { this.registrationStatus = registrationStatus; } public String getRelatedAgencies() { return this.relatedAgencies; } public void setRelatedAgencies(String relatedAgencies) { this.relatedAgencies = relatedAgencies; } public Date getUpdatedDate() { return this.updatedDate; } public void setUpdatedDate(Date updatedDate) { this.updatedDate = updatedDate; } public String getUpdatedUser() { return this.updatedUser; } public void setUpdatedUser(String updatedUser) { this.updatedUser = updatedUser; } }
package liu.lang.reflect.Method; import java.lang.reflect.Method; /**Method类的常用方法: * toString() * 返回该方法对象的字符串表示形式,会擦除泛型 * @author LIU * */ public class About_toString { public <T, V> void test() {} public static void main(String[] args) throws Exception { Method method = About_toString.class.getMethod("test"); // public void liu.lang.reflect.Method.About_toString.test() System.out.println(method.toString()); } }
package com.wangzhu.tmp; import java.util.List; /** * Created by wang.zhu on 2020-09-29 10:57. **/ public class SynchronizedTest { public synchronized void method1() throws Exception { System.out.println("method1 start"); Thread.sleep(1000); System.out.println("method1 end"); } public synchronized void method2() throws Exception { System.out.println("method2 start"); Thread.sleep(1000); System.out.println("method2 end"); } public synchronized static void method3() throws Exception { System.out.println("method3 start"); Thread.sleep(1000); System.out.println("method3 end"); } public synchronized static void method4() throws Exception { System.out.println("method4 start"); Thread.sleep(1000); System.out.println("method4 end"); } public void method5() throws Exception { System.out.println("method5 start"); Thread.sleep(1000); System.out.println("method5 end"); } public static void method6() throws Exception { System.out.println("method6 start"); Thread.sleep(1000); System.out.println("method6 end"); } public Integer findMaxItem(final List<Integer> list) { return null; } public String toBinaryString(int num){ return null; } public boolean isEven(int num){ return true; } public static void main(String[] args) { Integer a = 1; Integer b = 1; Integer c = new Integer(1); Integer d = new Integer(1); Integer e = 300; Integer f = 300; System.out.println(a == b); System.out.println(c == d); System.out.println(e == f); } }
package com.san.emergency; import org.springframework.stereotype.Service; @Service public class EmergencyService { }