text
stringlengths
10
2.72M
package com.example.demo.model; import java.util.UUID; public final class Manager { private final String name; private UUID id; private int salary; public Manager(String name, int salary) { this.name = name; this.salary = salary; } public Manager() { name = ""; } public UUID getId() { return id; } public void work() { System.out.println(this.name + " I am working "); } public String toString() { return this.name + " has salary: " + this.salary + "\n"; } }
package com.example.sourabh.bookmyticket; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class Main5Activity extends AppCompatActivity { /** * The {@link android.support.v4.view.PagerAdapter} that will provide * fragments for each of the sections. We use a * {@link FragmentPagerAdapter} derivative, which will keep every * loaded fragment in memory. If this becomes too memory intensive, it * may be best to switch to a * {@link android.support.v4.app.FragmentStatePagerAdapter}. */ private SectionsPagerAdapter mSectionsPagerAdapter; //ListView listView; /** * The {@link ViewPager} that will host the section contents. */ private ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main5); Intent intent=getIntent(); String u=intent.getStringExtra("U"); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle(u); toolbar.setSubtitle("2D Hindi"); setSupportActionBar(toolbar); // Create the adapter that will return a fragment for each of the three // primary sections of the activity. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.container1); mViewPager.setAdapter(mSectionsPagerAdapter); // MyListAdapter adapter= new MyListAdapter(this,cinema); //listView=(ListView)findViewById(R.id.listView); //listView.setAdapter(adapter); TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setTabTextColors(Color.BLACK,Color.BLACK); tabLayout.setSelectedTabIndicatorColor(Color.GREEN); tabLayout.setupWithViewPager(mViewPager); } @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_main5, 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); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ Context c=getContext(); ListView listView; String[] cinema={"Wave:Noida","Carnival:TGIP","DT Cinemas:Noida","Carnival:Greater Noida","Carnival:Vaishali"}; private static final String ARG_SECTION_NUMBER = "section_number"; // public Intent inten=c.getI; public PlaceholderFragment() { } /** * Returns a new instance of this fragment for the given section * number. */ public static PlaceholderFragment newInstance(int sectionNumber) { PlaceholderFragment fragment = new PlaceholderFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main5, container, false); // String u=inten.getStringExtra("U"); // TextView textView = (TextView) rootView.findViewById(R.id.section_label); MyLstAdapter adapter= new MyLstAdapter(getActivity(),cinema); listView=(ListView)rootView.findViewById(R.id.listView3); listView.setAdapter(adapter); return rootView; } } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class below). return PlaceholderFragment.newInstance(position + 1); } @Override public int getCount() { // Show 3 total pages. return 6; } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: SimpleDateFormat sdf = new SimpleDateFormat("EEE dd"); Date d = new Date(); String day = sdf.format(d); return day; case 1: SimpleDateFormat dateFormat= new SimpleDateFormat("EEE dd"); Calendar currentCal = Calendar.getInstance(); String currentdate=dateFormat.format(currentCal.getTime()); currentCal.add(Calendar.DATE, 1); String toDate=dateFormat.format(currentCal.getTime()); return toDate; case 2: SimpleDateFormat dateFormat1= new SimpleDateFormat("EEE dd"); Calendar currentCal1 = Calendar.getInstance(); String currentdate1=dateFormat1.format(currentCal1.getTime()); currentCal1.add(Calendar.DATE, 2); String toDate1=dateFormat1.format(currentCal1.getTime()); return toDate1; case 3: SimpleDateFormat dateFormat2= new SimpleDateFormat("EEE dd"); Calendar currentCal2 = Calendar.getInstance(); String currentdate2=dateFormat2.format(currentCal2.getTime()); currentCal2.add(Calendar.DATE, 3); String toDate2=dateFormat2.format(currentCal2.getTime()); return toDate2; case 4: SimpleDateFormat dateFormat3= new SimpleDateFormat("EEE dd"); Calendar currentCal3 = Calendar.getInstance(); String currentdate3=dateFormat3.format(currentCal3.getTime()); currentCal3.add(Calendar.DATE, 4); String toDate3=dateFormat3.format(currentCal3.getTime()); return toDate3; case 5: SimpleDateFormat dateFormat4= new SimpleDateFormat("EEE dd"); Calendar currentCal4 = Calendar.getInstance(); String currentdate4=dateFormat4.format(currentCal4.getTime()); currentCal4.add(Calendar.DATE, 5); String toDate4=dateFormat4.format(currentCal4.getTime()); return toDate4; } return null; } } }
package com.icanit.app.fragments; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageButton; import android.widget.Toast; import com.icanit.app.R; import com.icanit.app.adapter.MyArrayAdapter; import com.icanit.app.exception.AppException; import com.icanit.app.service.DataService; import com.icanit.app.util.AppUtil; public class Home_bottomtab02Fragment extends AbstractRadioBindFragment { private View self; private int resId=R.layout.fragment4home_02_searchpage; private EditText editText; private GridView gridView; private MyArrayAdapter maa; private DataService dataService; private String[] searchCategory; private ImageButton textDisposer,backButton; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { init(); bindListeners(); initGv(); } catch (AppException e) { e.printStackTrace(); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return self; } private void init() throws AppException { self=getActivity().getLayoutInflater().inflate(resId,null,false); backButton = (ImageButton) self.findViewById(R.id.imageButton2); editText = (EditText) self.findViewById(R.id.editText1); gridView = (GridView) self.findViewById(R.id.gridView1); dataService = AppUtil.getServiceFactory().getDataServiceInstance(getActivity()); textDisposer = (ImageButton) self.findViewById(R.id.imageButton1); } private void bindListeners() { AppUtil.bindBackListener(backButton); AppUtil.bindEditTextNtextDisposer(editText, textDisposer); } private void initGv() throws AppException { gridView.setAdapter(maa = new MyArrayAdapter(getActivity(), R.layout.item4gv_merchandize_cate_search, R.id.button1, searchCategory = dataService.getSearchCategory())); gridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View self, int position, long id) { Toast.makeText(getActivity(), searchCategory[position], Toast.LENGTH_SHORT).show(); } }); } }
package structural.composite; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static org.junit.Assert.*; /** * @author Renat Kaitmazov */ @RunWith(JUnit4.class) public final class DrawingTest { private Drawing drawing; @Before public final void setup() { drawing = new Drawing(); } @Test public final void drawShapeTest() throws Exception { final Shape square = new Square(); final Shape circle = new Circle(); drawing.addShape(square); drawing.addShape(circle); drawing.draw("Red"); drawing.draw("Green"); } }
/* * 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 ImpresionDocumentos; import static Formuarios.Inicio.Pane1; import java.awt.Dimension; /** * * @author jluis */ public class InduccionInicial extends javax.swing.JInternalFrame { /** * Creates new form InsuccionInicial */ public InduccionInicial() { 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() { jButton5 = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton6 = new javax.swing.JButton(); jButton7 = new javax.swing.JButton(); jButton8 = new javax.swing.JButton(); jButton9 = new javax.swing.JButton(); jButton5.setText("jButton5"); setTitle("IMPRECION DOCUMENTOS INDUCCION INICIAL"); jPanel1.setBackground(new java.awt.Color(153, 204, 255)); jButton1.setText("DERECHOS Y OBLIGACIONES"); jButton2.setText("DESCRIPTOR INTRODUCTORIO"); jButton3.setText("TRIFOLIAR"); jButton4.setText("CONCEPTOS SSO "); jButton6.setText("PLAN DE COMUNICACION INTERNO"); jButton7.setText("INGLES TECNICO"); jButton8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jButton8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancelar.png"))); // NOI18N jButton8.setText("CANCELAR"); jButton8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton8ActionPerformed(evt); } }); jButton9.setText("PROGRAMA INDUCCION INICIAL"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(40, 40, 40) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jButton6)) .addComponent(jButton3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton9, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(42, 42, 42)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(87, 87, 87) .addComponent(jButton8) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(31, 31, 31) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE) .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed ImpresionDoc tra = new ImpresionDoc(); Pane1.add(tra); Dimension desktopSize = Pane1.getSize(); Dimension FrameSize = tra.getSize(); tra.setLocation((desktopSize.width - FrameSize.width) / 2, (desktopSize.height - FrameSize.height) / 2); tra.show(); try { this.dispose(); } catch (Exception e) {System.out.println("F "+e); } }//GEN-LAST:event_jButton8ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButton6; private javax.swing.JButton jButton7; private javax.swing.JButton jButton8; private javax.swing.JButton jButton9; private javax.swing.JPanel jPanel1; // End of variables declaration//GEN-END:variables }
/* * MIT License * Copyright (c) 2020 corneliouz bett * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction,including without limitation * the rights to use, copy,modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.corneliouzbett.mpesasdk.base; import com.corneliouzbett.mpesasdk.core.rest.request.OnlinePayment; import com.corneliouzbett.mpesasdk.core.rest.request.OnlinePaymentStatus; import com.corneliouzbett.mpesasdk.core.rest.response.OnlinePaymentResponse; import com.corneliouzbett.mpesasdk.core.rest.response.OnlinePaymentStatusResponse; import jdk.nashorn.internal.ir.annotations.Immutable; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.POST; /** * .For Lipa na Mpesa using stk push * * @author corneliouzbett * @since 1.0.0 */ @Immutable public interface MExpress { /** * Use this API to check the status of a Lipa Na M-Pesa Online Payment * * @param onlinePaymentStatus Online payment status * @return Mpesa response */ @POST("/mpesa/stkpushquery/v1/query") Call<OnlinePaymentStatusResponse> checkOnlinePaymentStatus(@Body OnlinePaymentStatus onlinePaymentStatus); /** * @return Mpesa response */ @POST("/mpesa/stkpush/v1/processrequest") Call<OnlinePaymentResponse> initiateOnlinePayment(@Body OnlinePayment onlinePayment); }
/* * AddUserFragment * * Version 1.0 * * November 25, 2017 * * Copyright (c) 2017 Team 26, CMPUT 301, University of Alberta - All Rights Reserved. * You may use, distribute, or modify this code under terms and conditions of the Code of Student Behavior at University of Alberta. * You can find a copy of the license in this project. Otherwise please contact rohan@ualberta.ca * * Purpose: Fragment to add a new user. * Prompts the user for a username. */ package cmput301f17t26.smores.all_fragments; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import cmput301f17t26.smores.R; import cmput301f17t26.smores.all_models.User; import cmput301f17t26.smores.all_storage_controller.UserController; import cmput301f17t26.smores.utils.NotificationReceiver; /** * Created by apate on 2017-10-31. */ public class AddUserFragment extends DialogFragment { private Button mCheckButton; private EditText mUserName; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_adduser, null); mCheckButton = (Button) view.findViewById(R.id.Request_checkbtn); mUserName = (EditText) view.findViewById(R.id.Request_username); mCheckButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Context mContext = getActivity(); final UserController userController = UserController.getUserController(getActivity()); final String username = mUserName.getText().toString().trim(); if (username.equals("")) { Toast.makeText(getActivity(), "Please enter a username!", Toast.LENGTH_SHORT).show(); return; } new Thread(new Runnable() { @Override public void run() { if (userController.addUser(mContext, new User(username))) { ((Activity) mContext).runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(mContext, "Added!", Toast.LENGTH_SHORT).show(); NotificationReceiver.setUpNotifcations(mContext); if (getActivity() != null) { if (getActivity().getSupportFragmentManager() != null) { dismiss(); } } } }); } else { ((Activity) mContext).runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(mContext, "Another user already has your username! Please try again", Toast.LENGTH_SHORT).show(); } }); } } }).start(); } }); setCancelable(false); return view; } }
package org.db.ddbserver; import java.rmi.RemoteException; import java.util.LinkedList; /** * a sql construct tree * * @author Administrator * */ public class SqlTree { private SqlTreeNode root; private LinkedList<SqlTreeNode> leaf; private LinkedList<SqlTreeNode> temp_join; private GDD gdd = new GDD(); // static int num public SqlTree() { root = new SqlTreeNode(); root.setType("root"); leaf = new LinkedList<SqlTreeNode>(); temp_join = new LinkedList<SqlTreeNode>(); } public void modifySqlTree() { } /** * build the tree * * @param s */ public void buildTree(SqlSentence s) { // a lot of sentences String[] select_list = s.getSelect_list(); String[] from_list = s.getFrom_list(); String[] where_list = s.getWhere_list(); // a lot of constructions // we don't need to use project, we can use select_list // such as book.title LinkedList<String> project = new LinkedList<String>(); LinkedList<String[]> join = new LinkedList<String[]>(); LinkedList<String[]> select = new LinkedList<String[]>(); // all the leaves, deal with from clause first for (int i = 0; i < from_list.length; i++) { SqlTreeNode node = new SqlTreeNode(); node.setLeaf(true); node.setDetail(from_list[i]); node.setType("table"); node.setTablename(from_list[i]); leaf.add(node); // System.out.println(node.getDetail()); } // make join and select constructions for (int j = 0; j < where_list.length; j++) { String t = where_list[j]; /** * if where == "" then continue * * @@@@@@@@attention !!!!!!!!attention */ if (t == "") continue; String ss[] = makeJoinSelect(t); if (ss[1] == "join") join.add(ss); else select.add(ss); } // make project constructions, although it is useless for (int i = 0; i < select_list.length; i++) { /** * if * change to the whole colomn */ if (select_list[i].equals("*")) { for (int j = 0; j < leaf.size(); j++) { String[] ss = gdd.getAllColumn(leaf.get(i).getTablename()); for (int k = 0; k < ss.length; k++) { project.add(ss[k]); } } break; } if (select_list[i].contains(".")) { project.add(select_list[i]); } else { /** * if there is only one leaf and the select clause is like * title, we need to change it into book.title. */ project.add(leaf.get(0).getTablename() + "." + select_list[i]); } } /** * select */ /* * for(int i = 0; i < select.size(); i++) { String[] ss = select.get(i); * SqlTreeNode temp = new SqlTreeNode(); temp.setType(ss[1]); * temp.setDetail(ss[2] + ss[3] + ss[4]); String selectTable = * this.getSelectTable(ss[2]); SqlTreeNode left; left = * findInLeaf(selectTable); left.setParent(temp); temp.setLeft(left); } */ for (int i = 0; i < select.size(); i++) { String[] ss = select.get(i); // System.out.println("$$$$$$$$$$$ " + ss[1] + " " + ss[2] + " " + // ss[3]); String selectTable = this.getSelectTable(ss[2]); SqlTreeNode temp = null; for (int j = 0; j < leaf.size(); j++) { if (leaf.get(j).getTablename().equals(selectTable)) { temp = leaf.get(j); break; } } if (temp.getDetail().contains("select")) { temp.setDetail(temp.getDetail() + "&" + ss[1] + " " + ss[2] + ss[3] + ss[4]); } else { temp.setDetail(ss[1] + " " + ss[2] + ss[3] + ss[4]); } temp.setType("select");// // temp.setConstruction("c_select from table " + temp.getTablename() // + " " + ss[2] + ss[3] + ss[4]); // SqlTreeNode left; // left = findInLeaf(selectTable); // left.setParent(temp); // temp.setLeft(left); } /** * project */ for (int i = 0; i < leaf.size(); i++) { String detail; // to eliminate the possiblity of id and id repeated if (leaf.size() == 1 || isInProject(gdd.getKey(leaf.get(i).getTablename()), project)) { detail = ""; } else { /** * & replace \n */ detail = gdd.getKey(leaf.get(i).getTablename()) + "&"; } for (int j = i; j < project.size(); j++) { String ss = project.get(j); String projectTable = this.getProjectTable(ss); if (projectTable.equals(leaf.get(i).getTablename())) { /** * & replace \n */ detail = detail.concat(ss + "&"); } } // if(detail.equals(gdd.getAllColumn(leaf.get(i).getTablename()))) { // todo // todo // } SqlTreeNode temp = new SqlTreeNode(); temp.setType("project"); temp.setDetail(detail.substring(0, detail.length() - 1)); // temp.setConstruction("c_project " + detail.substring(0, // detail.length() - 1)); SqlTreeNode left; left = findInLeaf(leaf.get(i).getTablename()); left.setParent(temp); temp.setLeft(left); } /** * join */ for (int i = 0; i < join.size(); i++) { String[] ss = getJoinTable(join.get(i)); SqlTreeNode temp = new SqlTreeNode(); temp.setType("join"); temp.setDetail(join.get(i)[2] + join.get(i)[3] + join.get(i)[4]); // temp.setConstruction("c_join " + join.get(i)[2] + join.get(i)[3] // + join.get(i)[4]); SqlTreeNode left, right; // System.out.println(ss[0] + " " + ss[1]); left = findInLeaf(ss[0]); right = findInLeaf(ss[1]); left.setParent(temp); right.setParent(temp); temp.setLeft(left); temp.setRight(right); } // for(int i = 0; i < leaf.size(); i++) { // System.out.println(leaf.get(i).getDetail()); // } /** * customer vertical fragmentation */ for (int i = 0; i < leaf.size(); i++) { SqlTreeNode l = leaf.get(i); if (l.getTablename().equals("customer")) { // not have all if (!isInProject("customer.rank", project) && !isInSelect("customer.rank", select) && !isInProject("customer.name", project) && !isInSelect("customer.name", select)) { if (l.getDetail().equals("customer")) { l.setType("table"); } else { l.setType("select_rank"); } l.setDetail(l.getDetail()); l.setSite(2); break; } // have name if (!isInProject("customer.rank", project) && !isInSelect("customer.rank", select)) { if (l.getDetail().equals("customer")) { l.setType("table"); } else { l.setType("select_name"); } l.setDetail(l.getDetail()); l.setSite(1); break; } // have rank if (!isInProject("customer.name", project) && !isInSelect("customer.name", select)) { if (l.getDetail().equals("customer")) { l.setType("table"); } else { l.setType("select_rank"); } l.setDetail(l.getDetail()); l.setSite(2); break; } // have all // name SqlTreeNode left, right; left = new SqlTreeNode(); left.setParent(l); l.setLeft(left); left.setLeaf(true); if (l.getDetail().equals("customer")) { left.setType("table"); } else { left.setType("select_name"); } left.setTablename("customer"); left.setDetail(this.getName(l.getDetail())); if (left.getDetail().equals("")) { left.setType("table"); left.setDetail("customer_name"); } left.setSite(1); // rank right = new SqlTreeNode(); right.setParent(l); l.setRight(right); right.setLeaf(true); if (l.getDetail().equals("customer")) { right.setType("table"); } else { right.setType("select_rank"); } right.setTablename("customer"); right.setDetail(this.getRank(l.getDetail())); if (right.getDetail().equals("")) { right.setType("table"); left.setDetail("customer_rank"); } right.setSite(2); l.setType("join"); l.setDetail("customer.id=customer.id"); l.setLeaf(false); break; } } String book = "1&2&3", publisher = "1&2&3&4", orders = "1&2&3&4"; /** * get all the select which has the same table together */ for (int i = 0; i < select.size(); i++) { String[] ss = select.get(i); if (ss[2].equals("book.id") || ss[2].equals("orders.book_id")) { book = handleInter(book, gdd.bookId(Integer.valueOf(ss[4]), ss[3])); orders = handleInter(orders, gdd.ordersBookId(Integer.valueOf(ss[4]), ss[3])); } else if (ss[2].equals("publisher.id")) { publisher = handleInter(publisher, gdd.publisherId(Integer.valueOf(ss[4]), ss[3])); } else if (ss[2].equals("publisher.nation")) { publisher = handleInter(publisher, gdd.publisherNation(ss[4] .substring(1, ss[4].length() - 1))); } else if (ss[2].equals("customer.id") || ss[2].equals("orders.customer_id")) { orders = handleInter(orders, gdd.ordersCustomerId(Integer.valueOf(ss[4]), ss[3])); } } // System.out.println("zzzz: book " + book); // System.out.println("zzzz: publisher " + publisher); // System.out.println("zzzz: orders " + orders); String[] xbook = book.split("&"); String[] xorders = orders.split("&"); String[] xpublisher = publisher.split("&"); int cpublisher = -1; int corders = -1; int cbook = -1; /** * Union */ for (int i = 0; i < leaf.size(); i++) { SqlTreeNode l = leaf.get(i); if (l.getTablename().equals("customer")) { continue; } else if (l.getTablename().equals("publisher")) { cpublisher = publisher.split("&").length; // l.setDetail(l.getDetail() + " " + "publisher " + // xpublisher[cpublisher - 1]); } else if (l.getTablename().equals("orders")) { corders = orders.split("&").length; // l.setDetail(l.getDetail() + " " + "orders " + xorders[corders // - 1]); } else if (l.getTablename().equals("book")) { cbook = book.split("&").length; // l.setDetail(l.getDetail() + " " + "book " + xbook[cbook - // 1]); } } // System.out.println("xxxx: book " + cbook); // System.out.println("xxxx: publisher " + cpublisher); // System.out.println("xxxx: orders " + corders); SqlTreeNode toBeCopied = findInLeaf(from_list[0]); // this.printTree(toBeCopied); if (cpublisher != -1) { for (int i = 0; i < cpublisher; i++) { if (cbook != -1) { for (int j = 0; j < cbook; j++) { if (corders != -1) { for (int k = 0; k < corders; k++) { // /////// SqlTreeNode u = new SqlTreeNode(); u.setType("union"); // u.setDetail("j, i, k"); SqlTreeNode l = findInLeaf(from_list[0]); SqlTreeNode r = this.duplicateSqlTree( toBeCopied, xbook[j], xpublisher[i], xorders[k]); u.setRight(r); u.setLeft(l); l.setParent(u); r.setParent(u); } } else { // /////// SqlTreeNode u = new SqlTreeNode(); u.setType("union"); // u.setDetail("j, i, -1"); SqlTreeNode l = findInLeaf(from_list[0]); SqlTreeNode r = this.duplicateSqlTree(toBeCopied, xbook[j], xpublisher[i], "-1"); u.setRight(r); u.setLeft(l); l.setParent(u); r.setParent(u); } } } else { if (corders != -1) { for (int k = 0; k < corders; k++) { // /////// SqlTreeNode u = new SqlTreeNode(); u.setType("union"); // u.setDetail("-1, i, k"); SqlTreeNode l = findInLeaf(from_list[0]); SqlTreeNode r = this.duplicateSqlTree(toBeCopied, "-1", xpublisher[i], xorders[k]); u.setRight(r); u.setLeft(l); l.setParent(u); r.setParent(u); } } else { // /////// SqlTreeNode u = new SqlTreeNode(); u.setType("union"); // u.setDetail("-1, i, -1"); SqlTreeNode l = findInLeaf(from_list[0]); SqlTreeNode r = this.duplicateSqlTree(toBeCopied, "-1", xpublisher[i], "-1"); u.setRight(r); u.setLeft(l); l.setParent(u); r.setParent(u); } } } } else { if (cbook != -1) { for (int j = 0; j < cbook; j++) { if (corders != -1) { for (int k = 0; k < corders; k++) { // /////// SqlTreeNode u = new SqlTreeNode(); u.setType("union"); // u.setDetail("j, -1, k"); SqlTreeNode l = findInLeaf(from_list[0]); SqlTreeNode r = this.duplicateSqlTree(toBeCopied, xbook[j], "-1", xorders[k]); u.setRight(r); u.setLeft(l); l.setParent(u); r.setParent(u); } } else { // /////// SqlTreeNode u = new SqlTreeNode(); u.setType("union"); // u.setDetail("j, -1, -1"); SqlTreeNode l = findInLeaf(from_list[0]); SqlTreeNode r = this.duplicateSqlTree(toBeCopied, xbook[j], "-1", "-1"); u.setRight(r); u.setLeft(l); l.setParent(u); r.setParent(u); } } } else { if (corders != -1) { for (int k = 0; k < corders; k++) { // /////// SqlTreeNode u = new SqlTreeNode(); u.setType("union"); // u.setDetail("-1, -1, k"); SqlTreeNode l = findInLeaf(from_list[0]); SqlTreeNode r = this.duplicateSqlTree(toBeCopied, "-1", "-1", xorders[k]); u.setRight(r); u.setLeft(l); l.setParent(u); r.setParent(u); } } else { // /////// SqlTreeNode u = new SqlTreeNode(); u.setType("union"); // u.setDetail("-1, -1, -1"); SqlTreeNode l = findInLeaf(from_list[0]); SqlTreeNode r = this.duplicateSqlTree(toBeCopied, "-1", "-1", "-1"); u.setRight(r); u.setLeft(l); l.setParent(u); r.setParent(u); } } } /** * more project and it is the final project */ // if(leaf.size() > 1) { String detail = ""; for (int j = 0; j < project.size(); j++) { String ss = project.get(j); // String projectTable = this.getProjectTable(ss); /** * & replace \n */ detail = detail.concat(ss + "&"); } SqlTreeNode temp = new SqlTreeNode(); temp.setType("project"); temp.setDetail(detail.substring(0, detail.length() - 1)); SqlTreeNode left; left = findInLeaf(leaf.get(0).getTablename()); left.setParent(temp); temp.setLeft(left); // ???????????????????temp.setParent(root); // } root.setLeft(temp); // root.setLeft(findInLeaf(from_list[0])); root.setType("root"); deleteFirstUnion(); // changeTableToSelect(root); } /** * select_int customer.rank=1&select_int customer.rank=2 * * @param s * @return */ public String getRank(String s) { // System.out.println(s); String c = ""; String[] ss = s.split("&"); for (int i = 0; i < ss.length; i++) { if (ss[i].contains("rank")) { c = c + ss[i] + "&"; } } if (!c.equals("")) { c.substring(0, c.length() - 1); } // System.out.println("c " + c); return c; } /** * select_int customer.rank=1&select_int customer.rank=2 * * @param s * @return */ public String getName(String s) { // System.out.println(s); String c = ""; String[] ss = s.split("&"); for (int i = 0; i < ss.length; i++) { if (ss[i].contains("name")) { c = c + ss[i] + "&"; } } if (!c.equals("")) { c.substring(0, c.length() - 1); } // System.out.println("c " + c); return c; } public void deleteFirstUnion() { SqlTreeNode node = leaf.get(0); while (!node.getType().equals("union")) { node = node.getParent(); } if (node != null) { if (node.getParent() == null) { root = node.getRight(); } else { node.getRight().setParent(node.getParent()); node.getParent().setLeft(node.getRight()); } } } /** * * @param node * @param book * @param publisher * @param orders * @return */ public SqlTreeNode duplicateSqlTree(SqlTreeNode node, String book, String publisher, String orders) { if (node == null) return null; SqlTreeNode t = new SqlTreeNode(node); if (node.getType().equals("select") || node.getType().equals("table")) { if (t.getTablename().equals("book")) { // t.setDetail(t.getDetail() + " from " + // "book " + book); t.setSite(Integer.parseInt(book)); } if (t.getTablename().equals("publisher")) { // t.setDetail(t.getDetail() + " from " + // "publisher " + publisher); t.setSite(Integer.parseInt(publisher)); } if (t.getTablename().equals("orders")) { // t.setDetail(t.getDetail() + " from " + // "orders " + orders); t.setSite(Integer.parseInt(orders)); } } SqlTreeNode left, right; left = duplicateSqlTree(node.getLeft(), book, publisher, orders); right = duplicateSqlTree(node.getRight(), book, publisher, orders); t.setLeft(left); t.setRight(right); if (left != null) left.setParent(t); if (right != null) right.setParent(t); return t; } private void changeTableToSelect(SqlTreeNode node) { if (node == null) return; if (node.getType().equals("table")) { node.setType("select_all");// System.out.println("hi:1"); System.out.println(node.getDetail()); System.out.println("hi:"); String ss[]; if (node.getDetail().equals("customer_rank") || node.getDetail().equals("customer_name")) { ss = gdd.getAllColumn(node.getDetail()); } else { ss = gdd.getAllColumn(node.getDetail().split(" ")[0]); } // System.out.println("@@@@@@@@@@@@@@ " + node.getDetail()); String s = ""; for (int i = 0; i < ss.length; i++) { s = s + "&" + ss[i]; } node.setDetail(s); } changeTableToSelect(node.getLeft()); changeTableToSelect(node.getRight()); } public String handleInter(String r, String s) { String[] rr = r.split("&"); String[] ss = s.split("&"); String result = ""; for (int i = 0; i < rr.length; i++) { for (int j = 0; j < ss.length; j++) { if (rr[i].equals(ss[j])) { result = result + rr[i] + "&"; break; } } } if (result == "") return ""; return result.substring(0, result.length() - 1); } /** * * @param s * the string of project such as book.title or title * @param l * all the project colomn from select clause * @return */ private boolean isInProject(String s, LinkedList<String> l) { for (int i = 0; i < l.size(); i++) { if (s.equals(l.get(i))) return true; } return false; } /** * * @param s * the string of project such as customer.rank = 1 * @param l * all the project colomn from where clause * @return */ private boolean isInSelect(String s, LinkedList<String[]> l) { for (int i = 0; i < l.size(); i++) { if (s.equals(l.get(i)[2])) { return true; } } return false; } public SqlTreeNode getRoot() { return root; } public void setRoot(SqlTreeNode root) { this.root = root; } public LinkedList<SqlTreeNode> getLeaf() { return leaf; } public void setLeaf(LinkedList<SqlTreeNode> leaf) { this.leaf = leaf; } public LinkedList<SqlTreeNode> getTemp_join() { return temp_join; } public void setTemp_join(LinkedList<SqlTreeNode> temp_join) { this.temp_join = temp_join; } public void excuteTree(SqlTreeNode node) { if (node == null) { return; } RmiClient[] clients = RMIClients.getRMIClient(); if (node.getType().equals("root")) { System.out.println("---------root---------"); this.excuteTree(node.getLeft()); node.setGlobal_id(node.getLeft().getGlobal_id()); node.setSite(node.getLeft().getSite()); try { clients[node.getSite()].printResult(node.getLeft() .getGlobal_id()); System.out.println("---------finish_all---------"); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (node.getType().equals("select_all")) { this.excuteTree(node.getLeft()); // System.out.println("---------select_all---------"); String command = ""; String[] ss = new String[2]; ss[0] = node.getTablename(); ss[1] = command; // System.out.println("command " + ss[0] + " " + // ss[1]); try { int id = clients[node.getSite()].select(ss); node.setGlobal_id(id); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // for customer if (node.getType().equals("table")) { this.excuteTree(node.getLeft()); // System.out.println("---------table---------"); String command = ""; String[] ss = new String[2]; ss[0] = node.getTablename(); ss[1] = command; // System.out.println("command " + ss[0] + " " + // ss[1]); try { int id = clients[node.getSite()].select(ss); node.setGlobal_id(id); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (node.getType().equals("select") || node.getType().equals("select_name") || node.getType().equals("select_rank")) { this.excuteTree(node.getLeft()); // System.out.println("---------select---------"); String command = " where "; String[] ss = node.getDetail().split("&"); for (int i = 0; i < ss.length; i++) { System.out.println("command " + ss[i]); command = command + ss[i].split(" ")[1] + " and "; } command = command.substring(0, command.length() - 4); ss = new String[2]; ss[0] = node.getTablename(); ss[1] = command; // System.out.print("command " + ss[0] + " " + // ss[1]); try { int id = clients[node.getSite()].select(ss); node.setGlobal_id(id); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(node.getType().equals("union")) { this.excuteTree(node.getLeft()); this.excuteTree(node.getRight()); //System.out.println("---------union---------"); String temps=node.getDetail(); String[] tempss=temps.split("&"); int totallen=0; for(int i=0;i<tempss.length;i++){ if(tempss[i].equals("book.id")){ totallen+=10; }else if(tempss[i].equals("book.title")){ totallen+=80; }else if(tempss[i].equals("book.authors")){ totallen+=80; }else if(tempss[i].equals("book.publisher_id")){ totallen+=10; }else if(tempss[i].equals("book.copies")){ totallen+=10; }else if(tempss[i].equals("customer.id")){ totallen+=10; }else if(tempss[i].equals("customer.name")){ totallen+=80; }else if(tempss[i].equals("orders.customer_id")){ totallen+=10; }else if(tempss[i].equals("orders.book_id")){ totallen+=10; }else if(tempss[i].equals("orders.quantity")){ totallen+=10; }else if(tempss[i].equals("publisher.id")){ totallen+=10; }else if(tempss[i].equals("publisher.name")){ totallen+=80; }else if(tempss[i].equals("publisher.nation")){ totallen+=20; } } if(totallen==0){ totallen=21; } node.setSite(node.getLeft().getSite()); try { int id1 = clients[node.getSite()].getFromSite(node.getRight().getSite(), node.getRight().getGlobal_id(),totallen); int id = clients[node.getSite()].union(node.getLeft().getGlobal_id(), id1); node.setGlobal_id(id); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(node.getType().equals("join")) { this.excuteTree(node.getLeft()); this.excuteTree(node.getRight()); //System.out.println("---------join---------"); String temps=node.getDetail(); String[] tempss=temps.split("="); int totallen=0; //for(int i=0;i<tempss.length;i++){ int i=1; if(tempss[i].equals("book.id")){ totallen+=10; }else if(tempss[i].equals("book.title")){ totallen+=80; }else if(tempss[i].equals("book.authors")){ totallen+=80; }else if(tempss[i].equals("book.publisher_id")){ totallen+=10; }else if(tempss[i].equals("book.copies")){ totallen+=10; }else if(tempss[i].equals("customer.id")){ totallen+=10; }else if(tempss[i].equals("customer.name")){ totallen+=80; }else if(tempss[i].equals("orders.customer_id")){ totallen+=10; }else if(tempss[i].equals("orders.book_id")){ totallen+=10; }else if(tempss[i].equals("orders.quantity")){ totallen+=10; }else if(tempss[i].equals("publisher.id")){ totallen+=10; }else if(tempss[i].equals("publisher.name")){ totallen+=80; }else if(tempss[i].equals("publisher.nation")){ totallen+=20; } //} node.setSite(node.getLeft().getSite()); try { int id1 = clients[node.getSite()].getFromSite(node.getRight() .getSite(), node.getRight().getGlobal_id(),totallen); int id = clients[node.getSite()].hash_join(node.getLeft() .getGlobal_id(), id1, node.getDetail()); node.setGlobal_id(id); /*if(customer_id == -1 && node.isCustomerJoin()) { customer_id = node.getGlobal_id(); customer_site = node.getSite(); return; }*/ //System.out.println("---------join finish---------"); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (node.getType().equals("project")) { this.excuteTree(node.getLeft()); // System.out.println("---------project---------"); node.setSite(node.getLeft().getSite()); node.setGlobal_id(node.getLeft().getGlobal_id()); try { int id = clients[node.getSite()].project(node.getGlobal_id(), node.getDetail()); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return; } public String replace(String str) { String select = "σ", project = "Π", union = "∪(union)", join = "⋈"; String publisher = "Publisher", Customer = "Customer", Book = "Book", Orders = "Orders", Root = "Root"; if (str.toLowerCase().equals("join")) return join; if (str.toLowerCase().equals("select")) return select; if (str.toLowerCase().equals("project")) return project; if (str.toLowerCase().equals("union")) return union; if (str.toLowerCase().equals("publisher")) return publisher; if (str.toLowerCase().equals("customer")) return Customer; if (str.toLowerCase().equals("book")) return Book; if (str.toLowerCase().equals("orders")) return Orders; if (str.toLowerCase() == "root") return Root; else return ""; } public String printCommand(SqlTreeNode node, int n, String tree) { if (node == null) return ""; if (node.getLeft() == null && node.getRight() == null) { if (node.getTablename().trim().equals("") && node.getType().trim().equals("")) { return ""; } else { if (node.getTablename().trim().equals("")) { //tree += "<li>" + replace(node.getType()) +"("+node.getDetail()+")"+ "</li>"; if(!(node.getType().equals("union")||node.getType().toLowerCase().equals("root"))) tree += "<li>" + replace(node.getType()) +"("+node.getDetail()+")"; else { tree += "<li>" + replace(node.getType()) ; } } else { tree += "<li>" + replace(node.getTablename()) +"-S"+node.getSite()+ "</li>"; } } } else { if (node.getTablename().trim().equals("") && node.getType().trim().equals("")) { return ""; } else { if (node.getTablename().trim().equals("")) { if(!(node.getType().equals("union")||node.getType().toLowerCase().equals("root"))) tree += "<li>" + replace(node.getType()) +"("+node.getDetail()+")"; else { tree += "<li>" + replace(node.getType()) ; } //System.out.println( "<li>" + replace(node.getType())); } else { tree += "<li>" + replace(node.getTablename()); // System.out.println("<li>" + replace(node.getTablename())+"-S"+node.getSite()); } } tree += "<ul>"; if (node.getLeft() != null) { if(!printCommand(node.getLeft(), ++n, "").equals("")) tree += printCommand(node.getLeft(), ++n, ""); } if (node.getRight() != null) { if(!printCommand(node.getRight(), ++n, "").equals("")) tree += printCommand(node.getRight(), ++n, ""); } tree += "</ul>"; tree += "</li>"; } return tree; // ////////////////////////////////////////////////////////////////////////////////// /* * if(node == null) return; for(int j=0;j<n;j++) System.out.print("__"); * if(node.getTablename().trim().equals("")){ * System.out.print("["+node.getGlobal_id * ()+":"+replace(node.getType())+"]"); } else { * System.out.println("["+node * .getGlobal_id()+":"+replace(node.getTablename * ())+"-S"+node.getSite()+"]"); } * if(!(node.getLeft()==null&&node.getRight()==null)) * System.out.print("-->"); if(node.getLeft()!=null) { * if(node.getTablename().trim().equals("")){ * System.out.print("["+node.getLeft * ().getGlobal_id()+":"+replace(node.getLeft().getType())+"]"); } else * { * System.out.println("["+node.getLeft().getGlobal_id()+":"+replace(node * .getLeft().getTablename()) +"-S"+node.getLeft().getSite()+"]"); } * * } if(node.getRight()!=null) { * if(node.getTablename().trim().equals("")){ * System.out.print("["+node.getRight * ().getGlobal_id()+":"+replace(node.getRight().getType())+"]"); } else * { * System.out.println("["+node.getRight().getGlobal_id()+":"+replace(node * .getRight().getTablename()) +"-S"+node.getRight().getSite()+"]"); } } * System.out.println(); printCommand(node.getLeft(),++n); * printCommand(node.getRight(),++n); */ // System.out.println(node.getGlobal_id() + " *** " + // node.getTablename() + " *** " + node.getType() + " *** " + // node.getDetail() + " *** " + node.getSite()); } private int global_id = 1; public void setGlobalId(SqlTreeNode node) { if (node == null) return; setGlobalId(node.getLeft()); setGlobalId(node.getRight()); node.setGlobal_id(global_id); global_id++; } public void printTree(SqlTreeNode node) { if (node == null) return; System.out.println("**************"); System.out.println(node.getType() + "\n" + node.getDetail()); printTree(node.getLeft()); printTree(node.getRight()); } public void printTree1(SqlTreeNode node, int num) { if (node != null) { printTree1(node.getRight(), num + 7); for (int i = 0; i < num; i++) { System.out.print(" "); } System.out.println(node.getType()); for (int i = 0; i < num; i++) { System.out.print(" "); } System.out.println(node.getDetail()); printTree1(node.getLeft(), num + 7); } } /** * get the leaf and the root of that subtree * * @param tablename * @return */ private SqlTreeNode findInLeaf(String tablename) { for (int i = 0; i < leaf.size(); i++) { if (leaf.get(i).getTablename().equals(tablename)) return getSubRoot(leaf.get(i)); } return null; } /** * get top root of the subtree, using by findInLeaf * * @param node * @return */ private SqlTreeNode getSubRoot(SqlTreeNode node) { while (node.getParent() != null) { node = node.getParent(); } return node; } /** * return the table name * * book.id orders.book_id we return book & orders * * @param s * @return */ private String[] getJoinTable(String[] s) { String[] ss = new String[2]; ss[0] = s[2].substring(0, s[2].indexOf(".")); ss[1] = s[4].substring(0, s[4].indexOf(".")); return ss; } /** * return table name * * book.id or id we return both book * * @param s * @return */ private String getSelectTable(String s) { String ss; if (s.contains(".")) { ss = s.substring(0, s.indexOf(".")); } else { ss = leaf.get(0).getTablename(); } return ss; } /** * return table name * * book.id or id we return both book * * @param s * @return */ private String getProjectTable(String s) { String ss; if (s.contains(".")) { ss = s.substring(0, s.indexOf(".")); } else { ss = leaf.get(0).getTablename(); } return ss; } /** * analyze where clause and get the constructs out of the sentences. * select_int: id = 100 or id > 10 select_char: nation = 'usa' join: id = id * * @param s * @return ss[] 0 sql: book.id=orders.book_id 1 join 2 book.id 3 = 4 * orders.book_id 5 ************* */ private String[] makeJoinSelect(String s) { String ss[] = new String[6]; ss[0] = "sql: " + s; ss[5] = "*************"; if (s.contains("=")) { ss[2] = s.substring(0, s.indexOf("=")); ss[3] = "="; ss[4] = s.substring(s.indexOf("=") + 1); if (ss[4].charAt(0) == '\'') { ss[1] = "select_char"; } else if (ss[4].charAt(0) <= '9' && ss[4].charAt(0) >= '0') { ss[1] = "select_int"; } else { ss[1] = "join"; } } if (s.contains(">")) { ss[2] = s.substring(0, s.indexOf(">")); ss[3] = ">"; ss[4] = s.substring(s.indexOf(">") + 1); ss[1] = "select_int"; } if (s.contains("<")) { ss[2] = s.substring(0, s.indexOf("<")); ss[3] = "<"; ss[4] = s.substring(s.indexOf("<") + 1); ss[1] = "select_int"; } for (int i = 0; i < 6; i++) { // System.out.println(ss[i]); } if (!ss[2].contains(".")) { ss[2] = leaf.get(0).getTablename() + "." + ss[2]; } return ss; } }
package DataBase; import java.io.File; /** * * @author Enter-The-Dragon */ public class World extends EditDataBase { private int year; private int month; private int day; public World(int year, int month, int day) { this.year = year; this.month = month; this.day = day; /* * lets start with 256 couples */ Inital(25600); while (this.year != 200) { aDay(); nextDay(); } } public void aDay() { boolean firstTime = true; /* * its a brand new day! so let go to the start of the DataBase and go to * the first person. We will then go through each person. * * Check to see if the person is alive. * ( if alive ) * Get Age * Chance of death delt * */ try { rs.first(); while (rs.next()) { /* make sure that everyone is tested! */ if (firstTime) { rs.previous(); firstTime = false; } /* alive? */ int alive = checkIfAlive(); if (alive == 0) { /* get age */ int ageInDays = getAge(); /* small chance of death */ chanceOfDeath(ageInDays); } } } catch (Exception ex) { ex.printStackTrace(); } } public void Inital(int numberOfCouples) { for (int x = 0; x < numberOfCouples; x++) { File file = new File("surname.txt"); //number between 1 and 362 randomInt = random.nextInt(360) + 1; String Surname = NameReader(file, randomInt); //0 = random, 1 = male, 2 = female generate(Surname, year, month, day, 1); generate(Surname, year, month, day, 2); } } /* * check to see if the person is alive * if alive == zero they are alive */ public int checkIfAlive() { int alive = 0; try { alive = rs.getInt("Dyear"); } catch (Exception ex) { } return alive; } /* * get the age of the current person */ public int getAge() { int age = 0; try { /* * Lets work out the age */ int byear = rs.getInt("Byear"); int bmonth = rs.getInt("Bmonth"); int bday = rs.getInt("Bday"); int dayBorn = ((byear - 1) * 256); dayBorn += ((bmonth - 1) * 32); dayBorn += (bday - 1); int dayNumber = ((year - 1) * 256); dayNumber += ((month - 1) * 32); dayNumber += (day - 1); age = dayNumber - dayBorn; } catch (Exception ex) { ex.printStackTrace(); } return age; } /* * use age to give them a chance of death */ public void chanceOfDeath(int age) { try { if (age < 2560) { // 0 - 9 randomInt = random.nextInt(250000); } else if (age < 5120) { // 10 - 19 randomInt = random.nextInt(85000); } else if (age < 7680) { // 20 - 29 randomInt = random.nextInt(20000); } else if (age < 10240) { // 30 - 39 randomInt = random.nextInt(10000); } else if (age < 12800) { // 40 - 49 randomInt = random.nextInt(5000); } else if (age < 15360) { // 50 - 59 randomInt = random.nextInt(2500); } else if (age < 17920) { // 60 - 69 randomInt = random.nextInt(1000); } else if (age < 25600) { // 70 - 99 randomInt = random.nextInt(500); } else if (age >= 25600) { // 100+ randomInt = random.nextInt(250) ; } if (randomInt == 0) { rs.updateInt("Dyear", year); rs.updateInt("Dmonth", month); rs.updateInt("Dday", day); rs.updateRow(); System.out.println(day + "/" + month + "/" + year); System.out.println("Death " + age); } } catch (Exception ex) { ex.printStackTrace(); } } /* * 64 seconds in a minute * 64 minutes in an hour * 32 hours in a day | 8 days in a week * 32 days in a month | 4 weeks in a month * 8 months in a year | 32 weeks a year * * A year | World | Earth * seconds | 33554432 | 31556940 * minutes | 524288 | 525949 * hours | 8192 | 8765.81 * days | 256 | 365 * weeks | 32 | 52 * month | 8 | 12 * */ public void nextDay() { day++; if (day == 33) { month++; day = 1; /* * Months: * 1: unimensie * 2: duomensie * 3: tremensie * 4: quadmensie * 5: quinmensia * 6: sexamensia * 7: heptmensia * 8: octomensia */ if (month == 9) { year++; month = 1; } } } }
package com.apssouza.mytrade.trading.forex.order; public enum OrderOrigin { STOP_ORDER, EXITS, SIGNAL }
package cs301.carstereo; import android.graphics.Color; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.SeekBar; import android.widget.TextView; import android.widget.ToggleButton; public class MainActivity extends ActionBarActivity { ToggleButton power; ToggleButton amFm; TextView stationDisplay; Button preset1; Button preset2; Button preset3; Button preset4; Button preset5; Button preset6; SeekBar volume; SeekBar tuner; TextView printVol; int[] amPresets = {550,600,650,700,750,800}; double[] fmPresets = {90.9,92.9,94.9,96.9,98.9,100.9}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); power = (ToggleButton) findViewById(R.id.toggleButton); stationDisplay = (TextView)findViewById(R.id.textView); volume = (SeekBar) findViewById(R.id.seekBar2); tuner = (SeekBar) findViewById(R.id.seekBar); amFm = (ToggleButton) findViewById(R.id.toggleButton2); tuner.setOnSeekBarChangeListener(new ChangeSeekBarListener()); preset1 = (Button) findViewById(R.id.button6); preset2 = (Button) findViewById(R.id.button7); preset3 = (Button) findViewById(R.id.button8); preset4 = (Button) findViewById(R.id.button9); preset5 = (Button) findViewById(R.id.button10); preset6 = (Button) findViewById(R.id.button11); preset1.setOnLongClickListener(new ChangePresets()); preset2.setOnLongClickListener(new ChangePresets()); preset3.setOnLongClickListener(new ChangePresets()); preset4.setOnLongClickListener(new ChangePresets()); preset5.setOnLongClickListener(new ChangePresets()); preset6.setOnLongClickListener(new ChangePresets()); printVol = (TextView) findViewById(R.id.textView5); volume.setOnSeekBarChangeListener(new ChangeVolumeListener()); } @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); } public void powerOn(View v) { if(power.isChecked()) { power.setBackgroundColor(Color.GREEN); stationDisplay.setBackgroundColor(Color.GREEN); stationDisplay.setTextColor(Color.BLACK); volume.setBackgroundColor(Color.WHITE); tuner.setBackgroundColor(Color.WHITE); } else { power.setBackgroundColor(Color.LTGRAY); stationDisplay.setBackgroundColor(Color.BLACK); volume.setBackgroundColor(Color.BLACK); tuner.setBackgroundColor(Color.BLACK); } } public void changePreset(View v) { if(amFm.isChecked()) { if (v == preset1) { stationDisplay.setText((float)fmPresets[0] + "FM"); } else if (v == preset2) { stationDisplay.setText((float)fmPresets[1] + "FM"); } else if (v == preset3) { stationDisplay.setText((float)fmPresets[2] + "FM"); } else if (v == preset4) { stationDisplay.setText((float)fmPresets[3] + "FM"); } else if (v == preset5) { stationDisplay.setText((float)fmPresets[4] + "FM"); } else if (v == preset6) { stationDisplay.setText((float)fmPresets[5] + "FM"); } } else { if (v == preset1) { stationDisplay.setText(amPresets[0] + "AM"); } else if (v == preset2) { stationDisplay.setText(amPresets[1] + "AM"); } else if (v == preset3) { stationDisplay.setText(amPresets[2] + "AM"); } else if (v == preset4) { stationDisplay.setText(amPresets[3] + "AM"); } else if (v == preset5) { stationDisplay.setText(amPresets[4] + "AM"); } else if (v == preset6) { stationDisplay.setText(amPresets[5] + "AM"); } } } public class ChangePresets implements View.OnLongClickListener { @Override public boolean onLongClick(View v) { if (amFm.isChecked()) { if (v == preset1) { fmPresets[0] = ((tuner.getProgress() * 0.2) + 88.1); } else if (v == preset2) { fmPresets[1] = ((tuner.getProgress() * 0.2) + 88.1); } else if (v == preset3) { fmPresets[2] = ((tuner.getProgress() * 0.2) + 88.1); } else if (v == preset4) { fmPresets[3] = ((tuner.getProgress() * 0.2) + 88.1); } else if (v == preset5) { fmPresets[4] = ((tuner.getProgress() * 0.2) + 88.1); } else if (v == preset6) { fmPresets[5] = ((tuner.getProgress() * 0.2) + 88.1); } } else { if (v == preset1) { amPresets[0] = tuner.getProgress() * 10 + 530; } else if (v == preset2) { amPresets[1] = tuner.getProgress() * 10 + 530; } else if (v == preset3) { amPresets[2] = tuner.getProgress() * 10 + 530; } else if (v == preset4) { amPresets[3] = tuner.getProgress() * 10 + 530; } else if (v == preset5) { amPresets[4] = tuner.getProgress() * 10 + 530; } else if (v == preset6) { amPresets[5] = tuner.getProgress() * 10 + 530; } } return true; } } private class ChangeSeekBarListener implements SeekBar.OnSeekBarChangeListener { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (amFm.isChecked()) { seekBar.setMax(100); float p; p = (float)((seekBar.getProgress()*0.2)+88.1); stationDisplay.setText(p + "FM"); } else { seekBar.setMax(117); int p; p = seekBar.getProgress()*10+530; stationDisplay.setText(p + "AM"); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } } private class ChangeVolumeListener implements SeekBar.OnSeekBarChangeListener { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { seekBar.setMax(10); int v; v = seekBar.getProgress(); printVol.setText(v + ""); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } } }
public class Base { public void display() { System.out.println("DIsplay from Base"); } public void printff() { System.out.println("printfff from Base"); } } public class Child extends Base { public void display() { System.out.println("DIsplay from Child"); } public void printff() { System.out.println("printfff from Child"); } } Class Main { public static void main(String... harsh) { // Base b=new Base(); // b.display(); // b.printff(); // Child c=new Child(); // c.display(); // c.printff(); Base b1=new Child(); b1.display(); b1.printff(); /* Child c1=(Child)b1; c1.display(); c1.printff(); */ } }
/* * @(#) IDbsqlInfoDAO.java * Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved. */ package com.esum.wp.ims.dbsqlinfo.dao; import java.util.List; import com.esum.appframework.dao.IBaseDAO; import com.esum.appframework.exception.ApplicationException; /** * * @author heowon@esumtech.com * @version $Revision: 1.1 $ $Date: 2008/07/31 01:49:07 $ */ public interface IDbsqlInfoDAO extends IBaseDAO { List dbsqlInfoDetail(Object object) throws ApplicationException; List dbsqlInfoPageList(Object object) throws ApplicationException; }
package testdemo; public class Test { String name; public void test() {} }
/* * PsMainFrame.java * * All Rights Reserved, Copyright(c) FUJITSU FRONTECH LIMITED 2013 */ package com.fujitsu.frontech.palmsecure_smpl; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.SourceDataLine; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.border.BevelBorder; import javax.swing.JScrollPane; import javax.swing.AbstractListModel; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionListener; import javax.swing.event.ListSelectionEvent; import com.fujitsu.frontech.palmsecure_smpl.data.PsDataManager; import com.fujitsu.frontech.palmsecure_smpl.data.PsLogManager; import com.fujitsu.frontech.palmsecure_smpl.data.PsThreadResult; import com.fujitsu.frontech.palmsecure_smpl.event.PsBusinessListener; import com.fujitsu.frontech.palmsecure_smpl.exception.PsAplException; import com.fujitsu.frontech.palmsecure_smpl.segovia.Recipient; import com.fujitsu.frontech.palmsecure_smpl.segovia.RecipientDisplay; import com.fujitsu.frontech.palmsecure_smpl.segovia.SegoviaLogoLabel; import com.fujitsu.frontech.palmsecure_smpl.xml.PsFileAccessorIni; import com.fujitsu.frontech.palmsecure_smpl.xml.PsFileAccessorLang; import com.fujitsu.frontech.palmsecure.*; import com.fujitsu.frontech.palmsecure.util.*; public class PsMainFrame extends JFrame implements ActionListener, WindowListener, PsBusinessListener { private static final long serialVersionUID = 1L; private static final String PS_HANDGUIDE_FILENAME = "PalmSecureSample_HANDGUIDE.bmp"; private static final String PS_GUIDELESS_FILENAME = "PalmSecureSample_GUIDELESS.bmp"; private static final String PS_SOUND_OK_FILENAME = "PalmSecureSample_OK.wav"; private static final String PS_SOUND_NG_FILENAME = "PalmSecureSample_NG.wav"; private static final String SEGOVIA_LOGO = "segoviaband.bmp"; private static final String PS_FONT_NAME = null; private static final int PS_BTN_FONT_SIZE = 18; private static final int PS_BTN_WIDTH = 121; private static final int PS_BTN_HEIGHT = 57; private static final int PS_REGISTER_MAX = 1000; private static final int MARGIN = 12; private JTextField txtSensorMode = null; private JTextField txtProcess = null; private JTextField txtIDNum = null; private JTextArea txtGuidance = null; private JLabel lblFirst = null; private JLabel lblID = null; private JLabel lblLocation = null; private JLabel lblVillage = null; private JLabel lblAge = null; private JLabel lblRoofing = null; //private JLabel lblRoofing = null; private JLabel lblIdList = null; private JLabel lblIDNum = null; private JList lstID = null; private JButton btnEnroll = null; private JButton btnDelete = null; private JButton btnVerify = null; private JButton btnIdentify = null; private JButton btnExport = null; private JButton btnCancel = null; private JButton btnClose = null; private PsSilhouetteLabel lblImage = null; private SegoviaLogoLabel lblLogo = null; private PsInputIdText name = null; private PsInputIdText firstName = null; private PsInputIdText location = null; private PsInputIdText village = null; private PsInputIdText age = null; //private PsInputIdText roofing = null; private long usingGuideMode = 0; private long usingSensorType = 0; private long usingSensorExtKind = 0; private String campaign = "CT201412"; private BufferedImage guideImage = null; private byte[] silhouetteLog = null; private BufferedImage logoImage = null; private PsStateCallback psStateCB = null; private PsStreamingCallback psStreamingCB = null; private PalmSecureIf palmsecureIf = null; private JAVA_uint32 ModuleHandle = null; public boolean cancelFlg = false; public boolean enrollFlg = false; public int notifiedScore = 0; public byte[] silhouette = null; public PsMainFrame() { Font buttonFont = new Font(PS_FONT_NAME, Font.BOLD, PS_BTN_FONT_SIZE); // Main window setBounds(100, 100, 800, 550); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); getContentPane().setLayout(null); // Text(display):Kind of sensor and Mode of hand-guide //txtSensorMode = new JTextField(); //txtSensorMode.setEditable(false); //txtSensorMode.setFont(new Font(PS_FONT_NAME, Font.BOLD, 20)); //txtSensorMode.setHorizontalAlignment(SwingConstants.CENTER); //txtSensorMode.setText("Sensor name"); //txtSensorMode.setBackground(Color.CYAN); //txtSensorMode.setBounds(12, 10, 760, 35); //getContentPane().add(txtSensorMode); //txtSensorMode.setColumns(10); lblLogo = new SegoviaLogoLabel(); lblLogo.setBorder(null); lblLogo.setBounds(12, 10, 760, 35); getContentPane().add(lblLogo); // Label:Image display lblImage = new PsSilhouetteLabel(); lblImage.setBorder(null); lblImage.setBounds(12, 55, 369, 264); getContentPane().add(lblImage); // Panel:ID display JPanel pnlID = new JPanel(); pnlID.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null)); pnlID.setBounds(393, 55, 246, 309); // Stretch original panel to bottom of old idlist panel getContentPane().add(pnlID); pnlID.setLayout(null); // Label:First name lblFirst = new JLabel("First:"); lblFirst.setHorizontalAlignment(SwingConstants.RIGHT); lblFirst.setFont(new Font(PS_FONT_NAME, Font.PLAIN, 16)); lblFirst.setBounds(1, 15, 84, 33); pnlID.add(lblFirst); // Text(input):first name firstName = new PsInputIdText(); firstName.setFont(new Font(PS_FONT_NAME, Font.PLAIN, 16)); firstName.setText("1234567890123456"); firstName.setBounds(92, 15, 142, 33); pnlID.add(firstName); firstName.setColumns(10); // Label:Last name lblID = new JLabel("Last:"); lblID.setHorizontalAlignment(SwingConstants.RIGHT); lblID.setFont(new Font(PS_FONT_NAME, Font.PLAIN, 16)); lblID.setBounds(1, 63, 84, 33); pnlID.add(lblID); // Text(input):Name name = new PsInputIdText(); name.setFont(new Font(PS_FONT_NAME, Font.PLAIN, 16)); name.setText("1234567890123456"); name.setBounds(92, 63, 142, 33); pnlID.add(name); name.setColumns(10); // Label:Village lblVillage = new JLabel("Village:"); lblVillage.setHorizontalAlignment(SwingConstants.RIGHT); lblVillage.setFont(new Font(PS_FONT_NAME, Font.PLAIN, 16)); lblVillage.setBounds(1, 111, 84, 33); pnlID.add(lblVillage); // Text(input):village village = new PsInputIdText(); village.setFont(new Font(PS_FONT_NAME, Font.PLAIN, 16)); village.setText("1234567890123456"); village.setBounds(92, 111, 142, 33); pnlID.add(village); village.setColumns(10); // Label:Location lblLocation = new JLabel("Location:"); lblLocation.setHorizontalAlignment(SwingConstants.RIGHT); lblLocation.setFont(new Font(PS_FONT_NAME, Font.PLAIN, 16)); lblLocation.setBounds(1, 159, 84, 33); pnlID.add(lblLocation); // Text(input):family size location = new PsInputIdText(); location.setFont(new Font(PS_FONT_NAME, Font.PLAIN, 16)); location.setText("1234567890123456"); location.setBounds(92, 159, 142, 33); pnlID.add(location); location.setColumns(10); // Label:roofing lblAge = new JLabel("Age:"); lblAge.setHorizontalAlignment(SwingConstants.RIGHT); lblAge.setFont(new Font(PS_FONT_NAME, Font.PLAIN, 16)); lblAge.setBounds(1, 207, 84, 33); pnlID.add(lblAge); // Text(input):roofing age = new PsInputIdText(); age.setFont(new Font(PS_FONT_NAME, Font.PLAIN, 16)); age.setText("1234567890123456"); age.setBounds(92, 207, 142, 33); pnlID.add(age); age.setColumns(10); // Button:Enroll btnEnroll = new JButton("Enroll"); btnEnroll.setFont(buttonFont); btnEnroll.setBounds(651, 55, PS_BTN_WIDTH, PS_BTN_HEIGHT); getContentPane().add(btnEnroll); // Button:Delete btnDelete = new JButton("Delete"); btnDelete.setFont(buttonFont); btnDelete.setBounds(651, 122, PS_BTN_WIDTH, PS_BTN_HEIGHT); getContentPane().add(btnDelete); // Button:Verify //btnVerify = new JButton("Verify"); //btnVerify.setFont(buttonFont); //btnVerify.setBounds(651, 217, PS_BTN_WIDTH, PS_BTN_HEIGHT); //getContentPane().add(btnVerify); // Button:Identify btnIdentify = new JButton("Identify"); btnIdentify.setFont(buttonFont); btnIdentify.setBounds(651, 217, PS_BTN_WIDTH, PS_BTN_HEIGHT); getContentPane().add(btnIdentify); // Button:Export btnExport = new JButton("Export"); btnExport.setFont(buttonFont); btnExport.setBounds(651, 285, PS_BTN_WIDTH, PS_BTN_HEIGHT); getContentPane().add(btnExport); // Button:Cancel btnCancel = new JButton("Cancel"); btnCancel.setEnabled(false); btnCancel.setFont(buttonFont); btnCancel.setBounds(651, 378, PS_BTN_WIDTH, PS_BTN_HEIGHT); getContentPane().add(btnCancel); // Button:Close btnClose = new JButton("Close"); btnClose.setFont(buttonFont); btnClose.setBounds(651, 445, PS_BTN_WIDTH, PS_BTN_HEIGHT); getContentPane().add(btnClose); // Text(display):Processing state txtProcess = new JTextField(); txtProcess.setText("Process"); txtProcess.setHorizontalAlignment(SwingConstants.LEFT); txtProcess.setFont(new Font(PS_FONT_NAME, Font.PLAIN, 20)); txtProcess.setEditable(false); txtProcess.setColumns(10); txtProcess.setBackground(Color.GREEN); txtProcess.setBounds(12, 329, 369, 35); getContentPane().add(txtProcess); // Text(display):Guidance txtGuidance = new JTextArea(); txtGuidance.setEditable(false); txtGuidance.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null)); txtGuidance.setFont(new Font(PS_FONT_NAME, Font.BOLD, 20)); txtGuidance.setForeground(Color.BLUE); txtGuidance.setText("Guidance"); txtGuidance.setBounds(12, 374, 627, 128); getContentPane().add(txtGuidance); // Panel:ID-list //JPanel pnlIDList = new JPanel(); //pnlIDList.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null)); //pnlIDList.setBounds(393, 122, 246, 242); //getContentPane().add(pnlIDList); //pnlIDList.setLayout(null); // Text(display):number of ID //txtIDNum = new JTextField(); //txtIDNum.setEditable(false); //txtIDNum.setHorizontalAlignment(SwingConstants.RIGHT); //txtIDNum.setText("1000"); //txtIDNum.setFont(new Font(PS_FONT_NAME, Font.PLAIN, 16)); //txtIDNum.setColumns(10); //txtIDNum.setBounds(185, 10, 49, 26); //pnlIDList.add(txtIDNum); // Label:ID-list //lblIdList = new JLabel("ID List"); //lblIdList.setFont(new Font("MS UI Gothic", Font.PLAIN, 14)); //lblIdList.setBounds(12, 20, 68, 26); //pnlIDList.add(lblIdList); // label:number of ID //lblIDNum = new JLabel("ID num"); //lblIDNum.setHorizontalAlignment(SwingConstants.RIGHT); //lblIDNum.setFont(new Font("MS UI Gothic", Font.PLAIN, 14)); //lblIDNum.setBounds(74, 9, 100, 26); //pnlIDList.add(lblIDNum); // list:ID //JScrollPane scrollPane = new JScrollPane(); //scrollPane.setBounds(12, 46, 222, 186); //pnlIDList.add(scrollPane); //lstID = new JList(); //lstID.addListSelectionListener(new ListSelectionListener() { // public void valueChanged(ListSelectionEvent arg0) { // String selectID = (String) lstID.getSelectedValue(); // name.setText(selectID); // } //}); //lstID.addMouseListener(new MouseListener() { // public void mouseClicked(MouseEvent e) { // String selectID = (String) lstID.getSelectedValue(); // name.setText(selectID); // } // public void mousePressed(MouseEvent e) { // } // public void mouseReleased(MouseEvent e) { // } // public void mouseEntered(MouseEvent e) { // } // public void mouseExited(MouseEvent e) { // } //}); //lstID.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //lstID.setFont(new Font("MS UI Gothic", Font.PLAIN, 16)); //lstID.setModel(new AbstractListModel() { // private static final long serialVersionUID = 1L; // String[] values = new String[] {"1234567890123456", "id2"}; // public int getSize() { // return values.length; // } // public Object getElementAt(int index) { // return values[index]; // } //}); //scrollPane.setViewportView(lstID); } public boolean Ps_Sample_Apl_Java() { File checkFile = null; checkFile = new File(PsFileAccessorLang.FileName); if (!checkFile.exists()) { JOptionPane.showMessageDialog( null, "Read Error " + PsFileAccessorLang.FileName, null, JOptionPane.ERROR_MESSAGE); System.exit(0); } checkFile = new File(PsFileAccessorIni.FileName); if (!checkFile.exists()) { JOptionPane.showMessageDialog( null, "Read Error " + PsFileAccessorIni.FileName, null, JOptionPane.ERROR_MESSAGE); System.exit(0); } checkFile = new File(PS_GUIDELESS_FILENAME); if (!checkFile.exists()) { JOptionPane.showMessageDialog( null, "Read Error " + PS_GUIDELESS_FILENAME, null, JOptionPane.ERROR_MESSAGE); System.exit(0); } checkFile = new File(PS_HANDGUIDE_FILENAME); if (!checkFile.exists()) { JOptionPane.showMessageDialog( null, "Read Error " + PS_HANDGUIDE_FILENAME, null, JOptionPane.ERROR_MESSAGE); System.exit(0); } checkFile = new File(PS_SOUND_OK_FILENAME); if (!checkFile.exists()) { JOptionPane.showMessageDialog( null, "Read Error " + PS_SOUND_OK_FILENAME, null, JOptionPane.ERROR_MESSAGE); System.exit(0); } checkFile = new File(PS_SOUND_NG_FILENAME); if (!checkFile.exists()) { JOptionPane.showMessageDialog( null, "Read Error " + PS_SOUND_NG_FILENAME, null, JOptionPane.ERROR_MESSAGE); System.exit(0); } // Read the language file. PsFileAccessorLang psFileAcsLang = PsFileAccessorLang.GetInstance(); if (psFileAcsLang == null) { JOptionPane.showMessageDialog( null, "Read Error " + PsFileAccessorLang.FileName, null, JOptionPane.ERROR_MESSAGE); System.exit(0); } // Read the Configuration file. PsFileAccessorIni psFileAcsIni = PsFileAccessorIni.GetInstance(); if (psFileAcsIni == null) { JOptionPane.showMessageDialog( null, "Read Error " + PsFileAccessorIni.FileName, null, JOptionPane.ERROR_MESSAGE); System.exit(0); } // Initialize the Authentication library. if (!Ps_Sample_Apl_Java_InitLibrary()) { System.exit(0); } if (usingSensorType == PalmSecureConstant.JAVA_PvAPI_INFO_SENSOR_TYPE_4) { PsFileAccessorLang.GetInstance().SetValue( PsFileAccessorLang.Guidance_WorkEnroll, PsFileAccessorLang.GetInstance().GetValue(PsFileAccessorLang.Guidance_WorkEnroll3)); if (usingSensorExtKind == PalmSecureConstant.JAVA_PvAPI_INFO_SENSOR_MODE_EXTEND) { usingSensorType = PalmSecureConstant.JAVA_PvAPI_INFO_SENSOR_TYPE_8; PsFileAccessorLang.GetInstance().SetValue( PsFileAccessorLang.MainDialog_SensorName7, PsFileAccessorLang.GetInstance().GetValue(PsFileAccessorLang.MainDialog_SensorName3)); } } else if (usingSensorType == PalmSecureConstant.JAVA_PvAPI_INFO_SENSOR_TYPE_2) { if (usingSensorExtKind == PalmSecureConstant.JAVA_PvAPI_INFO_SENSOR_MODE_COMPATIBLE) { PsFileAccessorLang.GetInstance().SetValue( PsFileAccessorLang.MainDialog_SensorName1, PsFileAccessorLang.GetInstance().GetValue(PsFileAccessorLang.MainDialog_SensorName1_Compati)); } else if (usingSensorExtKind == PalmSecureConstant.JAVA_PvAPI_INFO_SENSOR_MODE_EXTEND){ PsFileAccessorLang.GetInstance().SetValue( PsFileAccessorLang.MainDialog_SensorName1, PsFileAccessorLang.GetInstance().GetValue(PsFileAccessorLang.MainDialog_SensorName1_Extend)); } } else if (usingSensorType == PalmSecureConstant.JAVA_PvAPI_INFO_SENSOR_TYPE_8) { PsFileAccessorLang.GetInstance().SetValue( PsFileAccessorLang.Guidance_WorkEnroll, PsFileAccessorLang.GetInstance().GetValue(PsFileAccessorLang.Guidance_WorkEnroll3)); } try { Ps_Sample_Apl_Java_ReadGuideBmp(); ReadLogoBmp(); Ps_Sample_Apl_Java_InitControls(); Ps_Sample_Apl_Java_InitIdList(); } catch(PsAplException pae) { JOptionPane.showMessageDialog(null, "Initialize Error"); System.exit(0); } return true; } /** * Initialize the Authentication library. */ private boolean Ps_Sample_Apl_Java_InitLibrary() { long ret = PalmSecureConstant.JAVA_BioAPI_FALSE; String Key = PsFileAccessorIni.GetInstance().GetValueString( PsFileAccessorIni.ApplicationKey); byte[] ModuleGuid = new byte[]{ (byte)0xe1, (byte)0x9a, (byte)0x69, (byte)0x01, (byte)0xb8, (byte)0xc2, (byte)0x49, (byte)0x80, (byte)0x87, (byte)0x7e, (byte)0x11, (byte)0xd4, (byte)0xd8, (byte)0xf1, (byte)0xbe, (byte)0x79 }; JAVA_uint32 lpuiSensorNum = new JAVA_uint32(); JAVA_PvAPI_SensorInfoEx[] lptSensorInfo = new JAVA_PvAPI_SensorInfoEx[(int)PalmSecureConstant.JAVA_PvAPI_GET_SENSOR_INFO_MAX]; JAVA_PvAPI_LBINFO lbInfo = new JAVA_PvAPI_LBINFO(); JAVA_PvAPI_ErrorInfo errorInfo = new JAVA_PvAPI_ErrorInfo(); //Create a instance of PalmSecureIf class /////////////////////////////////////////////////////////////////////////// palmsecureIf = new PalmSecureIf(); /////////////////////////////////////////////////////////////////////////// //Authenticate application by key /////////////////////////////////////////////////////////////////////////// try { ret = palmsecureIf.JAVA_PvAPI_ApAuthenticate(Key); if (ret != PalmSecureConstant.JAVA_BioAPI_OK) { palmsecureIf.JAVA_PvAPI_GetErrorInfo(errorInfo); PsMessageDialog.Ps_Sample_Apl_Java_ShowErrorDialog(this, errorInfo); return false; } } catch(PalmSecureException e) { PsMessageDialog.Ps_Sample_Apl_Java_ShowErrorDialog(this, e); return false; } /////////////////////////////////////////////////////////////////////////// //Load module /////////////////////////////////////////////////////////////////////////// try { ret = palmsecureIf.JAVA_BioAPI_ModuleLoad(ModuleGuid, null, null, null); if (ret != PalmSecureConstant.JAVA_BioAPI_OK) { palmsecureIf.JAVA_PvAPI_GetErrorInfo(errorInfo); PsMessageDialog.Ps_Sample_Apl_Java_ShowErrorDialog(this, errorInfo); return false; } } catch(PalmSecureException e) { PsMessageDialog.Ps_Sample_Apl_Java_ShowErrorDialog(this, e); return false; } /////////////////////////////////////////////////////////////////////////// //Get connected sensor information /////////////////////////////////////////////////////////////////////////// try { ret = palmsecureIf.JAVA_PvAPI_GetConnectSensorInfoEx( lpuiSensorNum, lptSensorInfo); if (ret != PalmSecureConstant.JAVA_BioAPI_OK) { palmsecureIf.JAVA_PvAPI_GetErrorInfo(errorInfo); PsMessageDialog.Ps_Sample_Apl_Java_ShowErrorDialog(this, errorInfo); return false; } } catch(PalmSecureException e) { PsMessageDialog.Ps_Sample_Apl_Java_ShowErrorDialog(this, e); return false; } /////////////////////////////////////////////////////////////////////////// //Attatch to module /////////////////////////////////////////////////////////////////////////// try { ModuleHandle = new JAVA_uint32(); ret = palmsecureIf.JAVA_BioAPI_ModuleAttach( ModuleGuid, null, null, null, null, null, null, null, null, null, ModuleHandle); if (ret != PalmSecureConstant.JAVA_BioAPI_OK) { palmsecureIf.JAVA_PvAPI_GetErrorInfo(errorInfo); PsMessageDialog.Ps_Sample_Apl_Java_ShowErrorDialog(this, errorInfo); return false; } } catch(PalmSecureException e) { PsMessageDialog.Ps_Sample_Apl_Java_ShowErrorDialog(this, e); return false; } /////////////////////////////////////////////////////////////////////////// //Set action listener /////////////////////////////////////////////////////////////////////////// try { psStreamingCB = new PsStreamingCallback(); psStateCB = new PsStateCallback(); ret = palmsecureIf.JAVA_BioAPI_SetGUICallbacks( ModuleHandle, psStreamingCB, this, psStateCB, this); if (ret != PalmSecureConstant.JAVA_BioAPI_OK) { palmsecureIf.JAVA_PvAPI_GetErrorInfo(errorInfo); PsMessageDialog.Ps_Sample_Apl_Java_ShowErrorDialog(this, errorInfo); return false; } } catch(PalmSecureException e) { PsMessageDialog.Ps_Sample_Apl_Java_ShowErrorDialog(this, e); return false; } /////////////////////////////////////////////////////////////////////////// //Get library information /////////////////////////////////////////////////////////////////////////// try { ret = palmsecureIf.JAVA_PvAPI_GetLibraryInfo(lbInfo); if (ret != PalmSecureConstant.JAVA_BioAPI_OK) { palmsecureIf.JAVA_PvAPI_GetErrorInfo(errorInfo); PsMessageDialog.Ps_Sample_Apl_Java_ShowErrorDialog(this, errorInfo); return false; } } catch(PalmSecureException e) { PsMessageDialog.Ps_Sample_Apl_Java_ShowErrorDialog(this, e); return false; } /////////////////////////////////////////////////////////////////////////// usingSensorType = (int)lptSensorInfo[0].uiSensor; usingSensorExtKind = lbInfo.uiSensorExtKind; usingGuideMode = PsFileAccessorIni.GetInstance().GetValueInteger(PsFileAccessorIni.GuideMode); //Set guide mode /////////////////////////////////////////////////////////////////////////// JAVA_uint32 dwFlag = new JAVA_uint32(); dwFlag.value = PalmSecureConstant.JAVA_PvAPI_PROFILE_GUIDE_MODE; JAVA_uint32 dwParam1 = new JAVA_uint32(); if ( usingGuideMode == 1 ) { dwParam1.value = (int)PalmSecureConstant.JAVA_PvAPI_PROFILE_GUIDE_MODE_GUIDE; } else { dwParam1.value = (int)PalmSecureConstant.JAVA_PvAPI_PROFILE_GUIDE_MODE_NO_GUIDE; } try { ret = palmsecureIf.JAVA_PvAPI_SetProfile( ModuleHandle, dwFlag, dwParam1, null, null); if (ret != PalmSecureConstant.JAVA_BioAPI_OK) { palmsecureIf.JAVA_PvAPI_GetErrorInfo(errorInfo); PsMessageDialog.Ps_Sample_Apl_Java_ShowErrorDialog(this, errorInfo); return false; } } catch(PalmSecureException e) { PsMessageDialog.Ps_Sample_Apl_Java_ShowErrorDialog(this, e); return false; } /////////////////////////////////////////////////////////////////////////// return true; } /** * Terminate the Authentication library. */ private void Ps_Sample_Apl_Java_TermLibrary() { long ret = PalmSecureConstant.JAVA_BioAPI_FALSE; byte[] ModuleGuid = new byte[]{ (byte)0xe1, (byte)0x9a, (byte)0x69, (byte)0x01, (byte)0xb8, (byte)0xc2, (byte)0x49, (byte)0x80, (byte)0x87, (byte)0x7e, (byte)0x11, (byte)0xd4, (byte)0xd8, (byte)0xf1, (byte)0xbe, (byte)0x79 }; //Detach module /////////////////////////////////////////////////////////////////////////// try { ret = palmsecureIf.JAVA_BioAPI_ModuleDetach( ModuleHandle); } catch(PalmSecureException e) { } /////////////////////////////////////////////////////////////////////////// //Unload module /////////////////////////////////////////////////////////////////////////// try { ret = palmsecureIf.JAVA_BioAPI_ModuleUnload( ModuleGuid, null, null); } catch(PalmSecureException e) { } /////////////////////////////////////////////////////////////////////////// return; } public void Ps_Sample_Apl_Java_SetSilhouette(JAVA_BioAPI_GUI_BITMAP Bitmap) { byte[] silhouette = Bitmap.Bitmap.Data; if ((silhouette != null) && (0 < silhouette.length)) { try { // Display the silhouette image. lblImage.Ps_Sample_Apl_Java_SetSilhouette(silhouette); this.silhouette = silhouette; lblImage.repaint(); silhouetteLog = silhouette; } catch (IOException ioEx) { } } } public byte[] Ps_Sample_Apl_Java_GetSilhouette() { return this.silhouette; } public void Ps_Sample_Apl_Java_PlayWave(String fileName) { try { File soundFile = new File(fileName); AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundFile); AudioFormat audioFormat = audioInputStream.getFormat(); DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info); line.open(audioFormat); line.start(); int nBytesRead = 0; byte[] abData = new byte[128000]; while (nBytesRead != -1) { nBytesRead = audioInputStream.read(abData, 0, abData.length); if (nBytesRead >= 0) { line.write(abData, 0, nBytesRead); } } line.drain(); line.close(); } catch (Exception e) { } } public void Ps_Sample_Apl_Java_SetSilhouetteLog(byte[] silhouetteLog) { this.silhouetteLog = silhouetteLog; } public byte[] Ps_Sample_Apl_Java_GetSilhouetteLog() { return silhouetteLog; } private void Ps_Sample_Apl_Java_ReadGuideBmp() throws PsAplException { guideImage = null; File guideFile; if ( usingGuideMode == 0 ) { guideFile = new File(PS_GUIDELESS_FILENAME); } else { guideFile = new File(PS_HANDGUIDE_FILENAME); } try { guideImage = ImageIO.read(guideFile); } catch (IOException e) { PsAplException pae = new PsAplException(PsFileAccessorLang.ErrorMessage_AplErrorGuideBmpLoad); throw pae; } if (guideImage == null) { PsAplException pae = new PsAplException(PsFileAccessorLang.ErrorMessage_AplErrorGuideBmpLoad); throw pae; } } private void Ps_Sample_Apl_Java_DisplayGuideBmp() { if (guideImage != null) { lblImage.Ps_Sample_Apl_Java_SetHandGuide(guideImage); lblImage.repaint(); } } private void ReadLogoBmp() throws PsAplException { logoImage = null; File logoFile = new File(SEGOVIA_LOGO); try { logoImage = ImageIO.read(logoFile); } catch (IOException e) { PsAplException pae = new PsAplException(PsFileAccessorLang.ErrorMessage_AplErrorGuideBmpLoad); throw pae; } if (logoImage == null) { PsAplException pae = new PsAplException(PsFileAccessorLang.ErrorMessage_AplErrorGuideBmpLoad); throw pae; } } private void SetSegoviaLogoBmp() { if (logoImage != null) { lblLogo.SetLogo(logoImage); lblLogo.repaint(); } } private void Ps_Sample_Apl_Java_SetGuidance(String guidanceKey, boolean error) { PsFileAccessorLang langAcs = PsFileAccessorLang.GetInstance(); String guidance; if (guidanceKey.compareTo("") == 0) { guidance = ""; } else { guidance = langAcs.GetValue(guidanceKey); } txtGuidance.setText(guidance); if (error) { txtGuidance.setForeground(Color.RED); } else { txtGuidance.setForeground(Color.BLUE); } } private void Ps_Sample_Apl_Java_SetGuidance(String guidanceKey, boolean error, String userID) { PsFileAccessorLang langAcs = PsFileAccessorLang.GetInstance(); String guidance; if (guidanceKey.compareTo("") == 0) { guidance = ""; } else { guidance = langAcs.GetValue(guidanceKey).replaceAll("\\{0\\}", userID); } txtGuidance.setText(guidance); if (error) { txtGuidance.setForeground(Color.RED); } else { txtGuidance.setForeground(Color.BLUE); } } private void Ps_Sample_Apl_Java_SetWorkMessage(String msgKey) { PsFileAccessorLang langAcs = PsFileAccessorLang.GetInstance(); if (msgKey.compareTo("") == 0) { txtProcess.setText(""); txtProcess.setBackground(Color.WHITE); } else { txtProcess.setText(langAcs.GetValue(msgKey)); txtProcess.setBackground(Color.GREEN); } } private void Ps_Sample_Apl_Java_SetWorkMessage(String msgKey, int count) { PsFileAccessorLang langAcs = PsFileAccessorLang.GetInstance(); if (msgKey.compareTo("") == 0) { txtProcess.setText(""); txtProcess.setBackground(Color.WHITE); } else { String workMessage = langAcs.GetValue(msgKey).replaceAll("\\{0\\}", String.valueOf(count)); txtProcess.setText(workMessage); txtProcess.setBackground(Color.GREEN); } } private void Ps_Sample_Apl_Java_InitControls() { PsFileAccessorLang langAcs = PsFileAccessorLang.GetInstance(); // Main window. String title = langAcs.GetValue(PsFileAccessorLang.MainDialog_Title); setTitle(title); Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); setLocation((d.width - getSize().width) / 2, (d.height - getSize().height) / 2); setResizable(false); // Text(display):Kind of sensor and Mode of hand-guide String sensorMode = langAcs.GetValue(PsFileAccessorLang.MainDialog_SensorName + String.valueOf(usingSensorType)); String guide = null; if ( usingGuideMode == 0 ) { guide = langAcs.GetValue(PsFileAccessorLang.MainDialog_GuideMode0); } else { guide = langAcs.GetValue(PsFileAccessorLang.MainDialog_GuideMode1); } sensorMode += " " + guide; //txtSensorMode.setText(sensorMode); // Show logo lblLogo.setText(""); SetSegoviaLogoBmp(); // Label:Image display lblImage.setText(""); Ps_Sample_Apl_Java_DisplayGuideBmp(); // Label:ID //String idLblTxt = langAcs.GetValue(PsFileAccessorLang.MainDialog_IdLbl); //lblID.setText(idLblTxt); // Text(input):name name.setText(""); // Text(input):first name firstName.setText(""); // Text(input):village village.setText(""); // Text(input):age age.setText(""); // Text(input):location location.setText(""); // Button:Enroll String enrollBtnTxt = langAcs.GetValue(PsFileAccessorLang.MainDialog_EnrollBtn); btnEnroll.setText(enrollBtnTxt); btnEnroll.addActionListener(this); // Button:Delete String deleteBtnTxt = langAcs.GetValue(PsFileAccessorLang.MainDialog_DeleteBtn); btnDelete.setText(deleteBtnTxt); btnDelete.addActionListener(this); // Button:Verify //String verifyBtnTxt = langAcs.GetValue(PsFileAccessorLang.MainDialog_VerifyBtn); //btnVerify.setText(verifyBtnTxt); //btnVerify.addActionListener(this); // Button:Identify String identifyBtnTxt = langAcs.GetValue(PsFileAccessorLang.MainDialog_IdentifyBtn); btnIdentify.setText(identifyBtnTxt); btnIdentify.addActionListener(this); // Button:Cancel String cancelBtnTxt = langAcs.GetValue(PsFileAccessorLang.MainDialog_CancelBtn); btnCancel.setText(cancelBtnTxt); btnCancel.addActionListener(this); // Button:Close String exitBtnTxt = langAcs.GetValue(PsFileAccessorLang.MainDialog_ExitBtn); btnClose.setText(exitBtnTxt); btnClose.addActionListener(this); // Text(display):Processing state txtProcess.setText(""); txtProcess.setBackground(Color.WHITE); // Text(display):Guidance txtGuidance.setText(""); txtGuidance.setOpaque(true); txtGuidance.setForeground(Color.BLUE); txtGuidance.setBackground(Color.WHITE); txtGuidance.setLineWrap(true); // Text(display):number of ID //txtIDNum.setText(""); // Label:ID-list //String idListTxt = langAcs.GetValue(PsFileAccessorLang.MainDialog_IdListLbl); //lblIdList.setText(idListTxt); // Label:number of ID //String idNumTxt = langAcs.GetValue(PsFileAccessorLang.MainDialog_IdNumLbl); //lblIDNum.setText(idNumTxt); addWindowListener(this); } /* * Note that this method initializes internal data structure as well as GUI element! * @throws PsAplException */ private void Ps_Sample_Apl_Java_InitIdList() throws PsAplException { PsDataManager dataMng = PsDataManager.GetInstance(); dataMng.Ps_Sample_Apl_Java_Init(usingSensorType, usingGuideMode, campaign); //Ps_Sample_Apl_Java_UpdateIdList(); } private void Ps_Sample_Apl_Java_UpdateIdList() { // PsDataManager dataMng = PsDataManager.GetInstance(); // ArrayList<String> idList = dataMng.Ps_Sample_Apl_Java_GetAllUserId(); // lstID.setListData(idList.toArray()); // Integer intNum = new Integer(idList.size()); // txtIDNum.setText(intNum.toString()); } public void Ps_Sample_Apl_Java_InitState() { Ps_Sample_Apl_Java_SetComponentEnabled(true); name.requestFocus(); name.selectAll(); cancelFlg = false; } private void Ps_Sample_Apl_Java_SetComponentEnabled(boolean enabled) { if (enabled) { btnEnroll.setEnabled(true); btnDelete.setEnabled(true); //btnVerify.setEnabled(true); btnIdentify.setEnabled(true); btnExport.setEnabled(true); btnCancel.setEnabled(false); btnClose.setEnabled(true); name.setEnabled(true); firstName.setEnabled(true); village.setEnabled(true); age.setEnabled(true); location.setEnabled(true); } else { btnEnroll.setEnabled(false); btnDelete.setEnabled(false); //btnVerify.setEnabled(false); btnIdentify.setEnabled(false); btnExport.setEnabled(false); btnCancel.setEnabled(true); btnClose.setEnabled(false); name.setEnabled(false); firstName.setEnabled(false); village.setEnabled(false); age.setEnabled(false); location.setEnabled(false); } } //TODO: this is the method in which we need to handle the other fields private void Ps_Sample_Apl_Java_ActionEnroll() { PsDataManager dataMng = PsDataManager.GetInstance(); String gdid = dataMng.nextGDID(); Recipient recipient = new Recipient(gdid); Ps_Sample_Apl_Java_SetWorkMessage(PsFileAccessorLang.Guidance_WorkEnrollStart); Ps_Sample_Apl_Java_SetGuidance("", false); Ps_Sample_Apl_Java_DisplayGuideBmp(); recipient.update("lastName", name.getText()); recipient.update("firstName", firstName.getText()); recipient.update("village", village.getText()); recipient.update("age", age.getText()); recipient.update("location", location.getText()); recipient.update("recipient_name", firstName.getText() + " " + name.getText()); if (recipient.get("firstName").compareTo("") == 0) { Ps_Sample_Apl_Java_SetGuidance(PsFileAccessorLang.Guidance_IllegalId, true); Ps_Sample_Apl_Java_SetWorkMessage(""); Ps_Sample_Apl_Java_InitState(); return; } if (dataMng.Ps_Sample_Apl_Java_IsRegist(gdid)) { // Will always be false, got next avail gdid. Ps_Sample_Apl_Java_SetGuidance(PsFileAccessorLang.Guidance_RegistId, true); Ps_Sample_Apl_Java_SetWorkMessage(""); Ps_Sample_Apl_Java_InitState(); return; } if (dataMng.Ps_Sample_Apl_Java_GetRegistNum() >= PS_REGISTER_MAX) { Ps_Sample_Apl_Java_SetGuidance(PsFileAccessorLang.Guidance_MaxOver, true); Ps_Sample_Apl_Java_SetWorkMessage(""); Ps_Sample_Apl_Java_InitState(); return; } Ps_Sample_Apl_Java_SetComponentEnabled(false); notifiedScore = PalmSecureConstant.JAVA_PvAPI_REGIST_SCORE_QUALITY_1; PsThreadEnroll enrollThread = new PsThreadEnroll(this, this, palmsecureIf, ModuleHandle, recipient); enrollThread.start(); btnCancel.requestFocus(); } private void Ps_Sample_Apl_Java_ActionDelete() { PsDataManager dataMng = PsDataManager.GetInstance(); Ps_Sample_Apl_Java_SetWorkMessage(PsFileAccessorLang.Guidance_WorkDelete); Ps_Sample_Apl_Java_SetGuidance("", false); String id = name.getText(); if (id.compareTo("") == 0) { Ps_Sample_Apl_Java_SetGuidance(PsFileAccessorLang.Guidance_IllegalId, true); Ps_Sample_Apl_Java_SetWorkMessage(""); return; } if (!dataMng.Ps_Sample_Apl_Java_IsRegist(id)) { Ps_Sample_Apl_Java_SetGuidance(PsFileAccessorLang.Guidance_UnregistId, true); Ps_Sample_Apl_Java_SetWorkMessage(""); return; } Ps_Sample_Apl_Java_SetComponentEnabled(false); btnCancel.setEnabled(false); int action = PsMessageDialog.Ps_Sample_Apl_Java_ShowConfirmDialog(this, PsFileAccessorLang.ConfirmMessage_Delete); if (action == JOptionPane.CANCEL_OPTION) { Ps_Sample_Apl_Java_InitState(); Ps_Sample_Apl_Java_SetWorkMessage(""); return; } try { dataMng.Ps_Sample_Apl_Java_Delete(id); Ps_Sample_Apl_Java_SetGuidance(PsFileAccessorLang.CompleteMessage_Delete, false); } catch (PsAplException ex) { Ps_Sample_Apl_Java_SetGuidance(ex.getErrorMsgKey(), true); } try { Ps_Sample_Apl_Java_InitState(); Ps_Sample_Apl_Java_InitIdList(); Ps_Sample_Apl_Java_SetWorkMessage(""); } catch(PsAplException pae) { } } private void Ps_Sample_Apl_Java_ActionVerify() { PsDataManager dataMng = PsDataManager.GetInstance(); Ps_Sample_Apl_Java_SetWorkMessage(PsFileAccessorLang.Guidance_WorkVerifyStart); Ps_Sample_Apl_Java_SetGuidance("", false); Ps_Sample_Apl_Java_DisplayGuideBmp(); String id = name.getText(); if (id.compareTo("") == 0) { Ps_Sample_Apl_Java_SetGuidance(PsFileAccessorLang.Guidance_IllegalId, true); Ps_Sample_Apl_Java_SetWorkMessage(""); return; } if (!dataMng.Ps_Sample_Apl_Java_IsRegist(id)) { Ps_Sample_Apl_Java_SetGuidance(PsFileAccessorLang.Guidance_UnregistId, true); Ps_Sample_Apl_Java_SetWorkMessage(""); return; } // Execute verification process. Ps_Sample_Apl_Java_SetComponentEnabled(false); PsThreadVerify verifyThread = new PsThreadVerify(this, this, palmsecureIf, ModuleHandle, id); verifyThread.start(); btnCancel.requestFocus(); } private void Ps_Sample_Apl_Java_ActionIdentify() { PsDataManager dataMng = PsDataManager.GetInstance(); Ps_Sample_Apl_Java_SetWorkMessage(PsFileAccessorLang.Guidance_WorkIdentifyStart); Ps_Sample_Apl_Java_SetGuidance("", false); Ps_Sample_Apl_Java_DisplayGuideBmp(); if (dataMng.Ps_Sample_Apl_Java_GetRegistNum() <= 0) { Ps_Sample_Apl_Java_SetGuidance(PsFileAccessorLang.Guidance_Unregist, true); Ps_Sample_Apl_Java_SetWorkMessage(""); return; } // Execute identification process. Ps_Sample_Apl_Java_SetComponentEnabled(false); PsThreadIdentify identifyThread = new PsThreadIdentify(this, this, palmsecureIf, ModuleHandle); identifyThread.start(); btnCancel.requestFocus(); } private void Ps_Sample_Apl_Java_ActionCancel() { PsThreadCancel cancelThread = new PsThreadCancel(this, this, palmsecureIf, ModuleHandle); cancelThread.start(); cancelFlg = true; } private void Ps_Sample_Apl_Java_ActionExit() { Ps_Sample_Apl_Java_TermLibrary(); System.exit(0); } public void Ps_Sample_Apl_Java_NotifyWorkMessage(String processKey) { Ps_Sample_Apl_Java_SetWorkMessage(processKey); } public void Ps_Sample_Apl_Java_NotifyWorkMessage(String processKey, int count) { Ps_Sample_Apl_Java_SetWorkMessage(processKey, count); } public void Ps_Sample_Apl_Java_NotifyGuidance(String guidanceKey, boolean error) { Ps_Sample_Apl_Java_SetGuidance(guidanceKey, error); } public void Ps_Sample_Apl_Java_NotifyResult_Enroll(PsThreadResult stResult, int enrollscore) { PsFileAccessorIni iniAcs = PsFileAccessorIni.GetInstance(); PsLogManager logMng = PsLogManager.GetInstance(); boolean enrollResult = false; //Show a guidance message. if (stResult.result != PalmSecureConstant.JAVA_BioAPI_OK || stResult.authenticated == false || cancelFlg == true) { if (cancelFlg == true) { Ps_Sample_Apl_Java_SetGuidance(PsFileAccessorLang.CompleteMessage_EnrollCancel, false); } else { Ps_Sample_Apl_Java_SetGuidance(PsFileAccessorLang.CompleteMessage_EnrollNg, true); } } else { enrollResult = true; if (enrollscore > PalmSecureConstant.JAVA_PvAPI_REGIST_SCORE_QUALITY_2 || stResult.farAchieved.get(0) < 3000) { Ps_Sample_Apl_Java_SetGuidance(PsFileAccessorLang.CompleteMessage_EnrollRetry, false); } else { Ps_Sample_Apl_Java_SetGuidance(PsFileAccessorLang.CompleteMessage_EnrollOk, false); } } //Output a silhouette image String silhouetteFile = new String(); if (iniAcs.GetValueInteger(PsFileAccessorIni.SilhouetteMode) == 1 && stResult.result == PalmSecureConstant.JAVA_BioAPI_OK && stResult.info != null && cancelFlg != true) { try { silhouetteFile = logMng.Ps_Sample_Apl_Java_OutputSilhouette( iniAcs.GetValueString(PsFileAccessorIni.LogFolderPath), usingSensorType, usingGuideMode, "E", stResult.info); } catch (PsAplException pae) { PsMessageDialog.Ps_Sample_Apl_Java_ShowErrorDialog(this, pae.getErrorMsgKey()); } } if (iniAcs.GetValueInteger(PsFileAccessorIni.LogMode) == 1 && stResult.result == PalmSecureConstant.JAVA_BioAPI_OK && cancelFlg != true) { // Output log try { logMng.Ps_Sample_Apl_Java_WriteLog( iniAcs.GetValueString(PsFileAccessorIni.LogFolderPath), usingSensorType, usingGuideMode, "E", enrollResult, stResult.retryCnt, silhouetteFile, stResult.userId, stResult.farAchieved); } catch (PsAplException pae) { PsMessageDialog.Ps_Sample_Apl_Java_ShowErrorDialog(this, pae.getErrorMsgKey()); } } try { Ps_Sample_Apl_Java_InitState(); Ps_Sample_Apl_Java_InitIdList(); Ps_Sample_Apl_Java_SetWorkMessage(""); } catch(PsAplException pae) { } return; } public void Ps_Sample_Apl_Java_NotifyResult_Verify(PsThreadResult stResult) { PsFileAccessorIni iniAcs = PsFileAccessorIni.GetInstance(); PsLogManager logMng = PsLogManager.GetInstance(); boolean verifyResult = false; //Show a guidance message. try { if (stResult.result == PalmSecureConstant.JAVA_BioAPI_OK && stResult.authenticated == true && cancelFlg != true) { verifyResult = true; Ps_Sample_Apl_Java_PlayWave(PS_SOUND_OK_FILENAME); Ps_Sample_Apl_Java_SetGuidance( PsFileAccessorLang.CompleteMessage_VerifyOk, false, stResult.userId.get(0)); } else { if (cancelFlg == true) { Ps_Sample_Apl_Java_SetGuidance( PsFileAccessorLang.CompleteMessage_VerifyCancel, false); } else { Ps_Sample_Apl_Java_PlayWave(PS_SOUND_NG_FILENAME); Ps_Sample_Apl_Java_SetGuidance( PsFileAccessorLang.CompleteMessage_VerifyNg, true, stResult.userId.get(0)); } } } catch(Exception e) { } //Output a silhouette image String silhouetteFile = new String(); if (iniAcs.GetValueInteger(PsFileAccessorIni.SilhouetteMode) == 1 && stResult.result == PalmSecureConstant.JAVA_BioAPI_OK && stResult.info != null && cancelFlg != true) { try { silhouetteFile = logMng.Ps_Sample_Apl_Java_OutputSilhouette( iniAcs.GetValueString(PsFileAccessorIni.LogFolderPath), usingSensorType, usingGuideMode, "V", stResult.info); } catch (PsAplException pae) { PsMessageDialog.Ps_Sample_Apl_Java_ShowErrorDialog(this, pae.getErrorMsgKey()); } } //Output log messages if (iniAcs.GetValueInteger(PsFileAccessorIni.LogMode) == 1 && stResult.result == PalmSecureConstant.JAVA_BioAPI_OK && cancelFlg != true) { ArrayList<String> idList = new ArrayList<String>(); idList.add(name.getText()); // Output log try { logMng.Ps_Sample_Apl_Java_WriteLog( iniAcs.GetValueString(PsFileAccessorIni.LogFolderPath), usingSensorType, usingGuideMode, "V", verifyResult, stResult.retryCnt, silhouetteFile, stResult.userId, stResult.farAchieved); } catch (PsAplException pae) { PsMessageDialog.Ps_Sample_Apl_Java_ShowErrorDialog(this, pae.getErrorMsgKey()); } } Ps_Sample_Apl_Java_InitState(); Ps_Sample_Apl_Java_SetWorkMessage(""); return; } public void Ps_Sample_Apl_Java_NotifyResult_Identify(PsThreadResult stResult) { PsFileAccessorIni iniAcs = PsFileAccessorIni.GetInstance(); PsLogManager logMng = PsLogManager.GetInstance(); boolean identifyResult = false; //Show a guidance message. try { if (stResult.result == PalmSecureConstant.JAVA_BioAPI_OK && stResult.farAchieved.size() > 0 && stResult.authenticated == true && cancelFlg != true) { identifyResult = true; Ps_Sample_Apl_Java_PlayWave(PS_SOUND_OK_FILENAME); Ps_Sample_Apl_Java_SetGuidance( PsFileAccessorLang.CompleteMessage_IdentifyOk, false, stResult.userId.get(0)); // Show message dialog with info RecipientDisplay.showRecipientDialog(this,stResult.recipient); } else { if (cancelFlg == true) { Ps_Sample_Apl_Java_SetGuidance( PsFileAccessorLang.CompleteMessage_IdentifyCancel, false); } else { Ps_Sample_Apl_Java_PlayWave(PS_SOUND_NG_FILENAME); Ps_Sample_Apl_Java_SetGuidance( PsFileAccessorLang.CompleteMessage_IdentifyNg, true); } } } catch(Exception e) { } //Output a silhouette image String silhouetteFile = new String(); if (iniAcs.GetValueInteger(PsFileAccessorIni.SilhouetteMode) == 1 && stResult.result == PalmSecureConstant.JAVA_BioAPI_OK && stResult.info != null && cancelFlg != true ) { try { silhouetteFile = logMng.Ps_Sample_Apl_Java_OutputSilhouette( iniAcs.GetValueString(PsFileAccessorIni.LogFolderPath), usingSensorType, usingGuideMode, "V", stResult.info); } catch (PsAplException pae) { PsMessageDialog.Ps_Sample_Apl_Java_ShowErrorDialog(this, pae.getErrorMsgKey()); } } //Output log messages if (iniAcs.GetValueInteger(PsFileAccessorIni.LogMode) == 1 && stResult.result == PalmSecureConstant.JAVA_BioAPI_OK && cancelFlg != true) { ArrayList<String> idList = new ArrayList<String>(); idList.add(name.getText()); // Output log try { logMng.Ps_Sample_Apl_Java_WriteLog( iniAcs.GetValueString(PsFileAccessorIni.LogFolderPath), usingSensorType, usingGuideMode, "V", identifyResult, stResult.retryCnt, silhouetteFile, stResult.userId, stResult.farAchieved); } catch (PsAplException pae) { PsMessageDialog.Ps_Sample_Apl_Java_ShowErrorDialog(this, pae.getErrorMsgKey()); } } Ps_Sample_Apl_Java_InitState(); Ps_Sample_Apl_Java_SetWorkMessage(""); return; } public void Ps_Sample_Apl_Java_NotifyResult_Cancel(PsThreadResult pvsResult) { } public void actionPerformed(ActionEvent e) { Object obj = e.getSource(); if (obj.equals(btnEnroll)) { Ps_Sample_Apl_Java_ActionEnroll(); } else if (obj.equals(btnDelete)) { Ps_Sample_Apl_Java_ActionDelete(); } else if (obj.equals(btnVerify)) { Ps_Sample_Apl_Java_ActionVerify(); } else if (obj.equals(btnIdentify)) { Ps_Sample_Apl_Java_ActionIdentify(); } else if (obj.equals(btnCancel)) { Ps_Sample_Apl_Java_ActionCancel(); } else if (obj.equals(btnClose)) { Ps_Sample_Apl_Java_ActionExit(); } } public void windowActivated(WindowEvent e) { } public void windowClosed(WindowEvent e) { } public void windowClosing(WindowEvent e) { Ps_Sample_Apl_Java_ActionExit(); } public void windowDeactivated(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowOpened(WindowEvent e) { } }
import java.util.Scanner; public class Main22 { /** * 统计出兔子总数。 * * @param monthCount 第几个月 * @return 兔子总数 */ public static int getTotalCount(int monthCount,int num) { int aaa=0; for(int i=num+2;i<=monthCount-1;i++){ aaa++; aaa=aaa+getTotalCount(monthCount,i); } return aaa; } public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc =new Scanner(System.in); while (sc.hasNext()) { int month=sc.nextInt(); System.out.println(getTotalCount(month,0)+1); } } }
package com.monkey1024.controller; import com.monkey1024.myexception.MyException; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class ExceptionController { @RequestMapping("/myException.do") public ModelAndView myException(String name)throws Exception{ ModelAndView mv= new ModelAndView(); if ("jack".equals(name)){ throw new MyException("我的自定义异常"); } if(!"jack".equals(name)){ throw new Exception("异常"); } return mv; } }
/** * Interfata State */ package state3; /** * Interfata State * @author Ali */ public interface State { void pull(); }
package com.everis.person.controller; import com.everis.person.entity.Payment; import com.everis.person.entity.Wallet; import com.everis.person.service.WalletService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Mono; @Slf4j @RestController @RequestMapping("/person") public class PersonController { private final WalletService service; @Autowired public PersonController(WalletService service) { this.service = service; } @PostMapping("/createWallet") public Mono<Wallet> createPago(@RequestBody Wallet request){ return service.createWallet(request); } @GetMapping("/retrieveWalletByPerson/{dni}") public Mono<Wallet> getWalletByPerson(@PathVariable("dni") String dni){ return service.getWalletByPerson(dni).switchIfEmpty(Mono.error(new Exception())); } @GetMapping("/") public Mono<Payment> getPayment(){ return service.getPayment(); } }
package com.designpattern.dp10adapterpattern.demo; /** * 对待修改类进行修改的接口(适配器接口) */ public interface DC5V { int outputDC5V(); // 具体的对待修改类进行修改的方法 }
package com.example.android.sqlitedemo.Classes; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CalendarView; import android.widget.EditText; import android.widget.Toast; import com.example.android.sqlitedemo.R; import java.sql.Date; import java.text.SimpleDateFormat; /** * Created by Nishita Aggarwal on 25-11-2017. */ public class InsertFragment extends Fragment { EditText edittext_name,percentage; CalendarView cal_doj; DataBase database; String data_date; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v=inflater.inflate(R.layout.insert_fragment,container,false); FloatingActionButton fab = v.findViewById(R.id.fab); edittext_name=v.findViewById(R.id.edittext_name); percentage=v.findViewById(R.id.percentage); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Data d=new Data(); d.setName(edittext_name.getText().toString()); d.setPercentage(Float.parseFloat(percentage.getText().toString())); d.setDoj(data_date); database.addData(d); Snackbar.make(view, "Data added succesfully in database", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); return v; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); database=new DataBase(this.getContext()); cal_doj=getActivity().findViewById(R.id.calview_doj); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); data_date = sdf.format(new Date(cal_doj.getDate())); cal_doj.setOnDateChangeListener(new CalendarView.OnDateChangeListener() { @Override public void onSelectedDayChange(@NonNull CalendarView calendarView, int year, int month, int date) { if(month==12) month=1; else month=month+1; data_date=date + "/" + month + "/" + year; Toast.makeText(getContext(), date + "/" + month + "/" + year , Toast.LENGTH_SHORT).show(); } }); } }
package examples; public class UsingException { public static void main(String[] args) { try { method1(); }catch(Exception exception) { System.err.printf("%s%n%n", exception.getMessage()); exception.printStackTrace(); StackTraceElement[] traceElement = exception.getStackTrace(); System.out.printf("%n StackTrace from getStackTrace%n"); System.out.println("Class \t\t\tFile\t\t\tLine\tMethod\n"); for(StackTraceElement element : traceElement) { System.out.printf("%s\t", element.getClassName()); System.out.printf("%s\t", element.getFileName()); System.out.printf("%s\t", element.getLineNumber()); System.out.printf("%s%n", element.getMethodName()); } } } public static void method1() throws Exception { method2(); } public static void method2() throws Exception { method3(); } public static void method3() throws Exception { throw new Exception("Exception thrown in method3"); } }
package com.spreadtrum.android.eng; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.PreferenceActivity; import android.util.Log; import android.widget.Toast; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.nio.charset.Charset; public class autoattachatpoweron extends PreferenceActivity implements OnPreferenceChangeListener { private boolean hasPara; private CheckBoxPreference mCheckBoxPreference; private engfetch mEf; private EventHandler mHandler; private int onoroff = 0; private int sockid = 0; private String str; private class EventHandler extends Handler { public EventHandler(Looper looper) { super(looper); } public void handleMessage(Message msg) { switch (msg.what) { case 45: case 46: ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream(); DataOutputStream outputBufferStream = new DataOutputStream(outputBuffer); Log.e("autoattachatpoweron", "engopen sockid=" + autoattachatpoweron.this.sockid); if (autoattachatpoweron.this.hasPara) { autoattachatpoweron.this.str = msg.what + "," + 1 + "," + autoattachatpoweron.this.onoroff; } else { autoattachatpoweron.this.str = msg.what + "," + 0; } try { outputBufferStream.writeBytes(autoattachatpoweron.this.str); autoattachatpoweron.this.mEf.engwrite(autoattachatpoweron.this.sockid, outputBuffer.toByteArray(), outputBuffer.toByteArray().length); byte[] inputBytes = new byte[128]; String str1 = new String(inputBytes, 0, autoattachatpoweron.this.mEf.engread(autoattachatpoweron.this.sockid, inputBytes, 128), Charset.defaultCharset()); Log.e("autoattachatpoweron", "str1=" + str1); if (str1.equals("0")) { autoattachatpoweron.this.mCheckBoxPreference.setChecked(false); autoattachatpoweron.this.onoroff = 1; return; } else if (str1.equals("1")) { autoattachatpoweron.this.mCheckBoxPreference.setChecked(true); autoattachatpoweron.this.onoroff = 0; return; } else if (str1.equals("OK")) { Toast.makeText(autoattachatpoweron.this.getApplicationContext(), "Set Success.", 0).show(); if (1 == autoattachatpoweron.this.onoroff) { autoattachatpoweron.this.onoroff = 0; return; } else { autoattachatpoweron.this.onoroff = 1; return; } } else if (str1.equals("error")) { Toast.makeText(autoattachatpoweron.this.getApplicationContext(), "Set Failed.", 0).show(); return; } else { Toast.makeText(autoattachatpoweron.this.getApplicationContext(), "Unknown", 0).show(); return; } } catch (IOException e) { Log.e("autoattachatpoweron", "writebytes error"); return; } default: return; } } } protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.layout.autoattach); this.mCheckBoxPreference = (CheckBoxPreference) findPreference("autoattach_value"); this.mCheckBoxPreference.setOnPreferenceChangeListener(this); this.hasPara = false; initialpara(); } private void initialpara() { this.mEf = new engfetch(); this.sockid = this.mEf.engopen(); this.mHandler = new EventHandler(Looper.myLooper()); this.mHandler.removeMessages(0); this.mHandler.sendMessage(this.mHandler.obtainMessage(45, 0, 0, Integer.valueOf(0))); } public boolean onPreferenceChange(Preference preference, Object newValue) { if (!preference.getKey().equals("autoattach_value")) { return false; } this.mHandler.sendMessage(this.mHandler.obtainMessage(46, 0, 0, Integer.valueOf(0))); this.hasPara = true; return true; } }
package de.hofuniversity.ejbbean.bean.impl; import java.util.ArrayList; import java.util.List; import javax.ejb.Stateless; import de.hofuniversity.ejbbean.bean.GroupOrderListRemote; import de.hofuniversity.ejbbean.data.GroupListSummaryData; import de.hofuniversity.ejbbean.data.impl.DefaultGroupListSummaryData; import de.hofuniversity.queries.MatchQuery; import de.hofuniversity.queries.QueryCache; /** * * @author Markus Exner * */ @Stateless(name = GroupOrderListRemote.MAPPED_NAME, mappedName = GroupOrderListRemote.MAPPED_NAME) public class GroupOrderListBean implements GroupOrderListRemote { private QueryCache queryCache; public GroupOrderListBean() {} private QueryCache getQueryCache() { if (this.queryCache == null) { this.queryCache = QueryCache.getInstance(); } return this.queryCache; } @Override public List<GroupListSummaryData> getGroupListSummaryDataList() { MatchQuery matchQuery = this.getQueryCache().getMatchQuery(); List<GroupListSummaryData> glsdList = new ArrayList<GroupListSummaryData>(); for (Long orderId : matchQuery.getAllGroups()) { DefaultGroupListSummaryData glsd = new DefaultGroupListSummaryData(); glsd.setOrderId(orderId); glsd.setGroupName(orderId); glsdList.add(glsd); } return glsdList; } }
package com.stk123.controller; import com.fasterxml.jackson.annotation.JsonView; import com.stk123.model.RequestResult; import com.stk123.model.core.Rps; import com.stk123.model.core.Stock; import com.stk123.model.core.Cache; import com.stk123.model.json.View; import com.stk123.model.strategy.Strategy; import com.stk123.model.strategy.StrategyResult; import com.stk123.service.core.StockService; import lombok.extern.apachecommons.CommonsLog; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.*; @RestController @RequestMapping("/rps") @CommonsLog public class RpsController { @Autowired private StockService stockService; @RequestMapping(value = {"/{rpsCode}", "/{rpsCode}/{type}/{codes}"}) @ResponseBody @JsonView(View.All.class) public RequestResult rps(@PathVariable(value = "rpsCode")String rpsCode, @PathVariable(value = "type", required = false)String type, @PathVariable(value = "codes", required = false)String codes, @RequestParam(value = "args", required = false)String args){ List<Stock> stocks; if(StringUtils.isNotEmpty(type) && StringUtils.isNotEmpty(codes)){ if("stock".equals(type)) { String[] stks = StringUtils.split(codes, ","); stocks = stockService.buildStocks(stks); }else if("bk".equals(type)){ List<Stock> bks = stockService.buildStocks(codes); stocks = bks.get(0).getStocks(); }else{ stocks = Collections.EMPTY_LIST; } stocks = stockService.getStocksWithBks(stocks, Cache.getBks(), false); }else { stocks = Cache.getStocksWithBks(); } List<StrategyResult> strategyResults = stockService.calcRps(stocks, rpsCode, args == null? null : StringUtils.split(args, ",")); strategyResults = strategyResults.subList(0, Math.min(200, strategyResults.size())); Map result = stockService.getStrategyResultAsMap(strategyResults); return RequestResult.success(result); } @RequestMapping(value = {"/list"}) public RequestResult listRpsCodeOnStock(){ List<Strategy> rpss = Rps.getAllRpsStrategyOnStock(); List<Map<String,String>> result = new ArrayList<>(rpss.size()); for(Strategy rps : rpss){ Map<String,String> map = new HashMap<>(); map.put("code", rps.getCode()); map.put("name", rps.getName()); result.add(map); } return RequestResult.success(result); } }
public class Person { private String name; private int idNum; public Person () { this.name = "Bob"; this.idNum = 0; } public Person(String name, int idNum) { this.name = name; this.idNum = idNum; } @Override public String toString() { String str = ""; str = "Name = " + name + "\n"; str += "Id Num = " + idNum; return str; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setIdNum(int idNum) { this.idNum = idNum; } public int getIdNum() { return idNum; } } //
package net.sxt.tcp; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; /** * 必须要先创建服务器,再创建客户端,这一点是与UDP协议的区别! * @author 东东 * */ public class Server { public static void main(String[] args) throws IOException { //1.创建服务器,指定端口 ServerSocket server=new ServerSocket(8888); //2.接受客户端连接 阻塞式?-->就是指线程不运行状态,因为是监听此端口,没来请求时必然是阻塞挂起状态! Socket socket=server.accept(); System.out.println("一个客户端建立连接"); //3.发送数据+接受数据 String msg="欢迎使用!"; /* BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); bw.write(msg); bw.newLine();//这里必须要newLine bw.flush(); */ DataOutputStream dos=new DataOutputStream(socket.getOutputStream()); dos.writeUTF(msg); dos.flush(); } }
package br.com.zolp.estudozolp.bean.filtro; /** * Classe responsável pelas informacoes base de Filtro de Consulta. * * @author mamede * @version 0.0.1-SNAPSHOT */ public class FiltroConsulta { private Long id; private String descricao; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } }
package colecaoelementos; import java.util.Scanner; import java.lang.Math; /* * Guilherme Araujo Sette TIA: 41783441 * Luiz Henrique Monteiro de Carvalho TIA: 41719468 * */ public class colecaoElemento { private listaPonto lista1; private Ponto ponto1; public colecaoElemento(listaPonto lista1, Ponto ponto1) { this.lista1 = lista1; this.ponto1 = ponto1; } public static void main(String[] args) { Ponto p1; listaPonto l1; colecaoElemento colecao; int numeroposicoes; int x, y; int posicao; double raio; listaPonto vetor; int escolha; Scanner input = new Scanner(System.in); System.out.print("--------------------------------------------\n"); System.out.print("|"); System.out.print(" |\n"); System.out.print("| Coleção de elementos |\n"); System.out.print("|"); System.out.print(" |\n"); System.out.print("--------------------------------------------\n"); System.out.print("\n"); System.out.print("Bem-vindo\n"); System.out.print("Quantas posicoes vão ter na lista?: "); numeroposicoes = input.nextInt(); vetor = new listaPonto(numeroposicoes); while (true) { System.out.println("----------------------\n"); System.out.println("Menu - Calculadora\n"); System.out.print("1.) Adicionar um elemento no final da coleção.\n"); System.out.print("2.) Adicionar um elemento na posicao especifca da coleção.\n"); System.out.print("3.) Retornar o índice da primeira ocorrência de um elemento especificado na coleção\n"); System.out.print("4.) Remover um elemento em uma posição na coleção\n"); System.out.print("5.) Calcular a distância dos dois pontos mais distantes na coleção.\n"); System.out.print("6.) Retornar uma coleção de pontos contido em uma circunferência.\n"); System.out.print("0.) Sair\n"); System.out.print("\nDigite sua opção: "); System.out.println("----------------------\n"); escolha = input.nextInt(); switch (escolha) { case 1: System.out.println("Adicionar um elemento no final da coleção. "); System.out.println("Vamos criar o ponto\n"); System.out.println("Digite o x: "); x = input.nextInt(); System.out.println("Digite o y: "); y = input.nextInt(); p1 = new Ponto(x, y); vetor.adiciona_final(p1); vetor.mostra(); break; case 2: System.out.println("Adicionar um elemento na posicao especifica da coleção. "); System.out.println("Vamos criar o ponto\n"); System.out.println("Digite o x: "); x = input.nextInt(); System.out.println("Digite o y: "); y = input.nextInt(); p1 = new Ponto(x, y); System.out.println("Digite a posicao: "); posicao = input.nextInt(); vetor.adiciona_posicao_especifica(p1,posicao); vetor.mostra(); break; case 3: System.out.println("Retornar o indice da primeira ocorrência de um elemento especificado na coleção."); System.out.println("Vamos criar o ponto\n"); System.out.println("Digite o x: "); x = input.nextInt(); System.out.println("Digite o y: "); y = input.nextInt(); p1 = new Ponto(x, y); System.out.println("O elemento esta na posicao: "+vetor.busca_ponto(p1)+"\n"); break; case 4: System.out.println("Remover um elemento em uma posição na coleção"); System.out.println("Digite a posicao: "); posicao = input.nextInt(); vetor.remove_ponto(posicao); break; case 5: System.out.println("Calcular a distância dos dois pontos mais distantes na coleção."); System.out.println("Distancia: "+vetor.calcula_distancia()); break; case 6: System.out.println("Retornar uma coleção de pontos contido em uma circunferência."); System.out.println("Vamos criar o ponto\n"); System.out.println("Digite o x: "); x = input.nextInt(); System.out.println("Digite o y: "); y = input.nextInt(); p1 = new Ponto(x, y); System.out.println("Digite o raio da circunferencia: "); raio = input.nextDouble(); vetor.pontos_circunferencia(raio, p1).mostra(); break; case 0: System.out.println("Ate mais..."); System.exit(0); break; default: System.out.println("Opcao invalida! Tente novamente."); break; } } } }
package com.niall.nmdb; import androidx.recyclerview.widget.DiffUtil; import com.niall.nmdb.entities.Movie; import java.util.List; public class CardStackCallback extends DiffUtil.Callback { private List<Movie> oldMovies, newMovies; public CardStackCallback(List<Movie> oldMovies, List<Movie> newMovies){ this.oldMovies = oldMovies; this.newMovies = newMovies; } @Override public int getOldListSize() { return oldMovies.size(); } @Override public int getNewListSize() { return newMovies.size(); } @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { return oldMovies.get(oldItemPosition).getImage() == newMovies.get(newItemPosition).getImage(); } @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { return oldMovies.get(oldItemPosition) == newMovies.get(newItemPosition); } }
/** * */ package com.isg.iloan.controller.functions.dataEntry; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.util.GenericForwardComposer; import org.zkoss.zul.Checkbox; import org.zkoss.zul.Datebox; import org.zkoss.zul.Textbox; /** * @author augusto.marte * */ public class DoaSaveAndSwipeViewCtrl extends GenericForwardComposer { private Checkbox acceptDOA; private Textbox branchNameAndCode; private Datebox dateApplied_datebox; private Textbox pledgedAmountFigure_txtbox; private Textbox pledgedAmountWord_txtbox; private Textbox branch_txtbox; private Textbox pledgedAccountNo_txtbox; private Checkbox specialAccount; private Checkbox time; private Checkbox savings; private Textbox incDecCreditLimit_txtbox; private Checkbox incDecCreditLimit; private Checkbox changeDepInst; private Checkbox issuance; private Textbox pledgedAccountTypeCode; private Textbox pledgedAccountTypeDesc; /** * * */ @Override public void doAfterCompose(Component comp) throws Exception { super.doAfterCompose(comp); issuance.setChecked(false); changeDepInst.setChecked(false); incDecCreditLimit.setChecked(false); savings.setChecked(false); time.setChecked(false); specialAccount.setChecked(false); acceptDOA.setChecked(false); } public void onCheck$savings(){ pledgedAccountTypeCode.setValue(savings.getLabel()); pledgedAccountTypeDesc.setValue(savings.getLabel()); time.setChecked(!savings.isChecked()); //pledgedAccountNo_txtbox.setDisabled(true); } public void onCheck$time(){ pledgedAccountTypeCode.setValue(time.getLabel()); pledgedAccountTypeDesc.setValue(time.getLabel()); savings.setChecked(!time.isChecked()); //pledgedAccountNo_txtbox.setDisabled(true); } // public void onCheck$specialAccount_chkbox(){ // pledgedAccountNo_txtbox.setDisabled(!specialAccount_chkbox.isChecked()); // } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hdfcraft; import java.awt.Rectangle; import java.io.IOException; import java.io.ObjectInputStream; import java.util.SortedMap; import static hdfcraft.Constants.*; /** * * @author pepijn */ public class HeightMapTileFactory extends AbstractTileFactory { public HeightMapTileFactory(long seed, HeightMap heightMap, int maxHeight, boolean floodWithLava, Theme theme) { this.seed = seed; this.heightMap = heightMap; this.maxHeight = maxHeight; this.floodWithLava = floodWithLava; heightMap.setSeed(seed); theme.setSeed(seed); this.theme = theme; } @Override public final int getMaxHeight() { return maxHeight; } @Override public long getSeed() { return seed; } @Override public void setSeed(long seed) { this.seed = seed; heightMap.setSeed(seed); theme.setSeed(seed); } public final void setMaxHeight(int maxHeight) { setMaxHeight(maxHeight, HeightTransform.IDENTITY); } @Override public final void setMaxHeight(int maxHeight, HeightTransform transform) { if (maxHeight != this.maxHeight) { this.maxHeight = maxHeight; theme.setMaxHeight(maxHeight, transform); } } public final int getWaterHeight() { return theme.getWaterHeight(); } public final void setWaterHeight(int waterHeight) { theme.setWaterHeight(waterHeight); } public final boolean isFloodWithLava() { return floodWithLava; } public final HeightMap getHeightMap() { return heightMap; } public final float getBaseHeight() { return heightMap.getBaseHeight(); } public final void setHeightMap(HeightMap heightMap) { if (heightMap == null) { throw new NullPointerException(); } this.heightMap = heightMap; } public Theme getTheme() { return theme; } public void setTheme(Theme theme) { this.theme = theme; theme.setMaxHeight(maxHeight, HeightTransform.IDENTITY); } /** * Always returns <code>true</code> since height map tile factories are * endless. */ @Override public boolean isTilePresent(int x, int y) { return true; } @Override public final Tile createTile(int tileX, int tileY) { final int maxY = getMaxHeight() - 1, myWaterHeight = getWaterHeight(); final Tile tile = new Tile(tileX, tileY, maxHeight); tile.setEventsInhibited(true); final int worldTileX = tileX * TILE_SIZE, worldTileY = tileY * TILE_SIZE; try { for (int x = 0; x < TILE_SIZE; x++) { for (int y = 0; y < TILE_SIZE; y++) { final int blockX = worldTileX + x, blockY = worldTileY + y; final float height = clamp(heightMap.getHeight(blockX, blockY), maxY); tile.setHeight(x, y, height); tile.setWaterLevel(x, y, myWaterHeight); if (floodWithLava) { tile.setBitLayerValue(FloodWithLava.INSTANCE, x, y, true); } theme.apply(tile, x, y); } } return tile; } finally { tile.setEventsInhibited(false); } } @Override public Rectangle getExtent() { return null; // Height map tile factories are endless } @Override public final void applyTheme(Tile tile, int x, int y) { theme.apply(tile, x, y); } protected final float clamp(float value, int max) { return (value < 0) ? 0 : ((value > max) ? max : value); } protected final void setRandomise(boolean randomise) { this.randomise = randomise; } protected final void setBeaches(boolean beaches) { this.beaches = beaches; } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); // Legacy map support if (maxHeight == 0) { maxHeight = 128; } if (version < 1) { theme = (terrainRanges != null) ? new SimpleTheme(seed, waterHeight, terrainRanges, null, maxHeight, randomise, beaches) : new SimpleTheme(seed, waterHeight, terrainRangesTable, maxHeight, randomise, beaches); waterHeight = -1; terrainRanges = null; terrainRangesTable = null; randomise = false; beaches = false; } version = CURRENT_VERSION; } @Deprecated int waterHeight = -1; @Deprecated private Terrain[] terrainRangesTable; private final boolean floodWithLava; private int maxHeight; @Deprecated private SortedMap<Integer, Terrain> terrainRanges; @Deprecated private boolean randomise, beaches; private long seed; private HeightMap heightMap; private Theme theme; private int version = CURRENT_VERSION; private static final long serialVersionUID = 2011032801L; private static final int CURRENT_VERSION = 1; }
package hwl3; import static hwl3.CommonFunctions.getRand; import static hwl3.CommonFunctions.printArray; public class MarksArray { public static void execute() { int maxMark = 0; int arSize = 0; while (arSize <= 0) { System.out.println("Введите расмер массива отметок"); arSize = MainClassl3.gSc.nextInt(); } int[] ar = new int[arSize]; for (int i = 0; i < ar.length; i++) { ar[i] = getRand(10) + 1; } printArray(ar); maxMark = ar[0]; for (int i = 0; i < ar.length; i++) { if (ar[i] > maxMark) { maxMark = ar[i]; } } System.out.println("Максимальная отметка: " + maxMark); System.out.println("Список максимальных отметок: "); for (int i = 0; i < ar.length; i++) { if (ar[i] == maxMark) { System.out.println("Отметка " + maxMark + " позиция :" + (i + 1)); } } System.out.println("Первая отметка " + ar[0]); System.out.println("Последняя отметка" + ar[ar.length - 1]); } }
package com.lantar.testtask.data.network; import com.lantar.testtask.data.network.model.Data; /** * Created by LantarPc on 1/18/2018. */ public interface OnResponse { void onResponse(Data data); }
package comp303.fivehundred.gui; import java.util.Enumeration; import javax.swing.AbstractButton; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JCheckBox; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; /** * @author Ioannis Fytilis 260482744 * Displays a dialog which asks the user for input, to customize players. * Inspired partially by : http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html */ @SuppressWarnings("serial") public class InputDialog extends JPanel { /** * All possible IPlayer types. */ public enum PlayerType {Random, Basic, Advanced}; private static final int TEXT_BOX_SIZE = 10; private String[] aNames; private PlayerType[] aDifficulty; private JTextField[] aTxtFields; private JPanel[] aPanels; private JPanel aOptionPanel; private ButtonGroup[] aAIButtons; private JCheckBox aHumanPlayBox; private JRadioButton[][] aGroupButtons; /** * Constructs the dialog. */ public InputDialog() { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); aAIButtons = new ButtonGroup[4]; aPanels = new JPanel[4]; aTxtFields = new JTextField[4]; aNames = new String[4]; aDifficulty = new PlayerType[4]; aGroupButtons = new JRadioButton[4][3]; for (int i = 0; i<4; i++) { aAIButtons[i] = new ButtonGroup(); aPanels[i] = new JPanel(); aTxtFields[i] = new JTextField(TEXT_BOX_SIZE); aPanels[i].add(aTxtFields[i]); add(aPanels[i]); aNames[i] = "Player " + (i+1); aTxtFields[i].setText(aNames[i]); aDifficulty[i] = PlayerType.Advanced; aGroupButtons[i][0] = new JRadioButton("Random"); aGroupButtons[i][1] = new JRadioButton("Basic"); aGroupButtons[i][2] = new JRadioButton("Advanced", true); aAIButtons[i].add(aGroupButtons[i][0]); aAIButtons[i].add(aGroupButtons[i][1]); aAIButtons[i].add(aGroupButtons[i][2]); aPanels[i].add(aGroupButtons[i][0]); aPanels[i].add(aGroupButtons[i][1]); aPanels[i].add(aGroupButtons[i][2]); } aOptionPanel = new JPanel(); add(aOptionPanel); aHumanPlayBox = new JCheckBox("<html>Enable Human Mode (Player 1 will be played by you!)<br>" + "In which case, the AI-level specified for <br> Player 1 will be the level of your Autoplay</html>"); aOptionPanel.add(aHumanPlayBox); } /** * Shows the dialog which asks for input. */ public void generatePlayers() { int closedHow; do { closedHow = JOptionPane.showConfirmDialog(null, this, "Player Setup", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE); } while (closedHow == JOptionPane.CLOSED_OPTION); for (int i = 0; i < 4; i++) { aNames[i] = aTxtFields[i].getText(); aDifficulty[i] = getActiveButtonType(aAIButtons[i]); } } /** * @return the names of the players */ public String[] getNames() { return aNames; } /** * @return the types of the players */ public PlayerType[] getPlayerTypes() { return aDifficulty; } /** * @return whether a human is playing */ public boolean isHumanMode() { return aHumanPlayBox.isSelected(); } private PlayerType getActiveButtonType(ButtonGroup pButtonGrp) { Enumeration<AbstractButton> elements = pButtonGrp.getElements(); while (elements.hasMoreElements()) { AbstractButton button = elements.nextElement(); if (button.isSelected()) { String type = button.getText(); for (PlayerType each : PlayerType.values()) { if (each.toString().equals(type)) { return each; } } } } throw new GUIException("No Selected Button from InputDialog"); } }
package Integracion; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import Negocio.Alumno; import Negocio.Asignaturas; import Negocio.Clase; import Negocio.Horario; import Negocio.Pagos; import Negocio.Profesor; public class DAOclase extends Conexion implements InterfaceDao { @Override public List<Clase> listar() { List<Clase> lista_clases = null; try { this.conectar(); PreparedStatement st = this.con.prepareStatement("SELECT * FROM Clase"); lista_clases = new ArrayList<Clase>(); ResultSet rs = st.executeQuery(); while(rs.next() ) { Clase as = new Clase(); as.setId_Clase(rs.getString("idClase")); as.setId_Alumno(rs.getString("idAlumno")); as.setId_Asignatura(rs.getString("idAsignatura")); as.setId_Profesor(rs.getString("idProfesor")); as.setId_Pago(rs.getString("Pago_idPago")); as.setId_horario(rs.getString("Horario")); if (!lista_clases.contains(as)) { lista_clases.add(as); } } rs.close(); this.cerrar(); } catch (Exception e) { e.getMessage(); } return lista_clases; } @Override public void eliminar(String id) { try { this.conectar(); PreparedStatement st = this.con.prepareStatement("DELETE FROM Clase WHERE idClase = ?"); st.setString(1, id); st.executeUpdate(); } catch (Exception e) { e.getMessage(); } } @Override public void aniadir(Alumno al) { // TODO Auto-generated method stub } @Override public void aniadir(Profesor pr) { // TODO Auto-generated method stub } @Override public void aniadir(Asignaturas as) { // TODO Auto-generated method stub } @Override public void modificar(String id, String a_modificar, String valor) { try { this.conectar(); PreparedStatement st = this.con.prepareStatement("UPDATE Clase SET ? = ? WHERE ? = ?"); st.setString(1, a_modificar); st.setString(2, valor); st.setString(3, "idClase"); st.setString(4, id); st.executeUpdate(); } catch (Exception e) { e.getMessage(); } } @Override public void aniadir(Clase cl) { try { this.conectar(); PreparedStatement st = this.con.prepareStatement("INSERT INTO Clase (idClase, idProfesor, idAlumno, idAsignatura, Horario, Pago_idPago) VALUES ( ?, ?, ?, ?, ?, ?)"); st.setString(1, cl.getId_Clase()); st.setString(2, cl.getId_Profesor()); st.setString(3, cl.getId_Alumno()); st.setString(4, cl.getId_Asignatura()); st.setString(5, cl.getId_horario()); st.setString(6, cl.getId_Pago()); st.executeUpdate(); } catch (Exception e) { System.out.println(e.getMessage()); } } @Override public void aniadir(Horario hr) { // TODO Auto-generated method stub } @Override public void aniadir(Pagos pg) { // TODO Auto-generated method stub } }
package com.zjf.myself.codebase.activity.ExerciseLibrary; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.zjf.myself.codebase.R; import com.zjf.myself.codebase.activity.BaseAct; import com.zjf.myself.codebase.model.BuilderUserTestInfo; /** * <pre> * author : ZouJianFeng * e-mail : 1434690833@qq.com * time : 2018/01/13 * desc : * version: 1.0 * </pre> */ public class BuilderTestAct extends BaseAct{ private Button btnAdd; private TextView txtResult; private BuilderUserTestInfo builderUserTestInfo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.act_builder_test); initView(); initData(); } private void initView() { txtResult = (TextView)findViewById(R.id.txtResult); btnAdd = (Button)findViewById(R.id.btnAdd); btnAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { builderUserTestInfo = new BuilderUserTestInfo.UserBuilder("Z","jf") .age(130) .phone("18888888888") .address("china sz") .build(); showResult(); } }); } private void showResult() { txtResult.setText(builderUserTestInfo.toString()); } private void initData() { } }
package com.thonline.DO; public class HJRegistrationDO { private String accNO; private String jenisAkaun; private String stsAkaun; private String stsHaji; private String tkhLahir; private String umur; private String dasarUmurMin; private String dasarUmurMax; private String dasarAmaunBeku; private String dasarHadKelompok; private String bakiSemasa; private String availableBalance; private boolean stsTunaiHaji; private boolean stsTunaiHajiThnSemasa; private String poskod; private String name; private String alamat1; private String alamat2; private String alamat3; private String jantina; private String negeri; private String telRumah; private String telPejabat; private String telBimbit; private String noKP; private String noID; private String pusatKos; private String noDaftar; private String kodTransaksi; private String txnID; private String noRujukan; private String thnPeruntukan; private String hjRegisterSequence; private String thnHijrah; // response private String uuid; private String THResponseCode; private String THRefNoHR; private String THRefNo; private String THRegDate; private String THRegTime; private String THHajjYear; private String THHajjYear1; private String THOffice; private String THAcct01; private String THRegNo01; private String THRefNo01; private String THRegDate01; private String THHajjYear01; private String THHajjYear101; private String THOffice01; private String THResponseCode01; private String THAcct02; private String THRegNo02; private String THRefNo02; private String THRegDate02; private String THHajjYear02; private String THHajjYear102; private String THOffice02; private String THResponseCode02; private String THAcct03; private String THRegNo03; private String THRefNo03; private String THRegDate03; private String THHajjYear03; private String THHajjYear103; private String THOffice03; private String THResponseCode03; private String THAcct04; private String THRegNo04; private String THRefNo04; private String THRegDate04; private String THHajjYear04; private String THHajjYear104; private String THOffice04; private String THResponseCode04; private String THAcct05; private String THRegNo05; private String THRefNo05; private String THRegDate05; private String THHajjYear05; private String THHajjYear105; private String THOffice05; private String THResponseCode05; private String THAcct06; private String THRegNo06; private String THRefNo06; private String THRegDate06; private String THHajjYear06; private String THHajjYear106; private String THOffice06; private String THResponseCode06; public String getAccNO() { return accNO; } public void setAccNO(String accNO) { this.accNO = accNO; } public String getJenisAkaun() { return jenisAkaun; } public void setJenisAkaun(String jenisAkaun) { this.jenisAkaun = jenisAkaun; } public String getStsAkaun() { return stsAkaun; } public void setStsAkaun(String stsAkaun) { this.stsAkaun = stsAkaun; } public String getStsHaji() { return stsHaji; } public void setStsHaji(String stsHaji) { this.stsHaji = stsHaji; } public String getTkhLahir() { return tkhLahir; } public void setTkhLahir(String tkhLahir) { this.tkhLahir = tkhLahir; } public String getUmur() { return umur; } public void setUmur(String umur) { this.umur = umur; } public String getDasarUmurMin() { return dasarUmurMin; } public void setDasarUmurMin(String dasarUmurMin) { this.dasarUmurMin = dasarUmurMin; } public String getDasarUmurMax() { return dasarUmurMax; } public void setDasarUmurMax(String dasarUmurMax) { this.dasarUmurMax = dasarUmurMax; } public String getDasarAmaunBeku() { return dasarAmaunBeku; } public void setDasarAmaunBeku(String dasarAmaunBeku) { this.dasarAmaunBeku = dasarAmaunBeku; } public String getDasarHadKelompok() { return dasarHadKelompok; } public void setDasarHadKelompok(String dasarHadKelompok) { this.dasarHadKelompok = dasarHadKelompok; } public String getBakiSemasa() { return bakiSemasa; } public void setBakiSemasa(String bakiSemasa) { this.bakiSemasa = bakiSemasa; } public String getAvailableBalance() { return availableBalance; } public void setAvailableBalance(String availableBalance) { this.availableBalance = availableBalance; } public boolean isStsTunaiHaji() { return stsTunaiHaji; } public void setStsTunaiHaji(boolean stsTunaiHaji) { this.stsTunaiHaji = stsTunaiHaji; } public boolean isStsTunaiHajiThnSemasa() { return stsTunaiHajiThnSemasa; } public void setStsTunaiHajiThnSemasa(boolean stsTunaiHajiThnSemasa) { this.stsTunaiHajiThnSemasa = stsTunaiHajiThnSemasa; } public String getPoskod() { return poskod; } public void setPoskod(String poskod) { this.poskod = poskod; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAlamat1() { return alamat1; } public void setAlamat1(String alamat1) { this.alamat1 = alamat1; } public String getAlamat2() { return alamat2; } public void setAlamat2(String alamat2) { this.alamat2 = alamat2; } public String getAlamat3() { return alamat3; } public void setAlamat3(String alamat3) { this.alamat3 = alamat3; } public String getJantina() { return jantina; } public void setJantina(String jantina) { this.jantina = jantina; } public String getNegeri() { return negeri; } public void setNegeri(String negeri) { this.negeri = negeri; } public String getTelRumah() { return telRumah; } public void setTelRumah(String telRumah) { this.telRumah = telRumah; } public String getTelPejabat() { return telPejabat; } public void setTelPejabat(String telPejabat) { this.telPejabat = telPejabat; } public String getTelBimbit() { return telBimbit; } public void setTelBimbit(String telBimbit) { this.telBimbit = telBimbit; } public String getNoKP() { return noKP; } public void setNoKP(String noKP) { this.noKP = noKP; } public String getNoID() { return noID; } public void setNoID(String noID) { this.noID = noID; } public String getPusatKos() { return pusatKos; } public void setPusatKos(String pusatKos) { this.pusatKos = pusatKos; } public String getNoDaftar() { return noDaftar; } public void setNoDaftar(String noDaftar) { this.noDaftar = noDaftar; } public String getKodTransaksi() { return kodTransaksi; } public void setKodTransaksi(String kodTransaksi) { this.kodTransaksi = kodTransaksi; } public String getTxnID() { return txnID; } public void setTxnID(String txnID) { this.txnID = txnID; } public String getNoRujukan() { return noRujukan; } public void setNoRujukan(String noRujukan) { this.noRujukan = noRujukan; } public String getThnPeruntukan() { return thnPeruntukan; } public void setThnPeruntukan(String thnPeruntukan) { this.thnPeruntukan = thnPeruntukan; } public String getHjRegisterSequence() { return hjRegisterSequence; } public void setHjRegisterSequence(String hjRegisterSequence) { this.hjRegisterSequence = hjRegisterSequence; } public String getThnHijrah() { return thnHijrah; } public void setThnHijrah(String thnHijrah) { this.thnHijrah = thnHijrah; } public String getTHRefNoHR() { return THRefNoHR; } public void setTHRefNoHR(String tHRefNoHR) { THRefNoHR = tHRefNoHR; } public String getTHAcct01() { return THAcct01; } public void setTHAcct01(String tHAcct01) { THAcct01 = tHAcct01; } public String getTHRegNo01() { return THRegNo01; } public void setTHRegNo01(String tHRegNo01) { THRegNo01 = tHRegNo01; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public String getTHResponseCode01() { return THResponseCode01; } public void setTHResponseCode01(String tHResponseCode01) { THResponseCode01 = tHResponseCode01; } public String getTHAcct02() { return THAcct02; } public void setTHAcct02(String tHAcct02) { THAcct02 = tHAcct02; } public String getTHRegNo02() { return THRegNo02; } public void setTHRegNo02(String tHRegNo02) { THRegNo02 = tHRegNo02; } public String getTHResponseCode02() { return THResponseCode02; } public void setTHResponseCode02(String tHResponseCode02) { THResponseCode02 = tHResponseCode02; } public String getTHAcct03() { return THAcct03; } public void setTHAcct03(String tHAcct03) { THAcct03 = tHAcct03; } public String getTHRegNo03() { return THRegNo03; } public void setTHRegNo03(String tHRegNo03) { THRegNo03 = tHRegNo03; } public String getTHResponseCode03() { return THResponseCode03; } public void setTHResponseCode03(String tHResponseCode03) { THResponseCode03 = tHResponseCode03; } public String getTHAcct04() { return THAcct04; } public void setTHAcct04(String tHAcct04) { THAcct04 = tHAcct04; } public String getTHRegNo04() { return THRegNo04; } public void setTHRegNo04(String tHRegNo04) { THRegNo04 = tHRegNo04; } public String getTHResponseCode04() { return THResponseCode04; } public void setTHResponseCode04(String tHResponseCode04) { THResponseCode04 = tHResponseCode04; } public String getTHAcct05() { return THAcct05; } public void setTHAcct05(String tHAcct05) { THAcct05 = tHAcct05; } public String getTHRegNo05() { return THRegNo05; } public void setTHRegNo05(String tHRegNo05) { THRegNo05 = tHRegNo05; } public String getTHResponseCode05() { return THResponseCode05; } public void setTHResponseCode05(String tHResponseCode05) { THResponseCode05 = tHResponseCode05; } public String getTHAcct06() { return THAcct06; } public void setTHAcct06(String tHAcct06) { THAcct06 = tHAcct06; } public String getTHRegNo06() { return THRegNo06; } public void setTHRegNo06(String tHRegNo06) { THRegNo06 = tHRegNo06; } public String getTHResponseCode06() { return THResponseCode06; } public void setTHResponseCode06(String tHResponseCode06) { THResponseCode06 = tHResponseCode06; } public String getTHResponseCode() { return THResponseCode; } public void setTHResponseCode(String tHResponseCode) { THResponseCode = tHResponseCode; } public String getTHRefNo01() { return THRefNo01; } public void setTHRefNo01(String tHRefNo01) { THRefNo01 = tHRefNo01; } public String getTHRegDate01() { return THRegDate01; } public void setTHRegDate01(String tHRegDate01) { THRegDate01 = tHRegDate01; } public String getTHHajjYear01() { return THHajjYear01; } public void setTHHajjYear01(String tHHajjYear01) { THHajjYear01 = tHHajjYear01; } public String getTHRefNo() { return THRefNo; } public void setTHRefNo(String tHRefNo) { THRefNo = tHRefNo; } public String getTHRegDate() { return THRegDate; } public void setTHRegDate(String tHRegDate) { THRegDate = tHRegDate; } public String getTHHajjYear() { return THHajjYear; } public void setTHHajjYear(String tHHajjYear) { THHajjYear = tHHajjYear; } public String getTHHajjYear1() { return THHajjYear1; } public void setTHHajjYear1(String tHHajjYear1) { THHajjYear1 = tHHajjYear1; } public String getTHOffice() { return THOffice; } public void setTHOffice(String tHOffice) { THOffice = tHOffice; } public String getTHHajjYear101() { return THHajjYear101; } public void setTHHajjYear101(String tHHajjYear101) { THHajjYear101 = tHHajjYear101; } public String getTHOffice01() { return THOffice01; } public void setTHOffice01(String tHOffice01) { THOffice01 = tHOffice01; } public String getTHRefNo02() { return THRefNo02; } public void setTHRefNo02(String tHRefNo02) { THRefNo02 = tHRefNo02; } public String getTHRegDate02() { return THRegDate02; } public void setTHRegDate02(String tHRegDate02) { THRegDate02 = tHRegDate02; } public String getTHHajjYear02() { return THHajjYear02; } public void setTHHajjYear02(String tHHajjYear02) { THHajjYear02 = tHHajjYear02; } public String getTHHajjYear102() { return THHajjYear102; } public void setTHHajjYear102(String tHHajjYear102) { THHajjYear102 = tHHajjYear102; } public String getTHOffice02() { return THOffice02; } public void setTHOffice02(String tHOffice02) { THOffice02 = tHOffice02; } public String getTHRefNo03() { return THRefNo03; } public void setTHRefNo03(String tHRefNo03) { THRefNo03 = tHRefNo03; } public String getTHRegDate03() { return THRegDate03; } public void setTHRegDate03(String tHRegDate03) { THRegDate03 = tHRegDate03; } public String getTHHajjYear03() { return THHajjYear03; } public void setTHHajjYear03(String tHHajjYear03) { THHajjYear03 = tHHajjYear03; } public String getTHHajjYear103() { return THHajjYear103; } public void setTHHajjYear103(String tHHajjYear103) { THHajjYear103 = tHHajjYear103; } public String getTHOffice03() { return THOffice03; } public void setTHOffice03(String tHOffice03) { THOffice03 = tHOffice03; } public String getTHRefNo04() { return THRefNo04; } public void setTHRefNo04(String tHRefNo04) { THRefNo04 = tHRefNo04; } public String getTHRegDate04() { return THRegDate04; } public void setTHRegDate04(String tHRegDate04) { THRegDate04 = tHRegDate04; } public String getTHHajjYear04() { return THHajjYear04; } public void setTHHajjYear04(String tHHajjYear04) { THHajjYear04 = tHHajjYear04; } public String getTHHajjYear104() { return THHajjYear104; } public void setTHHajjYear104(String tHHajjYear104) { THHajjYear104 = tHHajjYear104; } public String getTHOffice04() { return THOffice04; } public void setTHOffice04(String tHOffice04) { THOffice04 = tHOffice04; } public String getTHRefNo05() { return THRefNo05; } public void setTHRefNo05(String tHRefNo05) { THRefNo05 = tHRefNo05; } public String getTHRegDate05() { return THRegDate05; } public void setTHRegDate05(String tHRegDate05) { THRegDate05 = tHRegDate05; } public String getTHHajjYear05() { return THHajjYear05; } public void setTHHajjYear05(String tHHajjYear05) { THHajjYear05 = tHHajjYear05; } public String getTHHajjYear105() { return THHajjYear105; } public void setTHHajjYear105(String tHHajjYear105) { THHajjYear105 = tHHajjYear105; } public String getTHOffice05() { return THOffice05; } public void setTHOffice05(String tHOffice05) { THOffice05 = tHOffice05; } public String getTHRefNo06() { return THRefNo06; } public void setTHRefNo06(String tHRefNo06) { THRefNo06 = tHRefNo06; } public String getTHRegDate06() { return THRegDate06; } public void setTHRegDate06(String tHRegDate06) { THRegDate06 = tHRegDate06; } public String getTHHajjYear06() { return THHajjYear06; } public void setTHHajjYear06(String tHHajjYear06) { THHajjYear06 = tHHajjYear06; } public String getTHHajjYear106() { return THHajjYear106; } public void setTHHajjYear106(String tHHajjYear106) { THHajjYear106 = tHHajjYear106; } public String getTHOffice06() { return THOffice06; } public void setTHOffice06(String tHOffice06) { THOffice06 = tHOffice06; } public String getTHRegTime() { return THRegTime; } public void setTHRegTime(String tHRegTime) { THRegTime = tHRegTime; } }
package com.example.weather_forecast.DataItem; import android.app.Application; import androidx.fragment.app.FragmentActivity; public class Data extends Application { private String location=""; private String nlocation=""; private String Temperature_unit=""; private boolean Notification = false; public boolean isNotification() { return Notification; } public void setNotification(boolean notification) { Notification = notification; } public String getTemperature_unit() { return Temperature_unit; } public void setTemperature_unit(String temperature_unit) { Temperature_unit = temperature_unit; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getNlocation() { return nlocation; } public void setNlocation(String nlocation) { this.nlocation = nlocation; } }
package Lessons.lesson20; public class Main { public static void main(String[] args) { Music mc = Music.POP; System.out.println(mc); System.out.println(mc.name() + " " + mc.ordinal()); System.out.println("==================="); Music mc2 = Music.valueOf(Music.class,"ROCK"); System.out.println(mc2); System.out.println("==================="); for (Music element : Music.values() ) { System.out.println(element); } System.out.println("==================="); } }
package ru.yandex.qatools.htmlelements; import org.openqa.selenium.WebElement; /** * User: eroshenkoam * Date: 9/3/13, 6:34 PM */ public class Clickable extends Block { public Clickable(WebElement root) { super(root); } @SuppressWarnings("unused") public <T extends Block> T click() { getRoot().click(); return (T) this; } }
package com.atlassian.bitbucket.jenkins.internal.config; import com.atlassian.bitbucket.jenkins.internal.client.BitbucketClientFactoryProvider; import com.atlassian.bitbucket.jenkins.internal.client.BitbucketProjectSearchClient; import com.atlassian.bitbucket.jenkins.internal.client.BitbucketRepositorySearchClient; import com.atlassian.bitbucket.jenkins.internal.client.exception.BitbucketClientException; import com.atlassian.bitbucket.jenkins.internal.model.BitbucketPage; import com.atlassian.bitbucket.jenkins.internal.model.BitbucketProject; import com.atlassian.bitbucket.jenkins.internal.model.BitbucketRepository; import com.atlassian.bitbucket.jenkins.internal.utils.CredentialUtils; import com.cloudbees.plugins.credentials.Credentials; import hudson.Extension; import hudson.model.RootAction; import hudson.util.HttpResponses; import net.sf.json.JSONObject; import org.apache.commons.lang3.StringUtils; import org.kohsuke.stapler.HttpResponse; import org.kohsuke.stapler.HttpResponses.HttpResponseException; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.verb.GET; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import javax.inject.Inject; import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR; import static org.kohsuke.stapler.HttpResponses.error; @Extension public class BitbucketSearchEndpoint implements RootAction { public static final String BITBUCKET_SERVER_SEARCH_URL = "bitbucket-server-search"; private static final Logger LOGGER = LoggerFactory.getLogger(BitbucketSearchEndpoint.class); private BitbucketClientFactoryProvider bitbucketClientFactoryProvider; private BitbucketPluginConfiguration bitbucketPluginConfiguration; @GET public HttpResponse doFindProjects( @Nullable @QueryParameter("serverId") String serverId, @Nullable @QueryParameter("credentialsId") String credentialsId, @Nullable @QueryParameter("name") String name) { BitbucketProjectSearchClient projectSearchClient = bitbucketClientFactoryProvider .getClient(getServer(serverId), getCredentials(credentialsId)) .getProjectSearchClient(); try { BitbucketPage<BitbucketProject> projects = projectSearchClient.get(StringUtils.stripToEmpty(name)); return HttpResponses.okJSON(JSONObject.fromObject(projects)); } catch (BitbucketClientException e) { // Something wen wrong with the request to Bitbucket LOGGER.error(e.getMessage()); throw error(HTTP_INTERNAL_ERROR, e); } } @GET public HttpResponse doFindRepositories( @Nullable @QueryParameter("serverId") String serverId, @Nullable @QueryParameter("credentialsId") String credentialsId, @Nullable @QueryParameter("projectKey") String projectKey, @Nullable @QueryParameter("filter") String filter) { if (StringUtils.isBlank(projectKey)) { throw error(HTTP_BAD_REQUEST, "The projectKey must be present"); } BitbucketRepositorySearchClient searchClient = bitbucketClientFactoryProvider .getClient(getServer(serverId), getCredentials(credentialsId)) .getRepositorySearchClient(projectKey); try { BitbucketPage<BitbucketRepository> repositories = searchClient.get(StringUtils.stripToEmpty(filter)); return HttpResponses.okJSON(JSONObject.fromObject(repositories)); } catch (BitbucketClientException e) { // Something wen wrong with the request to Bitbucket LOGGER.error(e.getMessage()); throw error(HTTP_INTERNAL_ERROR, e); } } @CheckForNull @Override public String getDisplayName() { return getClass().getName(); } @CheckForNull @Override public String getIconFileName() { return null; } @CheckForNull @Override public String getUrlName() { return BITBUCKET_SERVER_SEARCH_URL; } @Inject public void setBitbucketClientFactoryProvider( BitbucketClientFactoryProvider bitbucketClientFactoryProvider) { this.bitbucketClientFactoryProvider = bitbucketClientFactoryProvider; } @Inject public void setBitbucketPluginConfiguration( BitbucketPluginConfiguration bitbucketPluginConfiguration) { this.bitbucketPluginConfiguration = bitbucketPluginConfiguration; } @Nullable private static Credentials getCredentials( @QueryParameter("credentialsId") @Nullable String credentialsId) throws HttpResponseException { Credentials credentials = null; if (!StringUtils.isBlank(credentialsId)) { credentials = CredentialUtils.getCredentials(credentialsId); if (credentials == null) { throw error( HTTP_BAD_REQUEST, "No corresponding credentials for the provided credentialsId"); } } return credentials; } private BitbucketServerConfiguration getServer( @QueryParameter("serverId") @Nullable String serverId) { if (StringUtils.isBlank(serverId)) { throw error( HTTP_BAD_REQUEST, "A Bitbucket Server serverId must be provided as a query parameter"); } return bitbucketPluginConfiguration .getServerById(serverId) .orElseThrow( () -> error( HTTP_BAD_REQUEST, "The provided Bitbucket Server serverId does not exist")); } }
package com.ilecreurer.drools.samples.sample2.service; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import com.ilecreurer.drools.samples.sample2.event.PositionEvent; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; @SpringBootTest public class CollisionServiceTest3 { /** * SimpleDateFormat object. */ private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ"); /** * CollisionService object. */ @Autowired private CollisionService collisionService; /** * Check that inserting a non-empty list is allowed. */ @Test void insertMutiplePositionEvents( ) { try { InputStream is = this.getClass().getClassLoader() .getResourceAsStream("data2.csv"); BufferedReader br = new BufferedReader(new InputStreamReader(is)); List<PositionEvent> positionEvents = new ArrayList<PositionEvent>(); String line; while((line = br.readLine()) != null) { String [] ar = line.split(","); String timestampAsString = ar[0]; String idEvent = ar[1]; String idOwner = ar[2]; String name = ar[3]; String latitudeAsString = ar[4]; String longitudeAsString = ar[5]; PositionEvent pe = new PositionEvent( idEvent, idOwner, name, sdf.parse(timestampAsString), Double.parseDouble(latitudeAsString), Double.parseDouble(longitudeAsString) ); positionEvents.add(pe); } assertDoesNotThrow(() -> { collisionService.insertPositionEvents(positionEvents); }); } catch (Exception e) { assertThat(true).isFalse(); } } }
package sources; public class PCMBuffer { String bufferedValue; public String getBufferedValue() { return bufferedValue; } public void setBufferedValue(String value) { this.bufferedValue = value; } }
package com.example.netflix_project.src.main.ViewPager.SignUp; import android.content.Intent; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.widget.Toolbar; import com.example.netflix_project.R; import com.example.netflix_project.src.BaseActivity; import com.example.netflix_project.src.main.ViewPager.User.Login; import com.example.netflix_project.src.main.ViewPager.User.LoginService; import com.example.netflix_project.src.main.ViewPager.User.interfaces.LoginActivityView; import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputLayout; public class SignUp extends BaseActivity implements LoginActivityView { Toolbar mToolbar; TextInputEditText mEmail, mPassword; Button mSingUpButton; TextInputLayout mEmailTextInput, mPassTextInput; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_up); mEmail=findViewById(R.id.sign_et_email); mPassword=findViewById(R.id.sign_et_pass); mSingUpButton=findViewById(R.id.sign_btn_signup); mEmailTextInput=findViewById(R.id.sign_text_input_email); mPassTextInput=findViewById(R.id.sign_text_input_password); //툴바 커스텀 mToolbar=findViewById(R.id.membership_toolbar); setSupportActionBar(mToolbar); ActionBar actionBar = getSupportActionBar(); View viewToolbar = getLayoutInflater().inflate(R.layout.actionbar_white, null); actionBar.setDisplayShowCustomEnabled(true); actionBar.setDisplayShowTitleEnabled(false); actionBar.setCustomView(viewToolbar, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER)); //-----RETROFIT------------- } private void tryPostSign(){ final String email=mEmail.getText().toString(); final String password=mPassword.getText().toString(); final String name="test"; final String typeNo="1"; LoginService loginService=new LoginService(this); loginService.postSign(email,password,name,typeNo); } @Override public void validateSuccess(boolean success,String message) { if (success) { showCustomToast(message); Intent intent=new Intent(getApplicationContext(), Login.class); startActivity(intent); } else showCustomToast(message); } @Override public void validateFailure(String message) { showCustomToast(message == null || message.isEmpty() ? getString(R.string.network_error) : message); } public void onSignUpClick(View view){ tryPostSign(); } }
package cn.funeralobjects.demo.jpa.entity; import lombok.Data; import lombok.experimental.Accessors; import javax.persistence.*; import java.util.Set; /** * @author FuneralObjects * Create date: 2020/5/18 10:02 AM */ @Entity @Table(name = "t_personnel") @Data @Accessors(chain = true) public class Personnel { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(unique = true) private String name; @ManyToMany(cascade = CascadeType.PERSIST) @JoinTable( name = "t_dept_person", joinColumns = @JoinColumn(name = "personnel_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "department_id", referencedColumnName = "id") ) private Set<Department> departments; }
package murat.javaPractice.JavaLoop2; import java.util.Scanner; public class JavaLoop2 { Scanner in; int[][] cikti; int[] boycikti = new int[2]; public JavaLoop2() { // TODO Auto-generated constructor stub in = new Scanner(System.in); System.out.println("query sayisini girin."); int count = in.nextInt(); int[] girdi = new int[3*count]; int count2=1; cikti = new int[count][15]; for(int i=0;i<count;i++) { System.out.println((i+1)+"/"+count+" adim 3 sayi girin."); //a, b, n constraintlerini gir 0<=a,b<=50 1<=n<=15 int a = in.nextInt(); int b = in.nextInt(); int n = in.nextInt(); girdi[i*3] = a; girdi[i*3+1] = b; girdi[i*3+2] = n; boycikti[i] = 0; SeriHesapla(a,b,n,i); } System.out.println(count); for(int i=0;i<girdi.length;i++) { System.out.print(girdi[i]); System.out.print(" "); if(count2%3==0) { System.out.println(); } count2++; } for(int i=0;i<count;i++) { for (int j=0;j<boycikti[i];j++) { System.out.print(cikti[i][j]); System.out.print(" "); } System.out.println(); } } private void SeriHesapla(int a, int b, int n, int j) { // TODO Auto-generated method stub int ikiuzeri=1,Sonuc=0; Sonuc = a; for(int i=0;i<n;i++) { Sonuc = Sonuc+ikiuzeri*b; ikiuzeri = ikiuzeri*2; cikti[j][i] = Sonuc; boycikti[j]++; } } }
/** * 1. Create a class Medicine to represent a drug manufactured by a pharmaceutical company. Provide a function displayLabel() in this class to print Name and address of the company. Derive Tablet, Syrup and Ointment classes from the Medicine class. Override the displayLabel() function in each of these classes to print additional information suitable to the type of medicine. For example, in case of tablets, it could be “store in a cool dry place”, in case of ointments it could be “for external use only” etc. Create a class TestMedicine . Write main function to do the following: Declare an array of Medicine references of size 10 Create a medicine object of the type as decided by a randomly generated integer in the range 1 to 3. Refer Java API Documentation to find out random generation feature. Check the polymorphic behavior of the displayLabel() method. */ import java.util.Random; class Medicine { String name="Medicine Company"; String address= "India"; String displayLabel(){ return "Name: "+name+" Address: "+address; } } class Tablet extends Medicine{ String type = "Tablet"; String info = "store in a cool dry place"; @Override String displayLabel() { return "Name: "+name+"\nAddress: "+address+" \nType and Info: "+type+" "+info; } } class Syrup extends Medicine{ String type = "Syrup"; String info = "Keep away from direct sunlight"; @Override String displayLabel() { return "Name: "+name+"\nAddress: "+address+" \nType and Info: "+type+" "+info; } } class Ointment extends Medicine{ String type = "Ointment"; String info = "for external use only"; @Override String displayLabel() { return "Name: "+name+"\nAddress: "+address+" \nType and Info: "+type+" "+info; } } public class TestMedicine { public static void main(String[] args) { Medicine med[] = new Medicine[10]; Random ran = new Random(); int num = ran.nextInt() % 4; for(int i=0;i<10;i++) { num = ran.nextInt(4); if(num == 1) med[i] = new Ointment(); else if(num == 2) med[i]= new Syrup(); else med[i] = new Tablet(); System.out.println(med[i].displayLabel()); System.out.println(); } } }
package com.phicomm.account.requestmanager; public class PoCRequestFactory { public static final int REQUEST_TYPE_INIT_CHECK = 0; public static final int REQUEST_TYPE_CONTACT_UPLOAD = 1; public static final int REQUEST_TYPE_INIT_UPLOAD = 2; public static final int REQUEST_TYPE_INIT_SYNC = 3; public static final int REQUEST_TYPE_INIT_CONTACT = 4; public static final int REQUEST_TYPE_INIT_MAP = 10; public static final int REQUEST_TYPE_GET_MAP = 11; public static Request getInitCheckRequest(){ Request request = new Request(REQUEST_TYPE_INIT_CHECK); return request; } public static Request getContactUploadRequest(){ Request request = new Request(REQUEST_TYPE_CONTACT_UPLOAD); return request; } public static Request getInitUploadRequest(){ Request request = new Request(REQUEST_TYPE_INIT_UPLOAD); return request; } public static Request getInitSyncRequest(){ Request request = new Request(REQUEST_TYPE_INIT_SYNC); return request; } public static Request getInitMapRequest(){ Request request = new Request(REQUEST_TYPE_INIT_MAP); return request; } public static Request getGetMapRequest(){ Request request = new Request(REQUEST_TYPE_GET_MAP); return request; } public static Request getInitContactRequest(){ Request request = new Request(REQUEST_TYPE_INIT_CONTACT); return request; } }
package viewText; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.Scanner; import javafx.scene.paint.Color; import model.*; public class Main { static Random ran = new Random(); static Scanner scan = new Scanner(System.in); static List<Integer> coord=new ArrayList<>(); static Player lagia = new Player(1,Color.BLACK); static int [] newOrder= new int[4]; static List<Integer> dc=new ArrayList<>(); public static void main(String[] args) { Model.deck.importDeck(); setupGame(); play(); } public static void setupGame() { /* * Le setupGame est très simple, chaque action fais une ligne, * sauf lors d'une boucle pour les 4 joueurs (ex: couleur) * * De plus certaines fonctions ont besoin de donnees de l'utilisateur, * dans ce cas on les definit ici (ex; choisir une couleur ou un nombre de joueur) * Les fonctions qui n'ont pas besoin de l'entree clavier sont definies dans Model * (ex: piocher, melanger) */ // on choisit le nb de joueurs nbPlayer(); //On choisit leur couleur for (int i = 0; i < Model.player.length; i++) { colorChoice(i); } //On mélange le deck Model.shuffleDeck(); //On pioche Model.draw(); //On affiche la pioche dc.add(0); showDominos(Model.onBoardDominos,dc); //On definit un ordre aleatoire pour le premier tour Model.setRandomOrder(); //Chaque joueur choisit un domino for (int i : Model.order) { int d = dominoChoice(i,dc); dc.add(d); for(int k=0; k< Model.order.length; k++) { if(Model.deck.getDomino(d)==Model.onBoardDominos.get(k)) newOrder[k]=i; } } dc.clear(); dc.add(0); } public static void nbPlayer() { //On demande a l'utilisateur le nombre de joueur System.out.println("Combien de personnes veulent jouer ?"); int nbPlayer = scan.nextInt(); scan.nextLine(); if(nbPlayer<=4) { //Si le nombre de joueurs est adéquat, on définit le nombre de joueur dans Model Model.setNbPlayer(nbPlayer); } else { //Sinon il suffit de relancer la fonction pour redemander le nombre System.out.println("Trop de joueurs !"); nbPlayer(); } } public static void colorChoice(int i){ System.out.println("Joueur"+" " +(i+1)+" "+" comment vous appellez-vous ? (alex, paul...)"); String name = scan.nextLine(); Model.createPlayer(i, Color.BLUE, name,false); } public static void showDomino(Domino d) { System.out.print(d.getNumber()+ " : "); System.out.println("Le premier territoire est "+ d.getHalf(0).getType() +" avec "+ d.getHalf(0).getCrown() +" couronnes\n" + "Le deuxieme territoire est "+ d.getHalf(1).getType() +" avec "+ d.getHalf(1).getCrown() +" couronnes\n"); } public static void showDominos(ArrayList<Domino> dominos, List<Integer> dc) { for(Domino d : dominos) { if(dc.size()==1) { showDomino(d); } else { if(!dc.contains(d.getNumber())) { showDomino(d); } } } } public static Domino getOnBoardDomino(int nbDomino) { for (Domino dom : Model.onBoardDominos) { if (dom.getNumber() == nbDomino) { return dom; } } return null; } public static int dominoChoice(int i,List<Integer> dc) { System.out.println("Joueur "+ (i+1) +" quelle domino choisissez vous ? (donner son numéro)"); int d=scan.nextInt(); scan.nextLine(); if(getOnBoardDomino(d)!=Model.deck.getDomino(d) || d>48) { return dominoChoice(i,dc); } else if(dc.contains(d)) { System.out.println("Ce domino à déja été choisi, veuillez en choisir un autre"); return dominoChoice(i,dc); } else { return d; } } public static void getCoord(int i) { System.out.println("Joueur "+ (i+1) +", veuillez rentrer la coordonnée selon x de la première partie du domino"); coord.add(scan.nextInt()); scan.nextLine(); System.out.println("Joueur "+ (i+1) +" veuillez rentrer la coordonnée selon y de la première partie du domino"); coord.add(scan.nextInt()); scan.nextLine(); System.out.println("Joueur "+ (i+1) +" veuillez rentrer la coordonnée selon x de la seconde partie du domino "); coord.add(scan.nextInt()); scan.nextLine(); System.out.println("Joueur "+ (i+1) +" veuillez rentrer la coordonnée selon y de la seconde partie du domino"); coord.add(scan.nextInt()); scan.nextLine(); } public static void dominoPlace(int j,Domino d) { getCoord(j); if(Model.player[j].isPlacable(coord.get(0),coord.get(1),coord.get(2),coord.get(3),d)) { Model.player[j].placeDomino(coord.get(0),coord.get(1),coord.get(2),coord.get(3),d); } else { System.out.println("Vous ne pouvez pas placer cette piece ici"); coord.clear(); dominoPlace(j,d); } } public static void play() { while(Model.deck.hasNext()) { System.out.println("\n\nNouveau tour \n"); Model.dominosPlaying = Model.onBoardDominos; Model.draw(); // création d'une liste temporaire pour faire l'ordre de jeu int[] newOrder2 = new int[4]; for(int i=0; i<Model.nbKings;i++) { int j = newOrder[i]; if(Model.player[j]==lagia) { } else { // affiche le board et le domino choisi puis le place Model.player[j].printBoard(); Domino d=Model.dominosPlaying.get(i); showDomino(d); //si le joueurs peut placer le domino on l'autorise à le placer sinon on passe au choix if(Model.player[j].listPlacable(d).size()!=0) { dominoPlace(j,d); coord.clear(); } // montre les dominos suivant pour qu'il choisisse son prochain domino showDominos(Model.onBoardDominos,dc); int newDc =dominoChoice(j,dc); dc.add(newDc); // Recupere l'ordre du domino qu'il a choisi pour avoir l'ordre de jeu for(Domino domino:Model.onBoardDominos) { if(Model.deck.getDomino(newDc)==domino) { newOrder2[Model.onBoardDominos.indexOf(domino)]=j; } } } } //met à jour l'ordre de jeu newOrder=newOrder2; dc.clear(); dc.add(0); } //fin de la partie, on compte les points System.out.println("La partie est finie !!!"); for (Player p : Model.player) { p.scoreBoard(p.board); System.out.println("Score : " + p.totalScore); } } }
package com.kodilla.patterns2.observer.homework; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class StudentHomeWorksTestSuite { @Test void testUpdate(){ //Given StudentHomeWorks john = new StudentHomeWorks("John Smith"); StudentHomeWorks max = new StudentHomeWorks("Max Brown"); StudentHomeWorks alex = new StudentHomeWorks("Alex Smith"); TeacherHomeWork bill = new TeacherHomeWork("Bill"); TeacherHomeWork peter = new TeacherHomeWork("Peter"); john.registerTeacher(bill); max.registerTeacher(bill); alex.registerTeacher(peter); //When john.addHomeWork("Poem about tree."); john.addHomeWork("Poem about rock."); john.addHomeWork("Poem about river."); max.addHomeWork("Poem about hardness of live."); max.addHomeWork("Poem about wife."); alex.addHomeWork("Poem about Poland."); //Then assertEquals(peter.getUpdatesCount(), 1); assertEquals(bill.getUpdatesCount(), 5); } }
/* * 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 dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import model.Course; import utils.DBUtils; /** * * @author Los_e */ public class CourseDAO { public static ArrayList<Course> getAllCourses() { ArrayList<Course> list = new ArrayList<Course>(); Connection con = DBUtils.getConnection(); PreparedStatement pst = null; String sql = "select * from courses"; try { pst = con.prepareStatement(sql); ResultSet rs = pst.executeQuery(sql); while (rs.next()) { Course course = new Course(); course.setCourseid(rs.getInt(1)); course.setTitle(rs.getString(2)); course.setStream(rs.getString(3)); course.setType(rs.getString(4)); course.setStartdate(rs.getString(5)); course.setEnddate(rs.getString(6)); list.add(course); } } catch (SQLException ex) { Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { try { pst.close(); } catch (SQLException ex) { Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); } try { con.close(); } catch (SQLException ex) { Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); } } return list; } public static Course getCourseById(int courseid) { Course course = new Course(); Connection con = DBUtils.getConnection(); PreparedStatement pst = null; String sql = "select * from courses where courseid = ?"; try { pst = con.prepareStatement(sql); pst.setInt(1, courseid); ResultSet rs = pst.executeQuery(); while (rs.next()) { course.setCourseid(rs.getInt(1)); course.setTitle(rs.getString(2)); course.setStream(rs.getString(3)); course.setType(rs.getString(4)); course.setStartdate(rs.getString(5)); course.setEnddate(rs.getString(6)); } } catch (SQLException ex) { Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { try { pst.close(); } catch (SQLException ex) { Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); } try { con.close(); } catch (SQLException ex) { Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); } } return course; } public static ArrayList<Course> getAllCoursesOrderedByStartdatePerStreamType(String stream, String type) { ArrayList<Course> list = new ArrayList<Course>(); Connection con = DBUtils.getConnection(); PreparedStatement pst = null; String sql = "select * from courses where stream = ? and type = ? order by startdate"; try { pst = con.prepareStatement(sql); pst.setString(1, stream); pst.setString(2, type); ResultSet rs = pst.executeQuery(); while (rs.next()) { Course course = new Course(); course.setCourseid(rs.getInt(1)); course.setTitle(rs.getString(2)); course.setStream(rs.getString(3)); course.setType(rs.getString(4)); course.setStartdate(rs.getString(5)); course.setEnddate(rs.getString(6)); list.add(course); } } catch (SQLException ex) { Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { try { pst.close(); } catch (SQLException ex) { Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); } try { con.close(); } catch (SQLException ex) { Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); } } return list; } public static ArrayList<Course> getAllCoursesOrderedByStreamType() { ArrayList<Course> list = new ArrayList<Course>(); Connection con = DBUtils.getConnection(); PreparedStatement pst = null; String sql = "select * from courses order by stream, type"; try { pst = con.prepareStatement(sql); ResultSet rs = pst.executeQuery(sql); while (rs.next()) { Course course = new Course(); course.setCourseid(rs.getInt(1)); course.setTitle(rs.getString(2)); course.setStream(rs.getString(3)); course.setType(rs.getString(4)); course.setStartdate(rs.getString(5)); course.setEnddate(rs.getString(6)); list.add(course); } } catch (SQLException ex) { Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { try { pst.close(); } catch (SQLException ex) { Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); } try { con.close(); } catch (SQLException ex) { Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); } } return list; } // public Course getCourseById(int courseid) { // // Course course = new Course(); // Connection con = DBUtils.getConnection(); // PreparedStatement pst = null; // String sql = "select * from courses where courseid=?;"; // // try { // // pst = con.prepareStatement(sql); // pst.setInt(1, courseid); // ResultSet rs = pst.executeQuery(); // // while (rs.next()) { // // course.setCourseid(rs.getInt(1)); // course.setTitle(rs.getString(2)); // course.setStream(rs.getString(3)); // course.setType(rs.getString(4)); // course.setStartdate(rs.getString(5)); // course.setStartdate(rs.getString(6)); // // } // } catch (SQLException ex) { // Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); // } finally { // // try { // pst.close(); // } catch (SQLException ex) { // Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); // } // try { // con.close(); // } catch (SQLException ex) { // Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); // } // } // // return course; // } // public static void insertCourse(Course course) { Connection con = DBUtils.getConnection(); PreparedStatement pst = null; String sql = "insert into courses(title, stream, type, startdate, enddate) values (?, ?, ?, ?, ?)"; boolean result = false; try { pst = con.prepareStatement(sql); pst.setString(1, course.getTitle()); pst.setString(2, course.getStream()); pst.setString(3, course.getType()); pst.setString(4, course.getStartdate().toString()); pst.setString(5, course.getEnddate().toString()); pst.executeUpdate(); result = true; } catch (SQLException ex) { Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); result = false; } finally { try { pst.close(); } catch (SQLException ex) { Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); } try { con.close(); } catch (SQLException ex) { Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); } } if (result) { System.out.println("Inserted new Course"); } // return result; } public static void updateCourse(Course course) { Connection con = DBUtils.getConnection(); PreparedStatement pst = null; String sql = "UPDATE courses SET title = ? /*1*/, stream= ? /*2*/, type = ? /*3*/ , startdate = ? /*4*/, enddate = ? /*5*/ WHERE courseid = ? /*6*/"; boolean result = false; try { pst = con.prepareStatement(sql); pst.setString(1, course.getTitle()); pst.setString(2, course.getStream()); pst.setString(3, course.getType()); pst.setString(4, course.getStartdate().toString()); pst.setString(5, course.getEnddate().toString()); pst.setInt(6, course.getCourseid()); pst.executeUpdate(); result = true; } catch (SQLException ex) { Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); result = false; } finally { try { pst.close(); } catch (SQLException ex) { Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); } try { con.close(); } catch (SQLException ex) { Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); } } if (result) { System.out.println("Updated Course"); } // return result; } public static void deleteCourse(int courseid) { Connection con = DBUtils.getConnection(); PreparedStatement pst = null; String sql = "DELETE FROM courses WHERE courseid = ?"; boolean result = false; try { pst = con. prepareStatement(sql); pst.setInt(1, courseid); pst.executeUpdate(); result = true; } catch (SQLException ex) { Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); result = false; } finally { try { pst.close(); } catch (SQLException ex) { Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); } try { con.close(); } catch (SQLException ex) { Logger.getLogger(CourseDAO.class.getName()).log(Level.SEVERE, null, ex); } } if (result) { System.out.println("Deleted Course"); } // return result; } }
package org.techstuff.auth.config; import org.apache.tomcat.jdbc.pool.DataSource; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.validation.constraints.NotNull; import java.sql.SQLException; @Configuration @ConfigurationProperties(locations = "classpath:mysql.properties", prefix="mysql") public class DataSourceConfiguration { private static final Integer DEFAULT_INITIAL_POOL_SIZE = 10; private static final Integer DEFAULT_MAX_ACTIVE_SIZE = 10; @NotNull private String userName; @NotNull private String password; @NotNull private String dbUrl; @NotNull private String driverClassName; @NotNull private Integer initialPoolSize; @NotNull private Integer maxActive; public void setUserName(String userName) { this.userName = userName; } public void setPassword(String password) { this.password = password; } public void setDbUrl(String dbUrl) { this.dbUrl = dbUrl; } public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } public void setInitialPoolSize(String size) { try { initialPoolSize = Integer.parseInt(size); } catch (NumberFormatException exception) { initialPoolSize = DEFAULT_INITIAL_POOL_SIZE; } } public void setMaxActive(String size) { try { maxActive = Integer.parseInt(size); } catch (NumberFormatException exception) { maxActive = DEFAULT_MAX_ACTIVE_SIZE; } } @Bean public javax.sql.DataSource dataSource() throws SQLException { DataSource ds = new DataSource(); ds.setUsername(userName); ds.setPassword(password); ds.setUrl(dbUrl); ds.setDriverClassName(driverClassName); ds.setTestOnConnect(true); ds.setInitialSize(initialPoolSize); ds.setMaxActive(maxActive); ds.setMinIdle(10); ds.setMaxIdle(20); ds.setMaxWait(10000); ds.setValidationQuery("SELECT 1"); ds.setDefaultAutoCommit(false); return ds; } }
package decisao; import javax.swing.JOptionPane; public class DesafioDecisa2 { public static void main(String[] args) { // TODO Auto-generated method stub int idade = Integer.parseInt(JOptionPane.showInputDialog("idade")); if (idade<16) { System.out.println("Voce possui " + idade + " anos : NÃO VAI VOTAR" ); } if (idade>=18 && idade<70) { System.out.println("Voce possui " + idade + " anos : VOTO OBRIGATÓRIO" ); } if (idade>70 || idade==16 || idade==17 ) { System.out.println("Voce possui " + idade + " anos : VOTO FACULTATIVO" ); } } }
package ru.shikhovtsev.framework.tests; import ru.shikhovtsev.framework.annotations.AfterEach; import ru.shikhovtsev.framework.annotations.Test; public class AfterFailedTest { @Test public void test() { System.out.println("Hello"); } @AfterEach public void afterWithException() { System.out.println("exception"); throw new RuntimeException(); } @AfterEach public void afterWithoutException() { System.out.println("Hi"); } }
import java.io.BufferedReader; import java.io.InputStreamReader; public class Test2_143 { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int su = Integer.parseInt(in.readLine()); System.out.println(su==1?"³²ÀÚ":"¿©ÀÚ"); } }
package com.yunwa.aggregationmall.service.pdd; import com.github.pagehelper.PageInfo; import com.yunwa.aggregationmall.pojo.pdd.dto.PddGoodsDto; import com.yunwa.aggregationmall.pojo.pdd.po.PddGoods; import com.yunwa.aggregationmall.pojo.pdd.vo.PddGoodsDocumentVO; import java.util.HashMap; import java.util.List; public interface PddGoodsService { String goodsSearch(); String getGoodsPicUrls(PddGoodsDto pddGoodsDto); //void getUrls(String p_id, List<PddGoods> list); boolean delPddGoods(); PageInfo<PddGoods> getGoodsList(int pageNum, HashMap<String, Object> map); PddGoods getGoodsDetil(long goods_id); PddGoodsDocumentVO getGoodsDocument(long goods_id); //删除优惠券啊过期的商品 void deleteOverdueGoods(); }
package com.javaee.ebook1.controller.admin; import com.javaee.ebook1.common.JsonMessage; import com.javaee.ebook1.common.exception.OpException; import com.javaee.ebook1.mybatis.vo.LogVO; import com.javaee.ebook1.service.FileService; import com.javaee.ebook1.service.LogService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import javax.annotation.Resource; /** * @author xuzihan * @version 1.0 * @description: TODO * @data 2021/4/15 **/ @Api(value = "日志接口") @RestController public class LogController { @Resource private LogService logService; @RequestMapping(value = "/admin/log", method = RequestMethod.GET) @ApiOperation(value = "方法描述:获得日志,请求方法:GET,参数:String,返回值:JsonMessage<LogVO>") public JsonMessage<LogVO> getLog(@RequestParam String type) throws OpException { return new JsonMessage<>(logService.getLog(type)); } }
package edu.uha.miage.core.service; import edu.uha.miage.core.entity.Domaine; import java.util.List; import java.util.Optional; /** * * @author victo */ public interface DomaineService { Domaine save(Domaine entity); void delete(Long id); List<Domaine> findAll(); Optional<Domaine> findById(Long id); Domaine findByLibelle(String libelle); Domaine getOne(Long id); }
package cn.auto.core.webdriver.web; import cn.auto.core.webdriver.DriverRequest; /** * Created by chenmeng on 2019/8/16. */ public class WebDriverRequest implements DriverRequest { private Browser browser; public WebDriverRequest(Browser browser) { this.browser = browser; } public Engine engineType() { return Engine.Web; } public Browser browser() { return this.browser; } }
package common.util.web; /** * Generic Server-side response * * @author rrajamiyer * */ public class ServiceResponse { private String message; private int code; public ServiceResponse() {} public ServiceResponse(String message, int code) { super(); this.message = message; this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } }
public class VisitedData { String url; int contentLength; int outlinkSize; String type; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public int getContentLength() { return contentLength; } public void setContentLength(int contentLength) { this.contentLength = contentLength; } public int getOutlinkSize() { return outlinkSize; } public void setOutlinkSize(int outlinkSize) { this.outlinkSize = outlinkSize; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
package at.wea5.geocaching.webserviceproxy; import java.io.ByteArrayInputStream; import javax.faces.context.FacesContext; import javax.faces.event.PhaseId; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import org.primefaces.model.DefaultStreamedContent; import org.primefaces.model.StreamedContent; /** * <p>Java-Klasse für Image complex type. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * &lt;complexType name="Image"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="ImageData" type="{http://www.w3.org/2001/XMLSchema}base64Binary" minOccurs="0"/> * &lt;element name="Id" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;element name="CacheId" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;element name="FileName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Image", propOrder = { "imageData", "id", "cacheId", "fileName" }) public class Image { @XmlElement(name = "ImageData") protected byte[] imageData; @XmlElement(name = "Id") protected int id; @XmlElement(name = "CacheId") protected int cacheId; @XmlElement(name = "FileName") protected String fileName; // -------------- manually added getter for rendering of images out of a byte array public StreamedContent getImage() { FacesContext context = FacesContext.getCurrentInstance(); if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) { return new DefaultStreamedContent(); } else { try { return new DefaultStreamedContent(new ByteArrayInputStream(this.imageData), "image/jpg"); } catch (Exception e) {} } return new DefaultStreamedContent(); } /** * Ruft den Wert der imageData-Eigenschaft ab. * * @return * possible object is * byte[] */ public byte[] getImageData() { return imageData; } /** * Legt den Wert der imageData-Eigenschaft fest. * * @param value * allowed object is * byte[] */ public void setImageData(byte[] value) { this.imageData = value; } /** * Ruft den Wert der id-Eigenschaft ab. * */ public int getId() { return id; } /** * Legt den Wert der id-Eigenschaft fest. * */ public void setId(int value) { this.id = value; } /** * Ruft den Wert der cacheId-Eigenschaft ab. * */ public int getCacheId() { return cacheId; } /** * Legt den Wert der cacheId-Eigenschaft fest. * */ public void setCacheId(int value) { this.cacheId = value; } /** * Ruft den Wert der fileName-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getFileName() { return fileName; } /** * Legt den Wert der fileName-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setFileName(String value) { this.fileName = value; } }
package com.ipincloud.iotbj.srv.domain; import java.io.Serializable; import java.math.BigDecimal; import java.sql.Time; import java.sql.Date; import java.sql.Timestamp; import com.alibaba.fastjson.annotation.JSONField; //(BtnAttr) //generate by redcloud,2020-07-24 19:59:20 public class BtnAttr implements Serializable { private static final long serialVersionUID = 15L; // 键值ID private Long id ; // 调用编码 private String encode ; // 功能配置1 private String cs1 ; // 功能配置2 private String cs2 ; // 功能配置3 private String cs3 ; // 功能配置4 private String cs4 ; // 功能配置5 private String cs5 ; // 功能配置5 private String cs6 ; // 备注 private String memo ; // 主sql private String cs7 ; // 版本锁 private Integer version ; public Long getId() { return id ; } public void setId(Long id) { this.id = id; } public String getEncode() { return encode ; } public void setEncode(String encode) { this.encode = encode; } public String getCs1() { return cs1 ; } public void setCs1(String cs1) { this.cs1 = cs1; } public String getCs2() { return cs2 ; } public void setCs2(String cs2) { this.cs2 = cs2; } public String getCs3() { return cs3 ; } public void setCs3(String cs3) { this.cs3 = cs3; } public String getCs4() { return cs4 ; } public void setCs4(String cs4) { this.cs4 = cs4; } public String getCs5() { return cs5 ; } public void setCs5(String cs5) { this.cs5 = cs5; } public String getCs6() { return cs6 ; } public void setCs6(String cs6) { this.cs6 = cs6; } public String getMemo() { return memo ; } public void setMemo(String memo) { this.memo = memo; } public String getCs7() { return cs7 ; } public void setCs7(String cs7) { this.cs7 = cs7; } public Integer getVersion() { return version ; } public void setVersion(Integer version) { this.version = version; } }
package kr.or.ddit.jobsboard.controller; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import kr.or.ddit.jobsboard.service.IJobsBoardService; import kr.or.ddit.profile_file.service.IProfileFileService; import kr.or.ddit.vo.JobsBoardCommentVO; import kr.or.ddit.vo.JobsBoardVO; import kr.or.ddit.vo.ProfileFileVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/user/jobsboard/") public class JobsBoardController { @Autowired private IJobsBoardService jobsBoardSerivce; @Autowired private IProfileFileService profileService; @RequestMapping("jobsBoardList") public ModelAndView josBoardList(ModelAndView modelAndView, HttpServletRequest request) throws Exception{ List<JobsBoardVO> jobsBoardList = this.jobsBoardSerivce.JobsBoardList(); modelAndView.addObject("breadcrumb_title", "뉴스 센터"); modelAndView.addObject("breadcrumb_first", "체용 공고 게시판"); modelAndView.addObject("breadcrumb_first_url", request.getContextPath() + "/user/jobsboard/jobsBoardList.do"); modelAndView.addObject("jobsBoardList",jobsBoardList); modelAndView.setViewName("user/jobsboard/jobsBoardList"); return modelAndView; } @RequestMapping("jobsBoardForm") public ModelAndView jobsBoardForm(HttpServletRequest request, ModelAndView modelAndView){ modelAndView.addObject("breadcrumb_title", "뉴스 센터"); modelAndView.addObject("breadcrumb_first", "체용 공고 게시판"); modelAndView.addObject("breadcrumb_first_url", request.getContextPath() + "/user/jobsboard/jobsBoardList.do"); modelAndView.addObject("breadcrumb_second", "채용 공고 게시글 등록"); modelAndView.setViewName("user/jobsboard/jobsBoardForm"); return modelAndView; } @RequestMapping("insertJobsBoard") public String jobsBoardInsert( HttpServletRequest request, String jobs_title, String jobs_content, String jobs_startdate, String jobs_enddate, String mem_id) throws Exception{ JobsBoardVO jobsboardInfo = new JobsBoardVO(); jobsboardInfo.setJobs_content(jobs_content); jobsboardInfo.setJobs_title(jobs_title); jobsboardInfo.setJobs_startdate(jobs_startdate); jobsboardInfo.setJobs_enddate(jobs_enddate); jobsboardInfo.setMem_id(mem_id); this.jobsBoardSerivce.jobsBoardInsert(jobsboardInfo); String taskResult = null; String message = null; taskResult = "success"; message = URLEncoder.encode("게시글이 정상적으로 등록되었습니다.", "UTF-8"); return "redirect:/user/jobsboard/jobsBoardList.do?taskResult=" + taskResult + "&message=" + message; } @RequestMapping("jobsBoardView") public ModelAndView jobsBoardView(Map<String, String> params , ModelAndView modelAndView, String jobs_no, HttpServletRequest request, String mem_id) throws Exception{ params.put("jobs_no", jobs_no); params.put("mem_id", mem_id); JobsBoardVO jobsboardInfo = new JobsBoardVO(); jobsboardInfo = this.jobsBoardSerivce.jobsBoardInfo(params); List<JobsBoardCommentVO> jobsBoardCommentInfo = null; jobsBoardCommentInfo = this.jobsBoardSerivce.jobsBoardCommentList(params); ProfileFileVO profileInfo = this.profileService.selectProfileFileInfo(params); modelAndView.addObject("breadcrumb_title", "뉴스 센터"); modelAndView.addObject("breadcrumb_first", "체용 공고 게시판"); modelAndView.addObject("breadcrumb_first_url", request.getContextPath() + "/user/jobsboard/jobsBoardList.do"); modelAndView.addObject("jobsboardInfo", jobsboardInfo); modelAndView.addObject("breadcrumb_second", "채용 공고 게시글 View"); modelAndView.addObject("commentList",jobsBoardCommentInfo); modelAndView.addObject("profileInfo", profileInfo); modelAndView.setViewName("user/jobsboard/jobsBoardView"); // 조회수 올리기 this.jobsBoardSerivce.hitup(params); return modelAndView; } @RequestMapping("updateJobsBoard") public String updateJobsBoard(JobsBoardVO vo) throws Exception{ int cnt = this.jobsBoardSerivce.modifyJobsBoard(vo); System.out.println(vo.getJobs_title()); String taskResult = null; String message = null; if (cnt > 0) { taskResult = "success"; message = URLEncoder.encode("게시글이 정상적으로 수정되었습니다.", "UTF-8"); } else { taskResult = "warning"; message = URLEncoder.encode("게시글 수정에 실패했습니다.", "UTF-8"); } return "redirect:/user/jobsboard/jobsBoardList.do?taskResult=" + taskResult + "&message=" + message; } @RequestMapping("deleteJobsBoard") public String deleteJobsBoard(String jobs_no ) throws Exception{ Map<String,String> params = new HashMap<String, String>(); params.put("jobs_no", jobs_no); int cnt =this.jobsBoardSerivce.deleteJobsBoard(params); String taskResult= null; String message= null; if(cnt > 0){ taskResult= "success"; message= URLEncoder.encode("게시글이 정상적으로 삭제되었습니다.", "UTF-8"); } else{ taskResult= "warning"; message= URLEncoder.encode("게시글 삭제에 실패했습니다 ","UTF-8"); } return "redirect:/user/jobsboard/jobsBoardList.do?taskResult=" + taskResult + "&message=" + message; } @RequestMapping("insertJobsComment") public String insertJobsComment(JobsBoardCommentVO vo) throws Exception{ System.out.println(vo); int cnt = this.jobsBoardSerivce.insertJobsBoardComment(vo); String taskResult= null; String message= null; if(cnt > 0){ taskResult= "success"; message= URLEncoder.encode("댓글이 정상적으로 작성되었습니다.", "UTF-8"); }else{ taskResult= "warning"; message= URLEncoder.encode("댓글 작성이 실패되었습니다.", "UTF-8"); } return "redirect:/user/jobsboard/jobsBoardView.do?taskResult=" + taskResult+ "&message=" +message + "&jobs_no=" + vo.getJobs_no() + "&mem_id=" + vo.getMem_id(); } @RequestMapping("deleteJobsComment") public String deleteJobsComment(String comment_seq,String mem_id ,String jobs_no) throws Exception{ Map<String,String> params = new HashMap<String, String>(); params.put("comment_seq", comment_seq); int cnt = this.jobsBoardSerivce.deleteJobsComment(params); String taskResult= null; String message= null; if(cnt > 0 ){ taskResult= "success"; message=URLEncoder.encode("댓글이 정상적으로 삭제되었습니다.","UTF-8"); }else{ taskResult="warning"; message=URLEncoder.encode("댓글 삭제가 실패되었습니다.","UTF-8"); } return "redirect:/user/jobsboard/jobsBoardView.do?taskResult=" + taskResult+ "&message=" +message +"&jobs_no="+ jobs_no +"&mem_id=" + mem_id; } @RequestMapping("modifyJobsComment") public String modifyJobsComment(String comment_seq, String comment_content, String jobs_no, String mem_id) throws Exception{ Map<String,String> params = new HashMap<String, String>(); System.out.println(comment_content +"글"); params.put("comment_seq", comment_seq); params.put("comment_content", comment_content); int cnt = this.jobsBoardSerivce.modifyJobsComment(params); String taskResult= null; String message= null; if(cnt > 0 ){ taskResult= "success"; message=URLEncoder.encode("댓글이 정상적으로 수정되었습니다.","UTF-8"); }else{ taskResult="warning"; message=URLEncoder.encode("댓글 수정이 실패되었습니다.","UTF-8"); } return "redirect:/user/jobsboard/jobsBoardView.do?taskResult=" + taskResult+ "&message=" +message +"&jobs_no="+ jobs_no +"&mem_id=" +mem_id; } }
package com.example.gopalawasthi.movielovers; import android.content.Intent; import android.graphics.Color; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.LinearSnapHelper; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SnapHelper; import android.view.View; import android.widget.Button; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.wang.avi.AVLoadingIndicatorView; import com.wang.avi.Indicator; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static com.example.gopalawasthi.movielovers.MovieFragment.API_key; import static com.example.gopalawasthi.movielovers.MovieFragment.LANGUGAGE; import static com.example.gopalawasthi.movielovers.MovieFragment.PAGE; import static com.example.gopalawasthi.movielovers.MovieFragment.POPULAR_CATEGORY; import static com.example.gopalawasthi.movielovers.MovieFragment.TOPRATED_CATEGORY; import static com.example.gopalawasthi.movielovers.MoviesActivity.MOVIEDATABASE_ID; public class ShowallList extends AppCompatActivity { int pagecount = 1; RecyclerView recyclerView; List<Nowplaying.ResultsBean> list; MoviesAdapter adapter; TvtopratedAdapter tvtopratedAdapter; List<TvClass.ResultsBean> populartv; MoviesDao dao; Moviedatabase moviedatabase; FavouriteFragment fragment; Button button; AVLoadingIndicatorView avi; FrameLayout frameLayout; String a; private boolean loading = true; int pastVisiblesItems, visibleItemCount, totalItemCount; LinearLayoutManager linearLayoutManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_showall_list); avi = findViewById(R.id.avi); Intent intent = getIntent(); frameLayout = findViewById(R.id.frameshowall); if(intent.hasCategory("nowplaying")){ a = "now_playing"; createfornowplaying(a); }else if(intent.hasCategory("popular")){ a = "popular"; createfornowplaying(a); }else if(intent.hasCategory("toprated")){ a = "top_rated"; createfornowplaying(a); }else if(intent.hasCategory("upcoming")){ a= "upcoming"; createfornowplaying(a); }else if(intent.hasCategory("tvpopular")){ a = "popular"; createforpopulartv(a); }else if(intent.hasCategory("tvtoprated")){ a = "top_rated"; createforpopulartv(a); } } private void createforpopulartv(final String a) { fragment = new FavouriteFragment(); populartv = new ArrayList<>(); recyclerView = findViewById(R.id.showalllistrecycler); fetchdatafrompopulartv(a); tvtopratedAdapter = new TvtopratedAdapter(this, populartv, new TvtopratedAdapter.onitemClicklistener() { @Override public void onitemclick(int position) { Intent intent = new Intent(ShowallList.this,MainActivity.class); int a = populartv.get(position).getId(); String b = populartv.get(position).getName(); intent.addCategory("TV"); intent.putExtra("movieid",a); intent.putExtra("moviename",b); intent.putExtra("movieposter",populartv.get(position).getPoster_path()); intent.putExtra("moviebackdrop",populartv.get(position).getBackdrop_path()); intent.putExtra("description",populartv.get(position).getOverview()); startActivity(intent); } @Override public void onitemLongclick(int position) { TvClass.ResultsBean bean = populartv.get(position); moviedatabase = Moviedatabase.getINSTANCE(ShowallList.this); dao = moviedatabase.getMovieDao(); dao.oninsertFavouriteTvShow(bean); Snackbar snackbar = Snackbar.make(frameLayout,"Added to Favourites",Snackbar.LENGTH_SHORT); snackbar.show(); } }); recyclerView.setAdapter(tvtopratedAdapter); linearLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false); recyclerView.setLayoutManager(linearLayoutManager); recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { if(dy > 0){ visibleItemCount = linearLayoutManager.getChildCount(); totalItemCount = linearLayoutManager.getItemCount(); pastVisiblesItems = linearLayoutManager.findFirstVisibleItemPosition(); if(loading){ if(visibleItemCount + pastVisiblesItems >= totalItemCount){ pagecount =pagecount+1; fetchdatafrompopulartv(a); } } } super.onScrolled(recyclerView, dx, dy); } }); } private void fetchdatafrompopulartv(String a) { retrofit2.Call<TvClass> nowplayingCall = ApiClient.getINSTANCE().getMoviesInterface().gettvpopular(a,API_key,LANGUGAGE,pagecount); nowplayingCall.enqueue(new Callback<TvClass>() { @Override public void onResponse(retrofit2.Call<TvClass> call, Response<TvClass> response) { if(response.body()!=null){ populartv.addAll(response.body().getResults()); tvtopratedAdapter.notifyDataSetChanged(); } avi.setVisibility(View.GONE); } @Override public void onFailure(retrofit2.Call<TvClass> call, Throwable t) { Toast.makeText(ShowallList.this, "No Internet Connection!!", Toast.LENGTH_SHORT).show(); avi.setVisibility(View.GONE); } }); } private void createfornowplaying(final String a) { list = new ArrayList<>(); recyclerView = findViewById(R.id.showalllistrecycler); // movieDatabase = Room.databaseBuilder(this,MovieDatabase.class,"mymovies").allowMainThreadQueries().build(); // movieDao= movieDatabase.getMovieDao(); // List<Nowplaying.ResultsBean> list =movieDao.getnowplaing(); recyclerView.setVisibility(View.GONE); fetchdatafromnetwork(a); adapter = new MoviesAdapter(list, this, new MoviesAdapter.onitemclicklistener() { @Override public void onItemclick(int position) { // Toast.makeText(ShowallList.this, "item click at position"+position, Toast.LENGTH_SHORT).show(); Intent intent = new Intent(ShowallList.this,MainActivity.class); int a = list.get(position).getId(); String b = list.get(position).getTitle(); intent.putExtra("movieid",a); intent.putExtra("moviename",b); intent.putExtra("movieposter",list.get(position).getPoster_path()); intent.putExtra("moviebackdrop",list.get(position).getBackdrop_path()); intent.putExtra("description",list.get(position).getOverview()); startActivity(intent); } @Override public void onlongItemclick(int position) { Nowplaying.ResultsBean bean = list.get(position); int id = bean.getId(); moviedatabase = Moviedatabase.getINSTANCE(ShowallList.this); dao = moviedatabase.getMovieDao(); dao.oninsertFavouriteMovie(bean); Snackbar snackbar = Snackbar.make(frameLayout,"Added to Favourites",Snackbar.LENGTH_SHORT); snackbar.show(); // Bundle bundle = new Bundle(); // bundle.putInt(MOVIEDATABASE_ID,id); // fragment.setArguments(bundle); } }); recyclerView.setAdapter(adapter); linearLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false); recyclerView.setLayoutManager(linearLayoutManager); recyclerView.setItemAnimator( new DefaultItemAnimator()); recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { if(dy > 0){ visibleItemCount = linearLayoutManager.getChildCount(); totalItemCount = linearLayoutManager.getItemCount(); pastVisiblesItems = linearLayoutManager.findFirstVisibleItemPosition(); if(loading){ if(visibleItemCount + pastVisiblesItems >= totalItemCount){ pagecount =pagecount+1; fetchdatafromnetwork(a); } } } super.onScrolled(recyclerView, dx, dy); } }); // List.clear(); // List.addAll(list); // adapter.notifyDataSetChanged(); } private void fetchdatafromnetwork(String a) { Call<Nowplaying> nowplayingCall = ApiClient.getINSTANCE().getMoviesInterface().getnowplayingMovies( a,API_key,LANGUGAGE,pagecount); nowplayingCall.enqueue(new Callback<Nowplaying>() { @Override public void onResponse(Call<Nowplaying> call, Response<Nowplaying> response) { if (response.isSuccessful()) { Nowplaying root = response.body(); list.addAll(root.getResults()); adapter.notifyDataSetChanged(); recyclerView.setVisibility(View.VISIBLE); } avi.setVisibility(View.GONE); } @Override public void onFailure(Call<Nowplaying> call, Throwable t) { Toast.makeText(ShowallList.this, "No Internet Connection!!", Toast.LENGTH_SHORT).show(); avi.setVisibility(View.GONE); } }); } public void LoadMore(View view) { } public void LoadMoreSearch(View view) { } }
package structural.adapter.my.demo1; // 用户使用 B 接口 public interface B { void runB(); }
import java.awt.*; import java.awt.event.*; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import javax.swing.*; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; public class TextEditor extends JFrame { private JTextArea ta; private JFileChooser fc; private JToolBar tb; public TextEditor() { ta = new JTextArea(20, 60); fc = new JFileChooser(); tb = new JToolBar(); JScrollPane sp = new JScrollPane(ta, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); FileFilter ff = new FileNameExtensionFilter("Plain text", "txt"); fc.setFileFilter(ff); add(sp); JMenuBar mb = new JMenuBar(); setJMenuBar(mb); JMenu file = new JMenu("File"); mb.add(file); file.add(Open); file.add(Save); file.addSeparator(); file.add(Exit); setDefaultCloseOperation(EXIT_ON_CLOSE); JMenu file2 = new JMenu("Help"); mb.add(file2); file2.add(About); JPanel p = new JPanel(); JButton b1 = new JButton("Bold"); JButton b2 = new JButton("Enlarge and Italic"); b1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ta.setFont(ta.getFont().deriveFont(Font.BOLD, 14f)); } }); b2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ta.setFont(ta.getFont().deriveFont(Font.ITALIC, 10f)); } }); p.add(b1); p.add(b2); tb.add(p); add(tb, BorderLayout.NORTH); pack(); setLocationRelativeTo(null); setVisible(true); } Action Open = new AbstractAction("Open File") { @Override public void actionPerformed(ActionEvent e) { if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) openFile(fc.getSelectedFile().getAbsolutePath()); } }; Action Save = new AbstractAction("Save File") { @Override public void actionPerformed(ActionEvent e) { saveFile(); } }; Action Exit = new AbstractAction("Exit") { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }; Action About = new AbstractAction("About") { @Override public void actionPerformed(ActionEvent e) { JFrame frame2 = new JFrame(); frame2.setBounds(100, 100, 450, 300); frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame2.getContentPane().setLayout(null); frame2.setVisible(true); } }; public void openFile(String fileName) { try { FileReader fr = new FileReader(fileName); ta.read(fr, null); fr.close(); setTitle(fileName); } catch (IOException e) { e.printStackTrace(); } } public void saveFile() { if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { try { FileWriter fw = new FileWriter(fc.getSelectedFile().getAbsolutePath() + ".txt"); ta.write(fw); fw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
package com.needii.dashboard.service; import com.needii.dashboard.dao.SupplierBalanceHistoryDao; import com.needii.dashboard.model.SupplierBalanceHistory; import com.needii.dashboard.model.form.SearchForm; import com.needii.dashboard.model.form.SupplierBalanceHistoryForm; import com.needii.dashboard.utils.ChartData; import com.needii.dashboard.utils.Pagination; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Transactional @Service("supplierBalanceHistoryService") public class SupplierBalanceHistoryServiceImpl implements SupplierBalanceHistoryService { @Autowired private SupplierBalanceHistoryDao dao; @Override public List<SupplierBalanceHistory> findByCustomerId(long customerId) { return dao.findByCustomerId(customerId); } @Override public SupplierBalanceHistory findOne(long id) { return dao.findOne(id); } @Override public SupplierBalanceHistory findLastBySupplierId(long supplierId) { return dao.findLastBySupplierId(supplierId); } @Override public void create(SupplierBalanceHistory entity) { // TODO Auto-generated method stub dao.create(entity); } @Override public void update(SupplierBalanceHistory entity) { // TODO Auto-generated method stub dao.update(entity); } @Override public void delete(SupplierBalanceHistory entity) { // TODO Auto-generated method stub dao.delete(entity); } @Override public List<SupplierBalanceHistory> findByCustomerId(long customerId, int limit, int offset) { // TODO Auto-generated method stub return dao.findByCustomerId(customerId, limit, offset); } @Override public long count(long customerId) { // TODO Auto-generated method stub return dao.count(customerId); } @Override public long count(SearchForm searchForm) { return dao.count(searchForm); } @Override public List<ChartData> findInWeek(String firstDay, String lastDay) { return dao.findInWeek(firstDay, lastDay); } @Override public List<ChartData> findInMonth(String firstDay, String lastDay) { return dao.findInMonth(firstDay, lastDay); } @Override public List<ChartData> findInYear(String firstDay, String lastDay) { return dao.findInYear(firstDay, lastDay); } @Override public List<SupplierBalanceHistory> findAll(SearchForm searchForm, Pagination pagination) { return dao.findAll(searchForm, pagination); } @Override public long count(SupplierBalanceHistoryForm supplierBalanceHistoryForm) { return dao.count(supplierBalanceHistoryForm); } @Override public List<SupplierBalanceHistory> findAll(SupplierBalanceHistoryForm supplierBalanceHistoryForm, Pagination pagination) { return dao.findAll(supplierBalanceHistoryForm, pagination); } }
// This is the main program for the blackjack game. public class Blackjack { // The main method should: // - Ask the user how many people want to play (up to 3, not including the dealer). // - Create an array of players. // - Create a Blackjack window. // - Play rounds until the players want to quit the game. // - Close the window. public static void main(String[] args){ GIO.displayMessage("Welcome to BlackjackGUI"); //define field for Player array creation int numPlayers; //ask for the amount of players w/ error checking. If it's valid, proceed to make the array of player objects. do { //error checking numPlayers = GIO.readInt("How many players are there (including the dealer, you can have 4 total)"); } while (numPlayers > 4 || numPlayers < 2); Player[] players = new Player[numPlayers]; //Make the array of players //Enter everyone's starting money. int starting = GIO.readInt("Enter the starting amount for every player:"); //Create the dealer String name = GIO.readString("Who is the dealer? Enter your name first:"); Player dealer = new Player(name, true, starting); players[players.length-1] = dealer; //Fill in the info for the rest of the players. for (int i = 0; i < players.length-1; i++){ name = GIO.readString("Player" + (i+1) + ", enter your name:"); players[i] = new Player(name, false, starting); } //Create the window after the players are made. BlackjackWindow window = new BlackjackWindow(players); window.setVisible(true); //Go through the round after the window has been created. Blackjack.playRound(players, window); } // This method executes an single round of play (for all players). It should: // - Create and shuffle a deck of cards. // - Start the round (deal cards) for each player, then the dealer. // - Allow each player to play, then the dealer. // - Finish the round (announce results) for each player. public static void playRound(Player[] players, BlackjackWindow window){ //Create the deck Deck deck = new Deck(); //Loop through this whole loop as long as there are 2 players in the game. boolean repeat = true; while (repeat == true){ //Go through each player to setup the round. //run through the setup round for each player. for (int i = 0; i < players.length; i++){ if (players[i].getPlaying() == true){ players[i].startRound(deck, window); } } //run through the round for each player. for (int i = 0; i < players.length; i++){ if (players[i].getPlaying() == true){ players[i].playRound(deck, window); } } //Get the dealer's score for the finishRound method. int dealerScore = 0; for (int i = 0; i < players.length; i++){ if (players[i].getPlaying() == true){ if (players[i].dealer == true){ dealerScore = players[i].getHand().getScore(); } } } //Cash everyone out according to dealer score. for (int i = 0; i < players.length; i++){ if (players[i].getPlaying() == true){ players[i].finishRound(dealerScore, window); Cashout(players[i].gethandWin(), players[i].getsplitWin(), players); } } //Ask everyone if they still want to play. //for loop is already implemented into these methods. Another loop not required. checkPlaying(players); repeat = stillInGame(players); //Special Case: If the dealer runs out of money before all players. All active players win. if (players[players.length-1].getMoney() <= 0) { GIO.displayMessage("You guys beat the dealer! Congratulations to the following players: "); //Loop to run through the names of players still in the game. for (int i = 0; i < players.length-1; i++){ if (players[i].getPlaying() == true){ GIO.displayMessage(players[i].getName()); } } GIO.displayMessage("Here are each of your current amounts of cash:"); //Loop to display each player's amount of money won/left. for (int i = 0; i < players.length-1; i++){ if (players[i].getPlaying() == true){ GIO.displayMessage(players[i].getName() + "'s Money: " + players[i].getMoney()); } } //Time to close the program since the casino ran out of money. GG. :D System.exit(0); } } //Now, if there is one player remaining, announce their name and their value. Congrats! if (repeat == false){ GIO.displayMessage("Congratulations " + players[1].getName() + ", you won!"); GIO.displayMessage("Total Cash Remaining: " + players[1].getMoney()); GIO.displayMessage("THANKS FOR PLAYING BLACKJACK!"); return; } } /* The methods were created to simplify the code inside main (String[] args). * Any methods regarding rounds are found here. */ //Create a method that will calculate the bank amount after all bets have been taken. public static void Cashout(int handWin, int splitWin, Player[] players){ double totalMoney = 0; for (int i = 0; i < players.length; i++){ if (players[i].gethandWin() == 1){ totalMoney -= players[i].getWager(); } if (players[i].gethandWin() == 0){ totalMoney += players[i].getWager(); } if (players[i].getsplitWin() == 1){ totalMoney -= players[i].getSplitWager(); } if (players[i].getsplitWin() == 0){ totalMoney += players[i].getSplitWager(); } } } //Create a method that will remove a player if they don't want to play. public static void checkPlaying(Player[] players){ //Ask all the players if they're playing or not. for (int i = 0; i < players.length-1; i++){ if (players[i].getMoney() > 0){ players[i].setPlaying(GIO.readBoolean(players[i].getName() + ", would you like to play again?")); } else { GIO.displayMessage(players[i].getName() + ",you ran out of money! You are disqualified."); players[i].setPlaying(false); } } } //This method checks if there is only 1 player left in the game. public static boolean stillInGame(Player[] players) { boolean stillPlaying = false; int playersLeft = 0; //Check if there's only one person left in the game. If there is, return false to stop BlackJack game. for (int i = 0; i < players.length; i++) { if (players[i].getPlaying() == true){ playersLeft++; } } if (playersLeft == 1){ stillPlaying = false; } else { for (int i = 0; i < players.length; i++) { if (players[i].getPlaying() == true){ stillPlaying = true; } } } return stillPlaying; } }
package com.programapprentice.app; import java.util.HashMap; import java.util.Map; /** * User: program-apprentice * Date: 10/4/15 * Time: 11:37 AM */ class TrieNode { public Integer value; public String key; public Map<String, TrieNode> childrenMap; // Initialize your data structure here. public TrieNode() { this(null); } public TrieNode(String key) { this.key = key; this.value = null; this.childrenMap = new HashMap<String, TrieNode>(); } } public class Trie { private TrieNode root; private int nextValue; public Trie() { root = new TrieNode(); this.nextValue = 1; } // Inserts a word into the trie. public void insert(String word) { TrieNode node = this.root; for(int i =0; i < word.length(); i++) { String cur = word.substring(i, i+1); TrieNode child = node.childrenMap.get(cur); if(child == null) { if(i == word.length()-1) { child = new TrieNode(word); child.value = this.nextValue; this.nextValue++; } else { child = new TrieNode(cur); } node.childrenMap.put(cur, child); } else { if(i == word.length()-1) { if(child.value == null) { child.value = this.nextValue; this.nextValue++; } } else { if(child.value != null) { child.key = cur; } } } node = child; } } // Returns if the word is in the trie. public boolean search(String word) { TrieNode node = this.root; for(int i = 0; i < word.length(); i++) { String cur = word.substring(i, i+1); TrieNode child = node.childrenMap.get(cur); if(child == null) { return false; } if(i == word.length()-1) { if(child.value == null) { return false; } break; } node = child; } return true; } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { TrieNode node = this.root; for(int i = 0; i < prefix.length(); i++) { String cur = prefix.substring(i, i+1); TrieNode child = node.childrenMap.get(cur); if(child == null) { return false; } node = child; } return true; } } // Your Trie object will be instantiated and called as such: // Trie trie = new Trie(); // trie.insert("somestring"); // trie.search("key");
package BinaryTree; /*Objective is to find half nodes in Binary Tree Full nodes are the nodes where node has 2 children Current tree: * 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 Solution Half Nodes :5 7 Total number of half nodes : 2 */ import java.util.LinkedList; import java.util.Queue; class Node { int data; Node left, right; Node(int key) { data = key; left = right = null; } } public class BinaryTreeHalfNodesWithCount { Node root; int count; BinaryTreeHalfNodesWithCount() { root = null; } BinaryTreeHalfNodesWithCount(int data) { root = new Node(data); } public void halfNodesAndCount() { System.out.print("Half Nodes :"); halfNodesAndCount(root); } public void halfNodesAndCount(Node root) { if(root==null) return; else { count = 0; Node temp; Queue<Node> queue = new LinkedList<Node>(); queue.add(root); while(!queue.isEmpty()) { temp = queue.poll(); if(((temp.left!=null) && (temp.right==null)) || ((temp.left==null) && (temp.right!=null)) ) { count++; System.out.print(temp.data+" "); } if(temp.left!=null) queue.add(temp.left); if(temp.right!=null) queue.add(temp.right); } System.out.println(); System.out.println("Total number of half nodes : "+ count); } } public static void main(String[] args) { BinaryTreeHalfNodesWithCount binaryTreeHalfNodesWithCount = new BinaryTreeHalfNodesWithCount(); binaryTreeHalfNodesWithCount.root = new Node(1); binaryTreeHalfNodesWithCount.root.left = new Node(2); binaryTreeHalfNodesWithCount.root.right = new Node(3); binaryTreeHalfNodesWithCount.root.left.left = new Node(4); binaryTreeHalfNodesWithCount.root.left.right = new Node(5); binaryTreeHalfNodesWithCount.root.right.left = new Node(6); binaryTreeHalfNodesWithCount.root.right.right = new Node(7); binaryTreeHalfNodesWithCount.root.left.right.left = new Node(8); binaryTreeHalfNodesWithCount.root.right.right.right = new Node(9); binaryTreeHalfNodesWithCount.halfNodesAndCount(); } }
import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Stream; /** * Decoder class to decode the huffman encoded file. * * Created by shivanggupta on 29/03/17. */ public class decoder { private MinHeapNode decodeTreeRoot = null; private FileInputStream inputStream = null; private static BufferedWriter bufferedWriter; private static boolean isPrintEnabled = false; void buildDecodeTree(String codeFileName) { try (Stream<String> stream = Files.lines(Paths.get(codeFileName))) { stream.forEach(line -> { String data = line.split(" ")[0]; String code = line.split(" ")[1]; decodeTreeRoot = insertInDecodeTree(decodeTreeRoot, code, 0, data); }); } catch (IOException e) { e.printStackTrace(); } } MinHeapNode insertInDecodeTree(MinHeapNode node, String code, int i, String data){ if(node == null) { node = new MinHeapNode(data,0); if(i == code.length()){ node.data = data; return node; } } if(code.charAt(i) == '0'){ node.left = insertInDecodeTree(node.left, code, i + 1, data); } else { node.right = insertInDecodeTree(node.right, code, i + 1, data); } return node; } void decodeFile(String encodedFile) throws IOException{ inputStream = new FileInputStream(encodedFile); MinHeapNode currentNode = decodeTreeRoot; int b = getByte(); // Reads a byte from the encoded file while (b != -1) { for(int i = 0 ; i < 8 ; i++) { int bit = b & getMask(i); if(bit != 0){ currentNode = currentNode.right; } else { currentNode = currentNode.left; } if(currentNode.isLeaf()) { writeToFile(currentNode.data); currentNode = decodeTreeRoot; } } b = getByte(); // Reads a byte from the encoded file } } int getMask(int i) { return (1 << (7 - i)); } int getByte() throws IOException { int b; if((b = inputStream.read()) != -1) { return b; } return -1; } void writeToFile(String data) { try { bufferedWriter.write(data); bufferedWriter.newLine(); } catch (IOException e) { e.printStackTrace(); } } static void printLog(String str) { if(isPrintEnabled) System.out.println(str); } public static void main(String[] args) throws IOException { Long start = System.currentTimeMillis(); String encodedFile = args[0]; String codeTableFile = args[1]; decoder d = new decoder(); FileWriter fw = new FileWriter("decoded.txt"); bufferedWriter = new BufferedWriter(fw); d.buildDecodeTree(codeTableFile); d.decodeFile(encodedFile); bufferedWriter.close(); printLog("Time to decode(milliseconds) = " + String.valueOf(System.currentTimeMillis() - start)); } }
package org.rita.harris.embeddedsystemhomework_termproject.AddNewItem; import android.Manifest; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.provider.Settings; import android.support.v7.app.AppCompatActivity; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.text.TextUtils; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.parse.ParseObject; import org.rita.harris.embeddedsystemhomework_termproject.MainActivity; import org.rita.harris.embeddedsystemhomework_termproject.R; import org.rita.harris.embeddedsystemhomework_termproject.StarterApplication; public class Add_Asylum_PointActivity extends AppCompatActivity implements LocationListener{ private UserLoginTask mAuthTask = null; // UI references. private EditText mTrueNameView; private EditText mCellPhoneView; private EditText mPlaceView; private EditText mDescriptionView; private RadioButton mAsylum_Point; private static StarterApplication mUser_BasicData; private View mProgressView; private View mLoginFormView; /*GPS*/ private TextView LongitudeLatitude_txt; private String longitude_txt,latitude_txt; private boolean getService = false; //是否已開啟定位服務 private LocationManager lms; private String bestProvider = LocationManager.GPS_PROVIDER; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_asylum_point); // Set up the login form. mTrueNameView = (EditText) findViewById(R.id.TrueName); mCellPhoneView = (EditText) findViewById(R.id.CellPhone); mPlaceView = (EditText) findViewById(R.id.Place); mDescriptionView = (EditText) findViewById(R.id.Description); mAsylum_Point = (RadioButton) findViewById(R.id.Asylum_Point); mUser_BasicData = (StarterApplication) MainActivity.MainActivity_Context().getApplicationContext(); Button mEmailSignInButton = (Button) findViewById(R.id.Add); mEmailSignInButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { attemptLogin(); } }); mLoginFormView = findViewById(R.id.login_form); mProgressView = findViewById(R.id.login_progress); LongitudeLatitude_txt = (TextView) findViewById(R.id.GpsLocation); //取得系統定位服務 LocationManager status = (LocationManager) (this.getSystemService(Context.LOCATION_SERVICE)); if (status.isProviderEnabled(LocationManager.GPS_PROVIDER) || status.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { //如果GPS或網路定位開啟,呼叫locationServiceInitial()更新位置 locationServiceInitial(); } else { Toast.makeText(this, "請開啟定位服務", Toast.LENGTH_LONG).show(); getService = true; //確認開啟定位服務 startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); //開啟設定頁面 } } private void attemptLogin() { if (mAuthTask != null) { return; } // Reset errors. mTrueNameView.setError(null); mCellPhoneView.setError(null); mPlaceView.setError(null); mDescriptionView.setError(null); // Store values at the time of the login attempt. String TrueName = mTrueNameView.getText().toString(); String CellPhone = mCellPhoneView.getText().toString(); String Place = mPlaceView.getText().toString(); String Description = mDescriptionView.getText().toString(); String Type = null; boolean cancel = false; View focusView = null; // Check for a valid password, if the user entered one. if (TextUtils.isEmpty(TrueName)) { mTrueNameView.setError(getString(R.string.error_field_required)); focusView = mTrueNameView; cancel = true; } if (TextUtils.isEmpty(CellPhone)) { mCellPhoneView.setError(getString(R.string.error_field_required)); focusView = mCellPhoneView; cancel = true; } if (TextUtils.isEmpty(Place)) { mPlaceView.setError(getString(R.string.error_field_required)); focusView = mPlaceView; cancel = true; } if (TextUtils.isEmpty(Description)) { mDescriptionView.setError(getString(R.string.error_field_required)); focusView = mDescriptionView; cancel = true; } if (cancel) { focusView.requestFocus(); } else { showProgress(true); if (mAsylum_Point.isChecked()) Type = "庇護點"; else Type = "緊急事件"; mAuthTask = new UserLoginTask(TrueName, CellPhone, Place, Description, Type,longitude_txt ,latitude_txt); mAuthTask.execute((Void) null); } } @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) private void showProgress(final boolean show) { // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow // for very easy animations. If available, use these APIs to fade-in // the progress spinner. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); mLoginFormView.animate().setDuration(shortAnimTime).alpha( show ? 0 : 1).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); } }); mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mProgressView.animate().setDuration(shortAnimTime).alpha( show ? 1 : 0).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); } }); } else { // The ViewPropertyAnimator APIs are not available, so simply show // and hide the relevant UI components. mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); } } public class UserLoginTask extends AsyncTask<Void, Void, Boolean> { private final String mTrueName; private final String mCellPhone; private final String mPlace; private final String mDescription; private final String mType; private final String mlongitude_txt; private final String mlatitude_txt; //TODO : private final String mLatitude; //private final String mLongitude; UserLoginTask(String TrueName, String CellPhone,String Place, String Description,String Type , String longitude_txt , String latitude_txt) { mTrueName = TrueName; mCellPhone = CellPhone; mPlace = Place; mDescription = Description; mType = Type; mlongitude_txt = longitude_txt; mlatitude_txt = latitude_txt; } @Override protected Boolean doInBackground(Void... params) { ParseObject SaveObject = new ParseObject("Location"); SaveObject.put("Type", mType); SaveObject.put("TrueName", mTrueName); SaveObject.put("Contact", mCellPhone); SaveObject.put("Place", mPlace); SaveObject.put("Description", mDescription); SaveObject.put("Latitude", mlatitude_txt); SaveObject.put("Longitude", mlongitude_txt); SaveObject.put("UserName", mUser_BasicData.mUser_BasicData.getAccount()); SaveObject.saveInBackground(); try { // Simulate network access. Thread.sleep(3000); } catch (InterruptedException e) { return false; } return true; } @Override protected void onPostExecute(final Boolean success) { mAuthTask = null; Toast.makeText(MainActivity.MainActivity_Context(), "Add Successfully! ", Toast.LENGTH_LONG).show(); showProgress(false); finish(); } @Override protected void onCancelled() { mAuthTask = null; showProgress(false); } } private void locationServiceInitial() { lms = (LocationManager) getSystemService(LOCATION_SERVICE); //取得系統定位服務 /*做法一,由程式判斷用GPS_provider if (lms.isProviderEnabled(LocationManager.GPS_PROVIDER) ) { location = lms.getLastKnownLocation(LocationManager.GPS_PROVIDER); //使用GPS定位座標 } else if ( lms.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { location = lms.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); //使用GPS定位座標 } else {}*/ // 做法二,由Criteria物件判斷提供最準確的資訊 Criteria criteria = new Criteria(); //資訊提供者選取標準 bestProvider = lms.getBestProvider(criteria, true); //選擇精準度最高的提供者 Location location = lms.getLastKnownLocation(bestProvider); getLocation(location); } private void getLocation(Location location) { //將定位資訊顯示在畫面中 if (location != null) { Double longitude = location.getLongitude(); //取得經度 Double latitude = location.getLatitude(); //取得緯度 longitude_txt = String.valueOf(longitude); latitude_txt = String.valueOf(latitude); LongitudeLatitude_txt.setText("Your Gps Location : ( " +longitude_txt+" , "+latitude_txt+" )"); } else { longitude_txt = "121"; latitude_txt = "24"; Toast.makeText(this, "無法定位座標", Toast.LENGTH_LONG).show(); } } @Override public void onLocationChanged(Location location) { //當地點改變時 // TODO 自動產生的方法 Stub getLocation(location); } @Override public void onProviderDisabled(String arg0) {//當GPS或網路定位功能關閉時 // TODO 自動產生的方法 Stub Toast.makeText(this, "請開啟gps或3G網路", Toast.LENGTH_LONG).show(); } @Override public void onProviderEnabled(String arg0) { //當GPS或網路定位功能開啟 // TODO 自動產生的方法 Stub } @Override public void onStatusChanged(String arg0, int arg1, Bundle arg2) { //定位狀態改變 // TODO 自動產生的方法 Stub } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); if (getService) { lms.requestLocationUpdates(bestProvider, 1000, 1, this); //服務提供者、更新頻率60000毫秒=1分鐘、最短距離、地點改變時呼叫物件 } } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); if (getService) { if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // public void requestPermissions(@NonNull String[] permissions, int requestCode) // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for Activity#requestPermissions for more details. return; } lms.removeUpdates(this); //離開頁面時停止更新 } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
package com.mao.springdata.springjpaquery.service; import com.mao.springdata.springjpaquery.bean.Clazz; import com.mao.springdata.springjpaquery.bean.Student; import com.mao.springdata.springjpaquery.repository.ClazzRepository; import com.mao.springdata.springjpaquery.repository.StudentRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Resource; import javax.transaction.Transactional; import java.rmi.MarshalledObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Service public class SchoolService { @Autowired private StudentRepository studentRepository; @Autowired private ClazzRepository clazzRepository; @Transactional public void saveClazzAll(List<Clazz> clazzs){ clazzRepository.saveAll(clazzs); } @Transactional public void saveStudentAll(List<Student> studens){ studentRepository.saveAll(studens); } public List<Map<String,Object>> getStusByClazzName(String clazzName){ List<Student> students=studentRepository.findByClazz_name(clazzName); List<Map<String,Object>> res=new ArrayList<>(); for (Student student:students){ Map<String,Object> stu=new HashMap<>(); stu.put("name",student.getName()); stu.put("age",student.getAge()); stu.put("sex",student.getSex()); res.add(stu); } return res; } public List<Map<String,Object>> findNameAndSexByClazzName(String clazzName){ return studentRepository.findNameAndSexClazzName(clazzName); } public List<String> findNameByClazzNameAndSex(String clazzName,char sex){ return studentRepository.findNameByClazzNameAndSex(clazzName,sex); } public String findClazzNameByStuName(String stuName){ return studentRepository.findClazzNameByStuName(stuName); } @Transactional public int deleteStuByName(String stuName){ return studentRepository.deleteStuByStuName(stuName); } }
package com.seven.jdbc.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import com.seven.jdbc.ConnectionManager; import com.seven.jdbc.SqlStatements; public class TourDAO extends DataAccessObject<Tour> { public TourDAO(Connection connection) { super(connection); } @Override public Tour findById(long id) { return null; } @Override public List<Tour> findAll() { return null; } @Override public Tour update(Tour dto) { return null; } @Override public Tour create(Tour dto) { String sql = SqlStatements.getInsertTourSql(); try(PreparedStatement stmt = connection.prepareStatement(sql);) { stmt.setInt(1, dto.getPackageId()); stmt.setString(2, dto.getTourName()); stmt.setString(3, dto.getBlurb()); stmt.setString(4, dto.getDescription()); stmt.setDouble(5, dto.getPrice()); stmt.setString(6, dto.getDifficulty()); stmt.setString(7, dto.getGraphic()); stmt.setInt(8, dto.getLength()); stmt.setString(9, dto.getRegion()); stmt.setString(10, dto.getKeywords()); stmt.execute(); return null; } catch (SQLException e) { ConnectionManager.processException(e); throw new RuntimeException(e); } } @Override public void delete(Tour dto) { } }
package com.jixin; public class MakeBus extends MakeCar { public void makeHead() { System.out.println("bus: 组装车头"); } public void makeBody() { System.out.println("bus: 组装车身"); } public void makeTail() { System.out.println("bus :组装车尾"); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.core.annotation; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Tests for {@link AttributeMethods}. * * @author Phillip Webb */ class AttributeMethodsTests { @Test void forAnnotationTypeWhenNullReturnsNone() { AttributeMethods methods = AttributeMethods.forAnnotationType(null); assertThat(methods).isSameAs(AttributeMethods.NONE); } @Test void forAnnotationTypeWhenHasNoAttributesReturnsNone() { AttributeMethods methods = AttributeMethods.forAnnotationType(NoAttributes.class); assertThat(methods).isSameAs(AttributeMethods.NONE); } @Test void forAnnotationTypeWhenHasMultipleAttributesReturnsAttributes() { AttributeMethods methods = AttributeMethods.forAnnotationType(MultipleAttributes.class); assertThat(methods.get("value").getName()).isEqualTo("value"); assertThat(methods.get("intValue").getName()).isEqualTo("intValue"); assertThat(getAll(methods)).flatExtracting(Method::getName).containsExactly("intValue", "value"); } @Test void indexOfNameReturnsIndex() { AttributeMethods methods = AttributeMethods.forAnnotationType(MultipleAttributes.class); assertThat(methods.indexOf("value")).isEqualTo(1); } @Test void indexOfMethodReturnsIndex() throws Exception { AttributeMethods methods = AttributeMethods.forAnnotationType(MultipleAttributes.class); Method method = MultipleAttributes.class.getDeclaredMethod("value"); assertThat(methods.indexOf(method)).isEqualTo(1); } @Test void sizeReturnsSize() { AttributeMethods methods = AttributeMethods.forAnnotationType(MultipleAttributes.class); assertThat(methods.size()).isEqualTo(2); } @Test void canThrowTypeNotPresentExceptionWhenHasClassAttributeReturnsTrue() { AttributeMethods methods = AttributeMethods.forAnnotationType(ClassValue.class); assertThat(methods.canThrowTypeNotPresentException(0)).isTrue(); } @Test void canThrowTypeNotPresentExceptionWhenHasClassArrayAttributeReturnsTrue() { AttributeMethods methods = AttributeMethods.forAnnotationType(ClassArrayValue.class); assertThat(methods.canThrowTypeNotPresentException(0)).isTrue(); } @Test void canThrowTypeNotPresentExceptionWhenNotClassOrClassArrayAttributeReturnsFalse() { AttributeMethods methods = AttributeMethods.forAnnotationType(ValueOnly.class); assertThat(methods.canThrowTypeNotPresentException(0)).isFalse(); } @Test void hasDefaultValueMethodWhenHasDefaultValueMethodReturnsTrue() { AttributeMethods methods = AttributeMethods.forAnnotationType(DefaultValueAttribute.class); assertThat(methods.hasDefaultValueMethod()).isTrue(); } @Test void hasDefaultValueMethodWhenHasNoDefaultValueMethodsReturnsFalse() { AttributeMethods methods = AttributeMethods.forAnnotationType(MultipleAttributes.class); assertThat(methods.hasDefaultValueMethod()).isFalse(); } @Test void isValidWhenHasTypeNotPresentExceptionReturnsFalse() { ClassValue annotation = mockAnnotation(ClassValue.class); given(annotation.value()).willThrow(TypeNotPresentException.class); AttributeMethods attributes = AttributeMethods.forAnnotationType(annotation.annotationType()); assertThat(attributes.isValid(annotation)).isFalse(); } @Test @SuppressWarnings({ "unchecked", "rawtypes" }) void isValidWhenDoesNotHaveTypeNotPresentExceptionReturnsTrue() { ClassValue annotation = mock(); given(annotation.value()).willReturn((Class) InputStream.class); AttributeMethods attributes = AttributeMethods.forAnnotationType(annotation.annotationType()); assertThat(attributes.isValid(annotation)).isTrue(); } @Test void validateWhenHasTypeNotPresentExceptionThrowsException() { ClassValue annotation = mockAnnotation(ClassValue.class); given(annotation.value()).willThrow(TypeNotPresentException.class); AttributeMethods attributes = AttributeMethods.forAnnotationType(annotation.annotationType()); assertThatIllegalStateException().isThrownBy(() -> attributes.validate(annotation)); } @Test @SuppressWarnings({ "unchecked", "rawtypes" }) void validateWhenDoesNotHaveTypeNotPresentExceptionThrowsNothing() { ClassValue annotation = mockAnnotation(ClassValue.class); given(annotation.value()).willReturn((Class) InputStream.class); AttributeMethods attributes = AttributeMethods.forAnnotationType(annotation.annotationType()); attributes.validate(annotation); } private List<Method> getAll(AttributeMethods attributes) { List<Method> result = new ArrayList<>(attributes.size()); for (int i = 0; i < attributes.size(); i++) { result.add(attributes.get(i)); } return result; } @SuppressWarnings({ "unchecked", "rawtypes" }) private <A extends Annotation> A mockAnnotation(Class<A> annotationType) { A annotation = mock(annotationType); given(annotation.annotationType()).willReturn((Class) annotationType); return annotation; } @Retention(RetentionPolicy.RUNTIME) @interface NoAttributes { } @Retention(RetentionPolicy.RUNTIME) @interface MultipleAttributes { int intValue(); String value(); } @Retention(RetentionPolicy.RUNTIME) @interface ValueOnly { String value(); } @Retention(RetentionPolicy.RUNTIME) @interface NonValueOnly { String test(); } @Retention(RetentionPolicy.RUNTIME) @interface ClassValue { Class<?> value(); } @Retention(RetentionPolicy.RUNTIME) @interface ClassArrayValue { Class<?>[] value(); } @Retention(RetentionPolicy.RUNTIME) @interface DefaultValueAttribute { String one(); String two(); String three() default "3"; } }
package com.ifeng.recom.mixrecall.common.service; import com.ifeng.recom.mixrecall.common.tool.ServiceLogUtil; import com.ifeng.recom.mixrecall.common.util.GsonUtil; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.NameValuePair; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.config.SocketConfig; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.elasticsearch.common.collect.Tuple; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; /** * 远端的集中过滤 * Created by geyl on 2017/10/30. */ public class BloomFilterClient { public enum Status { OK, ERROR } private static final Logger logger = LoggerFactory.getLogger(BloomFilterClient.class); private static final String URL = "http://local.recom.bloom.collector1.ifengidc.com/filter/check"; private static final String STATUS_OK = "ok"; private static PoolingHttpClientConnectionManager poolConnManager; private static CloseableHttpClient httpClient = null; private static RequestConfig config = null; static { poolConnManager = new PoolingHttpClientConnectionManager(); poolConnManager.setMaxTotal(600); poolConnManager.setDefaultMaxPerRoute(50); poolConnManager.closeIdleConnections(60, TimeUnit.SECONDS); SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(2000) // 开启监视TCP连接是否有效 // .setSoKeepAlive(true) // .setRcvBufSize(8192) // .setSndBufSize(8192) .build(); poolConnManager.setDefaultSocketConfig(socketConfig); config = RequestConfig.custom() .setConnectionRequestTimeout(100) .setConnectTimeout(100) .setSocketTimeout(100) .build(); httpClient = HttpClients.custom() .setConnectionManager(BloomFilterClient.poolConnManager) .setDefaultRequestConfig(config) .setConnectionManagerShared(true) .build(); } /** * 通过http获取bloom数据 * * @param uid * @param simIds * @return */ public static Tuple<Status, Set<String>> requestBloomFilter(String uid, Collection<String> simIds) { if (CollectionUtils.isEmpty(simIds)) { return Tuple.tuple(Status.OK, Collections.EMPTY_SET); } String url = URL + "?uid=" + uid; String simId = String.join(",", simIds); HttpPost post = new HttpPost(url); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("uid", uid)); nvps.add(new BasicNameValuePair("simids", simId)); try { post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); } catch (Exception e) { logger.error("request error, uid:{}, {}", uid, e); return Tuple.tuple(Status.ERROR, toSet(simIds)); } long start = System.currentTimeMillis(); try (CloseableHttpResponse response = httpClient.execute(post)) { String rt = EntityUtils.toString(response.getEntity()); long cost = System.currentTimeMillis() - start; if (cost > 50) { ServiceLogUtil.debug("bloom {} cost:{}, size:{}", uid, cost, simIds.size()); } if (StringUtils.isBlank(rt)) { return Tuple.tuple(Status.ERROR, toSet(simIds)); } BloomResult result = GsonUtil.json2Object(rt, BloomResult.class); if (STATUS_OK.equalsIgnoreCase(result.getStatus())) { List<String> filteredSimIds = result.getSimids(); if (filteredSimIds == null) { // 没有数据算作失败 return Tuple.tuple(Status.ERROR, Collections.EMPTY_SET); } return Tuple.tuple(Status.OK, new HashSet<>(filteredSimIds)); } } catch (Exception e) { ServiceLogUtil.debug("bloome {} cost:{}, size:{}", uid, System.currentTimeMillis() - start, simIds.size()); logger.error("request bloom error, uid:{}, e:{}", uid, e.toString()); return Tuple.tuple(Status.ERROR, toSet(simIds)); } return Tuple.tuple(Status.ERROR, toSet(simIds)); } private static Set<String> toSet(Collection<String> simIds) { return simIds instanceof Set ? (Set<String>) simIds : new HashSet<>(simIds); } }
package cartas; import efectos.EfectoFisura; public class Fisura extends CartaMagica { public Fisura() { super(); this.efecto = new EfectoFisura(this); this.nombre = "Fisura"; this.colocarImagenEnCartaDesdeArchivoDeRuta("resources/images/carta_Fisura.png"); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.tfar.dao; import com.tfar.entity.Androgene; import java.util.List; /** * * @author hatem */ public interface AndrogeneDao { public List <Androgene> getAllAndrogene(); public void add(Androgene newAndrogene); public void update(Androgene androgene); public List <Androgene> getListAndrogeneParnDossier(String nDossier); public void delete(Androgene androgene); }
package br.com.herculano.urlshortener.api.respository.jpa_respository; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import br.com.herculano.urlshortener.api.entity.EncurtadoURL; import br.com.herculano.urlshortener.api.respository.custom.EncurtadorURLRepositoryCustom; public interface EncurtadorURLRepository extends JpaRepository<EncurtadoURL, Integer>, EncurtadorURLRepositoryCustom { @Query(value = "SELECT count(*) FROM tb_url url", nativeQuery = true) public Long maxCount(); public Optional<EncurtadoURL> findByCode(String code); }
package fr.skytasul.quests.gui.mobs; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.UUID; import java.util.function.Consumer; import java.util.function.Function; import org.bukkit.DyeColor; import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemStack; import fr.skytasul.quests.api.mobs.LeveledMobFactory; import fr.skytasul.quests.api.mobs.Mob; import fr.skytasul.quests.editors.TextEditor; import fr.skytasul.quests.editors.checkers.NumberParser; import fr.skytasul.quests.gui.ItemUtils; import fr.skytasul.quests.gui.templates.ListGUI; import fr.skytasul.quests.utils.Lang; import fr.skytasul.quests.utils.Utils; import fr.skytasul.quests.utils.types.CountableObject; import fr.skytasul.quests.utils.types.CountableObject.MutableCountableObject; public class MobsListGUI extends ListGUI<MutableCountableObject<Mob<?>>> { private Consumer<List<MutableCountableObject<Mob<?>>>> end; public MobsListGUI(Collection<MutableCountableObject<Mob<?>>> objects, Consumer<List<MutableCountableObject<Mob<?>>>> end) { super(Lang.INVENTORY_MOBS.toString(), DyeColor.ORANGE, objects); this.end = end; } @Override public void finish(List<MutableCountableObject<Mob<?>>> objects) { end.accept(objects); } @Override public void clickObject(MutableCountableObject<Mob<?>> mob, ItemStack item, ClickType click) { super.clickObject(mob, item, click); if (click == ClickType.SHIFT_LEFT) { Lang.MOB_NAME.send(p); new TextEditor<>(p, super::reopen, name -> { mob.getObject().setCustomName((String) name); setItems(); reopen(); }).passNullIntoEndConsumer().enter(); } else if (click == ClickType.LEFT) { Lang.MOB_AMOUNT.send(p); new TextEditor<>(p, super::reopen, amount -> { mob.setAmount(amount); setItems(); reopen(); }, NumberParser.INTEGER_PARSER_STRICT_POSITIVE).enter(); } else if (click == ClickType.SHIFT_RIGHT) { if (mob.getObject().getFactory() instanceof LeveledMobFactory) { new TextEditor<>(p, super::reopen, level -> { mob.getObject().setMinLevel(level); setItems(); reopen(); }, new NumberParser<>(Double.class, true, false)).enter(); } else { Utils.playPluginSound(p.getLocation(), "ENTITY_VILLAGER_NO", 0.6f); } } else if (click == ClickType.RIGHT) { remove(mob); } } @Override public void createObject(Function<MutableCountableObject<Mob<?>>, ItemStack> callback) { new MobSelectionGUI(mob -> { if (mob == null) reopen(); else callback.apply(CountableObject.createMutable(UUID.randomUUID(), mob, 1)); }).create(p); } @Override public ItemStack getObjectItemStack(MutableCountableObject<Mob<?>> mob) { List<String> lore = new ArrayList<>(); lore.add(Lang.Amount.format(mob.getAmount())); lore.addAll(mob.getObject().getDescriptiveLore()); lore.add(""); lore.add(Lang.click.toString()); if (mob.getObject().getFactory() instanceof LeveledMobFactory) { lore.add("§7" + Lang.ClickShiftRight + " > §e" + Lang.setLevel); } else { lore.add("§8§n" + Lang.ClickShiftRight + " > " + Lang.setLevel); } ItemStack item = ItemUtils.item(mob.getObject().getMobItem(), mob.getObject().getName(), lore); item.setAmount(Math.min(mob.getAmount(), 64)); return item; } }
package com.daexsys.automata.world; public class AccessOutOfWorldException extends Exception { }
package cn.hellohao.pojo; public class EmailConfig { private Integer id ; private String emails; private String emailkey; private String emailurl; private String port; private String emailname; private Integer using ; public EmailConfig() { } public EmailConfig(Integer id, String emails, String emailkey, String emailurl, String port, String emailname, Integer using) { this.id = id; this.emails = emails; this.emailkey = emailkey; this.emailurl = emailurl; this.port = port; this.emailname = emailname; this.using = using; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getEmails() { return emails; } public void setEmails(String emails) { this.emails = emails; } public String getEmailkey() { return emailkey; } public void setEmailkey(String emailkey) { this.emailkey = emailkey; } public String getEmailurl() { return emailurl; } public void setEmailurl(String emailurl) { this.emailurl = emailurl; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public String getEmailname() { return emailname; } public void setEmailname(String emailname) { this.emailname = emailname; } public Integer getUsing() { return using; } public void setUsing(Integer using) { this.using = using; } }
package resources.todo; import java.util.List; import java.util.Observable; import javax.ejb.ConcurrencyManagement; import javax.ejb.ConcurrencyManagementType; import javax.ejb.Lock; import javax.ejb.LockType; import javax.ejb.Singleton; import javax.interceptor.AroundInvoke; import javax.interceptor.InvocationContext; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.criteria.CriteriaQuery; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rest.WebApplicationPreconditions; @Singleton @ConcurrencyManagement(ConcurrencyManagementType.CONTAINER) public class TodoItemDAO extends Observable { @PersistenceContext(unitName = "TodoApp") protected EntityManager em; protected Logger log = LoggerFactory.getLogger(this.getClass()); @AroundInvoke protected Object handleAroundInvoke(InvocationContext ctx) throws Exception { Object result = ctx.proceed(); if (ctx.getMethod().isAnnotationPresent(Lock.class) && ctx.getMethod().getAnnotation(Lock.class).value().equals(LockType.WRITE)) { log.debug("notify observers"); em.flush(); this.setChanged(); this.notifyObservers(this.list()); } return result; } /* * (non-Javadoc) * * @see resources.todo.ITodoItemDAO#add(resources.todo.TodoItem) */ @Lock(LockType.WRITE) public TodoItem add(TodoItem item) { WebApplicationPreconditions.checkNotNull(item, "001", "TodoItem is not allowed to be null."); WebApplicationPreconditions.checkArgument(item.getId() == null, "002", "Id is not allowed to be set."); em.persist(item); return item; } /* * (non-Javadoc) * * @see resources.todo.ITodoItemDAO#list() */ @Lock(LockType.READ) public List<TodoItem> list() { CriteriaQuery<TodoItem> criteria = em.getCriteriaBuilder().createQuery(TodoItem.class); criteria.select(criteria.from(TodoItem.class)); return em.createQuery(criteria).getResultList(); } /* * (non-Javadoc) * * @see resources.todo.ITodoItemDAO#get(java.lang.Long) */ @Lock(LockType.READ) public TodoItem get(Long id) { TodoItem item = em.find(TodoItem.class, id); WebApplicationPreconditions.checkNotNull(item, "003", "No Item found with id `" + id + "`"); return item; } /* * (non-Javadoc) * * @see resources.todo.ITodoItemDAO#update(java.lang.Long, * resources.todo.TodoItem) */ @Lock(LockType.WRITE) public TodoItem update(Long id, TodoItem updatedItem) { TodoItem item = get(id); item.setDone(updatedItem.isDone()); item.setDescription(updatedItem.getDescription()); return item; } /* * (non-Javadoc) * * @see resources.todo.ITodoItemDAO#remove(java.lang.Long) */ @Lock(LockType.WRITE) public void remove(Long id) { TodoItem item = get(id); em.remove(item); } }
package com.example.cropad; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.ListAdapter; import java.util.ArrayList; public class expertadvice extends AppCompatActivity { RecyclerView recyclerView; ArrayList<expertdata> expertdataList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_expertadvice); recyclerView = findViewById(R.id.expert_advice_recyclerview); expertdataList = new ArrayList<>(); expertdataList.add(new expertdata("T. Kuhu", "Coupling crop","https://www.sciencedirect.com/science/article/pii/S0308521X19303257")); expertdataList.add(new expertdata("Andrew P. Smith", "Farm implications","https://www.sciencedirect.com/science/article/pii/S0308521X18300222")); expertdataList.add(new expertdata("लोकसत्ता", "सेंद्रिय शेती","https://www.loksatta.com/lokshivar-news/marathi-articles-on-introduction-to-organic-farming-1507444/")); expertdataList.add(new expertdata("M.S Allahyari", "Precision Agriculture","https://www.sciencedirect.com/science/article/pii/S2214317316300397")); expertdataList.add(new expertdata("Economic Times", "Self Marketing","https://economictimes.indiatimes.com/news/economy/agriculture/agriculture-experts-call-on-farmers-to-focus-on-self-marketing/articleshow/58660917.cms")); expertdataList.add(new expertdata("Mr. Rajiv Ahuja", "Basic Agriculture","https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=15&ved=2ahUKEwidwuLc6OvnAhWoxzgGHZAnBSoQFjAOegQIBBAB&url=https%3A%2F%2Fwww.manage.gov.in%2Fpublications%2Ffarmerbook.pdf&usg=AOvVaw1ongbEpgeX_Q2KsXvBMe5y")); expertdataList.add(new expertdata("Mr. Devinder Sharma", "Farmer's Income","https://www.bhaskar.com/news/ABH-LCL-agricultural-expert-devinder-sharma-article-over-farmers-income-5797350-NOR.html")); expertdataList.add(new expertdata("A. Eitzinger", "GeoFarmer","https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=19&cad=rja&uact=8&ved=2ahUKEwidwuLc6OvnAhWoxzgGHZAnBSoQFjASegQIBhAB&url=https%3A%2F%2Fwww.ncbi.nlm.nih.gov%2Fpmc%2Farticles%2FPMC6472546%2F&usg=AOvVaw0_tD8CCbf16U5aFAcnTvtT")); expertdataList.add(new expertdata("S.J Dundon", "Agricultural Ethics","https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=15&cad=rja&uact=8&ved=2ahUKEwil4Nnt6evnAhXEyzgGHR2RCBw4ChAWMAR6BAgKEAE&url=https%3A%2F%2Fwww.ncbi.nlm.nih.gov%2Fpmc%2Farticles%2FPMC523869%2F&usg=AOvVaw3oJFJofim_3sNivn8C6-bD")); expertdataList.add(new expertdata("B A Wood", "Agricultural Science","https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=13&cad=rja&uact=8&ved=2ahUKEwil4Nnt6evnAhXEyzgGHR2RCBw4ChAWMAJ6BAgDEAE&url=https%3A%2F%2Fjournals.plos.org%2Fplosone%2Farticle%3Fid%3D10.1371%2Fjournal.pone.0105203&usg=AOvVaw21Ub9zs2uzGODa7sfzBHGG")); LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext()); RecyclerView.LayoutManager layoutManager1 = layoutManager; ExpertAdapter adapter = new ExpertAdapter(getApplicationContext(), expertdataList); recyclerView.setLayoutManager(layoutManager1); recyclerView.setAdapter(adapter); } }
package com.elo7.umatic; import java.net.URL; import org.junit.rules.MethodRule; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; import com.elo7.umatic.UnknownTracks.UnknownTrack; public class UMaticWebServer implements MethodRule { private final UMatic uMatic; public UMaticWebServer() { this.uMatic = new UMatic(); } public UMaticWebServer(int port) { this.uMatic = new UMatic(port); } public URL url(String path) { return uMatic.urlBy(path); } public void verify() throws UmaticException { UnknownTrack unknowTrack = uMatic.unknowTracks().last(); if (unknowTrack != null) { throw new UmaticException(unknowTrack.toString()); } } @Override public Statement apply(final Statement base, FrameworkMethod method, Object target) { uMatic.play(method.getAnnotation(Tape.class)); return new Statement() { @Override public void evaluate() throws Throwable { try { base.evaluate(); } finally { uMatic.stop(); } } }; } }
package com.aliam3.polyvilleactive; import com.aliam3.polyvilleactive.dsl.Interpreter; import com.aliam3.polyvilleactive.exception.LexicalException; import com.aliam3.polyvilleactive.exception.SemanticException; import com.aliam3.polyvilleactive.exception.SyntaxException; import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import static org.junit.jupiter.api.Assertions.*; public class GrammarDSLTest { File testFile; void loadResource(String name) { ClassLoader classLoader = getClass().getClassLoader(); testFile = new File(classLoader.getResource("dsl/"+name).getFile()); } @Test void temoinSectionGlobal() throws IOException { loadResource("ok_global.txt"); assertDoesNotThrow(() -> new Interpreter().read( testFile, true)); } @Test void erreurLexicale1SectionGlobal() throws IOException { loadResource("lex_error_global_1.txt"); assertThrows(LexicalException.class,() -> new Interpreter().read( testFile, true)); } @Test void erreurSyntaxique1SectionGlobal() throws IOException { loadResource("syntax_error_global_1.txt"); assertThrows(SyntaxException.class,() -> new Interpreter().read( testFile, true)); } @Test void erreurSyntaxiqueSectionGlobalNotClosed() throws IOException { loadResource("syntax_error_global_2.txt"); assertThrows(SyntaxException.class,() -> new Interpreter().read( testFile, true)); } @Test void erreurSemantiqueAvoidedAndPrioritizedSectionGlobal() throws IOException { loadResource("sem_error_global_1.txt"); assertThrows(SemanticException.class,() -> new Interpreter().read( testFile, true)); } @Test void erreurSemantiqueTwoTransportsOneRankSectionGlobal() throws IOException { loadResource("sem_error_global_2.txt"); assertThrows(SemanticException.class,() -> new Interpreter().read( testFile, true)); } @Test void erreurSemantiqueOneTransportTwoRanksSectionGlobal() throws IOException { loadResource("sem_error_global_3.txt"); assertThrows(SemanticException.class,() -> new Interpreter().read( testFile, true)); } @Test void erreurSemantiqueNegativePrioritySectionGlobal() throws IOException { loadResource("sem_error_global_4.txt"); assertThrows(SemanticException.class,() -> new Interpreter().read( testFile, true)); } @Test void erreurSyntaxiqueSectionLocalNotclosed() throws IOException { loadResource("syntax_error_local_1.txt"); assertThrows(SyntaxException.class,() -> new Interpreter().read( testFile, true)); } @Test void okSectionLocal() throws IOException { loadResource("ok_local.txt"); assertDoesNotThrow(() -> new Interpreter().read( testFile, true)); } @Test void erreurInterdictionGlobal() throws IOException { loadResource("lex_error_global_interdiction.txt"); assertThrows(LexicalException.class,() -> new Interpreter().read( testFile, true)); } @Test void okProgrammeComplexe() throws IOException { loadResource("ok_programmecomplexe.txt"); assertDoesNotThrow(() -> new Interpreter().read( testFile, true)); } @Test void erreurProgrammeComplexe() throws IOException { loadResource("sem_error_programmecomplexe.txt"); assertThrows(SemanticException.class,() -> new Interpreter().read( testFile, true)); } }
package com.innovattic.logeverywhere; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.widget.Toast; /** * Created by Jelle on 18-7-2015. */ public class Util { public static void showToast(final Context context, final String line) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Toast.makeText(context, line, Toast.LENGTH_SHORT).show(); } }); } }
package model; import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; public class Billetes { private Billete[] listaBilletes; private Billete[] listaBilletes_bkp; public Billetes() { listaBilletes = new Billete[5]; try (BufferedReader br = Files .newBufferedReader(Paths.get("data\\billetes.csv").toAbsolutePath())) { boolean ignoreFirstLine = true; String DELIMITER = ","; String line; int i = 0; while ((line = br.readLine()) != null) { if (ignoreFirstLine) { ignoreFirstLine = false; } else { String[] columns = line.split(DELIMITER); Billete nuevo = new Billete(Integer.parseInt(columns[0]), // ID columns[1], // Nominacion Integer.parseInt(columns[2]) // Cantidad ); listaBilletes[i] = nuevo; i++; } } } catch (IOException ex) { ex.printStackTrace(); } } public int getCantidad(String nominacion) { for (Billete b : listaBilletes) { if (b.getNominacion().equals(nominacion)) { return b.getCantidad(); } } return 0; } public boolean entregarBilletes(float cantidad_retirar) { float restante = cantidad_retirar; int cantidad50000 = (int) Math.floor(restante / 50000); restante -= 50000 * cantidad50000; int cantidad20000 = (int) Math.floor(restante / 20000); restante -= 20000 * cantidad20000; int cantidad10000 = (int) Math.floor(restante / 10000); restante -= 10000 * cantidad10000; int cantidad5000 = (int) Math.floor(restante / 5000); restante -= 5000 * cantidad5000; int cantidad2000 = (int) Math.floor(restante / 2000); restante -= 2000 * cantidad2000; if (restante > 0 || restante < 0) { System.out.println("No hay billetes suficientes para la transacción requerida."); return false; } else { listaBilletes_bkp = new Billete[5]; if (listaBilletes[0].getCantidad() - cantidad50000 >= 0) { listaBilletes_bkp[0] = listaBilletes[0]; listaBilletes[0].disminuirCantidad(cantidad50000); } else { return false; } if (listaBilletes[1].getCantidad() - cantidad20000 >= 0) { listaBilletes_bkp[1] = listaBilletes[1]; listaBilletes[1].disminuirCantidad(cantidad20000); } else { return false; } if (listaBilletes[2].getCantidad() - cantidad10000 >= 0) { listaBilletes_bkp[2] = listaBilletes[2]; listaBilletes[2].disminuirCantidad(cantidad10000); } else { return false; } if (listaBilletes[3].getCantidad() - cantidad5000 >= 0) { listaBilletes_bkp[3] = listaBilletes[3]; listaBilletes[3].disminuirCantidad(cantidad5000); } else { return false; } if (listaBilletes[4].getCantidad() - cantidad2000 >= 0) { listaBilletes_bkp[4] = listaBilletes[4]; listaBilletes[4].disminuirCantidad(cantidad2000); } else { return false; } } return true; } public void restablecer() { if (listaBilletes_bkp != null) { for (int i = 0; i < 5; i++) { listaBilletes[i] = listaBilletes_bkp[i]; listaBilletes_bkp[i] = null; } } } }
package se.kth.kthfsdashboard.util; import java.text.DecimalFormat; import java.text.ParseException; /** * * @author Hamidreza Afzali <afzali@kth.se> */ public class Parser { public Double parseDouble(String d) throws ParseException { DecimalFormat format = new DecimalFormat("#.##"); return format.parse(d.toUpperCase().replace("+", "")).doubleValue(); } public long parseLong(String d) throws ParseException { DecimalFormat format = new DecimalFormat("#.##"); return format.parse(d.toUpperCase().replace("+", "")).longValue(); } }
package xyz.noark.core.util; import xyz.noark.benchmark.Benchmark; import java.util.StringJoiner; import java.util.stream.Collectors; import java.util.stream.Stream; /** * 字符串相关测试数据 * * @author 小流氓[176543888@qq.com] * @since 3.4 */ public class StringBenchmark { private static final Benchmark benchmark = new Benchmark(100_0000); public static void main(String[] args) throws Exception { benchmark.doSomething("Jdk:", () -> StringUtils.split("127.0.0.1", ".")); benchmark.doSomething("Noark:", () -> testSplitByJdk("127.0.0.1", "\\.")); long value = Long.MIN_VALUE; benchmark.doSomething("OKIO的方案:", () -> StringUtils.asciiSizeInBytes(value)); benchmark.doSomething("成龙的方案:", () -> String.valueOf(value).length()); String[] strings = new String[]{"aaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbbb"}; benchmark.doSomething("join:", () -> StringUtils.build(",", "{", "}", strings)); benchmark.doSomething("join1:", () -> join1(",", "{", "}", strings)); benchmark.doSomething("join2:", () -> join2(",", "{", "}", strings)); } private static String join1(String delimiter, String prefix, String suffix, String... strings) { StringJoiner result = new StringJoiner(delimiter, prefix, suffix); for (String str : strings) { result.add(str); } return result.toString(); } private static String join2(String delimiter, String prefix, String suffix, String... strings) { return Stream.of(strings).collect(Collectors.joining(delimiter, prefix, suffix)); } private static String[] testSplitByJdk(String ip, String regex) { return ip.split(regex); } }
package me.ewriter.lambdasample; /** * Created by Zubin on 2016/8/19. */ public interface Factory<T extends Animal> { T create(String name, int age); }
//Benjamin Stanelle //1001534907 //3/312020 //Java Version: jdk-13.0.2 OS: windows 10 pro 64x import java.io.File; import java.io.IOException; public class 1001534907_PA2 { public static void main(String args[]) { File currentDir= new File("."); //The current directory long totalSum=directoryDisplay(currentDir); if(totalSum >= 1000) { double sizekb= (double)totalSum; sizekb=sizekb/1000; System.out.println(sizekb + " kilobytes"); } else if(totalSum>= 1000000) { double sizekb= (double)totalSum; sizekb=sizekb/1000000; System.out.println(sizekb + " megabytes"); } else { System.out.println(totalSum + " bytes"); } } public static long directoryDisplay(File currentDir) { //recursive function for getting the files and sub directories, and getting sum of file size in bytes long sum=0; try {File[] files= currentDir.listFiles(); //Makes an array of the files and sub-directories for(File file: files) { //loops through each file in the Array of files (the Current directory) to check and see if it is a directory or a text file if(file.isDirectory()) { //library function for determining if it is a directory System.out.println("Directory:" + file.getCanonicalPath()); //printing out the current path sum += directoryDisplay(file); //recursive step, when it is a sub-directory take what ever files or sub directories are in that and sum them } else { System.out.println(" file:" + file.getCanonicalPath()); //if its not a directory sum the file lengths sum += file.length(); //add file bytes to the sum } } } catch (IOException e) { e.printStackTrace(); } return sum; } }
package cs190i.cs.ucsb.edu.jingyangeofencing; import android.Manifest; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.Uri; import android.os.Handler; import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.util.JsonToken; import android.util.Log; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.Geofence; import com.google.android.gms.location.GeofencingRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import static java.lang.Thread.sleep; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapLoadedCallback, GoogleMap.OnInfoWindowClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback<Status> { private GoogleMap mMap; private Marker currentMarker; private LatLng currentLocation; private LatLng iniLocation; private GoogleApiClient googleApiClient; private PendingIntent geoFencePendingIntent; private final int GEOFENCE_REQ_CODE = 0; // KEY private static final String mKey = "google_maps_key"; private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place/nearbysearch"; private static final String OUT_JSON = "/json"; private static final String LOCATION = "?location="; private static final String RADIUS = "&radius="; private static final String KEY = "&key="; private static final String DETAILED_PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place/details"; private static final String PLACE_ID = "?placeid="; private static final int mRadius = 500; private static final float GEOFENCE_RADIUS_IN_METERS = 25.0f; private static final long GEOFENCE_EXPIRATION_IN_MILLISECONDS = 60 * 60 * 1000; ArrayList<HashMap<String, String>> resultList; ArrayList<Geofence> mGeofenceList; String place_id_current = null; public float mCameraZoom; public double mCameraPositionLat; public double mCameraPositionLng; //public ArrayList<? extends HashMap<String, String>> mResultList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); resultList = new ArrayList<>(); mGeofenceList = new ArrayList<>(); // create GoogleApiClient createGoogleApi(); } // ----------------------------------------------------------------------------------------------- // Create GoogleApiClient instance private void createGoogleApi() { Log.d("createGoogleApi", "createGoogleApi()"); if (googleApiClient == null) { googleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } } @Override protected void onStart() { super.onStart(); // Call GoogleApiClient connection when starting the Activity googleApiClient.connect(); } @Override protected void onStop() { super.onStop(); // Disconnect GoogleApiClient when stopping Activity googleApiClient.disconnect(); } // ----------------------------------------------------------------------------------------------- /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // Handling save state if(mCameraPositionLat!=0){ iniLocation = new LatLng(mCameraPositionLat,mCameraPositionLng); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(iniLocation, mCameraZoom)); }else{ // Add a marker on Campus and move the camera iniLocation = new LatLng(34.4140, -119.8489); if (getCurrentLocation() != null) { iniLocation = getCurrentLocation(); } mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(iniLocation, 17.0f)); } currentMarker = mMap.addMarker(new MarkerOptions() .position(iniLocation) .title("Current Location") .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))); // customize color mMap.setOnMapLoadedCallback(this); mMap.setOnInfoWindowClickListener(this); } @Override public void onMapLoaded() { //mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 17.0f)); // send request and get result - on new Thread Thread thread = new Thread(new Runnable() { @Override public void run() { try { Log.d("Run new Thread", "Run new Thread"); // TODO set [changed current location] to request //currentLocation = getCurrentLocation(); requestGetNearbyPlace(iniLocation); // add marker - on Main Thread runOnUiThread(new Runnable() { public void run() { Log.d("Run UI Thread", "Run UI Thread"); // add marker to nearby places for (int i = 0; i < resultList.size(); i++) { LatLng pos = new LatLng(Double.parseDouble(resultList.get(i).get("lat")), Double.parseDouble(resultList.get(i).get("lng"))); MarkerOptions mo = new MarkerOptions() .position(pos) .title(resultList.get(i).get("name")) .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)); Marker geoFenceMarker = mMap.addMarker(mo); drawGeofence(geoFenceMarker); //Build new GeoFences mGeofenceList.add(createGeofence(resultList.get(i).get("name"), resultList.get(i).get("lat"), resultList.get(i).get("lng"))); GeofencingRequest request = createGeofenceRequest(mGeofenceList.get(i)); addGeofence(request); } Log.d("mGeofenceList size", "" + mGeofenceList.size()); } }); } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); } // ----------------------------------------------------------------------------------------------- // Create a Geofence Request private GeofencingRequest createGeofenceRequest(Geofence geofence) { return new GeofencingRequest.Builder() .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER) .addGeofence(geofence) .build(); } // Create a Geofence private Geofence createGeofence(String geofence_id, String lat, String lng) { return new Geofence.Builder() .setRequestId(geofence_id) .setCircularRegion(Double.parseDouble(lat), Double.parseDouble(lng), GEOFENCE_RADIUS_IN_METERS) .setExpirationDuration(GEOFENCE_EXPIRATION_IN_MILLISECONDS) .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) .build(); } // draw geoFenceLimits private void drawGeofence(Marker geoFenceMarker) { //Log.d("drawGeofence","drawGeofence"); CircleOptions circleOptions = new CircleOptions() .center( geoFenceMarker.getPosition()) .strokeColor(Color.argb(100, 150,150,150) ) .fillColor( Color.argb(100, 150,150,150) ) .radius( GEOFENCE_RADIUS_IN_METERS ); mMap.addCircle( circleOptions ); } private PendingIntent createGeofencePendingIntent() { if (geoFencePendingIntent != null) { return geoFencePendingIntent; } Intent intent = new Intent(this, GeofenceTrasitionService.class); return PendingIntent.getService( this, GEOFENCE_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT); } // Add the created GeofenceRequest to the device's monitoring list private void addGeofence(GeofencingRequest request) { if (checkPermission()) { LocationServices.GeofencingApi.addGeofences( googleApiClient, request, createGeofencePendingIntent() ).setResultCallback(MapsActivity.this); } } static Intent makeNotificationIntent(Context geofenceService, String msg) { Log.d("msg",msg); return new Intent(geofenceService,MapsActivity.class); } private boolean checkPermission() { // Ask for permission if it wasn't granted yet return (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ); } // ----------------------------------------------------------------------------------------------- // Check for permission to access Location public LatLng getCurrentLocation() { LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); final int REQ_PERMISSION = 1234; if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (loc == null) { // fall back to network if GPS is not available loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } if (loc != null) { double myLat = loc.getLatitude(); double myLng = loc.getLongitude(); LatLng currLoc = new LatLng(myLat, myLng); // location changed >[currentLocation] locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() { public void onLocationChanged(Location location) { // code to run when user's location changes currentLocation = new LatLng(location.getLatitude(), location.getLongitude()); Toast.makeText(getApplicationContext(), "Move to " + location.getLatitude() + " " + location.getLongitude(), Toast.LENGTH_SHORT).show(); // create path mMap.addCircle(new CircleOptions() .center(currentLocation) .radius(1) .strokeColor(Color.TRANSPARENT) .fillColor(Color.GRAY)); // move current Marker currentMarker.setPosition(currentLocation); } public void onStatusChanged(String prov, int stat, Bundle b) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } } ); return currLoc; } } else { Toast.makeText(getApplicationContext(), "Missing permissions to access location.", Toast.LENGTH_SHORT).show(); // set app to ask for permissions ActivityCompat.requestPermissions( this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQ_PERMISSION); return null; } return null; } // ----------------------------------------------------------------------------------------------- public boolean requestGetNearbyPlace(LatLng l) throws IOException, JSONException { //https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&key=Google_API_KEY StringBuilder sb = new StringBuilder(PLACES_API_BASE); sb.append(OUT_JSON); sb.append(LOCATION); sb.append(l.latitude + "," + l.longitude); sb.append(RADIUS); sb.append(mRadius); sb.append(KEY); sb.append(mKey); URL url = new URL(sb.toString()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); InputStreamReader in = new InputStreamReader(connection.getInputStream()); int read; char[] buff = new char[1024]; StringBuilder jsonResults = new StringBuilder(); while ((read = in.read(buff)) != -1) { jsonResults.append(buff, 0, read); } JSONObject jsonObject = new JSONObject(jsonResults.toString()); Log.d("jsonObject", "" + jsonObject.toString()); // Getting JSON Array node JSONArray results = jsonObject.getJSONArray("results"); // looping through All results for (int i = 0; i < results.length(); i++) { JSONObject r = results.getJSONObject(i); JSONObject location = r.getJSONObject("geometry").getJSONObject("location"); String lat = location.getString("lat"); String lng = location.getString("lng"); String place_id = r.getString("place_id"); String name = r.getString("name"); // tmp hash map for single contact HashMap<String, String> result = new HashMap<>(); // adding each child node to HashMap key => value result.put("place_id", place_id); result.put("name", name); result.put("lat", lat); result.put("lng", lng); // adding contact to contact list resultList.add(result); } Log.d("resultList size", "" + resultList.size()); return true; } // ----------------------------------------------------------------------------------------------- @Override public void onInfoWindowClick(Marker marker) { for (int i = 0; i < resultList.size(); i++) { String place_name = resultList.get(i).get("name"); if (place_name.equals(marker.getTitle())) { place_id_current = resultList.get(i).get("place_id"); } } //Log.d("place_id", "" + place_id); Toast.makeText(this, "Info window :" + place_id_current, Toast.LENGTH_SHORT).show(); // send request and get result - on new Thread Thread thread_d = new Thread(new Runnable() { @Override public void run() { try { openDetailPlaceWebBrowser(place_id_current); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } }); thread_d.start(); } public void openDetailPlaceWebBrowser(String place_id) throws IOException, JSONException { // https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJN1t_tDeuEmsRUsoyG83frY4&key=YOUR_API_KEY StringBuilder sb_d = new StringBuilder(DETAILED_PLACES_API_BASE); sb_d.append(OUT_JSON); sb_d.append(PLACE_ID); sb_d.append(place_id); sb_d.append(KEY); sb_d.append(mKey); URL url_d = new URL(sb_d.toString()); HttpURLConnection connection_d = (HttpURLConnection) url_d.openConnection(); InputStreamReader in_d = new InputStreamReader(connection_d.getInputStream()); int read_d; char[] buff_d = new char[1024]; StringBuilder jsonResults_d = new StringBuilder(); while ((read_d = in_d.read(buff_d)) != -1) { jsonResults_d.append(buff_d, 0, read_d); } JSONObject jsonObject_d = new JSONObject(jsonResults_d.toString()); //Log.d("jsonObject detail place", "" + jsonResults_d.toString()); // Getting JSON Array node JSONObject results_d = jsonObject_d.getJSONObject("result"); String url_google = results_d.getString("url"); Intent intent = new Intent(this, WebViewActivity.class); // open web-browser page in app intent.putExtra("DETAIL_PLACE_URL", url_google); Log.d("SEND_DETAIL_PLACE_URL", "" + url_google); startActivity(intent); // open external browser // Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url_google.toString())); // startActivity(browserIntent); } // ----------------------------------------------------------------------------------------------- @Override public void onConnected(@Nullable Bundle bundle) { Log.i("onConnected", "onConnected()"); } @Override public void onConnectionSuspended(int i) { Log.w("onConnectionSuspended", "onConnectionSuspended()"); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Log.w("onConnectionFailed", "onConnectionFailed()"); } @Override public void onResult(@NonNull Status status) { //Log.d("onResult", "onResult()"); } // ----------------------------------------------------------------------------------------------- @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); savedInstanceState.putFloat("CameraZoom", mMap.getCameraPosition().zoom); savedInstanceState.putDouble("CameraPositionLatitude", mMap.getCameraPosition().target.latitude); savedInstanceState.putDouble("CameraPositionLongitude", mMap.getCameraPosition().target.longitude); //savedInstanceState.putParcelableArrayList("POIs", (ArrayList<? extends Parcelable>) resultList); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mCameraZoom = savedInstanceState.getFloat("CameraZoom"); mCameraPositionLat = savedInstanceState.getDouble("CameraPositionLatitude"); mCameraPositionLng = savedInstanceState.getDouble("CameraPositionLongitude"); //mResultList = savedInstanceState.getParcelableArrayList("POIs"); Log.d("CameraZoom_GET",""+ mCameraZoom); Log.d("CameraPositionLat_GET",""+ mCameraPositionLat); Log.d("CameraPositionLng_GET",""+ mCameraPositionLng); //Log.d("mResultList_GET",""+ mResultList); } }
import java.util.ArrayList; import java.util.Random; public class Individuos implements Comparable<Individuos>{ public double x; public double y; public double resp; public Individuos(double x, double y, double resp) { this.x = x; this.y = y; this.resp = resp; } public Individuos(){} @Override public int compareTo(Individuos i2) { if((this.resp-i2.resp)>0) return 1; else if((this.resp-i2.resp)<0) return -1; else return 0; } }
package conf; import org.apache.commons.dbcp2.BasicDataSource; import java.sql.Connection; import java.sql.SQLException; public class ConnectionProvider { static final String DB_URL = "jdbc:postgresql://localhost:5432/iasa-java"; static final String USER = "postgres"; static final String PASS = "123"; // private static BasicDataSource ds = new BasicDataSource(); // // static { // ds.setUrl(DB_URL); // ds.setUsername(USER); // ds.setPassword(PASS); // ds.setMinIdle(5); // ds.setMaxIdle(10); // ds.setMaxOpenPreparedStatements(100); // } public static Connection getConnection() throws SQLException { BasicDataSource ds = new BasicDataSource(); ds.setUrl("jdbc:postgresql://localhost:5432/iasa-java"); ds.setUsername("postgres"); ds.setPassword("123"); ds.setMinIdle(5); ds.setMaxIdle(10); ds.setMaxOpenPreparedStatements(100); return ds.getConnection(); } }
package com.mobdeve.ramos.isa; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class Profile extends AppCompatActivity { EditText username_profile, password_profile, repassword_profile; Button update_btn; DBHelper DB; String usernametemp; String user_hint, pass_hint, username, password,repassword; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); //connect password username_profile = (EditText) findViewById(R.id.username_profile); password_profile = (EditText) findViewById(R.id.password_profile); repassword_profile = (EditText) findViewById(R.id.repassword_profile); update_btn = (Button) findViewById(R.id.update_btn); DB = new DBHelper(this); Intent intent = getIntent(); usernametemp = intent.getStringExtra("username"); //username of current user Cursor cursor = DB.getUserCred(usernametemp); while(cursor.moveToNext()){ user_hint = cursor.getString(0); pass_hint = cursor.getString(1); } username_profile.setHint(user_hint); password_profile.setHint(pass_hint); update_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { username = username_profile.getText().toString(); password = password_profile.getText().toString(); repassword = repassword_profile.getText().toString(); if(password.equals(repassword)){// if passwords are correct proceed to updating Boolean isUpdated = DB.updateCreds(username,password); if(isUpdated == true){ Toast.makeText(Profile.this,"Profile Updated. Please Sign In Again", Toast.LENGTH_SHORT).show(); Intent intent = new Intent (Profile.this, LoginActivity.class); startActivity(intent); } else{ Toast.makeText(Profile.this,"Something went wrong.", Toast.LENGTH_SHORT).show(); } } else Toast.makeText(Profile.this,"Passwords Mismatch.", Toast.LENGTH_SHORT).show(); } }); } }
<<<<<<< HEAD ======= >>>>>>> rebuilt-version package com.example.sieunhan.github_client.api; import com.squareup.moshi.FromJson; import com.squareup.moshi.JsonDataException; import com.squareup.moshi.ToJson; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; <<<<<<< HEAD /** * Created by dannyle on 03/12/2016. */ public class DateAdapter { private final DateFormat[] formats = new DateFormat[3]; ======= public class DateAdapter { private final DateFormat[] formats = new DateFormat[3]; >>>>>>> rebuilt-version public DateAdapter() { formats[0] = new SimpleDateFormat("yyyy-MM-dd\'T\'HH:mm:ss\'Z\'"); formats[1] = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss Z"); formats[2] = new SimpleDateFormat("yyyy-MM-dd\'T\'HH:mm:ss"); final TimeZone timeZone = TimeZone.getTimeZone("Zulu"); for (DateFormat format : formats) { format.setTimeZone(timeZone); } } <<<<<<< HEAD ======= >>>>>>> rebuilt-version @ToJson String toJson(Date date) { return formats[0].format(date); } <<<<<<< HEAD ======= >>>>>>> rebuilt-version @FromJson Date fromJson(String date) { for (DateFormat format : formats) { try { return format.parse(date); } catch (ParseException e) { } } <<<<<<< HEAD throw new JsonDataException(); } } ======= throw new JsonDataException(); } } >>>>>>> rebuilt-version