text
stringlengths
10
2.72M
package services; import model.domain.Client; import model.forms.ClientFormModel; import java.util.List; public interface ClientService { List<Client> findAll(); Client saveClient(ClientFormModel entity); Client findOne(long idClient); }
/* * DataPanel.java * Copyright (C) 2016 NanChang University, JiangXi, China * */ package cn.myluo.datamining.gui; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.BorderLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableColumnModel; import javax.swing.BorderFactory; import cn.myluo.datamining.data.DataSet; import cn.myluo.datamining.util.Reader; /** * The data set panel. * * @author Luo Mingyuan * @version 1612 */ public class DataPanel extends JPanel { /** for serialization */ private static final long serialVersionUID = 627131485290359194L; /** * A table model that displays the data set. * * @author Luo Mingyuan * @version 1612 */ class DataTableModel extends AbstractTableModel { /** for serialization */ private static final long serialVersionUID = -4152987434024338064L; /** The data set. */ protected DataSet m_Dataset; /** * Creates the table model with the given data set. * * @param dataset * the given data set */ public DataTableModel(DataSet dataset) { setDataSet(dataset); } /** * Sets the data set with the given data set. * * @param dataset * the given data set */ public void setDataSet(DataSet dataset) { this.m_Dataset = dataset; } /** * Gets the number of attributes. * * @return the number of attributes. */ public int getRowCount() { return m_Dataset.numInstances(); } /** * Gets the number of instances. * * @return the number of instances. */ public int getColumnCount() { return m_Dataset.numAttributes(); } /** * Gets a table cell * * @param row * the row index * @param column * the column index * @return the value at row, column */ public Object getValueAt(int row, int column) { return m_Dataset.getInstances().get(row).getValues() .get(getColumnName(column)); } /** * Gets the name for a column. * * @param column * the column index. * @return the name of the column. */ public String getColumnName(int column) { return m_Dataset.getAttributes().get(column).getName(); } /** * Sets the value at a cell. * * @param value * the new value. * @param row * the row index. * @param col * the column index. */ public void setValueAt(Object value, int row, int col) { } /** * Gets the class of elements in a column. * * @param col * the column index. * @return the class of elements in the column. */ public Class<?> getColumnClass(int col) { return getValueAt(0, col).getClass(); } /** * Returns true if the column is the "selected" column. * * @param row * ignored * @param col * ignored * @return false */ public boolean isCellEditable(int row, int col) { return false; } } /** The data set table. */ protected JTable m_Table = new JTable(); /** The data set table model. */ protected DataTableModel m_Model; /** * Creates the data set panel. */ public DataPanel() { m_Table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); m_Table.setColumnSelectionAllowed(false); m_Table.setPreferredScrollableViewportSize(new Dimension(250, 150)); JPanel p1 = new JPanel(); p1.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5)); p1.setLayout(new GridLayout(1, 4, 5, 5)); setLayout(new BorderLayout()); add(p1, BorderLayout.NORTH); add(new JScrollPane(m_Table), BorderLayout.CENTER); } /** * Sets the data set with the given data set. * * @param dataset * the given data set */ public void setDataSet(DataSet dataset) { m_Model = new DataTableModel(dataset); m_Table.setModel(m_Model); m_Table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); TableColumnModel tcm = m_Table.getColumnModel(); int totalColumnWidth = 0; int[] widths = new int[m_Model.getColumnCount()]; for (int i = 0; i < widths.length; i++) { widths[i] = (int) m_Table .getTableHeader() .getDefaultRenderer() .getTableCellRendererComponent(m_Table, tcm.getColumn(i).getIdentifier(), false, false, -1, i).getPreferredSize().getWidth(); totalColumnWidth += widths[i]; } // resets widths to adaptive size. if (tcm.getTotalColumnWidth() < 800) { double ratio = 800.0 / totalColumnWidth; for (int i = 0; i < tcm.getColumnCount(); i++) { m_Table.getColumnModel().getColumn(i) .setMinWidth((int) (ratio * (double) widths[i])); } } else { for (int i = 0; i < tcm.getColumnCount(); i++) { int width = widths[i]; for (int j = 0; j < m_Model.getRowCount(); j++) { int preferedWidth = (int) m_Table .getCellRenderer(j, i) .getTableCellRendererComponent(m_Table, m_Table.getValueAt(j, i), false, false, j, i).getPreferredSize().getWidth(); if (preferedWidth > width) width = preferedWidth; } m_Table.getColumnModel().getColumn(i).setMinWidth(width + 4); } } m_Table.clearSelection(); m_Table.doLayout(); m_Table.revalidate(); m_Table.repaint(); } /** * Gets the current data set. * * @return the current data set */ public DataSet getDataSet() { return m_Model.m_Dataset; } /** * Gets the current selected model. * * @return the current selected model */ public ListSelectionModel getSelectionModel() { return m_Table.getSelectionModel(); } /** * Tests the data set panel with the given data set. * * @param args * must contain the name of an data set file to load. */ public static void main(String[] args) { if (args.length == 0) { System.out.println("\nUsage: " + DataPanel.class.getName() + " <dataset>\n"); return; } try { final JFrame jf = new JFrame("DataPanel"); jf.getContentPane().setLayout(new BorderLayout()); DataPanel sp = new DataPanel(); sp.setDataSet(new Reader(new File(args[0])).getDataSet()); jf.getContentPane().add(sp, BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); jf.setSize(700, 550); jf.setVisible(true); } catch (Exception e) { System.out.println(e); } } }
package codingTest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; public class kakao_2 { private static StringBuilder sb = new StringBuilder(); private static List<Character> food; private static List<String> tmp; private static List<String> ans; private static int max; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; String[] orders = {"XYZ", "XWY", "WXA"}; int[] course = {2,3,4}; System.out.println(Arrays.toString(solution(orders, course))); } public static String[] solution(String[] orders, int[] course) { String[] answer = {}; food = new ArrayList<>(); ans = new ArrayList<>(); // 우선 단품 리스트를 만든다 for (int i = 0; i < orders.length; i++) { for (int j = 0; j < orders[i].length(); j++) { if(!food.contains(orders[i].charAt(j))) { food.add(orders[i].charAt(j)); } } } // 그 알파벳 정렬도 해둔다 Collections.sort(food); for (int i = 0; i < course.length; i++) { int cour = course[i]; // 2부터 시작 max = 2; tmp = new ArrayList<>(); nCrRecursion(0,0,"",cour,orders); for (int j = 0; j < tmp.size(); j++) { ans.add(tmp.get(j)); } } Collections.sort(ans); answer = new String[ans.size()]; for (int i = 0; i < answer.length; i++) { answer[i] = ans.get(i); } return answer; } // 평범한 nCr public static void nCrRecursion(int r, int k, String result, int cour, String[] orders) { if(r == cour) { int cnt = 0; for (int j = 0; j < orders.length; j++) { // 없다면 boolean flag = true; for (int i = 0; i < result.length(); i++) { if(orders[j].indexOf(result.charAt(i)) < 0) { flag = false; break; } } if(flag) cnt++; } // max면 리스트에 추가 if(max == cnt) { tmp.add(result); }else if(max < cnt) { // 넘어가면 현재까지 모은거 지우고 추가 max = cnt; tmp.clear(); tmp.add(result); } return; } for (int i = k; i < food.size(); i++) { nCrRecursion(r+1,i+1,result+ food.get(i),cour,orders); } } }
package com.mimi.mimigroup.ui.adapter; import android.graphics.Color; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.mimi.mimigroup.R; import com.mimi.mimigroup.model.SM_ReportSaleRepActivitie; import com.mimi.mimigroup.ui.custom.CustomTextView; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class ReportSaleRepActivityAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{ public void setsmoReportSaleRepActivity(List<SM_ReportSaleRepActivitie> smoReportSaleRepActivity) { this.smoReportSaleRepActivity = smoReportSaleRepActivity; notifyDataSetChanged(); } List<SM_ReportSaleRepActivitie> smoReportSaleRepActivity; public List<SM_ReportSaleRepActivitie> SelectedList = new ArrayList<>(); public interface ListItemClickListener{ void onItemClick(List<SM_ReportSaleRepActivitie> SelectList); } private final ReportSaleRepActivityAdapter.ListItemClickListener mOnItemClicked; public ReportSaleRepActivityAdapter(ReportSaleRepActivityAdapter.ListItemClickListener mOnClickListener) { smoReportSaleRepActivity = new ArrayList<>(); this.mOnItemClicked=mOnClickListener; } @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { return new ReportSaleRepActivityAdapter.ReportSaleRepActivityHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_report_sale_rep_activity_item,viewGroup,false)); } @Override public void onBindViewHolder( final RecyclerView.ViewHolder viewHolder,final int iPos) { if(viewHolder instanceof ReportSaleRepActivityAdapter.ReportSaleRepActivityHolder){ ((ReportSaleRepActivityAdapter.ReportSaleRepActivityHolder) viewHolder).bind(smoReportSaleRepActivity.get(iPos)); } setRowSelected(SelectedList.contains(smoReportSaleRepActivity.get(iPos)),viewHolder); viewHolder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(SelectedList.contains(smoReportSaleRepActivity.get(iPos))){ SelectedList.remove(smoReportSaleRepActivity.get(iPos)); setRowSelected(false,viewHolder); clearSelected(); }else{ SelectedList.add(smoReportSaleRepActivity.get(iPos)); setRowSelected(true,viewHolder); } mOnItemClicked.onItemClick(SelectedList); } }); viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { return false; } }); } @Override public int getItemCount() { if(smoReportSaleRepActivity != null) { return smoReportSaleRepActivity.size(); } return 0; } public void clearSelected(){ SelectedList.clear(); notifyDataSetChanged(); } class ReportSaleRepActivityHolder extends RecyclerView.ViewHolder { @BindView(R.id.tvTitle) CustomTextView tvTitle; @BindView(R.id.tvNotes) CustomTextView tvNotes; @BindView(R.id.tvWorkday) CustomTextView tvWorkday; @BindView(R.id.tvPlace) CustomTextView tvPlace; public ReportSaleRepActivityHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } public void bind(SM_ReportSaleRepActivitie oDetail){ if(oDetail != null){ if(oDetail.getTitle() != null){ tvTitle.setText(oDetail.getTitle()); } if(oDetail.getNotes() != null){ tvNotes.setText(oDetail.getNotes()); } if(oDetail.getWorkDay() != null){ tvWorkday.setText(oDetail.getWorkDay()); } if(oDetail.getPlace() != null){ tvPlace.setText(oDetail.getPlace()); } } } } private void setRowSelected(boolean isSelected,RecyclerView.ViewHolder viewHolder){ if(isSelected){ viewHolder.itemView.setBackgroundColor(Color.parseColor("#F8D8E7")); viewHolder.itemView.setSelected(true); }else { viewHolder.itemView.setBackgroundColor(Color.parseColor("#ffffff")); viewHolder.itemView.setSelected(false); } } }
import java.util.ArrayList; import java.util.GregorianCalendar; /** * This class stores a booking with specific details whenever someone makes a new request. * @author z5059430 * */ public class Booking { public Booking(int id) { this.id = id; this.bookedRooms = new ArrayList<Room>(); } /** * Gets The venue this booking is using. * @return The venue field. */ public Venue getVenue() { return this.venue; } /** * Gets booking id. * @return the id field. */ public int getId() { return this.id; } /** * Gets the date the booking starts. * @return The startDate field. */ public GregorianCalendar getStartDate() { return startDate; } /** * Gets the date the booking ends. * @return The endDate field. */ public GregorianCalendar getEndDate() { return endDate; } /** * Gets the rooms that were booked together. * @return The list of rooms. */ public ArrayList<Room> getRoomList() { return bookedRooms; } /** * Gets the number of rooms booked under the same booking. * @return Number of rooms booked. */ public int getBookedListSize() { return bookedRooms.size(); } /** * Sets the venue that this booking is using. * @param venue */ public void setVenue(Venue venue) { this.venue = venue; } /** * Sets the start and end date of this booking * @param startDate * @param endDate */ public void setDate(GregorianCalendar startDate, GregorianCalendar endDate) { this.startDate = startDate; this.endDate = endDate; } /** * Adds a room to the list of rooms booked. * @param room */ public void bookRoom(Room room) { bookedRooms.add(room); room.addDate(startDate,endDate); } /** * Removes the date this booking set from all the rooms it booked. * @param startDate */ public void removeDate(GregorianCalendar startDate) { int i; Room currRoom; for (i = 0; i < bookedRooms.size(); i++) { currRoom = bookedRooms.get(i); currRoom.delBooking(startDate); } } /** * Empties the list of booked rooms. */ public void clearBookedRoomList() { bookedRooms.clear(); } private int id; private Venue venue; private ArrayList <Room> bookedRooms; private GregorianCalendar startDate; private GregorianCalendar endDate; }
package zm.gov.moh.cervicalcancer.submodule.dashboard.patient.adapter; public class ViewPagerAdapter { }
package com.mideas.rpg.v2.hud; /*import java.sql.SQLException; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.Display; import org.newdawn.slick.Color; import com.mideas.rpg.v2.utils.Texture; import com.mideas.rpg.v2.Interface; import com.mideas.rpg.v2.Mideas; import com.mideas.rpg.v2.Sprites; import com.mideas.rpg.v2.TTF2; import com.mideas.rpg.v2.game.CharacterStuff; import com.mideas.rpg.v2.game.Joueur; import com.mideas.rpg.v2.game.classes.ClassManager; import com.mideas.rpg.v2.game.spell.SpellBarManager; import com.mideas.rpg.v2.utils.Draw;*/ /** * UNUSED * @author Mideas * */ public class ClassSelectFrame { /*private static boolean warriorHover; private static boolean paladinHover; private static boolean hunterHover; private static boolean rogueHover; private static boolean priestHover; private static boolean deathknightHover; private static boolean shamanHover; private static boolean mageHover; private static boolean warlockHover; private static boolean monkHover; private static boolean isBagEquipped; private static float expClass; private static Color bgExpBarColor = new Color(0, 0, 0,.65f); public static void draw() { Color bgColor = new Color(0, 0, 0,.45f); Draw.drawColorQuad(Display.getWidth()/2-280, Display.getHeight()-330, 600, 550, bgColor); int x = -140; int xShift = 62; int yFirstLine = -80; int ySecondLine = -13; drawFrameCreateClass(Sprites.class_choose, x-22, yFirstLine-39); drawFrameCreateClass(Sprites.warrior_create_classe, x, yFirstLine); drawFrameCreateClass(Sprites.paladin_create_classe, x+xShift, yFirstLine); drawFrameCreateClass(Sprites.hunter_create_classe, x+2*xShift, yFirstLine); drawFrameCreateClass(Sprites.rogue_create_classe, x+3*xShift, yFirstLine); drawFrameCreateClass(Sprites.priest_create_classe, x+4*xShift, yFirstLine); drawFrameCreateClass(Sprites.deathknight_create_classe, x, ySecondLine); drawFrameCreateClass(Sprites.shaman_create_classe, x+xShift, ySecondLine); drawFrameCreateClass(Sprites.mage_create_classe, x+2*xShift, ySecondLine); drawFrameCreateClass(Sprites.warlock_create_classe, x+3*xShift, ySecondLine); drawFrameCreateClass(Sprites.monk_create_classe, x+4*xShift, ySecondLine); x-= 6; yFirstLine-= 5; ySecondLine-= 5; drawBorder(x, yFirstLine, 0); drawBorder(x+xShift, yFirstLine, 1); drawBorder(x+2*xShift, yFirstLine, 0); drawBorder(x+3*xShift, yFirstLine, 1); drawBorder(x+4*xShift, yFirstLine, 0); drawBorder(x, ySecondLine, 1); drawBorder(x+xShift, ySecondLine, 0); drawBorder(x+2*xShift, ySecondLine, 1); drawBorder(x+3*xShift, ySecondLine, 0); drawBorder(x+4*xShift, ySecondLine, 1); TTF2.playerName.drawStringShadow(Display.getWidth()/2-26, Display.getHeight()/2-108, "Class select", Color.yellow, Color.black, 1, 1, 1); int xLeft = -210; int xRight = 90; int y = -295; int yShift = 60; drawLevel(Mideas.getExpAll(1), xLeft, y); drawLevel(Mideas.getExpAll(5), xLeft, y+yShift); drawLevel(Mideas.getExpAll(2), xLeft, y+2*yShift); drawLevel(Mideas.getExpAll(7), xLeft, y+3*yShift); drawLevel(Mideas.getExpAll(6), xLeft, y+4*yShift); drawLevel(Mideas.getExpAll(0), xRight, y); drawLevel(Mideas.getExpAll(8), xRight, y+yShift); drawLevel(Mideas.getExpAll(3), xRight, y+2*yShift); drawLevel(Mideas.getExpAll(9), xRight, y+3*yShift); drawLevel(Mideas.getExpAll(4), xRight, y+4*yShift); y = -30; TTF2.spellName.drawStringShadow(Display.getWidth()/2+5, Display.getHeight()+y-295, "Level :", Color.white, Color.black, 1, 1, 1); xLeft = -270; xRight = 30; y = -285; drawFrameClass(Sprites.warrior_create_classe_level, xLeft, y); drawFrameClass(Sprites.paladin_create_classe_level, xLeft, y+yShift); drawFrameClass(Sprites.hunter_create_classe_level, xLeft, y+2*yShift); drawFrameClass(Sprites.rogue_create_classe_level, xLeft, y+3*yShift); drawFrameClass(Sprites.priest_create_classe_level, xLeft, y+4*yShift); drawFrameClass(Sprites.deathknight_create_classe_level, xRight, y); drawFrameClass(Sprites.shaman_create_classe_level, xRight, y+yShift); drawFrameClass(Sprites.mage_create_classe_level, xRight, y+2*yShift); drawFrameClass(Sprites.warlock_create_classe_level, xRight, y+3*yShift); drawFrameClass(Sprites.monk_create_classe_level, xRight, y+4*yShift); xLeft = -220; xRight = 80; y = -270; drawExpBar(Mideas.getExpAll(1), xLeft, y); drawExpBar(Mideas.getExpAll(5), xLeft, y+yShift); drawExpBar(Mideas.getExpAll(2), xLeft, y+2*yShift); drawExpBar(Mideas.getExpAll(7), xLeft, y+3*yShift); drawExpBar(Mideas.getExpAll(6), xLeft, y+4*yShift); drawExpBar(Mideas.getExpAll(0), xRight, y); drawExpBar(Mideas.getExpAll(8), xRight, y+yShift); drawExpBar(Mideas.getExpAll(3), xRight, y+2*yShift); drawExpBar(Mideas.getExpAll(9), xRight, y+3*yShift); drawExpBar(Mideas.getExpAll(4), xRight, y+4*yShift); y = -30; isClassHoverExp(warriorHover, Mideas.getExpAll(1), -144, -82, -220, y, -240); isClassHoverExp(paladinHover, Mideas.getExpAll(5), -82, -82, -220, y, -180); isClassHoverExp(hunterHover, Mideas.getExpAll(2), -20, -82, -220, y, -120); isClassHoverExp(rogueHover, Mideas.getExpAll(7), 40, -82, -220, y, -60); isClassHoverExp(priestHover, Mideas.getExpAll(6), 104, -82, -220, y, 0); isClassHoverExp(deathknightHover, Mideas.getExpAll(0), -144, -15, 80, y, -240); isClassHoverExp(shamanHover, Mideas.getExpAll(8), -82, -15, 80, y, -180); isClassHoverExp(mageHover, Mideas.getExpAll(3), -20, -15, 80, y, -120); isClassHoverExp(warlockHover, Mideas.getExpAll(9), 40, -15, 80, y, -60); isClassHoverExp(monkHover, Mideas.getExpAll(4), 104, -15, 80, y, 0); } public static boolean mouseEvent() throws SQLException { setHoverFalse(); warriorHover = isClassHover(-140, -80); paladinHover = isClassHover(-78, -80); hunterHover = isClassHover(-16, -80); rogueHover = isClassHover(46, -80); priestHover = isClassHover(108, -80); deathknightHover = isClassHover(-140, -13); shamanHover = isClassHover(-78, -13); mageHover= isClassHover(-16, -13); warlockHover = isClassHover(46, -13); monkHover = isClassHover(108, -13); if(Mouse.getEventButtonState()) { if(Mouse.getEventButton() == 0) { setNewClass("Guerrier", ClassManager.getPlayerClone("Guerrier"), warriorHover); setNewClass("Paladin", ClassManager.getPlayerClone("Paladin"), paladinHover); setNewClass("Hunter", ClassManager.getPlayerClone("Hunter"), hunterHover); setNewClass("Rogue", ClassManager.getPlayerClone("Rogue"), rogueHover); setNewClass("Priest", ClassManager.getPlayerClone("Priest"), priestHover); setNewClass("DeathKnight", ClassManager.getPlayerClone("DeathKnight"), deathknightHover); setNewClass("Shaman", ClassManager.getPlayerClone("Shaman"), shamanHover); setNewClass("Mage", ClassManager.getPlayerClone("Mage"), mageHover); setNewClass("Warlock", ClassManager.getPlayerClone("Warlock"), warlockHover); setNewClass("Monk", ClassManager.getPlayerClone("Monk"), monkHover); } } return false; } public static String talentTxt() { if(Mideas.joueur1() != null && !isBagEquipped) { if(Mideas.joueur1().getClasse().equals("Guerrier")) { return "talentGuerrier.txt"; } else if(Mideas.joueur1().getClasse().equals("Paladin")) { return "talentPaladin.txt"; } else if(Mideas.joueur1().getClasse().equals("Hunter")) { return "talentHunter.txt"; } else if(Mideas.joueur1().getClasse().equals("Rogue")) { return "talentRogue.txt"; } else if(Mideas.joueur1().getClasse().equals("Priest")) { return "talentPriest.txt"; } else if(Mideas.joueur1().getClasse().equals("DeathKnight")) { return "talentDeathKnight.txt"; } else if(Mideas.joueur1().getClasse().equals("Shaman")) { return "talentShaman.txt"; } else if(Mideas.joueur1().getClasse().equals("Mage")) { return "talentMage.txt"; } else if(Mideas.joueur1().getClasse().equals("Warlock")) { return "talentWarlock.txt"; } else { return "talentMonk.txt"; } } return null; } private static boolean isClassHover(int x, int y) { if(Mideas.mouseX() >= Display.getWidth()/2+x && Mideas.mouseX() <= Display.getWidth()/2+x+56 && Mideas.mouseY() >= Display.getHeight()/2+y && Mideas.mouseY() <= Display.getHeight()/2+y+56){ return true; } return false; } private static void isClassHoverExp(boolean classHover, float expClass, int x_sprite, int y_sprite, int x_exp_bar, int y_exp_bar, int y_exp_bar_border) { if(classHover) { if(Mideas.getLevelAll((int)expClass) > 1 && Mideas.getLevelAll((int)expClass) < 70) { expClass = (expClass-Mideas.getExpNeeded(Mideas.getLevelAll((int)expClass)-1))/((float)Mideas.getExpNeeded(Mideas.getLevelAll((int)expClass))-Mideas.getExpNeeded(Mideas.getLevelAll((int)expClass)-1)); } else if(Mideas.getLevelAll((int)expClass) == 70) { expClass = 1; } else { expClass = (expClass/Mideas.getExpNeeded(Mideas.getLevelAll((int)expClass))); } if(expClass == 0.0) { Draw.drawColorQuad(Display.getWidth()/2+x_exp_bar, Display.getHeight()+y_exp_bar+y_exp_bar_border, 220, 11, Color.decode("#D418DE")); } else { Draw.drawColorQuad(Display.getWidth()/2+x_exp_bar, Display.getHeight()+y_exp_bar+y_exp_bar_border, 220*expClass, 11, Color.decode("#D418DE")); } Draw.drawQuad(Sprites.hover, Display.getWidth()/2+x_sprite, Display.getHeight()/2+y_sprite); Draw.drawColorQuadBorder(Display.getWidth()/2+x_exp_bar, Display.getHeight()+y_exp_bar+y_exp_bar_border, 220, 12, Color.black); } } private static boolean setNewClass(String string, Joueur joueur, boolean hover) throws SQLException { if(hover) { if(Mideas.joueur1() != null && Mideas.joueur1().getClasse().equals(string)){ Interface.setIsChangeClassActive(true); CharacterStuff.getBagItems(); return true; } if(Mideas.joueur2() != null) { Mideas.joueur2().setStamina(Mideas.joueur2().getMaxStamina()); } Mideas.setJoueur1(joueur); Mideas.getExp(); CharacterStuff.getBagItems(); CharacterStuff.getEquippedItems(); SpellBarManager.loadSpellBar(); Mideas.getGold(); Mideas.getExp(); SpellLevel.setSpellLevelFalse(); Interface.setIsStuffEquipped(false); Interface.setIsStatsCalc(false); Interface.setIsChangeClassActive(true); return true; } return false; } private static void drawExpBar(int exp, int x, int y) { if(Mideas.getLevelAll(exp) == 70) { Draw.drawColorQuad(Display.getWidth()/2+x, Display.getHeight()+y, 220, 11, bgExpBarColor); Draw.drawColorQuad(Display.getWidth()/2+x, Display.getHeight()+y, 220, 11, Color.decode("#680764")); } else if(Mideas.getLevelAll(exp) > 1) { expClass = ((float)exp-(float)Mideas.getExpNeeded(Mideas.getLevelAll(exp)-1))/((float)Mideas.getExpNeeded(Mideas.getLevelAll(exp))-Mideas.getExpNeeded(Mideas.getLevelAll(exp)-1)); Draw.drawColorQuad(Display.getWidth()/2+x, Display.getHeight()+y, 220, 11, bgExpBarColor); Draw.drawColorQuad(Display.getWidth()/2+x, Display.getHeight()+y, 220*expClass, 11, Color.decode("#680764")); } else { expClass = ((float)exp/Mideas.getExpNeeded(Mideas.getLevelAll(exp))); Draw.drawColorQuad(Display.getWidth()/2+x, Display.getHeight()+y, 220, 11, bgExpBarColor); Draw.drawColorQuad(Display.getWidth()/2+x, Display.getHeight()+y, 220*expClass, 11, Color.decode("#680764")); } } private static void drawLevel(int exp, int x, int y) { TTF2.font5.drawStringShadow(Display.getWidth()/2+x, Display.getHeight()+y, String.valueOf(Mideas.getLevelAll(exp)), Color.white, Color.black, 1, 1, 1); } private static void drawBorder(int x, int y, int i) { if(i == 0) { Draw.drawQuad(Sprites.border, Display.getWidth()/2+x, Display.getHeight()/2+y); } else { Draw.drawQuad(Sprites.border2, Display.getWidth()/2+x, Display.getHeight()/2+y); } } private static void drawFrameClass(Texture texture, int x, int y) { Draw.drawQuad(texture, Display.getWidth()/2+x, Display.getHeight()+y); } private static void drawFrameCreateClass(Texture texture, int x, int y) { Draw.drawQuad(texture, Display.getWidth()/2+x, Display.getHeight()/2+y); } public static void setHoverFalse() { warriorHover = false; paladinHover = false; hunterHover = false; rogueHover = false; priestHover = false; deathknightHover = false; shamanHover = false; mageHover = false; warlockHover = false; monkHover = false; }*/ }
package hr.mealpler.client.adapters; import hr.mealpler.client.activities.R; import hr.mealpler.client.activities.FoodActivity; import hr.mealpler.client.activities.ProductInfoActivity; import hr.mealpler.client.activities.ProfileActivity; import hr.mealpler.client.controller.Constants; import hr.mealpler.client.exceptions.HealthBuddyException; import hr.mealpler.database.entities.MenuProductLight; import java.math.BigDecimal; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.jar.Attributes.Name; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.sax.StartElementListener; import android.text.InputType; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.WindowManager; import android.webkit.WebView.FindListener; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; public class ProductListAdapter extends ArrayAdapter<ProductItem> { private Context context; public List<ProductItem> itemList; public List<Long> productIdList = new ArrayList<Long>(); private String menuDateString; private BigDecimal newProductQuantity; private Long userId; private String username, password; public ProductListAdapter(Context c, int layoutResourceId, List<ProductItem> itemList) { super(c, layoutResourceId, itemList); context = c; this.itemList = new ArrayList<ProductItem>(); this.itemList.addAll(itemList); } private class ViewHolder { TextView name, quantity, calories, cholesterol, fiber, protein, carbohydrates, fats; ImageButton infoImageButton, quantityImageButton, deleteImageButton; } @Override public View getView(final int position, View convertView, ViewGroup parent) { productIdList.add(itemList.get(position).getId()); userId = itemList.get(position).getUserId(); username = itemList.get(position).getUsername(); password = itemList.get(position).getPassword(); ViewHolder holder = null; Log.w("ConvertView", String.valueOf(position)); if (convertView == null) { LayoutInflater vi = LayoutInflater.from(context); convertView = vi.inflate(R.layout.item_list_product, null); holder = new ViewHolder(); holder.name = (TextView) convertView.findViewById(R.id.textView1); holder.quantity = (TextView) convertView .findViewById(R.id.textView2); holder.calories = (TextView) convertView .findViewById(R.id.textView4); holder.cholesterol = (TextView) convertView .findViewById(R.id.textView6); holder.fiber = (TextView) convertView.findViewById(R.id.textView8); holder.protein = (TextView) convertView .findViewById(R.id.textView10); holder.carbohydrates = (TextView) convertView .findViewById(R.id.textView12); holder.fats = (TextView) convertView.findViewById(R.id.textView14); convertView.setTag(holder); holder.infoImageButton = (ImageButton) convertView .findViewById(R.id.imageButton1); holder.quantityImageButton = (ImageButton) convertView .findViewById(R.id.imageButton2); holder.deleteImageButton = (ImageButton) convertView .findViewById(R.id.imageButton3); } else { holder = (ViewHolder) convertView.getTag(); } holder.name.setText(itemList.get(position).getName()); holder.quantity.setText("(" + itemList.get(position).getQuantity() + " grams)"); holder.calories.setText(String.valueOf(itemList.get(position) .getCalories()) + " kcal"); holder.cholesterol.setText(String.valueOf(itemList.get(position) .getCholesterol()) + " grams"); holder.fiber.setText(String.valueOf(itemList.get(position).getFiber()) + " grams"); holder.protein.setText(String.valueOf(itemList.get(position) .getProtein()) + " grams"); holder.carbohydrates.setText(String.valueOf(itemList.get(position) .getCarbohydrates()) + " grams"); holder.fats.setText(String.valueOf(itemList.get(position).getFats()) + " grams"); holder.infoImageButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Bundle bundle = new Bundle(); bundle.putLong("productId", productIdList.get(position)); bundle.putLong("userId", userId); bundle.putString("username", username); bundle.putString("password", password); Intent intent = new Intent(context, ProductInfoActivity.class); intent.putExtras(bundle); context.startActivity(intent); } }); holder.quantityImageButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { final EditText input = new EditText(context); input.setInputType(InputType.TYPE_CLASS_NUMBER); Builder builder = new AlertDialog.Builder(context); builder.setTitle("Quantity in grams"); builder.setIcon(R.drawable.icon_edit); builder.setView(input); builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); builder.setNegativeButton("Edit", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); SharedPreferences settings; settings = context.getSharedPreferences("HealthBuddy", 0); menuDateString = settings.getString("menuDate", "error"); Log.w("MENU DATE ADA", menuDateString); newProductQuantity = new BigDecimal(input.getText().toString().trim()); new ProgressTaskAddMenu().execute(position); } }); AlertDialog weightGoalDialog = builder.create(); weightGoalDialog.show(); } }); holder.deleteImageButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { String removeProductWarning = context.getResources().getString( R.string.delete_menu_product); Builder builder = new AlertDialog.Builder(context); builder.setTitle("Warning!"); builder.setMessage(removeProductWarning); builder.setIcon(R.drawable.icon_delete); builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); builder.setNegativeButton("Remove", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); SharedPreferences settings; settings = context.getSharedPreferences("HealthBuddy", 0); menuDateString = settings.getString("menuDate", "error"); new ProgressTaskDeleteMenuProduct().execute(position); } }); AlertDialog weightGoalDialog = builder.create(); weightGoalDialog.show(); } }); return convertView; } private class ProgressTaskAddMenu extends AsyncTask<Integer, Void, String> { private ProgressDialog dialog; private HealthBuddyException e; protected void onPreExecute() { dialog = ProgressDialog.show(context, "", "Editing product quantity..."); } @Override protected void onPostExecute(final String status) { if (dialog.isShowing()) { dialog.dismiss(); } if (status == null) { Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG) .show(); } else if (status.equals("200")) { Toast.makeText(context, "Product edited! Refresh to see new condition.", Toast.LENGTH_LONG).show(); } else { Toast.makeText(context, "Product not added!", Toast.LENGTH_LONG) .show(); } } protected String doInBackground(final Integer... args) { String status = null; DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); java.sql.Date menuDate = null; try { menuDate = new java.sql.Date(df.parse(menuDateString).getTime()); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } MenuProductLight menu = new MenuProductLight(userId, menuDate, productIdList.get(args[0]), newProductQuantity); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); String menuProductLightJSON = gson.toJson(menu); Log.w("MENU UPDATE", menuProductLightJSON); try { do { status = Constants.controller.createMenu( menuProductLightJSON, username, password); } while (status == null); } catch (HealthBuddyException e) { // TODO Auto-generated catch block e.printStackTrace(); this.e = e; } return status; } } private class ProgressTaskDeleteMenuProduct extends AsyncTask<Integer, Void, String> { private ProgressDialog dialog; private HealthBuddyException e; protected void onPreExecute() { dialog = ProgressDialog.show(context, "", "Deleting product from menu..."); } @Override protected void onPostExecute(final String status) { if (dialog.isShowing()) { dialog.dismiss(); } if (status == null) { Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG) .show(); } else if (status.equals("200")) { Toast.makeText(context, "Product deleted! Refresh to see new condition", Toast.LENGTH_LONG).show(); } else { Toast.makeText(context, "Product not deleted!", Toast.LENGTH_LONG) .show(); } } protected String doInBackground(final Integer... args) { String status = null; DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); java.sql.Date menuDate = null; try { menuDate = new java.sql.Date(df.parse(menuDateString).getTime()); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { do { status = Constants.controller.deleteMenuProduct(menuDate, productIdList.get(args[0]), username, password); } while (status == null); } catch (HealthBuddyException e) { // TODO Auto-generated catch block e.printStackTrace(); this.e = e; } return status; } } }
package online.stringtek.toy.framework.toymybatis.parser; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import online.stringtek.toy.framework.toymybatis.handler.SQLHandler; import online.stringtek.toy.framework.toymybatis.io.Resources; import online.stringtek.toy.framework.toymybatis.pojo.BoundSQL; import online.stringtek.toy.framework.toymybatis.pojo.Configuration; import online.stringtek.toy.framework.toymybatis.pojo.MappedStatement; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import javax.sql.DataSource; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; public class ConfigurationParser { public Configuration parse(InputStream in) throws DocumentException { Configuration configuration=new Configuration(); Document document = new SAXReader().read(in); configuration.setDataSource(parseDataSource(document)); configuration.setMappedStatementMap(parseMappedStatement(document)); return configuration; } private Map<String, MappedStatement> parseMappedStatement(Document document) throws DocumentException { Map<String,MappedStatement> mappedStatementMap=new HashMap<>(); Element rootElement=document.getRootElement(); Element mappersElement = rootElement.element("mappers"); List<Element> mapperElementList = mappersElement.elements(); for (Element mapperElement : mapperElementList) { //读取每个mapper String resourcePath = mapperElement.attributeValue("resource"); InputStream resourceAsStream = Resources.getResourceAsStream(resourcePath); mappedStatementMap.putAll(parseMapper(resourceAsStream)); } return mappedStatementMap; } private Map<String,MappedStatement> parseMapper(InputStream in) throws DocumentException { Document document = new SAXReader().read(in); Element rootElement = document.getRootElement(); Map<String,MappedStatement> mappedStatementMap=new HashMap<>(); String namespace = rootElement.attributeValue("namespace"); List<Element> selectElementList = rootElement.elements("select"); for (Element selectElement : selectElementList) { String id = selectElement.attributeValue("id"); String parameterType = selectElement.attributeValue("parameterType"); String resultType = selectElement.attributeValue("resultType"); String sql = selectElement.getTextTrim(); MappedStatement mappedStatement=new MappedStatement(); mappedStatement.setId(namespace+"."+id); mappedStatement.setParameterType(parameterType); mappedStatement.setResultType(resultType); //TODO ${}的情况等 mappedStatement.setBoundSQL(new SQLHandler().handle(sql,"#\\{(.+?)}")); mappedStatementMap.put(namespace+"."+id,mappedStatement); } //TODO delete update insert return mappedStatementMap; } /** * 从配置文件中读取数据源配置信息 * @param document 配置文件 * @return 数据源对象 */ private DataSource parseDataSource(Document document){ Element root = document.getRootElement(); //获取dataSource标签 Element dataSourceElement = root.element("dataSource"); List<Element> dataSourcePropertyElementList = dataSourceElement.elements("property"); Properties properties=new Properties(); for (Element propertyElement : dataSourcePropertyElementList) { properties.put(propertyElement.attributeValue("name"),propertyElement.attributeValue("value")); } HikariDataSource hikariDataSource = new HikariDataSource(); hikariDataSource.setJdbcUrl(properties.getProperty("jdbcUrl")); hikariDataSource.setUsername(properties.getProperty("username")); hikariDataSource.setPassword(properties.getProperty("password")); return hikariDataSource; } }
package com.bowlong.tool; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletOutputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.ui.ModelMap; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import com.alibaba.fastjson.JSON; import com.bowlong.lang.StrEx; import com.bowlong.objpool.StringBufPool; import com.bowlong.text.EncodingEx; import com.bowlong.third.xml.province.entity.XmlCities; import com.bowlong.third.xml.province.entity.XmlCity; import com.bowlong.third.xml.province.entity.XmlProvinces; import com.bowlong.util.DateEx; import com.bowlong.util.ListEx; import com.bowlong.util.MapEx; @SuppressWarnings({ "unchecked", "rawtypes" }) public class TkitJsp extends TkitBase { /*** 转换时间为字符串 **/ static final public Map toBasicMap(Map orign) { if (MapEx.isEmpty(orign)) return orign; Map result = new HashMap(); for (Object key : orign.keySet()) { Object val = orign.get(key); if (val instanceof Date) { val = DateEx.format((Date) val, DateEx.fmt_yyyy_MM_dd_HH_mm_ss); } result.put(key, val); } return result; } /*** 添加消息 **/ static public final Map tipMap(Map map, int result, String msg) { if (MapEx.isEmpty(map)) map = new HashMap(); map.put("msg", msg); map.put("status", result); return map; } /*** 输出文本内容 **/ static public final void writeAndClose(OutputStream out, String content, String chaset) { try { if (StrEx.isEmptyTrim(chaset)) { chaset = EncodingEx.UTF_8; } else { boolean isU = EncodingEx.isSupported(chaset); if (!isU) { chaset = EncodingEx.UTF_8; } } out.write(content.getBytes(chaset)); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } } /*** 输出文本内容 **/ static public final void writeAndClose(HttpServletResponse response, String content, String chaset) { try { if (StrEx.isEmptyTrim(chaset)) { chaset = EncodingEx.UTF_8; } else { boolean isU = EncodingEx.isSupported(chaset); if (!isU) { chaset = EncodingEx.UTF_8; } } response.setCharacterEncoding(chaset); ServletOutputStream out = response.getOutputStream(); writeAndClose(out, content, chaset); } catch (IOException e) { e.printStackTrace(); } } /*** json格式写出map对象 [callfun:为空,就默认方式,不为空,就callFun方式] **/ static public final void writeAndClose(OutputStream out, Map map, String callBackFun) { try { String v = JSON.toJSONString(map); if (!StrEx.isEmptyTrim(callBackFun)) { v = callBackFun + "(" + v + ")"; } writeAndClose(out, v, ""); } catch (Exception e) { e.printStackTrace(); } } /*** json格式写出map对象 **/ static public final void writeAndClose(HttpServletResponse response, Map map, String callBackFun) { try { ServletOutputStream out = response.getOutputStream(); writeAndClose(out, map, callBackFun); } catch (Exception e) { e.printStackTrace(); } } /*** json格式写出map对象 **/ static public final void writeAndClose(OutputStream out, Map map) { writeAndClose(out, map, null); } /*** json格式写出map对象 **/ static public final void writeAndClose(HttpServletResponse response, Map map) { writeAndClose(response, map, null); } /*** 清空httpsession **/ static public final void clearHttpSession(HttpSession session) { clearHttpSession(session, ""); } /*** 清空httpsession **/ static public final void clearHttpSession(HttpSession session, String... excepts) { if (session == null) return; List<String> list = ListEx.toList(excepts); Enumeration names = session.getAttributeNames(); while (names.hasMoreElements()) { Object object = (Object) names.nextElement(); if (ListEx.have(list, object)) continue; session.removeAttribute(object.toString()); } } /*** 添加Cookie的实现 **/ static public final void addCookie(String name, String password, HttpServletResponse response, HttpServletRequest request) throws Exception { if (!StrEx.isEmptyTrim(name) && !StrEx.isEmptyTrim(password)) { // 创建Cookie Cookie nameCookie = new Cookie("name", URLEncoder.encode(name, "utf-8")); Cookie pswCookie = new Cookie("psw", password); // 设置Cookie的父路径 String fpath = request.getContextPath() + "/"; nameCookie.setPath(fpath); pswCookie.setPath(fpath); // 获取是否保存Cookie String rememberMe = request.getParameter("rememberMe"); if (rememberMe == null) {// 不保存Cookie nameCookie.setMaxAge(0); pswCookie.setMaxAge(0); } else { // 保存Cookie的时间长度,单位为秒 int day7 = 7 * 24 * 60 * 60; nameCookie.setMaxAge(day7); pswCookie.setMaxAge(day7); } // 加入Cookie到响应头 response.addCookie(nameCookie); response.addCookie(pswCookie); } } static public final void getCookie(HttpServletRequest request) throws Exception { // <% String name = ""; String psw = ""; String checked = ""; Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { // 遍历Cookie for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; // 此处类似与Map有name和value两个字段,name相等才赋值,并处理编码问题 if ("name".equals(cookie.getName())) { name = URLDecoder.decode(cookie.getValue(), "utf-8"); // 将"记住我"设置为勾选 checked = "checked"; } if ("psw".equals(cookie.getName())) { psw = cookie.getValue(); } } } System.out.println("name=" + name + ",pwd=" + psw + ",checked=" + checked); // %> } /*** 上传图片demo **/ static public void upload(HttpServletRequest request, MultipartHttpServletRequest fileRequest, HttpServletResponse response) { String pathDir = ""; /** 得到图片保存目录的真实路径 **/ String logoRealPathDir = request.getSession().getServletContext() .getRealPath(pathDir); /** 根据真实路径创建目录 **/ File logoSaveFile = new File(logoRealPathDir); if (!logoSaveFile.exists()) logoSaveFile.mkdirs(); /** 页面控件的文件流 **/ MultipartFile multipartFile = fileRequest.getFile("img2Upload"); /** 获取文件的后缀 **/ System.out.println(multipartFile.getOriginalFilename()); String suffix = multipartFile.getOriginalFilename().substring( multipartFile.getOriginalFilename().lastIndexOf(".")); /** 拼成完整的文件保存路径加文件 **/ String name = +System.currentTimeMillis() + suffix; String fileName = logoRealPathDir + File.separator + name; File file = new File(fileName); try { multipartFile.transferTo(file); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /*** 取得省份 **/ static public final void provinces(String path, ModelMap modelMap) { if (path == null) path = ""; XmlProvinces provinces = XmlProvinces.getEn4JarCache(path); if (provinces != null && !ListEx.isEmpty(provinces.getList())) { modelMap.put("provinces", provinces.getList()); } } /*** 根据省ID,取得该省份拥有的市区 **/ static public final void getCitiesByPid(String path, int pid, ModelMap modelMap) { if (path == null) path = ""; List<XmlCity> list = XmlCities.getList4Jar(path, pid); if (!ListEx.isEmpty(list)) { modelMap.put("cities", list); } } static final boolean isNullUnknownIP(String ip) { if (StrEx.isEmptyTrim(ip)) return true; return "unknown".equalsIgnoreCase(ip); } /** * 获取客户端[使用者]真实的IP<br/> * 如果使用了反向代理request.getRemoteAddr()获取的地址就不是客户端的真实IP * * @return 客户端真实IP地址,如:202.65.16.220 */ static public final String getVisitorIP(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (isNullUnknownIP(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (isNullUnknownIP(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (isNullUnknownIP(ip)) { ip = request.getRemoteAddr(); } return ip; } /** * 获取项目的IP地址<br> * * @return 协议://服务器名称:Web应用的端口号 <br/> * 如:http://127.0.0.1:81 */ static public final String getUrlIP(HttpServletRequest request) { StringBuffer buff = StringBufPool.borrowObject(); try { // 取得协议,如:http buff.append(request.getScheme()); buff.append("://"); // 取得您的服务器名称,如:127.0.0.1 buff.append(request.getServerName()); buff.append(":"); // 取得web应用的端口号,如:tomcat默认8080端口 buff.append(request.getServerPort()); return buff.toString(); } catch (Exception e) { } finally { StringBufPool.returnObject(buff); } return ""; } /** * 获取项目的IP+项目名称 * * @return 协议://服务器名称:Web应用的端口号/Context路径 <br/> * 如:http://127.0.0.1:81/项目名称 */ static public final String getUrlIPProject(HttpServletRequest request) { return getUrlIP(request).concat(request.getContextPath()); } }
package ru.itis.javalab.services; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import ru.itis.javalab.dto.UserSignInForm; import ru.itis.javalab.models.User; import ru.itis.javalab.models.UserCookie; import ru.itis.javalab.repositories.CookieRepository; import ru.itis.javalab.repositories.UserRepository; import ru.itis.javalab.utils.Cookies; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import java.util.Optional; import java.util.UUID; /** * created: 21-02-2021 - 14:12 * project: SemesterWork * * @author dinar * @version v0.1 */ @Service public class SignInServiceImpl implements SignInService { private final UserRepository userRepository; private final PasswordEncoder passwordEncoder; private final CookieRepository cookieRepository; public SignInServiceImpl(UserRepository userRepository, PasswordEncoder passwordEncoder, CookieRepository cookieRepository) { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; this.cookieRepository = cookieRepository; } @Override public User login(UserSignInForm userSignInForm) { Optional<User> optionalUser = userRepository .findByLogin(userSignInForm.getLogin()); if (optionalUser.isPresent()) { User user = optionalUser.get(); if (passwordEncoder.matches(userSignInForm.getPassword(), user.getPassword())){ return user; } } return null; } @Override public void rememberUser(User user, HttpServletResponse response) { String sessionId; do { sessionId = UUID.randomUUID().toString(); } while (cookieRepository.getBySessionId(sessionId).isPresent()); UserCookie userCookie = UserCookie.builder() .user(user) .sessionId(sessionId) .build(); cookieRepository.save(userCookie); Cookie cookie = new Cookie(Cookies.SESSION_ID.value, sessionId); cookie.setPath("/"); cookie.setMaxAge(60 * 60 * 24 * 365); } }
package com.lowes.lowesapp.rest.response; /** * Created by George on 1/23/2016. */ public class Breadcrumbs { private String nValue; private String name; public String getNValue () { return nValue; } public void setNValue (String nValue) { this.nValue = nValue; } public String getName () { return name; } public void setName (String name) { this.name = name; } @Override public String toString() { return "ClassPojo [nValue = "+nValue+", name = "+name+"]"; } }
package Client; import Client.Services.*; import Client.Services.Enums.*; import Client.Services.Enums.Help.*; public class MainClass { public static void main (String[] args) { AllExpenses all = new AllExpenses(); System.out.println("OUTPUT 1"); all.displayData(all.listOfWorker()); System.out.println("OUTPUT2"); all.createExpenses(); double to = all.totalBenefits(all.listOfWorker()); System.out.println("OUTPUT 3"); System.out.println("The sum of all salaries paid was"+to); System.out.println("The total operating expenses were"+all.getRecurringExpenses()); System.out.println("The total of all expenses were"+all.getTotalExpenses()); } }
package com.fleet.remote.shell; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @author April Han */ @SpringBootApplication public class RemoteShellApplication { public static void main(String[] args) { SpringApplication.run(RemoteShellApplication.class, args); } }
package sistema; /** * Aggregate.java * <p> * An interface for an aggregate. * * @author Sara Martino * * @param <E> The type of elements contained in this aggregate */ public interface Aggregate<E> { /** * Returns an iterator. * @return the iterator. */ public MyIterator<E> getIterator(); }
package com.modthemod.mtmspout; import java.io.File; import java.util.logging.Logger; import org.spout.api.Engine; import com.modthemod.api.platform.FileHierarchy; import com.modthemod.api.platform.Platform; public class SpoutPlatform implements Platform { private final ModTheModSpout plugin; private final Engine engine; private final FileHierarchy hierarchy; public SpoutPlatform(ModTheModSpout plugin) { this.plugin = plugin; this.engine = plugin.getGame(); File rootFolder = new File("./mtm"); rootFolder.mkdirs(); hierarchy = new SpoutFileHierarchy(rootFolder); } @Override public String getName() { return "spout"; } @Override public String getVersion() { return engine.getVersion(); } @Override public Logger getLogger() { return plugin.getLogger(); } @Override public FileHierarchy getFileHierarchy() { return hierarchy; } }
class Solution { public int uniqueMorseRepresentations(String[] words) { String[] morse = new String[] {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; Set<String> transformations = new HashSet<>(); for(int i = 0; i < words.length; i++){ StringBuilder wordToMorse = new StringBuilder(); for(char c : words[i].toCharArray()){ wordToMorse.append(morse[c - 'a']); } transformations.add(wordToMorse.toString()); } return transformations.size(); } }
package gil.action; import bol.BOLObject; import bol.utils.Case; import dal.DALObject; import gil.MainFrame; import gil.utils.DialogBox; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; public class ExportToDataBase implements ActionListener { private BOLObject obj; private MainFrame frame; private DALObject DBAccess; public ExportToDataBase(BOLObject obj, MainFrame frame) { this.obj = obj; this.frame = frame; } @Override public void actionPerformed(ActionEvent e) { DBAccess = new DALObject(); String name = ""; do { name = new DialogBox(frame).getText(); } while (!(name != null && !name.isEmpty() && !name.trim().isEmpty())); int TabTailleX = obj.getUpdatedTab().getX(); int TabTailleY = obj.getUpdatedTab().getY(); int actualStep = obj.getStep().getActualStepNumber(); int StepTotal = obj.getStep().getStepNumber(); String SaveString = ""; Case[][] temp = obj.getUpdatedTab().getTab(); for (int j = 0; j < temp[0].length; j++) { for (int i = 0; i < temp.length; i++) { SaveString += i + "," + j + "," + temp[i][j].toString() + ";"; } } JOptionPane.showMessageDialog(frame, "Le programme va faire un sauvegarde de la grille actuelle !", "Information", JOptionPane.INFORMATION_MESSAGE); try { DBAccess.insertSave(name, TabTailleX, TabTailleY, StepTotal, actualStep, SaveString); } catch (SQLException ex) { Logger.getLogger(ExportToDataBase.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(frame, "Une erreur est survenue lors de l'enregistrement !\nRéesssayez plus tard", "Erreur d'enregistrement", JOptionPane.ERROR_MESSAGE); } finally { DBAccess.closeConnection(); } DBAccess.closeConnection(); } }
package com.supconit.kqfx.web.fxzf.msg.services.Impl; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.supconit.honeycomb.business.authorization.entities.Role; import com.supconit.honeycomb.business.authorization.services.RoleService; import com.supconit.kqfx.web.fxzf.msg.daos.MsgDao; import com.supconit.kqfx.web.fxzf.msg.entities.Msg; import com.supconit.kqfx.web.fxzf.msg.services.MsgService; import com.supconit.kqfx.web.fxzf.msg.services.PushMsgFlagService; import com.supconit.kqfx.web.xtgl.entities.ExtUser; import com.supconit.kqfx.web.xtgl.services.ExtUserService; @Service("taizhou_offsite_enforcement_msg_service") public class MsgServiceImpl implements MsgService { @Autowired private MsgDao msgDao; @Autowired private ExtUserService extUserService; @Autowired private PushMsgFlagService pushMsgFlagService; @Autowired private RoleService roleService; @Value("${msg.hour}") private String msgHour; /*告警有效小时时间*/ @Value("${msg.min}") private String msgMin; /*告警有效期分钟*/ @Value("${android.apiKey}") private String apiKeyAndroid; ; /*手机端对应应用的KEY*/ @Value("${android.secretKey}") private String secretKeyAndroid; ; /*手机端对应应用的KEY*/ @Value("${ios.apiKey}") private String apiKeyIos; ; /*手机端对应应用的KEY*/ @Value("${ios.secretKey}") private String secretKeyIos; ; /*手机端对应应用的KEY*/ @Value("${device.android}") private String android; /*安卓手机类型*/ @Value("${device.ios}") private String ios; /*苹果手机类型*/ private transient static final Logger logger = LoggerFactory.getLogger(MsgServiceImpl.class); @Override public Msg getById(String arg0) { // TODO Auto-generated method stub return null; } @Override public void save(Msg arg0) { // TODO Auto-generated method stub } @Override public void insert(Msg entity) { msgDao.insert(entity); } @Override public void update(Msg entity) { // TODO Auto-generated method stub } @Override public void delete(Msg entity) { msgDao.delete(entity); } @Override public void insertWarnInfo(String pid, String flag, Date updateTime, String content,String jgid) { //根据告警或公告的JGID来获取对应的告警或公告要发送的用户 List<String> userId = getWebUserId(jgid); //告警信息设置有效期 Calendar calendar = Calendar.getInstance(); calendar.setTime(updateTime); calendar.add(Calendar.HOUR, Integer.valueOf(msgHour)); calendar.add(Calendar.MINUTE, Integer.valueOf(msgMin)); Date usefulDate = calendar.getTime(); List<Msg> msgs = new ArrayList<Msg>(); for(String iid : userId){ Msg obj = new Msg(); obj.setId("W_"+pid); obj.setFlag(flag); obj.setContent(content); obj.setUserId(iid); obj.setJgid(jgid); obj.setPid(pid); obj.setUpdateTime(usefulDate); obj.setUpdateTime(updateTime); obj.setUsefuldateTime(usefulDate); msgs.add(obj); } //批处理插入 msgDao.batchInert(msgs); } /** * 根据JGID获取找到的userid,WEB添加告警和公告信息的时候,添加上对应的JGID和超级管理员管理关联的信息 * 便于在进行添加用户的时候,可以将相应的信息关联到该用户中 * @param jgid * @return */ public List<String> getWebUserId(String jgid){ String[] jgids = jgid.split(","); List<String> userId = new ArrayList<String>(); for(int i=0;i<jgids.length ; i++){ List<ExtUser> userJgbh = extUserService.getUserIdByJgbh(Long.valueOf(jgids[i])); if(!CollectionUtils.isEmpty(userJgbh)){ //用户非空将用户信息插入 for(ExtUser user: userJgbh){ userId.add(String.valueOf(user.getId())); } } //将告警和警告信息添加到对应的角色中,用于添加新的用户或切换用户是获取未结束的告警或警告信息 userId.add(jgids[i]); } //添加超级管理员角色,用户添加新的超级管理员时获取未结束的告警或警告信息 userId.add("133_134"); //根据超级管理员角色获取所有对应的用户 Role admin = roleService.getByCode("ROLE_ADMIN"); List<ExtUser> userRole = extUserService.getUserIdByRoleId(admin.getId()); if(!CollectionUtils.isEmpty(userRole)){ for(ExtUser user: userRole){ if(!userId.contains(String.valueOf(user.getId()))){ userId.add(String.valueOf(user.getId())); } } } return userId; } /** * 根据JGID获取找到的userid,仅获取与该jgid关联的用户和超级管理员用户,用于手机消息推送 * @param jgid * @return */ public List<String> getAppUserId(String jgid){ String[] jgids = jgid.split(","); List<String> userId = new ArrayList<String>(); for(int i=0;i<jgids.length ; i++){ List<ExtUser> userJgbh = extUserService.getUserIdByJgbh(Long.valueOf(jgids[i])); if(!CollectionUtils.isEmpty(userJgbh)){ //用户非空将用户信息插入 for(ExtUser user: userJgbh){ userId.add(String.valueOf(user.getId())); } } } //根据超级管理员角色获取所有对应的用户 Role admin = roleService.getByCode("ROLE_ADMIN"); List<ExtUser> userRole = extUserService.getUserIdByRoleId(admin.getId()); if(!CollectionUtils.isEmpty(userRole)){ for(ExtUser user: userRole){ if(!userId.contains(String.valueOf(user.getId()))){ userId.add(String.valueOf(user.getId())); } } } return userId; } /** * 根据ID删除对应的信息 */ @Override public void deleteById(String id) { msgDao.deleteById(id); } @Override public void inserNotifyInfo(String pid, String flag, Date updateTime, Date usefulDate, String content, String jgid) { List<String> userId = getWebUserId(jgid); List<Msg> msgs = new ArrayList<Msg>(); for(String iid : userId){ Msg obj = new Msg(); obj.setId("N_"+pid); obj.setFlag(flag); obj.setContent(content); obj.setUserId(iid); obj.setJgid(jgid); obj.setPid(pid); obj.setUpdateTime(usefulDate); obj.setUpdateTime(updateTime); obj.setUsefuldateTime(usefulDate); msgs.add(obj); } //批处理插入 msgDao.batchInert(msgs); } @Override public List<Msg> getByUserId(String id) { // TODO Auto-generated method stub return msgDao.getByUserId(id); } @Override public void deleteByUsefulDate(Msg condition) { msgDao.deleteByUsefulDate(condition); } @Override public void deleteByUserId(Msg msg) { msgDao.deleteByUserId(msg); } }
package de.raidcraft.skillsandeffects.pvp.skills.magical; import com.sk89q.minecraft.util.commands.CommandContext; import de.raidcraft.skills.api.combat.EffectElement; import de.raidcraft.skills.api.combat.EffectType; import de.raidcraft.skills.api.exceptions.CombatException; import de.raidcraft.skills.api.hero.Hero; import de.raidcraft.skills.api.persistance.SkillProperties; import de.raidcraft.skills.api.profession.Profession; import de.raidcraft.skills.api.skill.AbstractSkill; import de.raidcraft.skills.api.skill.SkillInformation; import de.raidcraft.skills.api.trigger.CommandTriggered; import de.raidcraft.skills.tables.THeroSkill; import de.raidcraft.skillsandeffects.pvp.effects.debuff.FlamestrikeEffect; /** * @author Silthus */ @SkillInformation( name = "Flamestrike", description = "Verursacht Feuerschaden und nachhaltige Verbrennungen.", types = {EffectType.MAGICAL, EffectType.DAMAGING, EffectType.SILENCABLE}, elements = {EffectElement.FIRE} ) public class Flamestrike extends AbstractSkill implements CommandTriggered { public Flamestrike(Hero hero, SkillProperties data, Profession profession, THeroSkill database) { super(hero, data, profession, database); } @Override public void runCommand(CommandContext args) throws CombatException { magicalAttack(getTarget(), getTotalDamage(), attack -> addEffect(attack.getTarget(), FlamestrikeEffect.class)).run(); } }
package be.appfoundry.templateexample.ui.detail; import be.appfoundry.core.di.ActivityScope; import be.appfoundry.core.di.ApplicationComponent; import dagger.Component; @ActivityScope @Component(dependencies = ApplicationComponent.class) interface DetailComponent extends DetailContract.Component<DetailContract.MvpView, DetailPresenter> { }
package cd.com.a.bo; public interface PrdOrderService { }
package com.skh.hkhr.util.image; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader; import com.skh.hkhr.util.log.PrintLog; import com.squareup.picasso.Transformation; import timber.log.Timber; /*** * @DEV #SamiranKumar11 * @Created by Samiran on 23/06/2021. */ public class ScaleRoundedTransformation implements Transformation { private final int margin; private final int radius; private final int maxWidth; private final int maxHeight; public String key() { return "rounded"; } public ScaleRoundedTransformation(int maxWidth, int maxHeight, int radius, int margin) { this.maxWidth = maxWidth; this.maxHeight = maxHeight; this.radius = radius; this.margin = margin; } public Bitmap transform(Bitmap source) { int targetWidth, targetHeight; double aspectRatio; PrintLog.print("==================================="); PrintLog.print("Width:" + source.getWidth()); PrintLog.print("Height:" + source.getHeight()); if (source.getWidth() > source.getHeight()) { targetWidth = maxWidth; aspectRatio = (double) source.getHeight() / (double) source.getWidth(); targetHeight = (int) (targetWidth * aspectRatio); } else { targetHeight = maxHeight; aspectRatio = (double) source.getWidth() / (double) source.getHeight(); targetWidth = (int) (targetHeight * aspectRatio); } Bitmap bitmap = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, true); if (bitmap != source) { source.recycle(); } Paint paint = new Paint(); paint.setAntiAlias(true); paint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)); Bitmap createBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(createBitmap); int margin = this.margin; RectF rectF = new RectF((float) margin, (float) margin, (float) (bitmap.getWidth() - this.margin), (float) (bitmap.getHeight() - this.margin)); int radius = this.radius; canvas.drawRoundRect(rectF, (float) radius, (float) radius, paint); if (bitmap != createBitmap) { bitmap.recycle(); } PrintLog.print("Width:" + createBitmap.getWidth()); PrintLog.print("Height:" + createBitmap.getHeight()); PrintLog.print("==================================="); return createBitmap; } }
package com.tencent.mm.plugin.appbrand.game.a; import com.tencent.mm.plugin.appbrand.app.e; import com.tencent.mm.plugin.appbrand.appusage.k; import com.tencent.mm.sdk.e.j.a; import com.tencent.mm.sdk.e.l; import com.tencent.mm.sdk.platformtools.x; import java.util.ArrayList; import java.util.List; class i$2 implements a { i$2() { } public final void a(String str, l lVar) { x.i("MicroMsg.SearchMiniGameQueryLogic", "AppBrandUsage storage change: event=%s | eventData=%s", new Object[]{str, lVar}); k sQ; List<String> list; List arrayList; switch (lVar.fBN) { case 2: case 3: if (!"batch".equals(str)) { sQ = i.sQ(lVar.obj.toString()); if (sQ != null) { e.abo().a(i.b(sQ), true); return; } return; } else if (lVar.obj != null && (lVar.obj instanceof List)) { list = (List) lVar.obj; arrayList = new ArrayList(); for (String sQ2 : list) { sQ = i.sQ(sQ2); if (sQ != null) { arrayList.add(i.b(sQ)); } } e.abo().d(arrayList, true); return; } else { return; } case 5: if (!"batch".equals(str)) { e.abo().U(lVar.obj.toString(), true); return; } else if (lVar.obj != null && (lVar.obj instanceof List)) { list = (List) lVar.obj; arrayList = new ArrayList(); for (String sQ22 : list) { sQ = i.sQ(sQ22); if (sQ != null) { com.tencent.mm.plugin.appbrand.game.a.a.a b = i.b(sQ); if (b != null) { arrayList.add(b.dfX); } } } e.abo().an(arrayList); return; } else { return; } default: return; } } }
package mk.petrovski.weathergurumvp.data.remote.helper.error; /** * Created by Nikola Petrovski on 2/22/2017. */ public class InternetConnectionException extends Throwable { }
package com.tencent.mm.plugin.offline.ui; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import com.tencent.mm.g.a.gg; import com.tencent.mm.sdk.b.a; class WalletOfflineCoinPurseUI$33 implements OnMenuItemClickListener { final /* synthetic */ WalletOfflineCoinPurseUI lMe; WalletOfflineCoinPurseUI$33(WalletOfflineCoinPurseUI walletOfflineCoinPurseUI) { this.lMe = walletOfflineCoinPurseUI; } public final boolean onMenuItemClick(MenuItem menuItem) { gg ggVar = new gg(); ggVar.bPt.bPu = "ok"; a.sFg.m(ggVar); if (WalletOfflineCoinPurseUI.c(this.lMe) == 8) { com.tencent.mm.plugin.offline.c.a.Jl(this.lMe.getIntent().getStringExtra("key_appid")); } this.lMe.finish(); return false; } }
package ua.nure.timoshenko.summaryTask4.web.command.all; import org.apache.log4j.Logger; import ua.nure.timoshenko.summaryTask4.Path; import ua.nure.timoshenko.summaryTask4.web.command.Command; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Logout command. * * @author L.Timoshenko * */ public class LogoutCommand extends Command { private static final long serialVersionUID = -5834484888825715763L; private static final Logger LOG = Logger.getLogger(LogoutCommand.class); @Override public String execute(HttpServletRequest request,HttpServletResponse response) { LOG.debug("Command starts"); HttpSession session = request.getSession(false); if (session != null) { session.invalidate(); } LOG.debug("Command finished"); return Path.PAGE_LOGIN; } }
package com.tencent.mm.plugin.game.gamewebview.ipc; import android.os.Message; import android.os.Messenger; import android.os.Parcel; import android.os.Parcelable; import android.os.Process; import com.tencent.mm.sdk.platformtools.x; import java.util.HashSet; import java.util.Set; public abstract class GWMainProcessTask implements Parcelable { private static final Set<Object> fEi = new HashSet(); String fEl = (Process.myPid() + hashCode()); Messenger fEz; public abstract void aai(); public void aaj() { } public void g(Parcel parcel) { } public void writeToParcel(Parcel parcel, int i) { } public int describeContents() { return 0; } public final boolean ahH() { if (this.fEz == null) { return false; } Message obtain = Message.obtain(); obtain.setData(GameWebViewMainProcessService.a(this, false)); try { this.fEz.send(obtain); return true; } catch (Exception e) { x.e("MicroMsg.GWMainProcessTask", e.getMessage()); return false; } } public final void ahA() { fEi.add(this); } public final void ahB() { fEi.remove(this); } }
package util.evaluator; import enums.Operation; import org.junit.Test; import static org.junit.Assert.*; public class ArithmeticEvalTest { @Test public void test_willOverFlowTrue(){ int a,b; // addition a = Integer.MAX_VALUE; b= Integer.MAX_VALUE; assertTrue(ArithmeticEval.willOverFlow(a,b, Operation.ADD)); a = Integer.MIN_VALUE; b= Integer.MIN_VALUE; assertTrue(ArithmeticEval.willOverFlow(a,b, Operation.ADD)); // subtraction a = Integer.MAX_VALUE; b= Integer.MIN_VALUE; assertTrue(ArithmeticEval.willOverFlow(a,b, Operation.SUBTRACT)); a = Integer.MIN_VALUE; b= Integer.MAX_VALUE; assertTrue(ArithmeticEval.willOverFlow(a,b, Operation.SUBTRACT)); // multiplication a = Integer.MAX_VALUE; b= Integer.MAX_VALUE; assertTrue(ArithmeticEval.willOverFlow(a,b, Operation.MULTIPLY)); a = Integer.MIN_VALUE; b= Integer.MIN_VALUE; assertTrue(ArithmeticEval.willOverFlow(a,b, Operation.MULTIPLY)); a = Integer.MAX_VALUE; b= Integer.MIN_VALUE; assertTrue(ArithmeticEval.willOverFlow(a,b, Operation.MULTIPLY)); } @Test public void test_willOverFlowFalse(){ int a,b; // addition a = Integer.MAX_VALUE; b= 0; assertFalse(ArithmeticEval.willOverFlow(a,b, Operation.ADD)); a = Integer.MIN_VALUE; b= 0; assertFalse(ArithmeticEval.willOverFlow(a,b, Operation.ADD)); // subtraction a = 0; b= Integer.MAX_VALUE; assertFalse(ArithmeticEval.willOverFlow(a,b, Operation.SUBTRACT)); a = 0; b= Integer.MAX_VALUE; assertFalse(ArithmeticEval.willOverFlow(a,b, Operation.SUBTRACT)); // multiplication a = Integer.MAX_VALUE; b= 1; assertFalse(ArithmeticEval.willOverFlow(a,b, Operation.MULTIPLY)); a = Integer.MIN_VALUE; b= 1; assertFalse(ArithmeticEval.willOverFlow(a,b, Operation.MULTIPLY)); } }
package game.base.data; /** * 各个模块转化的基本data * @author zoodoz * create date 2018/6/20 */ public abstract class PlayerBaseData { }
package Model; interface BuyComputer{ void buyCom(); } class Real implements BuyComputer{ @Override public void buyCom() { System.out.println("buy computer"); } } class Proxy implements BuyComputer{ private BuyComputer buyComputer; public Proxy(BuyComputer buyComputer){ this.buyComputer = buyComputer; } public void produce(){ System.out.println("1、生产电脑"); } public void after(){ System.out.println("3、售后"); } @Override public void buyCom() { this.produce(); this.buyComputer.buyCom(); this.after(); } } class Factory{ public static BuyComputer getInstance(){ return new Proxy(new Real()); } } public class AgencyModel { }
package leetcode_easy; public class Question_693 { public boolean hasAlternatingBits(int n) { boolean hasAlternatingBits = true; int expect_lsb = ((1 & n) == 1) ? 0 : 1; n = n >> 1; while (n > 0) { int lsb = 1 & n; if (expect_lsb != lsb) { hasAlternatingBits = false; break; } expect_lsb = ((1 & n) == 1) ? 0 : 1; n = n >> 1; } return hasAlternatingBits; } public void solve() { System.out.println(hasAlternatingBits(10)); } }
package com.arkaces.aces_marketplace_api.error; import lombok.Data; @Data public class FieldError { private String field; private String code; private String message; private Object[] messageArguments; }
package com.tencent.tencentmap.mapsdk.a; public final class jt extends mf { static byte[] h; public String a = ""; public int b = 0; public int c = 0; public int d = 0; public int e = 0; public byte[] f = null; public String g = ""; public final void writeTo(me meVar) { meVar.a(this.a, 0); meVar.a(this.b, 1); meVar.a(this.c, 2); meVar.a(this.d, 3); meVar.a(this.e, 4); if (this.f != null) { meVar.a(this.f, 5); } if (this.g != null) { meVar.a(this.g, 6); } } static { byte[] bArr = new byte[1]; h = bArr; bArr[0] = (byte) 0; } public final void readFrom(md mdVar) { this.a = mdVar.a(0, true); this.b = mdVar.a(this.b, 1, true); this.c = mdVar.a(this.c, 2, false); this.d = mdVar.a(this.d, 3, false); this.e = mdVar.a(this.e, 4, false); this.f = mdVar.a(h, 5, false); this.g = mdVar.a(6, false); } }
package mainmenu; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.layout.*; import javafx.stage.Stage; import newgame.ButtonHandlerNewGame; import newgame.TeamsList; import java.io.FileInputStream; public class ButtonOneHandlerObject extends ButtonHandler{ private Stage primaryStage; public void buttonOneObject() { // create a input stream try { ButtonHandlerNewGame bnw = new ButtonHandlerNewGame(); ButtonHandler bh = new ButtonHandler(); TeamsList teamsList = new TeamsList(); bnw.groupStyle(); bnw.raffleStyle(); bh.button5(); // when button is pressed bnw.setScene(primaryStage); bnw.groups.setOnAction(bnw.eventGroups); bnw.raffle.setOnAction(bnw.eventRaffle); bh.setScene(primaryStage); bh.button5.setOnAction(bh.event5); root = new Pane(); root.getChildren().addAll(bh.button5, bnw.groups, bnw.raffle, teamsList.printDatabase1()); // create a scene Scene scene = new Scene(root, 1650, 928); FileInputStream inputBackground = new FileInputStream("C:\\Users\\Asus\\WorldCupSimulator\\src\\main\\resources\\teams.jpg"); // create a image Image image = new Image(inputBackground); // create a background image BackgroundImage backgroundimage = new BackgroundImage(image, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, BackgroundSize.DEFAULT); // create Background Background background = new Background(backgroundimage); // set background root.setBackground(background); //set the scene primaryStage.setScene(scene); primaryStage.show(); } catch (Exception r) { r.printStackTrace(); } } public void setScene(Stage primaryStage){ this.primaryStage = primaryStage; } }
package de.davelee.trams.customer.rest.controllers; import de.davelee.trams.customer.api.CustomerFeedbackModel; import de.davelee.trams.customer.data.CustomerFeedback; import de.davelee.trams.customer.services.CustomerFeedbackService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RequestBody; import java.util.regex.Pattern; @RestController @Api(value="customer", description="Customer Interaction Operations") @RequestMapping(value="/customer") /** * This class contains the REST endpoints for customer feedback which at the moment is a single method to post feedback. * @author Dave Lee */ public class CustomerInteractionRestController { @Autowired private CustomerFeedbackService customerFeedbackService; @ApiOperation(value = "Send customer feedback", notes="Method to submit customer feedback to transport operator.") @RequestMapping(method = RequestMethod.POST, produces="text/plain", value="/feedback") @ResponseBody @ApiResponses(value = {@ApiResponse(code=201,message="Successfully submitted feedback to database"), @ApiResponse(code=500,message="Database not available")}) /** * Save the supplied feedback into the system and return an appropriate http status code as follows: * 201 - data stored successfully, 400 - validation failed, 500 - data could not be saved because of database problems. * @param feedbackModel a <code>CustomerFeedbackModel</code> object containg the data to store. * @return a <code>ResponseEntity</code> object with the appropriate http status code. */ public ResponseEntity<Void> feedback (@RequestBody final CustomerFeedbackModel feedbackModel ) { if (!validateInput(feedbackModel) ) { return ResponseEntity.badRequest().build(); } else if ( customerFeedbackService.addCustomerFeedback(convertToCustomerFeedback(feedbackModel)) != null ) { return ResponseEntity.status(HttpStatus.CREATED).build(); } else { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } /** * Validate the supplied data based on the following validation rules: * title, first name, surname, email address and telephone number are required. * Email address must be in form: text"AT"server.domainExtension * @param customerFeedbackModel a <code>CustomerFeedbackModel</code> object to validate. * @return a <code>boolean</code> which is true iff the input is correct. */ public boolean validateInput ( final CustomerFeedbackModel customerFeedbackModel ) { if ( isFieldEmpty(customerFeedbackModel.getTitle()) ) { return false; } else if ( isFieldEmpty(customerFeedbackModel.getFirstName()) ) { return false; } else if ( isFieldEmpty(customerFeedbackModel.getSurname()) ) { return false; } else if ( isFieldEmpty(customerFeedbackModel.getEmailAddress()) ) { return false; } else if ( isFieldEmpty(customerFeedbackModel.getTelephoneNumber()) ) { return false; } return (Pattern.matches(".*@.*[.]?.*$", customerFeedbackModel.getEmailAddress())); } /** * Private helper method to check if a field value is either null or empty. * @param fieldValue a <code>String</code> with the field value to check. * @return a <code>boolean</code> which is true iff the fieldValue is not empty. */ private boolean isFieldEmpty ( final String fieldValue ) { return fieldValue == null || fieldValue.isEmpty(); } /** * Private helper method to convert a CustomerFeedbackModel object to a CustomerFeedback object which can * be stored in the database. * @param customerFeedbackModel a <code>CustomerFeedbackModel</code> object to convert. * @return a <code>CustomerFeedback</code> object which can be stored in the database. */ private CustomerFeedback convertToCustomerFeedback ( final CustomerFeedbackModel customerFeedbackModel ) { CustomerFeedback customerFeedback = new CustomerFeedback(); customerFeedback.setAddress(customerFeedbackModel.getAddress()); customerFeedback.setExtraInfos(customerFeedbackModel.getExtraInfos()); customerFeedback.setEmailAddress(customerFeedbackModel.getEmailAddress()); customerFeedback.setFirstName(customerFeedbackModel.getFirstName()); customerFeedback.setMessage(customerFeedbackModel.getMessage()); customerFeedback.setSurname(customerFeedbackModel.getSurname()); customerFeedback.setTelephoneNumber(customerFeedbackModel.getTelephoneNumber()); customerFeedback.setTitle(customerFeedbackModel.getTitle()); return customerFeedback; } }
package com.seemoreinteractive.seemoreinteractive; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.webkit.WebView; import android.widget.ImageView; import android.widget.Toast; import com.google.analytics.tracking.android.EasyTracker; import com.seemoreinteractive.seemoreinteractive.helper.Common; public class OptionsShowWebsiteUrls extends Activity { public boolean isBackPressed = false; final Context context = this; String className =this.getClass().getSimpleName(); @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_website_urls); try{ //findViewById(R.id.imgvBtnCart).setVisibility(View.INVISIBLE); findViewById(R.id.closetProgressBar).setVisibility(View.VISIBLE); //new Common().showDrawableImageFromAquery(this, R.id.progressBar1, R.id.imgvBtnCart); ImageView imgBtnCart = (ImageView) findViewById(R.id.imgvBtnCart); imgBtnCart.setImageAlpha(0); Intent getIntVals = getIntent(); //new Common().pageHeaderTitle(OptionsShowWebsiteUrls.this, getIntVals.getStringExtra("headTitle")); new Common().clientLogoOrTitleWithThemeColorAndBgImgByPassingColor( this, Common.sessionClientBgColor, Common.sessionClientBackgroundLightColor, Common.sessionClientBackgroundDarkColor, Common.sessionClientLogo, getIntVals.getStringExtra("headTitle"), ""); WebView webview = (WebView)findViewById(R.id.webView1); webview.getSettings().setJavaScriptEnabled(true); if(getIntVals.getExtras()!=null){ //txtHeadTitle.setText(getIntVals.getStringExtra("headTitle")); webview.loadUrl(getIntVals.getStringExtra("redirectToWebsiteUrl")); } new Common().clickingOnBackButtonWithAnimation(OptionsShowWebsiteUrls.this, OptionsAbout.class,"0"); findViewById(R.id.closetProgressBar).setVisibility(View.INVISIBLE); String screenName = "/web/"+getIntVals.getStringExtra("headTitle")+"/?url="+getIntVals.getStringExtra("redirectToWebsiteUrl"); String productIds = ""; String offerIds = ""; Common.sendJsonWithAQuery(this, ""+Common.sessionIdForUserLoggedIn, screenName, productIds, offerIds); } catch (Exception ex) { Toast.makeText(getApplicationContext(), "Error: Show website urls onCreate.", Toast.LENGTH_LONG).show(); ex.printStackTrace(); String errorMsg = className+" | onStart | " +ex.getMessage(); Common.sendCrashWithAQuery(OptionsShowWebsiteUrls.this,errorMsg); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { try{ if (keyCode == KeyEvent.KEYCODE_BACK) { //Log.i("Press Back", "BACK PRESSED EVENT"); onBackPressed(); isBackPressed = true; } // Call super code so we dont limit default interaction return super.onKeyDown(keyCode, event); } catch (Exception ex) { Toast.makeText(getApplicationContext(), "Error: Show website urls onKeyDown.", Toast.LENGTH_LONG).show(); String errorMsg = className+" | onKeyDown | " +ex.getMessage(); Common.sendCrashWithAQuery(OptionsShowWebsiteUrls.this,errorMsg); return false; } } @Override public void onBackPressed() { try{ new Common().clickingOnBackButtonWithAnimationWithBackPressed(this, OptionsAbout.class, "0"); } catch (Exception ex) { Toast.makeText(getApplicationContext(), "Error: Show website urls onBackPressed.", Toast.LENGTH_LONG).show(); String errorMsg = className+" | onBackPressed | " +ex.getMessage(); Common.sendCrashWithAQuery(OptionsShowWebsiteUrls.this,errorMsg); } return; } @Override public void onStart() { try{ super.onStart(); EasyTracker.getInstance(this).activityStart(this); // Add this method. }catch(Exception e){ e.printStackTrace(); String errorMsg = className+" | onStart | " +e.getMessage(); Common.sendCrashWithAQuery(OptionsShowWebsiteUrls.this,errorMsg); } } @Override public void onStop() { try{ super.onStop(); EasyTracker.getInstance(this).activityStop(this); // Add this method. }catch(Exception e){ e.printStackTrace(); String errorMsg = className+" | onStop | " +e.getMessage(); Common.sendCrashWithAQuery(OptionsShowWebsiteUrls.this,errorMsg); } } }
package com.infotec.registro; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import java.io.IOException; import java.io.InputStream; public class MetricaRepo { Connection con = null; public MetricaRepo(){ /* String urldb="jdbc:mariadb://localhost:3306/ctldoc"; String usrname="root"; String paswd="rootiptv"; String urldb="jdbc:mariadb://172.17.0.3:3306/ctldoc"; String usrname="crlconn"; String paswd="welcome1"; */ Properties prop= new Properties(); String propFilename="config.properties"; String urldb=""; String usrname=""; String paswd=""; InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFilename); if (inputStream != null) { try { prop.load(inputStream); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } urldb= prop.getProperty("db"); usrname= prop.getProperty("usr"); paswd= prop.getProperty("pwd"); try { Class.forName("org.mariadb.jdbc.Driver"); con = DriverManager.getConnection(urldb, usrname, paswd); System.out.println("Conexion exitosa"); } catch (SQLException | ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e); } } public Metrica getMetrica( int idUsuario) { Metrica m = new Metrica(); String sql; sql="Select ctldoc.metricas.* from ctldoc.metricas where metricas.idUsuario="+ Integer.toString(idUsuario); try { Statement st=con.createStatement(); ResultSet rs=st.executeQuery(sql); while (rs.next()) { m.setIdUsuario(rs.getInt("idUsuario")); m.setAsignado(rs.getInt("asignado")); m.setAtendido(rs.getInt("atendido")); m.setCancelado(rs.getInt("cancelado")); m.setCreado(rs.getInt("creado")); m.setTerminado(rs.getInt("terminado")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e); } return m; } public void create(Metrica metrica) { /* Paso 1 crea el evento */ String sql="insert into ctldoc.metricas (idUsuario,creado,asignado,atendido,terminado,cancelado) values (?,?,?,?,?,?)"; try { PreparedStatement st=con.prepareStatement(sql); st.setInt (1, metrica.getIdUsuario() ); st.setInt (2, metrica.getCreado()); st.setInt(3, metrica.getAsignado() ); st.setInt(4, metrica.getAtendido() ); st.setInt(5, metrica.getTerminado() ); st.setInt(6, metrica.getCancelado() ); st.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e); } } public void update(Metrica metrica) { String sql=""; sql="update ctldoc.metricas set creado=?, asignado=?, atendido=?, terminado=?, cancelado=? where idUsuario=?"; try { PreparedStatement st=con.prepareStatement(sql); st.setInt(1, metrica.getCreado() ); st.setInt(2, metrica.getAsignado() ); st.setInt(3, metrica.getAtendido() ); st.setInt(4, metrica.getTerminado() ); st.setInt(5, metrica.getCancelado() ); st.setInt(6, metrica.getIdUsuario() ); st.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e); } } }
/* * 2012-3 Red Hat Inc. and/or its affiliates and other contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.overlord.rtgov.activity.collector; import java.util.Stack; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import javax.transaction.Synchronization; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import org.overlord.commons.services.ServiceClose; import org.overlord.commons.services.ServiceInit; import org.overlord.commons.services.ServiceListener; import org.overlord.commons.services.ServiceRegistryUtil; import org.overlord.rtgov.activity.model.ActivityType; import org.overlord.rtgov.activity.model.ActivityUnit; import org.overlord.rtgov.activity.model.Origin; import org.overlord.rtgov.activity.processor.InformationProcessorManager; import org.overlord.rtgov.activity.validator.ActivityValidatorManager; import org.overlord.rtgov.common.util.RTGovProperties; /** * This class provides an abstract implementation of the activity * collector interface. * */ public abstract class AbstractActivityCollector implements ActivityCollector, AbstractActivityCollectorMBean { private static final Logger LOG=Logger.getLogger(AbstractActivityCollector.class.getName()); private static final boolean DEFAULT_COLLECTION_ENABLED=true; private Boolean _enabled; private CollectorContext _collectorContext=null; private ActivityUnitLogger _activityLogger=null; private InformationProcessorManager _infoProcessorManager=null; private ActivityValidatorManager _activityValidatorManager=null; private ThreadLocalStack<ActivityUnit> _activityUnit = new ThreadLocalStack<ActivityUnit>(); class ThreadLocalStack<T> { private java.lang.ThreadLocal<java.util.Stack<T>> _threadLocalStack = new ThreadLocal<java.util.Stack<T>>(); public T get() { Stack<T> stack = _threadLocalStack.get(); if (stack == null || stack.isEmpty()) { return null; } return stack.peek(); } public void set(T value) { Stack<T> stack = _threadLocalStack.get(); if (stack == null) { _threadLocalStack.set(new Stack<T>()); stack = _threadLocalStack.get(); } stack.push(value); } public void remove() { Stack<T> stack = _threadLocalStack.get(); if (stack == null) { return; } stack.pop(); } } /** * The default constructor. */ public AbstractActivityCollector() { _enabled = RTGovProperties.getPropertyAsBoolean("ActivityCollector.enabled", DEFAULT_COLLECTION_ENABLED); } /** * Initialize the activity collector. */ @ServiceInit public void init() { if (_infoProcessorManager == null) { ServiceRegistryUtil.addServiceListener(InformationProcessorManager.class, new ServiceListener<InformationProcessorManager>() { @Override public void registered(InformationProcessorManager service) { setInformationProcessorManager(service); } @Override public void unregistered(InformationProcessorManager service) { setInformationProcessorManager(null); } }); } if (_activityValidatorManager == null) { ServiceRegistryUtil.addServiceListener(ActivityValidatorManager.class, new ServiceListener<ActivityValidatorManager>() { @Override public void registered(ActivityValidatorManager service) { setActivityValidatorManager(service); } @Override public void unregistered(ActivityValidatorManager service) { setActivityValidatorManager(null); } }); } if (_collectorContext == null) { ServiceRegistryUtil.addServiceListener(CollectorContext.class, new ServiceListener<CollectorContext>() { @Override public void registered(CollectorContext service) { setCollectorContext(service); } @Override public void unregistered(CollectorContext service) { setCollectorContext(null); } }); } if (_activityLogger == null) { ServiceRegistryUtil.addServiceListener(ActivityUnitLogger.class, new ServiceListener<ActivityUnitLogger>() { @Override public void registered(ActivityUnitLogger service) { setActivityUnitLogger(service); } @Override public void unregistered(ActivityUnitLogger service) { setActivityUnitLogger(null); } }); } } /** * This method sets the collector context. * * @param cc The collector context */ public void setCollectorContext(CollectorContext cc) { _collectorContext = cc; } /** * This method gets the collector context. * * @return The collector context */ public CollectorContext getCollectorContext() { return (_collectorContext); } /** * This method indicates whether activity collection is * currently enabled. * * @return Whether collection is enabled */ public boolean isCollectionEnabled() { return (_enabled == null ? DEFAULT_COLLECTION_ENABLED : _enabled); } /** * This method identifies whether the collection process should be * enabled. * * @return Whether enabled */ public boolean getCollectionEnabled() { return (isCollectionEnabled()); } /** * This method sets whether the collection process should be * enabled. * * @param enabled Whether enabled */ public void setCollectionEnabled(boolean enabled) { _enabled = enabled; } /** * This method sets the activity logger. * * @param activityLogger The activity logger */ public void setActivityUnitLogger(ActivityUnitLogger activityLogger) { _activityLogger = activityLogger; } /** * This method gets the activity logger. * * @return The activity logger */ public ActivityUnitLogger getActivityUnitLogger() { return (_activityLogger); } /** * This method gets the information processor manager. * * @return The information processor manager */ public InformationProcessorManager getInformationProcessorManager() { return (_infoProcessorManager); } /** * This method sets the information processor manager. * * @param ipm The information processor manager */ public void setInformationProcessorManager(InformationProcessorManager ipm) { _infoProcessorManager = ipm; } /** * This method gets the activity validator manager. * * @return The activity validator manager */ public ActivityValidatorManager getActivityValidatorManager() { return (_activityValidatorManager); } /** * This method sets the activity validator manager. * * @param aim The activity validator manager */ public void setActivityValidatorManager(ActivityValidatorManager aim) { _activityValidatorManager = aim; } /** * This method generates a unique transaction id. * * @return The transaction id */ protected String createTransactionId() { return (UUID.randomUUID().toString()); } /** * This method returns the current date/time. * * @return The timestamp */ protected long getTimestamp() { return (System.currentTimeMillis()); } /** * {@inheritDoc} */ public void startScope() { if (!isCollectionEnabled()) { return; } ActivityUnit au=_activityUnit.get(); if (au != null) { if (LOG.isLoggable(Level.FINEST)) { LOG.finest("Starting nested scope"); } } startScope(createActivityUnit()); } /** * {@inheritDoc} */ public boolean isScopeActive() { return (_activityUnit.get() != null); } /** * This method starts the scope associated with the supplied activity unit. * * @param au The activity unit */ protected void startScope(ActivityUnit au) { if (LOG.isLoggable(Level.FINEST)) { LOG.finest("Start scope"); } _activityUnit.set(au); } /** * This method creates a new activity unit and * initializes its origin based on the template * supplied by the OriginInitializer, if * available. * * @return The new activity unit */ protected ActivityUnit createActivityUnit() { ActivityUnit ret=new ActivityUnit(); Origin origin=new Origin(); origin.setHost(_collectorContext.getHost()); origin.setNode(_collectorContext.getNode()); origin.setThread(Thread.currentThread().getName()); ret.setOrigin(origin); return (ret); } /** * {@inheritDoc} */ public void endScope() { if (!isCollectionEnabled()) { return; } ActivityUnit au=_activityUnit.get(); if (LOG.isLoggable(Level.FINEST)) { LOG.finest("End scope for: "+au); } if (au != null) { _activityLogger.log(au); _activityUnit.remove(); } else { LOG.severe(java.util.PropertyResourceBundle.getBundle( "activity.Messages").getString("ACTIVITY-1")); } } /** * {@inheritDoc} */ public String processInformation(String processor, String type, Object info, java.util.Map<String, Object> headers, ActivityType actType) { if (_infoProcessorManager != null) { return (_infoProcessorManager.process(processor, type, info, headers, actType)); } else if (LOG.isLoggable(Level.WARNING)) { LOG.warning("Information processor manager not specified: " +"unable to process type '"+type+"' info: "+info); } return (null); } /** * {@inheritDoc} */ public void validate(ActivityType actType) throws Exception { // Check if activity is of interest to validators if (_activityValidatorManager != null) { _activityValidatorManager.validate(actType); } } /** * {@inheritDoc} */ public void record(ActivityType actType) { if (!isCollectionEnabled()) { return; } ActivityUnit au=_activityUnit.get(); // Check if need to create a single event activity unit outside of transaction scope boolean transactional=true; if (au == null) { au = createActivityUnit(); TransactionManager tm=_collectorContext.getTransactionManager(); if (tm != null) { try { Transaction txn=tm.getTransaction(); if (txn != null) { txn.registerSynchronization( new Synchronization() { public void afterCompletion(int arg0) { endScope(); } public void beforeCompletion() { } }); startScope(au); } else { if (LOG.isLoggable(Level.FINEST)) { LOG.finest("No transaction available"); } transactional = false; } } catch (Exception e) { LOG.log(Level.SEVERE, java.util.PropertyResourceBundle.getBundle( "activity.Messages").getString("ACTIVITY-2"), e); transactional = false; } } else { if (LOG.isLoggable(Level.FINEST)) { LOG.finest("No transaction manager available"); } transactional = false; } } // Set/override timestamp actType.setTimestamp(getTimestamp()); au.getActivityTypes().add(actType); if (!transactional) { _activityLogger.log(au); } } /** * This method closes the activity collector. */ @ServiceClose public void close() { } }
package com.tencent.mm.plugin.sns.ui; import android.app.Dialog; import android.content.Context; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.TextView; import com.tencent.mm.plugin.sns.i.f; import com.tencent.mm.plugin.sns.i.g; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.base.k; import com.tencent.mm.ui.base.l; import com.tencent.mm.ui.base.m; import com.tencent.mm.ui.base.n$c; import com.tencent.mm.ui.base.n.d; import java.util.HashMap; public final class ba implements OnItemClickListener { private LayoutInflater Bc; private Context mContext; private k ofo; n$c ofp; d ofq; private l ofr; private a ofs; private HashMap<Integer, CharSequence> oft = new HashMap(); private HashMap<Integer, Integer> ofu = new HashMap(); private class a extends BaseAdapter { private a() { } /* synthetic */ a(ba baVar, byte b) { this(); } public final int getCount() { return ba.this.ofr.size(); } public final Object getItem(int i) { return null; } public final long getItemId(int i) { return 0; } public final View getView(int i, View view, ViewGroup viewGroup) { a aVar; if (view == null) { view = ba.this.Bc.inflate(g.sns_timeline_list_menu_item, viewGroup, false); aVar = new a(this, (byte) 0); aVar.eGX = (TextView) view.findViewById(f.title); aVar.ofw = (TextView) view.findViewById(f.right_hint); view.setTag(aVar); } else { aVar = (a) view.getTag(); } MenuItem item = ba.this.ofr.getItem(i); aVar.eGX.setText(item.getTitle()); if (ba.this.oft.get(Integer.valueOf(item.getItemId())) != null) { aVar.ofw.setText((CharSequence) ba.this.oft.get(Integer.valueOf(item.getItemId()))); aVar.ofw.setVisibility(0); } else { aVar.ofw.setVisibility(4); } if (ba.this.ofu.get(Integer.valueOf(item.getItemId())) != null) { aVar.ofw.setTextColor(((Integer) ba.this.ofu.get(Integer.valueOf(item.getItemId()))).intValue()); } return view; } } public ba(Context context) { this.mContext = context; this.Bc = LayoutInflater.from(context); this.ofo = new k(context); this.ofr = new l(context); } public final void c(int i, CharSequence charSequence) { this.oft.put(Integer.valueOf(i), charSequence); } public final void onItemClick(AdapterView<?> adapterView, View view, int i, long j) { m mVar = (m) this.ofr.twb.get(i); if (mVar.performClick()) { x.i("MicroMsg.SnsTimelineListMenu", "onItemClick menu item has listener"); dismiss(); return; } if (this.ofq != null) { this.ofq.onMMMenuItemSelected(mVar, i); } dismiss(); } private void dismiss() { if (this.ofo.isShowing()) { this.ofo.dismiss(); } } public final Dialog bEo() { if (this.ofp != null) { this.ofr.clear(); this.ofr = new l(this.mContext); this.ofp.a(this.ofr); } if (this.ofr.crF()) { x.w("MicroMsg.SnsTimelineListMenu", "show, menu empty"); return null; } if (this.ofs == null) { this.ofs = new a(this, (byte) 0); } this.ofo.hAv = this.ofs; this.ofo.qRL = this; this.ofo.setTitle(this.ofr.Io); this.ofo.show(); return this.ofo; } }
package com.sobey.exportExcel; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.sobey.exportExcel.model.ExcelModel; @RunWith(SpringRunner.class) @SpringBootTest public class NMexportExcelApplicationTests { @Test public void contextLoads() { // /Users/lijunhong/Desktop/NMExportExcel ExcelModel excelModel = new ExcelModel("1.xls","/Users/lijunhong/Desktop/NMExportExcel"); excelModel.createExcelTableHeader(); } }
package edu.wayne.cs.severe.redress2.entity; /** * @author ojcchar * @version 1.0 * @created 23-Mar-2014 12:28:48 */ public class Refactoring { public Refactoring() { } public void finalize() throws Throwable { } /** * @param classQName */ public double getLOC(String classQName) { return 0; } /** * @param classQName */ public double getPredLOC(String classQName) { return 0; } }// end Refactoring
/* * 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 org.sudrf.dao; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jsoup.nodes.Node; /** * * @author Kalinin Maksim */ public class Attributes { private static final Map<Integer, String> regionsCodes = new HashMap<Integer, String>(); static { regionsCodes.put(1, "Республика Адыгея (Адыгея)"); regionsCodes.put(2, "Республика Башкортостан"); regionsCodes.put(3, "Республика Бурятия"); regionsCodes.put(4, "Республика Алтай"); regionsCodes.put(5, "Республика Дагестан"); regionsCodes.put(6, "Республика Ингушетия"); regionsCodes.put(7, "Кабардино-Балкарская Республика"); regionsCodes.put(8, "Республика Калмыкия"); regionsCodes.put(9, "Карачаево-Черкесская Республика"); regionsCodes.put(10, "Республика Карелия"); regionsCodes.put(11, "Республика Коми"); regionsCodes.put(12, "Республика Марий Эл"); regionsCodes.put(13, "Республика Мордовия"); regionsCodes.put(14, "Республика Саха (Якутия)"); regionsCodes.put(15, "Республика Северная Осетия-Алания"); regionsCodes.put(16, "Республика Татарстан"); regionsCodes.put(17, "Республика Тыва"); regionsCodes.put(18, "Удмуртская Республика"); regionsCodes.put(19, "Республика Хакасия"); regionsCodes.put(20, "Чеченская Республика"); regionsCodes.put(21, "Чувашская Республика-Чувашия"); regionsCodes.put(22, "Алтайский край"); regionsCodes.put(23, "Краснодарский край"); regionsCodes.put(24, "Красноярский край"); regionsCodes.put(25, "Приморский край"); regionsCodes.put(26, "Ставропольский край"); regionsCodes.put(27, "Хабаровский край"); regionsCodes.put(28, "Амурская область"); regionsCodes.put(29, "Архангельская область"); regionsCodes.put(30, "Астраханская область"); regionsCodes.put(31, "Белгородская область"); regionsCodes.put(32, "Брянская область"); regionsCodes.put(33, "Владимирская область"); regionsCodes.put(34, "Волгоградская область"); regionsCodes.put(35, "Вологодская область"); regionsCodes.put(36, "Воронежская область"); regionsCodes.put(37, "Ивановская область"); regionsCodes.put(38, "Иркутская область"); regionsCodes.put(39, "Калининградская область"); regionsCodes.put(40, "Калужская область"); regionsCodes.put(41, "Камчатский край"); regionsCodes.put(42, "Кемеровская область"); regionsCodes.put(43, "Кировская область"); regionsCodes.put(44, "Костромская область"); regionsCodes.put(45, "Курганская область"); regionsCodes.put(46, "Курская область"); regionsCodes.put(47, "Ленинградская область"); regionsCodes.put(48, "Липецкая область"); regionsCodes.put(49, "Магаданская область"); regionsCodes.put(50, "Московская область"); regionsCodes.put(51, "Мурманская область"); regionsCodes.put(52, "Нижегородская область"); regionsCodes.put(53, "Новгородская область"); regionsCodes.put(54, "Новосибирская область"); regionsCodes.put(55, "Омская область"); regionsCodes.put(56, "Оренбургская область"); regionsCodes.put(57, "Орловская область"); regionsCodes.put(58, "Пензенская область"); regionsCodes.put(59, "Пермский край"); regionsCodes.put(60, "Псковская область"); regionsCodes.put(61, "Ростовская область"); regionsCodes.put(62, "Рязанская область"); regionsCodes.put(63, "Самарская область"); regionsCodes.put(64, "Саратовская область"); regionsCodes.put(65, "Сахалинская область"); regionsCodes.put(66, "Свердловская область"); regionsCodes.put(67, "Смоленская область"); regionsCodes.put(68, "Тамбовская область"); regionsCodes.put(69, "Тверская область"); regionsCodes.put(70, "Томская область"); regionsCodes.put(71, "Тульская область"); regionsCodes.put(72, "Тюменская область"); regionsCodes.put(73, "Ульяновская область"); regionsCodes.put(74, "Челябинская область"); regionsCodes.put(75, "Забайкальский край"); regionsCodes.put(76, "Ярославская область"); regionsCodes.put(77, "Город Москва"); regionsCodes.put(78, "Город Санкт-Петербург"); regionsCodes.put(79, "Еврейская автономная область"); regionsCodes.put(83, "Ненецкий автономный округ"); regionsCodes.put(86, "Ханты-Мансийский автономный округ-Югра"); regionsCodes.put(87, "Чукотский автономный округ"); regionsCodes.put(89, "Ямало-Ненецкий автономный округ"); regionsCodes.put(91, "Республика Крым"); regionsCodes.put(92, "Севастополь"); regionsCodes.put(99, "Иные территории, включая город и космодром Байконур"); regionsCodes.put(9901, "Волго-Вятский округ"); regionsCodes.put(9902, "Восточно-Сибирский округ"); regionsCodes.put(9903, "Дальневосточный округ"); regionsCodes.put(9904, "Еврейская автономная область"); regionsCodes.put(9905, "Западно-Сибирский округ"); regionsCodes.put(9906, "Московский округ"); regionsCodes.put(9907, "Поволжский округ"); regionsCodes.put(9908, "Республика Адыгея"); regionsCodes.put(9909, "Северо-Западный округ"); regionsCodes.put(9910, "Северо-Кавказский округ"); regionsCodes.put(9911, "Уральский округ"); regionsCodes.put(9912, "Центральный округ"); regionsCodes.put(9914, "Город Севастополь"); } public static String getRegionNameByCode(Integer regionCode) { String st = regionsCodes.get(regionCode); if (st != null) { return st; } return "unknow"; } public static Integer getCodeByRegionName(String name) { return regionsCodes.entrySet() .stream() .filter(kv -> kv .getValue() .toLowerCase() .equals(name.toLowerCase())) .map(kv -> kv.getKey()) .findFirst().orElse(-1); } // Suppresses default constructor, ensuring non-instantiability. private Attributes() { } public static void setAttributesOrder(String... names) { for (String name : names) { AttributeImpl.castAndAddNameId(name); } } public static Attribute create(String... keyValue) { return new AttributeImpl(keyValue); } public static Stream<String> asString(Map.Entry<String, Attributes.List> entry) { return Stream.of(entry.getKey(), entry.getValue().toString()); } public interface List extends Collection<Attribute> { public static Attributes.List create() { return new Attributes.ListImpl(); } public String getByName(String region); } public static Iterator<Map.Entry<String, Integer>> attributesNamesItterator() { return AttributeImpl.namesId.entrySet().iterator(); } private static class ListImpl extends ArrayList<Attribute> implements List { public boolean add(Attribute e) { Optional<Attribute> c = stream() .filter(a -> a.getName().equals(e.getName())).findFirst(); if (c.isPresent()) { c.get().setValue(c.get().getValue().concat(", ").concat(e.getValue())); return true; } return super.add(e); } @Override public String toString() { return stream().map(Attribute::toString).collect(Collectors.joining("],[", "[", "]")); } @Override public String getByName(String name) { return stream().filter((t) -> { return name.equals(t.getName()); }).findFirst().orElseThrow(() -> new NullPointerException()).getValue(); } } private static class AttributeImpl implements Attribute { static private final Map<String, Integer> namesId = new HashMap<>(); private final String name; private String value; private AttributeImpl(String... src) { this.name = validName(src[0]); this.value = src[1]; addNameId(this.name); } static String validName(String name) { return name .toLowerCase() .replace(":", "") .replace("-", "") .replace("официальный", "") .trim(); } static private void castAndAddNameId(String name) { addNameId(validName(name)); } static private void addNameId(String name) { String nameValid = validName(name); if (!namesId.containsKey(nameValid)) { synchronized (namesId) { if (!namesId.containsKey(nameValid)) { namesId.put(nameValid, namesId .values() .stream() .max(Integer::compare).map(e -> e + 1) .orElse(0)); } } } } @Override public int getId() { return namesId.get(name); } @Override public String getName() { return name; } @Override public void setValue(String value) { this.value = value; } @Override public String getValue() { return value; } @Override public String toString() { return name.concat(": ").concat(value); } } }
package arrays; // Java program to calculate the maximum // absolute difference of an array. public class MaximumAbsoluteDifference { private static int maxDistance(int[] array) { int min = array[0]; int max = array[0]; int minidx = 1; int maxidx = 1; int maxSum = 0; for (int i = 1; i < array.length; i++) { if (array[i] < min && (Math.abs(max - array[i]) + Math.abs(i + 1 - maxidx)) > maxSum) { // To check whether previous min can contribute to max sum if ((min - array[i]) > (i + 1 - minidx)) { min = array[i]; minidx = i + 1; } maxSum = (Math.abs(max - array[i]) + Math.abs(i + 1 - maxidx)); } else if (array[i] > max && (Math.abs(min - array[i]) + Math.abs(i + 1 - minidx)) > maxSum) { // To check whether previous max can contribute to max sum if ((array[i] - max) > (i + 1 - maxidx)) { max = array[i]; maxidx = i + 1; } maxSum = (Math.abs(min - array[i]) + Math.abs(i + 1 - minidx)); } else if ((Math.abs(min - array[i]) + Math.abs(i + 1 - minidx)) > maxSum) { maxSum = Math.abs(min - array[i]) + Math.abs(i + 1 - minidx); } else if (Math.abs(max - array[i] + Math.abs(i + 1 - maxidx)) > maxSum) { maxSum = Math.abs(max - array[i]) + Math.abs(i + 1 - maxidx); } } return maxSum; } public static void main(String[] args) { int[] array = { -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 }; System.out.println(maxDistance(array)); } }
package io.fab.connector.data; import java.io.Serializable; public class Brand implements Serializable { private static final long serialVersionUID = -5053645053414726365L; private String name; Brand() {} public Brand(final String name) { this.name = name; } public String getName() { return name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (name == null ? 0 : name.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Brand other = (Brand) obj; if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } @Override public String toString() { return "Brand [name=" + name + "]"; } }
package ch.springcloud.lite.core.loadBalance; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import ch.springcloud.lite.core.model.CloudServer; public class RoundRobinLoadBalance implements LoadBalance { class RoundRobinServer { AtomicInteger picknum = new AtomicInteger(); AtomicInteger priority = new AtomicInteger(); } Map<CloudServer, RoundRobinServer> running_servers = new ConcurrentHashMap<>(); @Override public CloudServer pickOne(List<CloudServer> servers) { if (servers.isEmpty()) { return null; } servers = servers.stream().sorted((s1, s2) -> s1.getMeta().getServerid().compareTo(s1.getMeta().getServerid())) .collect(Collectors.toList()); return doPickOne1(servers); } private CloudServer doPickOne1(List<CloudServer> servers) { if (!isCached(servers)) { synchronized (this) { running_servers.clear(); servers.forEach(server -> { RoundRobinServer running_server = new RoundRobinServer(); running_server.priority = new AtomicInteger(server.getMeta().getPriority()); running_servers.put(server, running_server); }); return doPickOne2(servers); } } else { return doPickOne2(servers); } } CloudServer doPickOne2(List<CloudServer> servers) { int minnum = Integer.MAX_VALUE; double minratio = Double.MAX_VALUE; CloudServer minserver = null; for (Entry<CloudServer, RoundRobinServer> entry : running_servers.entrySet()) { RoundRobinServer value = entry.getValue(); int picknum = value.picknum.get(); double ratio = picknum / (double) value.priority.get(); if (ratio < minratio) { minratio = ratio; minnum = picknum; minserver = entry.getKey(); } } if (minserver == null) { return doPickOne1(servers); } RoundRobinServer roundRobinServer = running_servers.get(minserver); if (roundRobinServer == null) { return doPickOne1(servers); } boolean ok = roundRobinServer.picknum.compareAndSet(minnum, minnum + 1); if (ok) { return minserver; } else { return doPickOne1(servers); } } private boolean isCached(List<CloudServer> servers) { if (servers.size() != running_servers.size()) { return false; } for (int i = 0; i < servers.size(); i++) { CloudServer server = servers.get(i); RoundRobinServer running_server = running_servers.get(server); if (running_server == null || (int) running_server.priority.get() != server.getMeta().getPriority()) { return false; } } return true; } }
package com.spqa.wefun.include; public class Const { //"http://api.androidhive.info/volley/string_response.html" public static final String URL_STRING_REQ = "http://192.168.1.114/wefun/v1/newfeeds"; //"http://192.168.1.112/wefun/v1/newfeeds"; }
/* * 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 projectclient; import java.util.List; import java.util.ArrayList; import javax.swing.*; import java.awt.*; import java.awt.event.*; import beans.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Date; import javax.naming.*; import javax.ejb.*; /** * * @author r0614393 */ public class GUI extends JFrame implements ActionListener { private final JLabel lbl; private final DBBean2Remote db; private final Container pane; private final JList comp; private final List<Integer> pcId; public GUI() throws NamingException { //pr = pbean; db = (DBBean2Remote)(new InitialContext().lookup(DBBean2Remote.class.getName())); pane = getContentPane(); FlowLayout layout = new FlowLayout(); //pane.setLayout(layout); List<Object[]> pc = db.getMachinesNaam(); List<String> pcNaam = new ArrayList(); pcId = new ArrayList(); for(Object[] obj : pc) { pcNaam.add(((String)obj[0])); pcId.add((((BigDecimal)obj[1]).intValue())); } lbl = new JLabel("Selecteer computer:"); comp = new JList(pcNaam.toArray()); JButton b = new JButton("Print");//creating instance of JButton b.addActionListener(this); pane.add(lbl, BorderLayout.NORTH); pane.add(comp, BorderLayout.CENTER); pane.add(b, BorderLayout.SOUTH);//adding button in JFrame setDefaultCloseOperation(EXIT_ON_CLOSE); //setSize(400, 100); pack(); setTitle("Overzicht"); setVisible(true);//making the frame visible } @Override public void actionPerformed(ActionEvent e) { List<Object[]> res = db.getResLoginMid(pcId.get(comp.getSelectedIndex())); System.out.println("==============================================================="); for(Object[] obj : res) { Object[] mom = db.getMomRid(((BigDecimal)obj[0]).intValue()); System.out.println("" + ((BigDecimal)obj[0]).toString() + " - " + (String)obj[1] + " - " + ((Date)mom[0]).toString() + " - " + ((BigInteger)mom[1]).toString() + "u"); } System.out.println("==============================================================="); } }
package Array; import java.util.*; //给定一个整数数组和一个数字,求数组中元素组合之和等于该数字的组合,数组中的数字可以重复使用 public class CombinationSum { public static void main(String[] args) { int [] a = {1,1, 4,2,3}; ArrayList<ArrayList<Integer>> res = FindPath(a, 5); for (int i = 0; i < res.size(); i++) { System.out.println(res.get(i)); } System.out.println("---------------------------"); ArrayList<ArrayList<Integer>> res1 = FindPathII(a, 5); for (int i = 0; i < res1.size(); i++) { System.out.println(res1.get(i)); } } //给定一个整数数组和一个数字,求数组中元素组合之和等于该数字的组合,数组中的数字可以重复使用 public static ArrayList<ArrayList<Integer>> FindPath(int[] A, int target){ ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> path = new ArrayList<>(); if (A.length == 0) return res; f(A, 0, 0, target, res, path); return res; } public static void f(int[] A, int pos, int sum, int target, ArrayList<ArrayList<Integer>> res, ArrayList<Integer> path){ if(sum == target){ res.add(new ArrayList<>(path)); return; } if(sum > target) return; for(int i=pos;i<A.length;i++){ path.add(A[i]); f(A,i,sum+A[i],target,res,path); //回溯 path.remove(path.size()-1); } } //给定一个整数数组和一个数字,求数组中元素组合之和等于该数字的组合,数组中的数字不可以重复使用 public static ArrayList<ArrayList<Integer>> FindPathII(int[] A, int target){ ArrayList<ArrayList<Integer>> res = new ArrayList<>(); ArrayList<Integer> path = new ArrayList<>(); if(A.length == 0) return res; f1(A, target, 0, 0, res, path); return res; } public static void f1(int[] A, int target, int pos, int sum, ArrayList<ArrayList<Integer>> res, ArrayList<Integer> path) { if(sum == target) { res.add(new ArrayList<Integer>(path)); return; } if(sum > target) return; for(int i=pos;i<A.length;i++) { path.add(A[i]); f1(A, target, i+1,sum+A[i], res, path); path.remove(path.size()-1); } } }
package martin.s4a.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.ArrayList; import java.util.Calendar; import martin.s4a.library.Database; import martin.s4a.library.SchemeHelper; import martin.s4a.library.ShiftHelper; import martin.s4a.shift4all2.R; import martin.s4a.templates.ShiftTemplates; /** * Created by Martin on 15.2.2015. */ public class StatisticAdapter extends BaseAdapter { Calendar cal; Context context; Database data; ShiftHelper shiftHelper; SchemeHelper schemeHelper; ArrayList<ShiftTemplates> shifts; int[] countOf; public StatisticAdapter(Context context, Calendar cal) { this.cal = cal; cal.set(Calendar.DAY_OF_MONTH, 1); this.context = context; data = new Database(context); shifts = data.getAllShifts(); shiftHelper = new ShiftHelper(data, cal); schemeHelper = new SchemeHelper(data, cal); countOf = new int[shifts.size()]; getStatisticCount(); } @Override public int getCount() { return shifts.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (convertView == null) { // if it's not recycled, initialize some // attributes LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.statistic_item, null); } TextView name = (TextView)v.findViewById(R.id.textView_statistic_item_name); TextView count = (TextView)v.findViewById(R.id.textView_statistic_item_count); name.setText(shifts.get(position).getTitle()); count.setText(String.valueOf(countOf[position])); return v; } public void getStatisticCount() { for(int i = 1; i <= cal.getActualMaximum(Calendar.DAY_OF_MONTH);i++) { cal.set(Calendar.DAY_OF_MONTH, i); shiftHelper.setCalendar(cal); schemeHelper.setCalendar(cal); int shiftForThisDay = -1; if (shiftHelper.getCustomShift() != -1) countOf[shiftHelper.getCustomShift()]++; else { shiftForThisDay = schemeHelper.getShiftForDay(); if(shiftForThisDay != -1) countOf[shiftForThisDay]++; } } } }
package artista; import java.util.*; public class Accounts { private final int userIDNum; private String userName; private String password; private String firstName; private String lastName; private String email; List <Image> Images = new ArrayList<Image>(); //for accounts that are in the database that already have userIDNum. public Accounts(int userID, String un, String pw, String fn, String ln, String email) { this.userIDNum = userID; this.userName = un; this.password = pw; this.firstName = fn; this.lastName = ln; this.email = email; } public int getUserIDNum() { return this.userIDNum; } public String getUserName() { return this.userName; } public String getPassword() { return this.password; } public String getFirstName() { return this.firstName; } public String getLastName() { return this.lastName; } public String getEmail() { return this.email; } public void setUserName(String un) { this.userName = un; } public void setFirstName(String fn) { this.firstName = fn; } public void setLastName(String ln) { this.lastName = ln; } public void setEmail(String email) { this.email = email; } }
/* 1: */ package com.kaldin.questionbank.question.hibernate; /* 2: */ /* 3: */ import com.kaldin.common.util.HibernateUtil; /* 4: */ import com.kaldin.common.util.PagingBean; /* 5: */ import com.kaldin.common.utility.StringUtility; /* 6: */ import com.kaldin.questionbank.answer.dto.AnswerDTO; /* 7: */ import com.kaldin.questionbank.question.dto.ListCounterDTO; /* 8: */ import com.kaldin.questionbank.question.dto.QuestionDTO; /* 9: */ import java.util.ArrayList; /* 10: */ import java.util.Iterator; /* 11: */ import java.util.List; /* 12: */ import org.apache.commons.lang.StringEscapeUtils; /* 13: */ import org.hibernate.Criteria; /* 14: */ import org.hibernate.HibernateException; /* 15: */ import org.hibernate.Query; /* 16: */ import org.hibernate.Session; /* 17: */ import org.hibernate.Transaction; /* 18: */ import org.hibernate.criterion.Restrictions; /* 19: */ /* 20: */ public class QuestionHibernate /* 21: */ { /* 22: */ public List<?> showQuestion(int companyid) /* 23: */ { /* 24: 34 */ Transaction trObj = null; /* 25: 35 */ Session sesObj = null; /* 26: 36 */ List<?> listObj = null; /* 27: */ try /* 28: */ { /* 29: 38 */ sesObj = HibernateUtil.getSession(); /* 30: 39 */ trObj = HibernateUtil.getTrascation(sesObj); /* 31: 40 */ Query qry = sesObj.createQuery("from QuestionDTO qustDTO where qustDTO.companyId=?"); /* 32: 41 */ qry.setParameter(0, Integer.valueOf(companyid)); /* 33: 42 */ listObj = qry.list(); /* 34: 43 */ trObj.commit(); /* 35: */ } /* 36: */ catch (HibernateException e) /* 37: */ { /* 38: 45 */ trObj.rollback(); /* 39: 46 */ e.printStackTrace(); /* 40: */ } /* 41: */ finally /* 42: */ { /* 43: 48 */ sesObj.close(); /* 44: */ } /* 45: 50 */ return listObj; /* 46: */ } /* 47: */ /* 48: */ public List<?> getQuestion(int topicId, int lvlid) /* 49: */ { /* 50: 62 */ Transaction trObj = null; /* 51: 63 */ Session sesObj = null; /* 52: 64 */ List<?> listObj = null; /* 53: */ try /* 54: */ { /* 55: 66 */ sesObj = HibernateUtil.getSession(); /* 56: 67 */ trObj = HibernateUtil.getTrascation(sesObj); /* 57: 68 */ Query query = sesObj.createQuery("from QuestionDTO questdto where questdto.topicid=:tpcid AND questdto.levelid=:levelId"); /* 58: 69 */ query.setInteger("tpcid", topicId); /* 59: 70 */ query.setInteger("levelId", lvlid); /* 60: 71 */ listObj = query.list(); /* 61: 72 */ trObj.commit(); /* 62: */ } /* 63: */ catch (HibernateException e) /* 64: */ { /* 65: 74 */ trObj.rollback(); /* 66: 75 */ e.printStackTrace(); /* 67: */ } /* 68: */ finally /* 69: */ { /* 70: 77 */ sesObj.close(); /* 71: */ } /* 72: 79 */ return listObj; /* 73: */ } /* 74: */ /* 75: */ public List<?> getQuestion(int topicId) /* 76: */ { /* 77: 89 */ Transaction trObj = null; /* 78: 90 */ Session sesObj = null; /* 79: 91 */ List<?> listObj = null; /* 80: */ try /* 81: */ { /* 82: 93 */ sesObj = HibernateUtil.getSession(); /* 83: 94 */ trObj = HibernateUtil.getTrascation(sesObj); /* 84: 95 */ Query query = sesObj.createQuery("from QuestionDTO questdto where questdto.topicid=:tpcid"); /* 85: 96 */ query.setInteger("tpcid", topicId); /* 86: 97 */ listObj = query.list(); /* 87: 98 */ trObj.commit(); /* 88: */ } /* 89: */ catch (HibernateException e) /* 90: */ { /* 91:100 */ trObj.rollback(); /* 92:101 */ e.printStackTrace(); /* 93: */ } /* 94: */ finally /* 95: */ { /* 96:103 */ sesObj.close(); /* 97: */ } /* 98:105 */ return listObj; /* 99: */ } /* 100: */ /* 101: */ public List<?> getQuestionbylevel(int level, int userCompanyId) /* 102: */ { /* 103:115 */ Transaction trObj = null; /* 104:116 */ Session sesObj = null; /* 105:117 */ List<?> listObj = null; /* 106: */ try /* 107: */ { /* 108:119 */ sesObj = HibernateUtil.getSession(); /* 109:120 */ trObj = HibernateUtil.getTrascation(sesObj); /* 110:121 */ Query query = sesObj.createQuery("from QuestionDTO questdto where questdto.levelid=:levelid AND questdto.companyId:companyId"); /* 111:122 */ query.setInteger("levelid", level); /* 112:123 */ query.setInteger("companyId", userCompanyId); /* 113:124 */ listObj = query.list(); /* 114:125 */ trObj.commit(); /* 115: */ } /* 116: */ catch (HibernateException e) /* 117: */ { /* 118:127 */ trObj.rollback(); /* 119:128 */ e.printStackTrace(); /* 120: */ } /* 121: */ finally /* 122: */ { /* 123:130 */ sesObj.close(); /* 124: */ } /* 125:132 */ return listObj; /* 126: */ } /* 127: */ /* 128: */ public List<?> getQuestionbytopic(int topic, int userCompanyId) /* 129: */ { /* 130:136 */ Transaction trObj = null; /* 131:137 */ Session sesObj = null; /* 132:138 */ List<?> listObj = null; /* 133: */ try /* 134: */ { /* 135:140 */ sesObj = HibernateUtil.getSession(); /* 136:141 */ trObj = HibernateUtil.getTrascation(sesObj); /* 137:142 */ Query query = sesObj.createQuery("from QuestionDTO questdto where questdto.topicid=:tpcid AND questdto.companyId:companyId"); /* 138:143 */ query.setInteger("tpcid", topic); /* 139:144 */ query.setInteger("companyId", userCompanyId); /* 140:145 */ listObj = query.list(); /* 141:146 */ trObj.commit(); /* 142: */ } /* 143: */ catch (HibernateException e) /* 144: */ { /* 145:148 */ trObj.rollback(); /* 146:149 */ e.printStackTrace(); /* 147: */ } /* 148: */ finally /* 149: */ { /* 150:151 */ sesObj.close(); /* 151: */ } /* 152:153 */ return listObj; /* 153: */ } /* 154: */ /* 155: */ public List<?> showQuestion(PagingBean pagingBean, int records, int topicId, int levelID, int subjectId, int companyid, String keyword) /* 156: */ { /* 157:165 */ Transaction trObj = null; /* 158:166 */ Session sesObj = null; /* 159:167 */ List<?> listObj = null; /* 160:168 */ List<?> countlistObj = null; /* 161: */ try /* 162: */ { /* 163:170 */ sesObj = HibernateUtil.getSession(); /* 164:171 */ trObj = HibernateUtil.getTrascation(sesObj); /* 165:172 */ Query query = null; /* 166: */ /* 167:174 */ String filterQuery = "from QuestionDTO questdto where "; /* 168:176 */ if (topicId > 0) { /* 169:177 */ filterQuery = filterQuery + " questdto.topicid=:tpcid and "; /* 170: */ } /* 171:179 */ if (levelID > 0) { /* 172:180 */ filterQuery = filterQuery + " questdto.levelid = :levid and "; /* 173: */ } /* 174:183 */ query = sesObj.createQuery(filterQuery + " questdto.subjectId=:subid and questdto.question like :keyword order by questdto.questionid desc "); /* 175:184 */ pagingBean.setCount(records); /* 176:185 */ if (topicId > 0) { /* 177:186 */ query.setInteger("tpcid", topicId); /* 178: */ } /* 179:188 */ if (levelID > 0) { /* 180:189 */ query.setInteger("levid", levelID); /* 181: */ } /* 182:191 */ query.setInteger("subid", subjectId); /* 183: */ /* 184:193 */ query.setParameter("keyword", "%" + keyword + "%"); /* 185: */ /* 186:195 */ countlistObj = query.list(); /* 187:196 */ pagingBean.setCount(countlistObj.size()); /* 188:197 */ query.setFirstResult(pagingBean.getStartRec()); /* 189:198 */ query.setMaxResults(pagingBean.getViewperpage()); /* 190:199 */ listObj = query.list(); /* 191:200 */ trObj.commit(); /* 192: */ } /* 193: */ catch (HibernateException e) /* 194: */ { /* 195:202 */ trObj.rollback(); /* 196:203 */ e.printStackTrace(); /* 197: */ } /* 198: */ finally /* 199: */ { /* 200:205 */ sesObj.close(); /* 201: */ } /* 202:207 */ return listObj; /* 203: */ } /* 204: */ /* 205: */ public int getMCQstatus(QuestionDTO dtoObj) /* 206: */ { /* 207:217 */ Transaction trObj = null; /* 208:218 */ Session sesObj = null; /* 209:219 */ List<?> listObj = null; /* 210: */ try /* 211: */ { /* 212:221 */ sesObj = HibernateUtil.getSession(); /* 213:222 */ trObj = HibernateUtil.getTrascation(sesObj); /* 214:223 */ Query query = sesObj.createQuery("from QuestionDTO questdto where questdto.questionid=:questid"); /* 215:224 */ query.setInteger("questid", dtoObj.getQuestionid()); /* 216:225 */ listObj = query.list(); /* 217:226 */ if (listObj != null) { /* 218:227 */ dtoObj = (QuestionDTO)listObj.iterator().next(); /* 219: */ } /* 220:228 */ trObj.commit(); /* 221: */ } /* 222: */ catch (HibernateException e) /* 223: */ { /* 224:230 */ trObj.rollback(); /* 225:231 */ e.printStackTrace(); /* 226: */ } /* 227: */ finally /* 228: */ { /* 229:233 */ sesObj.close(); /* 230: */ } /* 231:235 */ return dtoObj.getShowAsMCQ(); /* 232: */ } /* 233: */ /* 234: */ public List<?> showQuestion(PagingBean pagingBean, int records, int companyid, String keyword) /* 235: */ { /* 236:246 */ Transaction trObj = null; /* 237:247 */ Session sesObj = null; /* 238:248 */ List<?> listObj = null; /* 239:249 */ List<?> countlistObj = null; /* 240: */ try /* 241: */ { /* 242:251 */ sesObj = HibernateUtil.getSession(); /* 243:252 */ trObj = HibernateUtil.getTrascation(sesObj); /* 244:253 */ Query query = sesObj.createQuery("from QuestionDTO questdto where questdto.companyId=? and questdto.subjectId <> 0 and questdto.question like :keyword order by questdto.questionid desc"); /* 245: */ /* 246:255 */ query.setParameter(0, Integer.valueOf(companyid)); /* 247:256 */ query.setParameter("keyword", "%" + keyword + "%"); /* 248:257 */ countlistObj = query.list(); /* 249:258 */ pagingBean.setCount(countlistObj.size()); /* 250: */ /* 251:260 */ query.setFirstResult(pagingBean.getStartRec()); /* 252:261 */ query.setMaxResults(pagingBean.getViewperpage()); /* 253:262 */ listObj = query.list(); /* 254:263 */ trObj.commit(); /* 255: */ } /* 256: */ catch (HibernateException e) /* 257: */ { /* 258:265 */ trObj.rollback(); /* 259:266 */ e.printStackTrace(); /* 260: */ } /* 261: */ finally /* 262: */ { /* 263:268 */ sesObj.close(); /* 264: */ } /* 265:270 */ return listObj; /* 266: */ } /* 267: */ /* 268: */ public boolean deleteQuestion(QuestionDTO questionObj, int answerid) /* 269: */ { /* 270:282 */ Transaction trObj = null; /* 271: */ /* 272:284 */ Session sesObj = null; /* 273: */ try /* 274: */ { /* 275:287 */ sesObj = HibernateUtil.getSession(); /* 276:288 */ trObj = HibernateUtil.getTrascation(sesObj); /* 277:289 */ AnswerDTO dtoAnswer = (AnswerDTO)sesObj.get(AnswerDTO.class, Integer.valueOf(answerid)); /* 278:290 */ if (answerid != 0) /* 279: */ { /* 280:291 */ sesObj.delete(dtoAnswer); /* 281:292 */ QuestionDTO dtoObj = (QuestionDTO)sesObj.createCriteria(QuestionDTO.class).add(Restrictions.eq("questionid", Integer.valueOf(questionObj.getQuestionid()))).add(Restrictions.eq("companyId", Integer.valueOf(questionObj.getCompanyId()))).uniqueResult(); /* 282: */ /* 283: */ /* 284:295 */ sesObj.delete(dtoObj); /* 285:296 */ trObj.commit(); /* 286: */ } /* 287:298 */ return true; /* 288: */ } /* 289: */ catch (HibernateException e) /* 290: */ { /* 291: */ QuestionDTO dtoObj; /* 292:301 */ trObj.rollback(); /* 293: */ /* 294:303 */ e.printStackTrace(); /* 295:304 */ return false; /* 296: */ } /* 297: */ finally /* 298: */ { /* 299:308 */ sesObj.close(); /* 300: */ } /* 301: */ } /* 302: */ /* 303: */ public boolean saveQuestion(QuestionDTO quesObj) /* 304: */ { /* 305:320 */ Transaction trObj = null; /* 306:321 */ Session sesObj = null; /* 307: */ try /* 308: */ { /* 309:324 */ sesObj = HibernateUtil.getSession(); /* 310:325 */ trObj = HibernateUtil.getTrascation(sesObj); /* 311: */ /* 312:327 */ sesObj.save(quesObj); /* 313: */ /* 314:329 */ trObj.commit(); /* 315:330 */ return true; /* 316: */ } /* 317: */ catch (HibernateException e) /* 318: */ { /* 319:334 */ trObj.rollback(); /* 320:335 */ e.printStackTrace(); /* 321:336 */ return false; /* 322: */ } /* 323: */ finally /* 324: */ { /* 325:338 */ sesObj.close(); /* 326: */ } /* 327: */ } /* 328: */ /* 329: */ public boolean editQuestion(QuestionDTO quesObj) /* 330: */ { /* 331:349 */ Transaction trObj = null; /* 332:350 */ Session sesObj = null; /* 333: */ try /* 334: */ { /* 335:352 */ sesObj = HibernateUtil.getSession(); /* 336:353 */ trObj = HibernateUtil.getTrascation(sesObj); /* 337: */ /* 338:355 */ QuestionDTO dtoObj = (QuestionDTO)sesObj.createCriteria(QuestionDTO.class).add(Restrictions.eq("questionid", Integer.valueOf(quesObj.getQuestionid()))).add(Restrictions.eq("companyId", Integer.valueOf(quesObj.getCompanyId()))).uniqueResult(); /* 339: */ /* 340: */ /* 341: */ /* 342:359 */ dtoObj.setQuestion(quesObj.getQuestion()); /* 343:360 */ dtoObj.setSubjectId(quesObj.getSubjectId()); /* 344:361 */ dtoObj.setTopicid(quesObj.getTopicid()); /* 345:362 */ dtoObj.setLevelid(quesObj.getLevelid()); /* 346:363 */ dtoObj.setShowAsMCQ(quesObj.getShowAsMCQ()); /* 347:364 */ dtoObj.setQuestionHint(("<br>".equals(StringUtility.removeNull(quesObj.getQuestionHint()))) || ("".equals(StringUtility.removeNull(quesObj.getQuestionHint()))) ? "" : quesObj.getQuestionHint()); /* 348:365 */ dtoObj.setQuestiontype(quesObj.getQuestiontype()); /* 349:366 */ dtoObj.setQuestionURL(quesObj.getQuestionURL()); /* 350: */ /* 351:368 */ trObj.commit(); /* 352:369 */ return true; /* 353: */ } /* 354: */ catch (HibernateException e) /* 355: */ { /* 356: */ boolean bool; /* 357:372 */ trObj.rollback(); /* 358: */ /* 359:374 */ e.printStackTrace(); /* 360:375 */ return false; /* 361: */ } /* 362: */ finally /* 363: */ { /* 364:379 */ sesObj.close(); /* 365: */ } /* 366: */ } /* 367: */ /* 368: */ public int getMaxQuestionid() /* 369: */ { /* 370:390 */ int maxQuesionId = 0; /* 371:391 */ Transaction trObj = null; /* 372:392 */ Session sesObj = null; /* 373:393 */ List<?> listObj = null; /* 374:394 */ QuestionDTO questObj = new QuestionDTO(); /* 375: */ try /* 376: */ { /* 377:396 */ sesObj = HibernateUtil.getSession(); /* 378:397 */ trObj = HibernateUtil.getTrascation(sesObj); /* 379:398 */ String sql = "from QuestionDTO qustDTO"; /* 380:399 */ listObj = sesObj.createQuery(sql).list(); /* 381:400 */ Iterator<?> itrObj = listObj.iterator(); /* 382:401 */ while (itrObj.hasNext()) /* 383: */ { /* 384:402 */ questObj = (QuestionDTO)itrObj.next(); /* 385:403 */ maxQuesionId = questObj.getQuestionid(); /* 386: */ } /* 387:405 */ trObj.commit(); /* 388: */ } /* 389: */ catch (HibernateException e) /* 390: */ { /* 391:407 */ trObj.rollback(); /* 392:408 */ e.printStackTrace(); /* 393: */ } /* 394: */ finally /* 395: */ { /* 396:410 */ sesObj.close(); /* 397: */ } /* 398:412 */ return maxQuesionId; /* 399: */ } /* 400: */ /* 401: */ public int getQuestionCount(int companyid) /* 402: */ { /* 403:421 */ int questionCount = 0; /* 404:422 */ Session sesObj = null; /* 405: */ try /* 406: */ { /* 407:424 */ sesObj = HibernateUtil.getSession(); /* 408:425 */ String SQL_QUERY = "SELECT COUNT(questionid) FROM QuestionDTO WHERE companyid = ?"; /* 409:426 */ Query query = sesObj.createQuery(SQL_QUERY); /* 410:427 */ query.setParameter(0, Integer.valueOf(companyid)); /* 411:428 */ Iterator it; for (it = query.iterate(); it.hasNext();) { /* 412:429 */ questionCount = Integer.parseInt(it.next().toString()); /* 413: */ } /* 414: */ } /* 415: */ catch (HibernateException e) /* 416: */ { /* 417: */ Iterator<?> it; /* 418:432 */ e.printStackTrace(); /* 419: */ } /* 420: */ finally /* 421: */ { /* 422:434 */ sesObj.close(); /* 423: */ } /* 424:436 */ return questionCount; /* 425: */ } /* 426: */ /* 427: */ public List<?> getQuestionbySubject(int subjectId, int companyId) /* 428: */ { /* 429:440 */ Transaction trObj = null; /* 430:441 */ Session sesObj = null; /* 431:442 */ List<?> listObj = null; /* 432: */ try /* 433: */ { /* 434:444 */ sesObj = HibernateUtil.getSession(); /* 435:445 */ trObj = HibernateUtil.getTrascation(sesObj); /* 436:446 */ Query query = sesObj.createQuery("from QuestionDTO questdto where questdto.subjectId=:subid AND questdto.companyId=:companyId"); /* 437: */ /* 438:448 */ query.setInteger("subid", subjectId); /* 439:449 */ query.setInteger("companyId", companyId); /* 440:450 */ listObj = query.list(); /* 441:451 */ trObj.commit(); /* 442: */ } /* 443: */ catch (HibernateException e) /* 444: */ { /* 445:453 */ trObj.rollback(); /* 446:454 */ e.printStackTrace(); /* 447: */ } /* 448: */ finally /* 449: */ { /* 450:456 */ sesObj.close(); /* 451: */ } /* 452:458 */ return listObj; /* 453: */ } /* 454: */ /* 455: */ public List<?> showQuestionbySubject(PagingBean pagingBean, int records, int subjectId, int companyid, String keyword) /* 456: */ { /* 457:462 */ Transaction trObj = null; /* 458:463 */ Session sesObj = null; /* 459:464 */ List<?> listObj = null; /* 460:465 */ List<?> countlistObj = null; /* 461: */ try /* 462: */ { /* 463:467 */ sesObj = HibernateUtil.getSession(); /* 464:468 */ trObj = HibernateUtil.getTrascation(sesObj); /* 465:469 */ Query query = sesObj.createQuery("from QuestionDTO questdto where questdto.subjectId=:subid and questdto.question like :keyword"); /* 466: */ /* 467:471 */ query.setInteger("subid", subjectId); /* 468:472 */ query.setParameter("keyword", "%" + keyword + "%"); /* 469:473 */ countlistObj = query.list(); /* 470:474 */ pagingBean.setCount(countlistObj.size()); /* 471:475 */ query.setFirstResult(pagingBean.getStartRec()); /* 472:476 */ query.setMaxResults(pagingBean.getViewperpage()); /* 473:477 */ listObj = query.list(); /* 474:478 */ trObj.commit(); /* 475: */ } /* 476: */ catch (HibernateException e) /* 477: */ { /* 478:480 */ trObj.rollback(); /* 479:481 */ e.printStackTrace(); /* 480: */ } /* 481: */ finally /* 482: */ { /* 483:483 */ sesObj.close(); /* 484: */ } /* 485:485 */ return listObj; /* 486: */ } /* 487: */ /* 488: */ public int getQuestionCountbySubject(int subjectid, int companyid) /* 489: */ { /* 490:489 */ int questionCount = 0; /* 491:490 */ Session sesObj = null; /* 492: */ try /* 493: */ { /* 494:492 */ sesObj = HibernateUtil.getSession(); /* 495:493 */ String SQL_QUERY = "SELECT COUNT(questionid) FROM QuestionDTO WHERE subjectid = ? AND companyid = ?"; /* 496:494 */ Query query = sesObj.createQuery(SQL_QUERY); /* 497:495 */ query.setParameter(0, Integer.valueOf(subjectid)); /* 498:496 */ query.setParameter(1, Integer.valueOf(companyid)); Iterator it; /* 499:497 */ for (it = query.iterate(); it.hasNext();) { /* 500:498 */ questionCount = Integer.parseInt(it.next().toString()); /* 501: */ } /* 502: */ } /* 503: */ catch (HibernateException e) /* 504: */ { /* 505: */ Iterator<?> it; /* 506:501 */ e.printStackTrace(); /* 507: */ } /* 508: */ finally /* 509: */ { /* 510:503 */ sesObj.close(); /* 511: */ } /* 512:505 */ return questionCount; /* 513: */ } /* 514: */ /* 515: */ public int getQuestionCountbyTopic(int topicid, int companyid) /* 516: */ { /* 517:509 */ int questionCount = 0; /* 518:510 */ Session sesObj = null; /* 519: */ try /* 520: */ { /* 521:512 */ sesObj = HibernateUtil.getSession(); /* 522:513 */ String SQL_QUERY = "SELECT COUNT(questionid) FROM QuestionDTO WHERE topicid = ? AND companyid = ?"; /* 523:514 */ Query query = sesObj.createQuery(SQL_QUERY); /* 524:515 */ query.setParameter(0, Integer.valueOf(topicid)); /* 525:516 */ query.setParameter(1, Integer.valueOf(companyid)); Iterator it; /* 526:517 */ for (it = query.iterate(); it.hasNext();) { /* 527:518 */ questionCount = Integer.parseInt(it.next().toString()); /* 528: */ } /* 529: */ } /* 530: */ catch (HibernateException e) /* 531: */ { /* 532: */ Iterator<?> it; /* 533:521 */ e.printStackTrace(); /* 534: */ } /* 535: */ finally /* 536: */ { /* 537:523 */ sesObj.close(); /* 538: */ } /* 539:525 */ return questionCount; /* 540: */ } /* 541: */ /* 542: */ public int getQuestionCountbyLevel(int levelid, int companyid) /* 543: */ { /* 544:529 */ int questionCount = 0; /* 545:530 */ Session sesObj = null; /* 546: */ try /* 547: */ { /* 548:532 */ sesObj = HibernateUtil.getSession(); /* 549:533 */ String SQL_QUERY = "SELECT COUNT(questionid) FROM QuestionDTO WHERE levelid = ? AND companyid = ?"; /* 550:534 */ Query query = sesObj.createQuery(SQL_QUERY); /* 551:535 */ query.setParameter(0, Integer.valueOf(levelid)); /* 552:536 */ query.setParameter(1, Integer.valueOf(companyid)); Iterator it; /* 553:537 */ for (it = query.iterate(); it.hasNext();) { /* 554:538 */ questionCount = Integer.parseInt(it.next().toString()); /* 555: */ } /* 556: */ } /* 557: */ catch (HibernateException e) /* 558: */ { /* 559: */ Iterator<?> it; /* 560:541 */ e.printStackTrace(); /* 561: */ } /* 562: */ finally /* 563: */ { /* 564:543 */ sesObj.close(); /* 565: */ } /* 566:545 */ return questionCount; /* 567: */ } /* 568: */ /* 569: */ public List<ListCounterDTO> getTopicsWithCount(int companyid) /* 570: */ { /* 571:549 */ Transaction trObj = null; /* 572:550 */ Session sesObj = null; /* 573:551 */ List<?> resultList = null; /* 574:552 */ List<ListCounterDTO> listObj = new ArrayList(); /* 575: */ try /* 576: */ { /* 577:554 */ sesObj = HibernateUtil.getSession(); /* 578:555 */ trObj = HibernateUtil.getTrascation(sesObj); /* 579:556 */ Query query = sesObj.createQuery("SELECT t.topicId, t.topicName, count(t.topicId) FROM QuestionDTO q, TopicDTO t where q.companyId = ? and t.topicId = q.topicid group by t.topicId"); /* 580: */ /* 581: */ /* 582:559 */ query.setInteger(0, companyid); /* 583:560 */ resultList = query.list(); /* 584:561 */ Iterator<?> result = resultList.iterator(); /* 585:562 */ while (result.hasNext()) /* 586: */ { /* 587:563 */ ListCounterDTO listCounter = new ListCounterDTO(); /* 588:564 */ Object[] row = (Object[])result.next(); /* 589: */ /* 590:566 */ listCounter.setId(Integer.parseInt(row[0].toString())); /* 591:567 */ listCounter.setName(StringEscapeUtils.escapeHtml(row[1].toString()).replace("'", "\\'")); /* 592:568 */ listCounter.setCount(Integer.parseInt(row[2].toString())); /* 593: */ /* 594:570 */ listObj.add(listCounter); /* 595: */ } /* 596:574 */ trObj.commit(); /* 597: */ } /* 598: */ catch (HibernateException e) /* 599: */ { /* 600:576 */ trObj.rollback(); /* 601:577 */ e.printStackTrace(); /* 602: */ } /* 603: */ finally /* 604: */ { /* 605:579 */ sesObj.close(); /* 606: */ } /* 607:581 */ return listObj; /* 608: */ } /* 609: */ /* 610: */ public List<ListCounterDTO> getSubjectWithCount(int companyid) /* 611: */ { /* 612:585 */ Transaction trObj = null; /* 613:586 */ Session sesObj = null; /* 614:587 */ List<?> resultList = null; /* 615:588 */ List<ListCounterDTO> listObj = new ArrayList(); /* 616: */ try /* 617: */ { /* 618:590 */ sesObj = HibernateUtil.getSession(); /* 619:591 */ trObj = HibernateUtil.getTrascation(sesObj); /* 620:592 */ Query query = sesObj.createQuery("SELECT s.subjectId, s.subjectName, COUNT(s.subjectId) FROM QuestionDTO q, SubjectDTO s WHERE q.companyId = ? AND s.subjectId = q.subjectId GROUP BY s.subjectId"); /* 621: */ /* 622: */ /* 623:595 */ query.setInteger(0, companyid); /* 624:596 */ resultList = query.list(); /* 625:597 */ Iterator<?> result = resultList.iterator(); /* 626:598 */ while (result.hasNext()) /* 627: */ { /* 628:599 */ ListCounterDTO listCounter = new ListCounterDTO(); /* 629:600 */ Object[] row = (Object[])result.next(); /* 630: */ /* 631:602 */ listCounter.setId(Integer.parseInt(row[0].toString())); /* 632:603 */ listCounter.setName(StringEscapeUtils.escapeHtml(row[1].toString()).replace("'", "\\'")); /* 633:604 */ listCounter.setCount(Integer.parseInt(row[2].toString())); /* 634: */ /* 635:606 */ listObj.add(listCounter); /* 636: */ } /* 637:610 */ trObj.commit(); /* 638: */ } /* 639: */ catch (HibernateException e) /* 640: */ { /* 641:612 */ trObj.rollback(); /* 642:613 */ e.printStackTrace(); /* 643: */ } /* 644: */ finally /* 645: */ { /* 646:615 */ sesObj.close(); /* 647: */ } /* 648:617 */ return listObj; /* 649: */ } /* 650: */ /* 651: */ public List<ListCounterDTO> getLevelWithCount(int companyid) /* 652: */ { /* 653:621 */ Transaction trObj = null; /* 654:622 */ Session sesObj = null; /* 655:623 */ List<?> resultList = null; /* 656:624 */ List<ListCounterDTO> listObj = new ArrayList(); /* 657: */ try /* 658: */ { /* 659:626 */ sesObj = HibernateUtil.getSession(); /* 660:627 */ trObj = HibernateUtil.getTrascation(sesObj); /* 661:628 */ Query query = sesObj.createQuery("SELECT l.levelid, l.level, COUNT(l.levelid) FROM QuestionDTO q, LevelDTO l WHERE q.companyId = ? AND l.levelid = q.levelid GROUP BY l.levelid"); /* 662: */ /* 663: */ /* 664:631 */ query.setInteger(0, companyid); /* 665:632 */ resultList = query.list(); /* 666:633 */ Iterator<?> result = resultList.iterator(); /* 667:634 */ while (result.hasNext()) /* 668: */ { /* 669:635 */ ListCounterDTO listCounter = new ListCounterDTO(); /* 670:636 */ Object[] row = (Object[])result.next(); /* 671: */ /* 672:638 */ listCounter.setId(Integer.parseInt(row[0].toString())); /* 673:639 */ listCounter.setName(StringEscapeUtils.escapeHtml(row[1].toString()).replace("'", "\\'")); /* 674:640 */ listCounter.setCount(Integer.parseInt(row[2].toString())); /* 675: */ /* 676:642 */ listObj.add(listCounter); /* 677: */ } /* 678:646 */ trObj.commit(); /* 679: */ } /* 680: */ catch (HibernateException e) /* 681: */ { /* 682:648 */ trObj.rollback(); /* 683:649 */ e.printStackTrace(); /* 684: */ } /* 685: */ finally /* 686: */ { /* 687:651 */ sesObj.close(); /* 688: */ } /* 689:653 */ return listObj; /* 690: */ } /* 691: */ /* 692: */ public List<ListCounterDTO> getTopicsWithCount(int subjectid, int companyid) /* 693: */ { /* 694:657 */ Transaction trObj = null; /* 695:658 */ Session sesObj = null; /* 696:659 */ List<?> resultList = null; /* 697:660 */ List<ListCounterDTO> listObj = new ArrayList(); /* 698: */ try /* 699: */ { /* 700:662 */ sesObj = HibernateUtil.getSession(); /* 701:663 */ trObj = HibernateUtil.getTrascation(sesObj); /* 702:664 */ Query query = sesObj.createQuery("SELECT t.topicId, t.topicName, count(t.topicId) FROM QuestionDTO q, TopicDTO t, SubjectDTO s where q.companyId = ? and s.subjectId = ? AND t.subjectId = s.subjectId and t.topicId = q.topicid AND s.subjectId = q.subjectId group by t.topicId"); /* 703: */ /* 704: */ /* 705:667 */ query.setInteger(0, companyid); /* 706:668 */ query.setInteger(1, subjectid); /* 707:669 */ resultList = query.list(); /* 708:670 */ Iterator<?> result = resultList.iterator(); /* 709:671 */ while (result.hasNext()) /* 710: */ { /* 711:672 */ ListCounterDTO listCounter = new ListCounterDTO(); /* 712:673 */ Object[] row = (Object[])result.next(); /* 713: */ /* 714:675 */ listCounter.setId(Integer.parseInt(row[0].toString())); /* 715:676 */ listCounter.setName(StringEscapeUtils.escapeHtml(row[1].toString()).replace("'", "\\'")); /* 716:677 */ listCounter.setCount(Integer.parseInt(row[2].toString())); /* 717: */ /* 718:679 */ listObj.add(listCounter); /* 719: */ } /* 720:683 */ trObj.commit(); /* 721: */ } /* 722: */ catch (HibernateException e) /* 723: */ { /* 724:685 */ trObj.rollback(); /* 725:686 */ e.printStackTrace(); /* 726: */ } /* 727: */ finally /* 728: */ { /* 729:688 */ sesObj.close(); /* 730: */ } /* 731:690 */ return listObj; /* 732: */ } /* 733: */ /* 734: */ public List<ListCounterDTO> getLevelWithCount(int topicid, int subjectid, int companyid) /* 735: */ { /* 736:694 */ Transaction trObj = null; /* 737:695 */ Session sesObj = null; /* 738:696 */ List<?> resultList = null; /* 739:697 */ List<ListCounterDTO> listObj = new ArrayList(); /* 740:698 */ Query query = null; /* 741: */ try /* 742: */ { /* 743:700 */ sesObj = HibernateUtil.getSession(); /* 744:701 */ trObj = HibernateUtil.getTrascation(sesObj); /* 745:702 */ if (topicid != 0) { /* 746:703 */ query = sesObj.createQuery("SELECT l.levelid, l.level, COUNT(l.levelid) FROM QuestionDTO q, LevelDTO l, TopicDTO t, SubjectDTO s WHERE q.companyId = ? AND s.subjectId = ? AND t.topicId = ? AND t.topicId = q.topicid AND t.subjectId = s.subjectId AND s.subjectId = q.subjectId AND l.levelid = q.levelid GROUP BY l.levelid"); /* 747: */ } else { /* 748:705 */ query = sesObj.createQuery("SELECT l.levelid, l.level, COUNT(l.levelid) FROM QuestionDTO q, LevelDTO l, SubjectDTO s WHERE q.companyId = ? AND s.subjectId = ? AND s.subjectId = q.subjectId AND l.levelid = q.levelid GROUP BY l.levelid"); /* 749: */ } /* 750:707 */ query.setInteger(0, companyid); /* 751:708 */ query.setInteger(1, subjectid); /* 752:709 */ if (topicid != 0) { /* 753:710 */ query.setInteger(2, topicid); /* 754: */ } /* 755:712 */ resultList = query.list(); /* 756:713 */ Iterator<?> result = resultList.iterator(); /* 757:714 */ while (result.hasNext()) /* 758: */ { /* 759:715 */ ListCounterDTO listCounter = new ListCounterDTO(); /* 760:716 */ Object[] row = (Object[])result.next(); /* 761: */ /* 762:718 */ listCounter.setId(Integer.parseInt(row[0].toString())); /* 763:719 */ listCounter.setName(StringEscapeUtils.escapeHtml(row[1].toString()).replace("'", "\\'")); /* 764:720 */ listCounter.setCount(Integer.parseInt(row[2].toString())); /* 765: */ /* 766:722 */ listObj.add(listCounter); /* 767: */ } /* 768:726 */ trObj.commit(); /* 769: */ } /* 770: */ catch (HibernateException e) /* 771: */ { /* 772:728 */ trObj.rollback(); /* 773:729 */ e.printStackTrace(); /* 774: */ } /* 775: */ finally /* 776: */ { /* 777:731 */ sesObj.close(); /* 778: */ } /* 779:733 */ return listObj; /* 780: */ } /* 781: */ /* 782: */ public List<ListCounterDTO> getSubjectWiseTopicsCount(int companyid) /* 783: */ { /* 784:737 */ Transaction trObj = null; /* 785:738 */ Session sesObj = null; /* 786:739 */ List<?> resultList = null; /* 787:740 */ List<ListCounterDTO> listObj = new ArrayList(); /* 788: */ try /* 789: */ { /* 790:742 */ sesObj = HibernateUtil.getSession(); /* 791:743 */ trObj = HibernateUtil.getTrascation(sesObj); /* 792:744 */ Query query = sesObj.createQuery("SELECT s.subjectId, s.subjectName, COUNT(t.topicId) FROM TopicDTO t, SubjectDTO s WHERE s.companyId = ? AND t.subjectId = s.subjectId GROUP BY s.subjectId"); /* 793: */ /* 794: */ /* 795:747 */ query.setInteger(0, companyid); /* 796: */ /* 797:749 */ resultList = query.list(); /* 798:750 */ Iterator<?> result = resultList.iterator(); /* 799:751 */ while (result.hasNext()) /* 800: */ { /* 801:752 */ ListCounterDTO listCounter = new ListCounterDTO(); /* 802:753 */ Object[] row = (Object[])result.next(); /* 803: */ /* 804:755 */ listCounter.setId(Integer.parseInt(row[0].toString())); /* 805:756 */ listCounter.setName(StringEscapeUtils.escapeHtml(row[1].toString()).replace("'", "\\'")); /* 806:757 */ listCounter.setCount(Integer.parseInt(row[2].toString())); /* 807: */ /* 808:759 */ listObj.add(listCounter); /* 809: */ } /* 810:761 */ trObj.commit(); /* 811: */ } /* 812: */ catch (HibernateException e) /* 813: */ { /* 814:763 */ trObj.rollback(); /* 815:764 */ e.printStackTrace(); /* 816: */ } /* 817: */ finally /* 818: */ { /* 819:766 */ sesObj.close(); /* 820: */ } /* 821:768 */ return listObj; /* 822: */ } /* 823: */ /* 824: */ public QuestionDTO getQuestionDetails(int questionid) /* 825: */ { /* 826:772 */ List<?> listObj = null; /* 827:773 */ Session sesObj = null; /* 828:774 */ Transaction trObj = null; /* 829:775 */ QuestionDTO questDTO = null; /* 830: */ try /* 831: */ { /* 832:777 */ sesObj = HibernateUtil.getSession(); /* 833:778 */ trObj = HibernateUtil.getTrascation(sesObj); /* 834: */ /* 835:780 */ Query query = sesObj.createQuery("from QuestionDTO qustDTO where qustDTO.questionid=:qid"); /* 836:781 */ query.setInteger("qid", questionid); /* 837:782 */ listObj = query.list(); /* 838:783 */ if (listObj.size() != 0) /* 839: */ { /* 840:784 */ Iterator<?> itr = listObj.iterator(); /* 841:785 */ questDTO = (QuestionDTO)itr.next(); /* 842: */ } /* 843:787 */ trObj.commit(); /* 844: */ } /* 845: */ catch (HibernateException e) /* 846: */ { /* 847:791 */ trObj.rollback(); /* 848:792 */ e.printStackTrace(); /* 849: */ } /* 850: */ finally /* 851: */ { /* 852:795 */ sesObj.close(); /* 853: */ } /* 854:797 */ return questDTO; /* 855: */ } /* 856: */ } /* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip * Qualified Name: kaldin.questionbank.question.hibernate.QuestionHibernate * JD-Core Version: 0.7.0.1 */
package page; public class Sundara { public static void main(String[] args) { System.out.println("Hi Sundra"); } }
public class ReversedArray extends SortedArray implements ReversedADT { public ReversedArray() { } public ReversedArray(int size) { super(size); } public ReversedADT reverse() { // create reversed array with size based on the number of objects in the array to be reversed ReversedArray reversedObjects = new ReversedArray(this.objectCount); for (int index = this.objectCount - 1; index >= 0; index--) { reversedObjects.objects[this.objectCount - index - 1] = this.objects[index]; } reversedObjects.objectCount = this.objectCount; return reversedObjects; } }
package com.ctac.jpmc.game.conway; import com.ctac.jpmc.game.ICoordinates; /** * * 2D Coordinates * * */ public class Coordinates3D implements ICoordinates { private int x; private int y; private int z; /** * Constructor with coordinates * * @param x x-coordinate * @param y y-coordinate * @param z z-coordinate */ public Coordinates3D(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } /** * Default Constructor * */ public Coordinates3D() { this (0,0,0); } @Override public String toString() { return "[" + x + ", " + y + ", " + z + "]"; } @Override public int hashCode() { int h = x; h = h * 31 + y; h = h * 31 + z; return h; } @Override public boolean equals(Object other) { if (!( other instanceof Coordinates3D)) { return false; } Coordinates3D other3D = (Coordinates3D) other; return (other3D.x == x && other3D.y == y && other3D.z == z ); } /** * get Number Of Dimensions * * @return returns <code>3</code> */ @Override public int getNumberOfDimensions() { return 3; } /** * get coordinates * * @return coordinates array [x,y,z] */ @Override public int [] getValues () { return new int [] {x,y,z}; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapred; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.HashSet; import junit.framework.Assert; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.mapred.TaskStatus.Phase; import org.apache.hadoop.mapred.TaskStatus.State; import org.apache.hadoop.mapreduce.protocol.ClientProtocol; import org.apache.hadoop.mapreduce.server.jobtracker.JTConfig; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapred.FakeJobs; import org.junit.Test; public class TestSimulatorJobTracker { SimulatorTaskTracker taskTracker; public static final Log LOG = LogFactory .getLog(TestSimulatorJobTracker.class); @SuppressWarnings("deprecation") public JobConf createJobConf() { JobConf jtConf = new JobConf(); jtConf.set("mapred.job.tracker", "localhost:8012"); jtConf.set("mapred.jobtracker.job.history.block.size", "512"); jtConf.set("mapred.jobtracker.job.history.buffer.size", "512"); jtConf.setLong("mapred.tasktracker.expiry.interval", 5000); jtConf.setInt("mapred.reduce.copy.backoff", 4); jtConf.setLong("mapred.job.reuse.jvm.num.tasks", -1); jtConf.setUser("mumak"); jtConf.set("mapred.system.dir", jtConf.get("hadoop.tmp.dir", "/tmp/hadoop-" + jtConf.getUser()) + "/mapred/system"); jtConf.set("mapred.queue.names",JobConf.DEFAULT_QUEUE_NAME); jtConf.setBoolean(JTConfig.JT_PERSIST_JOBSTATUS, false); System.out.println("Created JobConf"); return jtConf; } public static class FakeJobClient { ClientProtocol jobTracker; int numMaps; int numReduces; public FakeJobClient(ClientProtocol jobTracker, int numMaps, int numReduces) { this.jobTracker = jobTracker; this.numMaps = numMaps; this.numReduces = numReduces; } public void submitNewJob() throws IOException, InterruptedException { org.apache.hadoop.mapreduce.JobID jobId = jobTracker.getNewJobID(); LOG.info("Obtained from Jobtracker jobid = " + jobId); FakeJobs job = new FakeJobs("job1", 0, numMaps, numReduces); SimulatorJobCache.put(org.apache.hadoop.mapred.JobID.downgrade(jobId), job); jobTracker.submitJob(jobId, "dummy-path", null); } } public static class FakeTaskTracker extends SimulatorTaskTracker { boolean firstHeartbeat = true; short responseId = 0; int now = 0; FakeTaskTracker(InterTrackerProtocol jobTracker, Configuration conf) { super(jobTracker, conf); LOG.info("FakeTaskTracker constructor, taskTrackerName=" + taskTrackerName); } private List<TaskStatus> collectAndCloneTaskStatuses() { ArrayList<TaskStatus> statuses = new ArrayList<TaskStatus>(); Set<TaskAttemptID> mark = new HashSet<TaskAttemptID>(); for (SimulatorTaskInProgress tip : tasks.values()) { statuses.add((TaskStatus) tip.getTaskStatus().clone()); if (tip.getFinalRunState() == State.SUCCEEDED) { mark.add(tip.getTaskStatus().getTaskID()); } } for (TaskAttemptID taskId : mark) { tasks.remove(taskId); } return statuses; } public int sendFakeHeartbeat(int current) throws IOException { int numLaunchTaskActions = 0; this.now = current; List<TaskStatus> taskStatuses = collectAndCloneTaskStatuses(); TaskTrackerStatus taskTrackerStatus = new SimulatorTaskTrackerStatus( taskTrackerName, hostName, httpPort, taskStatuses, 0, maxMapSlots, maxReduceSlots, this.now); // Transmit the heartbeat HeartbeatResponse response = null; LOG.debug("sending heartbeat at time = " + this.now + " responseId = " + responseId); response = jobTracker.heartbeat(taskTrackerStatus, false, firstHeartbeat, true, responseId); firstHeartbeat = false; responseId = response.getResponseId(); numLaunchTaskActions = findLaunchTaskActions(response); return numLaunchTaskActions; } int findLaunchTaskActions(HeartbeatResponse response) { TaskTrackerAction[] actions = response.getActions(); int numLaunchTaskActions = 0; // HashSet<> numLaunchTaskActions for (TaskTrackerAction action : actions) { if (action instanceof SimulatorLaunchTaskAction) { Task task = ((SimulatorLaunchTaskAction) action).getTask(); numLaunchTaskActions++; TaskAttemptID taskId = task.getTaskID(); if (tasks.containsKey(taskId)) { // already have this task..do not need to generate new status continue; } TaskStatus status; if (task.isMapTask()) { status = new MapTaskStatus(taskId, 0f, 1, State.RUNNING, "", "", taskTrackerName, Phase.MAP, new Counters()); } else { status = new ReduceTaskStatus(taskId, 0f, 1, State.RUNNING, "", "", taskTrackerName, Phase.SHUFFLE, new Counters()); } status.setRunState(State.SUCCEEDED); status.setStartTime(this.now); SimulatorTaskInProgress tip = new SimulatorTaskInProgress( (SimulatorLaunchTaskAction) action, status, this.now); tasks.put(taskId, tip); } } return numLaunchTaskActions; } } @Test public void testTrackerInteraction() throws IOException, InterruptedException { LOG.info("Testing Inter Tracker protocols"); int now = 0; JobConf jtConf = createJobConf(); int NoMaps = 2; int NoReduces = 10; // jtConf.set("mapred.jobtracker.taskScheduler", // DummyTaskScheduler.class.getName()); jtConf.set("fs.default.name", "file:///"); jtConf.set("mapred.jobtracker.taskScheduler", JobQueueTaskScheduler.class .getName()); SimulatorJobTracker sjobTracker = SimulatorJobTracker.startTracker(jtConf, 0); System.out.println("Created the SimulatorJobTracker successfully"); sjobTracker.offerService(); FakeJobClient jbc = new FakeJobClient(sjobTracker, NoMaps, NoReduces); int NoJobs = 1; for (int i = 0; i < NoJobs; i++) { jbc.submitNewJob(); } org.apache.hadoop.mapreduce.JobStatus[] allJobs = sjobTracker.getAllJobs(); Assert.assertTrue("allJobs queue length is " + allJobs.length, allJobs.length >= 1); for (org.apache.hadoop.mapreduce.JobStatus js : allJobs) { LOG.info("From JTQueue: job id = " + js.getJobID()); } Configuration ttConf = new Configuration(); ttConf.set("mumak.tasktracker.tracker.name", "tracker_host1.foo.com:localhost/127.0.0.1:9010"); ttConf.set("mumak.tasktracker.host.name", "host1.foo.com"); ttConf.setInt("mapred.tasktracker.map.tasks.maximum", 10); ttConf.setInt("mapred.tasktracker.reduce.tasks.maximum", 10); ttConf.setInt("mumak.tasktracker.heartbeat.fuzz", -1); FakeTaskTracker fakeTracker = new FakeTaskTracker(sjobTracker, ttConf); int numLaunchTaskActions = 0; for (int i = 0; i < NoMaps * 2; ++i) { // we should be able to assign all // tasks within 2X of NoMaps // heartbeats numLaunchTaskActions += fakeTracker.sendFakeHeartbeat(now); if (numLaunchTaskActions >= NoMaps) { break; } now += 5; LOG.debug("Number of MapLaunchTasks=" + numLaunchTaskActions + " now = " + now); } Assert.assertTrue("Failed to launch all maps: " + numLaunchTaskActions, numLaunchTaskActions >= NoMaps); // sending the completed status LOG.info("Sending task completed status"); numLaunchTaskActions += fakeTracker.sendFakeHeartbeat(now); // now for the reduce tasks for (int i = 0; i < NoReduces * 2; ++i) { // we should be able to assign all // tasks within 2X of NoReduces // heartbeats if (numLaunchTaskActions >= NoMaps + NoReduces) { break; } numLaunchTaskActions += fakeTracker.sendFakeHeartbeat(now); now += 5; LOG.debug("Number of ReduceLaunchTasks=" + numLaunchTaskActions + " now = " + now); } Assert.assertTrue("Failed to launch all reduces: " + numLaunchTaskActions, numLaunchTaskActions >= NoMaps + NoReduces); // sending the reduce completion numLaunchTaskActions += fakeTracker.sendFakeHeartbeat(now); } }
package com.rudecrab.springsecurity.security; import com.rudecrab.springsecurity.serviceimpl.UserServiceImpl; import io.jsonwebtoken.Claims; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 认证过滤器 * * @author RudeCrab */ @Slf4j @Component public class LoginFilter extends OncePerRequestFilter { @Autowired private JwtManager jwtManager; @Autowired private UserServiceImpl userService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { log.info("---LoginFilter---"); // 从请求头中获取token字符串并解析 Claims claims = jwtManager.parse(request.getHeader("Authorization")); if (claims != null) { String username = claims.getSubject(); UserDetails user = userService.loadUserByUsername(username); Authentication authentication = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); } chain.doFilter(request, response); } }
package iristk.app.puzzle; import java.awt.Color; public class Figure { public String form; public Color color; public String size; public int[][] shape; public int id; public boolean isSet; public boolean isSet() { return isSet; } public void setSet(boolean isSet) { this.isSet = isSet; } public Figure(int id, int[][] shape, String form, Color color, String size) { this.id = id; this.shape = shape; this.form = form; this.color = color; this.size = size; this.isSet = false; } public int getId() { return id; } public void setId(int id) { this.id = id; } //Returns the shape as a public int[][] getShape() { return shape; } public void setShape(int[][] shape) { this.shape = shape; } public String getForm() { return form; } public void setForm(String form) { this.form = form; } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } }
package org.zx.common.security; import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import org.springframework.context.ApplicationContext; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.zx.common.exception.BizException; import org.zx.common.security.entity.User; import org.zx.common.security.service.RedisService; import org.zx.common.util.ApplicationContextUtil; import javax.servlet.FilterChain; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Date; import static org.zx.common.security.JWTConst.*; public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter { private final AuthenticationManager authenticationManager; private UserRepository userRepository; private RedisService redisService; /** * 设置登录重定向 * * @param authenticationManager */ public JwtAuthenticationFilter(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; // 如果不设置这一行,spring会自动创建一个login的controller // 所以不用在controller当中设置login setFilterProcessesUrl(SIGN_UP_URL); setUserRepository(ApplicationContextUtil.context()); setRedisService(ApplicationContextUtil.context()); } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { try { User user = new ObjectMapper().readValue(request.getInputStream(), User.class); String username = user.getUsername(); String password = user.getPassword(); final UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password, Lists.newArrayList()); super.setDetails(request,authRequest); return authenticationManager.authenticate(authRequest); } catch (IOException e) { throw new BizException("登录请求格式错误"); } } /** * 生成jwt Token并返回 * @param request * @param response * @param chain * @param authResult * @throws IOException */ @Override protected void successfulAuthentication(HttpServletRequest request , HttpServletResponse response , FilterChain chain , Authentication authResult) throws IOException { final String name = authResult.getName(); String jwtToken = JWT.create() .withSubject(name) .withClaim("role",userRepository.findUserByUsername(name).getRole()) .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) .sign(Algorithm.HMAC512(SECRET.getBytes(StandardCharsets.UTF_8))); Cookie cookie = new Cookie("TOKEN", jwtToken); // 设置cookie的过期时间为7天 cookie.setMaxAge(7 * 24 * 60 * 60); cookie.setHttpOnly(true); response.addCookie(cookie); redisService.save(SessionToken.builder(). name(name).token(jwtToken).build()); response.getWriter().write(name + " success login"); response.getWriter().flush(); } public void setUserRepository(ApplicationContext ctx) { this.userRepository = ctx.getBean(UserRepository.class); } public void setRedisService(ApplicationContext ctx){ this.redisService = ctx.getBean(RedisService.class); } }
package com.data.rhis2; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.SimpleAdapter; import android.widget.TextView; import java.util.ArrayList; import java.util.HashMap; import Common.Connection; import Common.Global; /** * Created by ccah on 3/15/2016. */ public class MemberFormFPI extends Activity { boolean netwoekAvailable = false; Location currentLocation; double currentLatitude, currentLongitude; Location currentLocationNet; double currentLatitudeNet, currentLongitudeNet; //Disabled Back/Home key //-------------------------------------------------------------------------------------------------- @Override public boolean onKeyDown(int iKeyCode, KeyEvent event) { if (iKeyCode == KeyEvent.KEYCODE_BACK || iKeyCode == KeyEvent.KEYCODE_HOME) { return false; } else { return true; } } //Top menu //-------------------------------------------------------------------------------------------------- public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.mnuclose, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { AlertDialog.Builder adb = new AlertDialog.Builder(MemberFormFPI.this); switch (item.getItemId()) { case R.id.menuClose: adb.setTitle("Close"); adb.setMessage("আপনি কি এই ফর্ম থেকে বের হতে চান[হাঁ/না]?"); adb.setNegativeButton("না", null); adb.setPositiveButton("হাঁ", new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); if (g.getCallFrom().equals("newh") | g.getCallFrom().equalsIgnoreCase("h")) { Intent f1 = new Intent(getApplicationContext(), HouseholdIndex.class); startActivity(f1); } else if (g.getCallFrom().equalsIgnoreCase("m") | g.getCallFrom().equalsIgnoreCase("mu")) { Intent f2 = new Intent(getApplicationContext(), MemberListFPI.class); startActivity(f2); } else if (g.getCallFrom().equalsIgnoreCase("V")) { Intent f2 = new Intent(getApplicationContext(), VillageList.class); startActivity(f2); } } }); adb.show(); return true; } return false; } String VariableID; private int hour; private int minute; private int mDay; private int mMonth; private int mYear; static final int DATE_DIALOG = 1; static final int TIME_DIALOG = 2; CheckBox chkIDHave; Connection C; Global g; SimpleAdapter dataAdapter; ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>(); private String TableName; EditText txtHealthID; LinearLayout seclblH; LinearLayout secDiv; TextView VlblDiv; EditText txtDiv; LinearLayout secDist; TextView VlblDist; EditText txtDist; LinearLayout secUpz; TextView VlblUpz; EditText txtUpz; LinearLayout secUN; TextView VlblUN; EditText txtUN; LinearLayout secMouza; TextView VlblMouza; EditText txtMouza; LinearLayout secVill; TextView VlblVill; EditText txtVill; LinearLayout secHHNo; TextView VlblHHNo; EditText txtHHNo; LinearLayout secSNo; TextView VlblSNo; TextView txtSNo; LinearLayout secNameEng; TextView VlblNameEng; TextView txtNameEng; LinearLayout secNameBang; TextView VlblNameBang; TextView txtNameBang; TextView txtRth; LinearLayout secHaveNID; TextView VlblHaveNID; RadioGroup rdogrpHaveNID; RadioButton rdoHaveNID1; RadioButton rdoHaveNID2; CheckBox chkNIDDontKnow; LinearLayout secNID; TextView VlblNID; TextView txtNID; LinearLayout secNIDStatus; TextView VlblNIDStatus; TextView txtNIDStatus; CheckBox chkBRIDDontKnow; LinearLayout secNIDStatus1; LinearLayout secHaveBR; TextView VlblHaveBR; RadioGroup rdogrpHaveBR; RadioButton rdoHaveBR1; RadioButton rdoHaveBR2; LinearLayout secBRID; TextView VlblBRID; TextView txtBRID; LinearLayout secBRIDStatus; TextView VlblBRIDStatus; TextView txtBRIDStatus; LinearLayout secBRIDStatus1; LinearLayout secMobileNo1; TextView VlblMobileNo1; TextView txtMobileNo1; LinearLayout secMobileNo2; TextView VlblMobileNo2; TextView txtMobileNo2; CheckBox chkMobileNo; LinearLayout secDOB; TextView VlblDOB; TextView dtpDOB; ImageButton btnDOB; LinearLayout secAge; TextView VlblAge; TextView txtAge; LinearLayout secDOBSource; TextView VlblDOBSource; RadioGroup rdogrpDOBSource; RadioButton rdoDOBSource1; RadioButton rdoDOBSource2; LinearLayout secBPlace; TextView VlblBPlace; TextView txtBPlace; LinearLayout secFNo; TextView VlblFNo; TextView txtFNo; LinearLayout secFather; LinearLayout secFather1; TextView VlblFather; TextView txtFather; CheckBox chkFatherDontKnow; LinearLayout secMNo; TextView VlblMNo; TextView txtMNo; LinearLayout secMother; LinearLayout secMother1; TextView VlblMother; TextView txtMother; CheckBox chkMotherDontKnow; LinearLayout secSex; TextView VlblSex; RadioGroup rdogrpSex; RadioButton rdoSex1; RadioButton rdoSex2; RadioButton rdoSex3; LinearLayout secMS; TextView VlblMS; TextView txtMS; LinearLayout secSPNo; TextView VlblSPNo; TextView txtSPNo4; LinearLayout secSPNo1; TextView VlblSPNo1; TextView txtSPNo1; LinearLayout secSPNo2; TextView VlblSPNo2; TextView txtSPNo2; LinearLayout secSPNo3; TextView VlblSPNo3; TextView txtSPNo3; LinearLayout secSP10; LinearLayout secSPNo11; LinearLayout secSPNo21; LinearLayout secSPNo31; LinearLayout secELCONo; TextView VlblELCONo; EditText txtELCONo; TextView VlblELCODontKnow; CheckBox chkELCODontKnow; LinearLayout secEDU; TextView VlblEDU; TextView txtEDU; LinearLayout secRel; TextView VlblRel; TextView txtRel; LinearLayout secNationality; TextView VlblNationality; CheckBox chkNationality; LinearLayout secOCP; TextView VlblOCP; TextView txtOCP; RadioGroup rdogrpNameEng; RadioButton rdoNameEng1; RadioButton rdoNameEng2; RadioGroup rdogrpNameBang; RadioButton rdoNameBang1; RadioButton rdoNameBang2; RadioGroup rdogrpRth; RadioButton rdoRth1; RadioButton rdoRth2; RadioGroup rdogrpNID; RadioButton rdoNID1; RadioButton rdoNID2; RadioGroup rdogrpNIDStatus; RadioButton rdoNIDStatus1; RadioButton rdoNIDStatus2; RadioGroup rdogrpBRID; RadioButton rdoBRID1; RadioButton rdoBRID2; RadioGroup rdogrpBRIDStatus; RadioButton rdoBRIDStatus1; RadioButton rdoBRIDStatus2; RadioGroup rdogrpMobileNo; RadioButton rdoMobileNo1; RadioButton rdoMobileNo2; RadioGroup rdogrpMobileNo2; RadioButton rdoMobileNo21; RadioButton rdoMobileNo22; RadioGroup rdogrpDOBStatus; RadioButton rdoDOBStatus1; RadioButton rdoDOBStatus2; RadioGroup rdogrpDOB; RadioButton rdoDOB1; RadioButton rdoDOB2; RadioGroup rdogrpAge; RadioButton rdoAge1; RadioButton rdoAge2; RadioGroup rdogrpBPlace; RadioButton rdoBPlace1; RadioButton rdoBPlace2; RadioGroup rdogrpFNo; RadioButton rdoFNo1; RadioButton rdoFNo2; RadioGroup rdogrpFather; RadioButton rdoFather1; RadioButton rdoFather2; RadioGroup rdogrpMNo; RadioButton rdoMNo1; RadioButton rdoMNo2; RadioGroup rdogrpMother; RadioButton rdoMother1; RadioButton rdoMother2; RadioGroup rdogrpGender; RadioButton rdoGender1; RadioButton rdoGender2; RadioGroup rdogrpMS; RadioButton rdoMS1; RadioButton rdoMS2; RadioGroup rdogrpSPNo1; RadioButton rdoSPNo11; RadioButton rdoSPNo12; RadioGroup rdogrpSPNo2; RadioButton rdoSPNo13; RadioButton rdoSPNo14; RadioGroup rdogrpSPNo3; RadioButton rdoSPNo15; RadioButton rdoSPNo16; RadioGroup rdogrpSPNo4; RadioButton rdoSPNo17; RadioButton rdoSPNo18; RadioGroup rdogrpEDU; RadioButton rdoEDU1; RadioButton rdoEDU2; RadioGroup rdogrpRel; RadioButton rdoRel1; RadioButton rdoRel2; RadioGroup rdogrpNationality; RadioButton rdoNationality1; RadioButton rdoNationality2; RadioGroup rdogrpOCP; RadioButton rdoOCP1; RadioButton rdoOCP2; LinearLayout secNameEng1; LinearLayout secRth1; LinearLayout secNID1; LinearLayout secBRID1; String StartTime; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { setContentView(R.layout.memberformfpi); C = new Connection(this); g = Global.getInstance(); FindLocation(); StartTime = g.CurrentTime24(); TableName = "MemberFPI"; txtHealthID = (EditText) findViewById(R.id.txtHealthID); txtHealthID.setEnabled(false); chkIDHave = (CheckBox) findViewById(R.id.chkIDHave); chkIDHave.setChecked(false); seclblH = (LinearLayout) findViewById(R.id.seclblH); VlblSNo = (TextView) findViewById(R.id.VlblSNo); txtSNo = (TextView) findViewById(R.id.txtSNo); /*if(g.getSerialNo().toString().length()==0) txtSNo.setText( SerialNumber() ); else txtSNo.setText(g.getSerialNo().toString());*/ txtSNo.setText(g.getSerialNo().toString()); secNameEng = (LinearLayout) findViewById(R.id.secNameEng); VlblNameEng = (TextView) findViewById(R.id.VlblNameEng); txtNameEng = (TextView) findViewById(R.id.txtNameEng); secNameBang = (LinearLayout) findViewById(R.id.secNameBang); VlblNameBang = (TextView) findViewById(R.id.VlblNameBang); txtNameBang = (TextView) findViewById(R.id.txtNameBang); txtRth = (TextView) findViewById(R.id.txtRth); secHaveNID = (LinearLayout) findViewById(R.id.secHaveNID); VlblHaveNID = (TextView) findViewById(R.id.VlblHaveNID); rdogrpHaveNID = (RadioGroup) findViewById(R.id.rdogrpHaveNID); rdoHaveNID1 = (RadioButton) findViewById(R.id.rdoHaveNID1); rdoHaveNID2 = (RadioButton) findViewById(R.id.rdoHaveNID2); secNID = (LinearLayout) findViewById(R.id.secNID); VlblNID = (TextView) findViewById(R.id.VlblNID); txtNID = (TextView) findViewById(R.id.txtNID); chkNIDDontKnow = (CheckBox) findViewById(R.id.chkNIDDontKnow); chkNIDDontKnow.setEnabled(false); secNIDStatus = (LinearLayout) findViewById(R.id.secNIDStatus); secNIDStatus1 = (LinearLayout) findViewById(R.id.secNIDStatus1); VlblNIDStatus = (TextView) findViewById(R.id.VlblNIDStatus); txtNIDStatus = (TextView) findViewById(R.id.txtNIDStatus); secHaveBR = (LinearLayout) findViewById(R.id.secHaveBR); VlblHaveBR = (TextView) findViewById(R.id.VlblHaveBR); rdogrpHaveBR = (RadioGroup) findViewById(R.id.rdogrpHaveBR); rdoHaveBR1 = (RadioButton) findViewById(R.id.rdoHaveBR1); rdoHaveBR2 = (RadioButton) findViewById(R.id.rdoHaveBR2); secBRID = (LinearLayout) findViewById(R.id.secBRID); VlblBRID = (TextView) findViewById(R.id.VlblBRID); txtBRID = (TextView) findViewById(R.id.txtBRID); chkBRIDDontKnow = (CheckBox) findViewById(R.id.chkBRIDDontKnow); chkBRIDDontKnow.setEnabled(false); secBRIDStatus = (LinearLayout) findViewById(R.id.secBRIDStatus); secBRIDStatus1 = (LinearLayout) findViewById(R.id.secBRIDStatus1); VlblBRIDStatus = (TextView) findViewById(R.id.VlblBRIDStatus); txtBRIDStatus = (TextView) findViewById(R.id.txtBRIDStatus); secMobileNo1 = (LinearLayout) findViewById(R.id.secMobileNo1); VlblMobileNo1 = (TextView) findViewById(R.id.VlblMobileNo1); txtMobileNo1 = (TextView) findViewById(R.id.txtMobileNo1); secMobileNo2 = (LinearLayout) findViewById(R.id.secMobileNo2); VlblMobileNo2 = (TextView) findViewById(R.id.VlblMobileNo2); txtMobileNo2 = (TextView) findViewById(R.id.txtMobileNo2); chkMobileNo = (CheckBox) findViewById(R.id.chkMobileNo); chkMobileNo.setEnabled(false); /*txtMobileNo1.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { if (txtMobileNo1.getText().length() > 0) { chkMobileNo.setChecked(false); } else { //chkMobileNo.setChecked(true); } } }); txtMobileNo2.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { if (txtMobileNo2.getText().length() > 0) { chkMobileNo.setChecked(false); } else { //chkMobileNo.setChecked(true); } } }); chkMobileNo.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (((CheckBox) v).isChecked()) { txtMobileNo1.setText(""); txtMobileNo2.setText(""); } } });*/ secDOB = (LinearLayout) findViewById(R.id.secDOB); VlblDOB = (TextView) findViewById(R.id.VlblDOB); dtpDOB = (TextView) findViewById(R.id.dtpDOB); secAge = (LinearLayout) findViewById(R.id.secAge); VlblAge = (TextView) findViewById(R.id.VlblAge); txtAge = (TextView) findViewById(R.id.txtAge); secDOBSource = (LinearLayout) findViewById(R.id.secDOBSource); VlblDOBSource = (TextView) findViewById(R.id.VlblDOBSource); rdogrpDOBSource = (RadioGroup) findViewById(R.id.rdogrpDOBSource); rdogrpDOBSource.setEnabled(false); rdoDOBSource1 = (RadioButton) findViewById(R.id.rdoDOBSource1); rdoDOBSource1.setEnabled(false); rdoDOBSource2 = (RadioButton) findViewById(R.id.rdoDOBSource2); rdoDOBSource2.setEnabled(false); rdogrpDOBSource.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup arg0, int id) { if (id == R.id.rdoDOBSource1) { secDOB.setVisibility(View.VISIBLE); secAge.setVisibility(View.GONE); txtAge.setText(""); } else if (id == R.id.rdoDOBSource2) { dtpDOB.setText(""); secDOB.setVisibility(View.GONE); secAge.setVisibility(View.VISIBLE); txtAge.requestFocus(); } } }); secBPlace = (LinearLayout) findViewById(R.id.secBPlace); VlblBPlace = (TextView) findViewById(R.id.VlblBPlace); txtBPlace = (TextView) findViewById(R.id.txtBPlace); secFNo = (LinearLayout) findViewById(R.id.secFNo); VlblFNo = (TextView) findViewById(R.id.VlblFNo); txtFNo = (TextView) findViewById(R.id.txtFNo); secFather = (LinearLayout) findViewById(R.id.secFather); secFather1 = (LinearLayout) findViewById(R.id.secFather1); VlblFather = (TextView) findViewById(R.id.VlblFather); txtFather = (TextView) findViewById(R.id.txtFather); chkFatherDontKnow = (CheckBox) findViewById(R.id.chkFatherDontKnow); chkFatherDontKnow.setEnabled(false); secMNo = (LinearLayout) findViewById(R.id.secMNo); VlblMNo = (TextView) findViewById(R.id.VlblMNo); txtMNo = (TextView) findViewById(R.id.txtMNo); secMother = (LinearLayout) findViewById(R.id.secMother); secMother1 = (LinearLayout) findViewById(R.id.secMother1); VlblMother = (TextView) findViewById(R.id.VlblMother); txtMother = (TextView) findViewById(R.id.txtMother); chkMotherDontKnow = (CheckBox) findViewById(R.id.chkMotherDontKnow); chkMotherDontKnow.setEnabled(false); secSex = (LinearLayout) findViewById(R.id.secSex); VlblSex = (TextView) findViewById(R.id.VlblSex); rdogrpSex = (RadioGroup) findViewById(R.id.rdogrpSex); rdoSex1 = (RadioButton) findViewById(R.id.rdoSex1); rdoSex1.setEnabled(false); rdoSex2 = (RadioButton) findViewById(R.id.rdoSex2); rdoSex2.setEnabled(false); rdoSex3 = (RadioButton) findViewById(R.id.rdoSex3); rdoSex3.setEnabled(false); secMS = (LinearLayout) findViewById(R.id.secMS); VlblMS = (TextView) findViewById(R.id.VlblMS); txtMS = (TextView) findViewById(R.id.txtMS); secSPNo = (LinearLayout) findViewById(R.id.secSPNo); VlblSPNo = (TextView) findViewById(R.id.VlblSPNo); txtSPNo1 = (TextView) findViewById(R.id.txtSPNo1); secSPNo1 = (LinearLayout) findViewById(R.id.secSPNo1); VlblSPNo1 = (TextView) findViewById(R.id.VlblSPNo1); txtSPNo1 = (TextView) findViewById(R.id.txtSPNo1); secSPNo2 = (LinearLayout) findViewById(R.id.secSPNo2); VlblSPNo2 = (TextView) findViewById(R.id.VlblSPNo2); txtSPNo2 = (TextView) findViewById(R.id.txtSPNo2); secSPNo3 = (LinearLayout) findViewById(R.id.secSPNo3); VlblSPNo3 = (TextView) findViewById(R.id.VlblSPNo3); txtSPNo3 = (TextView) findViewById(R.id.txtSPNo3); txtSPNo4 = (TextView) findViewById(R.id.txtSPNo4); secSP10 = (LinearLayout) findViewById(R.id.secSP10); secSPNo11 = (LinearLayout) findViewById(R.id.secSPNo11); secSPNo21 = (LinearLayout) findViewById(R.id.secSPNo21); secSPNo31 = (LinearLayout) findViewById(R.id.secSPNo31); secELCONo = (LinearLayout) findViewById(R.id.secELCONo); VlblELCONo = (TextView) findViewById(R.id.VlblELCONo); txtELCONo = (EditText) findViewById(R.id.txtELCONo); VlblELCODontKnow = (TextView) findViewById(R.id.VlblELCODontKnow); chkELCODontKnow = (CheckBox) findViewById(R.id.chkELCODontKnow); secEDU = (LinearLayout) findViewById(R.id.secEDU); VlblEDU = (TextView) findViewById(R.id.VlblEDU); txtEDU = (TextView) findViewById(R.id.txtEDU); secRel = (LinearLayout) findViewById(R.id.secRel); VlblRel = (TextView) findViewById(R.id.VlblRel); txtRel = (TextView) findViewById(R.id.txtRel); secNationality = (LinearLayout) findViewById(R.id.secNationality); VlblNationality = (TextView) findViewById(R.id.VlblNationality); chkNationality = (CheckBox) findViewById(R.id.chkNationality); chkNationality.setChecked(true); chkNationality.setEnabled(false); secOCP = (LinearLayout) findViewById(R.id.secOCP); VlblOCP = (TextView) findViewById(R.id.VlblOCP); txtOCP = (TextView) findViewById(R.id.txtOCP); //----------------------------------------------------------- secNID.setVisibility(View.VISIBLE); txtNID.setText(""); secNIDStatus.setVisibility(View.VISIBLE); txtNIDStatus.setText(""); secBRID.setVisibility(View.VISIBLE); txtBRID.setText(""); secBRIDStatus.setVisibility(View.VISIBLE); txtBRIDStatus.setText(""); secAge.setVisibility(View.GONE); secFather.setVisibility(View.GONE); secFather1.setVisibility(View.GONE); txtFather.setText(""); secMother.setVisibility(View.GONE); secMother1.setVisibility(View.GONE); txtMother.setText(""); //secELCONo.setVisibility( View.GONE ); //txtELCONo.setText(""); //chkELCODontKnow.setChecked( false ); secSPNo.setVisibility(View.GONE); secSPNo1.setVisibility(View.GONE); secSPNo2.setVisibility(View.GONE); secSPNo3.setVisibility(View.GONE); //secSP10.setVisibility( View.GONE ); secSPNo11.setVisibility(View.GONE); secSPNo21.setVisibility(View.GONE); secSPNo31.setVisibility(View.GONE); //---------------------FPI-------------------------------------- rdogrpNameEng = (RadioGroup) findViewById(R.id.rdogrpNameEng); rdoNameEng1 = (RadioButton) findViewById(R.id.rdoNameEng1); rdoNameEng2 = (RadioButton) findViewById(R.id.rdoNameEng2); secNameEng1 = (LinearLayout) findViewById(R.id.secNameEng1); secRth1 = (LinearLayout) findViewById(R.id.secRth1); secNID1 = (LinearLayout) findViewById(R.id.secNID1); secBRID1 = (LinearLayout) findViewById(R.id.secBRID1); rdogrpRth = (RadioGroup) findViewById(R.id.rdogrpRth); rdoRth1 = (RadioButton) findViewById(R.id.rdoRth1); rdoRth2 = (RadioButton) findViewById(R.id.rdoRth2); rdogrpNID = (RadioGroup) findViewById(R.id.rdogrpNID); rdoNID1 = (RadioButton) findViewById(R.id.rdoNID1); rdoNID2 = (RadioButton) findViewById(R.id.rdoNID2); rdogrpNIDStatus = (RadioGroup) findViewById(R.id.rdogrpNIDStatus); rdoNIDStatus1 = (RadioButton) findViewById(R.id.rdoNIDStatus1); rdoNIDStatus2 = (RadioButton) findViewById(R.id.rdoNIDStatus2); rdogrpBRID = (RadioGroup) findViewById(R.id.rdogrpBRID); rdoBRID1 = (RadioButton) findViewById(R.id.rdoBRID1); rdoBRID2 = (RadioButton) findViewById(R.id.rdoBRID2); rdogrpBRIDStatus = (RadioGroup) findViewById(R.id.rdogrpBRIDStatus); rdoBRIDStatus1 = (RadioButton) findViewById(R.id.rdoBRIDStatus1); rdoBRIDStatus2 = (RadioButton) findViewById(R.id.rdoBRIDStatus2); rdogrpMobileNo = (RadioGroup) findViewById(R.id.rdogrpMobileNo); rdoMobileNo1 = (RadioButton) findViewById(R.id.rdoMobileNo1); rdoMobileNo2 = (RadioButton) findViewById(R.id.rdoMobileNo2); rdogrpMobileNo2 = (RadioGroup) findViewById(R.id.rdogrpMobileNo2); rdoMobileNo21 = (RadioButton) findViewById(R.id.rdoMobileNo21); rdoMobileNo22 = (RadioButton) findViewById(R.id.rdoMobileNo22); rdogrpDOBStatus = (RadioGroup) findViewById(R.id.rdogrpDOBStatus); rdoDOBStatus1 = (RadioButton) findViewById(R.id.rdoDOBStatus1); rdoDOBStatus2 = (RadioButton) findViewById(R.id.rdoDOBStatus2); rdogrpDOB = (RadioGroup) findViewById(R.id.rdogrpDOB); rdoDOB1 = (RadioButton) findViewById(R.id.rdoDOB1); rdoDOB2 = (RadioButton) findViewById(R.id.rdoDOB2); rdogrpAge = (RadioGroup) findViewById(R.id.rdogrpAge); rdoAge1 = (RadioButton) findViewById(R.id.rdoAge1); rdoAge2 = (RadioButton) findViewById(R.id.rdoAge2); rdogrpBPlace = (RadioGroup) findViewById(R.id.rdogrpBPlace); rdoBPlace1 = (RadioButton) findViewById(R.id.rdoBPlace1); rdoBPlace2 = (RadioButton) findViewById(R.id.rdoBPlace2); rdogrpFNo = (RadioGroup) findViewById(R.id.rdogrpFNo); rdoFNo1 = (RadioButton) findViewById(R.id.rdoFNo1); rdoFNo2 = (RadioButton) findViewById(R.id.rdoFNo2); rdogrpFather = (RadioGroup) findViewById(R.id.rdogrpFather); rdoFather1 = (RadioButton) findViewById(R.id.rdoFather1); rdoFather2 = (RadioButton) findViewById(R.id.rdoFather2); rdogrpMNo = (RadioGroup) findViewById(R.id.rdogrpMNo); rdoMNo1 = (RadioButton) findViewById(R.id.rdoMNo1); rdoMNo2 = (RadioButton) findViewById(R.id.rdoMNo2); rdogrpMother = (RadioGroup) findViewById(R.id.rdogrpMother); rdoMother1 = (RadioButton) findViewById(R.id.rdoMother1); rdoMother2 = (RadioButton) findViewById(R.id.rdoMother2); rdogrpGender = (RadioGroup) findViewById(R.id.rdogrpGender); rdoGender1 = (RadioButton) findViewById(R.id.rdoGender1); rdoGender2 = (RadioButton) findViewById(R.id.rdoGender2); rdogrpMS = (RadioGroup) findViewById(R.id.rdogrpMS); rdoMS1 = (RadioButton) findViewById(R.id.rdoMS1); rdoMS2 = (RadioButton) findViewById(R.id.rdoMS2); rdogrpSPNo1 = (RadioGroup) findViewById(R.id.rdogrpSPNo1); rdoSPNo11 = (RadioButton) findViewById(R.id.rdoSPNo11); rdoSPNo12 = (RadioButton) findViewById(R.id.rdoSPNo12); rdogrpSPNo2 = (RadioGroup) findViewById(R.id.rdogrpSPNo2); rdoSPNo13 = (RadioButton) findViewById(R.id.rdoSPNo13); rdoSPNo14 = (RadioButton) findViewById(R.id.rdoSPNo14); rdogrpSPNo3 = (RadioGroup) findViewById(R.id.rdogrpSPNo3); rdoSPNo15 = (RadioButton) findViewById(R.id.rdoSPNo15); rdoSPNo16 = (RadioButton) findViewById(R.id.rdoSPNo16); rdogrpSPNo4 = (RadioGroup) findViewById(R.id.rdogrpSPNo4); rdoSPNo17 = (RadioButton) findViewById(R.id.rdoSPNo17); rdoSPNo18 = (RadioButton) findViewById(R.id.rdoSPNo18); rdogrpEDU = (RadioGroup) findViewById(R.id.rdogrpEDU); rdoEDU1 = (RadioButton) findViewById(R.id.rdoEDU1); rdoEDU2 = (RadioButton) findViewById(R.id.rdoEDU2); rdogrpRel = (RadioGroup) findViewById(R.id.rdogrpRel); rdoRel1 = (RadioButton) findViewById(R.id.rdoRel1); rdoRel2 = (RadioButton) findViewById(R.id.rdoRel2); rdogrpNationality = (RadioGroup) findViewById(R.id.rdogrpNationality); rdoNationality1 = (RadioButton) findViewById(R.id.rdoNationality1); rdoNationality2 = (RadioButton) findViewById(R.id.rdoNationality2); rdogrpOCP = (RadioGroup) findViewById(R.id.rdogrpOCP); rdoOCP1 = (RadioButton) findViewById(R.id.rdoOCP1); rdoOCP2 = (RadioButton) findViewById(R.id.rdoOCP2); //DataSearch("93","9","71","78","1","10002","1"); Button cmdSave = (Button) findViewById(R.id.cmdSave); cmdSave.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DataSave(); } }); DataSearch(g.getDistrict(), g.getUpazila(), g.getUnion(), g.getMouza(), g.getVillage(), g.getHouseholdNo(), txtSNo.getText().toString()); FPIDataSearch(g.getDistrict(), g.getUpazila(), g.getUnion(), g.getMouza(), g.getVillage(), g.getHouseholdNo(), txtSNo.getText().toString()); } catch (Exception e) { Connection.MessageBox(MemberFormFPI.this, e.getMessage()); return; } } private void DataSave() { try { String SQL = ""; String AG = ""; if (!rdoNameEng1.isChecked() & !rdoNameEng2.isChecked() & secNameEng1.isShown()) { Connection.MessageBox(MemberFormFPI.this, "সদস্যের নাম যাচাই করুন ।"); rdoNameEng1.requestFocus(); return; } else if (!rdoRth1.isChecked() & !rdoRth2.isChecked() & secRth1.isShown()) { Connection.MessageBox(MemberFormFPI.this, "সদস্যের খানা প্রধানের সাথে সম্পর্ক যাচাই করুন ।"); rdoRth1.requestFocus(); return; } else if (!rdoNID1.isChecked() & !rdoNID2.isChecked() & secNID1.isShown()) { Connection.MessageBox(MemberFormFPI.this, "সদস্যের জাতীয় পরিচয় পত্র নম্বর যাচাই করুন ।"); rdoNID1.requestFocus(); return; } else if (!rdoNIDStatus1.isChecked() & !rdoNIDStatus2.isChecked() & secNIDStatus1.isShown()) { Connection.MessageBox(MemberFormFPI.this, "সদস্যের জাতীয় পরিচয় পত্র নম্বর না থাকলে কেন নাই যাচাই করুন ।"); rdoNIDStatus1.requestFocus(); return; } else if (!rdoBRID1.isChecked() & !rdoBRID2.isChecked() & secBRID1.isShown()) { Connection.MessageBox(MemberFormFPI.this, "সদস্যের জন্ম নিবন্ধন নম্বর যাচাই করুন ।"); rdoBRID1.requestFocus(); return; } else if (!rdoBRIDStatus1.isChecked() & !rdoBRIDStatus2.isChecked() & secBRIDStatus1.isShown()) { Connection.MessageBox(MemberFormFPI.this, "সদস্যের জন্ম নিবন্ধন নম্বর না থাকলে কেন নাই যাচাই করুন ।"); rdoBRIDStatus1.requestFocus(); return; } if (!C.Existence("Select Dist,Upz,UN,Mouza,Vill,HHNo,SNo from " + TableName + " Where Dist='" + g.getDistrict() + "' and Upz='" + g.getUpazila() + "' and UN='" + g.getUnion() + "' and Mouza='" + g.getMouza() + "' and Vill='" + g.getVillage() + "' and HHNo='" + g.getHouseholdNo() + "' and SNo='" + txtSNo.getText().toString() + "'")) { SQL = "Insert into " + TableName + "(Dist,Upz,UN,Mouza,Vill,ProvType,ProvCode,HHNo,SNo,HealthID,Lat,Lon,StartTime,EnType,EnDate,EndTime,ExType,ExDate,UserId,EnDt,Upload)Values('" + g.getDistrict() + "','" + g.getUpazila() + "','" + g.getUnion() + "','" + g.getMouza() + "','" + g.getVillage() + "','" + g.getProvType() + "','" + g.getProvCode() + "','" + g.getHouseholdNo() + "','" + txtSNo.getText() + "','" + txtHealthID.getText().toString() + "','" + Double.toString(currentLatitude) + "','" + Double.toString(currentLongitude) + "','" + StartTime + "','','" + g.DateNowYMD() + "','" + g.CurrentTime24() + "','','','" + g.getUserID() + "','" + Global.DateTimeNowYMDHMS() + "','2')"; C.Save(SQL); } SQL = "Update " + TableName + " Set Upload='2',"; SQL += "NameEngStatus = '" + (rdoNameEng1.isChecked() ? "1" : (rdoNameEng2.isChecked() ? "2" : "")) + "',"; SQL += "RTHStatus ='" + (rdoRth1.isChecked() ? "1" : (rdoRth2.isChecked() ? "2" : "")) + "',"; SQL += "HaveNIDStatus = '" + (rdoNID1.isChecked() ? "1" : (rdoNID2.isChecked() ? "2" : "")) + "',"; SQL += "NIDStatus = '" + (rdoNIDStatus1.isChecked() ? "1" : (rdoNIDStatus2.isChecked() ? "2" : "")) + "',"; SQL += "HaveBRStatus = '" + (rdoBRID1.isChecked() ? "1" : (rdoBRID2.isChecked() ? "2" : "")) + "',"; SQL += "BRIDStatus = '" + (rdoBRIDStatus1.isChecked() ? "1" : (rdoBRIDStatus2.isChecked() ? "2" : "")) + "',"; SQL += "MobileNo1Status = '" + (rdoMobileNo1.isChecked() ? "1" : (rdoMobileNo2.isChecked() ? "2" : "")) + "',"; SQL += "MobileNo2Status = '" + (rdoMobileNo21.isChecked() ? "1" : (rdoMobileNo22.isChecked() ? "2" : "")) + "',"; if (rdoDOBSource1.isChecked()) { SQL += "DOBStatus = '" + (rdoDOB1.isChecked() ? "1" : (rdoDOB2.isChecked() ? "2" : "")) + "',"; SQL += "AgeStatus = '" + (rdoAge1.isChecked() ? "1" : (rdoAge2.isChecked() ? "2" : "")) + "',"; } else { SQL += "DOBStatus = '" + (rdoDOB1.isChecked() ? "1" : (rdoDOB2.isChecked() ? "2" : "")) + "',"; SQL += "AgeStatus = '" + (rdoAge1.isChecked() ? "1" : (rdoAge2.isChecked() ? "2" : "")) + "',"; } SQL += "DOBSourceStatus = '" + (rdoDOBStatus1.isChecked() ? "1" : (rdoDOBStatus2.isChecked() ? "2" : "")) + "',"; SQL += "BPlaceStatus = '" + (rdoBPlace1.isChecked() ? "1" : (rdoBPlace2.isChecked() ? "2" : "")) + "',"; SQL += "FNoStatus = '" + (rdoFNo1.isChecked() ? "1" : (rdoFNo2.isChecked() ? "2" : "")) + "',"; SQL += "FatherStatus = '" + (rdoFather1.isChecked() ? "1" : (rdoFather2.isChecked() ? "2" : "")) + "',"; SQL += "MNoStatus = '" + (rdoMNo1.isChecked() ? "1" : (rdoMNo2.isChecked() ? "2" : "")) + "',"; SQL += "MotherStatus = '" + (rdoMother1.isChecked() ? "1" : (rdoMother2.isChecked() ? "2" : "")) + "',"; SQL += "SexStatus = '" + (rdoGender1.isChecked() ? "1" : (rdoGender2.isChecked() ? "2" : "")) + "',"; SQL += "MSStatus = '" + (rdoMS1.isChecked() ? "1" : (rdoMS2.isChecked() ? "2" : "")) + "',"; SQL += "SPNo1Status = '" + (rdoSPNo11.isChecked() ? "1" : (rdoSPNo12.isChecked() ? "2" : "")) + "',"; SQL += "SPNo2Status = '" + (rdoSPNo13.isChecked() ? "1" : (rdoSPNo14.isChecked() ? "2" : "")) + "',"; SQL += "SPNo3Status = '" + (rdoSPNo15.isChecked() ? "1" : (rdoSPNo16.isChecked() ? "2" : "")) + "',"; SQL += "SPNo4Status = '" + (rdoSPNo17.isChecked() ? "1" : (rdoSPNo18.isChecked() ? "2" : "")) + "',"; SQL += "EDUStatus = '" + (rdoEDU1.isChecked() ? "1" : (rdoEDU2.isChecked() ? "2" : "")) + "',"; SQL += "RelStatus = '" + (rdoRel1.isChecked() ? "1" : (rdoRel2.isChecked() ? "2" : "")) + "',"; SQL += "NationalityStatus = '" + (rdoNationality1.isChecked() ? "1" : (rdoNationality2.isChecked() ? "2" : "")) + "',"; SQL += "OCPStatus = '" + (rdoOCP1.isChecked() ? "1" : (rdoOCP2.isChecked() ? "2" : "")) + "'"; SQL += " Where Dist='" + g.getDistrict() + "' and Upz='" + g.getUpazila() + "' and UN='" + g.getUnion() + "' and Mouza='" + g.getMouza() + "' and Vill='" + g.getVillage() + "' and HHNo='" + g.getHouseholdNo() + "' and SNo='" + txtSNo.getText().toString() + "'"; C.Save(SQL); Connection.MessageBox(MemberFormFPI.this, "তথ্য সফলভাবে সংরক্ষণ হয়েছে।"); finish(); Intent f2 = new Intent(getApplicationContext(), MemberListFPI.class); startActivity(f2); } catch (Exception e) { Connection.MessageBox(MemberFormFPI.this, e.getMessage()); return; } } /* private int SpNoNoPosition(String spouseNo, int spSerial) { int pos = 0; if(spouseNo.length()!=0 & !spouseNo.equalsIgnoreCase("null")) { spouseNo = Integer.valueOf(spouseNo).toString(); String[] f; if(spSerial==1) { for (int i = 0; i < spnSPNo.getCount(); i++) { f = spnSPNo.getItemAtPosition(i).toString().split("-"); if (spnSPNo.getItemAtPosition(i).toString().length() != 0) { if (f[0].toString().equalsIgnoreCase(spouseNo)) { pos = i; i = spnSPNo.getCount(); } } } } else if(spSerial==2) { for (int i = 0; i < spnSPNo1.getCount(); i++) { f = spnSPNo1.getItemAtPosition(i).toString().split("-"); if (spnSPNo1.getItemAtPosition(i).toString().length() != 0) { if (f[0].toString().equalsIgnoreCase(spouseNo)) { pos = i; i = spnSPNo1.getCount(); } } } } if(spSerial==3) { for (int i = 0; i < spnSPNo2.getCount(); i++) { f = spnSPNo2.getItemAtPosition(i).toString().split("-"); if (spnSPNo2.getItemAtPosition(i).toString().length() != 0) { if (f[0].toString().equalsIgnoreCase(spouseNo)) { pos = i; i = spnSPNo2.getCount(); } } } } if(spSerial==4) { for (int i = 0; i < spnSPNo3.getCount(); i++) { f = spnSPNo3.getItemAtPosition(i).toString().split("-"); if (spnSPNo3.getItemAtPosition(i).toString().length() != 0) { if (f[0].toString().equalsIgnoreCase(spouseNo)) { pos = i; i = spnSPNo3.getCount(); } } } } } return pos; } private int FSerialNoPosition(String fatherNo) { int pos = 0; if(fatherNo.length()!=0) { fatherNo = Integer.valueOf(fatherNo).toString(); String[] f; for(int i=0;i<spnFNo.getCount();i++) { f = spnFNo.getItemAtPosition(i).toString().split("-"); if(spnFNo.getItemAtPosition(i).toString().length()!=0) { if(f[0].toString().equalsIgnoreCase(fatherNo)) { pos = i; i = spnFNo.getCount(); } } } } return pos; } private int MSerialNoPosition(String motherNo) { int pos = 0; if(motherNo.length()!=0) { motherNo = Integer.valueOf(motherNo).toString(); String[] m; for(int i=0;i<spnMNo.getCount();i++) { m = spnMNo.getItemAtPosition(i).toString().split("-"); if(spnMNo.getItemAtPosition(i).toString().length()!=0) { if(m[0].toString().equalsIgnoreCase(motherNo)) { pos = i; i = spnMNo.getCount(); } } } } return pos; }*/ private void DataSearch(String Dist, String Upz, String UN, String Mouza, String Vill, String HHNo, String SNo) { try { RadioButton rb; String SQL = ""; /*SQL = "Select FPI.Dist, FPI.Upz, FPI.UN, FPI.Mouza, FPI.Vill, FPI.HHNo, FPI.SNo as SNo, ifnull(FPI.HealthID,'') as HealthID,\n" + "ifnull(mem.NameEng,'') as NameEng,ifnull(FPI.NameEngStatus,'') as NameEngStatus,ifnull(mem.NameBang,'') as NameBang, \n" + "ifnull(mem.Rth,'') as Rth,ifnull(FPI.RthStatus,'') as RthStatus, ifnull(mem.HaveNID,'') as HaveNID,ifnull(FPI.HaveNIDStatus,'') as HaveNIDStatus,ifnull(mem.NID,'') as NID,ifnull(mem.NIDStatus,'') as NIDStatus,ifnull(FPI.NIDStatus,'') as FPINIDStatus,\n" + "ifnull(mem.HaveBR,'') as HaveBR,ifnull(FPI.HaveBRStatus,'') as HaveBRStatus,ifnull(mem.BRID,'') as BRID, ifnull(mem.BRIDStatus,'') as BRIDStatus,ifnull(FPI.BRIDStatus,'') as FPIBRIDStatus,ifnull(mem.MobileNo1,'') as MobileNo1,ifnull(FPI.MobileNo1Status,'') as MobileNo1Status,\n" + "ifnull(mem.MobileNo2,'') as MobileNo2,ifnull(FPI.MobileNo2Status,'') as MobileNo2Status, ifnull(mem.MobileYN,'')as MobileYN, ifnull(mem.DOB,'') as DOB,ifnull(FPI.DOBStatus,'') as DOBStatus,\n" + "ifnull(cast(((julianday(date('now'))-julianday(mem.DOB))/365)as int),'') as Age, ifnull(FPI.AgeStatus,'') as FPIAge,ifnull(mem.DOBSource,'') as DOBSource,ifnull(FPI.DOBSourceStatus,'') as DOBSourceStatus, \n" + "ifnull(mem.BPlace,'') as BPlace,ifnull(FPI.BPlaceStatus,'') as BPlaceStatus,ifnull(mem.FNo,'') as FNo,ifnull(FPI.FNoStatus,'') as FNoStatus,ifnull(mem.Father,'') as Father,ifnull(FPI.FatherStatus,'') as FatherStatus,ifnull(mem.FDontKnow,'')as FDontKnow, \n" + "ifnull(mem.MNo,'') as MNo,ifnull(FPI.MNoStatus,'') as MNoStatus,ifnull(mem.Mother,'') as Mother,ifnull(FPI.MotherStatus,'') as MotherStatus,ifnull(mem.MDontKnow,'')as MDontKnow,ifnull(mem.Sex,'') as Sex,ifnull(FPI.SexStatus,'') as SexStatus, \n" + "ifnull(mem.MS,'') as MS,ifnull(FPI.MSStatus,'') as MSStatus,ifnull(mem.SPNO1,'') as SPNO1,ifnull(FPI.SPNO1Status,'') as SPNO1Status,ifnull(mem.SPNO2,'') as SPNO2,ifnull(FPI.SPNO2Status,'') as SPNO2Status,ifnull(mem.SPNO3,'') as SPNO3,ifnull(FPI.SPNO3Status,'') as SPNO3Status,\n" + "ifnull(mem.SPNO4,'') as SPNO4,ifnull(FPI.SPNO4Status,'') as SPNO4Status,ifnull(mem.ELCONo,'') as ELCONo, ifnull(mem.ELCODontKnow,'') as ELCODontKnow, ifnull(mem.EDU,'') as EDU,ifnull(FPI.EDUStatus,'') as EDUStatus,ifnull(mem.Rel,'') as Rel,ifnull(FPI.RelStatus,'') as RelStatus,ifnull(mem.Nationality,'') as Nationality,ifnull(FPI.NationalityStatus,'') as NationalityStatus,ifnull(mem.OCP,'') as OCP,ifnull(FPI.OCPStatus,'') as OCPStatus\n" + "from MemberFPI FPI LEFT JOIN Member mem\n" + "ON mem.healthId = FPI.healthid Where FPI.Dist='"+ Dist +"' and FPI.Upz='"+ Upz +"' and FPI.UN='"+ UN +"' and FPI.Mouza='"+ Mouza +"' and FPI.Vill='"+ Vill +"' and FPI.HHNo='"+ HHNo +"' and FPI.SNo='"+ SNo +"'";*/ SQL = "Select Dist, Upz, UN, Mouza, Vill, HHNo, SNo as SNo, ifnull(HealthID,'') as HealthID, ifnull(NameEng,'') as NameEng,"; SQL += " ifnull(NameBang,'') as NameBang, ifnull(Rth,'') as Rth, ifnull(HaveNID,'') as HaveNID, ifnull(NID,'') as NID, ifnull(NIDStatus,'') as NIDStatus, ifnull(HaveBR,'') as HaveBR, ifnull(BRID,'') as BRID, ifnull(BRIDStatus,'') as BRIDStatus, ifnull(MobileNo1,'') as MobileNo1,"; SQL += " ifnull(MobileNo2,'') as MobileNo2, ifnull(MobileYN,'')as MobileYN, ifnull(DOB,'') as DOB, ifnull(cast(((julianday(date('now'))-julianday(DOB))/365)as int),'') as Age, ifnull(DOBSource,'') as DOBSource, ifnull(BPlace,'') as BPlace, ifnull(FNo,'') as FNo, ifnull(Father,'') as Father, ifnull(FDontKnow,'')as FDontKnow, ifnull(MNo,'') as MNo, ifnull(Mother,'') as Mother,ifnull(MDontKnow,'')as MDontKnow,"; SQL += " ifnull(Sex,'') as Sex, ifnull(MS,'') as MS, ifnull(SPNO1,'') as SPNO1,ifnull(SPNO2,'') as SPNO2,ifnull(SPNO3,'') as SPNO3,ifnull(SPNO4,'') as SPNO4, ifnull(ELCONo,'') as ELCONo, ifnull(ELCODontKnow,'') as ELCODontKnow, ifnull(EDU,'') as EDU, ifnull(Rel,'') as Rel, ifnull(Nationality,'') as Nationality, ifnull(OCP,'') as OCP"; SQL += " from Member Where Dist='" + Dist + "' and Upz='" + Upz + "' and UN='" + UN + "' and Mouza='" + Mouza + "' and Vill='" + Vill + "' and HHNo='" + HHNo + "' and SNo='" + SNo + "'"; Cursor cur = C.ReadData(SQL); cur.moveToFirst(); while (!cur.isAfterLast()) { chkIDHave.setEnabled(false); txtHealthID.setEnabled(false); txtHealthID.setText(cur.getString(cur.getColumnIndex("HealthID"))); txtSNo.setText(cur.getString(cur.getColumnIndex("SNo"))); txtNameEng.setText(cur.getString(cur.getColumnIndex("NameEng")).replace("null", "")); //txtNameBang.setText(cur.getString(cur.getColumnIndex("NameBang")).replace("null", "")); String RelWithHead = (cur.getString(cur.getColumnIndex("Rth")).toString()); if (RelWithHead.equalsIgnoreCase("00")) { txtRth.setText("00-খানা প্রধানের সাথে সম্পর্ক নাই"); } else if (RelWithHead.equalsIgnoreCase("01")) { txtRth.setText("01-নিজেই খানা প্রধান"); } else if (RelWithHead.equalsIgnoreCase("02")) { txtRth.setText("02-খানা প্রধানের স্বামী/স্ত্রী"); } else if (RelWithHead.equalsIgnoreCase("03")) { txtRth.setText("03-খানা প্রধানের ছেলে /মেয়ে"); } else if (RelWithHead.equalsIgnoreCase("04")) { txtRth.setText("04-খানা প্রধানের বাবা /মা"); } else if (RelWithHead.equalsIgnoreCase("05")) { txtRth.setText("05-খানা প্রধানের ভাই /বোন"); } else if (RelWithHead.equalsIgnoreCase("06")) { txtRth.setText("06-খানা প্রধানের চাচা/ফুফু/মামা/খালা"); } else if (RelWithHead.equalsIgnoreCase("07")) { txtRth.setText("07-খানা প্রধানের দাদা/দাদি/নানা/নানি"); } else if (RelWithHead.equalsIgnoreCase("08")) { txtRth.setText("08-খানা প্রধানের নাতি/নাতনী"); } else if (RelWithHead.equalsIgnoreCase("09")) { txtRth.setText("09-খানা প্রধানের শ্যালক/শ্যালিকা/দেবর/ননদ"); } else if (RelWithHead.equalsIgnoreCase("10")) { txtRth.setText("10-খানা প্রধানের শ্বশুর/শাশুড়ি"); } else if (RelWithHead.equalsIgnoreCase("11")) { txtRth.setText("11-খানা প্রধানের সৎ বাবা /মা"); } else if (RelWithHead.equalsIgnoreCase("12")) { txtRth.setText("12-খানা প্রধানের সৎ ছেলে /মেয়ে"); } else if (RelWithHead.equalsIgnoreCase("13")) { txtRth.setText("13-খানা প্রধানের পালিত ছেলে /মেয়ে"); } else if (RelWithHead.equalsIgnoreCase("14")) { txtRth.setText("14-খানা প্রধানের সৎ ভাই/বোন"); } else if (RelWithHead.equalsIgnoreCase("15")) { txtRth.setText("15-খানা প্রধানের ছেলের বউ/মেয়ের জামাই"); } else if (RelWithHead.equalsIgnoreCase("16")) { txtRth.setText("16-খানা প্রধানের ভাতিজা/ভাতিজী/ভাগ্নে/ভাগ্নি"); } else if (RelWithHead.equalsIgnoreCase("17")) { txtRth.setText("17-খানা প্রধানের বোন জামাই/ভাবি"); } else if (RelWithHead.equalsIgnoreCase("18")) { txtRth.setText("18-চাকর/চাকরানী"); } else if (RelWithHead.equalsIgnoreCase("77")) { txtRth.setText("77-অন্য সম্পর্ক যা উপরের তালিকায় নাই"); } else if (RelWithHead.equalsIgnoreCase("99")) { txtRth.setText("99-জানিনা"); } if (cur.getString(cur.getColumnIndex("HaveNID")).equals("1")) { chkNIDDontKnow.setChecked(false); //rdoHaveNID1.setChecked(true); secNID.setVisibility(View.VISIBLE); secNIDStatus.setVisibility(View.GONE); secNIDStatus1.setVisibility(View.GONE); } else if (cur.getString(cur.getColumnIndex("HaveNID")).equals("2")) { chkNIDDontKnow.setChecked(true); //rdoHaveNID2.setChecked(true); secNID.setVisibility(View.VISIBLE); secNIDStatus.setVisibility(View.VISIBLE); secNIDStatus1.setVisibility(View.VISIBLE); rdogrpNIDStatus.clearCheck(); } txtNID.setText(cur.getString(cur.getColumnIndex("NID")).replace("null", "")); //txtNIDStatus.setText(cur.getString(cur.getColumnIndex("NIDStatus")).replace("null","")); String NIDStatus = (cur.getString(cur.getColumnIndex("NIDStatus")).replace("null", "").toString()); if (NIDStatus.equalsIgnoreCase("1")) { txtNIDStatus.setText("1-কখনো ছিল না"); } else if (NIDStatus.equalsIgnoreCase("2")) { txtNIDStatus.setText("2-হারিয়ে ফেলেছি"); } else if (NIDStatus.equalsIgnoreCase("3")) { txtNIDStatus.setText("3-খুঁজে পাচ্ছি না"); } else if (NIDStatus.equalsIgnoreCase("4")) { txtNIDStatus.setText("4-অন্য জায়গায় আছে"); } else if (NIDStatus.equalsIgnoreCase("7")) { txtNIDStatus.setText("7-নাগরিক নয়"); } //spnNIDStatus.setSelection(Global.SpinnerItemPosition(spnNIDStatus, 1 ,cur.getString(cur.getColumnIndex("NIDStatus")))); /*if(cur.getString(cur.getColumnIndex("HaveNID")).equals("1")) { rdoHaveNID1.setChecked(true); secNID.setVisibility( View.VISIBLE ); secNIDStatus.setVisibility( View.VISIBLE ); } else if(cur.getString(cur.getColumnIndex("HaveNID")).equals("2")) { rdoHaveNID2.setChecked(true); secNID.setVisibility( View.GONE ); secNIDStatus.setVisibility( View.VISIBLE ); } txtNID.setText(cur.getString(cur.getColumnIndex("NID"))); spnNIDStatus.setSelection(Global.SpinnerItemPosition(spnNIDStatus, 1 ,cur.getString(cur.getColumnIndex("NIDStatus"))));*/ if (cur.getString(cur.getColumnIndex("HaveBR")).equals("1")) { chkBRIDDontKnow.setChecked(false); //rdoHaveBR1.setChecked(true); secBRID.setVisibility(View.VISIBLE); secBRIDStatus.setVisibility(View.GONE); secBRIDStatus1.setVisibility(View.GONE); } else if (cur.getString(cur.getColumnIndex("HaveBR")).equals("2")) { chkBRIDDontKnow.setChecked(true); //rdoHaveBR2.setChecked(true); secBRID.setVisibility(View.VISIBLE); secBRIDStatus.setVisibility(View.VISIBLE); secBRIDStatus1.setVisibility(View.VISIBLE); } /* if(cur.getString(cur.getColumnIndex("HaveBR")).equals("1")) { rdoHaveBR1.setChecked(true); secBRID.setVisibility( View.VISIBLE ); secBRIDStatus.setVisibility( View.VISIBLE ); } else if(cur.getString(cur.getColumnIndex("HaveBR")).equals("2")) { rdoHaveBR2.setChecked(true); secBRID.setVisibility( View.GONE ); secBRIDStatus.setVisibility( View.VISIBLE ); } */ txtBRID.setText(cur.getString(cur.getColumnIndex("BRID")).replace("null", "")); //txtBRIDStatus.setText(cur.getString(cur.getColumnIndex("BRIDStatus")).replace("null", "")); String BRIDStatus = (cur.getString(cur.getColumnIndex("BRIDStatus")).replace("null", "").toString()); if (BRIDStatus.equalsIgnoreCase("1")) { txtBRIDStatus.setText("1-কখনো ছিল না"); } else if (BRIDStatus.equalsIgnoreCase("2")) { txtBRIDStatus.setText("2-হারিয়ে ফেলেছি"); } else if (BRIDStatus.equalsIgnoreCase("3")) { txtBRIDStatus.setText("3-খুঁজে পাচ্ছি না"); } else if (BRIDStatus.equalsIgnoreCase("4")) { txtBRIDStatus.setText("4-অন্য জায়গায় আছে"); } else if (BRIDStatus.equalsIgnoreCase("7")) { txtBRIDStatus.setText("7-নাগরিক নয়"); } //spnBRIDStatus.setSelection(Global.SpinnerItemPosition(spnBRIDStatus, 1 ,cur.getString(cur.getColumnIndex("BRIDStatus")))); txtMobileNo1.setText(cur.getString(cur.getColumnIndex("MobileNo1")).replace("null", "")); txtMobileNo2.setText(cur.getString(cur.getColumnIndex("MobileNo2")).replace("null", "")); if (cur.getString(cur.getColumnIndex("MobileYN")).equals("1")) chkMobileNo.setChecked(true); else chkMobileNo.setChecked(false); if (cur.getString(cur.getColumnIndex("DOBSource")).equals("1")) rdoDOBSource1.setChecked(true); else rdoDOBSource2.setChecked(true); dtpDOB.setText(Global.DateConvertDMY(cur.getString(cur.getColumnIndex("DOB")))); txtAge.setText(cur.getString(cur.getColumnIndex("Age")).replace("null", "")); //txtBPlace.setText(cur.getString(cur.getColumnIndex("BPlace")).replace("null", "")); String BPlace = (cur.getString(cur.getColumnIndex("BPlace")).replace("null", "").toString()); if (BPlace.equalsIgnoreCase("93")) { txtBPlace.setText("93-টাঙ্গাইল"); } String FNo = (cur.getString(cur.getColumnIndex("FNo")).replace("null", "").toString()); if (FNo.equalsIgnoreCase("55")) { txtFNo.setText("55-মারা গিয়েছে"); secFather.setVisibility(View.VISIBLE); secFather1.setVisibility(View.VISIBLE); txtFather.setText(cur.getString(cur.getColumnIndex("Father")).replace("null", "")); } else if (FNo.equalsIgnoreCase("77")) { txtFNo.setText("77-এই খানার সদস্য না"); secFather.setVisibility(View.VISIBLE); secFather1.setVisibility(View.VISIBLE); txtFather.setText(cur.getString(cur.getColumnIndex("Father")).replace("null", "")); } else if (FNo.equalsIgnoreCase("88")) { txtFNo.setText("88-পরে আপডেট হবে"); } else { secFather.setVisibility(View.GONE); secFather1.setVisibility(View.GONE); txtFNo.setText(C.ReturnSingleValue("select ifnull(NameEng,'') as NameEng from Member where Dist='" + Dist + "' and Upz='" + Upz + "' and UN='" + UN + "' and Mouza='" + Mouza + "' and Vill='" + Vill + "' and HHNo='" + HHNo + "' and SNo='" + FNo + "'")); } if (cur.getString(cur.getColumnIndex("FDontKnow")).equals("1")) { chkFatherDontKnow.setChecked(true); } else { chkFatherDontKnow.setChecked(false); } /*if(cur.getString(cur.getColumnIndex("FNo")).endsWith( "77" )) { secFather.setVisibility( View.VISIBLE ); } else { secFather.setVisibility( View.GONE ); }*/ //txtMNo.setText(cur.getString(cur.getColumnIndex("MNo")).replace("null", "")); String MNo = (cur.getString(cur.getColumnIndex("MNo")).replace("null", "").toString()); if (MNo.equalsIgnoreCase("55")) { txtMNo.setText("55-মারা গিয়েছে"); secMother.setVisibility(View.VISIBLE); secMother1.setVisibility(View.VISIBLE); txtMother.setText(cur.getString(cur.getColumnIndex("Mother")).replace("null", "")); } else if (MNo.equalsIgnoreCase("77")) { txtMNo.setText("77-এই খানার সদস্য না"); secMother.setVisibility(View.VISIBLE); secMother1.setVisibility(View.VISIBLE); txtMother.setText(cur.getString(cur.getColumnIndex("Mother")).replace("null", "")); } else if (MNo.equalsIgnoreCase("88")) { txtMNo.setText("88-পরে আপডেট হবে"); } else { secMother.setVisibility(View.GONE); secMother1.setVisibility(View.GONE); txtMNo.setText(C.ReturnSingleValue("select ifnull(NameEng,'') as NameEng from Member where Dist='" + Dist + "' and Upz='" + Upz + "' and UN='" + UN + "' and Mouza='" + Mouza + "' and Vill='" + Vill + "' and HHNo='" + HHNo + "' and SNo='" + MNo + "'")); } //txtMother.setText(cur.getString(cur.getColumnIndex("Mother")).replace("null", "")); if (cur.getString(cur.getColumnIndex("MDontKnow")).equals("1")) { chkMotherDontKnow.setChecked(true); } else { chkMotherDontKnow.setChecked(false); } if (cur.getString(cur.getColumnIndex("Sex")).equals("1")) rdoSex1.setChecked(true); else if (cur.getString(cur.getColumnIndex("Sex")).equals("2")) rdoSex2.setChecked(true); else if (cur.getString(cur.getColumnIndex("Sex")).equals("3")) rdoSex3.setChecked(true); /*if(cur.getString(cur.getColumnIndex("MNo")).endsWith( "77" )) { secMother.setVisibility( View.VISIBLE ); } else { secMother.setVisibility(View.GONE); }*/ //txtMS.setText(cur.getString(cur.getColumnIndex("MS")).replace("null", "")); String MS = (cur.getString(cur.getColumnIndex("MS")).replace("null", "").toString()); if (MS.equalsIgnoreCase("1")) { txtMS.setText("1-অবিবাহিত"); secSP10.setVisibility(View.GONE); } else if (MS.equalsIgnoreCase("2")) { txtMS.setText("2-বিবাহিত"); } else if (MS.equalsIgnoreCase("3")) { txtMS.setText("3-বিধবা/বিপত্নীক"); } else if (MS.equalsIgnoreCase("4")) { txtMS.setText("4-স্বামী/স্ত্রী পৃথক"); } else if (MS.equalsIgnoreCase("5")) { txtMS.setText("5-তালাক প্রাপ্ত/ বিবাহ বিচ্ছিন্ন"); } //spnMS.setSelection(Global.SpinnerItemPosition(spnMS, 1, cur.getString(cur.getColumnIndex("MS")))); /* if(cur.getString(cur.getColumnIndex("SPNO1")).replace("null","").toString().trim().length()>0) { secSPNo.setVisibility(View.VISIBLE); spnSPNo.setSelection(SpNoNoPosition(cur.getString(cur.getColumnIndex("SPNO1")).replace("-", ""), 1)); } if(cur.getString(cur.getColumnIndex("SPNO2")).replace("null", "").toString().trim().length()>0) { secSPNo1.setVisibility(View.VISIBLE); spnSPNo1.setSelection(SpNoNoPosition(cur.getString(cur.getColumnIndex("SPNO2")).replace("-", ""), 2)); } else { secSPNo1.setVisibility(View.GONE); VlblSPNo1.setVisibility(View.GONE); } if(cur.getString(cur.getColumnIndex("SPNO3")).replace("null", "").toString().trim().length()>0) { secSPNo2.setVisibility(View.VISIBLE); spnSPNo2.setSelection(SpNoNoPosition(cur.getString(cur.getColumnIndex("SPNO3")).replace("-", ""), 3)); } else { secSPNo2.setVisibility(View.GONE); VlblSPNo2.setVisibility(View.GONE); } if(cur.getString(cur.getColumnIndex("SPNO4")).replace("null","").toString().trim().length()>0) { secSPNo3.setVisibility(View.VISIBLE); spnSPNo3.setSelection(SpNoNoPosition(cur.getString(cur.getColumnIndex("SPNO4")).replace("-",""), 4)); } else { secSPNo3.setVisibility(View.GONE); VlblSPNo3.setVisibility(View.GONE); }*/ //txtSPNo1.setText(cur.getString(cur.getColumnIndex("SPNO1"))); String SPNo1 = (cur.getString(cur.getColumnIndex("SPNO1")).replace("null", "").toString()); txtSPNo1.setText(C.ReturnSingleValue("select ifnull(NameEng,'') as NameEng from Member where Dist='" + Dist + "' and Upz='" + Upz + "' and UN='" + UN + "' and Mouza='" + Mouza + "' and Vill='" + Vill + "' and HHNo='" + HHNo + "' and SNo='" + SPNo1 + "'")); //txtSPNo2.setText(cur.getString(cur.getColumnIndex("SPNO2"))); String SPNo2 = (cur.getString(cur.getColumnIndex("SPNO2")).replace("null", "").toString()); txtSPNo2.setText(C.ReturnSingleValue("select ifnull(NameEng,'') as NameEng from Member where Dist='" + Dist + "' and Upz='" + Upz + "' and UN='" + UN + "' and Mouza='" + Mouza + "' and Vill='" + Vill + "' and HHNo='" + HHNo + "' and SNo='" + SPNo2 + "'")); //txtSPNo3.setText(cur.getString(cur.getColumnIndex("SPNO3"))); String SPNo3 = (cur.getString(cur.getColumnIndex("SPNO3")).replace("null", "").toString()); txtSPNo3.setText(C.ReturnSingleValue("select ifnull(NameEng,'') as NameEng from Member where Dist='" + Dist + "' and Upz='" + Upz + "' and UN='" + UN + "' and Mouza='" + Mouza + "' and Vill='" + Vill + "' and HHNo='" + HHNo + "' and SNo='" + SPNo3 + "'")); //txtSPNo4.setText(cur.getString(cur.getColumnIndex("SPNO4"))); String SPNo4 = (cur.getString(cur.getColumnIndex("SPNO4")).replace("null", "").toString()); txtSPNo4.setText(C.ReturnSingleValue("select ifnull(NameEng,'') as NameEng from Member where Dist='" + Dist + "' and Upz='" + Upz + "' and UN='" + UN + "' and Mouza='" + Mouza + "' and Vill='" + Vill + "' and HHNo='" + HHNo + "' and SNo='" + SPNo4 + "'")); if (!txtSPNo1.getText().toString().equalsIgnoreCase("")) { secSPNo.setVisibility(View.VISIBLE); } if (!txtSPNo2.getText().toString().equalsIgnoreCase("")) { secSPNo1.setVisibility(View.VISIBLE); secSPNo11.setVisibility(View.VISIBLE); } if (!txtSPNo3.getText().toString().equalsIgnoreCase("")) { secSPNo2.setVisibility(View.VISIBLE); secSPNo21.setVisibility(View.VISIBLE); } if (!txtSPNo4.getText().toString().equalsIgnoreCase("")) { secSPNo3.setVisibility(View.VISIBLE); secSPNo31.setVisibility(View.VISIBLE); } txtELCONo.setText(cur.getString(cur.getColumnIndex("ELCONo")).replace("null", "")); if (cur.getString(cur.getColumnIndex("ELCODontKnow")).equals("1")) { chkELCODontKnow.setChecked(true); } else if (cur.getString(cur.getColumnIndex("ELCODontKnow")).equals("2")) { chkELCODontKnow.setChecked(false); } if (cur.getString(cur.getColumnIndex("MS")).equalsIgnoreCase("2")) { //secELCONo.setVisibility( View.VISIBLE ); } else { //secELCONo.setVisibility( View.GONE ); //txtELCONo.setText(""); //chkELCODontKnow.setChecked( false ); } //txtEDU.setText(cur.getString(cur.getColumnIndex("EDU")).replace("null","")); String EDU = (cur.getString(cur.getColumnIndex("EDU")).replace("null", "").toString()); if (EDU.equalsIgnoreCase("00")) { txtEDU.setText("স্কুলে যায়নি বা প্রথম শ্রেণী পাশ করেনি"); } else if (EDU.equalsIgnoreCase("01")) { txtEDU.setText("১ম শ্রেনী"); } else if (EDU.equalsIgnoreCase("02")) { txtEDU.setText("২য় শ্রেনী"); } else if (EDU.equalsIgnoreCase("03")) { txtEDU.setText("৩য় শ্রেনী"); } else if (EDU.equalsIgnoreCase("04")) { txtEDU.setText("৪র্থ শ্রেনী"); } else if (EDU.equalsIgnoreCase("05")) { txtEDU.setText("৫ম শ্রেনী"); } else if (EDU.equalsIgnoreCase("06")) { txtEDU.setText("৬ষ্ঠ শ্রেনী"); } else if (EDU.equalsIgnoreCase("07")) { txtEDU.setText("৭ম শ্রেনী"); } else if (EDU.equalsIgnoreCase("08")) { txtEDU.setText("৮ম শ্রেনী"); } else if (EDU.equalsIgnoreCase("09")) { txtEDU.setText("৯ম শ্রেনী"); } else if (EDU.equalsIgnoreCase("10")) { txtEDU.setText("মাধ্যমিক বা সমতুল্য"); } else if (EDU.equalsIgnoreCase("11")) { txtEDU.setText("উচ্চ মাধ্যমিক বা সমতুল্য"); } else if (EDU.equalsIgnoreCase("12")) { txtEDU.setText("স্নাতক বা সমতুল্য"); } else if (EDU.equalsIgnoreCase("13")) { txtEDU.setText("স্নাতকোত্তর বা সমতুল্য"); } else if (EDU.equalsIgnoreCase("14")) { txtEDU.setText("ডাক্তারি"); } else if (EDU.equalsIgnoreCase("15")) { txtEDU.setText("ইঞ্জিনিয়ারিং"); } else if (EDU.equalsIgnoreCase("16")) { txtEDU.setText("বৃত্তিমুলক শিক্ষা"); } else if (EDU.equalsIgnoreCase("17")) { txtEDU.setText("কারিগরি শিক্ষা"); } else if (EDU.equalsIgnoreCase("18")) { txtEDU.setText("ধাত্রীবিদ্যা/নার্সিং"); } else if (EDU.equalsIgnoreCase("19")) { txtEDU.setText("অন্যান্য"); } else if (EDU.equalsIgnoreCase("77")) { txtEDU.setText("প্রযোজ্য নয়"); } else if (EDU.equalsIgnoreCase("99")) { txtEDU.setText("শিক্ষাগত যোগ্যতা নেই"); } /* listEDU.add("14-ডাক্তারি"); listEDU.add("15-ইঞ্জিনিয়ারিং"); listEDU.add("16-বৃত্তিমুলক শিক্ষা"); listEDU.add("17-কারিগরি শিক্ষা"); listEDU.add("18-ধাত্রীবিদ্যা/নার্সিং"); listEDU.add("19-অন্যান্য"); listEDU.add("77-প্রযোজ্য নয়"); listEDU.add("99-শিক্ষাগত যোগ্যতা নেই"); */ String Rel = (cur.getString(cur.getColumnIndex("Rel")).replace("null", "").toString()); if (Rel.equalsIgnoreCase("1")) { txtRel.setText("ইসলাম"); } else if (Rel.equalsIgnoreCase("2")) { txtRel.setText("হিন্দু"); } else if (Rel.equalsIgnoreCase("3")) { txtRel.setText("বৌদ্ধ"); } else if (Rel.equalsIgnoreCase("4")) { txtRel.setText("খ্রীস্টান"); } else if (Rel.equalsIgnoreCase("8")) { txtRel.setText("Refuse to disclose"); } else if (Rel.equalsIgnoreCase("0")) { txtRel.setText("Not a believer"); } else if (Rel.equalsIgnoreCase("0")) { txtRel.setText("অন্যান্য"); } //spnEDU.setSelection(Global.SpinnerItemPosition(spnEDU, 2 ,cur.getString(cur.getColumnIndex("EDU")))); //spnRel.setSelection(Global.SpinnerItemPosition(spnRel, 1 ,cur.getString(cur.getColumnIndex("Rel")))); if (cur.getString(cur.getColumnIndex("Nationality")).equals("1")) { chkNationality.setChecked(true); } else if (cur.getString(cur.getColumnIndex("Nationality")).equals("2")) { chkNationality.setChecked(false); } //txtOCP.setText(cur.getString(cur.getColumnIndex("OCP")).replace("null","")); String OCP = (cur.getString(cur.getColumnIndex("OCP")).replace("null", "").toString()); txtOCP.setText(C.ReturnSingleValue("select substr('0' ||ocpCode, -2, 2)||'-'||ifnull(ocpName,'') as ocpName from ocpList where ocpCode='" + OCP + "'")); cur.moveToNext(); } cur.close(); } catch (Exception e) { Connection.MessageBox(MemberFormFPI.this, e.getMessage()); return; } } //Search Status private void FPIDataSearch(String Dist, String Upz, String UN, String Mouza, String Vill, String HHNo, String SNo) { try { RadioButton rb; String SQL1 = ""; SQL1 = "Select FPI.Dist, FPI.Upz, FPI.UN, FPI.Mouza, FPI.Vill, FPI.HHNo, FPI.SNo as SNo, ifnull(FPI.HealthID,'') as HealthID,\n" + "ifnull(FPI.NameEngStatus,'') as NameEngStatus,ifnull(FPI.RthStatus,'') as RthStatus,ifnull(FPI.HaveNIDStatus,'') as HaveNIDStatus,ifnull(FPI.NIDStatus,'') as FPINIDStatus,\n" + "ifnull(FPI.HaveBRStatus,'') as HaveBRStatus,ifnull(FPI.BRIDStatus,'') as FPIBRIDStatus,ifnull(FPI.MobileNo1Status,'') as MobileNo1Status,\n" + "ifnull(FPI.MobileNo2Status,'') as MobileNo2Status,ifnull(FPI.DOBStatus,'') as DOBStatus,ifnull(FPI.AgeStatus,'') as FPIAge,ifnull(FPI.DOBSourceStatus,'') as DOBSourceStatus, \n" + "ifnull(FPI.BPlaceStatus,'') as BPlaceStatus,ifnull(FPI.FNoStatus,'') as FNoStatus,ifnull(FPI.FatherStatus,'') as FatherStatus, \n" + "ifnull(FPI.MNoStatus,'') as MNoStatus,ifnull(FPI.MotherStatus,'') as MotherStatus,ifnull(FPI.SexStatus,'') as SexStatus, \n" + "ifnull(FPI.MSStatus,'') as MSStatus,ifnull(FPI.SPNO1Status,'') as SPNO1Status,ifnull(FPI.SPNO2Status,'') as SPNO2Status,ifnull(FPI.SPNO3Status,'') as SPNO3Status,\n" + "ifnull(FPI.SPNO4Status,'') as SPNO4Status,ifnull(FPI.EDUStatus,'') as EDUStatus,ifnull(FPI.RelStatus,'') as RelStatus,ifnull(FPI.NationalityStatus,'') as NationalityStatus,ifnull(FPI.OCPStatus,'') as OCPStatus\n" + "from MemberFPI FPI Where Dist='" + Dist + "' and Upz='" + Upz + "' and UN='" + UN + "' and Mouza='" + Mouza + "' and Vill='" + Vill + "' and HHNo='" + HHNo + "' and SNo='" + SNo + "'"; /*SQL += " ifnull(NameBang,'') as NameBang, ifnull(Rth,'') as Rth, ifnull(HaveNID,'') as HaveNID, ifnull(NID,'') as NID, ifnull(NIDStatus,'') as NIDStatus, ifnull(HaveBR,'') as HaveBR, ifnull(BRID,'') as BRID, ifnull(BRIDStatus,'') as BRIDStatus, ifnull(MobileNo1,'') as MobileNo1,"; SQL += " ifnull(MobileNo2,'') as MobileNo2, ifnull(MobileYN,'')as MobileYN, ifnull(DOB,'') as DOB, ifnull(cast(((julianday(date('now'))-julianday(DOB))/365)as int),'') as Age, ifnull(DOBSource,'') as DOBSource, ifnull(BPlace,'') as BPlace, ifnull(FNo,'') as FNo, ifnull(Father,'') as Father, ifnull(FDontKnow,'')as FDontKnow, ifnull(MNo,'') as MNo, ifnull(Mother,'') as Mother,ifnull(MDontKnow,'')as MDontKnow,"; SQL += " ifnull(Sex,'') as Sex, ifnull(MS,'') as MS, ifnull(SPNO1,'') as SPNO1,ifnull(SPNO2,'') as SPNO2,ifnull(SPNO3,'') as SPNO3,ifnull(SPNO4,'') as SPNO4, ifnull(ELCONo,'') as ELCONo, ifnull(ELCODontKnow,'') as ELCODontKnow, ifnull(EDU,'') as EDU, ifnull(Rel,'') as Rel, ifnull(Nationality,'') as Nationality, ifnull(OCP,'') as OCP";*/ //SQL1 += " from MemberFPI Where Dist='"+ Dist +"' and Upz='"+ Upz +"' and UN='"+ UN +"' and Mouza='"+ Mouza +"' and Vill='"+ Vill +"' and HHNo='"+ HHNo +"' and SNo='"+ SNo +"'"; Cursor cur1 = C.ReadData(SQL1); cur1.moveToFirst(); while (!cur1.isAfterLast()) { /*for (int i = 0; i < rdogrpNameEng.getChildCount(); i++) { rb = (RadioButton)rdogrpNameEng.getChildAt(i); if (Global.Left(rb.getText().toString(), 1).equalsIgnoreCase(cur1.getString(cur1.getColumnIndex("NameEngStatus")))) rb.setChecked(true); else rb.setChecked(false); }*/ //-----------FPI Retrived------------------- if (cur1.getString(cur1.getColumnIndex("NameEngStatus")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoNameEng1.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("NameEngStatus")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoNameEng2.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("RthStatus")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoRth1.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("RthStatus")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoRth2.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("HaveNIDStatus")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoNID1.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("HaveNIDStatus")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoNID2.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("FPINIDStatus")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoNIDStatus1.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("FPINIDStatus")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoNIDStatus2.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("HaveBRStatus")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoBRID1.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("HaveBRStatus")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoBRID2.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("FPIBRIDStatus")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoBRIDStatus1.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("FPIBRIDStatus")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoBRIDStatus2.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("MobileNo1Status")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoMobileNo1.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("MobileNo1Status")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoMobileNo2.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("MobileNo2Status")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoMobileNo21.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("MobileNo2Status")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoMobileNo22.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("DOBStatus")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoDOB1.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("DOBStatus")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoDOB2.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("FPIAge")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoAge1.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("FPIAge")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoAge2.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("DOBSourceStatus")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoDOBStatus1.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("DOBSourceStatus")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoDOBStatus2.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("BPlaceStatus")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoBPlace1.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("BPlaceStatus")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoBPlace2.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("FNoStatus")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoFNo1.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("FNoStatus")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoFNo2.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("FatherStatus")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoFather1.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("FatherStatus")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoFather2.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("MNoStatus")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoMNo1.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("MNoStatus")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoMNo2.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("MotherStatus")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoMother1.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("MotherStatus")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoMother2.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("SexStatus")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoGender1.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("SexStatus")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoGender2.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("MSStatus")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoMS1.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("MSStatus")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoMS2.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("SPNO1Status")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoSPNo11.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("SPNO1Status")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoSPNo12.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("SPNO2Status")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoSPNo13.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("SPNO2Status")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoSPNo14.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("SPNO3Status")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoSPNo15.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("SPNO3Status")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoSPNo16.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("SPNO4Status")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoSPNo17.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("SPNO4Status")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoSPNo18.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("EDUStatus")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoEDU1.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("EDUStatus")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoEDU2.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("RelStatus")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoRel1.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("RelStatus")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoRel2.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("NationalityStatus")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoNationality1.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("NationalityStatus")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoNationality2.setChecked(true); } if (cur1.getString(cur1.getColumnIndex("OCPStatus")).replace("null", "").toString().equalsIgnoreCase("1")) { rdoOCP1.setChecked(true); } else if (cur1.getString(cur1.getColumnIndex("OCPStatus")).replace("null", "").toString().equalsIgnoreCase("2")) { rdoOCP2.setChecked(true); } cur1.moveToNext(); } cur1.close(); } catch (Exception e) { Connection.MessageBox(MemberFormFPI.this, e.getMessage()); return; } } //GPS Reading //..................................................................................................... public void FindLocation() { LocationManager locationManager = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE); LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { updateLocation(location); } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }; locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); } void updateLocation(Location location) { currentLocation = location; currentLatitude = currentLocation.getLatitude(); currentLongitude = currentLocation.getLongitude(); } // Method to turn on GPS public void turnGPSOn() { try { String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); if (!provider.contains("gps")) { //if gps is disabled final Intent poke = new Intent(); poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); poke.addCategory(Intent.CATEGORY_ALTERNATIVE); poke.setData(Uri.parse("3")); sendBroadcast(poke); } } catch (Exception e) { } } // Method to turn off the GPS public void turnGPSOff() { String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); if (provider.contains("gps")) { //if gps is enabled final Intent poke = new Intent(); poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); poke.addCategory(Intent.CATEGORY_ALTERNATIVE); poke.setData(Uri.parse("3")); sendBroadcast(poke); } } // turning off the GPS if its in on state. to avoid the battery drain. @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); turnGPSOff(); } }
package exer; import java.util.HashMap; import java.util.Scanner; /** * @author menglanyingfei * @date 2017-7-14 */ public class Main03_Distance { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<String, Integer>(); Scanner in = new Scanner(System.in); String str; int cnt = 0; while (true) { str = in.next(); if (str.equals("###")) { break; } else { map.put(str, ++cnt); } } int[][] arr = new int[cnt][cnt]; for (int i = 0; i < cnt; i++) { for (int j = 0; j < cnt; j++) { arr[i][j] = in.nextInt(); } } String place1 = in.next(); String place2 = in.next(); int num1 = map.get(place1); int num2 = map.get(place2); System.out.println(arr[num1 - 1][num2 - 1]); } }
package br.com.matheusvieira.appleilaoii; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.text.NumberFormat; import java.util.Locale; public class RecebeLanceActivity extends AppCompatActivity implements View.OnClickListener { private TextView txtObra; private TextView txtLanceMin; private EditText edtCliente; private EditText edtEmail; private EditText edtLance; private Button btnEnviar; private double lanceMin; private TextView txtMensa; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recebe_lance); txtObra = (TextView) findViewById(R.id.txtObra); txtLanceMin = (TextView) findViewById(R.id.txtLanceMin); edtCliente = (EditText) findViewById(R.id.edtCliente); edtEmail = (EditText) findViewById(R.id.edtEmail); edtLance = (EditText) findViewById(R.id.edtLance); btnEnviar = (Button) findViewById(R.id.btnEnviar); txtMensa = (TextView) findViewById(R.id.txtMensa); Intent it = getIntent(); String obra = it.getStringExtra("obra"); lanceMin = it.getDoubleExtra("lanceMin", -1); txtObra.setText("Obra em Leilão: " + obra); NumberFormat nfNr = NumberFormat.getCurrencyInstance(new Locale("pt", "BR")); txtLanceMin.setText("Lance Mínimo: "+nfNr.format(lanceMin)); btnEnviar.setOnClickListener(this); } @Override public void onClick(View view) { String cliente = edtCliente.getText().toString(); String email = edtEmail.getText().toString(); String lance = edtLance.getText().toString(); if(cliente.trim().isEmpty() || email.trim().isEmpty() || lance.trim().isEmpty()){ Toast.makeText(this, "Erro... Preencha os campos!", Toast.LENGTH_LONG).show(); edtCliente.requestFocus(); return; } if(Double.parseDouble(lance)<lanceMin){ Toast.makeText(this, "Erro... Lance inferiror ao minimo!", Toast.LENGTH_LONG).show(); edtLance.requestFocus(); return; } EnviaLance enviaLance = new EnviaLance(txtMensa); enviaLance.execute("http://192.168.200.3/edecio/gravalance.php", cliente, email, lance); } }
/** * Spring Framework configuration files. */ package com.africa.gateway.config;
package tests; import weightlifting.WeightLifter; import utest.*; import java.util.Arrays; public class Part1 extends Testable { public void assertion() { check("WeightLifter.getStrongestWeightLifter: a metodusnak null-t kell visszaadnia, ha meg nem hoztak letre WeightLifter objektumot.", WeightLifter.getStrongestWeightLifter() == null); WeightLifter wl1 = WeightLifter.make("A", 15); check("WeightLifter.make: tul rovid nevhez is letrehozza az objektumot.", wl1 == null); wl1 = WeightLifter.make("ABC", -5); check("WeightLifter.make: negativ sulynal is letrehozza az objektumot.", wl1 == null); wl1 = WeightLifter.make("ABC", 0); check("WeightLifter.make: nulla erteku sulynal is letrehozza az objektumot.", wl1 == null); wl1 = WeightLifter.make("ABC", 301); check("WeightLifter.make: tul nagy sulynal is letrehozza az objektumot.", wl1 == null); wl1 = WeightLifter.make("AB,C", 200); check("WeightLifter.make: illegalis karaktert tartalmazo nevnel is letrehozza az objektumot.", wl1 == null); wl1 = WeightLifter.make("Ivan Ivanov", 120); check("WeightLifter.make: helyes parameterekkel sem hozza letre az objektumot.", wl1 != null); check("WeightLifter.getWeight: a metodus nem ad vissza helyes adatot.", wl1.getWeight() == 120); WeightLifter wl2 = WeightLifter.make("Foldi Imre", 137); check("WeightLifter.strongerThan: a metodus nem ad vissza helyes adatot.", !wl1.strongerThan(wl2)); check("WeightLifter.strongerThan: a metodus nem ad vissza helyes adatot.", wl2.strongerThan(wl1)); check("WeightLifter.show: a metodus nem ad vissza helyes adatot haromszamjegyu sulynal.", wl1.show().equals("Ivan Ivanov - 120 kg")); WeightLifter wl3 = WeightLifter.make("Pablo Lara", 25); check("WeightLifter.show: a metodus nem ad vissza helyes adatot ketszamjegyu sulynal.", wl3.show().equals("Pablo Lara - 25 kg")); WeightLifter wl4 = WeightLifter.make("Aleksey Petrov", 9); check("WeightLifter.show: a metodus nem ad vissza helyes adatot egyszamjegyu sulynal.", wl4.show().equals("Aleksey Petrov - 9 kg")); check("WeightLifter.getStrongestWeightLifter: a metodus nem a valaha letrehozott legerosebb WeightLifter objektumot adja vissza.", WeightLifter.getStrongestWeightLifter().show().equals(wl2.show())); WeightLifter wl5 = WeightLifter.make("Koji Miki", 137); check("WeightLifter.strongerThan: a metodus nem ad vissza helyes adatot egyforma erossegu sulyemeloknel.", !wl5.strongerThan(wl2)); check("WeightLifter.strongerThan: a metodus nem ad vissza helyes adatot egyforma erossegu sulyemeloknel.", !wl2.strongerThan(wl5)); check("WeightLifter.getStrongestWeightLifter: ha a valaha letrehozott legerosebb sulyemelovel egyforma erossegu is van, akkor a metodusnak ezek kozul a legkorabban letrehozottat kell visszaania.", WeightLifter.getStrongestWeightLifter().show().equals(wl2.show())); } public String description() { return "1. resz"; } public String className() { return "weightlifting.WeightLifter"; } public Object[] expectedMethods() throws Exception { return new Object[] { constructor(className(), new Class[] {String.class, Integer.TYPE}) , staticMethod(className() + ".make", String.class, Integer.TYPE) , method(className() + ".getWeight") , method(className() + ".strongerThan", weightlifting.WeightLifter.class) , method(className() + ".show") , staticMethod(className() + ".getStrongestWeightLifter") }; } public static void main(String... args) { Test.main(new Part1()); } }
package service; import domain.Curso; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import repository.CursoRepository; import javax.transaction.Transactional; import java.util.Collection; @Service public class CursoService { @Autowired CursoRepository repository; @Transactional public void save(Curso curso) { repository.save(curso); } public Collection<Curso> getAll() { return repository.findAll(); } public Curso getById(Long id) { return repository.findOne(id); } public Collection<Curso> getByNombre(String nombre) { return repository.getByNombre(nombre); } }
/* * 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 Aula4.Questao2; import java.util.List; import java.util.ArrayList; /** * * @author mauricio.moreira */ public class Professor2 { public String nome; public int id; public List<Disciplina2> disciplinas = new ArrayList<Disciplina2>(); Professor2(String nome, int id){ this.nome = nome; this.id = id; } public String getNomeProfessor(){ return this.nome; } public int getId(){ return this.id; } public void addDisciplina(Disciplina2 disciplina) { this.disciplinas.add(disciplina); } public int getTotalDisciplinas(){ int totalDisciplinas = 0; for (Disciplina2 d: disciplinas) { totalDisciplinas++; } return totalDisciplinas; } public void getNomeDasDisciplinas() { for (Disciplina2 d: disciplinas) { System.out.println(d.getNomeDisciplina()); } } }
package jp.abyss.sysparticle.api.particle; public interface PointParticleListEditable { }
package com.fmachinus.practice.entity.mapping; import com.fmachinus.practice.entity.Customer; import com.fmachinus.practice.entity.dto.CustomerDto; import org.mapstruct.Mapper; import org.mapstruct.factory.Mappers; @Mapper public interface CustomerMapper { CustomerMapper MAPPER = Mappers.getMapper(CustomerMapper.class); CustomerDto fromCustomer(Customer customer); Customer toCustomer(CustomerDto customerDto); }
package com.lqs.hrm.entity; import java.util.ArrayList; import java.util.Date; import java.util.List; public class PositionLevelExample { /** * This field was generated by MyBatis Generator. This field corresponds to the database table position_level * @mbg.generated Mon May 25 00:12:01 CST 2020 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. This field corresponds to the database table position_level * @mbg.generated Mon May 25 00:12:01 CST 2020 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. This field corresponds to the database table position_level * @mbg.generated Mon May 25 00:12:01 CST 2020 */ protected List<Criteria> oredCriteria; /** * This method was generated by MyBatis Generator. This method corresponds to the database table position_level * @mbg.generated Mon May 25 00:12:01 CST 2020 */ public PositionLevelExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method was generated by MyBatis Generator. This method corresponds to the database table position_level * @mbg.generated Mon May 25 00:12:01 CST 2020 */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * This method was generated by MyBatis Generator. This method corresponds to the database table position_level * @mbg.generated Mon May 25 00:12:01 CST 2020 */ public String getOrderByClause() { return orderByClause; } /** * This method was generated by MyBatis Generator. This method corresponds to the database table position_level * @mbg.generated Mon May 25 00:12:01 CST 2020 */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * This method was generated by MyBatis Generator. This method corresponds to the database table position_level * @mbg.generated Mon May 25 00:12:01 CST 2020 */ public boolean isDistinct() { return distinct; } /** * This method was generated by MyBatis Generator. This method corresponds to the database table position_level * @mbg.generated Mon May 25 00:12:01 CST 2020 */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method was generated by MyBatis Generator. This method corresponds to the database table position_level * @mbg.generated Mon May 25 00:12:01 CST 2020 */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method was generated by MyBatis Generator. This method corresponds to the database table position_level * @mbg.generated Mon May 25 00:12:01 CST 2020 */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method was generated by MyBatis Generator. This method corresponds to the database table position_level * @mbg.generated Mon May 25 00:12:01 CST 2020 */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method was generated by MyBatis Generator. This method corresponds to the database table position_level * @mbg.generated Mon May 25 00:12:01 CST 2020 */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * This method was generated by MyBatis Generator. This method corresponds to the database table position_level * @mbg.generated Mon May 25 00:12:01 CST 2020 */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. This class corresponds to the database table position_level * @mbg.generated Mon May 25 00:12:01 CST 2020 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andPlIdIsNull() { addCriterion("pl_id is null"); return (Criteria) this; } public Criteria andPlIdIsNotNull() { addCriterion("pl_id is not null"); return (Criteria) this; } public Criteria andPlIdEqualTo(Integer value) { addCriterion("pl_id =", value, "plId"); return (Criteria) this; } public Criteria andPlIdNotEqualTo(Integer value) { addCriterion("pl_id <>", value, "plId"); return (Criteria) this; } public Criteria andPlIdGreaterThan(Integer value) { addCriterion("pl_id >", value, "plId"); return (Criteria) this; } public Criteria andPlIdGreaterThanOrEqualTo(Integer value) { addCriterion("pl_id >=", value, "plId"); return (Criteria) this; } public Criteria andPlIdLessThan(Integer value) { addCriterion("pl_id <", value, "plId"); return (Criteria) this; } public Criteria andPlIdLessThanOrEqualTo(Integer value) { addCriterion("pl_id <=", value, "plId"); return (Criteria) this; } public Criteria andPlIdIn(List<Integer> values) { addCriterion("pl_id in", values, "plId"); return (Criteria) this; } public Criteria andPlIdNotIn(List<Integer> values) { addCriterion("pl_id not in", values, "plId"); return (Criteria) this; } public Criteria andPlIdBetween(Integer value1, Integer value2) { addCriterion("pl_id between", value1, value2, "plId"); return (Criteria) this; } public Criteria andPlIdNotBetween(Integer value1, Integer value2) { addCriterion("pl_id not between", value1, value2, "plId"); return (Criteria) this; } public Criteria andLevelIsNull() { addCriterion("level is null"); return (Criteria) this; } public Criteria andLevelIsNotNull() { addCriterion("level is not null"); return (Criteria) this; } public Criteria andLevelEqualTo(Integer value) { addCriterion("level =", value, "level"); return (Criteria) this; } public Criteria andLevelNotEqualTo(Integer value) { addCriterion("level <>", value, "level"); return (Criteria) this; } public Criteria andLevelGreaterThan(Integer value) { addCriterion("level >", value, "level"); return (Criteria) this; } public Criteria andLevelGreaterThanOrEqualTo(Integer value) { addCriterion("level >=", value, "level"); return (Criteria) this; } public Criteria andLevelLessThan(Integer value) { addCriterion("level <", value, "level"); return (Criteria) this; } public Criteria andLevelLessThanOrEqualTo(Integer value) { addCriterion("level <=", value, "level"); return (Criteria) this; } public Criteria andLevelIn(List<Integer> values) { addCriterion("level in", values, "level"); return (Criteria) this; } public Criteria andLevelNotIn(List<Integer> values) { addCriterion("level not in", values, "level"); return (Criteria) this; } public Criteria andLevelBetween(Integer value1, Integer value2) { addCriterion("level between", value1, value2, "level"); return (Criteria) this; } public Criteria andLevelNotBetween(Integer value1, Integer value2) { addCriterion("level not between", value1, value2, "level"); return (Criteria) this; } public Criteria andLevelDescIsNull() { addCriterion("level_desc is null"); return (Criteria) this; } public Criteria andLevelDescIsNotNull() { addCriterion("level_desc is not null"); return (Criteria) this; } public Criteria andLevelDescEqualTo(String value) { addCriterion("level_desc =", value, "levelDesc"); return (Criteria) this; } public Criteria andLevelDescNotEqualTo(String value) { addCriterion("level_desc <>", value, "levelDesc"); return (Criteria) this; } public Criteria andLevelDescGreaterThan(String value) { addCriterion("level_desc >", value, "levelDesc"); return (Criteria) this; } public Criteria andLevelDescGreaterThanOrEqualTo(String value) { addCriterion("level_desc >=", value, "levelDesc"); return (Criteria) this; } public Criteria andLevelDescLessThan(String value) { addCriterion("level_desc <", value, "levelDesc"); return (Criteria) this; } public Criteria andLevelDescLessThanOrEqualTo(String value) { addCriterion("level_desc <=", value, "levelDesc"); return (Criteria) this; } public Criteria andLevelDescLike(String value) { addCriterion("level_desc like", value, "levelDesc"); return (Criteria) this; } public Criteria andLevelDescNotLike(String value) { addCriterion("level_desc not like", value, "levelDesc"); return (Criteria) this; } public Criteria andLevelDescIn(List<String> values) { addCriterion("level_desc in", values, "levelDesc"); return (Criteria) this; } public Criteria andLevelDescNotIn(List<String> values) { addCriterion("level_desc not in", values, "levelDesc"); return (Criteria) this; } public Criteria andLevelDescBetween(String value1, String value2) { addCriterion("level_desc between", value1, value2, "levelDesc"); return (Criteria) this; } public Criteria andLevelDescNotBetween(String value1, String value2) { addCriterion("level_desc not between", value1, value2, "levelDesc"); return (Criteria) this; } public Criteria andLastOperatorDateIsNull() { addCriterion("last_operator_date is null"); return (Criteria) this; } public Criteria andLastOperatorDateIsNotNull() { addCriterion("last_operator_date is not null"); return (Criteria) this; } public Criteria andLastOperatorDateEqualTo(Date value) { addCriterion("last_operator_date =", value, "lastOperatorDate"); return (Criteria) this; } public Criteria andLastOperatorDateNotEqualTo(Date value) { addCriterion("last_operator_date <>", value, "lastOperatorDate"); return (Criteria) this; } public Criteria andLastOperatorDateGreaterThan(Date value) { addCriterion("last_operator_date >", value, "lastOperatorDate"); return (Criteria) this; } public Criteria andLastOperatorDateGreaterThanOrEqualTo(Date value) { addCriterion("last_operator_date >=", value, "lastOperatorDate"); return (Criteria) this; } public Criteria andLastOperatorDateLessThan(Date value) { addCriterion("last_operator_date <", value, "lastOperatorDate"); return (Criteria) this; } public Criteria andLastOperatorDateLessThanOrEqualTo(Date value) { addCriterion("last_operator_date <=", value, "lastOperatorDate"); return (Criteria) this; } public Criteria andLastOperatorDateIn(List<Date> values) { addCriterion("last_operator_date in", values, "lastOperatorDate"); return (Criteria) this; } public Criteria andLastOperatorDateNotIn(List<Date> values) { addCriterion("last_operator_date not in", values, "lastOperatorDate"); return (Criteria) this; } public Criteria andLastOperatorDateBetween(Date value1, Date value2) { addCriterion("last_operator_date between", value1, value2, "lastOperatorDate"); return (Criteria) this; } public Criteria andLastOperatorDateNotBetween(Date value1, Date value2) { addCriterion("last_operator_date not between", value1, value2, "lastOperatorDate"); return (Criteria) this; } public Criteria andOperatorEmpjobidIsNull() { addCriterion("operator_empJobId is null"); return (Criteria) this; } public Criteria andOperatorEmpjobidIsNotNull() { addCriterion("operator_empJobId is not null"); return (Criteria) this; } public Criteria andOperatorEmpjobidEqualTo(String value) { addCriterion("operator_empJobId =", value, "operatorEmpjobid"); return (Criteria) this; } public Criteria andOperatorEmpjobidNotEqualTo(String value) { addCriterion("operator_empJobId <>", value, "operatorEmpjobid"); return (Criteria) this; } public Criteria andOperatorEmpjobidGreaterThan(String value) { addCriterion("operator_empJobId >", value, "operatorEmpjobid"); return (Criteria) this; } public Criteria andOperatorEmpjobidGreaterThanOrEqualTo(String value) { addCriterion("operator_empJobId >=", value, "operatorEmpjobid"); return (Criteria) this; } public Criteria andOperatorEmpjobidLessThan(String value) { addCriterion("operator_empJobId <", value, "operatorEmpjobid"); return (Criteria) this; } public Criteria andOperatorEmpjobidLessThanOrEqualTo(String value) { addCriterion("operator_empJobId <=", value, "operatorEmpjobid"); return (Criteria) this; } public Criteria andOperatorEmpjobidLike(String value) { addCriterion("operator_empJobId like", value, "operatorEmpjobid"); return (Criteria) this; } public Criteria andOperatorEmpjobidNotLike(String value) { addCriterion("operator_empJobId not like", value, "operatorEmpjobid"); return (Criteria) this; } public Criteria andOperatorEmpjobidIn(List<String> values) { addCriterion("operator_empJobId in", values, "operatorEmpjobid"); return (Criteria) this; } public Criteria andOperatorEmpjobidNotIn(List<String> values) { addCriterion("operator_empJobId not in", values, "operatorEmpjobid"); return (Criteria) this; } public Criteria andOperatorEmpjobidBetween(String value1, String value2) { addCriterion("operator_empJobId between", value1, value2, "operatorEmpjobid"); return (Criteria) this; } public Criteria andOperatorEmpjobidNotBetween(String value1, String value2) { addCriterion("operator_empJobId not between", value1, value2, "operatorEmpjobid"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. This class corresponds to the database table position_level * @mbg.generated Mon May 25 00:12:01 CST 2020 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table position_level * * @mbg.generated do_not_delete_during_merge Sun Apr 12 14:49:04 CST 2020 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } }
/* * Copyright 2011 Sergio Moyano Serrano. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.ac.brunel.sc2dm.server; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; /** * @author Sergio Moyano Serrano * Created: 12:42 - 2/06/11 */ public class SC2DMConnection { private static String DEFAULT_URL = "https://android.apis.google.com/c2dm/send"; private static String METHOD_POST = "POST"; private String method = null; private URL url = null; private HttpURLConnection connection = null; private boolean connected = false; public SC2DMConnection (String accountType, String senderId, String password, String service, String source ) { try { this.url = new URL(DEFAULT_URL); this.method = METHOD_POST; SC2DMAuthToken.setParams(accountType, senderId, password, service, source); SC2DMAuthToken.authenticate(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public SC2DMConnection (String url, String method, String accountType, String senderId, String password, String service, String source) { try { this.url = new URL(url); this.method = method; SC2DMAuthToken.setParams(accountType, senderId, password, service, source); SC2DMAuthToken.authenticate(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void openConnection(){ try { if(SC2DMAuthToken.getAuthToken() == null){ SC2DMAuthToken.authenticate(); } connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod(method); connection.setUseCaches(false); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Authorization", "GoogleLogin auth=" + SC2DMAuthToken.getAuthToken()); connected = true; } catch (MalformedURLException e) { closeConnection(); e.printStackTrace(); } catch (ProtocolException e) { closeConnection(); e.printStackTrace(); } catch (IOException e) { closeConnection(); e.printStackTrace(); } } public HttpURLConnection getHttpURLConnection() { return connection; } public void closeConnection(){ connection.disconnect(); connection = null; connected = false; } public boolean isConnected(){ return connected; } }
package com.java.tut.test; import org.apache.commons.lang3.Validate; public class Main { public static void main(String[] args) { try { Validate.matchesPattern("15:16", "^([01]?[0-9]|2[0-3]):[0-5][0-9]"); } catch( IllegalArgumentException e) { System.out.println( e.getMessage()); } } }
package com.company; import java.util.Random; import java.util.Scanner; public class One_Shot_hi_lo { public static void main(String[] args) { Random random = new Random(); Scanner scanner= new Scanner(System.in); int right=1+random.nextInt(100); int guess; System.out.println("I'm thinking of a number between 1-100. Try to guess it."); guess=scanner.nextInt(); if(guess==right){ System.out.println("You guessed it! What are the odds?!?"); } else if(guess>right){ System.out.println("Sorry, you are too high. I was thinking of "+right+"."); } else if(guess<right){ System.out.println("Sorry, you are too low. I was thinking of "+right+"."); } } }
import java.util.Scanner; public class SubtractQuiz { public static void main(String[] args) { final int NUMBER_OF_QUESTIONS = 5;// Number of questions int correctCount = 0; // count of correct answers int count = 0 ;// count the number of questions long startTime = System.currentTimeMillis(); String output = " "; Scanner input = new Scanner(System.in); while(count < NUMBER_OF_QUESTIONS) { //Generate two random single digits int number1 = (int)(Math.random() * 10); int number2 = (int)(Math.random() * 10); //If number1 < number2 ,swap number1 with number2 if(number1 < number2) { int temp = number1; number1 = number2; temp = number2; } //Prompt the user to answer "what is number1- number2 System.out.print(" What is " + number1 + "-"+ number2 +"?" ); int answer = input.nextInt(); // Grade the answer and display the result if(number1 - number2 == answer) { System.out.println(" You are correct "); correctCount++; } else System.out.println(" You answer is wrong \n " + number1 + " - " +number2 +" should be "+ (number1 - number2 )); count++; output += "\n" +number1 + "-" +number2 + "=" +answer + ((number1 - number2 ==answer ? "Correct" : "Wrong")); } long endTime = System.currentTimeMillis(); long testTime = endTime - startTime; System.out.println(" correctCount is " +correctCount + "\n" + "testTime is" +testTime /1000 + " seconds " +output ); } }
package ve.com.mastercircuito.objects; public class BoardVoltage { private Integer id; private String voltage; public BoardVoltage() { super(); } public BoardVoltage(Integer id, String voltage) { super(); this.id = id; this.voltage = voltage; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getVoltage() { return voltage; } public void setVoltage(String voltage) { this.voltage = voltage; } }
/* * Squares and cubes the array elements using two threads. */ public class SquareCube { private static int arr1[] = new int[]{1,2,3,4,5}; private static int arr2[] = new int[]{2,3,4,5,6}; private static int sumSquare=0, sumCube=0, finalSum=0; public static void main(String[] args) { Runnable run1 = new Runnable1(); Thread t1 = new Thread(run1); Runnable run2 = new Runnable2(); Thread t2 = new Thread(run2); Runnable run3 = new Runnable3(); Thread t3 = new Thread(run3); t1.start(); t2.start(); t3.start(); } static class Runnable1 implements Runnable{ public void run(){ int length1 = arr1.length; for(int i=0;i<length1;i++) { sumSquare+=(arr1[i]*arr1[i]); } } } static class Runnable2 implements Runnable{ public void run(){ int length2 = arr2.length; for(int i=0;i<length2;i++) { sumCube+=(arr2[i]*arr2[i]*arr2[i]); } } } static class Runnable3 implements Runnable{ public void run(){ int arr[] = new int[arr1.length]; int length1 = arr1.length; for(int i=0;i<length1;i++) { arr[i] = arr1[i]+arr2[i]; System.out.println(arr[i]); } } } }
package br.unit.uibb.entidades; import java.util.UUID; public class Conta { private String numero; private double saldo; private Cliente cliente; private String senha; public Conta() { } public Conta(String numero, double saldo, Cliente cliente, String senha) { this.numero = numero; this.saldo = saldo; this.cliente = cliente; this.senha = senha; } public String getNumero() { return numero; } public void setNumero(String numero) { this.numero = numero; } public double getSaldo() { return saldo; } //setSaldo nao deve ser implementado public Cliente getCliente() { return cliente; } public void setCliente(Cliente cliente) { this.cliente = cliente; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } public void creditar(double valor) { saldo += valor; } public void debitar(double valor) { saldo -= valor; } public void transferir(Conta contaDestino, double valor) { debitar(valor); contaDestino.creditar(valor); } public static String gerarNumero() { return UUID.randomUUID().toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((cliente == null) ? 0 : cliente.hashCode()); result = prime * result + ((numero == null) ? 0 : numero.hashCode()); long temp; temp = Double.doubleToLongBits(saldo); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((senha == null) ? 0 : senha.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Conta other = (Conta) obj; if (cliente == null) { if (other.cliente != null) return false; } else if (!cliente.equals(other.cliente)) return false; if (numero == null) { if (other.numero != null) return false; } else if (!numero.equals(other.numero)) return false; if (Double.doubleToLongBits(saldo) != Double.doubleToLongBits(other.saldo)) return false; if (senha == null) { if (other.senha != null) return false; } else if (!senha.equals(other.senha)) return false; return true; } public String toString() { return "cliente: " + cliente.getNome() // + " numero: " + numero // + " saldo: " + saldo; } }
import java.util.*; public class Main { static Scanner in; static int maxnum = 100; //받을 수 있는 숫자의 최대 개수 public static void main(String[] args) { in = new Scanner(System.in); int[] fnumbers = new int[maxnum]; int count = 0; int searchNum; System.out.println("숫자를 차례대로 입력하세요.(최대 " + maxnum + "개) q를 입력시 입력이 종료"); while(true){ String numbers = in.next(); if (numbers.equals("q") || numbers.equals("Q")) break; fnumbers[count++] = Integer.parseInt(numbers); } Sorting.qsort(fnumbers, 0, count - 1); //퀵소트 Printer.printer(fnumbers, count); //결과 출력 System.out.println("\n찾을 숫자를 입력해주세요. q를 입력시 입력이 종료"); while(true){ String numbers = in.next(); if (numbers.equals("q") || numbers.equals("Q")) break; searchNum = Integer.parseInt(numbers); Searching.search(fnumbers, 0, count, searchNum); } } }
package com.es.phoneshop.web; import com.es.phoneshop.model.product.Cart.Cart; import com.es.phoneshop.model.product.Cart.CartService; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class CartItemDeleteServletTest { @Mock private CartService cartService; @Mock private HttpServletRequest request; @Mock private HttpSession session; @Mock private HttpServletResponse response; @Mock private Cart cart; @InjectMocks private CartItemDeleteServlet servlet; @Test public void testGoPost() throws IOException { when(request.getPathInfo()).thenReturn("/1"); when(request.getSession()).thenReturn(session); when(cartService.getCart(session)).thenReturn(cart); servlet.doPost(request, response); verify(request).getSession(); verify(cartService).getCart(session); verify(response).sendRedirect(request.getContextPath() + "/cart"); } }
/** * Dedicated for methods needed to make the program robust in all areas. Returns * boolean to program instructing whether user's input was valid */ package stockorganizer; import java.util.ArrayList; import java.util.LinkedList; public class RobustChecker { private String errorMessage; // Sets error message for error frame public RobustChecker() { errorMessage = getErrorMessage(); // Default error message } public RobustChecker(String errorMessage) { this.errorMessage = errorMessage; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } public boolean validDay(String day) { int dateInt; try { dateInt = Integer.parseInt(day); if (dateInt<=0) { setErrorMessage("Error! Date value '" + day + "' must be greater than 0."); return false; } else if (dateInt>31) { setErrorMessage("Error! Date value '" + day + "' cannot be greater than 31."); return false; } } catch (NumberFormatException e) { setErrorMessage("Error! Numerical input '" + day + "' contains invalid characters."); return false; } return true; } public boolean validYear(String year) { int yearInt; try { yearInt = Integer.parseInt(year); if (yearInt<1800) { setErrorMessage("Error! Date value '" + year + "' must be no less than 1800."); return false; } } catch(NumberFormatException e) { setErrorMessage("Error! Numerical input '" + year + "' contains invalid characters."); return false; } return true; } public boolean strToDub(String strInput) { // Tests conversion from string to a double boolean isDouble = true; // Flag boolean set to true double dubOutput; // Initializing double, not used try { dubOutput = Double.parseDouble(strInput); // Tries } catch (NumberFormatException e) { setErrorMessage("Error! Numerical input '" + strInput + "' contains invalid characters."); // Sets error message isDouble = false; // Changes flag to false } catch (Exception e) { setErrorMessage("Unknown error! Please try again."); } return isDouble; // Returns flag } public boolean strToInt (String strInput) { boolean isInteger = true; int intOutput; try { intOutput = Integer.parseInt(strInput); } catch (NumberFormatException e) { setErrorMessage("Error! Numerical input '" + strInput + "' contains invalid characters."); // Sets error message isInteger = false; } catch (Exception e) { setErrorMessage("Unknown error! Please try again."); } return isInteger; } /** * Tests every sale transaction to prevent quantities of stock under zero. For * every sale, tests to see if quantity falls under zero * @param stock * @param date * @param quantity * @param salesPrice * @return */ public boolean simNewSale(String stock, String date, String quantity, String salesPrice) { EditDataDb edi = new EditDataDb(); TableFill fill = new TableFill(); Object[][] purchases, sales; Object[][] newSales; LinkedList<ArrayList> data = new LinkedList(); Object[][] newData; // Gets data purchases = edi.fetchTable(InfoDb.PURCHASE_TABLE, InfoDb.PURCHASE_HEADER); sales = edi.fetchTable(InfoDb.SALE_TABLE, InfoDb.SALE_HEADER); newSales = new Object[sales.length+1][7]; // Length of sales plus room for new transaction if (purchases.length == 0) { // No purchases yet setErrorMessage("Error! No sales can be made until a purchase is made"); return false; } // Mimics new sale transaction data info // Index out of bounds int i = sales.length; if (sales.length==0) { // If sales are empty, can't do minus one newSales[i][0] = ("999"); // ID number newSales[i][1] = (stock); newSales[i][2] = (date); newSales[i][3] = (quantity); newSales[i][4] = (salesPrice); newSales[i][5] = ("0"); // proceeds newSales[i][6] = ("0"); // realized gain } else { // Need to fill newSales for(int a=0; a<sales.length; a++) { for(int b=0; b<sales[a].length; b++) { newSales[a][b]=sales[a][b]; } } i--; // Last possible index, empty row sales[i][0] = ("999"); // ID number sales[i][1] = (stock); sales[i][2] = (date); sales[i][3] = (quantity); sales[i][4] = (salesPrice); sales[i][5] = ("0"); // proceeds sales[i][6] = ("0"); // realized gain } // Sorts simulation data try { data = fill.sortPurchaseSale(purchases, sales, stock); } catch (Exception e) { setErrorMessage("Error! Purchase can not be made"); } // Tests if new sale insert is earliest date if (date.equals(data.get(0).get(2))) { setErrorMessage("Error! You can not have a sale transaction occur before the first purchase transaction."); return false; } newData = new Object[data.size()][7]; // Converting linkedlist to array for(int j=0; j<data.size(); j++) { for(int k=0; k<data.get(j).size();k++) { newData[j][k] = data.get(j).get(k); } newData[j][3] = Double.parseDouble((String) newData[j][3]); } return quantityAboveZero(newData); } /** * When user deletes a purchase transaction row, must check to make sure all * transactions affected do not cause quantity of shares held to drop below 0 * * @param id * @return */ public boolean simDeletePurchase(String id) { EditDataDb edi = new EditDataDb(); TableFill fill = new TableFill(); Object[][] purchases, sales; ArrayList<ArrayList> purchaseList = new ArrayList(); LinkedList<ArrayList> data = new LinkedList(); Object[][] newData; Object[][] sortedData; String stock = ""; // Gets data purchases = edi.fetchTable(InfoDb.PURCHASE_TABLE, InfoDb.PURCHASE_HEADER); sales = edi.fetchTable(InfoDb.SALE_TABLE, InfoDb.SALE_HEADER); if (purchases.length == 0) { // No purchases yet setErrorMessage("Error! There are no purchases."); return false; } // Convert purchases to ArrayList for(int r=0; r<purchases.length; r++) { ArrayList temp = new ArrayList(); if (id.equals((String)purchases[r][0])) { stock = (String) purchases[r][1]; // Save ticker of id } for(int c=0; c<purchases[r].length; c++) { if (!id.equals((String)purchases[r][0])) { // If IDs aren't equal, fill line temp.add(purchases[r][c]); } } purchaseList.add(temp); } newData = new Object[purchaseList.size()][6]; // Convert back to array for(int r=0; r<purchaseList.size(); r++) { for(int c=0; c<purchaseList.get(r).size(); c++) { newData[r][c] = purchaseList.get(r).get(c); } } try { data = fill.sortPurchaseSale(newData, sales, stock); } catch (Exception e) { setErrorMessage("Error! Purchase can not be deleted"); } sortedData = new Object[data.size()][7]; // Covert to array for(int r=0; r<data.size(); r++) { for(int c=0; c<data.get(r).size(); c++) { sortedData[r][c] = data.get(r).get(c); } sortedData[r][3] = Double.parseDouble((String) sortedData[r][3]); } return quantityAboveZero(sortedData); } /** Tests if quantity is above zero * * @param data * @return */ public boolean quantityAboveZero(Object[][] data) { TableFill fill = new TableFill(); double cumulative; int a=0; while(a<data.length) { cumulative = fill.cumulative(data, 3, a); if (cumulative < 0) { setErrorMessage("Error! Your cumulative quantity sold exceeds your cumulative quantity purchased at date " + data[a][2]+"."); return false; } a++; } return true; } }
/** * Copyright 2019 bejson.com */ package com.wxapp.jsonbean; /** * Auto-generated: 2019-12-31 15:56:46 * * @author bejson.com (i@bejson.com) * @website http://www.bejson.com/java2pojo/ */ public class UploadContact { private OnlineAccount_wxid onlineAccount_wxid; public OnlineAccount_wxid getOnlineAccount_wxid() { return onlineAccount_wxid; } public void setOnlineAccount_wxid(OnlineAccount_wxid onlineAccount_wxid) { this.onlineAccount_wxid = onlineAccount_wxid; } }
package org.nmrg.model.page; import java.io.Serializable; import java.util.Set; import org.nmrg.model.BaseModel; /** ** 分页参数 ** * @ClassName: PageModel ** @Description: TODO ** @author CC ** @date 2017年8月11日 - 下午1:11:04 */ public class PageModel implements Serializable { // --- @Fields serialVersionUID : TODO private static final long serialVersionUID = 54075905336367806L; // --- 页码 private Integer pageNum = 1; // --- 每页的大小 private Integer pageSize = 11; // --- 排序方式 Set<OrderModel> orderSet; public PageModel() { super(); } public PageModel(Integer pageNum, Integer pageSize) { super(); this.pageNum = pageNum; this.pageSize = pageSize; } public PageModel(Integer pageNum, Integer pageSize, Set<OrderModel> orderSet) { super(); this.pageNum = pageNum; this.pageSize = pageSize; this.orderSet = orderSet; } public Integer getPageNum() { return pageNum; } public void setPageNum(Integer pageNum) { this.pageNum = pageNum; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public Set<OrderModel> getOrderSet() { return orderSet; } public void setOrderSet(Set<OrderModel> orderSet) { this.orderSet = orderSet; } }
package com.IRCTradingDataGenerator.tradingDataGenerator.Repository; import org.springframework.data.jpa.repository.JpaRepository; import com.IRCTradingDataGenerator.tradingDataGenerator.Models.Principle; public interface PrincipleDao extends JpaRepository<Principle, Integer>{ }
package test; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ServletTest extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void init(ServletConfig config) throws ServletException { } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub DatagramSocket tojava = new DatagramSocket(); //페이지가 열리면 진재한테 send>>> 값은 1또는 0 int port1 = 10002; String i = "0"; InetAddress ip = InetAddress.getByName("127.0.0.1"); request.setCharacterEncoding("utf-8"); String r_hidden = request.getParameter("h_field"); if (r_hidden.equals("0")) { i = r_hidden; } else { i = r_hidden; } DatagramPacket camdp = new DatagramPacket(i.getBytes(), i.getBytes().length, ip, port1); tojava.send(camdp); tojava.close(); response.sendRedirect("Main.jsp"); } }
package com.lubarov.daniel.blog.post; import com.lubarov.daniel.blog.comment.Comment; import com.lubarov.daniel.blog.comment.CommentFormFormatter; import com.lubarov.daniel.blog.comment.CommentFormatter; import com.lubarov.daniel.data.option.Option; import com.lubarov.daniel.data.sequence.Sequence; import com.lubarov.daniel.web.html.AnchorBuilder; import com.lubarov.daniel.web.html.Attribute; import com.lubarov.daniel.web.html.Element; import com.lubarov.daniel.web.html.HtmlUtils; import com.lubarov.daniel.web.html.Tag; public final class PostFormatter { private PostFormatter() {} public static Element full(Post post, Sequence<Comment> commentsByDate) { Element.Builder builder = new Element.Builder(Tag.DIV); builder.addRawText(post.getContent()); Option<Element> optCommentsSection = getCommentsSection(commentsByDate); if (optCommentsSection.isDefined()) builder.addChild(optCommentsSection.getOrThrow()); return builder .addChild(HtmlUtils.getClearDiv()) .addChild(CommentFormFormatter.getAddCommentForm(post)) .build(); } private static Option<Element> getCommentsSection(Sequence<Comment> commentsByDate) { if (commentsByDate.isEmpty()) return Option.none(); String headerText = String.format("%d Comments", commentsByDate.getSize()); Element commentsHeader = new Element.Builder(Tag.H2) .addEscapedText(headerText) .build(); return Option.some(new Element.Builder(Tag.SECTION) .setRawAttribute(Attribute.CLASS, "comments") .addChild(commentsHeader) .addChildren(commentsByDate.map(CommentFormatter::full)) .build()); } public static Element summaryLink(Post post) { AnchorBuilder anchorBuilder = new AnchorBuilder() .setHref(PostUrlFactory.getViewUrl(post)) .addEscapedText(post.getSubject()); if (!post.isPublished()) anchorBuilder.setStyle("color: #aaa;"); return anchorBuilder.build(); } }
package com.jst.web; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.jst.myservice.PermissionServiceImpl; @Controller public class PermissionController { @Autowired private PermissionServiceImpl p; // @RequestMapping("/permission") // public ModelAndView getAllPermission() { // ModelAndView md = new ModelAndView("Permission_Add", "permissionList",p.selectAll()); // return md; // } @RequestMapping("/admin/sysfunctioin/showfunctionztree") public String toPermissionList() { return "/manager/permission"; } // @RequestMapping("/permission_Add") // public String insertPermission(HttpServletRequest request) { // Permission pp = new Permission(); // pp.setPname(request.getParameter("pname")); // pp.setPaddr(request.getParameter("paddr")); // int state = Integer.parseInt(request.getParameter("state")); // pp.setState(state); // pp.setPid(state == 1 ? 0 : Integer.parseInt(request.getParameter("pid"))); // p.insertPermission(pp); // return "redirect:permission.jsp"; // } // @RequestMapping("/permissionjsp") // public ModelAndView getAllPermissions() { // ModelAndView md = new ModelAndView("permission", "permissions",p.selectAll()); // return md; // } }
package beans; import lombok.Data; import util.Default; @Data public class PayrollCorrectingEntry { private String id; private String rowstamp; private String firstname; private String middlename; private String lastname; private String employeeid; private String department; private String explanationOfcorrection; private java.sql.Date payPeriod; private String notes; private String submittedBy; private java.sql.Timestamp submitted; private String isactive; public PayrollCorrectingEntry(){ rowstamp = Default.getInstance().getDefaultRawstramp(); isactive = Default.getInstance().getDefaultIsActive(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getRowstamp() { return rowstamp; } public void setRowstamp(String rowstamp) { this.rowstamp = rowstamp; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getMiddlename() { return middlename; } public void setMiddlename(String middlename) { this.middlename = middlename; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getEmployeeid() { return employeeid; } public void setEmployeeid(String employeeid) { this.employeeid = employeeid; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getExplanationOfcorrection() { return explanationOfcorrection; } public void setExplanationOfcorrection(String explanationOfcorrection) { this.explanationOfcorrection = explanationOfcorrection; } public java.sql.Date getPayPeriod() { return payPeriod; } public void setPayPeriod(java.sql.Date payPeriod) { this.payPeriod = payPeriod; } public String getNotes() { return notes; } public void setNotes(String notes) { this.notes = notes; } public String getSubmittedBy() { return submittedBy; } public void setSubmittedBy(String submittedBy) { this.submittedBy = submittedBy; } public java.sql.Timestamp getSubmitted() { return submitted; } public void setSubmitted(java.sql.Timestamp submitted) { this.submitted = submitted; } public String getIsactive() { return isactive; } public void setIsactive(String isactive) { this.isactive = isactive; } }
package ru.gadjets.comppartapp.service; import ru.gadjets.comppartapp.dao.utils.Pager; import ru.gadjets.comppartapp.entity.Part; import java.util.List; import java.util.Properties; public interface PartPagerService { void delete(int p); public List<Part> findAll(Properties prop); Part getById(int id); void update(Part part); public Pager getPager(); void add(Part part); }
package com.jx.product.service; import com.jx.product.model.Product; import java.util.List; public interface ProductService { List<Product> query(); void updStock(String[] id, String[] num); }
package org.gmart.devtools.java.serdes.codeGenExample.openApiExample.generatedFiles; import java.util.List; import javax.annotation.processing.Generated; import org.gmart.devtools.java.serdes.codeGen.javaGen.model.classTypes.AbstractClassDefinition; import org.gmart.devtools.java.serdes.codeGen.javaGen.model.classTypes.ClassInstance; import org.gmart.devtools.java.serdes.codeGen.javaGen.model.classTypes.ClassSerializationToYamlDefaultImpl; import org.gmart.devtools.java.serdes.codeGenExample.openApiExample.generatedFilesCustomizationStubs.SchemaOrRef; @Generated("") public class ArrayType extends Schema implements ClassSerializationToYamlDefaultImpl, ClassInstance { private static AbstractClassDefinition classSpecification; private SchemaOrRef items; private boolean uniqueItems; private long minItems; private long maxItems; private List<Object> default_; public ArrayType() { } public SchemaOrRef getItems() { return items; } public void setItems(SchemaOrRef items) { this.items = items; } public boolean getUniqueItems() { return uniqueItems; } public void setUniqueItems(boolean uniqueItems) { this.uniqueItems = uniqueItems; } public long getMinItems() { return minItems; } public void setMinItems(long minItems) { this.minItems = minItems; } public long getMaxItems() { return maxItems; } public void setMaxItems(long maxItems) { this.maxItems = maxItems; } public List<Object> getDefault_() { return default_; } public void setDefault_(List<Object> default_) { this.default_ = default_; } public AbstractClassDefinition getClassDefinition() { return classSpecification; } }
package elora; import static org.junit.Assert.*; import java.util.Calendar; import java.util.Date; import org.junit.Test; import elora.TellMeWhen; /** * Tests the {@link TellMeWhen} class. * * @author akauffman * */ public class TellMeWhenTest { /** * Tests that empty parameters are being handled. */ @Test public void testEmpty() { try{ TellMeWhen.listen(null); fail("Allowed null phrase."); } catch (NullPointerException e){ //Passes test } catch (InvalidPatternException e) { e.printStackTrace(); } try{ TellMeWhen.listen("NOW", null); fail("Allowed null fromWhen."); } catch (NullPointerException e){ //Passes test } catch (InvalidPatternException e) { e.printStackTrace(); } try{ TellMeWhen.listen(""); fail("Allowed empty phrase."); } catch (InvalidPatternException e) { //passes test } try{ TellMeWhen.listen("NOT A VALID PATTERN"); fail("Allowed invalid pattern."); } catch (InvalidPatternException e){ //passes } } /** * Tests passing just the phrase returns the time relative to now. * @throws InvalidPatternException * @throws Exception */ @Test public void testPhrase() throws InvalidPatternException{ final Calendar cal = Calendar.getInstance(); assertTrue(isEqual(cal, TellMeWhen.listen("now"))); assertTrue(isEqual(cal, TellMeWhen.listen("NOW"))); } /** * Tests passing phrase and fromDate returns time relative to the fromDate * @throws InvalidPatternException * @throws Exception */ @Test public void testPhraseFromWhen() throws InvalidPatternException{ final Calendar fromWhen = Calendar.getInstance(); fromWhen.set(2015, 3, 6, 1, 1, 1); //Monday, April 6th, 2015 assertEquals(fromWhen.getTime(), TellMeWhen.listen("NOW", fromWhen.getTime())); } /** * Compares a calendar and a date to see if they're equal within a tolerance of one hour. * * @param cal * @param date * @return */ private boolean isEqual(Calendar cal, Date date){ Calendar cal1 = (Calendar)cal.clone(); Calendar cal2 = Calendar.getInstance(); cal2.setTime(date); cal1.set(Calendar.MILLISECOND, 0); cal2.set(Calendar.MILLISECOND, 0); cal1.set(Calendar.SECOND, 0); cal2.set(Calendar.SECOND, 0); cal1.set(Calendar.MINUTE, 0); cal2.set(Calendar.MINUTE, 0); return cal1.equals(cal2); } }
package sample.entity; import sample.util.DbHelper; import javax.persistence.*; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import java.sql.Date; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.Objects; @Entity @Table(name = "dogovor", schema = "komraz", catalog = "") public class DogovorEntity { private int id; private UrLicoEntity urLico; private String nomer; private Date date; @Id @Column(name = "id") public int getId() { return id; } public void setId(int id) { this.id = id; } @ManyToOne @JoinColumn(name = "ur_lico_id") public UrLicoEntity getUrLico() { return urLico; } public void setUrLico(UrLicoEntity urLico) { this.urLico = urLico; } @Basic @Column(name = "nomer") public String getNomer() { return nomer; } public void setNomer(String nomer) { this.nomer = nomer; } @Basic @Column(name = "date") public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DogovorEntity that = (DogovorEntity) o; if (id != that.id) return false; if (urLico != that.urLico) return false; if (!Objects.equals(nomer, that.nomer)) return false; if (!Objects.equals(date, that.date)) return false; return true; } @Override public int hashCode() { int result = id; result = 31 * result + urLico.hashCode(); result = 31 * result + (nomer != null ? nomer.hashCode() : 0); result = 31 * result + (date != null ? date.hashCode() : 0); return result; } @Override public String toString() { return toStringExtended(); } @SuppressWarnings("unchecked") public List<SchetchikEntity> allSchetchiki() { DbHelper.checkSession(); CriteriaBuilder cb = DbHelper.session.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(ObjectEntity.class); Root root = cq.from(ObjectEntity.class); cq = cq.where(cb.equal(root.get("dogovor"), this)); TypedQuery allQuery = DbHelper.session.createQuery(cq.select(root)); List<ObjectEntity> objects = allQuery.getResultList(); if (objects.isEmpty()) { return new ArrayList<>(); } cq = cb.createQuery(SchetchikEntity.class); root = cq.from(SchetchikEntity.class); cq = cq.where( root .get("object") .in(objects) ); allQuery = DbHelper.session.createQuery(cq.select(root)); return allQuery.getResultList(); } public String toStringExtended() { StringBuilder sb = new StringBuilder("Договор №" + nomer); if (urLico != null) { sb.append(" с ").append(urLico.getName()); } if (date != null) { sb.append(" от ").append(DateTimeFormatter.ofPattern("dd.MM.yyyy").format(DbHelper.getLocalDate(date))); } return sb.toString(); } }
package com.mysql.cj.xdevapi; import com.mysql.cj.MysqlxSession; import com.mysql.cj.protocol.Message; import com.mysql.cj.protocol.x.XMessage; import java.util.concurrent.CompletableFuture; public class FindStatementImpl extends FilterableStatement<FindStatement, DocResult> implements FindStatement { FindStatementImpl(MysqlxSession mysqlxSession, String schema, String collection, String criteria) { super(new DocFilterParams(schema, collection)); this.mysqlxSession = mysqlxSession; if (criteria != null && criteria.length() > 0) this.filterParams.setCriteria(criteria); if (!this.mysqlxSession.supportsPreparedStatements()) this.preparedState = PreparableStatement.PreparedState.UNSUPPORTED; } protected DocResult executeStatement() { return (DocResult)this.mysqlxSession.query((Message)getMessageBuilder().buildFind(this.filterParams), new StreamingDocResultBuilder(this.mysqlxSession)); } protected XMessage getPrepareStatementXMessage() { return getMessageBuilder().buildPrepareFind(this.preparedStatementId, this.filterParams); } protected DocResult executePreparedStatement() { return (DocResult)this.mysqlxSession.query((Message)getMessageBuilder().buildPrepareExecute(this.preparedStatementId, this.filterParams), new StreamingDocResultBuilder(this.mysqlxSession)); } public CompletableFuture<DocResult> executeAsync() { return this.mysqlxSession.queryAsync((Message)getMessageBuilder().buildFind(this.filterParams), new DocResultBuilder(this.mysqlxSession)); } public FindStatement fields(String... projection) { resetPrepareState(); this.filterParams.setFields(projection); return this; } public FindStatement fields(Expression docProjection) { resetPrepareState(); ((DocFilterParams)this.filterParams).setFields(docProjection); return this; } public FindStatement groupBy(String... groupBy) { resetPrepareState(); this.filterParams.setGrouping(groupBy); return this; } public FindStatement having(String having) { resetPrepareState(); this.filterParams.setGroupingCriteria(having); return this; } public FindStatement lockShared() { return lockShared(Statement.LockContention.DEFAULT); } public FindStatement lockShared(Statement.LockContention lockContention) { resetPrepareState(); this.filterParams.setLock(FilterParams.RowLock.SHARED_LOCK); switch (lockContention) { case NOWAIT: this.filterParams.setLockOption(FilterParams.RowLockOptions.NOWAIT); break; case SKIP_LOCKED: this.filterParams.setLockOption(FilterParams.RowLockOptions.SKIP_LOCKED); break; } return this; } public FindStatement lockExclusive() { return lockExclusive(Statement.LockContention.DEFAULT); } public FindStatement lockExclusive(Statement.LockContention lockContention) { resetPrepareState(); this.filterParams.setLock(FilterParams.RowLock.EXCLUSIVE_LOCK); switch (lockContention) { case NOWAIT: this.filterParams.setLockOption(FilterParams.RowLockOptions.NOWAIT); break; case SKIP_LOCKED: this.filterParams.setLockOption(FilterParams.RowLockOptions.SKIP_LOCKED); break; } return this; } @Deprecated public FindStatement where(String searchCondition) { return super.where(searchCondition); } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\xdevapi\FindStatementImpl.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package ru.hitpoint.lib.hitpoint.network; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class NetServiceManager { // private static final String BASE_URL = "http://192.168.0.100:8080"; private static final String BASE_URL = "http://superapi.pythonanywhere.com"; private Retrofit retrofit; public ApiService getApiService(){ if (retrofit == null){ retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit.create(ApiService.class); } }
package util; public class Util { public String compare(StringCompare stringCompare) { if (stringCompare == null) return null; if (stringCompare.first == null || stringCompare.second == null) { return stringCompare.second; } if (stringCompare.first.length() + stringCompare.second.length() > 10) { return null; } else { return stringCompare.second; } } }
package com.rockwellcollins.atc.limp.translate.lustre.limp2lustre; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import jkind.lustre.Ast; import jkind.lustre.Constant; import jkind.lustre.Expr; import jkind.lustre.Function; import jkind.lustre.Node; import jkind.lustre.Type; import jkind.lustre.TypeDef; import jkind.lustre.VarDecl; import org.eclipse.emf.ecore.EObject; import com.rockwellcollins.atc.limp.ArrayTypeDef; import com.rockwellcollins.atc.limp.ConstantDeclaration; import com.rockwellcollins.atc.limp.EnumTypeDef; import com.rockwellcollins.atc.limp.EnumValue; import com.rockwellcollins.atc.limp.Equation; import com.rockwellcollins.atc.limp.ExternalFunction; import com.rockwellcollins.atc.limp.ExternalProcedure; import com.rockwellcollins.atc.limp.GlobalDeclaration; import com.rockwellcollins.atc.limp.LocalFunction; import com.rockwellcollins.atc.limp.LocalProcedure; import com.rockwellcollins.atc.limp.RecordFieldType; import com.rockwellcollins.atc.limp.RecordTypeDef; import com.rockwellcollins.atc.limp.TypeAlias; import com.rockwellcollins.atc.limp.exceptions.UnexpectedException; import com.rockwellcollins.atc.limp.util.LimpSwitch; /** * LimpToLustre is the top level translator for Limp files to * an equivalent Lustre representation for analysis. */ public class LimpDeclarationToLustreDeclaration extends LimpSwitch<Ast> { public static VarDecl crunch(GlobalDeclaration gd) { return (VarDecl) new LimpDeclarationToLustreDeclaration().doSwitch(gd); } public static Node crunch(LocalFunction lf) { return (Node) new LimpDeclarationToLustreDeclaration().doSwitch(lf); } public static Function crunch(ExternalFunction ef) { return (Function) new LimpDeclarationToLustreDeclaration().doSwitch(ef); } public static Function crunch(ExternalProcedure ep) { return (Function) new LimpDeclarationToLustreDeclaration().doSwitch(ep); } public static Function crunch(LocalProcedure lp) { return (Function) new LimpDeclarationToLustreDeclaration().doSwitch(lp); } public static TypeDef crunch(TypeAlias ta) { return (TypeDef) new LimpDeclarationToLustreDeclaration().doSwitch(ta); } public static TypeDef crunch(EnumTypeDef etd) { return (TypeDef) new LimpDeclarationToLustreDeclaration().doSwitch(etd); } public static TypeDef crunch(RecordTypeDef rtd) { return (TypeDef) new LimpDeclarationToLustreDeclaration().doSwitch(rtd); } public static TypeDef crunch(ArrayTypeDef atd) { return (TypeDef) new LimpDeclarationToLustreDeclaration().doSwitch(atd); } public static Constant crunch(ConstantDeclaration cd) { return (Constant) new LimpDeclarationToLustreDeclaration().doSwitch(cd); } /** * LocalFunctions are directly translated to Lustre nodes. */ @Override public Node caseLocalFunction(LocalFunction lf) { String nodeName = lf.getName(); List<VarDecl> inputs = LimpArgsToVarDecl.crunchInputs(lf.getInputs()); List<VarDecl> locals = LimpArgsToVarDecl.crunchLocals(lf.getVarBlock()); List<VarDecl> outputs = LimpArgsToVarDecl.crunchOutput(lf.getOutput()); List<jkind.lustre.Equation> equations = new ArrayList<>(); for(Equation eq : lf.getEquationBlock().getEquations()) { equations.add(LimpStatementToLustreEquation.translate(eq)); } List<String> properties = new ArrayList<>(); List<Expr> assertions = new ArrayList<>(); Node n = new Node(nodeName, inputs, outputs, locals, equations, properties, assertions); return n; } /** * ExternalFunctions are translated into Lustre uninterpreted functions. */ @Override public Function caseExternalFunction(ExternalFunction ef) { List<jkind.lustre.VarDecl> inputs = LimpArgsToVarDecl.crunchInputs(ef.getInputs()); List<jkind.lustre.VarDecl> outputs = LimpArgsToVarDecl.crunchOutput(ef.getOutput()); jkind.lustre.Function function = new jkind.lustre.Function(ef.getName(), inputs, outputs); return function; } /** * ExternalProcedures are translated into Lustre uninterpreted functions. */ @Override public Function caseExternalProcedure(ExternalProcedure ep) { List<jkind.lustre.VarDecl> inputs = LimpArgsToVarDecl.crunchInputs(ep.getInputs()); List<jkind.lustre.VarDecl> outputs = LimpArgsToVarDecl.crunchOutputs(ep.getOutputs()); jkind.lustre.Function function = new jkind.lustre.Function(ep.getName(), inputs, outputs); return function; } /** * LocalProcedures are translated into Lustre uninterpreted functions, however they * should only be encountered if they are called from the main LocalProcedure. */ @Override public Function caseLocalProcedure(LocalProcedure lp) { List<jkind.lustre.VarDecl> inputs = LimpArgsToVarDecl.crunchInputs(lp.getInputs()); List<jkind.lustre.VarDecl> outputs = LimpArgsToVarDecl.crunchOutputs(lp.getOutputs()); jkind.lustre.Function function = new jkind.lustre.Function(lp.getName(), inputs, outputs); return function; } /** * TypeAlias are translated into Lustre typedefs. */ @Override public TypeDef caseTypeAlias(TypeAlias ta) { jkind.lustre.Type t = LimpTypeToLustreType.translateType(ta.getType()); jkind.lustre.TypeDef typeDef = new jkind.lustre.TypeDef(ta.getName(), t); return typeDef; } /** * EnumTypeDefs are translated into Lustre EnumTypes with an associated TypeDef */ @Override public TypeDef caseEnumTypeDef(EnumTypeDef etd) { String name = etd.getName(); List<String> values = new ArrayList<>(); for(EnumValue ev : etd.getEnumerations()) { values.add(ev.getName()); } jkind.lustre.EnumType enumType = new jkind.lustre.EnumType(name,values); jkind.lustre.TypeDef typeDef = new jkind.lustre.TypeDef(etd.getName(), enumType); return typeDef; } /** * RecordTypeDefs are translated into RecordTypes with an associated TypeDef */ @Override public TypeDef caseRecordTypeDef(RecordTypeDef rtd) { Map<String,jkind.lustre.Type> fields = new LinkedHashMap<>(); for(RecordFieldType rft : rtd.getFields()) { String fieldname = rft.getFieldName(); jkind.lustre.Type fieldType = LimpTypeToLustreType.translateType(rft.getFieldType()); fields.put(fieldname, fieldType); } jkind.lustre.RecordType rt = new jkind.lustre.RecordType(rtd.getName(), fields); jkind.lustre.TypeDef typeDef = new jkind.lustre.TypeDef(rtd.getName(), rt); return typeDef; } /** * ArrayTypeDefs are translated into ArrayTypes with an associated TypeDef */ @Override public TypeDef caseArrayTypeDef(ArrayTypeDef atd) { Type baseType = LimpTypeToLustreType.translateType(atd.getBaseType()); int index = atd.getSize().intValue(); jkind.lustre.ArrayType arrayType = new jkind.lustre.ArrayType(baseType, index); jkind.lustre.TypeDef typeDef = new jkind.lustre.TypeDef(atd.getName(), arrayType); return typeDef; } /** * Limp Constants are translated to Lustre Constants */ @Override public Constant caseConstantDeclaration(ConstantDeclaration cd) { jkind.lustre.Expr expr = LimpExprToLustreExpr.translate(cd.getExpr()); jkind.lustre.Type type = LimpTypeToLustreType.translateType(cd.getType()); jkind.lustre.Constant constant = new Constant(cd.getName(),type,expr); return constant; } /** * GlobalDeclarations are translated as VarDecls which are input to the main node. */ @Override public VarDecl caseGlobalDeclaration(GlobalDeclaration gd) { jkind.lustre.Type t = LimpTypeToLustreType.translateType(gd.getType()); return new VarDecl(gd.getName(),t); } @Override public Ast defaultCase(EObject eo) { throw new UnexpectedException("No method declared to handle this argument."); } }
package com.tencent.mm.opensdk.modelpay; import android.os.Bundle; import com.tencent.mm.opensdk.modelbase.BaseResp; public class JumpToOfflinePay { public static class Resp extends BaseResp { public Resp(Bundle bundle) { fromBundle(bundle); } public boolean checkArgs() { return true; } public void fromBundle(Bundle bundle) { super.fromBundle(bundle); } public int getType() { return 24; } public void toBundle(Bundle bundle) { super.toBundle(bundle); } } }
/* * Copyright ApeHat.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.apehat.newyear.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; /** * @author hanpengfei * @since 1.0 */ public class IOUtils { private static final int DEFAULT_BUFFER_SIZE = 8192; private static final int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8; private IOUtils() { } public static byte[] readAllBytes(InputStream is) throws IOException { byte[] buf = new byte[DEFAULT_BUFFER_SIZE]; int capacity = buf.length; int nread = 0; int n; for (; ; ) { // read to EOF which may read more or less than initial buffer size while ((n = is.read(buf, nread, capacity - nread)) > 0) { nread += n; } // if the last call to read returned -1, then we're done if (n < 0) { break; } // need to allocate a larger buffer if (capacity <= MAX_BUFFER_SIZE - capacity) { capacity = capacity << 1; } else { if (capacity == MAX_BUFFER_SIZE) throw new OutOfMemoryError("Required array size too large"); capacity = MAX_BUFFER_SIZE; } buf = Arrays.copyOf(buf, capacity); } return (capacity == nread) ? buf : Arrays.copyOf(buf, nread); } public static byte[] toByteArray(InputStream in) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); byte[] data = new byte[DEFAULT_BUFFER_SIZE]; int len; while ((len = in.read(data, 0, data.length)) != -1) { buffer.write(data, 0, len); } buffer.flush(); return buffer.toByteArray(); } }
// Sun Certified Java Programmer // Chapter 2, P125 // Object Orientation interface Baz { }
package com.tencent.mm.g.a; public final class fm$a { public int bNR; public int bNS; public int bNT; public int bNU; public String fileName; public int result; }
package support.yz.data.mvc.service.inter; import support.yz.data.entity.entityInfo.EnterprisePatent; public interface PatentService { EnterprisePatent getPatentByName(String patentName) throws Exception; }