text
stringlengths
10
2.72M
/* * Copyright 2014 Intel Corporation. * * 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.xwalk.ide.eclipse.xdt.wizards.newproject; import org.eclipse.jface.wizard.IWizardPage; import java.io.ByteArrayInputStream; import java.io.InputStream; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.Wizard; import org.eclipse.ui.INewWizard; import org.eclipse.ui.IWorkbench; import org.json.JSONObject; import org.xwalk.ide.eclipse.xdt.XdtConstants; import org.xwalk.ide.eclipse.xdt.XdtPluginLog; import org.xwalk.ide.eclipse.xdt.project.XwalkNature; public class NewProjectWizard extends Wizard implements INewWizard { static final String DefaultEntryFileContent = "<html><body><p>Welcome to Crosswalk!</p></body></html>"; private NewProjectWizardState mValues; private NewProjectPage mMainPage; private IProject mProject; public NewProjectWizard() { } @Override public void init(IWorkbench workbench, IStructuredSelection selection) { setWindowTitle("New Crosswalk Application"); mValues = new NewProjectWizardState(); mMainPage = new NewProjectPage(mValues); } @Override public void addPages() { super.addPages(); addPage(mMainPage); } @Override public boolean performFinish() { try { // create the web staff here // ---- create the project in workspace ---- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); mProject = root.getProject(mValues.projectName); mProject.create(null); mProject.open(IResource.BACKGROUND_REFRESH, null); // ---- Create manifest.json according mValues ---- JSONObject manifest = new JSONObject(); manifest.put("name", mValues.applicationName); manifest.put("version", mValues.applicationVersion); manifest.put("app", new JSONObject()); // add the main entry for app launch setting manifest.getJSONObject("app").put("main", new JSONObject().put("source", mValues.entryFile)); // add the launch entry for app lunch setting manifest.getJSONObject("app").put("launch", new JSONObject().put("local_path", mValues.entryFile)); if (mValues.applicationDescription != null) { manifest.put("description", mValues.applicationDescription); } if (!mValues.useDefaultIcon && mValues.customizedIcon != null) { manifest.put("icon", mValues.customizedIcon); } // ---- write the manifest.json to workspace ---- IFile manifestFile = mProject.getFile(XdtConstants.MANIFEST_PATH); InputStream fileStream = new ByteArrayInputStream(manifest .toString(2).getBytes()); manifestFile.create(fileStream, true, null); fileStream.close(); // ---- create a default entry file ---- IFile entryFile = mProject.getFile(mValues.entryFile); fileStream = new ByteArrayInputStream( DefaultEntryFileContent.getBytes()); entryFile.create(fileStream, true, null); fileStream.close(); // add crosswalk nature to the project XwalkNature.setupProjectNatures(mProject, null); } catch (Exception e) { XdtPluginLog.logError(e); return false; } return true; } public IWizardPage getNextPage(IWizardPage currentPage) { return mMainPage; } public boolean canFinish() { if (mMainPage.isPageComplete()) return true; else return false; } }
/* * 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 servlet; import java.util.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import connection.Issuemanager; import java.util.logging.Level; import java.util.logging.Logger; import java.text.SimpleDateFormat; import javax.servlet.annotation.WebServlet; public class assignissue extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try (PrintWriter out = response.getWriter()) { int k = 0; String stat = request.getParameter("stt"); String prior = request.getParameter("prior"); String id = request.getParameter("iid"); String dept = request.getParameter("dep"); String pr = "low"; String sta = "assigned"; String open= "open"; String verified= "verified"; String ret; if(stat.equals(open)){ ret = Issuemanager.assignissue(prior,dept,sta,id); response.sendRedirect("assignissue.jsp?m1="+ret); } else if(stat.equals(verified)){ response.sendRedirect("assignissue.jsp?m2="+id); } else{ response.sendRedirect("assignissue.jsp?m2=failed"); } } catch(Exception ex) { System.out.println(ex.getMessage()); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override public String getServletInfo() { return "Short description"; } }
import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; /** * Iterates through and finds the most shallow files in a folder */ public class ShallowFileIterator implements Iterator { private File[] folderContents; private int nextIndex; /** * Constructs an iterator that finds the most shallow files in a folder * * @param folder the folder that you want to iterate through * @throws FileNotFoundException if the supplied folder does not exist */ public ShallowFileIterator(File folder) throws FileNotFoundException { if (!folder.exists()) { throw new FileNotFoundException("The given file does not exist"); } folderContents = folder.listFiles(); Arrays.sort(folderContents); nextIndex = 0; } /** * Returns a reference to a different file that is contained within the provided dictionary. Once * all files have been iterated through, throws No Such Element Exception. */ @Override public File next() { // If there are no more files, throws exception if (!hasNext()) { throw new NoSuchElementException("There are no more files in this folder"); } else if (hasNext()) { // Iterates through files File f = folderContents[nextIndex]; nextIndex++; return f; } System.out.println("Error: default case reached in next method"); return null; } /** * Checks to see if there are un-iterated files in the file system. * * @return Returns true while there are more files that have not been iterated through in the file * system, otherwise returns false */ @Override public boolean hasNext() { if (nextIndex >= folderContents.length) { return false; } return true; } }
/** * */ package com.thonline.DAO; import java.sql.Connection; import java.sql.PreparedStatement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.thonline.DO.AbstractDAO; import com.thonline.DO.HJRegistrationDO; import com.thonline.common.Conversion; import com.thonline.common.THConstant; /** * @author Alyza Osman * @tableName DPASCPP * */ public class HJDPPenyataDAO extends AbstractDAO { Logger logger = LoggerFactory.getLogger(HJDPPenyataDAO.class); private Connection conn = null; public HJDPPenyataDAO(Connection conn) { this.conn = conn; } public boolean createHjDPPenyata(HJRegistrationDO regData) { PreparedStatement stmt = null; Conversion conv = new Conversion(); int rs = 0; boolean flag = false; try { System.out.println("in create DP Penyata >> "+ regData.getUuid()); String uuid = regData.getUuid(); //THOHREG201910240101010055 String dateTimeThijari = uuid.substring(7)+"00"; System.out.println("dateTimeThijari "+ dateTimeThijari); String year = dateTimeThijari.substring(0, 4); String mon = dateTimeThijari.substring(4,6); String day = dateTimeThijari.substring(6,8); String hour = dateTimeThijari.substring(8,10); String minute = dateTimeThijari.substring(10,12); String seconds = dateTimeThijari.substring(12,14); String milisec = dateTimeThijari.substring(14,20); System.out.println("sdf1 > "+ year+mon+day+" "+hour+minute+seconds+milisec); System.out.println("regData.getTxnID() " + regData.getTxnID()); String sql = "INSERT INTO " + THConstant.LIBRARY + ".DPASCPP (ASADTS,ASACDT,ASALVA,ASL9CE,ASBNCE,ASHQCE,ASJMST,ASQTCE,ASHBST,ASN9CE,ASHJST,ASAGTS,\r\n" + "ASLICE,ASLJCE,ASK0DZ,ASFHCD,ASA4CD,ASJQVA,ASN5VA,ASPWCE,ASBUCD,\r\n" + "ASPXCE,ASAGVN,ASAFVN,ASABDT,ASAEST) " + "values (CURRENT TIMESTAMP,CURRENT DATE," + "(SELECT AOAOVA FROM "+THConstant.LIBRARY+".DPAOCPP WHERE AOBFCD = '"+regData.getAccNO()+"')" + ",?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; System.out.println(sql); stmt = this.conn.prepareStatement(sql); int i=0; //stmt.setString(1, conv.nullCheck("CURRENT TIMESTAMP")); //stmt.setString(13, conv.nullCheck("CURRENT DATE")); stmt.setString(++i, conv.nullCheck(regData.getAccNO())); System.out.println("regData.getAccNO() " + regData.getAccNO()); stmt.setString(++i, conv.nullCheck("")); stmt.setString(++i, conv.nullCheck(regData.getNoRujukan())); System.out.println("regData.getNoRujukan() " + regData.getNoRujukan()); stmt.setString(++i, conv.nullCheck("1")); stmt.setString(++i, conv.nullCheck(regData.getNoDaftar()));//stmt.setString(++i, conv.nullCheck(regData.getAccNO())); stmt.setString(++i, conv.nullCheck("N")); stmt.setString(++i, conv.nullCheck("")); stmt.setString(++i, conv.nullCheck("9")); stmt.setString(++i, conv.nullCheck(year+"-"+mon+"-"+day+" "+hour+":"+minute+":"+seconds+"."+milisec)); System.out.println("ASAGTS " + year+"-"+mon+"-"+day+" "+hour+":"+minute+":"+seconds+"."+milisec); stmt.setString(++i, conv.nullCheck(regData.getTxnID())); System.out.println("ASLICE " + regData.getTxnID()); stmt.setString(++i, conv.nullCheck(regData.getKodTransaksi())); System.out.println("regData.getKodTransaksi() " + regData.getKodTransaksi()); stmt.setString(++i, conv.nullCheck(year+"-"+mon+"-"+day)); //tkh buka cawangan System.out.println("year-mon-day " + year+"-"+mon+"-"+day); stmt.setString(++i, conv.nullCheck(regData.getPusatKos())); System.out.println("regData.getPusatKos() " + regData.getPusatKos()); stmt.setString(++i, conv.nullCheck("93")); stmt.setString(++i, conv.nullCheck(regData.getDasarAmaunBeku())); System.out.println("ASA4CD " + regData.getDasarAmaunBeku()); stmt.setString(++i, conv.nullCheck("0")); stmt.setString(++i, conv.nullCheck("")); stmt.setString(++i, conv.nullCheck("")); //stmt.setString(++i, conv.nullCheck(regData.getUuid().substring(0,15))); stmt.setString(++i, conv.nullCheck(mon+day+hour+minute+seconds+milisec.substring(0,4))); System.out.println("ASPXCE " + mon+day+hour+minute+seconds+milisec.substring(0,4)); stmt.setString(++i, conv.nullCheck(regData.getTxnID())); //stmt.setString(++i, conv.nullCheck("THIJARI")); System.out.println("regData.getTxnID() " + regData.getTxnID()); stmt.setString(++i, conv.nullCheck("")); stmt.setString(++i, conv.nullCheck("0001-01-01")); stmt.setString(++i, conv.nullCheck("2")); rs = stmt.executeUpdate(); if (rs > 0) { flag = true; System.out.println(rs + "records updated - createHjDPPenyata"); } } catch (Exception ex) { System.out.println(ex.getMessage()); } finally { // release(stmt, rs); } return flag; } }
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.sample.agdktunnel; import android.os.Bundle; import com.google.androidgamesdk.GameActivity; // A minimal extension of GameActivity. For this sample, it is only used to invoke // a workaround for loading the runtime shared library on old Android versions public class AGDKTunnelActivity extends GameActivity { // Load our native library: static { // Load the STL first to workaround issues on old Android versions: // "if your app targets a version of Android earlier than Android 4.3 // (Android API level 18), // and you use libc++_shared.so, you must load the shared library before any other // library that depends on it." // See https://developer.android.com/ndk/guides/cpp-support#shared_runtimes System.loadLibrary("c++_shared"); // Load the game library: System.loadLibrary("game"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } }
package FlappyBird; import java.awt.Graphics; import java.awt.event.MouseEvent; import setup.*; public class TrainFlappyAI implements Manager{ public static final int Width = 700, Height = 700; PG pg; public TrainFlappyAI(int sub, int layers, int[] nnodes) { pg = new PG(sub, layers, nnodes, 0.1, Width, Height); } @Override public void draw(Graphics g) { pg.draw(g); } @Override public void tick() { pg.tick(); } @Override public void mouseDragged(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { } @Override public void mouseClicked(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void keyPressed(int e) { pg.keyPressed(e); } @Override public void keyReleased(int e) { } @Override public void keyTyped(int e) { } public static void main(String[] args) { int sub = 50; int layers = 4; int[] nnodes = {4, 5, 3, 1}; @SuppressWarnings("unused") Window wind = new Window(Width, Height, 60, 60, "Train AI", new TrainFlappyAI(sub, layers, nnodes)); } }
/** * */ package org.artifact.security.intercept; import org.artifact.security.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; /** * 查询当前用户所具有的权限 * <p> * 日期:2015年8月26日 * * @version 0.1 * @author Netbug */ @Component public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserService userService; public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return userService.findUser(username, null); } }
package sr.hakrinbank.intranet.api.service; import sr.hakrinbank.intranet.api.model.RatesControlling; import java.util.List; /** * Created by clint on 5/24/17. */ public interface RatesControllingService { List<RatesControlling> findAllRatesByControlling(); RatesControlling findById(long id); void updateRatesByControlling(RatesControlling module); List<RatesControlling> findAllActiveRatesByControlling(); RatesControlling findByName(String name); List<RatesControlling> findAllActiveRatesByControllingBySearchQuery(String qry); int countRatesByControllingOfTheWeek(); List<RatesControlling> findAllActiveRatesByControllingOrderedByDate(); List<RatesControlling> findAllActiveRatesByControllingByDate(String date); }
package com.ideaheap.logic; public class OperatorFactory { public OperatorFactory() { } public boolean hasOperator(String atom) { // TODO Auto-generated method stub return false; } }
package com.zhaoyan.ladderball.domain.account.http; import com.zhaoyan.ladderball.domain.common.http.Request; public class RecorderAddRequest extends Request { /** * 电话号码 */ public String phone; /** * 密码 */ public String password; /** * 姓名 */ public String name; /** * 地址 */ public String address; /** * 性别 */ public int gender; /** * 性别:未知 */ public static final int GENDER_UNKNOWN = 0; /** * 性别:男 */ public static final int GENDER_MALE = 1; /** * 性别:女 */ public static final int GENDER_FEMALE = 2; public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getGender() { return gender; } public void setGender(int gender) { this.gender = gender; } @Override public String toString() { return super.toString() + "RecorderAddRequest{" + "phone='" + phone + '\'' + ", name='" + name + '\'' + ", address='" + address + '\'' + ", gender=" + gender + '}'; } }
package global.coda.hospitalmanagement.dbconnection; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ResourceBundle; import org.apache.log4j.Logger; import global.coda.hospitalmanagement.constant.BundleFile; import global.coda.hospitalmanagement.constant.BundleKey; // TODO: Auto-generated Javadoc /** * The Class SqlConnection. */ public class SqlConnection { /** The Constant BUNDLE. */ private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(BundleFile.FILE); /** The Constant LOGGER. */ private static final Logger LOGGER = Logger.getLogger(SqlConnection.class); /** The connection. */ private static Connection connection; /** * Gets the connection. * * @return the connection * @throws ClassNotFoundException the class not found exception * @throws SQLException the SQL exception */ public static Connection getConnection() throws ClassNotFoundException, SQLException { LOGGER.info("Executing getConnection function"); final String driver = BUNDLE.getString(BundleKey.DRIVER); LOGGER.debug("driver used is :" + driver); Class.forName(driver); final String userName = BUNDLE.getString(BundleKey.USERNAME); LOGGER.debug("username is :" + userName); final String password = BUNDLE.getString(BundleKey.PASSWORD); final String dataBase = BUNDLE.getString(BundleKey.DATABASE); LOGGER.debug("database is :" + dataBase); String url = BUNDLE.getString(BundleKey.URL); LOGGER.debug("retrieved url is :" + url); url = url + "/" + dataBase; LOGGER.debug("cuurent url is :" + url); connection = DriverManager.getConnection(url, userName, password); LOGGER.info("Exiting getConnection function"); return connection; } /** * Close connection. * * @throws SQLException the SQL exception */ public static void closeConnection() throws SQLException { try { LOGGER.info("trying to close connection"); connection.close(); LOGGER.info("connection closed successfully"); } catch (SQLException e) { throw new SQLException(e); } } /** * Roll back. * * @throws SQLException the SQL exception */ public static void rollBack() throws SQLException { try { LOGGER.info("trying to rollback"); connection.rollback(); LOGGER.info("roll back Successfull"); } catch (SQLException e) { throw new SQLException(e); } } }
package analysis.service.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import analysis.service.AnalysisService; import analysis.util.AnalysisUtil; import berkeley.service.BerkeleyService; import berkeley.service.impl.BerkeleyServiceImpl; import csv.bean.Daily; import elasticsearch.bean.SearchParamCollection; import elasticsearch.service.ElasticService; import elasticsearch.service.impl.ElasticServiceImpl; import elasticsearch.util.ClientUtil; import elasticsearch.util.ElasticUtil; import quartz.job.AnalysisJob; import quartz.util.JobUtil; import realtime.bean.TotalStock; import util.ConstantUtil; public class AnalysisServiceImpl implements AnalysisService { private static Map<String, String> compMap; private static AnalysisServiceImpl INSTANCE; public static synchronized AnalysisServiceImpl getInstance() { if (null == INSTANCE) { INSTANCE = new AnalysisServiceImpl(); } return INSTANCE; } private AnalysisServiceImpl() { // 获取编码信息 BerkeleyService berkeleyService = BerkeleyServiceImpl.getInstance(); compMap = berkeleyService.queryDatabaseByKey(ConstantUtil.STOCK_DB, ConstantUtil.STOCK_KEY); } /** * 将分析数据插入放到日常库 */ @Override public void getDailyStockAnalysis() { ClientUtil.getNewClient(); ElasticService elasticService = ElasticServiceImpl.getInstance(); // 收集数据 List<TotalStock> tsAllList = integrationTotalStock(elasticService); // 保存数据 saveDailyTotalStock(elasticService, tsAllList); // 整理完数据后删除索引释放空间 elasticService.deleteIndexByName(ConstantUtil.INDICES_TIM); ClientUtil.closeClient(); } /** * 整合所有TotalStock日数据 */ @Override public List<TotalStock> integrationTotalStock( ElasticService elasticService) { SearchParamCollection spc; List<TotalStock> tsList; List<TotalStock> tsAllList = new ArrayList<>(); // 按照股票代码遍历找到所有日数据并放到集合中 for (Map.Entry<String, String> entry : compMap.entrySet()) { spc = AnalysisUtil.getSPCAtNight(entry.getValue()); tsList = elasticService.queryEntityByParam(spc, ConstantUtil.INDICES_TIM, TotalStock.class); tsAllList.addAll(tsList); } return tsAllList; } /** * 保存日常数据 * * @param elasticService * @param tsAllList */ @Override public void saveDailyTotalStock(ElasticService elasticService, List<TotalStock> tsAllList) { if (null != tsAllList && !tsAllList.isEmpty()) { Map<String, Object> paramMap = setInsertJsonList(tsAllList); List<String> jsonSzList = (List<String>) paramMap.get("jsonSz"); if (null != jsonSzList && !jsonSzList.isEmpty()) { elasticService.batchInsertEntity(jsonSzList, ConstantUtil.INDICES_DAY, ConstantUtil.TYPES_SZ); } List<String> jsonShList = (List<String>) paramMap.get("jsonSh"); if (null != jsonShList && !jsonShList.isEmpty()) { elasticService.batchInsertEntity(jsonShList, ConstantUtil.INDICES_DAY, ConstantUtil.TYPES_SS); } } } /** * 为插入elasticsearch设值 * * @param elasticService * @param tsAllList * @return */ private Map<String, Object> setInsertJsonList(List<TotalStock> tsAllList) { String exchange; String stockCode; Daily daily; List<String> jsonSzList = new ArrayList<>(); List<String> jsonShList = new ArrayList<>(); Map<String, Object> reMap = new HashMap<>(); for (TotalStock ts : tsAllList) { stockCode = ts.getStockCode(); exchange = stockCode.substring(0, 2); daily = new Daily(); daily.setDate(ts.getDate()); daily.setAdjClose(ts.getCurrentPrice()); daily.setClose(ts.getCurrentPrice()); daily.setCompCode(stockCode); daily.setExchange(exchange); daily.setHigh(ts.getTdyHighPrice()); daily.setLow(ts.getTdyLowPrice()); daily.setOpen(ts.getTdyOpenPrice()); daily.setVolume(ts.getNumSharesTraded()); if ("sz".equalsIgnoreCase(exchange)) { jsonSzList.add(ElasticUtil.model2Json(daily)); } else { jsonShList.add(ElasticUtil.model2Json(daily)); } } reMap.put("jsonSz", jsonSzList); reMap.put("jsonSh", jsonShList); return reMap; } /** * 定时器启动执行分析任务 */ @Override public void startDailyStockJobThread() { Map<String, String> paramMap = new HashMap<>(); paramMap.put("type", "cron"); paramMap.put("cron", "0 30 15 * * ?"); try { JobUtil.initJob(AnalysisJob.class, "AnalysisJob", paramMap); } catch (Exception e) { e.printStackTrace(); } } }
package game.gfx; import java.awt.image.BufferedImage; import game.Game; public class SpriteSheet { private BufferedImage sheet; public SpriteSheet(BufferedImage sheet) { this.sheet = sheet; } public BufferedImage crop(int x, int y, int width, int height) { BufferedImage bI = new BufferedImage( (int) (Game.SCALE * width), (int) (Game.SCALE * height), BufferedImage.TYPE_INT_ARGB); bI.getGraphics().drawImage(sheet.getSubimage(x, y, width, height), 0, 0, (int) (width * Game.SCALE), (int) (height * Game.SCALE), null); return (bI); } }
package crawler.core; public class DataExtractor { }
package com.radauer.mathrix.tasks; import java.math.BigDecimal; import java.util.Map; import org.apache.commons.lang3.ArrayUtils; import com.radauer.mathrix.GroupKey; import com.radauer.mathrix.Mathrix; import com.radauer.mathrix.Position; import com.radauer.mathrix.RowKey; import com.radauer.mathrix.RowType; /** * Calculation Task for copying values from rows of one group and into an other row * vertical summing */ public class SumTask implements Task { private GroupKey groupKey; private RowType[] sourceRowTypes; private RowKey targetRowKey; public SumTask(GroupKey groupKey, RowType[] sourceRowTypes, RowKey targetRowKey) { this.groupKey = groupKey; this.sourceRowTypes = sourceRowTypes; this.targetRowKey = targetRowKey; } @Override public void calc(Mathrix mathrix) { Map<RowKey, Position> group = mathrix.getGroup(groupKey); BigDecimal result = group.values().stream() .filter(p -> sourceRowTypes == null || ArrayUtils.contains(sourceRowTypes, p.getRowKey().getRowType())) .filter(p -> p.getValue() != null) .map(p -> p.getValue()) .reduce(BigDecimal.ZERO, BigDecimal::add); mathrix.insert(new Position(groupKey, targetRowKey, result)); } }
package com.jfronny.raut.mixin.interfacing; public interface ItemExtension { public void SetCount(int count); }
package hr.apps.cookies.mcpare.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import hr.apps.cookies.mcpare.R; import hr.apps.cookies.mcpare.data.Posao; /** * Created by lmita_000 on 26.5.2015.. */ public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> { private LayoutInflater inflater; private Context context; private List<Posao> listaPodataka; public RecyclerAdapter(Context context, List<Posao> lista){ listaPodataka = lista; this.context = context; inflater = LayoutInflater.from(context); } @Override public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View v = inflater.inflate(R.layout.row, viewGroup, false); MyViewHolder holder = new MyViewHolder(v); return holder; } @Override public void onBindViewHolder(MyViewHolder myViewHolder, int i) { Posao podatak = listaPodataka.get(i); SimpleDateFormat dayFormat = new SimpleDateFormat("EEE, dd."); SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm"); Calendar calendar = Calendar.getInstance(); myViewHolder.pozicija.setText(podatak.getPozicija().getIme_pozicija()); myViewHolder.datum_do.setText(timeFormat.format(podatak.getKraj())); myViewHolder.datum_od.setText(timeFormat.format(podatak.getPocetak())); myViewHolder.datum.setText(dayFormat.format(podatak.getPocetak())); } @Override public int getItemCount() { return listaPodataka.size(); } class MyViewHolder extends RecyclerView.ViewHolder{ TextView pozicija, datum_od, datum_do, datum; public MyViewHolder(View itemView) { super(itemView); pozicija = (TextView) itemView.findViewById(R.id.pozicijaText); datum_od = (TextView) itemView.findViewById(R.id.pocetakText); datum_do = (TextView) itemView.findViewById(R.id.krajText); datum = (TextView) itemView.findViewById(R.id.datumText); } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.davivienda.sara.tablas.TiraAuditoria.servicio; import com.davivienda.sara.base.AdministracionTablasInterface; import com.davivienda.sara.base.BaseEntityServicio; import com.davivienda.sara.base.exception.EntityServicioExcepcion; import com.davivienda.sara.entitys.TiraAuditoria; import com.davivienda.sara.tablas.edccargue.servicio.EdcCargueServicio; import com.davivienda.utilidades.conversion.Fecha; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.logging.Level; import javax.persistence.EntityManager; import javax.persistence.ParameterMode; import javax.persistence.Query; import javax.persistence.StoredProcedureQuery; /** * * @author nmelo */ public class TiraAuditoriaServicio{ private EntityManager em; public TiraAuditoriaServicio(final EntityManager em) { this.em=em; } public List<TiraAuditoria> getTira(Integer codigo, Date fechaInicial, Date fechaFinal) throws EntityServicioExcepcion { List<TiraAuditoria> items = null; //items=query.getResultList();*/ Query query = null; query=em.createNativeQuery( " SELECT " +" TA.CODIGOBANCO, " +" TA.IDZONA, " +" TA.IDOCCA, " +" TA.IDCAJERO, " +" TA.TIPOMAQUINA, " +" TA.TIPOREGISTRO, " +" TA.NUMEROTRANSACCION, " +" (SELECT TA.IDTRANSACCION||'-'||DESCRIPCION " +" FROM ADMINATM.TIRA_TIPO_TRANSACCION T " +" WHERE T.CODIGO = TA.IDTRANSACCION " +" AND ESTADO = 1) IDTRANSACCION, " +" TA.TIPOTRANSACCION, " +" ( SELECT M.CODIGO||'-'||M.DESCRIPCION " +" FROM ADMINATM.TIRA_TIPO_MENSAJE M " +" WHERE M.CODIGO = TA.IDMENSAJE " +" AND M.ESTADO = 1) DESCTRANSACCION, " +" TA.FECHAREALTRANSACCION, " +" TA.FECHACONTABLETRANSACCION, " +" TA.NUMEROTARJETA, " +" TA.NUMEROPRODUCTO, " +" ( SELECT TP.CODIGO ||'-'|| TP.DESCRIPCION " +" FROM ADMINATM.TIRA_TIPO_PRODUCTO TP " +" WHERE TP.CODIGO = TA.IDPRODUCTOORIGEN " +" AND TP.ESTADO = 1 )PTODUCTORIGEN, " +" MT.MONTOTRANSACCIONRETIRO, " +" MT.MONTOTXRETIROENTREGADO, " +" MT.VALORDONACION, " +" MT.COSTOTRANSACCION, " +" MT.VUELTASDESCRIPCION, " +" MT.MONTOTXDEPOSITO, " +" MT.MONTOTXDEPOSITORECIBIDO, " +" ( SELECT REFERENCIA " +" FROM ADMINATM.TIRA_REFERENCIAS TR " +" WHERE TR.IDCAJERO=TA.IDCAJERO " +" AND TR.FECHAREALTRANSACCION= TA.FECHAREALTRANSACCION " +" AND TR.NUMEROTRANSACCION = TA.NUMEROTRANSACCION " +" AND NUMREGISTRO = 1 " +" )REFERENCIA1, " +" ( SELECT REFERENCIA " +" FROM ADMINATM.TIRA_REFERENCIAS TR " +" WHERE TR.IDCAJERO=TA.IDCAJERO " +" AND TR.FECHAREALTRANSACCION= TA.FECHAREALTRANSACCION " +" AND TR.NUMEROTRANSACCION = TA.NUMEROTRANSACCION " +" AND NUMREGISTRO = 2 " +" )REFERENCIA2, " +" ( SELECT REFERENCIA " +" FROM ADMINATM.TIRA_REFERENCIAS TR " +" WHERE TR.IDCAJERO=TA.IDCAJERO " +" AND TR.FECHAREALTRANSACCION= TA.FECHAREALTRANSACCION " +" AND TR.NUMEROTRANSACCION = TA.NUMEROTRANSACCION " +" AND NUMREGISTRO = 3 " +" )REFERENCIA3, " +" ( SELECT TP.CODIGO ||'-'|| TP.DESCRIPCION " +" FROM ADMINATM.TIRA_TIPO_PRODUCTO TP " +" WHERE TP.CODIGO = TA.IDPRODUCTODESTINO " +" AND TP.ESTADO = 1 )PTODUCTODESTINO, " +" TA.NUMEROPRODUCTODESTINO, " +" TA.NUMEROAPROBACION, " +" TA.CODIGOERRORHOST, " +" TA.DESCRIPCIONERRORHOST, " +" TA.CODIGOERRORATM, " +" TA.DESCRIPCIONERRORATM, " +" TA.ESTADOIMPRESION, " +" TA.LOGAUDITA, " +" TI.CANTIDAD, " +" TI.VALOR, " +" TI1.CANTIDAD CANTIDAD1, " +" TI1.VALOR VALOR1, " +" TI2.CANTIDAD CANTIDAD2, " +" TI2.VALOR VALOR2, " +" TI3.CANTIDAD CANTIDAD3, " +" TI3.VALOR VALOR3, " +" TI4.CANTIDAD CANTIDAD4, " +" TI4.VALOR VALOR4, " +" TI5.CANTIDAD CANTIDAD5, " +" TI5.VALOR VALOR5, " +" TI6.CANTIDAD CANTIDAD6, " +" TI6.VALOR VALOR6, " +" TI7.CANTIDAD CANTIDAD7, " +" TI7.VALOR VALOR7, " +" TI8.CANTIDAD CANTIDAD8, " +" TI8.VALOR VALOR8, " +" TG.DENOMINACIONBILLETES, " +" TG.CANTBILLETESPROVISION, " +" TG.BILLETESDISPENSADOS, " +" TG.ACUMBILLETESDISPENSADOS, " +" TG.BILLETESDEPOSITADOS, " +" TG.ACUMBILLETESDEPOSITADOS, " +" TG.BILLETESREMANENTES, " +" TG.BILLETESRECHAZADOS, " +" TG.ACUMBILLETESRECHAZADOS, " +" TG.BILLETESRETRAC, " +" TG.ACUMBILLETESRETRACT, " +" TG2.DENOMINACIONBILLETES DENOMINACIONBILLETES1, " +" TG2.CANTBILLETESPROVISION CANTBILLETESPROVISION1, " +" TG2.BILLETESDISPENSADOS BILLETESDISPENSADOS1, " +" TG2.ACUMBILLETESDISPENSADOS ACUMBILLETESDISPENSADOS1, " +" TG2.BILLETESDEPOSITADOS BILLETESDEPOSITADOS1, " +" TG2.ACUMBILLETESDEPOSITADOS ACUMBILLETESDEPOSITADOS1, " +" TG2.BILLETESREMANENTES BILLETESREMANENTES1, " +" TG2.BILLETESRECHAZADOS BILLETESRECHAZADOS1, " +" TG2.ACUMBILLETESRECHAZADOS ACUMBILLETESRECHAZADOS1, " +" TG2.BILLETESRETRAC BILLETESRETRAC1, " +" TG2.ACUMBILLETESRETRACT ACUMBILLETESRETRACT1, " +" TG3.DENOMINACIONBILLETES DENOMINACIONBILLETES2, " +" TG3.CANTBILLETESPROVISION CANTBILLETESPROVISION2, " +" TG3.BILLETESDISPENSADOS BILLETESDISPENSADOS2, " +" TG3.ACUMBILLETESDISPENSADOS ACUMBILLETESDISPENSADOS2, " +" TG3.BILLETESDEPOSITADOS BILLETESDEPOSITADOS2, " +" TG3.ACUMBILLETESDEPOSITADOS ACUMBILLETESDEPOSITADOS2, " +" TG3.BILLETESREMANENTES BILLETESREMANENTES2, " +" TG3.BILLETESRECHAZADOS BILLETESRECHAZADOS2, " +" TG3.ACUMBILLETESRECHAZADOS ACUMBILLETESRECHAZADOS2, " +" TG3.BILLETESRETRAC BILLETESRETRAC2, " +" TG3.ACUMBILLETESRETRACT ACUMBILLETESRETRACT2, " +" TG4.DENOMINACIONBILLETES DENOMINACIONBILLETES3, " +" TG4.CANTBILLETESPROVISION CANTBILLETESPROVISION3, " +" TG4.BILLETESDISPENSADOS BILLETESDISPENSADOS3, " +" TG4.ACUMBILLETESDISPENSADOS ACUMBILLETESDISPENSADOS3, " +" TG4.BILLETESDEPOSITADOS BILLETESDEPOSITADOS3, " +" TG4.ACUMBILLETESDEPOSITADOS ACUMBILLETESDEPOSITADOS3, " +" TG4.BILLETESREMANENTES BILLETESREMANENTES3, " +" TG4.BILLETESRECHAZADOS BILLETESRECHAZADOS3, " +" TG4.ACUMBILLETESRECHAZADOS ACUMBILLETESRECHAZADOS3, " +" TG4.BILLETESRETRAC BILLETESRETRAC3, " +" TG4.ACUMBILLETESRETRACT ACUMBILLETESRETRACT3, " +" TG5.DENOMINACIONBILLETES DENOMINACIONBILLETES4, " +" TG5.CANTBILLETESPROVISION CANTBILLETESPROVISION4, " +" TG5.BILLETESDISPENSADOS BILLETESDISPENSADOS4, " +" TG5.ACUMBILLETESDISPENSADOS ACUMBILLETESDISPENSADOS4, " +" TG5.BILLETESDEPOSITADOS BILLETESDEPOSITADOS4, " +" TG5.ACUMBILLETESDEPOSITADOS ACUMBILLETESDEPOSITADOS4, " +" TG5.BILLETESREMANENTES BILLETESREMANENTES4, " +" TG5.BILLETESRECHAZADOS BILLETESRECHAZADOS4, " +" TG5.ACUMBILLETESRECHAZADOS ACUMBILLETESRECHAZADOS4, " +" TG5.BILLETESRETRAC BILLETESRETRAC4, " +" TG5.ACUMBILLETESRETRACT ACUMBILLETESRETRACT4, " +" TG6.DENOMINACIONBILLETES DENOMINACIONBILLETES5, " +" TG6.CANTBILLETESPROVISION CANTBILLETESPROVISION5, " +" TG6.BILLETESDISPENSADOS BILLETESDISPENSADOS5, " +" TG6.ACUMBILLETESDISPENSADOS ACUMBILLETESDISPENSADOS5, " +" TG6.BILLETESDEPOSITADOS BILLETESDEPOSITADOS5, " +" TG6.ACUMBILLETESDEPOSITADOS ACUMBILLETESDEPOSITADOS5, " +" TG6.BILLETESREMANENTES BILLETESREMANENTES5, " +" TG6.BILLETESRECHAZADOS BILLETESRECHAZADOS5, " +" TG6.ACUMBILLETESRECHAZADOS ACUMBILLETESRECHAZADOS5, " +" TG6.BILLETESRETRAC BILLETESRETRAC5, " +" TG6.ACUMBILLETESRETRACT ACUMBILLETESRETRACT5 " +"FROM ADMINATM.TIRA_AUDITORIA TA " +"JOIN TIRA_MONTO_TRANSACCION MT " +"ON MT.IDCAJERO = TA.IDCAJERO " +"AND MT.FECHAREALTRANSACCION = TA.FECHAREALTRANSACCION " +"AND MT.NUMEROTRANSACCION = TA.NUMEROTRANSACCION " +"JOIN ADMINATM.TIRA_GAVETAS TG " +"ON TG.IDCAJERO = TA.IDCAJERO " +"AND TG.FECHAREALTRANSACCION = TA.FECHAREALTRANSACCION " +"AND TG.NUMEROTRANSACCION = TA.NUMEROTRANSACCION " +"AND TG.NUMEROGAVETA = 1 " +"JOIN ADMINATM.TIRA_GAVETAS TG2 " +"ON TG2.IDCAJERO = TA.IDCAJERO " +"AND TG2.FECHAREALTRANSACCION = TA.FECHAREALTRANSACCION " +"AND TG2.NUMEROTRANSACCION = TA.NUMEROTRANSACCION " +"AND TG2.NUMEROGAVETA = 2 " +"JOIN ADMINATM.TIRA_GAVETAS TG3 " +"ON TG3.IDCAJERO = TA.IDCAJERO " +"AND TG3.FECHAREALTRANSACCION = TA.FECHAREALTRANSACCION " +"AND TG3.NUMEROTRANSACCION = TA.NUMEROTRANSACCION " +"AND TG3.NUMEROGAVETA = 3 " +"JOIN ADMINATM.TIRA_GAVETAS TG4 " +"ON TG4.IDCAJERO = TA.IDCAJERO " +"AND TG4.FECHAREALTRANSACCION = TA.FECHAREALTRANSACCION " +"AND TG4.NUMEROTRANSACCION = TA.NUMEROTRANSACCION " +"AND TG4.NUMEROGAVETA = 4 " +"JOIN ADMINATM.TIRA_GAVETAS TG5 " +"ON TG5.IDCAJERO = TA.IDCAJERO " +"AND TG5.FECHAREALTRANSACCION = TA.FECHAREALTRANSACCION " +"AND TG5.NUMEROTRANSACCION = TA.NUMEROTRANSACCION " +"AND TG5.NUMEROGAVETA = 5 " +"JOIN ADMINATM.TIRA_GAVETAS TG6 " +"ON TG6.IDCAJERO = TA.IDCAJERO " +"AND TG6.FECHAREALTRANSACCION = TA.FECHAREALTRANSACCION " +"AND TG6.NUMEROTRANSACCION = TA.NUMEROTRANSACCION " +"AND TG6.NUMEROGAVETA = 6 " +"JOIN ADMINATM.TIRA_TOTAL_TRANSACCION TI " +"ON TI.IDCAJERO = TA.IDCAJERO " +"AND TI.FECHAREALTRANSACCION = TA.FECHAREALTRANSACCION " +"AND TI.NUMEROTRANSACCION = TA.NUMEROTRANSACCION " +"AND TI.CODIGOMOVIMIENTO = 'RETDAV' " +"JOIN ADMINATM.TIRA_TOTAL_TRANSACCION TI1 " +"ON TI1.IDCAJERO = TA.IDCAJERO " +"AND TI1.FECHAREALTRANSACCION = TA.FECHAREALTRANSACCION " +"AND TI1.NUMEROTRANSACCION = TA.NUMEROTRANSACCION " +"AND TI1.CODIGOMOVIMIENTO = 'AVADAV' " +"JOIN ADMINATM.TIRA_TOTAL_TRANSACCION TI2 " +"ON TI2.IDCAJERO = TA.IDCAJERO " +"AND TI2.FECHAREALTRANSACCION = TA.FECHAREALTRANSACCION " +"AND TI2.NUMEROTRANSACCION = TA.NUMEROTRANSACCION " +"AND TI2.CODIGOMOVIMIENTO = 'AVAOTR' " +"JOIN ADMINATM.TIRA_TOTAL_TRANSACCION TI3 " +"ON TI3.IDCAJERO = TA.IDCAJERO " +"AND TI3.FECHAREALTRANSACCION = TA.FECHAREALTRANSACCION " +"AND TI3.NUMEROTRANSACCION = TA.NUMEROTRANSACCION " +"AND TI3.CODIGOMOVIMIENTO = 'RETCIB' " +"JOIN ADMINATM.TIRA_TOTAL_TRANSACCION TI4 " +"ON TI4.IDCAJERO = TA.IDCAJERO " +"AND TI4.FECHAREALTRANSACCION = TA.FECHAREALTRANSACCION " +"AND TI4.NUMEROTRANSACCION = TA.NUMEROTRANSACCION " +"AND TI4.CODIGOMOVIMIENTO = 'RETGIR' " +"JOIN ADMINATM.TIRA_TOTAL_TRANSACCION TI5 " +"ON TI5.IDCAJERO = TA.IDCAJERO " +"AND TI5.FECHAREALTRANSACCION = TA.FECHAREALTRANSACCION " +"AND TI5.NUMEROTRANSACCION = TA.NUMEROTRANSACCION " +"AND TI5.CODIGOMOVIMIENTO = 'DEPAHO' " +"JOIN ADMINATM.TIRA_TOTAL_TRANSACCION TI6 " +"ON TI6.IDCAJERO = TA.IDCAJERO " +"AND TI6.FECHAREALTRANSACCION = TA.FECHAREALTRANSACCION " +"AND TI6.NUMEROTRANSACCION = TA.NUMEROTRANSACCION " +"AND TI6.CODIGOMOVIMIENTO = 'DEPCOR' " +"JOIN ADMINATM.TIRA_TOTAL_TRANSACCION TI7 " +"ON TI7.IDCAJERO = TA.IDCAJERO " +"AND TI7.FECHAREALTRANSACCION = TA.FECHAREALTRANSACCION " +"AND TI7.NUMEROTRANSACCION = TA.NUMEROTRANSACCION " +"AND TI7.CODIGOMOVIMIENTO = 'DEPDAV' " +"JOIN ADMINATM.TIRA_TOTAL_TRANSACCION TI8 " +"ON TI8.IDCAJERO = TA.IDCAJERO " +"AND TI8.FECHAREALTRANSACCION = TA.FECHAREALTRANSACCION " +"AND TI8.NUMEROTRANSACCION = TA.NUMEROTRANSACCION " +"AND TI8.CODIGOMOVIMIENTO = 'DEPOTR' " +"WHERE TA.FECHAREALTRANSACCION BETWEEN ?2 AND ?3 "//TO_DATE('15/03/2020','DD/MM/YYYY') " +" AND TA.IDCAJERO = (CASE WHEN -1=?1 THEN TA.IDCAJERO " +" ELSE ?1 END ) " +"ORDER BY TA.IDCAJERO, TA.FECHAREALTRANSACCION DESC ", TiraAuditoria.class); query.setParameter(1, codigo); query.setParameter(2, fechaInicial); query.setParameter(3, fechaFinal); items=query.getResultList(); //query.executeUpdate(); if(items!=null){ return items; }else{ return null; } } }
package ClassPackage; public class SecondClass extends FirstClass implements ClassInterface{ @Override public void doingSomething() { } public void doingSomething2(String name){ } public void doingSomething2(String name, int age){ } @Override public void doSomething() { } @Override public void wakingUp() { } @Override public void goingToSleep() { } }
package leader.game.event; import java.util.LinkedList; import java.util.logging.Logger; public class GameEventQueue { private static Logger logger = Logger.getLogger(GameEventQueue.class.getName()); private LinkedList<GameEvent> events = new LinkedList<>(); public GameEventQueue(){ } public void publish(GameEvent event){ synchronized (GameEventQueue.class) { events.add(event); } } public GameEvent pop(){ synchronized (GameEventQueue.class){ if (!events.isEmpty()){ return events.pop(); } } return null; } public int size(){ return events.size(); } public boolean isEmpty(){ return events.isEmpty(); } }
package com.senati.mediateca; public class Socio { int id; String nombre; String apellido; String distrito; //Constructor lleno public Socio(int id, String nombre, String apellido, String distrito) { super(); this.id = id; this.nombre = nombre; this.apellido = apellido; this.distrito = distrito; } //Constructor vacio public Socio() { super(); } //Getters and Setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellido() { return apellido; } public void setApellido(String apellido) { this.apellido = apellido; } public String getDistrito() { return distrito; } public void setDistrito(String distrito) { this.distrito = distrito; } //To String @Override public String toString() { return "Socio [id=" + id + ", nombre=" + nombre + ", apellido=" + apellido + ", distrito=" + distrito + "]"; } }
package chap5; public class Quotation { public static void main(String[] args) { System.out.println("文字列リテラルと文字数について。"); System.out.println("二重引用符で囲まれた\"ABC\"は文字列リテラルです。"); System.out.print("一重引用符で囲まれた"); System.out.print('\''); System.out.println("A'は文字リテラルです。"); System.out.println(""); System.out.println("\\\\\""); System.out.println("\61\62\63\64\65\66\67\70\71\72\73\74"); System.out.println("\160\161\162"); System.out.println("\u11c1"); } }
package com.worldchip.bbpawphonechat.fragment; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.util.Pair; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ImageView; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import com.easemob.chat.EMChatManager; import com.easemob.chat.EMContactManager; import com.easemob.chat.EMConversation; import com.worldchip.bbpawphonechat.R; import com.worldchip.bbpawphonechat.activity.CaptureActivity; import com.worldchip.bbpawphonechat.activity.MainActivity; import com.worldchip.bbpawphonechat.activity.PhoneChatActivity; import com.worldchip.bbpawphonechat.adapter.ChatContactsAdapter; import com.worldchip.bbpawphonechat.application.MyApplication; import com.worldchip.bbpawphonechat.comments.MyComment; import com.worldchip.bbpawphonechat.comments.MySharePreData; import com.worldchip.bbpawphonechat.db.InviteMessgeDao; import com.worldchip.bbpawphonechat.db.UserDao; import com.worldchip.bbpawphonechat.dialog.DelectPaidChatDialog; import com.worldchip.bbpawphonechat.dialog.EditFriendsRemarkName; import com.worldchip.bbpawphonechat.dialog.MyProgressDialog; import com.worldchip.bbpawphonechat.entity.User; import com.worldchip.bbpawphonechat.utils.Configure; public class ContactListFragment extends Fragment implements OnClickListener { private static final String TAG = "ContactListFragment"; private Context mContext; private ListView mContactsListView; private List<User> contactsList; private ChatContactsAdapter adapter; private ImageView mNote; private TextView mTvScanAddFriend; private Class<MainActivity> mActivity; private String chatToheadUrl = null; private String chattoName = null; private List<EMConversation> conversationList = new ArrayList<EMConversation>(); private int mChosePosition; private List<String> urls; private int urlId; private UserDao userDao; private PopupWindow mPopupWindow; private View mPopupView; private int mScreenHeight; private int mScreenWidth; private int xPosition; private TextView mTvRemarkName, mTvDelectFriends,mTvCancle; Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case MyComment.CHAT_FRAGMWENT_DELECT_FRIEND: mChosePosition = adapter.getmPosition(); User tobeDeleteUser = (User) adapter.getItem(mChosePosition); deleteContact(tobeDeleteUser); InviteMessgeDao dao = new InviteMessgeDao(getActivity()); dao.deleteMessage(tobeDeleteUser.getUsername()); refresh(); break; case MyComment.CHANGE_FRIENDS_REMARKNAME: User cUser = (User) adapter.getItem(mChosePosition); String remarkName = (String) msg.obj; userDao.updataRemarkName(cUser, remarkName); initMyContactList(); break; default: break; } }; }; public ContactListFragment(Context context) { this.mContext = context; } public ContactListFragment(){} @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); conversationList.addAll(loadConversationsWithRecentChat()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_chat_tab_content, container, false); ImageView iv_head = (ImageView) view .findViewById(R.id.iv_top_bar_my_head); mContactsListView = (ListView) view.findViewById(R.id.lv_chat_contacts); mNote = (ImageView) view.findViewById(R.id.iv_null_contacts_note); mTvScanAddFriend = (TextView) view.findViewById(R.id.tv_top_bar_title); //mTvScanAddFriend.setBackground(null); userDao = new UserDao(mContext); contactsList = new ArrayList<User>(); mTvScanAddFriend.setOnClickListener(this); MyApplication .getInstance() .getImageLoader() .displayImage(MyApplication.getInstance().getHeadImageUrl(), iv_head, MyApplication.getInstance().getDisplayOptionsHead()); initMyContactList(); initControlBabyData(); LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mPopupView = layoutInflater.inflate(R.layout.popup_window_layout, null); mPopupWindow = new PopupWindow(mPopupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); mPopupWindow.setFocusable(true); mPopupWindow.setOutsideTouchable(true); mPopupWindow.setBackgroundDrawable(new BitmapDrawable()); mScreenHeight = Configure.getScreenHeight(mContext); mScreenWidth = Configure.getScreenWidth(mContext); xPosition = mScreenWidth/2 - 150; System.out.println(xPosition+"---mScreenWidth---"+mScreenWidth+"-----"+mPopupView.getWidth()/2); mTvRemarkName = (TextView) mPopupView.findViewById(R.id.tv_change_remarkname); mTvDelectFriends = (TextView) mPopupView.findViewById(R.id.tv_delect_contact); mTvCancle = (TextView) mPopupView.findViewById(R.id.tv_pupopwindow_cancle); mTvRemarkName.setOnClickListener(this); mTvDelectFriends.setOnClickListener(this); mTvCancle.setOnClickListener(this); mContactsListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { User userToChat = (User) adapter.getItem(position); if (userToChat.getHeadurl() != null) { chatToheadUrl = userToChat.getHeadurl(); } if(userToChat.getRemark_name() != null && !userToChat.getRemark_name().equals("")){ chattoName = userToChat.getRemark_name(); }else if (!userToChat.getNick().equals("")) { chattoName = userToChat.getNick(); }else { chattoName = userToChat.getUsername(); } Intent intent = new Intent(mContext, PhoneChatActivity.class); intent.putExtra("chatto", userToChat.getUsername()); intent.putExtra("nick", chattoName); intent.putExtra("chattoheadurl", chatToheadUrl); startActivity(intent); } }); mContactsListView.setOnItemLongClickListener(new OnItemLongClickListener() { @SuppressLint("NewApi") @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) { View parentView = mContactsListView.getChildAt(position); mChosePosition = position; adapter.setmPosition(mChosePosition); View view = adapter.getView(position, arg1, arg0); mPopupWindow.showAsDropDown(parentView, xPosition, -50); return true; } }); initMyContactList(); return view; } @Override public void onResume() { super.onResume(); initMyContactList(); } @Override public void onDestroy() { super.onDestroy(); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.tv_top_bar_title: Intent intent = new Intent(mContext, CaptureActivity.class); getActivity().startActivityForResult(intent, MyComment.START_SCAN_ADD_FRIEND); break; case R.id.tv_change_remarkname: popupDismiss(); EditFriendsRemarkName dialog = new EditFriendsRemarkName(handler, mContext,adapter); dialog.show(); break; case R.id.tv_pupopwindow_cancle: popupDismiss(); break; case R.id.tv_delect_contact: popupDismiss(); DelectPaidChatDialog delectLockPaidDialog = new DelectPaidChatDialog( handler, getActivity()); delectLockPaidDialog.show(); break; default: break; } } private void popupDismiss() { if(mPopupWindow != null && mPopupView != null){ if(mPopupWindow.isShowing()){ mPopupWindow.dismiss(); } } } // 刷新好友列表 public void refresh() { try { // 可能会在子线程中调到这方法 getActivity().runOnUiThread(new Runnable() { public void run() { initMyContactList(); initControlBabyData(); mContext.sendBroadcast(new Intent( MyComment.SEND_CONTACT_INFO_BROADCAST)); } }); } catch (Exception e) { e.printStackTrace(); } } public void refreshMessage() { try { // 可能会在子线程中调到这方法 getActivity().runOnUiThread(new Runnable() { public void run() { updataConversation(); adapter.notifyDataSetChanged(); } }); } catch (Exception e) { e.printStackTrace(); } } /** * 刷新聊天对象列表 */ private void updataConversation() { if (conversationList != null) { conversationList.removeAll(conversationList); conversationList.addAll(loadConversationsWithRecentChat()); } } /** * 获取联系人列表,并过滤掉黑名单和排序 */ private void initMyContactList() { if (contactsList != null) { contactsList.removeAll(contactsList); contactsList.clear(); } // 获取本地好友列表 Map<String, User> users = MyApplication.getInstance().getContactList(); Iterator<Entry<String, User>> iterator = users.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, User> entry = iterator.next(); if (!entry.getKey().equals(MyComment.NEW_FRIENDS_USERNAME) && !entry.getKey().equals(MyComment.GROUP_USERNAME)) contactsList.add(entry.getValue()); } setContactsListView(); } private void initControlBabyData(){ if (contactsList.size() <= 0) { MySharePreData.SetBooleanData(mContext, MyComment.CHAT_SP_NAME, "show_select", false); MySharePreData.SetData(mContext, MyComment.CHAT_SP_NAME, "control_to", ""); MyComment.CONTROL_BABY_NAME = ""; } else if (contactsList.size() >= 1) { MySharePreData.SetBooleanData(mContext, MyComment.CHAT_SP_NAME, "show_select", true); MySharePreData.SetData(mContext, MyComment.CHAT_SP_NAME, "control_to", contactsList.get(0).getUsername()); MyComment.CONTROL_BABY_NAME = contactsList.get(0).getUsername(); } } @SuppressLint("NewApi") private void setContactsListView() { if (contactsList.size() == 0) { MyApplication.getInstance().ImageAdapter( mNote, new int[] { R.drawable.chat_scan_txt_note, R.drawable.chat_scan_txt_note_es, R.drawable.chat_scan_txt_note_en }); } else { MyApplication.getInstance().ImageAdapter( mNote, new int[] { R.drawable.chat_fragment_top_note, R.drawable.chat_fragment_top_note_es, R.drawable.chat_fragment_top_note_en }); if (adapter != null) { adapter = null; } adapter = new ChatContactsAdapter(handler, contactsList, conversationList, mContext); mContactsListView.setAdapter(adapter); } } /** * 获取所有会话 * * @param context * @return + */ private List<EMConversation> loadConversationsWithRecentChat() { // 获取所有会话,包括陌生人 Hashtable<String, EMConversation> conversations = EMChatManager .getInstance().getAllConversations(); List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>(); synchronized (conversations) { for (EMConversation conversation : conversations.values()) { if (conversation.getAllMessages().size() != 0) { sortList.add(new Pair<Long, EMConversation>(conversation .getLastMessage().getMsgTime(), conversation)); } } } List<EMConversation> list = new ArrayList<EMConversation>(); for (Pair<Long, EMConversation> sortItem : sortList) { list.add(sortItem.second); } return list; } /** * 删除联系人 * * @param toDeleteUser */ public void deleteContact(final User tobeDeleteUser) { String st1 = getResources().getString(R.string.deleting); final String st2 = getResources().getString(R.string.Delete_failed); final MyProgressDialog pd = MyProgressDialog .createProgressDialog(mContext); if (pd != null) { pd.setMessage(st1); pd.setCanceledOnTouchOutside(false); pd.show(); } new Thread(new Runnable() { public void run() { try { EMContactManager.getInstance().deleteContact( tobeDeleteUser.getUsername()); // 删除db和内存中此用户的数据 UserDao dao = new UserDao(getActivity()); dao.deleteContact(tobeDeleteUser.getUsername()); MyApplication.getInstance().getContactList() .remove(tobeDeleteUser.getUsername()); getActivity().runOnUiThread(new Runnable() { public void run() { if (pd != null) pd.dismiss(); } }); } catch (final Exception e) { getActivity().runOnUiThread(new Runnable() { public void run() { if (pd != null) pd.dismiss(); Toast.makeText(getActivity(), st2, 1).show(); } }); } } }).start(); } }
package com.legaoyi.protocol.messagebody.encoder; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import com.legaoyi.protocol.down.messagebody.JTT1078_9205_MessageBody; import com.legaoyi.protocol.exception.IllegalMessageException; import com.legaoyi.protocol.message.MessageBody; import com.legaoyi.protocol.message.encoder.MessageBodyEncoder; import com.legaoyi.protocol.util.ByteUtils; import com.legaoyi.protocol.util.DateUtils; import com.legaoyi.protocol.util.MessageBuilder; /** * * @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a> * @version 1.0.0 * @since 2018-04-09 */ @Component(MessageBodyEncoder.MESSAGE_BODY_ENCODER_BEAN_PREFIX + "9205_2016" + MessageBodyEncoder.MESSAGE_BODY_ENCODER_BEAN_SUFFIX) public class JTT1078_9205_MessageBodyEncoder implements MessageBodyEncoder { @Override public byte[] encode(MessageBody message) throws IllegalMessageException { try { JTT1078_9205_MessageBody messageBody = (JTT1078_9205_MessageBody) message; MessageBuilder mb = new MessageBuilder(); mb.addByte(messageBody.getChannelId()); String startTime = messageBody.getStartTime(); if (startTime == null || "".equals(startTime)) { startTime = "000000000000"; } else { startTime = DateUtils.dateTime2bcd(startTime); } mb.append(ByteUtils.bcd2bytes(startTime, 6)); String endTime = messageBody.getEndTime(); if (endTime == null || "".equals(endTime)) { endTime = "000000000000"; } else { endTime = DateUtils.dateTime2bcd(endTime); } mb.append(ByteUtils.bcd2bytes(endTime, 6)); String alarmFlag = messageBody.getAlarmFlag(); alarmFlag = StringUtils.reverse(alarmFlag); for (int i = 0; i < 4; i++) { String bitStr = alarmFlag.substring(i * 16, (i + 1) * 16); mb.addWord(ByteUtils.bin2int(bitStr)); } mb.addByte(messageBody.getResourceType()); mb.addByte(messageBody.getStreamType()); mb.addByte(messageBody.getStoreType()); return mb.getBytes(); } catch (Exception e) { throw new IllegalMessageException(e); } } }
package de.uulm.in.vs.grn.a2; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.util.Scanner; public class URLFetcher { public static void main(String[] args) { System.out.println("___________________________________________"); System.out.println("-- HTTPS only - HTTP-URLs werden angepasst --"); System.out.println("Akzeptierte Eingaben:"); System.out.println("https://www.example.domain"); System.out.println("http://www.example.domain"); System.out.println("www.example.domain"); System.out.println("example.domain"); System.out.println("___________________________________________\n"); while(true) { System.out.println("\nURL eingeben:"); Scanner sc = new Scanner(System.in); String adress = sc.nextLine(); // ADRESSE FORMATIEREN adress = formate(adress); //System.out.println(formate(adress)); URL url; InputStream is = null; BufferedReader br; String line; try { url = new URL(adress); is = url.openStream(); // throws an IOException br = new BufferedReader(new InputStreamReader(is)); String response = ""; while ((line = br.readLine()) != null) { response += line; } // GENERATE FILE NAME String [] arr = adress.split("\\."); String filename = arr[1] + ".html"; if(response != null && !response.trim().equals("")) { // GENERATE FILE File file = new File(filename); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(response); writer.close(); System.out.println("Download completed!"); } else { System.out.println("Response Error"); } } catch (MalformedURLException mue) { System.out.println("Ungültige URL"); } catch (IOException ioe) { System.out.println("Ungültige URL"); } finally { try { if (is != null) is.close(); } catch (IOException ioe) { // nothing to see here } } } } public static String formate(String adress) { String result = ""; String [] arr = adress.split("\\."); if(!adress.contains("www")){ result = "https://www"; for(int i =0; i<arr.length; i++) { result += "." + arr[i]; } } else { arr[0] = "https://www"; for(int i =0; i<arr.length; i++) { result += arr[i] + "."; } result = result.substring(0,result.length()-1); } return result; } }
/* * 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 lk.vcnet.storemodule.controller; import java.rmi.Remote; import me.colhh.usermanager.rmi.first.controller.UserControllerInterface; /** * * @author Lahiru Udana <lahirukaka@gmail.com> */ public interface ControllerAccessorInterface extends Remote { public UserControllerInterface getDBAdapter() throws Exception; }
import java.io.*; public class main { public static void main(String [] args){ System.out.println("miau"); } }
package Admin; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.*; import javax.swing.border.TitledBorder; public class User extends javax.swing.JFrame{ private Connection con=null; private Statement s=null; private JTextField userid= new JTextField(); private JTextField password= new JTextField(); private JButton login= new JButton("LOGIN"); public static String userID; public User(){ init();} public User(Connection c) { init(); try{ Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/libdb", "root","Albert1792"); s = con.createStatement(); }catch(Exception e){ System.err.println("ERROR: "+e); }} private void init() { userid.setHorizontalAlignment(JTextField.LEFT);// Set inputs alignments password.setHorizontalAlignment(JTextField.LEFT); JPanel p1=new JPanel(new GridLayout(1,1,0,0)); //Creating a panel for GUI p1.add(new JLabel("READER ID")); p1.add(userid); p1.add(new JLabel("PASSWORD")); p1.add(password); p1.setBorder(new TitledBorder("READER LOGIN")); add(p1,BorderLayout.NORTH); setSize(400,300); JPanel p2= new JPanel(new FlowLayout(FlowLayout.CENTER)); p2.add(login); add(p2,BorderLayout.CENTER); login.addActionListener(new ButtonListener()); } private class ButtonListener implements ActionListener{ public void actionPerformed(ActionEvent e){ if(e.getActionCommand().equals("LOGIN")){ userID = userid.getText(); String pwd = password.getText(); String query = "select password from reader where readerid = '"+userID+"'"; try { ResultSet r = s.executeQuery(query); if(r == null){ System.out.print("off"); } if(r.next() == false){ JOptionPane op = new JOptionPane(); op.setMessage("The user "+userID+" doesn't exist "); op.setMessageType(0); JDialog dia = op.createDialog(null,"Error"); dia.setTitle("LOGIN ERROR"); dia.setVisible(true); } else{ if(r.getString("password").equals(pwd)){ dispose(); UserMenu uMenu = new UserMenu(); uMenu.setVisible(true);; }else{ JOptionPane op = new JOptionPane(); op.setMessage("The password for "+userID+" user is different "); op.setMessageType(0); JDialog dia = op.createDialog(null,"Error"); dia.setTitle("LOGIN ERROR"); dia.setVisible(true); } } } catch (SQLException ex) { Logger.getLogger(Admin.class.getName()).log(Level.SEVERE, null, ex); } } } } }
package com.cts.controller; import java.util.*; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.cts.dao.Person; import com.google.gson.Gson; @RestController public class CountryController { @RequestMapping(value="/person", method = RequestMethod.GET) public String getAllDetails(){ Person person = new Person(); Person person1 = new Person(); List<Person> personList = new ArrayList<Person>(); person.setFirstName("Souvik"); person.setLastName("Sen"); //person.setRoles(Arrays.asList("Application Lead", "Sr. Developer")); person1.setFirstName("Raju"); person1.setLastName("Bibar"); //person1.setRoles(Arrays.asList("Team Member", "Developer")); personList.add(person); personList.add(person1); Gson gson = new Gson(); String json = gson.toJson(personList); return json; } }
package com.shilong.jysgl.service.impl; import java.util.List; import javax.annotation.Resource; import com.shilong.jysgl.dao.culture.mapper.CouGrMapper; import com.shilong.jysgl.dao.culture.mapper.CoursegroupMapper; import com.shilong.jysgl.dao.culture.mapper.TeaGrMapper; import com.shilong.jysgl.dao.custom.mapper.CoursegroupMapperCustom; import com.shilong.jysgl.pojo.po.CouGr; import com.shilong.jysgl.pojo.po.CouGrExample; import com.shilong.jysgl.pojo.po.Course; import com.shilong.jysgl.pojo.po.Coursegroup; import com.shilong.jysgl.pojo.po.TeaGrExample; import com.shilong.jysgl.pojo.po.TeaGrExample.Criteria; import com.shilong.jysgl.pojo.po.TeaGrKey; import com.shilong.jysgl.pojo.po.Teacher; import com.shilong.jysgl.pojo.vo.CourseCustom; import com.shilong.jysgl.pojo.vo.CourseGroupCustom; import com.shilong.jysgl.pojo.vo.CourseGroupQueryVo; import com.shilong.jysgl.pojo.vo.TeacherCustom; import com.shilong.jysgl.process.context.Config; import com.shilong.jysgl.process.result.ResultUtil; import com.shilong.jysgl.service.CourseGroupService; import com.shilong.jysgl.utils.UUIDBuild; /** * @Descriptrion : * @author mr-li * @Company www.shilong.com * @CreateDate 2015年12月16日 */ public class CourseGroupServiceImpl implements CourseGroupService { @Resource private CoursegroupMapper courseGroupMapper; @Resource private CoursegroupMapperCustom courseGroupMapperCustom; @Resource private CouGrMapper couGrMapper; @Resource private TeaGrMapper teaGrMapper; @Override public void insertCourseGroup(CourseGroupQueryVo courseGroupQueryVo) throws Exception { if(courseGroupQueryVo==null||courseGroupQueryVo.getCourseGroupCustom()==null){ ResultUtil.throwExcepion(ResultUtil.createFail(Config.MESSAGE, 901, null)); } CourseGroupCustom groupCustom = courseGroupQueryVo.getCourseGroupCustom(); String kczmc = groupCustom.getKczmc(); if(kczmc==null || kczmc.equals("")){ ResultUtil.throwExcepion(ResultUtil.createFail(Config.MESSAGE, 901, null)); } Coursegroup cg=new Coursegroup(); cg.setCgid(UUIDBuild.getUUID()); cg.setKczmc(kczmc); courseGroupMapper.insert(cg); } @Override public void updateCourseGroup(String id, CourseGroupQueryVo courseGroupQueryVo) throws Exception { if(courseGroupQueryVo==null ||// courseGroupQueryVo.getCourseGroupCustom()==null ||// courseGroupQueryVo.getCourseGroupCustom().getKczmc()==null||// courseGroupQueryVo.getCourseGroupCustom().getKczmc().equals("")){// ResultUtil.throwExcepion(ResultUtil.createFail(Config.MESSAGE, 901, null)); } Coursegroup coursegroup = courseGroupMapper.selectByPrimaryKey(id); if(coursegroup==null){ ResultUtil.throwExcepion(ResultUtil.createFail(Config.MESSAGE, 901, null)); } coursegroup.setKczmc(courseGroupQueryVo.getCourseGroupCustom().getKczmc()); courseGroupMapper.updateByPrimaryKey(coursegroup); } @Override public Coursegroup getCourseGroupById(String cgid) throws Exception { return courseGroupMapper.selectByPrimaryKey(cgid); } @Override public void deleteCourseGroupById(String cgid) throws Exception { courseGroupMapper.deleteByPrimaryKey(cgid); } @Override public List<CourseGroupCustom> findCourseGroupList(CourseGroupQueryVo courseGroupQueryVo) throws Exception { List<CourseGroupCustom> list = courseGroupMapperCustom.findCourseGroupList(courseGroupQueryVo); return list; } @Override public int findCourseGroupCount(CourseGroupQueryVo courseGroupQueryVo) throws Exception { int count = courseGroupMapperCustom.findCourseGroupCount(courseGroupQueryVo); return count; } @Override public List<Teacher> findCgteasById(String cgid,String eq,CourseGroupQueryVo courseGroupQueryVo) throws Exception { courseGroupQueryVo=courseGroupQueryVo!=null ? courseGroupQueryVo:new CourseGroupQueryVo(); CourseGroupCustom courseGroupCustom = courseGroupQueryVo.getCourseGroupCustom(); if(courseGroupCustom==null){ courseGroupCustom=new CourseGroupCustom(); } courseGroupCustom.setCgid(cgid); courseGroupCustom.setEqCgid(eq); courseGroupQueryVo.setCourseGroupCustom(courseGroupCustom); List<Teacher> list = courseGroupMapperCustom.findCgteasById(courseGroupQueryVo); return list; } @Override public int findCgteasCountById(String cgid,String eq, CourseGroupQueryVo courseGroupQueryVo) throws Exception { courseGroupQueryVo=courseGroupQueryVo!=null ? courseGroupQueryVo:new CourseGroupQueryVo(); CourseGroupCustom courseGroupCustom = courseGroupQueryVo.getCourseGroupCustom(); if(courseGroupCustom==null){ courseGroupCustom=new CourseGroupCustom(); } courseGroupCustom.setCgid(cgid); courseGroupCustom.setEqCgid(eq); courseGroupQueryVo.setCourseGroupCustom(courseGroupCustom); int count = courseGroupMapperCustom.findCgteasCountById(courseGroupQueryVo); return count; } @Override public List<Course> findCgcousById(String cgid,String eq,CourseGroupQueryVo courseGroupQueryVo) throws Exception { courseGroupQueryVo=courseGroupQueryVo!=null ? courseGroupQueryVo:new CourseGroupQueryVo(); CourseGroupCustom courseGroupCustom = courseGroupQueryVo.getCourseGroupCustom(); if(courseGroupCustom==null){ courseGroupCustom=new CourseGroupCustom(); } courseGroupCustom.setCgid(cgid); courseGroupCustom.setEqCgid(eq); courseGroupQueryVo.setCourseGroupCustom(courseGroupCustom); List<Course> list = courseGroupMapperCustom.findCgcousById(courseGroupQueryVo); return list; } @Override public int findCgcousCountById(String cgid,String eq, CourseGroupQueryVo courseGroupQueryVo) throws Exception { courseGroupQueryVo=courseGroupQueryVo!=null ? courseGroupQueryVo:new CourseGroupQueryVo(); CourseGroupCustom courseGroupCustom = courseGroupQueryVo.getCourseGroupCustom(); if(courseGroupCustom==null){ courseGroupCustom=new CourseGroupCustom(); } courseGroupCustom.setCgid(cgid); courseGroupCustom.setEqCgid(eq); courseGroupQueryVo.setCourseGroupCustom(courseGroupCustom); int count = courseGroupMapperCustom.findCgcousCountById(courseGroupQueryVo); return count; } @Override public void addCgcou(String cgid, String cid) throws Exception { CouGr gr = new CouGr(); gr.setCgid(cgid); gr.setCid(cid); couGrMapper.insert(gr); } @Override public void addCgtea(String cgid, String teaid) throws Exception { TeaGrKey tg=new TeaGrKey(); tg.setCgid(cgid); tg.setTeaid(teaid); teaGrMapper.insert(tg); } @Override public void delCgcou(String cgid, String cid) throws Exception { CouGrExample gr = new CouGrExample(); CouGrExample.Criteria grc=gr.createCriteria(); grc.andCgidEqualTo(cgid); grc.andCidEqualTo(cid); couGrMapper.deleteByExample(gr); } @Override public void delCgtea(String cgid, String teaid) throws Exception { TeaGrExample tg=new TeaGrExample(); TeaGrExample.Criteria tgc = tg.createCriteria(); tgc.andCgidEqualTo(cgid); tgc.andTeaidEqualTo(teaid); teaGrMapper.deleteByExample(tg); } }
package com.karya.dao; import java.util.List; import com.karya.model.AccountsReceivable001MB; public interface IAccountsReceivableDAO { public List<AccountsReceivable001MB> accountsreceivable(); public void addaccountsreceivable(AccountsReceivable001MB accountsreceivable); public AccountsReceivable001MB getAccountsReceivable(int id); public void deleteaccountsreceivable(int id); }
package controller; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXComboBox; import com.jfoenix.controls.JFXListView; import com.jfoenix.controls.JFXTextField; import db.DBConnection; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.TextField; import javafx.scene.input.KeyEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import java.io.IOException; import java.sql.*; import java.util.Arrays; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ManageQuarantineCentersController { public AnchorPane root; public TextField txtSearch; public JFXListView<String> lstCenters; public JFXComboBox<String> cmbDistricts; public JFXButton btnHome; public JFXButton btnNewCenter; public JFXButton btnSave; public JFXButton btnDelete; public JFXTextField txtId; public JFXTextField txtName; public JFXTextField txtCity; public JFXTextField txtHead; public JFXTextField txtHeadContactNo; public JFXTextField txtQuarantineCenterContactNo1; public JFXTextField txtQuarantineCenterContactNo2; public JFXTextField txtCapacity; public void initialize() { loadAllQuarantineCenters(); String districtsText = " Colombo\n" + " Gampaha\n" + " Kalutara\n" + " Kandy\n" + " Matale\n" + " Nuwara Eliya\n" + " Galle\n" + " Matara\n" + " Hambantota\n" + " Jaffna\n" + " Mannar\n" + " Vauniya\n" + " Mullativue\n" + " Ampara\n" + " Trincomalee\n" + " Batticaloa\n" + " Kilinochchi\n" + " Kurunegala\n" + " Puttalam\n" + " Anuradhapura\n" + " Polonnaruwa\n" + " Badulla\n" + " Moneragala\n" + " Ratnapura\n" + " Kegalle"; String[] districts = districtsText.split("\n"); ObservableList<String> olDistricts = FXCollections.observableArrayList(Arrays.asList(districts)); cmbDistricts.setItems(olDistricts); lstCenters.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if(lstCenters.getSelectionModel().getSelectedItems().isEmpty()){ return; } String name = lstCenters.getSelectionModel().getSelectedItem().toString(); Connection connection = DBConnection.getInstance().getConnection(); try { PreparedStatement pstm = connection.prepareStatement("SELECT * FROM quarantinecenter WHERE name =?"); pstm.setObject(1,name); ResultSet rst = pstm.executeQuery(); if(rst.next()){ txtId.setText(rst.getString(1)); txtName.setText(rst.getString(2)); txtCity.setText(rst.getString(3)); cmbDistricts.getSelectionModel().select(rst.getString(4)); txtHead.setText(rst.getString(5)); txtHeadContactNo.setText(rst.getString(6)); txtQuarantineCenterContactNo1.setText(rst.getString(7)); txtQuarantineCenterContactNo2.setText(rst.getString(8)); txtCapacity.setText(rst.getString(9)); btnSave.setText("Update"); btnSave.setDisable(false); btnDelete.setDisable(false); txtName.requestFocus(); } } catch (SQLException throwables) { throwables.printStackTrace(); } } }); } private void loadAllQuarantineCenters() { try { ObservableList centers = lstCenters.getItems(); centers.clear(); Statement stm = DBConnection.getInstance().getConnection().createStatement(); ResultSet rst = stm.executeQuery("SELECT name FROM quarantinecenter"); while (rst.next()){ centers.add(rst.getString(1)); } lstCenters.refresh(); } catch (SQLException e) { e.printStackTrace(); } } public void txtSearchOnKeyReleased(KeyEvent keyEvent) { String cname = txtSearch.getText(); ObservableList items = lstCenters.getItems(); items.clear(); Connection connection = DBConnection.getInstance().getConnection(); try { Statement stm = connection.createStatement(); ResultSet resultSet = stm.executeQuery("SELECT name FROM quarantinecenter WHERE name LIKE '%" + cname + "%'"); while(resultSet.next()){ items.add(resultSet.getString(1)); } lstCenters.refresh(); } catch (SQLException e) { e.printStackTrace(); } } public void btnHome_OnAction(ActionEvent actionEvent) throws IOException { Scene mainScene = new Scene(FXMLLoader.load(this.getClass().getResource("/view/Dashboard.fxml"))); Stage primaryStage = (Stage) (cmbDistricts.getScene().getWindow()); primaryStage.setScene(mainScene); primaryStage.centerOnScreen(); primaryStage.sizeToScene(); } public void btnNewCenter_OnAction(ActionEvent event) { txtId.clear(); txtName.clear(); txtCity.clear(); cmbDistricts.getSelectionModel().clearSelection(); txtHead.clear(); txtHeadContactNo.clear(); txtQuarantineCenterContactNo1.clear(); txtQuarantineCenterContactNo2.clear(); txtCapacity.clear(); txtId.setDisable(false); txtName.setDisable(false); txtCity.setDisable(false); cmbDistricts.setDisable(false); txtHead.setDisable(false); txtHeadContactNo.setDisable(false); txtQuarantineCenterContactNo1.setDisable(false); txtQuarantineCenterContactNo2.setDisable(false); txtCapacity.setDisable(false); txtName.requestFocus(); btnSave.setDisable(false); // Generate a new id int maxId = 0; try { Statement stm = DBConnection.getInstance().getConnection().createStatement(); ResultSet rst = stm.executeQuery("SELECT quarantineCenterID FROM quarantinecenter ORDER BY quarantineCenterID DESC LIMIT 1"); if (rst.next()) { maxId = Integer.parseInt(rst.getString(1).replace("C", "")); } } catch (SQLException e) { e.printStackTrace(); } maxId = maxId + 1; String id = ""; if (maxId < 10) { id = "C00" + maxId; } else if (maxId < 100) { id = "C0" + maxId; } else { id = "C" + maxId; } txtId.setText(id); } public void btnSave_OnAction(ActionEvent event) { if (txtId.getText().isEmpty() || txtName.getText().isEmpty() || txtCity.getText().isEmpty() || txtHead.getText().isEmpty() || txtHeadContactNo.getText().isEmpty() || txtQuarantineCenterContactNo1.getText().isEmpty() || txtQuarantineCenterContactNo2.getText().isEmpty() || txtCapacity.getText().isEmpty()){ new Alert(Alert.AlertType.ERROR,"Please Make Sure To Fill All The Fields").show(); return; } if (btnSave.getText().equalsIgnoreCase("Save")){ String regex = "\\d{3}[-]\\d{7}"; Pattern pattern = Pattern.compile(regex); String dCon = txtHeadContactNo.getText(); Matcher matcher = pattern.matcher(dCon); if (!matcher.matches()){ new Alert(Alert.AlertType.ERROR,"You are entered Head Contact Number is wrong, Please re enter!").show(); return; } if (!Pattern.matches("\\d{3}[-]\\d{7}", txtQuarantineCenterContactNo1.getText())){ new Alert(Alert.AlertType.ERROR,"You are entered QuarantineCenter Contact Number 1 is wrong, Please re enter!").show(); return; } if (!Pattern.matches("\\d{3}[-]\\d{7}", txtQuarantineCenterContactNo2.getText())){ new Alert(Alert.AlertType.ERROR,"You are entered QuarantineCenter Contact Number 2 is wrong, Please re enter!").show(); return; } try { PreparedStatement pstm = DBConnection.getInstance().getConnection().prepareStatement("INSERT INTO quarantinecenter VALUES (?,?,?,?,?,?,?,?,?)"); pstm.setString(1, txtId.getText()); pstm.setString(2, txtName.getText()); pstm.setString(3, txtCity.getText()); pstm.setString(4, cmbDistricts.getValue()); pstm.setString(5, txtHead.getText()); pstm.setString(6, txtHeadContactNo.getText()); pstm.setString(7, txtQuarantineCenterContactNo1.getText()); pstm.setString(8, txtQuarantineCenterContactNo2.getText()); pstm.setString(9, txtCapacity.getText()); int affectedRows = pstm.executeUpdate(); if (affectedRows <= 0){ new Alert(Alert.AlertType.ERROR,"Record cannot be added!", ButtonType.OK).show(); } else { new Alert(Alert.AlertType.INFORMATION,"Record added successfully", ButtonType.OK).show(); lstCenters.getItems().clear(); loadAllQuarantineCenters(); } } catch (SQLException e) { e.printStackTrace(); } } else { try { PreparedStatement pstm = DBConnection.getInstance().getConnection().prepareStatement("UPDATE quarantinecenter SET name=?, city=?, district=?, head=?, headContactNo=?, centerContactNo1=?, centerContactNo2=?, capacity=? WHERE quarantineCenterID=?"); pstm.setString(1, txtName.getText()); pstm.setString(2, txtCity.getText()); pstm.setString(3, cmbDistricts.getValue()); pstm.setString(4, txtHead.getText()); pstm.setString(5, txtHeadContactNo.getText()); pstm.setString(6, txtQuarantineCenterContactNo1.getText()); pstm.setString(7, txtQuarantineCenterContactNo2.getText()); pstm.setString(8, txtCapacity.getText()); pstm.setString(9, txtId.getText()); int affectedRows = pstm.executeUpdate(); if (affectedRows <= 0){ new Alert(Alert.AlertType.ERROR,"Record cannot be updated!", ButtonType.OK).show(); } else { new Alert(Alert.AlertType.INFORMATION,"Record updated successfully", ButtonType.OK).show(); lstCenters.getItems().clear(); loadAllQuarantineCenters(); } } catch (SQLException e) { e.printStackTrace(); } } reset(); } public void reset(){ btnDelete.setDisable(true); btnSave.setText("Save"); txtId.setText(""); txtName.setText(""); txtCity.setText(""); cmbDistricts.setValue(null); txtHead.setText(""); txtHeadContactNo.setText(""); txtQuarantineCenterContactNo1.setText(""); txtQuarantineCenterContactNo2.setText(""); txtCapacity.setText(""); txtId.setPromptText("Quarantine Center ID"); txtName.setPromptText("Quarantine Center Name"); txtCity.setPromptText("City"); txtHead.setPromptText("Head"); txtHeadContactNo.setPromptText("Head Contact No"); txtQuarantineCenterContactNo1.setPromptText("Quarantine Center Contact No1"); txtQuarantineCenterContactNo2.setPromptText("Quarantine Center Contact No2"); txtCapacity.setPromptText("Capacity"); } public void btnDelete_OnAction(ActionEvent event) throws SQLException { PreparedStatement pstm = DBConnection.getInstance().getConnection().prepareStatement("DELETE FROM quarantinecenter WHERE quarantineCenterID = ?"); pstm.setString(1, txtId.getText()); Optional<ButtonType> alert = new Alert(Alert.AlertType.CONFIRMATION, "Are you sure whether you want to delete this QuarantineCenter?", ButtonType.YES, ButtonType.NO).showAndWait(); if (alert.get().equals(ButtonType.YES)) { try { pstm.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } clearAll(); btnSave.setText("Save"); btnDelete.setDisable(true); btnSave.setDisable(true); btnNewCenter.requestFocus(); loadAllQuarantineCenters(); } } private void clearAll() { txtId.clear(); txtName.clear(); txtCity.clear(); cmbDistricts.getSelectionModel().clearSelection(); txtHead.clear(); txtHeadContactNo.clear(); txtQuarantineCenterContactNo1.clear(); txtQuarantineCenterContactNo2.clear(); txtCapacity.clear(); txtSearch.clear(); } }
package pl.edu.pw.mini.taio.omino.lib.solvers; import pl.edu.pw.mini.taio.omino.core.Block; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class OptimalRectangle extends RectangleSolver { public OptimalRectangle(Block[] blocks) { super(blocks); } @Override public Block[][] solve() { cuts = 0; Block[][] solution = prepareBoard(); if(solution == null || solution.length == 0) return solution; while (true) { int[] cutsDistribution = new int[blocks.length]; if (solveRec(cutsDistribution, 0, cuts, solution)) return solution; if(Thread.interrupted()) return null; cuts++; } } private boolean solveRec(int[] cutsDistribution, int level, int cuts, Block[][] solution) { if (cuts == 0) { return solveRecRec(new ArrayList<>(), 0, cutsDistribution, solution); } if (level >= cutsDistribution.length) return false; for (int i = 0; i <= cuts; i++) { cutsDistribution[level] += i; if (solveRec(cutsDistribution, level + 1, cuts - i, solution)) return true; cutsDistribution[level] -= i; } return false; } private boolean solveRecRec(List<Block> blockList, int level, int[] cutsDistribution, Block[][] solution) { if (level == cutsDistribution.length) { return solveRecRecRec(solution, blockList, 0); } var combinations = blocks[level].getCutBlocks(cutsDistribution[level]); if (combinations == null) return false; for (Collection<Block> combination : combinations) { blockList.addAll(combination); if (solveRecRec(blockList, level + 1, cutsDistribution, solution)) return true; blockList.subList(blockList.size()-combination.size(), blockList.size()).clear(); } return false; } private boolean solveRecRecRec(Block[][] solution, List<Block> blockList, int level) { if (level == blockList.size()) { return true; } for (Block rotation : blockList.get(level).getRotations()) { for (int i = 0; i < solution.length - rotation.getWidth() + 1; i++) { for (int j = 0; j < solution[0].length - rotation.getHeight() + 1; j++) { if(Thread.currentThread().isInterrupted()) return false; if (!available(solution, rotation, i, j)) continue; insert(solution, rotation, i, j); if (solveRecRecRec(solution, blockList, level + 1)) return true; erase(solution, rotation, i, j); } } } return false; } }
package com.example.currencyconverter; import android.support.annotation.DrawableRes; 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.ImageView; import android.widget.TextView; public class MainActivity extends AppCompatActivity { EditText value; Button btn; ImageView img; TextView txt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); value = findViewById(R.id.dollar_value); btn = findViewById(R.id.convert_btn); img = findViewById(R.id.currency_image); txt = findViewById(R.id.text_display); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { double dollarValue = Double.parseDouble(value.getText().toString()); double inrValue = dollarValue * 6937; inrValue=Math.round(inrValue)/100.0; txt.setText("Rs." + inrValue); img.setImageResource(R.drawable.rupees); } }); } }
package org.techstuff.auth.data; import org.apache.log4j.Logger; import org.springframework.jdbc.core.RowMapper; import java.sql.ResultSet; import java.sql.SQLException; /** * Created by andersonkmi on 1/1/2017. */ public class RestrictedWordRowMapper implements RowMapper<RestrictedWord> { private static final Logger logger = Logger.getLogger(RestrictedWordRowMapper.class); @Override public RestrictedWord mapRow(ResultSet resultSet, int i) throws SQLException { logger.info(String.format("Processing row number = %d", i)); RestrictedWord restrictedWord = new RestrictedWord(); restrictedWord.setId(resultSet.getInt("id")); restrictedWord.setWord(resultSet.getString("word")); return restrictedWord; } }
package com.youthlin.example.rpc.consumer.async; import com.youthlin.rpc.core.ProxyFactory; import com.youthlin.rpc.core.SimpleProxyFactory; import com.youthlin.rpc.core.config.AbstractConsumerConfig; import com.youthlin.rpc.core.config.Config; import com.youthlin.rpc.util.NetUtil; import java.lang.reflect.Method; /** * 创建: youthlin.chen * 时间: 2017-11-27 11:19 */ public class AsyncConfig extends AbstractConsumerConfig { @Override public String host() { String host = System.getProperty("provider.host"); if (host != null && !host.isEmpty()) { return host; } return NetUtil.getLocalAddress().getHostAddress(); } @Override public int port() { return NetUtil.DEFAULT_PORT; } @Override public Class<? extends ProxyFactory> proxy() { return SimpleProxyFactory.class; } @Override public Boolean async(Method method) { if (method.getName().equals("findAll")) { return true; } return super.async(method); } @Override public Boolean getConfig(Method method, String key, boolean dft) { if (method.getName().equals("aLongTimeMethod") && key.equals(AsyncConfig.RETURN)) { return false; } return super.getConfig(method, key, dft); } @SuppressWarnings("unchecked") @Override public <T> T getConfig(Method method, String key, T dft) { int length = method.getParameterTypes().length; if (method.getName().equals("async")) { if (key.equals(Config.CALLBACK)) { boolean[] ret = new boolean[length]; ret[0] = true; return (T) ret; } } return null; } }
package com.example.kuno.intentobject; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; /** * Created by kuno on 2017-02-01. */ public class SecondActivity extends Activity { TextView tvView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); tvView = (TextView) findViewById(R.id.tvView); Intent intent = getIntent(); if(intent == null){ tvView.setText("데이터가 없습니다."); }else{ String strText = ""; DataSerial obj = null; obj = (DataSerial)intent.getSerializableExtra("ObjectData"); strText = "type: " + intent.getStringExtra("ObjectType") + "\n" + "name: " + obj.name + "\n" + "age: " + obj.age + "\n" + "address: " + obj.address + "\n"; tvView.setText(strText); } } }
package com.loading.graphqldemo.graphql; import com.loading.graphqldemo.entity.CompanyEntity; import com.loading.graphqldemo.entity.PersonEntity; import com.loading.graphqldemo.service.CompanyService; import graphql.kickstart.execution.context.GraphQLContext; import graphql.kickstart.tools.GraphQLResolver; import graphql.schema.DataFetchingEnvironment; import java.util.List; import java.util.concurrent.CompletableFuture; import org.dataloader.DataLoader; import org.dataloader.DataLoaderRegistry; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * desc: * * @author Lo_ading * @version 1.0.0 * @date 2021/9/14 */ @Component public class CompanyResolver implements GraphQLResolver<CompanyEntity> { @Autowired private CompanyService companyService; public CompletableFuture<List<PersonEntity>> persons(CompanyEntity company, DataFetchingEnvironment environment) { DataLoaderRegistry registry = ((GraphQLContext) environment.getContext()) .getDataLoaderRegistry(); DataLoader<String, List<PersonEntity>> dataLoader = registry.getDataLoader("personCompanyIdLoader"); if (dataLoader != null) { return dataLoader.load(company.getId()); } throw new IllegalStateException("No customer data loader found"); } public List<CompanyEntity> partners(CompanyEntity company, DataFetchingEnvironment environment) { String[] partnerIds = company.getPartnerCompanyIds().split("\\|"); return companyService.findByIds(partnerIds); } }
package com.example.canalu.ui.exit; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import com.example.canalu.R; import com.example.canalu.ui.main.MainActivity; public class ExitFragment extends Fragment { private ExitViewModel exitViewModel; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { exitViewModel = ViewModelProviders.of(this).get(ExitViewModel.class); View root = inflater.inflate(R.layout.fragment_exit, container, false); final TextView textView = root.findViewById(R.id.text_exit); exitViewModel.getText().observe(this, new Observer<String>() { @Override public void onChanged(@Nullable String s) { textView.setText(s); } }); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext()); alertDialogBuilder.setTitle("Confirmar"); alertDialogBuilder .setMessage("Realmente desea salir de la aplicación?") .setCancelable(false) .setPositiveButton("Si",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { //Intent i = new Intent(getContext(), MainActivity.class); //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); //startActivity(i); System.exit(0); } }) .setNegativeButton("No",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.cancel(); Intent i = new Intent(getContext(), MainActivity.class); startActivity(i); } }).create().show(); return root; } }
package bis.project.validators; import bis.project.security.User; public class UserValidator { public static void Validate(User user) throws ValidationException{ ValidationException.ThrowIfNullOrEmpty(user.getFirstName(),"First name"); ValidationException.ThrowIfNullOrEmpty(user.getLastName(),"Last name"); ValidationException.ThrowIfNullOrEmpty(user.getPassword(),"Password"); ValidationException.ThrowIfNullOrEmpty(user.getEmail(),"Email"); ValidationException.ThrowIfLengthGratherThan(80, user.getFirstName(), "First name"); ValidationException.ThrowIfLengthGratherThan(80, user.getLastName(), "Last name"); ValidationException.ThrowIfLengthGratherThan(120, user.getEmail(), "Email"); ValidationException.ThrowIfLengthGratherThan(20, user.getEmail(), "Password"); } }
package DuckHunt.GameObjects.Ducks; import DuckHunt.Constant.MoveType; import DuckHunt.Global.GameGlobalVariables; import DuckHunt.Main.Game; import DuckHunt.Request.Move; import javafx.animation.*; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.effect.Glow; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.util.Duration; import java.awt.*; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Date; public abstract class NewDuck { private Image image[]; private ImageView imageView; private int number; // A number to recognise the duck useful in multi player game private int hitPoints; // Health of the duck private boolean isBoss; // True if the bird is a boss private double speed; // pixel per sec private boolean isAlive; // Tell if the Duck is Alive private long entryDate; // Entry Date private long score; // Score Awarded private double speedIncrement; // Increment in the speed based on level private int level; // Level of the bird private SequentialTransition sequentialTransition; private TranslateTransition endTransition; private int[] property = new int[3]; private Color color; // private int randomability; // frames // private int leavetime; // frames private String bio; // About me of the Duck private String picLocation; // Pic Location of the Duck private String menuPicLocation; // Pic Location of the Duck private String name; // Name of the Duck // Duck properties stars count for almanac public NewDuck(String name,double[] X,double[] Y,int numberOfTrips,double speed,int hitpoints,boolean isBoss,long score, int speedIncrement,int level,int number ){ this.number = number; this.entryDate = new Date().getTime(); this.speedIncrement = speedIncrement; this.level = level; this.score = score; this.isBoss = isBoss; this.isAlive = true; this.name = name; this.hitPoints = hitpoints; this.speed = speed; this.image = new Image[hitpoints+1]; for (int i = 0; i < hitpoints+1; i++) { try { image[i] = new Image(new FileInputStream("assets/image/duck/"+name+"/"+i+".png")); } catch (FileNotFoundException e) { e.printStackTrace(); } } imageView = new ImageView(image[hitpoints]); imageView.setX(X[0]); imageView.setY(Y[0]); imageView.setFitHeight(GameGlobalVariables.getInstance().getObjectSize()); imageView.setFitWidth(GameGlobalVariables.getInstance().getObjectSize()); sequentialTransition = new SequentialTransition(this.imageView); TranslateTransition[] translateTransition = new TranslateTransition[numberOfTrips]; RotateTransition[] rotateTransitions = new RotateTransition[numberOfTrips]; imageView.setOpacity(0); FadeTransition fadeTransition = new FadeTransition(Duration.millis(20)); fadeTransition.setFromValue(0); fadeTransition.setToValue(1); sequentialTransition.getChildren().addAll(new PauseTransition(Duration.millis(3000)),fadeTransition); double distance,time,newAngle,rotateBy,tmp1,tmp2,tmp3,angle=0; for (int i = 0; i < numberOfTrips; i++) { distance = Math.sqrt(Math.pow(X[i+1]-X[i],2)+Math.pow(Y[i+1]-Y[i],2)); time = (distance*1000)/speed; newAngle = Math.acos(Math.abs(X[i+1]-X[i])/distance)*(180.0/Math.PI); if (X[i+1]>=X[i]){ if(Y[i+1]<=Y[i]){ // First Quadrant newAngle = newAngle; }else{ // Forth Quadrant newAngle = 360 - newAngle; } }else{ if(Y[i+1]<=Y[i]){ // Second Quadrant newAngle = 180 - newAngle; }else{ // Third Quadrant newAngle = 180 + newAngle; } } rotateBy = angle - newAngle; rotateTransitions[i] = new RotateTransition(Duration.millis(100)); rotateTransitions[i].setByAngle(rotateBy); translateTransition[i] = new TranslateTransition(Duration.millis(time)); translateTransition[i].setByY(Y[i+1]-Y[i]); translateTransition[i].setByX(X[i+1]-X[i]); sequentialTransition.getChildren().addAll(rotateTransitions[i],translateTransition[i]); endTransition = new TranslateTransition(Duration.millis(1000000/speed),imageView); endTransition.setByY(-1*1000); endTransition.onFinishedProperty().set(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { isAlive = false; } }); sequentialTransition.onFinishedProperty().set(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { isAlive = false; GameGlobalVariables.getInstance().updateMissed(); if (GameGlobalVariables.getInstance().isOnline()){ if (GameGlobalVariables.getInstance().getGamer().isIsOwner()){ GameGlobalVariables.getInstance().getGamer().sendMessage(new Move(number, MoveType.Left)); } } } }); angle = newAngle; } EventHandler<MouseEvent> eventHandler = new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent e) { GameGlobalVariables.getInstance().updateScore(shot(GameGlobalVariables.getInstance().getActiveGun().shot())); } }; //Adding event Filter imageView.addEventFilter(MouseEvent.MOUSE_CLICKED, eventHandler); } public ImageView getImageView() { return imageView; } public void play(){ this.sequentialTransition.play(); } private long shot(int damage){ if (GameGlobalVariables.getInstance().isOnline()){ GameGlobalVariables.getInstance().getGamer().sendMessage(new Move(number,damage,MoveType.Damage)); } hitPoints -= damage; if (hitPoints<=0){ hitPoints=0; } imageView.setImage(image[hitPoints]); if (hitPoints==0){ sequentialTransition.stop(); endTransition.play(); Glow glow = new Glow(); glow.setLevel(0.8); imageView.setEffect(glow); isAlive = false; score = score - ((new Date().getTime() ) - entryDate ); if (score<0){ score = 0; } return score; } return 0; } public long shotext(int damage){ hitPoints -= damage; if (hitPoints<=0){ hitPoints=0; } imageView.setImage(image[hitPoints]); if (hitPoints==0){ sequentialTransition.stop(); endTransition.play(); Glow glow = new Glow(); glow.setLevel(0.8); imageView.setEffect(glow); isAlive = false; score = score - ((new Date().getTime() ) - entryDate ); if (score<0){ score = 0; } return score; } return 0; } public long hit(double x, double y,int damage){ if(imageView.contains(x,y)){ return shot(damage); } return 0; } public boolean isDead(){ return !isAlive; } }
/** * */ package com.pelephone_mobile.songwaiting.service.threads; import com.pelephone_mobile.songwaiting.service.interfaces.ISWServiceResponceListener; import com.pelephone_mobile.songwaiting.service.pojos.Pojo; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * @author Galit.Feller * */ public class SWJSONParserThread extends Thread { private final static int CONNECTION_TIMEOUT = 30000; private String mUrl = null; private ISWServiceResponceListener mPojoResponceListener = null; private Class<? extends Pojo> mClassToParseJsonResponse = null; private Pojo mResultPojo; /** * * @param url * @param listener * @param classToParseJsonResponse */ public SWJSONParserThread(String url, ISWServiceResponceListener listener, Class<? extends Pojo> classToParseJsonResponse) { mUrl = url; mPojoResponceListener = listener; mClassToParseJsonResponse = classToParseJsonResponse; } @Override public void run() { if (mUrl == null || mPojoResponceListener == null || mClassToParseJsonResponse == null) { return; } ObjectMapper mapper = new ObjectMapper(); HttpURLConnection connection = null; InputStream in = null; try { // connection to server connection = (HttpURLConnection) (new URL(mUrl)).openConnection(); connection.setConnectTimeout(CONNECTION_TIMEOUT); connection.setReadTimeout(CONNECTION_TIMEOUT); in = connection.getInputStream(); String result = null; if (in != null) { // read json as a string StringBuilder stringBuilder; BufferedReader bufferedReader; stringBuilder = new StringBuilder(); bufferedReader = new BufferedReader(new InputStreamReader(in), 1000); for (String line = bufferedReader.readLine(); line != null; line = bufferedReader .readLine()) { stringBuilder.append(line); } result = stringBuilder.toString(); // read json string to POJO object if (result != null) { mResultPojo = mapper.readValue(result, mClassToParseJsonResponse); mPojoResponceListener.onResponce(mResultPojo); } else { mPojoResponceListener .onError(ISWServiceResponceListener.ErrorsTypes.CONNECTION_ERROR); } } else { mPojoResponceListener .onError(ISWServiceResponceListener.ErrorsTypes.CONNECTION_ERROR); return; } } catch (JsonParseException e) { mPojoResponceListener .onError(ISWServiceResponceListener.ErrorsTypes.JSON_PARSE_ERROR); e.printStackTrace(); } catch (JsonMappingException e) { mPojoResponceListener .onError(ISWServiceResponceListener.ErrorsTypes.JSON_PARSE_ERROR); e.printStackTrace(); } catch (IOException e) { mPojoResponceListener .onError(ISWServiceResponceListener.ErrorsTypes.CONNECTION_ERROR); e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
package com.example.qunxin.erp.utils; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; /** * Author: wls-gcc * Date on: 2019\1\9 15:16 * Version: v1.0 */ public class OkHttpUtils { /** * 获取类名 */ private final String TAG = OkHttpUtils.class.getSimpleName(); /** * mdiatype 这个需要和服务端保持一致 */ private final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"); // okHttp post异步请求 public void post(String url, String jsonStr) { MediaType mediaType = MediaType.parse("application/json; charset=utf-8");//"类型,字节码" //1.创建OkHttpClient对象 OkHttpClient okHttpClient = new OkHttpClient(); //2.通过RequestBody.create 创建requestBody对象 RequestBody requestBody = RequestBody.create(mediaType, jsonStr); //3.创建Request对象,设置URL地址,将RequestBody作为post方法的参数传入 final Request request = new Request.Builder().url(url).post(requestBody).build(); //4.创建一个call对象,参数就是Request请求对象 Call call = okHttpClient.newCall(request); //5.请求加入调度,重写回调方法 call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { System.out.println("请求错误"); } @Override public void onResponse(Call call, Response response) throws IOException { System.out.println("请求成功"); System.out.println(response.body().string()); } }); } }
package com.rallytac.engageandroid.legba.fragment; import android.content.res.Configuration; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.Fragment; import androidx.navigation.fragment.NavHostFragment; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import com.rallytac.engageandroid.R; import com.rallytac.engageandroid.databinding.FragmentChannelBinding; import com.rallytac.engageandroid.legba.HostActivity; import com.rallytac.engageandroid.legba.data.dto.Channel; import com.rallytac.engageandroid.legba.data.dto.Member; import com.rallytac.engageandroid.legba.util.RUtils; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; public class ChannelFragment extends Fragment { private FragmentChannelBinding binding; private Channel channel; private FrameLayout redCircle; private TextView notificationsText; private int notificationsCount = 0; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ChannelFragmentArgs channelFragmentArgs = ChannelFragmentArgs.fromBundle(requireArguments()); channel = channelFragmentArgs.getChannel(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setupToolbar(); setHasOptionsMenu(true); binding = DataBindingUtil.inflate(inflater, R.layout.fragment_channel, container, false); UsersRecyclerViewAdapter adapter = new UsersRecyclerViewAdapter(new UsersRecyclerViewAdapter.AdapterDiffCallback(), this); binding.channelElementsRecycler.setHasFixedSize(true); int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_PORTRAIT) { binding.channelElementsRecycler.setLayoutManager(new LinearLayoutManager(getContext())); } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) { binding.channelElementsRecycler.setLayoutManager(new GridLayoutManager(getContext(), 2)); } binding.channelElementsRecycler.setAdapter(adapter); // List<Member> members = new ArrayList<>(); members = channel.users .stream() .map(userIdentity -> { Member newMember = new Member(); newMember.setName(userIdentity.displayName); newMember.setNickName(userIdentity.displayName); newMember.setState(Member.RequestType.ADDED); newMember.setNumber("544321591"); return newMember; }).collect(Collectors.toList()); // adapter.setMembers(members); return binding.getRoot(); } private void setupToolbar() { requireActivity().findViewById(R.id.toolbar_left_title_text).setVisibility(View.VISIBLE); ((TextView) requireActivity().findViewById(R.id.toolbar_left_title_text)).setText(channel.getName()); requireActivity().findViewById(R.id.toolbar_background_image).setVisibility(View.VISIBLE); ((ImageView)requireActivity().findViewById(R.id.toolbar_background_image)).setImageResource(RUtils.getImageResource(channel.getImage())); requireActivity().findViewById(R.id.logo_image).setVisibility(View.VISIBLE); Objects.requireNonNull(((HostActivity) requireActivity()).getSupportActionBar()).setHomeAsUpIndicator(R.drawable.ic_round_keyboard_arrow_left_24); //Default dp is unknown } @Override public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.channel_fragment_menu, menu); } @Override public void onPrepareOptionsMenu(@NonNull Menu menu) { /*MenuItem item = menu.findItem(R.id.notifications_action); View root = item.getActionView(); root.setOnClickListener(view -> onOptionsItemSelected(item)); redCircle = root.findViewById(R.id.notifications_action_red_circle); notificationsText = root.findViewById(R.id.notifications_action_red_circle_count_text);*/ super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { /*if (item.getItemId() == R.id.notifications_action) { notificationsCount = (notificationsCount + 1) % 6; //Cycle trhough 0 - 5 updateNotificationsIcon(); return true; } else */if (item.getItemId() == R.id.history_action) { NavHostFragment.findNavController(this) .navigate(ChannelFragmentDirections.actionChannelFragmentToChannelHistoryFragment(channel.getId())); return true; } return super.onOptionsItemSelected(item); } private void updateNotificationsIcon() { // if notifications count extends into two digits, just show the red circle if (0 < notificationsCount && notificationsCount < 10) { notificationsText.setText(String.valueOf(notificationsCount)); } else { notificationsText.setText(""); } redCircle.setVisibility((notificationsCount > 0) ? View.VISIBLE : View.GONE); } }
package com.bnebit.sms.service; import java.io.File; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartRequest; import org.springframework.web.servlet.ModelAndView; import com.bnebit.sms.dao.ConsultingDAO; import com.bnebit.sms.util.FileRenamePolicy; import com.bnebit.sms.util.UploadUtil; import com.bnebit.sms.vo.Consulting; import com.bnebit.sms.vo.ConsultingImg; @Service("consultingService") public class ConsultingService { @Autowired private ConsultingDAO consultingDAO; // 상담일지 목록조회 public ModelAndView selectConsultingListWorker(HttpServletRequest request) throws SQLException { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("dailyReportId", request.getParameter("dailyReportId")); Iterator<String> iterator = paramMap.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); System.out.println("key : " + key + ", value : " + paramMap.get(key)); } ArrayList<Consulting> consultingList = (ArrayList<Consulting>) consultingDAO.selectConsultingListWorker(paramMap); for(int i=0; i<consultingList.size(); i++) { System.out.println(consultingList.get(i)); } ModelAndView mav = new ModelAndView(); mav.addObject("consultingList", consultingList); return mav; } // 상담일지 작성, 파일추가 public void insertConsulting(Consulting consulting, MultipartFile file) throws SQLException { String index = consultingDAO.insertConsulting(consulting); ConsultingImg consultingImg = new ConsultingImg(); if(file != null && !file.isEmpty()) { File defaultFile = new File("//192.168.1.20/Upload/", file.getOriginalFilename()); System.out.println("기존 fileName : " + file.getOriginalFilename()); defaultFile = FileRenamePolicy.rename(defaultFile); String fileName = defaultFile.getName(); System.out.println("Rename fileName : " + fileName); UploadUtil.uploadHelper(file, fileName); consultingImg.setImgName(fileName); consultingImg.setOriginName(file.getOriginalFilename()); consultingImg.setConsultingId(index); consultingDAO.insertConsultingImg(consultingImg); } } // 상담일지 수정, 파일수정 public Map<String, Object> updateConsulting(Consulting consulting, MultipartFile file) throws SQLException { Map<String, Object> fileMap = new HashMap<>(); consultingDAO.updateConsulting(consulting); ConsultingImg consultingImg = new ConsultingImg(); System.out.println(consulting); // 수정 전 file 유무 String name = consulting.getConsultingImg().getImgName(); System.out.println(file); System.out.println(name); if(file != null && !file.isEmpty()) { File defaultFile = new File("//192.168.1.20/Upload/", file.getOriginalFilename()); System.out.println("기존 fileName : " + file.getOriginalFilename()); defaultFile = FileRenamePolicy.rename(defaultFile); String fileName = defaultFile.getName(); System.out.println("Rename fileName : " + fileName); UploadUtil.uploadHelper(file, fileName); consultingImg.setImgName(fileName); consultingImg.setOriginName(file.getOriginalFilename()); consultingImg.setConsultingId(consulting.getConsultingId()); if(name.equals("")) { consultingDAO.insertConsultingImg(consultingImg); } else { consultingDAO.updateConsultingImg(consultingImg); } fileMap.put("originalFileName", file.getOriginalFilename()); fileMap.put("fileName", fileName); return fileMap; } return null; } // 상담일지 삭제, 파일삭제 public void deleteConsultingWorker(Consulting consulting) throws SQLException { ConsultingImg consultingImg = new ConsultingImg(); consultingImg.setConsultingId(consulting.getConsultingId()); consultingDAO.deleteConsultingWorker(consulting); consultingDAO.deleteConsultingImg(consultingImg); } }
package com.aowin.frame; import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import com.aowin.Database.Database; public class LogView extends Thread{ MainView mv; JPanel panel13,panel2,panel1; Container con; JFrame frame; JTextField tUser; JPasswordField password; JMenu menu1; public void run(){ frame=new JFrame("登录"); con=frame.getContentPane(); con.setLayout(new FlowLayout()); JLabel lUser=new JLabel("用户名:"); tUser=new JTextField(12); JPanel panel11=new JPanel(); panel11.add(lUser); panel11.add(tUser); con.add(panel11); JPanel panel12=new JPanel(); JLabel lPassword=new JLabel("密 码:"); password=new JPasswordField(12); panel12.add(lPassword); panel12.add(password); con.add(panel12); panel13=new JPanel(); JButton bAdmin=new JButton("登录"); JButton bTravel=new JButton("游客登录"); panel2=new JPanel(); panel2.add(bAdmin); panel2.add(bTravel); con.add(panel2); ActionListener lal=new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { String cmd=e.getActionCommand(); mv=getMV(); switch(cmd){ case "登录":{ String userName=tUser.getText(); String truePass=Database.queryPassword(userName); String password1=new String(password.getPassword()); boolean hasName=Database.queryName(userName); if(hasName==false){ tUser.setText(""); JOptionPane.showMessageDialog(null, "用户名错误!"); }else{ if(!truePass.equals(password1)){ password.setText(""); JOptionPane.showMessageDialog(null, "密码错误!"); }else{ frame.setVisible(false); mv=new MainView("管理员",userName); mv.getFrame().setVisible(true); menu1=mv.getMenu1(); if(menu1.getItemCount()==3){ menu1.add(mv.getMAdd()); menu1.add(mv.getMDelete()); menu1.add(mv.getMUpdate()); menu1.add(mv.getMImport()); menu1.add(mv.getMExport()); } mv.getCon().remove(mv.getPanel1()); mv.getModel().setRowCount(0); } } break; } case "游客登录":{ frame.setVisible(false); mv=new MainView("用户",""); menu1=mv.getMenu1(); if(menu1.getItemCount()==8){ menu1.remove(mv.getMAdd()); menu1.remove(mv.getMDelete()); menu1.remove(mv.getMUpdate()); menu1.remove(mv.getMImport()); menu1.remove(mv.getMExport()); } mv.getFrame().setVisible(true); mv.getCon().remove(mv.getPanel3()); break; } } } }; bAdmin.addActionListener(lal); bTravel.addActionListener(lal); frame.setLocation(200, 300); frame.setSize(280, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public Container getCon(){ return con; } public JPanel getPanel13(){ return panel13; } public MainView getMV(){ return mv; } public JFrame getFrame(){ return frame; } public JTextField getTUser(){ return tUser; } public JPasswordField getPasswordField(){ return password; } public JPanel getPanel2(){ return panel2; } public JPanel getPanel1(){ return panel1; } }
import java.*; public class ClosingBalance { public static void main(String[] args) { //class object instance with actual parameters passed by value Accounts1 ObjOne = new Accounts1("saving account",30000,12000,10000); ObjOne.print();//printout values of object instance for Account class } }
package com.main.salon.models; import java.util.*; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.*; @Entity @Table(name="appointment") // we use @entity to define our database table name for this model @JsonIgnoreProperties({"hibernateLazyInitializer","handler"}) // this annotation is for to ignore those properties these two will load all relational data and will cause problem public class Appointment { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String full_name; private String phone_number; @DateTimeFormat(pattern = "yyyy-MM-dd") private Date appointment_date; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "service_id", referencedColumnName = "service_id") private Services services; public Services getServices() { return services; } public void setServices(Services services) { this.services = services; } public Appointment(String full_name, String phone_number, Date appointment_date, Services services) { this.full_name = full_name; this.phone_number = phone_number; this.appointment_date = appointment_date; this.services = services; } /* these attribute that we define up is equal to columns in database and @Id and generated values is for our primary key and with these config spring data jpa will handle our connection to database */ public Appointment() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFull_name() { return full_name; } public void setFull_name(String full_name) { this.full_name = full_name; } public String getPhone_number() { return phone_number; } public void setPhone_number(String phone_number) { this.phone_number = phone_number; } public Date getAppointment_date() { return appointment_date; } public void setAppointment_date(Date appointment_date) { this.appointment_date = appointment_date; } }
package p13; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; public class MapExam { public static void main(String[]args) { HashMap<String, String> hm=new HashMap<String, String>(); hm.put("age", 10+""); hm.put("name","홍길동"); ArrayList<HashMap<String, String>> al=new ArrayList<HashMap<String, String>>(); for(int i=0;i<10;i++) { hm=new HashMap<String, String>(); Random r=new Random(); String tmp=(r.nextInt(100)+1)+""; if(hm.containsValue(tmp)) { i--; }else { hm.put("age",tmp); hm.put("name", i+""); al.add(hm); } } /*int age1; int age2; HashMap<String, String> temp=new HashMap<String, String>(); for(int i=0;i<al.size();i++) { age1=Integer.parseInt(al.get(i).get("age")); for(int j=0;j<al.size();j++) { age2=Integer.parseInt(al.get(j).get("age")); if(age1>age2) { temp=al.get(i); al.set(i, al.get(j)); al.set(j, temp); } } }*/ ArrayList<HashMap<String, String>> al2=new ArrayList<HashMap<String, String>>(); int max=0; int idx=0; for(int i=0;i<al.size();i++) { if(max<Integer.parseInt(al.get(i).get("age"))) { max=Integer.parseInt(al.get(i).get("age")); idx=i; } if(i==al.size()-1) { al2.add(al.get(idx)); al.remove(idx); idx=max=0; i=-1; } } for(HashMap<String, String> h:al2) { System.out.println(h); } } }
package fr.insee.aventcalendar.service; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import java.util.Locale; import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest class DateServiceTest { @Autowired private DateService dateService; @Test public void shallGetEqualString() { Long timestamp = Long.valueOf(0); assertEquals("01/01/1970 00:00:00", dateService.formatDate(timestamp)); } }
package zee.project.flashcards; import java.awt.BorderLayout; import java.awt.event.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import javax.imageio.*; import javax.swing.*; /** * Hello world! */ public final class App { private App() { } ArrayList<Integer> questions = new ArrayList<Integer>(); BufferedImage question; BufferedImage answer; Boolean isQuestion = true; Iterator<Integer> iter; private void initList() { for (int i = 1; i < 200; i = i+2) { questions.add(i); } Collections.shuffle(questions); iter = questions.iterator(); } private File getFileFromResources(String filename) { ClassLoader classLoader = getClass().getClassLoader(); URL resource = classLoader.getResource(filename); return new File(resource.getFile()); } private void setQuestionAnswer(App app, int index) throws IOException { app.question = ImageIO.read(app.getFileFromResources("CivicsFlashCards-" + String.format("%03d", index) + ".jpg")); app.answer = ImageIO.read(app.getFileFromResources("CivicsFlashCards-" + String.format("%03d", index + 1) + ".jpg")); } /** * Says hello to the world. * * @param args The arguments of the program. * @throws IOException */ public static void main(String[] args) throws IOException { App app = new App(); app.initList(); app.setQuestionAnswer(app, app.iter.next()); JFrame frame = new JFrame("My First GUI"); JButton nextBtn = new JButton("Next Question"); JButton picBtn = new JButton(); picBtn.setIcon(new ImageIcon(app.question)); picBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { picBtn.setIcon(app.isQuestion ? new ImageIcon(app.answer) : new ImageIcon(app.question)); app.isQuestion = !app.isQuestion; } }); nextBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { try { if (!app.iter.hasNext()) { app.questions.clear(); app.initList(); System.out.println(app.questions); } app.setQuestionAnswer(app, app.iter.next()); picBtn.setIcon(new ImageIcon(app.question)); app.isQuestion = true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(1400,850); frame.getContentPane().add(BorderLayout.CENTER, picBtn); frame.getContentPane().add(BorderLayout.SOUTH, nextBtn); // Adds Button to content pane of frame frame.setVisible(true); } }
package com.docker.http; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CrossOriginFilter implements Filter { public CrossOriginFilter() { } public void init(FilterConfig config) throws ServletException { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { this.handle((HttpServletRequest)request, (HttpServletResponse)response, chain); } private void handle(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS"); response.addHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, MSGReferer, token"); if(request.getMethod().toLowerCase().equals("options")) { response.setStatus(200); return; } chain.doFilter(request, response); } public void destroy() { } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.context; import jakarta.servlet.ServletContextEvent; import jakarta.servlet.ServletContextListener; /** * Bootstrap listener to start up and shut down Spring's root {@link WebApplicationContext}. * Simply delegates to {@link ContextLoader} as well as to {@link ContextCleanupListener}. * * <p>{@code ContextLoaderListener} supports injecting the root web application * context via the {@link #ContextLoaderListener(WebApplicationContext)} * constructor, allowing for programmatic configuration in Servlet initializers. * See {@link org.springframework.web.WebApplicationInitializer} for usage examples. * * @author Juergen Hoeller * @author Chris Beams * @since 17.02.2003 * @see #setContextInitializers * @see org.springframework.web.WebApplicationInitializer */ public class ContextLoaderListener extends ContextLoader implements ServletContextListener { /** * Create a new {@code ContextLoaderListener} that will create a web application * context based on the "contextClass" and "contextConfigLocation" servlet * context-params. See {@link ContextLoader} superclass documentation for details on * default values for each. * <p>This constructor is typically used when declaring {@code ContextLoaderListener} * as a {@code <listener>} within {@code web.xml}, where a no-arg constructor is * required. * <p>The created application context will be registered into the ServletContext under * the attribute name {@link WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE} * and the Spring application context will be closed when the {@link #contextDestroyed} * lifecycle method is invoked on this listener. * @see ContextLoader * @see #ContextLoaderListener(WebApplicationContext) * @see #contextInitialized(ServletContextEvent) * @see #contextDestroyed(ServletContextEvent) */ public ContextLoaderListener() { } /** * Create a new {@code ContextLoaderListener} with the given application context. This * constructor is useful in Servlet initializers where instance-based registration of * listeners is possible through the {@link jakarta.servlet.ServletContext#addListener} API. * <p>The context may or may not yet be {@linkplain * org.springframework.context.ConfigurableApplicationContext#refresh() refreshed}. If it * (a) is an implementation of {@link ConfigurableWebApplicationContext} and * (b) has <strong>not</strong> already been refreshed (the recommended approach), * then the following will occur: * <ul> * <li>If the given context has not already been assigned an {@linkplain * org.springframework.context.ConfigurableApplicationContext#setId id}, one will be assigned to it</li> * <li>{@code ServletContext} and {@code ServletConfig} objects will be delegated to * the application context</li> * <li>{@link #customizeContext} will be called</li> * <li>Any {@link org.springframework.context.ApplicationContextInitializer ApplicationContextInitializer org.springframework.context.ApplicationContextInitializer ApplicationContextInitializers} * specified through the "contextInitializerClasses" init-param will be applied.</li> * <li>{@link org.springframework.context.ConfigurableApplicationContext#refresh refresh()} will be called</li> * </ul> * If the context has already been refreshed or does not implement * {@code ConfigurableWebApplicationContext}, none of the above will occur under the * assumption that the user has performed these actions (or not) per his or her * specific needs. * <p>See {@link org.springframework.web.WebApplicationInitializer} for usage examples. * <p>In any case, the given application context will be registered into the * ServletContext under the attribute name {@link * WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE} and the Spring * application context will be closed when the {@link #contextDestroyed} lifecycle * method is invoked on this listener. * @param context the application context to manage * @see #contextInitialized(ServletContextEvent) * @see #contextDestroyed(ServletContextEvent) */ public ContextLoaderListener(WebApplicationContext context) { super(context); } /** * Initialize the root web application context. */ @Override public void contextInitialized(ServletContextEvent event) { initWebApplicationContext(event.getServletContext()); } /** * Close the root web application context. */ @Override public void contextDestroyed(ServletContextEvent event) { closeWebApplicationContext(event.getServletContext()); ContextCleanupListener.cleanupAttributes(event.getServletContext()); } }
package com.example.tarena.protop.listener; import com.example.tarena.protop.Bean.News; import java.util.List; /** * 作者:Linqiang * 时间:2016/5/21:17:02 * 邮箱: linqiang2010@outlook.com * 说明:刷新完成监听器 */ public interface RefreshListener { void refreshFinish(List<News> list); }
package com.classichu.titlebar.helper; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.PopupWindow; /** * Created by louisgeek on 2017/2/28. */ public class ClassicTitleBarMoreWindowWindowHelper { private static PopupWindow mPopupWindow; private static View mPopupWindowContentView; public static void setOnMoreWindowItemClickListener(int itemId, final OnMoreWindowItemClickListener listener) { mPopupWindowContentView.findViewById(itemId).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mPopupWindow.dismiss(); if (listener!=null){ listener.onMoreWindowItemClick(v); } } }); } public interface OnMoreWindowItemClickListener{ void onMoreWindowItemClick(View view); } public static void initMoreWindow(View anchorView, int moreWindowContentLayoutResId) { mPopupWindowContentView = LayoutInflater.from(anchorView.getContext()).inflate(moreWindowContentLayoutResId, null); mPopupWindow = new PopupWindow(mPopupWindowContentView); // mPopupWindowContentView .measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); int realWidth=mPopupWindowContentView.getMeasuredWidth(); // focusable 为true,PopupWindow的点击事件才会响应 mPopupWindow.setFocusable(true); mPopupWindow.setWidth(realWidth==0?ViewGroup.LayoutParams.MATCH_PARENT:realWidth); mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); mPopupWindow.setContentView(mPopupWindowContentView); // 必须设置一下背景色,否则点击外面不会隐藏此弹窗 mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); mPopupWindow.setTouchable(true); // focusable 为false时,不执行则点击外面不会隐藏此弹窗 //mPopWindow.setOutsideTouchable(true); mPopupWindow.showAsDropDown(anchorView); } }
package com.telpoo.hotpic.object; public class MenuOj { public static String keys[] = { "group_name", "group_id", "name", "category", "url", "type_cut" }; // public static final String GROUP_NAME = keys[0]; public static final String GROUP_ID = keys[1]; public static final String NAME = keys[2]; public static final String CATEGORY = keys[3]; public static final String URL = keys[4]; public static final String TYPE_CUT = keys[5]; //key db }
import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import javax.ejb.EJB; @RunWith(Arquillian.class) public class CategoryEjbTest { @Deployment public static JavaArchive createDeployment() { return ShrinkWrap.create(JavaArchive.class) .addPackages(true, "D:\\Java\\Skol\\Projects\\exercises_new\\stirfry") .addAsResource("META-INF/persistence.xml"); } @EJB private CategoryEjb ctgEjb; @EJB private ResetEjb resetEjb; @Before public void init(){ resetEjb.resetDatabase(); } @Test public void testNoCategory() { } @Test public void testCreateCategory() { } @Test public void testGetCategory() { } @Test public void testCreateSubCategory() { } @Test public void testGetAllCategories() { } @Test public void testCreateTwice() { } }
package com.team3.bra; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import java.util.ArrayList; /** * Show all the users to the manager screen * */ public class ManagerShowUsers extends Activity { UserArrayAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.manager_users_show_layout); loadUsers(); } /** * Load all the users from the database to the screen of the manager */ public void loadUsers(){ User.findUsers(); adapter=new UserArrayAdapter(this, User.getUsers()); ListView lv=(ListView) findViewById(R.id.listUsers); lv.setAdapter(adapter); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(ManagerShowUsers.this, ManagerEditUser.class); Bundle b = new Bundle(); b.putInt("key", (int)id); b.putString("info", User.getUserById((int)id)); intent.putExtras(b); startActivity(intent); } }); } @Override public void onResume(){ super.onResume(); loadUsers(); } /** * Return to the main menu of the manager * @param v the view that clicked the button */ public void backClicked(View v){ finish(); } }
package com.robin.springbootlearn.app.controller; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; /** * @author silkNets * @program springboot-learn * @description 文件上传下载控制器 * @createDate 2020-02-27 15:27 */ @Slf4j @Controller public class FileuploadController { // 上传文件会自动绑定到 MultipartFile 中 @PostMapping(value = "/fileUpload") public String fileupload(HttpServletRequest request, @RequestParam("description") String description, @RequestParam("file") MultipartFile file) throws IOException { boolean isNotEmpty = !file.isEmpty(); log.info("description: {}, 文件{}为空", description, isNotEmpty ? "不" : ""); if (isNotEmpty) { // 上传文件路径 String path = request.getServletContext().getRealPath("/upload/"); log.info("上传文件,原文件路径:{}", path); // 上传文件名 String fileName = file.getOriginalFilename(); if (StringUtils.isNotBlank(fileName)) { File newFile = new File(path, fileName); // 判断路径是否存在,如果不存在就创建一个 File parentFile = newFile.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } // 将上传的文件保存到一个目标文件当中 String newFilePath = "D:\\upload" + File.pathSeparator + fileName; log.info("上传文件,新文件路径:{}", newFilePath); file.transferTo(new File(newFilePath)); return "success"; } } return "error"; } @PostMapping(value = "/fileDownload") public ResponseEntity<byte[]> fileDownload(HttpServletRequest request, Model model, @RequestParam("filename") String fileName, @RequestHeader("User-Agent") String userAgent) throws IOException { // 下载文件路径 String filePath = request.getServletContext().getRealPath("/upload"); // 构建 File String newFilePath = filePath + File.pathSeparator + fileName; File file = new File(newFilePath); // ok 表示 HTTP 中的状态为 200 ResponseEntity.BodyBuilder bodyBuilder = ResponseEntity.ok(); // 内容长度 bodyBuilder.contentLength(file.length()); // application/octet-stream 二进制流数据(最常见的文件下载) bodyBuilder.contentType(MediaType.APPLICATION_OCTET_STREAM); // 使用 URLEncoder.encode 对文件进行解码 fileName = URLEncoder.encode(fileName, "UTF-8"); // 设置实际的响应文件名,告诉浏览器文件要用于 下载 和 保存;不同浏览器,处理方式不同,要区别对待 if (userAgent.indexOf("MSIE") > 0) { // 如果是 IE, 只需要用 UTF-8 字符集对 URL 编码即可 bodyBuilder.header("Content-Disposition", "attachement; filename =" + fileName); } else { // Chrome\FireFox 等,需要说明编码的字符集 bodyBuilder.header("Content-Disposition", "attachement; filename*=UTF-8''" + fileName); } return bodyBuilder.body(FileUtils.readFileToByteArray(file)); } @RequestMapping("/download") public String downloadFile(HttpServletRequest request, HttpServletResponse response) { String fileName = "haha.jpg"; String filePath = "D:\\develop_space\\0IDEA_DEV\\springboot-learn\\src\\main\\resources\\statics\\img\\"; if (fileName != null) { //当前是从该工程的WEB-INF//File//下获取文件(该目录可以在下面一行代码配置)然后下载到C:\\users\\downloads即本机的默认下载的目录 String realPath = request.getServletContext().getRealPath("//statics//"); File file = new File(filePath, fileName); if (file.exists()) { response.setContentType("application/force-download");// 设置强制下载不打开 response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名 byte[] buffer = new byte[1024]; FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); OutputStream os = response.getOutputStream(); int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } System.out.println("success"); } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } } return null; } }
package com.test.base; import java.util.Arrays; import com.test.SolutionA; import junit.framework.TestCase; public class Example extends TestCase { private Solution solution; @Override protected void setUp() throws Exception { super.setUp(); } public void testSolutionA() { solution = new SolutionA(); assertSolution(); } private void assertSolution() { assertEquals("[1]", Arrays.toString(solution.getRow(0).toArray())); assertEquals("[1, 1]", Arrays.toString(solution.getRow(1).toArray())); assertEquals("[1, 2, 1]", Arrays.toString(solution.getRow(2).toArray())); assertEquals("[1, 3, 3, 1]", Arrays.toString(solution.getRow(3).toArray())); assertEquals("[1, 4, 6, 4, 1]", Arrays.toString(solution.getRow(4).toArray())); assertEquals("[1, 5, 10, 10, 5, 1]", Arrays.toString(solution.getRow(5).toArray())); assertEquals("[1, 6, 15, 20, 15, 6, 1]", Arrays.toString(solution.getRow(6).toArray())); assertEquals("[1, 7, 21, 35, 35, 21, 7, 1]", Arrays.toString(solution.getRow(7).toArray())); assertEquals("[1, 8, 28, 56, 70, 56, 28, 8, 1]", Arrays.toString(solution.getRow(8).toArray())); assertEquals("[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]", Arrays.toString(solution.getRow(9).toArray())); } @Override protected void tearDown() throws Exception { solution = null; super.tearDown(); } }
package ur.ur_flow.widget; import android.content.Context; import com.google.gson.Gson; import com.gtambit.gt.app.api.GtSharedPreferences; import lib.hyxen.http_request.RequestHandler; import lib.hyxen.http_request.RequestResponseListener; import lib.hyxen.http_request.RequestSetting; import ur.api_ur.URApiSetting; import ur.api_ur.api_data_obj.sys.URApiSysResponseObj; import ur.api_ur.sys.URApiSys; /** * Created by redjack on 15/9/28. */ public class URSysInfoFetcher implements RequestResponseListener { static URApiSysResponseObj res; private SysInfoListener listener; private RequestHandler requestHandler; private Context mContext; public URSysInfoFetcher(Context context) { mContext = context; } public static void initialFromApi(Context context, SysInfoListener listener) { if (res != null) { if (listener != null) listener.onGotSystemInfo(res); return; } RequestHandler handler = new RequestHandler(); URSysInfoFetcher fetcher = new URSysInfoFetcher(context); fetcher.listener = listener; fetcher.requestHandler = handler; URApiSetting setting = URApiSys.getSysInfo(); setting.listener = fetcher; handler.sendRequest(setting); } public static void getSystemInfo(Context context,SysInfoListener listener) { if (res != null) listener.onGotSystemInfo(res); else initialFromApi(context,listener); } @Override public void requesting(RequestSetting setting) { } @Override public void requestComplete(RequestSetting setting, String result) { URApiSysResponseObj res = new Gson().fromJson(result, URApiSysResponseObj.class); this.res = res; // GtSharedPreferences.saveGeoCdTime(mContext,String.valueOf(res.gfcd)); // GtSharedPreferences.saveBeaconTime(mContext,String.valueOf(res.bccd)); GtSharedPreferences.savePrivacy(mContext,res.privacy); if (listener != null) listener.onGotSystemInfo(res); } @Override public void requestFault(RequestSetting setting) { if (listener != null) listener.onFailed(); } @Override public void requestDone(RequestSetting setting) { requestHandler.stopHandle(); } public interface SysInfoListener { public void onGotSystemInfo(URApiSysResponseObj res); public void onFailed(); } }
/* * 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 swrubrica; import gui.FinestraPrincipale; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Scanner; import java.util.Vector; import javax.swing.JOptionPane; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.*; /** * * @author anne */ public class SwRubrica { private Vector<Persona> contatti; private FinestraPrincipale finestra; private final String url = "jdbc:postgresql://localhost:5432/rubrica_postgresql"; private final String username = "rubrica"; private final String password = "rubric@"; private Connection conn; private boolean connesso = false; private int userid; public SwRubrica(){ contatti = new Vector<Persona>(); } public Vector<Persona> getContatti(){ return this.contatti; } public Vector<Persona> getContatti(int u){ return this.contatti; } public void setContatti(Vector<Persona> c){ this.contatti = c; } public int getUserid() { return userid; } public void setUserid(int userid) { this.userid = userid; } /* Inizializza la finestra della rubrica dell'utente corrente. */ public void startSwRubrica(int u){ SwRubrica sr = new SwRubrica(); sr.initGUI(u); } /* Recupera tutti i contatti della rubrica dal file. */ public Vector<Persona> listaContatti(){ boolean vuota = true; System.out.println("*** File --> Lista ***"); try{ FileInputStream info = new FileInputStream("informazioni.txt"); Scanner s = new Scanner(info); String nome= ""; String cognome = ""; String indirizzo=""; String telefono = ""; int eta =0; for(int index=0; s.hasNextLine(); index++) { System.out.println("index "+index); vuota = false; String line = s.nextLine(); Scanner ls = new Scanner(line); ls.useDelimiter(";"); for(int counter=0; ls.hasNext(); counter++){ String word = ls.next(); switch(counter){ case 0: System.out.println(word); nome = word; break; case 1: System.out.println(word); cognome = word; break; case 2: System.out.println(word); indirizzo = word; break; case 3: System.out.println(word); telefono = word; break; case 4: System.out.println(word); eta = Integer.parseInt(word); break; default: break; } } if(!vuota){ Persona p = new Persona(nome, cognome, indirizzo, telefono, eta); if(!contatti.contains(p)) contatti.addElement(p); } ls.close(); } s.close(); } catch(FileNotFoundException fnfe){System.err.println(fnfe);} return contatti; } /** * @param args the command line arguments */ public static void main(String[] args) { SwRubrica r = new SwRubrica(); //r.initGUI(); } /* Inizializza la finestra principale. */ public void initGUI(int u){ finestra = new FinestraPrincipale(u); finestra.setVisible(true); } /* Crea un contatto in Rubrica. */ public void creaContatto(Persona p) { if(contatti.contains(p)){ JOptionPane.showMessageDialog(null, "Contatto gia' esistente."); System.out.println("Contatto gia' esistente."); } else{ contatti.addElement(p); //aggiornaFileSwRubrica(); JOptionPane.showMessageDialog(null, p.getNome().toUpperCase()+" "+ p.getCognome().toUpperCase()+" aggiunto."); System.out.println("Persona: "+ p.toString() +" aggiunto."); } } /* Modifica un contatto in Rubrica. */ public void modificaContatto(int i, Persona pn){ Persona per = contatti.get(i); per.setNome(pn.nome); per.setCognome(pn.cognome); per.setIndirizzo(pn.indirizzo); per.setTelefono(pn.telefono); per.setEta(pn.eta); contatti.setElementAt(per, i); //aggiornaFileSwRubrica(); JOptionPane.showMessageDialog(null, "Contatto modificato."); System.out.println("Contatto modificato."); } /* Elimina un contatto in Rubrica. */ public Persona eliminaContatto(Persona p){ if(contatti.contains(p)){ contatti.remove(p); //aggiornaFileSwRubrica(); JOptionPane.showMessageDialog(null, p.getNome().toUpperCase()+" "+p.getCognome().toUpperCase()+" eliminato."); System.out.println("Contatto eliminato."); return p; } else{ JOptionPane.showMessageDialog(null, "Contatto NON esistente."); System.out.println("Contatto non presente."); return null; } } /* Aggiorna il file "informazioni.txt". */ public void aggiornaFileSwRubrica(){ System.out.println("*** Lista -> File ***"); try{ FileOutputStream info = new FileOutputStream("informazioni.txt"); PrintStream scrivi = new PrintStream(info); for(int i=0; i<contatti.size(); i++) scrivi.println(contatti.get(i).toString()); } catch(FileNotFoundException ex){System.out.println("nel aggiornaFileSwRubrica"); System.err.println(ex);} } /* Aggiorna la lista Vector<Persona> contatti. */ public void aggiornaListaSwRubrica(){ boolean vuota = true; System.out.println("*** File --> Lista ***"); try{ FileInputStream info = new FileInputStream("informazioni.txt"); Scanner s = new Scanner(info); String nome= ""; String cognome = ""; String indirizzo=""; String telefono = ""; int eta =0; for(int index=0; s.hasNextLine(); index++) { //System.out.println("index "+index); vuota = false; String line = s.nextLine(); Scanner ls = new Scanner(line); ls.useDelimiter(";"); for(int counter=0; ls.hasNext(); counter++){ String word = ls.next(); switch(counter){ case 0: System.out.println(word); nome = word; break; case 1: System.out.println(word); cognome = word; break; case 2: System.out.println(word); indirizzo = word; break; case 3: System.out.println(word); telefono = word; break; case 4: System.out.println(word); eta = Integer.parseInt(word); break; default: break; } } if(!vuota){ Persona p = new Persona(nome, cognome, indirizzo, telefono, eta); if(!contatti.contains(p)) contatti.addElement(p); } ls.close(); } s.close(); } catch(FileNotFoundException fnfe){System.err.println(fnfe);} } /* Trova l'indice di un contatto dato il nome, cognome e telefono. */ public int trovaIndice(String n, String c, String t){ int ind =0; try{ for(int i=0; i<contatti.size(); i++){ Persona p = contatti.get(i); if((p.nome.compareTo(n)==0) && (p.cognome.compareTo(c)==0) && (p.telefono.compareTo(t)==0)) ind = contatti.indexOf(p); } } catch(NullPointerException e){ System.err.println(e); } return ind; } }
package by.orion.onlinertasks.data.datasource.profile.reviews.remote; import android.support.annotation.NonNull; import by.orion.onlinertasks.common.network.services.BaseService; import by.orion.onlinertasks.data.datasource.profile.reviews.ProfileReviewsDataSource; import by.orion.onlinertasks.data.models.common.requests.ProfileReviewsRequestParams; import by.orion.onlinertasks.data.models.profile.reviews.ProfileReviewsPage; import io.reactivex.Completable; import io.reactivex.Single; public class RemoteProfileReviewsDataSource implements ProfileReviewsDataSource { @NonNull private final BaseService service; public RemoteProfileReviewsDataSource(@NonNull BaseService service) { this.service = service; } @Override public Single<ProfileReviewsPage> getValue(@NonNull Integer key) { throw new UnsupportedOperationException(); } @Override public Completable setValue(@NonNull Integer key, @NonNull ProfileReviewsPage value) { throw new UnsupportedOperationException(); } @Override public Single<ProfileReviewsPage> getReviews(@NonNull ProfileReviewsRequestParams params) { return service.getProfileReviews(params.id(), params.page(), params.role().getName()); } }
package com.niksoftware.snapseed.controllers; import android.graphics.Bitmap; import android.view.View; import com.niksoftware.snapseed.controllers.adapters.StyleItemListAdapter; import com.niksoftware.snapseed.controllers.touchhandlers.CenterFocusHotspotHandler; import com.niksoftware.snapseed.controllers.touchhandlers.TouchHandler; import com.niksoftware.snapseed.core.NotificationCenter; import com.niksoftware.snapseed.core.NotificationCenterListener; import com.niksoftware.snapseed.core.NotificationCenterListener.ListenerType; import com.niksoftware.snapseed.core.filterparameters.FilterParameter; import com.niksoftware.snapseed.util.TrackerData; import com.niksoftware.snapseed.views.BaseFilterButton; import com.niksoftware.snapseed.views.ItemSelectorView; import com.niksoftware.snapseed.views.ItemSelectorView.OnClickListener; import com.niksoftware.snapseed.views.ItemSelectorView.OnVisibilityChangeListener; import java.util.List; public class CenterFocusController extends EmptyFilterController { private static final int[] ADJUSTABLE_FILTER_PARAMETERS = new int[]{19, 23, 22}; private CenterFocusHotspotHandler centerFocusHotspotHandler; private NotificationCenterListener didChangeFilterParameterValue; private ItemSelectorView itemSelectorView; private BaseFilterButton presetButton; private StyleItemListAdapter styleListAdapter; private BaseFilterButton weakStrongButton; private class StyleSelectorOnClickListener implements OnClickListener { private StyleSelectorOnClickListener() { } public boolean onItemClick(Integer itemId) { if (CenterFocusController.this.changeParameter(CenterFocusController.this.getFilterParameter(), 3, itemId.intValue())) { TrackerData.getInstance().usingParameter(3, false); CenterFocusController.this.styleListAdapter.setActiveItemId(itemId); CenterFocusController.this.itemSelectorView.refreshSelectorItems(CenterFocusController.this.styleListAdapter, true); } return true; } public boolean onContextButtonClick() { return false; } } public void init(ControllerContext context) { super.init(context); TouchHandler centerFocusHotspotHandler = new CenterFocusHotspotHandler(); this.centerFocusHotspotHandler = centerFocusHotspotHandler; addTouchListener(centerFocusHotspotHandler); addParameterHandler(); this.didChangeFilterParameterValue = new NotificationCenterListener() { public void performAction(Object arg) { if (arg != null && ((Integer) arg).intValue() == 3) { CenterFocusController.this.updateWeakStrongState(); } } }; NotificationCenter.getInstance().addListener(this.didChangeFilterParameterValue, ListenerType.DidChangeFilterParameterValue); this.styleListAdapter = new StyleItemListAdapter(getContext(), getFilterParameter(), 3, getTilesProvider().getStyleSourceImage()); this.itemSelectorView = getItemSelectorView(); this.itemSelectorView.reloadSelector(this.styleListAdapter); this.itemSelectorView.setSelectorOnClickListener(new StyleSelectorOnClickListener()); this.itemSelectorView.setOnVisibilityChangeListener(new OnVisibilityChangeListener() { public void onVisibilityChanged(boolean isVisible) { CenterFocusController.this.presetButton.setSelected(isVisible); } }); } public void cleanup() { getEditingToolbar().itemSelectorWillHide(); this.itemSelectorView.setVisible(false, false); this.itemSelectorView.cleanup(); this.itemSelectorView = null; NotificationCenter.getInstance().removeListener(this.didChangeFilterParameterValue, ListenerType.DidChangeFilterParameterValue); super.cleanup(); } public int getFilterType() { return 11; } public int[] getGlobalAdjustmentParameters() { return ADJUSTABLE_FILTER_PARAMETERS; } public boolean showsParameterView() { return true; } public boolean initLeftFilterButton(BaseFilterButton button) { if (button == null) { this.presetButton = null; return false; } this.presetButton = button; this.presetButton.setStateImages((int) R.drawable.icon_tb_presets_default, (int) R.drawable.icon_tb_presets_active, 0); this.presetButton.setText(getButtonTitle(R.string.presets)); this.presetButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { CenterFocusController.this.styleListAdapter.setActiveItemId(Integer.valueOf(CenterFocusController.this.getFilterParameter().getParameterValueOld(3))); CenterFocusController.this.itemSelectorView.refreshSelectorItems(CenterFocusController.this.styleListAdapter, true); CenterFocusController.this.itemSelectorView.setVisible(true, true); CenterFocusController.this.previewImages(3); } }); return true; } public boolean initRightFilterButton(BaseFilterButton button) { if (button == null) { this.weakStrongButton = null; return false; } this.weakStrongButton = button; this.weakStrongButton.setStyle(R.style.EditToolbarButtonTitle.Selectable.PreserveTitleColor); this.weakStrongButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { CenterFocusController.this.toggleWeakStrong(); } }); updateWeakStrongState(); return true; } public BaseFilterButton getLeftFilterButton() { return this.presetButton; } public BaseFilterButton getRightFilterButton() { return this.weakStrongButton; } public void toggleWeakStrong() { FilterParameter filter = getFilterParameter(); if (changeParameter(filter, 12, filter.getParameterValueOld(12) != 0 ? 0 : 1)) { updateWeakStrongState(); } } public void undoRedoStateChanged() { super.undoRedoStateChanged(); updateWeakStrongState(); } private void updateWeakStrongState() { this.weakStrongButton.setSelected(getFilterParameter().getParameterValueOld(12) > 0); if (this.weakStrongButton.isSelected()) { this.weakStrongButton.setStateImages((int) R.drawable.icon_tb_status_strong_active, (int) R.drawable.icon_tb_status_strong_active, 0); this.weakStrongButton.setText(getButtonTitle(R.string.strong)); return; } this.weakStrongButton.setStateImages((int) R.drawable.icon_tb_status_weak_default, (int) R.drawable.icon_tb_status_weak_default, 0); this.weakStrongButton.setText(getButtonTitle(R.string.weak)); } public int getHelpResourceId() { return R.xml.overlay_two_gestures_on_image; } public void onPause() { this.centerFocusHotspotHandler.handlePinchAbort(); } public void setPreviewImage(List<Bitmap> images, int parameter) { if (this.styleListAdapter.updateStylePreviews(images)) { this.itemSelectorView.refreshSelectorItems(this.styleListAdapter, false); } } }
package co.sblock.events.event; import java.util.Set; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.player.AsyncPlayerChatEvent; import co.sblock.chat.message.Message; import co.sblock.utilities.CollectionConversions; /** * Event wrapper allowing us to more easily manage our channeled chat system. * * @author Jikoo */ public class SblockAsyncChatEvent extends AsyncPlayerChatEvent { private final Message message; private boolean globalCancelled; private final boolean checkSpam; public SblockAsyncChatEvent(boolean async, Player who, Message message) { this(async, who, message, true); } public SblockAsyncChatEvent(boolean async, Player who, Message message, boolean checkSpam) { this(async, who, CollectionConversions.toSet(message.getChannel().getListening(), uuid -> Bukkit.getPlayer(uuid)), message, checkSpam); } public SblockAsyncChatEvent(boolean async, Player who, Set<Player> players, Message message) { this(async, who, players, message, true); } public SblockAsyncChatEvent(boolean async, Player who, Set<Player> players, Message message, boolean checkSpam) { super(async, who, message.getMessage(), players); setFormat(message.getConsoleFormat()); this.message = message; this.checkSpam = checkSpam; this.globalCancelled = false; } public boolean checkSpam() { return checkSpam; } public Message getSblockMessage() { return message; } @Override public void setCancelled(boolean cancel) { super.setCancelled(cancel); globalCancelled = false; } public void setGlobalCancelled(boolean cancelled) { if (cancelled && !isCancelled()) { globalCancelled = true; super.setCancelled(true); return; } globalCancelled = false; } public boolean isGlobalCancelled() { return globalCancelled; } }
package com.mpls.v2.controller; import com.google.api.services.drive.model.File; import com.mpls.v2.dro.DriveFile; import com.mpls.v2.service.GoogleDriveService; import com.mpls.v2.service.exceptions.GoogleDriveException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.util.LinkedList; import java.util.List; @CrossOrigin() @RestController @RequestMapping("/restful/google-drive") public class GoogleDriveController { private final String FOLDER_FLAG = "application/vnd.google-apps.folder"; @Autowired private GoogleDriveService driveService; @ResponseStatus(HttpStatus.OK) @GetMapping("/{id}") public DriveFile getFile(@PathVariable String id) { return getDriveFileFrom(driveService.getFile(id)); } @ResponseStatus(HttpStatus.OK) @GetMapping("/parent/{id}") public List<DriveFile> findByParentId(@PathVariable String id) { return getDriveFilesFrom(driveService.findByParentId(id)); } @ResponseStatus(HttpStatus.OK) @PostMapping("/create/{parentId}") public DriveFile createFolder(@PathVariable String parentId, @RequestBody String name) { return getDriveFileFrom(driveService.createFolder(name, parentId)); } @ResponseStatus(HttpStatus.OK) @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE) public String delete(@PathVariable String id) { return driveService.delete(id); } @ResponseStatus(HttpStatus.OK) @PutMapping("update/{id}") public DriveFile update(@PathVariable String id, @RequestBody String name) { return getDriveFileFrom(driveService.update(id, name)); } @ResponseStatus(HttpStatus.OK) @PostMapping("/upload") public void upload(@RequestParam("file") MultipartFile file) { driveService.upload(file); } @ResponseStatus(HttpStatus.OK) @GetMapping("download/{id}") public void download(@PathVariable String id, HttpServletResponse response) { driveService.download(id, response); } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(IllegalArgumentException.class) public Error illegalFileName(IllegalArgumentException exception) { String message = exception.getLocalizedMessage(); return new Error(400 + message); } @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(GoogleDriveException.class) public Error googleDriveError(GoogleDriveException exception) { String message = exception.getMessage(); return new Error(500 + message); } private List<DriveFile> getDriveFilesFrom(List<File> list) { List<DriveFile> files = new LinkedList<>(); list.forEach(file -> { files.add(getDriveFileFrom(file)); }); return files; } private DriveFile getDriveFileFrom(File file) { DriveFile driveFile = new DriveFile(); driveFile.setId(file.getId()); driveFile.setName(file.getName()); driveFile.setFolder(file.getMimeType().equals(FOLDER_FLAG)); driveFile.setParents(file.getParents()); return driveFile; } }
package com.djtracksholder.djtracksholder.interfaces; /** * Created by Вадим on 21.08.2014. */ public interface TrackCreator<T> { public void createTrack(T object); }
package com.eichiba.demo.entitys; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; import javax.persistence.*; import java.util.ArrayList; import java.util.List; @Entity @Table(name = "USERS") @Data @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class User { @Id @Column(name = "id") private int userId; @Column(nullable = false, name = "first_name") private String firstName; @Column(nullable = false, name = "last_name") private String lastName; @OneToMany(mappedBy = "createdBy", cascade = CascadeType.ALL, orphanRemoval = true) @JsonIgnoreProperties("createdBy") private List<Reciepe> reciepeList = new ArrayList<>(); }
package ru.steagle.protocol.request; /** * Created by bmw on 16.02.14. */ public class GetDevModesCommand extends Command { @Override protected String getRootTagName() { return "var"; } @Override protected String getCommandName() { return "dev_mode"; } }
package enums; public enum QuerySQL { CREATE_RECORD ("INSERT INTO Student (name, age) VALUES (?, ?)"), GET_STUDENT ("SELECT id, name, age FROM Student WHERE id = ?"), GET_ALL_STUDENTS ("SELECT id, name, age FROM STUDENT"), DELETE_RECORD ("DELETE FROM Student WHERE id = ?"), UPDATE_RECORD ("UPDATE Student set age = ? WHERE id = ?"); private final String field; QuerySQL(String field) { this.field = field; } public String field() { return field; } }
package org.vaadin.addons.tokenfilter.model; public class MissingDocumentFilterOption implements Cloneable { private String name; private Long documentCount; public MissingDocumentFilterOption(String name) { this.name = name; } public String getName() { return name; } public void setDocumentCount(Long count) { this.documentCount = count; } public Long getDocumentCount() { return documentCount; } @Override protected Object clone() throws CloneNotSupportedException { return new MissingDocumentFilterOption(this.name); } }
package com.sha.springbootmongo.service; import com.sha.springbootmongo.model.Order; import java.util.List; /** * @author sa * @date 1/10/21 * @time 12:20 PM */ public interface IOrderService { void saveOrder(Order order); List<Order> ordersOfUser(String userId); }
package com.controller.resource; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import com.controller.entidade.ControleCliente; import com.google.gson.Gson; import com.model.entidade.Cliente; @Path("/fila") public class ResourceFila { @POST @Path("/removerCliente") @Produces("application/json") public String removerClienteFila(Cliente cliente){ return new ControleCliente().remover(cliente); } }
package zkouska; public class PC extends Laptop{ private Monitors monitor; private Periferie perif; public PC(Integer id, String name, Integer cpu, Integer ram, Monitors monitor, Periferie perif) { super(id, name, cpu, ram, monitor); this.setPerif(perif); // TODO Auto-generated constructor stub } public Periferie getPerif() { return perif; } public void setPerif(Periferie perif) { this.perif = perif; } public Monitors getMonitor() { // TODO Auto-generated method stub return monitor; } public void setMonitor(Monitors m) { // TODO Auto-generated method stub monitor = m; } @Override public Integer getId() { // TODO Auto-generated method stub return super.getId(); } @Override public void setId(Integer id) { // TODO Auto-generated method stub super.setId(id); } @Override public String getName() { // TODO Auto-generated method stub return super.getName(); } @Override public void setName(String name) { // TODO Auto-generated method stub super.setName(name); } @Override public Integer getCpu() { // TODO Auto-generated method stub return super.getCpu(); } @Override public void setCpu(Integer cpu) { // TODO Auto-generated method stub super.setCpu(cpu); } @Override public Integer getRam() { // TODO Auto-generated method stub return super.getRam(); } @Override public void setRam(Integer ram) { // TODO Auto-generated method stub super.setRam(ram); } @Override public String toString() { return "\n" + "PC" + " - ID = " + this.getId() + ", name = " + this.getName() + ", cpu = " + this.getCpu() + ", ram = " + this.getRam() + ", " + this.getMonitor() + perif; } }
package com.wh.controller; import com.wh.myInterface.AModulesApi; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * @program: maven-modules * @description: * @author: wh * @create: 2021-07-08 17:37 **/ @RestController @RequestMapping("test1") public class TestController { public TestController(){ System.out.println("init"); } @Resource private AModulesApi aModulesApi; @RequestMapping("test1") public String test1(){ return aModulesApi.test1(); } }
package com.questionanswer.questionanswer.model; public class AdminQuestionOptionModel { private int id; private String option; private boolean correct; private boolean selected; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getOption() { return option; } public void setOption(String option) { this.option = option; } public boolean isCorrect() { return correct; } public void setCorrect(boolean isCorrect) { this.correct = isCorrect; } public boolean isSelected() { return selected; } public void setSelected(boolean isSelected) { this.selected = isSelected; } }
import java.io.*; class employee1 { public static void main(String args[])throws IOException { BufferedReader d=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter Employee code:-"); String ecode=(d.readLine()); System.out.print("Enter Basic pay in Rs:-"); double basic=Double.parseDouble(d.readLine()); double hra=basic*30/100; double ca=250*4; double ma=basic*20/100; double gross=basic+ca+ma+hra; double lv=gross/31*5; double itax=gross*12/100; double net=gross-lv-itax; System.out.println("=================Salery======================="); System.out.println("Employee code:- "+ecode); System.out.println("Employee Basic pay in Rs:- "+basic); System.out.println("Convenioan allowance in RS:- "+ca); System.out.println("House rent allowance in Rs:- "+hra); System.out.println("Madical allowance in Rs:- "+ma); System.out.println("----------------------------------------------"); System.out.println("Gross/total salery in Rs:- "+gross); System.out.println("Leav deduction in Rs:- "+lv); System.out.println("-----------------------------------------------"); System.out.println("Net Saleryy in Rs:- "+net); }//close of main }//close of class
package org.cellcore.code.model; import org.cellcore.code.shared.GsonExclude; import javax.persistence.*; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * * Copyright 2013 Freddy Munoz (freddy@cellcore.org) * * 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. * * ============================================================== */ @Entity @Table(name = "CARD_PRICE_SOURCE") public class CardPriceSource extends AbstractJPAEntity { @Enumerated(EnumType.STRING) private PriceSources sourceType; private String sourceName; /** * by default the currency is euros */ @Enumerated(EnumType.STRING) private Currency currency = Currency.EUR; @Column(columnDefinition = "VARCHAR(300)") private String url; @Temporal(value = TemporalType.TIMESTAMP) private Date lastUpdate; @ManyToOne @GsonExclude private Card card; @OneToMany(mappedBy = "source", cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE}) private Set<CardPrice> priceSet; private float lastPrice; private int lastStock=-1; public PriceSources getSourceType() { return sourceType; } public void setSourceType(PriceSources sourceType) { this.sourceType = sourceType; } public Card getCard() { return card; } public void setCard(Card card) { this.card = card; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Date getLastUpdate() { return lastUpdate; } public void setLastUpdate(Date lastUpdate) { this.lastUpdate = lastUpdate; } public Set<CardPrice> getPriceSet() { if (priceSet == null) { priceSet = new HashSet<CardPrice>(); } return priceSet; } public void setPriceSet(Set<CardPrice> priceSet) { this.priceSet = priceSet; } @Override public String toString() { return "CardPriceSource{" + "sourceType=" + sourceType + ", url='" + url + '\'' + ", lastUpdate=" + lastUpdate + ", priceSet=" + priceSet + '}'; } public String getSourceName() { return sourceName; } public void setSourceName(String sourceName) { this.sourceName = sourceName; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CardPriceSource)) return false; CardPriceSource that = (CardPriceSource) o; if (sourceType != that.sourceType) return false; return true; } @Override public int hashCode() { int result = sourceType != null ? sourceType.hashCode() : 0; result = 31 * result + (url != null ? url.hashCode() : 0); return result; } public void setLastPrice(float lastPrice) { this.lastPrice = lastPrice; } public float getLastPrice() { return lastPrice; } public int getLastStock() { return lastStock; } public void setLastStock(int lastStock) { this.lastStock = lastStock; } public Currency getCurrency() { return currency; } public void setCurrency(Currency currency) { this.currency = currency; } }
package fr.skytasul.quests.requirements; import java.util.ArrayList; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import org.bukkit.DyeColor; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemStack; import com.massivecraft.factions.FactionsIndex; import com.massivecraft.factions.entity.Faction; import com.massivecraft.factions.entity.FactionColl; import com.massivecraft.factions.entity.MPlayer; import fr.skytasul.quests.BeautyQuests; import fr.skytasul.quests.api.objects.QuestObjectClickEvent; import fr.skytasul.quests.api.requirements.AbstractRequirement; import fr.skytasul.quests.gui.ItemUtils; import fr.skytasul.quests.gui.templates.ListGUI; import fr.skytasul.quests.gui.templates.PagedGUI; import fr.skytasul.quests.utils.Lang; import fr.skytasul.quests.utils.XMaterial; import fr.skytasul.quests.utils.compatibility.Factions; public class FactionRequirement extends AbstractRequirement { public List<Faction> factions; public FactionRequirement() { this(new ArrayList<>()); } public FactionRequirement(List<Faction> factions) { this.factions = factions; } public void addFaction(Object faction){ factions.add((Faction) faction); } @Override public String getDescription(Player p) { return Lang.RDFaction.format(String.join(" " + Lang.Or.toString() + " ", (Iterable<String>) () -> factions.stream().map(Faction::getName).iterator())); } @Override public boolean test(Player p) { if (factions.isEmpty()) return true; for (Faction fac : factions){ if (FactionsIndex.get().getFaction(MPlayer.get(p)) == fac) return true; } return false; } @Override public String[] getLore() { return new String[] { "§8> §7" + factions.size() + " factions", "", Lang.RemoveMid.toString() }; } @Override public void itemClick(QuestObjectClickEvent event) { new ListGUI<Faction>(Lang.INVENTORY_FACTIONS_REQUIRED.toString(), DyeColor.LIGHT_BLUE, factions) { @Override public ItemStack getObjectItemStack(Faction object) { return ItemUtils.item(XMaterial.IRON_SWORD, object.getName(), "", Lang.RemoveMid.toString()); } @Override public void createObject(Function<Faction, ItemStack> callback) { new PagedGUI<Faction>(Lang.INVENTORY_FACTIONS_LIST.toString(), DyeColor.PURPLE, Factions.getFactions()) { @Override public ItemStack getItemStack(Faction object) { return ItemUtils.item(XMaterial.IRON_SWORD, object.getName()); } @Override public void click(Faction existing, ItemStack item, ClickType clickType) { callback.apply(existing); } }.create(p); } @Override public void finish(List<Faction> objects) { factions = objects; event.reopenGUI(); } }.create(event.getPlayer()); } @Override public AbstractRequirement clone() { return new FactionRequirement(new ArrayList<>(factions)); } @Override public void save(ConfigurationSection section) { section.set("factions", factions.stream().map(Faction::getId).collect(Collectors.toList())); } @Override public void load(ConfigurationSection section) { for (String s : section.getStringList("factions")) { if (!FactionColl.get().containsId(s)) { BeautyQuests.getInstance().getLogger().warning("Faction with ID " + s + " no longer exists."); continue; } factions.add(FactionColl.get().get(s)); } } }
import io.restassured.RestAssured; import io.restassured.http.ContentType; import io.restassured.path.json.JsonPath; import io.restassured.response.Response; import static org.hamcrest.Matchers.equalTo; import static io.restassured.RestAssured.given; import org.testng.annotations.*; import files.reusableMethods; public class basics4 { @Test public void Test1() { // TODO Auto-generated method stub //BaseUrl or Host RestAssured.baseURI="http://216.10.245.166"; Response res=given(). param("key","qaclick123"). /* * header("....","...."). * cookie("...","...."). * body()*/ when(). get("/maps/api/place/add/json"). then().assertThat(). statusCode(200).and().contentType(ContentType.JSON).and(). body("results[0].name", equalTo("Sydney")).and() .header("Server", "pablo"). extract().response(); JsonPath js=reusableMethods.rawToJSON(res); int count=js.getInt("results.size()"); System.out.println(count); } }
package com.javabanktech; import java.util.Scanner; public class LanguageSupport { private String language = "English"; public void main(String[] args) { beginLaunch(); } void beginLaunch() { System.out.println("We are sorry that we have defaulted to " + this.language + ". What language do you prefer?"); userSetsLanguage(); } String getLanguage() { return language; } private void userSetsLanguage() { Scanner input = new Scanner(System.in); this.language = input.nextLine(); System.out.println(String.format("Okay, your preference of %s being the default language has been saved.", this.language)); System.out.println("Please allow 10-15 Business Days for the changes to be made. Thank you for using JavaBank!"); } }
package graphics_control.game_control; import game_logic.TurnsManager; import game_object.Board; import game_object.Cell; import game_object.Position; import graphics_control.event_handling.controllers_events.GameOverEvent; import graphics_control.event_handling.controllers_events.GameOverEventArguments; import javafx.fxml.FXMLLoader; import javafx.geometry.Insets; import javafx.scene.layout.GridPane; import graphics_control.factory.CellMatrixGenerator; import graphics_control.drawables.GameCell; import graphics_control.event_handling.game.CellPressedHandler; import graphics_control.event_handling.BoardEventHandler; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class BoardController extends GridPane { //--------- INNER CLASS VARIABLES ---------- private Board gameBoard; private GameCell[][] gameCells; private TurnsManager turnsManager; private BoardEventHandler boardEventHandler; List<GameCell> availableMoves; //---------- CLASS STATIC VARIABLES ---------- private static int BOARD_HEIGHT = 400; private static int BOARD_WIDTH = 400; /** * BoardController(int boardType). * * @param board Board -- a board to be held by this board controller */ public BoardController(Board board, TurnsManager turnsManager) { // create the game board and graphics board this.gameBoard = board; this.turnsManager = turnsManager; // create the grid this.setPadding(new Insets(2)); this.setHgap(2); this.setVgap(2); // set Grid Pane sizes this.setPrefHeight(BOARD_HEIGHT); this.setPrefWidth(BOARD_WIDTH); CellMatrixGenerator matrixGenerator = new CellMatrixGenerator(); this.gameCells = matrixGenerator.generateMatrix(this); this.availableMoves = new ArrayList<>(); initializeFXML(); } //---------- PUBLIC FUNCTIONS ---------- /** * evaluateAvailableMovesForThisTurn(List<Position> availableMoves). * * @param availableMoves List<Position> -- a list of positions of the available moves for this turn. */ public void evaluateAvailableMovesForThisTurn(List<Position> availableMoves) { // clear all available moves for (GameCell availableCell : this.availableMoves) { availableCell.setAvailableMove(false); } // update cells on the GameCells matrix for (Position p : availableMoves) { int row = p.getRow(); int col = p.getCol(); GameCell gC = gameCells[row][col]; // change color accordingly and set to not available. gC.setColor(gameBoard.getCellColor(row, col)); gC.setAvailableMove(true); this.availableMoves.add(gC); } } /** * moveMade(int row, int col, Cell color). * * @param row int -- row number. * @param col int -- col number * @param color Cell -- cell color */ public void moveMade(int row, int col, Cell color) { // update the game board gameBoard.moveMade(new Position(row, col), color); // update the GameCell matrix GameCell updateCell = gameCells[row][col]; updateCell.setCellOccupied(true); updateCell.setColor(color); updateCell.setAvailableMove(false); updateBoard(); } /** * evaluateMove(). * <p> * Once a move was made, we will need to check whether the player now has any available moves to make. * In case he doesn't we will want to skip his turn. In case the game is stuck in a position where both * players cannot move - the game is over. */ public void evaluateMove() { // check if game is over if (this.gameBoard.getSpaceLeft() == 0) { gameOver(); return; } if (turnsManager.availableMoves() != 0) return; turnsManager.endTurn(); turnsManager.evaluateAvailableMovesForThisTurn(); evaluateAvailableMovesForThisTurn(turnsManager.getAvailableMoves()); if (turnsManager.availableMoves() != 0) return; // no moves left for both players, force to end the game this.gameBoard.setSpaceLeft(0); gameOver(); } /** * evaluatePlayer2Score(). * * @return player 1 score. */ public int evaluatePlayer1Score() { return this.gameBoard.onBoard(turnsManager.getPlayer1Color()); } /** * evaluatePlayer2Score(). * * @return player 2 score. */ public int evaluatePlayer2Score() { return this.gameBoard.onBoard(turnsManager.getPlayer2Color()); } //---------- PRIVATE FUNCTIONS ---------- /** * updateBoard(). */ private void updateBoard() { // Local Variables int size = gameBoard.getSize(); for (int row = 0; row < size; ++row) { for (int col = 0; col < size; ++col) { GameCell gC = gameCells[row][col]; gC.setColor(gameBoard.getCellColor(row, col)); } } } /** * initializeFXML(). */ private void initializeFXML() { FXMLLoader fxmlLoader = new FXMLLoader(ClassLoader.getSystemClassLoader().getResource("Board.fxml")); fxmlLoader.setRoot(this); fxmlLoader.setController(this); // try to load fxml loader try { fxmlLoader.load(); } catch (IOException exception) { throw new RuntimeException(exception); } } /** * gameOver(). */ private void gameOver() { // Local Variables String winner, loser; int winnerScore, loserScore; Cell player1Color = turnsManager.getPlayer1Color(); Cell player2Color = turnsManager.getPlayer2Color(); // check winner int winScore = gameBoard.onBoard(player1Color); int loseScore = gameBoard.onBoard(player2Color); if (winScore > loseScore) { winner = player1Color.toString(); loser = player1Color.toString(); winnerScore = winScore; loserScore = loseScore; } else { winner = player2Color.toString(); loser = player1Color.toString(); winnerScore = loseScore; loserScore = winScore; } // create arguments GameOverEventArguments args = new GameOverEventArguments(winner, loser, winnerScore, loserScore); // handle event boardEventHandler.gameOver(new GameOverEvent(args)); } //---------- GETTERS & SETTERS ---------- /** * getBoardType(). * * @return the size of the board controlled by this controller. */ public int getBoardSize() { return this.gameBoard.getSize(); } /** * getGameCell(int row, int col). * * @param row int -- row number * @param col int -- col number * @return the game cell at this row,col */ public GameCell getGameCell(int row, int col) { return gameCells[row][col]; } /** * cellColorAt(int row, int col). * * @param row int -- row number. * @param col int -- col numer. * @return the color of the cell on given row,col */ public Cell cellColorAt(int row, int col) { return this.gameBoard.getCellColor(row, col); } //---------- HANDLERS ----------- /** * attachBoardEventHandler(BoardEventHandler boardEventHandler). * * @param boardEventHandler BoardEventHandler -- the board event handler */ public void attachBoardEventHandler(BoardEventHandler boardEventHandler) { this.boardEventHandler = boardEventHandler; attachListenerToGameCells(); } /** * attachListenerToGameCells(). */ public void attachListenerToGameCells() { // Local Variables int boardSize = gameBoard.getSize(); CellPressedHandler cellPressedHandler = this.boardEventHandler.getCellPressedHandler(); for (int i = 0; i < boardSize; ++i) { for (int j = 0; j < boardSize; ++j) { gameCells[i][j].attachMousePressedListener(cellPressedHandler); } } } //---------- GRAPHICS ---------- /** * draw(). */ public void draw() { // local variables int boardSize = gameBoard.getSize(); // clear children this.getChildren().clear(); for (int i = 0; i < boardSize; i++) { for (int j = 0; j < boardSize; j++) { gameCells[i][j].draw(); } this.addColumn(i); } } }
/* * 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 EvaluacionDesempeñoSupervisores; import EvaluacionDesempeñoOperativo.*; import BD.BD; import Clases.EvaluacionOperativo.BDEvaluacion; import Clases.EvaluacionOperativo.ClassEvaluacionOperativo; import Clases.EvaluacionSupervisores.BDEvaluacionSupervisores; import Clases.EvaluacionSupervisores.ClassEvaluacionSupervisores; import static Formuarios.Inicio.Pane1; import java.awt.Dimension; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.JOptionPane; /** * * @author jluis */ public class NuevaEvaluacionSupervisores extends javax.swing.JInternalFrame { int idlistaempleado; int face = 1; int codigo; int año; int evaluacion; int evalua; int dept; /** * Creates new form NuevaEvaluacion */ public NuevaEvaluacionSupervisores() { initComponents(); } private void buscar() { try { ClassEvaluacionSupervisores p = BDEvaluacionSupervisores.buscarEmpleado(Integer.parseInt(CODIGO.getText())); nombre.setText(p.getNombres());// + ' ' + p.getApellidos()); PUESTO.setText(p.getPuesto()); DEPTO.setText(p.getDepto()); evalua = p.getEvalua(); idlistaempleado = p.getId_listaempleados(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "ERRORRRR" + e); } } private void next() { BuscarCodigo tra = new BuscarCodigo(); Pane1.add(tra); Dimension desktopSize = Pane1.getSize(); Dimension FrameSize = tra.getSize(); tra.setLocation((desktopSize.width - FrameSize.width) / 2, (desktopSize.height - FrameSize.height) / 2); tra.show(); try { this.dispose(); } catch (Exception e) { System.out.println("F " + e); } } private void departamento(){ if (DEPTO.getText().equalsIgnoreCase("INSPECCION")) { dept = 1; } else if (DEPTO.getText().equalsIgnoreCase("TESTING")) { dept = 2; } else if (DEPTO.getText().equalsIgnoreCase("CHIPS")) { dept = 3; } else if (DEPTO.getText().equalsIgnoreCase("SOLDER DIP, STRIP & POTTING")) { dept = 4; } else if (DEPTO.getText().equalsIgnoreCase("TRANSFORMADORES")) { dept = 5; } else if (DEPTO.getText().equalsIgnoreCase("TALLER")) { dept = 6; } else if (DEPTO.getText().equalsIgnoreCase("BODEGA")) { dept = 7; } else if (DEPTO.getText().equalsIgnoreCase("ADMINISTRACION")) { dept = 8; } else if (DEPTO.getText().equalsIgnoreCase("GERENCIA")) { dept = 9; } else if (DEPTO.getText().equalsIgnoreCase("TECNOLOGIA DE LA INFORMACION/MANTENIMIENTO")){ dept = 10; } } private void ValidarExistencia() { try { Connection con = BD.getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select COUNT(codigo) from alistaempleados where codigo=" + CODIGO.getText()); rs.next(); int c = rs.getInt("count(codigo)"); if (CODIGO.getText() == "") { JOptionPane.showMessageDialog(null, "INGRESE EL CODIGO"); } else if (c == 1) { ValidarFaceEnProceso(); } else { JOptionPane.showMessageDialog(null, "EL CODIGO EMPLEADO NO EXITE INTENTE DE NUEVO..."); } } catch (Exception e) { System.out.println("ERROR " + e); } } private void ValidarFaceEnProceso() { try { Connection con = BD.getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select nvl(MIN(b.estado),'2') as ESTADO from bevaluacion_desempeno b inner join alistaempleados a on b.id_listaempleados = a.id_listaempleados where b.tipo = 2 and a.codigo=" + CODIGO.getText()); rs.next(); int c = rs.getInt("ESTADO"); if (c >= 2 ) { buscar(); fechaEvaluacion.setEnabled(true); nuevo.setEnabled(true); guardar.setEnabled(true); fechaEvaluacion.requestFocus(); } else { JOptionPane.showMessageDialog(null, "EL EMPLEADO AUN TIENE FACES ANTERIORES PENDIENTES DE COMPLETAR, COMPLETE O ELIMINE LA EVALUACION "); CODIGO.setText(""); } } catch (Exception e) { System.out.println("ERROR " + e); } } /* private void ValidarExistenciaFaceporAño() { try { if (fechaEvaluacion.getDate() != null && face != 0 && CODIGO.getText().compareTo("") != 0) { Date date = fechaEvaluacion.getDate(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy"); String fecha = sdf.format(date); Connection con = BD.getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select COUNT(codigo) as cantidaFace from alistaempleados e inner join bevaluacion_desempeno d on e.id_listaempleados = d.id_listaempleados where e.codigo = " + CODIGO.getText() + " and d.face = " + face + " and TO_CHAR(d.fecha,'yyyy') = '" + fecha + "'"); rs.next(); int c = rs.getInt("cantidaFace"); if (c == 1) { JOptionPane.showMessageDialog(null, "LA FACE No. " + face + " PARA EL AÑO = " + fecha + " YA FUE CREADA"); } else { guardarEvaluacion(); } } else { JOptionPane.showMessageDialog(null, "LLENE TODOS LOS DATOS"); } } catch (Exception e) { System.out.println("ERROR " + e); } }*/ private void ValidarNodeEvaluacion() { try { Connection con = BD.getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select max(d.evaluacion) evaluacion from alistaempleados e inner join bevaluacion_desempeno d on e.id_listaempleados = d.id_listaempleados where e.codigo ="+CODIGO.getText()); rs.next(); int c = rs.getInt("evaluacion"); evaluacion = c+1; } catch (Exception e) { System.out.println("ERROR " + e); } } private void limpiar() { CODIGO.setText(""); nombre.setText(""); PUESTO.setText(""); DEPTO.setText(""); fechaEvaluacion.setDate(null); fechaEvaluacion.setEnabled(false); nuevo.setEnabled(false); guardar.setEnabled(false); CODIGO.requestFocus(); } private void guardarEvaluacion() { try { departamento(); ValidarNodeEvaluacion(); ClassEvaluacionSupervisores l = new ClassEvaluacionSupervisores(); l.setId_listaempleados(idlistaempleado); l.setFace(face); l.setFecha(fechaEvaluacion.getDate()); l.setNoEvaluacion(evaluacion); l.setDept(dept); l.setEvalua(evalua); Clases.EvaluacionSupervisores.BDEvaluacionSupervisores.insertarEvaluacionSuper(l); JOptionPane.showMessageDialog(null, "EVALUACION ASIGNADA"); crearEvaluacionesSuper(); this.dispose(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "ERROR INGRESO EMPLEADOS" + e); } } public void crearEvaluacionesSuper(){ Date date = fechaEvaluacion.getDate(); SimpleDateFormat sdf = new SimpleDateFormat("d/MM/yyyy"); String fecha = sdf.format(date); try { Connection c = BD.getConnection(); Statement ps = c.createStatement(); ps.executeUpdate("BEGIN CREAREVALUACIONESSUPER(NID_EMPLEADO=>"+idlistaempleado+",NFECHA=>'"+fecha+"',NEVALUACION=>"+evaluacion+",NDEPTO=>"+dept+",NEVALUA=>"+evalua+"); COMMIT; END;"); c.close(); ps.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error"+e); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); CODIGO = new javax.swing.JTextField(); jPanel2 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); nombre = new javax.swing.JTextField(); DEPTO = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); PUESTO = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); fechaEvaluacion = new com.toedter.calendar.JDateChooser(); guardar = new javax.swing.JButton(); nuevo = new javax.swing.JButton(); setClosable(true); setTitle("INGRESO NUEVA EVALUACION SUPERVISORES"); addInternalFrameListener(new javax.swing.event.InternalFrameListener() { public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) { formInternalFrameClosed(evt); } public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) { formInternalFrameClosing(evt); } public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) { } }); jPanel1.setBackground(new java.awt.Color(153, 204, 255)); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1.setText("CODIGO DEL EMPLEADO"); CODIGO.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N CODIGO.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CODIGOActionPerformed(evt); } }); jPanel2.setBackground(new java.awt.Color(204, 204, 255)); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "DATOS DEL EMPLEADO", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel2.setText("NOMBRE"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel3.setText("DEPARTAMENTO"); nombre.setEditable(false); nombre.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N DEPTO.setEditable(false); DEPTO.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel5.setText("PUESTO"); PUESTO.setEditable(false); PUESTO.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(DEPTO) .addComponent(nombre) .addComponent(PUESTO) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel5)) .addGap(0, 278, Short.MAX_VALUE))) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(PUESTO, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(DEPTO, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(12, 12, 12)) ); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel4.setText("FECHA "); fechaEvaluacion.setEnabled(false); fechaEvaluacion.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N guardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/save2.png"))); // NOI18N guardar.setText("GUARDAR"); guardar.setEnabled(false); guardar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { guardarActionPerformed(evt); } }); nuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/New.png"))); // NOI18N nuevo.setText("NUEVO"); nuevo.setEnabled(false); nuevo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { nuevoActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(CODIGO, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addGap(90, 90, 90) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(guardar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(nuevo)) .addComponent(fechaEvaluacion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(94, 94, 94)))))) .addContainerGap(18, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(34, 34, 34) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CODIGO, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(fechaEvaluacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(guardar, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(nuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(14, 14, 14)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void guardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarActionPerformed //ValidarExistenciaFaceporAño(); guardarEvaluacion(); }//GEN-LAST:event_guardarActionPerformed private void CODIGOActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CODIGOActionPerformed ValidarExistencia(); }//GEN-LAST:event_CODIGOActionPerformed private void nuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoActionPerformed limpiar(); }//GEN-LAST:event_nuevoActionPerformed private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing /* InicioEvaluacioOperativos tra = new InicioEvaluacioOperativos(); Pane1.add(tra); Dimension desktopSize = Pane1.getSize(); Dimension FrameSize = tra.getSize(); tra.setLocation((desktopSize.width - FrameSize.width) / 2, (desktopSize.height - FrameSize.height) / 2); tra.show();*/ }//GEN-LAST:event_formInternalFrameClosing private void formInternalFrameClosed(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosed InicioEvaluacioSupervisores tra = new InicioEvaluacioSupervisores(); Pane1.add(tra); Dimension desktopSize = Pane1.getSize(); Dimension FrameSize = tra.getSize(); tra.setLocation((desktopSize.width - FrameSize.width) / 2, (desktopSize.height - FrameSize.height) / 2); tra.show(); }//GEN-LAST:event_formInternalFrameClosed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField CODIGO; private javax.swing.JTextField DEPTO; private javax.swing.JTextField PUESTO; private com.toedter.calendar.JDateChooser fechaEvaluacion; private javax.swing.JButton guardar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JTextField nombre; private javax.swing.JButton nuevo; // End of variables declaration//GEN-END:variables }
package com.example.flying_h; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentUris; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.provider.MediaStore.Images.Media; import android.text.Editable; import android.text.TextWatcher; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.view.ViewTreeObserver; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import android.provider.DocumentsContract; public class PhotoAct extends Activity { public static final int TAKE_PHOTO = 1; public static int i = 0; public static final int CROP_PHOTO=2; private Button takePhoto; private ImageView picture; private Uri imageUri; private static final int CHOOSE_PHOTO =3; private Button chooseFromAlbum; //位于图片中的文本组件 private TextView tvInImage; //图片和文本的父组件 private View containerView; //父组件的尺寸 private float imageWidth, imageHeight, imagePositionX, imagePositionY; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_photo); takePhoto =(Button) findViewById(R.id.take_photo); chooseFromAlbum=(Button) findViewById(R.id.choose_from_album); picture = (ImageView) findViewById(R.id.picture); tvInImage = (TextView) findViewById(R.id.writeText_image_tv); containerView = findViewById(R.id.writeText_img_rl); EditText editText = (EditText) findViewById(R.id.writeText_et); takePhoto.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v){//创建file对象用于存储拍照后的图片 File outputImage = new File (Environment.getExternalStorageDirectory(),"output_image.jpg"); try{ if (outputImage.exists()){outputImage.delete();} outputImage.createNewFile(); }catch(IOException e){ e.printStackTrace(); } imageUri = Uri.fromFile(outputImage); Intent intent = new Intent ("android.media.action.IMAGE_CAPTURE"); intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri); startActivityForResult(intent,TAKE_PHOTO);//启动相机程序 } }); chooseFromAlbum.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v){ Intent intent = new Intent("android.intent.action.GET_CONTENT"); intent.setType("image/*"); startActivityForResult(intent,CHOOSE_PHOTO);//打开相册 } }); //输入框 editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.toString().equals("")) { tvInImage.setVisibility(View.INVISIBLE); } else { tvInImage.setVisibility(View.VISIBLE); tvInImage.setText(s); } } @Override public void afterTextChanged(Editable s) { } }); final GestureDetector gestureDetector = new GestureDetector(this, new SimpleGestureListenerImpl()); //移动 tvInImage.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { gestureDetector.onTouchEvent(event); return true; } }); findViewById(R.id.y).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = getPackageManager().getLaunchIntentForPackage("com.android.soundrecorder"); if (intent == null) { Toast.makeText(getApplicationContext(), "抱歉,没有找到您的录音机", Toast.LENGTH_SHORT).show(); } else{ startActivity(intent);} } }); findViewById(R.id.back).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); findViewById(R.id.share).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_SEND); Bitmap bm = loadBitmapFromView(containerView); bm= comp(bm); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_hhmmss",Locale.SIMPLIFIED_CHINESE); String filePath = Environment.getExternalStorageDirectory() +File.separator +sdf.format(new Date()) + ".jpg"; try { bm.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(filePath)); Toast.makeText(PhotoAct.this, "图片已保存", Toast.LENGTH_SHORT).show(); intent.setType("image/jpg"); File f=new File(filePath); Uri u = Uri.fromFile(f); intent.putExtra(Intent.EXTRA_STREAM, u); startActivity(intent); } catch (FileNotFoundException e) { e.printStackTrace(); } } }); } protected void onActivityResult(int requestCode,int resultCode,Intent data){ switch (requestCode){ case TAKE_PHOTO: if(resultCode ==RESULT_OK){ Intent intent= new Intent("com.android.camera.action.CROP"); intent.setDataAndType(imageUri, "image/*"); intent.putExtra("scale",true); intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri); startActivityForResult(intent,CROP_PHOTO);//启动裁剪程序 }break; case CROP_PHOTO: if(resultCode ==RESULT_OK){ try{ Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri)); picture.setImageBitmap(bitmap);//将裁剪后的照片显示出来 picture.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { public void onGlobalLayout() { picture.getViewTreeObserver().removeGlobalOnLayoutListener(this); imagePositionX = picture.getX(); imagePositionY = picture.getY(); imageWidth =picture.getWidth(); imageHeight =picture.getHeight(); //设置文本大小 tvInImage.setMaxWidth((int) imageWidth); } }); }catch(FileNotFoundException e ){ e.printStackTrace(); } } break; case CHOOSE_PHOTO: if(resultCode == RESULT_OK){//判断手机系统版本号 if(Build.VERSION.SDK_INT>=19){//4.4及以上系统使用这个方法处理图片 handleImageOnKitKat(data); }else{//4.4及以下系统使用这个方法处理图片 handleImageBeforeKitKat(data); } }break; default:break; } } @TargetApi(19) private void handleImageOnKitKat(Intent data){ String imagePath = null; Uri uri = data.getData(); if(DocumentsContract.isDocumentUri(PhotoAct.this, uri)){//如果是document类型的Uri,则通过document id处理 String docId = DocumentsContract.getDocumentId(uri); if("com.android.providers.media.documents".equals(uri.getAuthority())){ String id = docId.split(":")[1];//解析出数字格式的Id String selection = MediaStore.Images.Media._ID + "=" +id; imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection); }else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){ Uri contentUri =ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId)); imagePath = getImagePath(contentUri,null); } }else if("content".equalsIgnoreCase(uri.getScheme())){//如果不是document类型的Uri则使用普通方式处理 imagePath = getImagePath(uri,null); } displayImage(imagePath);//根据图片路径显示图片/////////////////////////////////////////////////////////////////////////////////////// picture.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { public void onGlobalLayout() { picture.getViewTreeObserver().removeGlobalOnLayoutListener(this); imagePositionX = picture.getX(); imagePositionY = picture.getY(); imageWidth =picture.getWidth(); imageHeight =picture.getHeight(); //设置文本大小 tvInImage.setMaxWidth((int) imageWidth); } });} private void handleImageBeforeKitKat(Intent data){ Uri uri = data.getData(); String imagePath = getImagePath(uri,null); displayImage(imagePath);////////////////////////////////////////////////////////////////////////////////////////////////////// picture.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { public void onGlobalLayout() { picture.getViewTreeObserver().removeGlobalOnLayoutListener(this); imagePositionX = picture.getX(); imagePositionY = picture.getY(); imageWidth =picture.getWidth(); imageHeight =picture.getHeight(); //设置文本大小 tvInImage.setMaxWidth((int) imageWidth); } });} private String getImagePath(Uri uri,String selection){ String path =null;//通过Uri 和selection 来获取真实的图片路径 Cursor cursor = getContentResolver().query(uri, null, selection, null, null); if(cursor != null){ if(cursor.moveToFirst()){ path = cursor.getString(cursor.getColumnIndex(Media.DATA)); } cursor.close(); } return path; } private void displayImage(String imagePath){ if(imagePath != null){ Bitmap bitmap = BitmapFactory.decodeFile(imagePath); picture.setImageBitmap(bitmap); }else{ Toast.makeText(PhotoAct.this, "操作失败", Toast.LENGTH_SHORT).show(); } } //以图片形式获取View显示的内容(类似于截图) public static Bitmap loadBitmapFromView(View view) { Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); view.draw(canvas); return bitmap; } private int count = 0; //tvInImage的x方向和y方向移动量 private float mDx, mDy; //移动 private class SimpleGestureListenerImpl extends GestureDetector.SimpleOnGestureListener { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { //向右移动时,distanceX为负;向左移动时,distanceX为正 //向下移动时,distanceY为负;向上移动时,distanceY为正 count++; mDx -= distanceX; mDy -= distanceY; //边界检查 mDx = calPosition(imagePositionX - tvInImage.getX(), imagePositionX + imageWidth - (tvInImage.getX() + tvInImage.getWidth()), mDx); mDy = calPosition(imagePositionY - tvInImage.getY(), imagePositionY + imageHeight - (tvInImage.getY() + tvInImage.getHeight()), mDy); //控制刷新频率 if (count % 5 == 0) { tvInImage.setX(tvInImage.getX() + mDx); tvInImage.setY(tvInImage.getY() + mDy); } return true; } } //计算正确的显示位置(不能超出边界) private float calPosition(float min, float max, float current) { if (current < min) { return min; } if (current > max) { return max; } return current; } //获取压缩后的bitmap private Bitmap comp(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos); if( baos.toByteArray().length / 1024>1024) {//判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出 baos.reset();//重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%,把压缩后的数据存放到baos中 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray()); BitmapFactory.Options newOpts = new BitmapFactory.Options(); //开始读入图片,此时把options.inJustDecodeBounds 设回true了 newOpts.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts); newOpts.inJustDecodeBounds = false; int w = newOpts.outWidth; int h = newOpts.outHeight; //现在主流手机比较多是800*480分辨率,所以高和宽我们设置为 float hh = 800f;//这里设置高度为800f float ww = 480f;//这里设置宽度为480f //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可 int be = 1;//be=1表示不缩放 if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放 be = (int) (newOpts.outWidth / ww); } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放 be = (int) (newOpts.outHeight / hh); } if (be <= 0) be = 1; newOpts.inSampleSize = be;//设置缩放比例 //重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了 isBm = new ByteArrayInputStream(baos.toByteArray()); bitmap = BitmapFactory.decodeStream(isBm, null, newOpts); //return comp(bitmap)//压缩好比例大小后再进行质量压缩 \ return bitmap; } }
/* Steven Croft homework 3 volume of a cube */ public class VolumeOfACube { public static void main (String [] args) { //variables double length; double height; double width; double volume; //assign variables length = 10; height = 10; width = 10; //assign volume equation volume = length * height * width; //output System.out.println("The volume of the cube is " + volume); } }
package com.syscxp.biz.core.exception; import com.syscxp.biz.core.base.BaseError; /** * @Author: sunxuelong. * @Cretion Date: 2018-05-10. * @Description: . */ public class BaseException extends RuntimeException { private BaseError baseError; private String message; public BaseException() { super(); } public BaseException(BaseError baseError) { super(baseError.error()); this.baseError = baseError; this.message = baseError.error(); } public BaseException(BaseError baseError,Throwable e) { super(baseError.error(),e); this.baseError = baseError; this.message = baseError.error(); } public BaseException(String message) { super(message); this.message = message; } public BaseException(String message, Throwable cause) { super(message, cause); } public BaseError getBaseError() { return baseError; } public void setBaseError(BaseError baseError) { this.baseError = baseError; } @Override public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
package com.ehy.utils;/** * Created by Administrator on 2018-7-17. */ import org.apache.shiro.crypto.hash.Md5Hash; /** * @Author zhouyu * @Date2018-7-17 8:56 **/ public class MD5 { /*source 明文密码 *salt 盐 *hashIterations 哈希次数 */ public static String getMd5Hash(String userName, String password) { Md5Hash md5Hash = new Md5Hash(password, userName, 3); return md5Hash.toString(); } }
/** * A number can be broken into different continguous sub-subsequence parts * Suppose, a number 3245 can be broken into parts like 3 2 4 5 32 24 45 324 245. And this number is a COLORFUL number, since product of every digit of a contiguous subsequence is different. N = 23 2 3 23 2 -> 2 3 -> 3 23 -> 6 this number is a COLORFUL number since product of every digit of a sub-sequence are different. */ import java.util.HashSet; public class ColorfulNum { // function returns 1 if integer is a colorful else return 0 public static int colorful(int n) { if(n <= 0) { return 0; } HashSet<Integer> set = new HashSet<>(); int prod; String a = String.valueOf(n); for(int i = 0; i < a.length(); i++) { prod = 1; for(int j = i; j < a.length(); j++) { prod *= a.charAt(j) - '0'; if(!set.contains(prod)) { set.add(prod); } else { return 0; } } } return 1; } // main method public static void main(String args[]) { int n = 23; int colorFul = colorful(n); System.out.println(colorFul); } }
package br.com.fibonacci; public class Main { public static void main(String[] args) { Fibonacci f = new Fibonacci(); f.calcFibonacci(); } }
package com.tpv.storagefiletest.application; import android.app.Application; import android.content.Context; import com.tpv.storagefiletest.domain.FileInfo; import com.tpv.storagefiletest.domain.StorageInfo; import com.tpv.storagefiletest.domain.StorageState; import com.tpv.storagefiletest.domain.TestCase; import com.tpv.storagefiletest.domain.TestInfo; import com.tpv.storagefiletest.domain.TransResult; import java.util.ArrayList; /** * Created by Jack.Weng on 2017/6/25. */ public class MyApplication extends Application { private static final String TAG = "MyApplication"; private static Context mContext; private FileInfo mFileInfo = null; private StorageInfo mStorageInfo = null; private StorageState mStorageState = null; private TestCase mTestCase = null; private TestInfo mTestInfo = null; private TransResult mTransResult = null; private ArrayList<TransResult> mResults = null; @Override public void onCreate() { super.onCreate(); MyApplication.mContext = getApplicationContext(); } public static Context getAppContext() { return MyApplication.mContext; } public FileInfo getFileInfo() { return mFileInfo; } public void setFileInfo(FileInfo fileInfo) { if (null != mFileInfo) mFileInfo = null; mFileInfo = fileInfo; } public StorageInfo getStorageInfo() { return mStorageInfo; } public void setStorageInfo(StorageInfo storageInfo) { if (null != mStorageInfo) mStorageInfo = null; mStorageInfo = storageInfo; } public TestCase getTestCase() { return mTestCase; } public void setTestCase(TestCase testCase) { if (null != mTestCase) mTestCase = null; mTestCase = testCase; } public TestInfo getTestInfo() { return mTestInfo; } public void setTestInfo(TestInfo testInfo) { if (null != mTestInfo) mTestInfo = null; mTestInfo = testInfo; } public TransResult getTransResult() { return mTransResult; } public void setTransResult(TransResult transResult) { if (null != mTransResult) mTransResult = null; mTransResult = transResult; } public ArrayList<TransResult> getResults() { return mResults; } public void setResults(ArrayList<TransResult> results) { if (null != mResults && mResults.size() > 0) { mResults = null; } mResults = results; } }
package com.guang.bishe.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.guang.bishe.domain.Product; import com.guang.bishe.domain.ProductExample; import com.guang.bishe.domain.Productimg; import com.guang.bishe.domain.ProductimgExample; import com.guang.bishe.mapper.ProductMapper; import com.guang.bishe.mapper.ProductimgMapper; import com.guang.bishe.service.PageService; import com.guang.bishe.service.dto.PageResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class PageServiceImpl implements PageService { @Autowired private ProductMapper productMapper; @Autowired private ProductimgMapper productimgMapper; @Override public PageResult getProductList(int page, int row, int status, double min, double max, String word) { //根据输入条件,进行组合查询 ProductExample example1 = new ProductExample(); ProductExample.Criteria criteria1 = example1.createCriteria(); //确定最高价和最低价 criteria1.andProductPriceBetween(min, max); //上架的才显示 不上架的不显示 criteria1.andProductIsSellEqualTo("1"); //判断商品的状态 if (status != 0) { if (status == 1) { //按照最新查询 example1.setOrderByClause("product_id DESC"); } else { //按照卖出最多查询 example1.setOrderByClause("product_hass_selled DESC"); } } //根据搜索的关键词在进行查询 if (word != null) { criteria1.andProductNameLike("%" + word + "%"); } //执行查询 PageHelper.startPage(page, row); List<Product> productList = productMapper.selectByExample(example1); PageInfo pageInfo = new PageInfo(productList); //总页数 int totalPages = pageInfo.getPages(); for (Product product : productList) { ProductimgExample example2 = new ProductimgExample(); ProductimgExample.Criteria criteria2 = example2.createCriteria(); criteria2.andProductIdEqualTo(product.getProductId()); List<Productimg> productImgList = productimgMapper.selectByExample(example2); if (productImgList.size() == 0) { product.setProductPicture("static/img/defult.jpg"); } else { //因为可能上传多张图片,这里取一张显示 product.setProductPicture(productImgList.get(0).getImgurl()); } } return PageResult.buid(page, productList, totalPages); } }
package cn.hustxq.hust.controller; import cn.hustxq.hust.bean.Header; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; /** * @Author hustxq. * @Date 2017/9/20 16:41 */ @Controller //@RequestMapping("/hust") public class IndexController { @RequestMapping("") public String index(ModelMap map){ // map.addAttribute("v",new Header()); // 添加对象. map.addAttribute("v","testJs"); return "home"; } @RequestMapping("/include") public String include(ModelMap map){ map.addAttribute("head",new Header()); // 添加对象 return "include"; } @RequestMapping("/json") @ResponseBody public Map json(){ Map map = new HashMap<>(); map.put("name","xq"); return map; } @RequestMapping("/tabs") public String dev(){ return "tabbar"; } @RequestMapping("/e") public String employee(){ return "employee"; } @RequestMapping("/u") public String upRefresh(){ return "ptr"; } @RequestMapping("/home") public String home(){ return "home"; } }
package com.aidigame.hisun.imengstar.ui; import com.aidigame.hisun.imengstar.PetApplication; import com.aidigame.hisun.imengstar.constant.Constants; import com.aidigame.hisun.imengstar.util.StringUtil; import com.aidigame.hisun.imengstar.util.UiUtil; import com.aidigame.hisun.imengstar.widget.WeixinShare; import com.aidigame.hisun.imengstar.R; import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.AbsListView; import android.widget.FrameLayout; import android.widget.Toast; import android.widget.AbsListView.OnScrollListener; import android.widget.TextView; public class AboutUsActivity extends BaseActivity implements OnClickListener{ // FrameLayout frameLayout; // View viewTopWhite; private TextView agreementTV; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_about_us); setBlurImageBackground(); TextView versionTv=(TextView)findViewById(R.id.textView3); TextView focusXinLang=(TextView)findViewById(R.id.textView4); TextView focusWeiXin=(TextView)findViewById(R.id.textView5); TextView mailBox=(TextView)findViewById(R.id.textView8); TextView copyRight=(TextView)findViewById(R.id.textView10); agreementTV=(TextView)findViewById(R.id.textView6); focusWeiXin.setOnClickListener(this); focusXinLang.setOnClickListener(this); agreementTV.setOnClickListener(this); versionTv.setText("V"+StringUtil.getAPKVersionName(this)); findViewById(R.id.imageView1).setOnClickListener(this); } private void setBlurImageBackground() { // TODO Auto-generated method stub // frameLayout=(FrameLayout)findViewById(R.id.framelayout); // viewTopWhite=(View)findViewById(R.id.top_white_view); } @Override public void onClick(View arg0) { // TODO Auto-generated method stub switch (arg0.getId()) { case R.id.imageView1: if(isTaskRoot()){ if(HomeActivity.homeActivity!=null){ ActivityManager am=(ActivityManager)getSystemService(Context.ACTIVITY_SERVICE); am.moveTaskToFront(HomeActivity.homeActivity.getTaskId(), 0); }else{ Intent intent=new Intent(this,HomeActivity.class); this.startActivity(intent); } } this.finish(); System.gc(); break; case R.id.textView4: Uri uri=Uri.parse("http://weibo.com/u/5252680717"); Intent intent=new Intent(Intent.ACTION_VIEW,uri); startActivity(intent); break; case R.id.textView5: break; case R.id.textView6: Intent intent2=new Intent(this,WarningDialogActivity.class); intent2.putExtra("mode", 7); this.startActivity(intent2); break; } } }
package com.evan.demo.yizhu.shouye; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.evan.demo.yizhu.R; import com.evan.demo.yizhu.keting; import com.evan.demo.yizhu.yushi; import java.util.ArrayList; public class fangkejilu_all extends Fragment { private View rootView; @Override public void onAttach(Context context){ super.onAttach(context); } @Override public View onCreateView(@Nullable LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ rootView = inflater.inflate(R.layout.fragment_fangkejilu_all,container,false); initUi(); return rootView; } private void initUi(){ //这里写加载布局的代码 } @Override public void onActivityCreated(Bundle savedInstanceState){ super.onActivityCreated(savedInstanceState); //这里写逻辑代码 } }
package com.gaoshin.coupon.android; public class BusinessException extends RuntimeException { private ServiceError errorCode; private String data; public BusinessException(ServiceError errorCode) { super("Error code: " + errorCode); this.errorCode = errorCode; } public BusinessException(ServiceError errorCode, Throwable t) { super("Error code: " + errorCode, t); this.errorCode = errorCode; data = WebClient.getStackTrace(t); } public BusinessException(ServiceError errorCode, String errorMessage) { super(errorMessage); this.errorCode = errorCode; } public void setData(String data) { this.data = data; } public String getData() { return data; } public ServiceError getErrorCode() { return errorCode; } }
/* * Copyright © 2018 www.noark.xyz All Rights Reserved. * * 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 ! * 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件: * * http://www.noark.xyz/LICENSE * * 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播; * 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本; * 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利; * 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明! */ package xyz.noark.core.thread; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * 可命名的线程工厂. * * @author 小流氓[176543888@qq.com] * @since 3.0 */ public class NamedThreadFactory implements ThreadFactory { private final AtomicInteger threadCounter = new AtomicInteger(1); private final String name; private final boolean hasSuffix; private final ThreadGroup group; public NamedThreadFactory(String name) { this(name, true); } public NamedThreadFactory(String name, boolean hasSuffix) { final SecurityManager securitymanager = System.getSecurityManager(); this.group = securitymanager == null ? Thread.currentThread().getThreadGroup() : securitymanager.getThreadGroup(); this.name = name; this.hasSuffix = hasSuffix; } @Override public Thread newThread(Runnable runnable) { StringBuilder threadName = new StringBuilder(56); threadName.append(name); if (hasSuffix) { threadName.append("-").append(threadCounter.getAndIncrement()); } Thread thread = new Thread(group, runnable, threadName.toString()); if (thread.isDaemon()) { thread.setDaemon(false); } if (thread.getPriority() != Thread.NORM_PRIORITY) { thread.setPriority(Thread.NORM_PRIORITY); } return thread; } }
package org.robotframework.formslibrary.keyword; import org.robotframework.formslibrary.operator.TabOperator; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords; @RobotKeywords public class TabKeywords { @RobotKeyword("Select a tab by name.\n\n Example:\n | Select Forms Tab | _name_ | \n") @ArgumentNames({ "tabname" }) public void selectFormsTab(String name) { new TabOperator().select(name); } }
public class ReverseInteger7 { public static void main(String[] args) { System.out.println(reverse(123)); } public static int reverse(int x) { int ans = 0; while (x != 0) { // != will deal with negative. if (ans > Integer.MAX_VALUE / 10) { //check if out of the boundary. return 0; } if (ans < Integer.MIN_VALUE / 10) { return 0; } ans = ans * 10 + x % 10; x = x / 10; System.out.println(ans); } return ans; } }
package cz.metacentrum.perun.spRegistration.common.enums; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; public enum AuditMessageType { UNKNOWN(-1), REQUEST_REG_SERVICE_CREATED(0), REQUEST_UPDATE_SERVICE_CREATED(1), REQUEST_TRANSFER_SERVICE_CREATED(2), REQUEST_REMOVE_SERVICE_CREATED(3), REQUEST_APPROVED(4), REQUEST_REJECTED(5), REQUEST_CHANGES_REQUEST(6), REQUEST_UPDATED(7), REQUEST_CANCELED(8); private final int value; private static final Map<Integer, AuditMessageType> lookup = new HashMap<>(); static { for (AuditMessageType status : EnumSet.allOf(AuditMessageType.class)) { lookup.put(status.value, status); } } AuditMessageType(int value) { this.value = value; } public int getValue() { return value; } public static AuditMessageType resolve(int code) { return lookup.get(code); } }
package ro.fr33styler.frconomy.account; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import ro.fr33styler.frconomy.FrConomy; public class Accounts { private FrConomy main; private Map<UUID, Account> cached = new HashMap<>(); public Accounts(FrConomy main) { this.main = main; } public Map<UUID, Account> getCached() { return cached; } public void onJoin(Player p) { Account account = new Account(p.getUniqueId(), p.getName()); account.setBalance(main.getDefaultMoney()); main.getSQLDatabase().getOrInsertAccountAsync(account); cached.put(p.getUniqueId(), account); } public void onQuit(Player p) { Account account = cached.remove(p.getUniqueId()); if (account != null) { main.getSQLDatabase().updateAccountAsync(account); } } public boolean createAccount(OfflinePlayer player) { Account account = cached.get(player.getUniqueId()); if (account == null) { account = new Account(player); account.setBalance(main.getDefaultMoney()); if (!main.getSQLDatabase().hasAccount(account)) { return main.getSQLDatabase().createAccount(account); } } return false; } public Account getAccount(OfflinePlayer player) { Account account = cached.get(player.getUniqueId()); if (account == null) { account = new Account(player); main.getSQLDatabase().getAccount(account, null); } return account; } public boolean hasAccount(OfflinePlayer player) { Account account = cached.get(player.getUniqueId()); if (account == null) { return main.getSQLDatabase().hasAccount(new Account(player)); } return true; } }