text
stringlengths
10
2.72M
package com.examples.io.heaps; import java.util.ArrayList; import java.util.List; import java.util.PriorityQueue; public class MergeKSortedLists { public static void main(String[] args) { Node head1 = new Node(1); head1.next = new Node(3); head1.next.next = new Node(5); Node head2 = new Node(2); head2.next = new Node(4); head2.next.next = new Node(7); Node head3 = new Node(6); head3.next = new Node(8); head3.next.next = new Node(9); List<Node> nodes = new ArrayList<>(); nodes.add(head1); nodes.add(head2); nodes.add(head3); MergeKSortedLists mergeKSortedLists = new MergeKSortedLists(); Node node = mergeKSortedLists.mergeKSortedLists(nodes); node.printNode(node); } public Node mergeKSortedLists(List<Node> lists) { PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(); for (Node head : lists) { while (head != null) { priorityQueue.add(head.data); head = head.next; } } Node dummy = new Node(-1); Node head = dummy; System.out.println("size " + priorityQueue.size()); while (!priorityQueue.isEmpty()) { head.next = new Node(priorityQueue.poll()); head = head.next; } return dummy.next; } } class Node { int data; Node next; Node(int d) { data = d; next = null; } public void printNode(Node head) { while (head != null) { System.out.println(head.data); head = head.next; } } }
package com.kuang.生产者消费者; public class A { public static void main(String[] args) { Thing th=new Thing(); new Thread(()->{ for(int i=1;i<=500;i++) { try { th.decrement(); } catch (InterruptedException e) { e.printStackTrace(); } } },"A").start(); new Thread(()->{ for(int i=1;i<=500;i++) { try { th.increment(); } catch (InterruptedException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } },"B").start(); new Thread(()->{ for(int i=1;i<=500;i++) { try { th.decrement(); } catch (InterruptedException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } },"C").start(); new Thread(()->{ for(int i=1;i<=500;i++) { try { th.increment(); } catch (InterruptedException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } },"D").start(); } } class Thing{ public static int number=0; public synchronized void increment() throws Exception { while(number!=0){ this.wait(); } number++; System.out.println(Thread.currentThread().getName()+"----number增加到:"+number); this.notifyAll(); } public synchronized void decrement() throws InterruptedException { while(number==0){ this.wait(); } number--; System.out.println(Thread.currentThread().getName()+"----number减少到:"+number); this.notifyAll(); } }
package sr.hakrinbank.intranet.api.dto; /** * Created by clint on 6/5/17. */ public class RelationshipAccountManagerDto extends RelationshipAccountBasisDto{ private Long businessAccountType; private Long relationshipManager; public Long getRelationshipManager() { return relationshipManager; } public void setRelationshipManager(Long relationshipManager) { this.relationshipManager = relationshipManager; } public Long getBusinessAccountType() { return businessAccountType; } public void setBusinessAccountType(Long businessAccountType) { this.businessAccountType = businessAccountType; } }
package notebook; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class note { static ArrayList<String> Title_list = new ArrayList<>(); static ArrayList<String> Content_list = new ArrayList<>(); static ArrayList<String> Status_list = new ArrayList<>(); public static void main(String[] args) { while(true) { System.out.println("输入1添加,输入2删除,输入3改变状态,输入4查询,输入其他退出"); int number = InputInt(); if(number==1) { if(Add()) System.out.println("添加成功"); } else if (number==2) { int index1 = InputInt(); if(Delete(index1)) System.out.println("删除成功"); else { System.out.println("删除失败"); } } else if(number==3) { System.out.println("请输入要删除的事项的序号:"); int index2 = InputInt(); if(Change_status(index2)) System.out.println("改变状态"); else { System.out.println("改变状态失败"); } } else if (number==4) { printf_list(); } else { System.out.println("结束了"); break; } } } public static String InputString() { Scanner scanner = new Scanner(System.in); String s = scanner.nextLine(); return s; } public static int InputInt() { Scanner scanner = new Scanner(System.in); int x = scanner.nextInt(); return x; } public static boolean Delete(int index) { if (index<=Title_list.size()) { Title_list.remove(index-1); Content_list.remove(index-1); Status_list.remove(index-1); return true; } else { return false; } } public static boolean Add() { String string1 = InputString(); Title_list.add(string1); String string2 = InputString(); Content_list.add(string2); Status_list.add("未完成"); return true; } public static boolean Change_status(int index) { if (index<=Title_list.size()) { Status_list.set(index-1,"已完成"); return true; } else { return false; } } public static boolean printf_list() { int i; for(i=0;i<Title_list.size();i++) { System.out.println("标题: "+Title_list.get(i)); System.out.println("内容: "+Content_list.get(i)); System.out.println("属性: "+Status_list.get(i)); } return true; } }
package it.onyx.Login.util; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import javax.servlet.ServletContext; public class StmtCreator { //static Logger logger = Logger.getLogger(Factory_connection.class); public static String getQuery (String query, ServletContext servletContext) { String outQuery; Properties prop = new Properties(); try { InputStream fis = servletContext.getResourceAsStream("/WEB-INF/query.properties"); prop.load(fis); }catch (FileNotFoundException e){ System.out.println("can't load input-stream"); e.printStackTrace(); }catch (IOException e) { System.out.println("troubles with properties variable"); } outQuery = prop.getProperty(query); return outQuery; } }
package com.cninnovatel.ev.db; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit. /** * Entity mapped to table "REST_CALL_ROW_". */ public class RestCallRow_ { private Long id; private String peerSipNum; private Boolean isOutgoing; private Boolean isVideoCall; private Long startTime; private Long duration; public RestCallRow_() { } public RestCallRow_(Long id) { this.id = id; } public RestCallRow_(Long id, String peerSipNum, Boolean isOutgoing, Boolean isVideoCall, Long startTime, Long duration) { this.id = id; this.peerSipNum = peerSipNum; this.isOutgoing = isOutgoing; this.isVideoCall = isVideoCall; this.startTime = startTime; this.duration = duration; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getPeerSipNum() { return peerSipNum; } public void setPeerSipNum(String peerSipNum) { this.peerSipNum = peerSipNum; } public Boolean getIsOutgoing() { return isOutgoing; } public void setIsOutgoing(Boolean isOutgoing) { this.isOutgoing = isOutgoing; } public Boolean getIsVideoCall() { return isVideoCall; } public void setIsVideoCall(Boolean isVideoCall) { this.isVideoCall = isVideoCall; } public Long getStartTime() { return startTime; } public void setStartTime(Long startTime) { this.startTime = startTime; } public Long getDuration() { return duration; } public void setDuration(Long duration) { this.duration = duration; } }
// Generated code from Butter Knife. Do not modify! package com.zhicai.byteera.activity.product; import android.view.View; import butterknife.ButterKnife.Finder; import butterknife.ButterKnife.ViewBinder; public class ProductFragment$$ViewBinder<T extends com.zhicai.byteera.activity.product.ProductFragment> implements ViewBinder<T> { @Override public void bind(final Finder finder, final T target, Object source) { View view; view = finder.findRequiredView(source, 2131428103, "field 'mPager' and method 'onPageSelected'"); target.mPager = finder.castView(view, 2131428103, "field 'mPager'"); ((android.support.v4.view.ViewPager) view).setOnPageChangeListener( new android.support.v4.view.ViewPager.OnPageChangeListener() { @Override public void onPageSelected( int p0 ) { target.onPageSelected(p0); } @Override public void onPageScrolled( int p0, float p1, int p2 ) { } @Override public void onPageScrollStateChanged( int p0 ) { } }); view = finder.findRequiredView(source, 2131428102, "field 'qiehuan' and method 'clickListener'"); target.qiehuan = finder.castView(view, 2131428102, "field 'qiehuan'"); view.setOnClickListener( new butterknife.internal.DebouncingOnClickListener() { @Override public void doClick( android.view.View p0 ) { target.clickListener(); } }); view = finder.findRequiredView(source, 2131427653, "field 'topHead'"); target.topHead = view; view = finder.findRequiredView(source, 2131427663, "field 'mIndicator'"); target.mIndicator = finder.castView(view, 2131427663, "field 'mIndicator'"); } @Override public void unbind(T target) { target.mPager = null; target.qiehuan = null; target.topHead = null; target.mIndicator = null; } }
package br.com.sergio.app.service; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import br.com.sergio.app.model.dao.GrupoContaDao; @Service public class GrupoContaService { @Autowired private GrupoContaDao dao; public Long salvar(Long id, String nome){ if(id != null && id.longValue() > 0){ dao.edita(id, nome); return id; } else { return dao.adiciona(nome); } } public boolean remove(Long id){ try { dao.remove(id); return true; } catch (Exception e){ return false; } } public String buscaNome(Long id){ return dao.buscaNome(id); } public Map<Long, String> lista(){ Map<Long, String> linkedHashMap = new LinkedHashMap<>(); List<Map<Long,String>> lista = dao.lista(); for(Map<Long,String> map : lista){ Entry<Long, String> entry = map.entrySet().iterator().next(); Long key = entry.getKey(); String value = entry.getValue(); linkedHashMap.put(key, value); } return linkedHashMap; } }
package program; @SuppressWarnings("serial") public class MainWindow extends javax.swing.JFrame { public MainWindow() throws java.awt.HeadlessException { super("My Program"); initGui(); } private void initGui() { javax.swing.JPanel contentPane = new javax.swing.JPanel(); contentPane.setLayout(new javax.swing.BoxLayout(contentPane, javax.swing.BoxLayout.Y_AXIS)); javax.swing.JTextField ad = new javax.swing.JTextField(20); contentPane.add(ad); javax.swing.JTextField soyad = new javax.swing.JTextField(20); contentPane.add(soyad); javax.swing.JButton ok = new javax.swing.JButton(); ok.setText("Ok"); ok.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { javax.swing.JOptionPane.showMessageDialog(getThis(), "ok tusuna tiklandi."); } }); contentPane.add(ok); setContentPane(contentPane); } public MainWindow getThis() { return this; } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { startGui(); } }); } public static void startGui() { MainWindow mainWindow = new MainWindow(); mainWindow .setDefaultCloseOperation(javax.swing.JFrame.DISPOSE_ON_CLOSE); mainWindow.pack(); mainWindow.setVisible(true); } }
package network.nerve.converter.rpc.cmd; import io.nuls.base.RPCUtil; import io.nuls.base.basic.AddressTool; import io.nuls.base.basic.NulsByteBuffer; import io.nuls.base.basic.TransactionFeeCalculator; import io.nuls.base.data.CoinData; import io.nuls.base.data.CoinFrom; import io.nuls.base.data.CoinTo; import io.nuls.base.data.Transaction; import io.nuls.base.signture.P2PHKSignature; import io.nuls.base.signture.TransactionSignature; import io.nuls.core.constant.TxType; import io.nuls.core.crypto.HexUtil; import io.nuls.core.exception.NulsException; import io.nuls.core.log.Log; import io.nuls.core.model.BigIntegerUtils; import io.nuls.core.parse.JSONUtils; import io.nuls.core.rpc.info.Constants; import io.nuls.core.rpc.info.HostInfo; import io.nuls.core.rpc.info.NoUse; import io.nuls.core.rpc.model.ModuleE; import io.nuls.core.rpc.model.message.Response; import io.nuls.core.rpc.netty.processor.ResponseMessageProcessor; import io.nuls.core.rpc.util.NulsDateUtils; import network.nerve.converter.constant.ConverterCmdConstant; import network.nerve.converter.constant.ConverterErrorCode; import network.nerve.converter.enums.ProposalTypeEnum; import network.nerve.converter.enums.ProposalVoteChoiceEnum; import network.nerve.converter.enums.ProposalVoteRangeTypeEnum; import network.nerve.converter.model.bo.Chain; import network.nerve.converter.model.bo.ConfigBean; import network.nerve.converter.model.bo.NonceBalance; import network.nerve.converter.model.dto.SignAccountDTO; import network.nerve.converter.model.dto.WithdrawalTxDTO; import network.nerve.converter.model.txdata.WithdrawalTxData; import network.nerve.converter.rpc.call.BaseCall; import network.nerve.converter.rpc.call.LedgerCall; import network.nerve.converter.utils.ConverterUtil; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static network.nerve.converter.constant.ConverterConstant.DISTRIBUTION_FEE_10; public class CvTest { /* static String address20 = "tNULSeBaMvEtDfvZuukDf2mVyfGo3DdiN8KLRG"; static String address21 = "tNULSeBaMnrs6JKrCy6TQdzYJZkMZJDng7QAsD"; static String address22 = "tNULSeBaMrbMRiFAUeeAt6swb4xVBNyi81YL24"; static String address23 = "tNULSeBaMu38g1vnJsSZUCwTDU9GsE5TVNUtpD"; static String address24 = "tNULSeBaMp9wC9PcWEcfesY7YmWrPfeQzkN1xL"; static String address25 = "tNULSeBaMshNPEnuqiDhMdSA4iNs6LMgjY6tcL"; static String address26 = "tNULSeBaMoodYW7AqyJrgYdWiJ6nfwfVHHHyXm"; static String address27 = "tNULSeBaMmTNYqywL5ZSHbyAQ662uE3wibrgD1"; static String address28 = "tNULSeBaMoNnKitV28JeuUdBaPSR6n1xHfKLj2"; static String address29 = "tNULSeBaMqywZjfSrKNQKBfuQtVxAHBQ8rB2Zn"; static String address30 = "tNULSeBaMfQ6VnRxrCwdU6aPqdiPii9Ks8ofUQ"; static String address31 = "tNULSeBaMrbmG67VrTJeZswv4P2uXXKoFMa6RH"; */ static String address20 = "TNVTdTSPVcqUCdfVYWwrbuRtZ1oM6GpSgsgF5"; static String address21 = "TNVTdTSPNEpLq2wnbsBcD8UDTVMsArtkfxWgz"; static String address22 = "TNVTdTSPRyJgExG4HQu5g1sVxhVVFcpCa6fqw"; static String address23 = "TNVTdTSPUR5vYdstWDHfn5P8MtHB6iZZw3Edv"; static String address24 = "TNVTdTSPPXtSg6i5sPPrSg3TfFrhYHX5JvMnD"; static String address25 = "TNVTdTSPT5KdmW1RLzRZCa5yc7sQCznp6fES5"; static String address26 = "TNVTdTSPPBao2pGRc5at7mSdBqnypJbMqrKMg"; static String address27 = "TNVTdTSPLqKoNh2uiLAVB76Jyq3D6h3oAR22n"; static String address28 = "TNVTdTSPNkjaFbabm5P73m7VHBRQef4NDsgYu"; static String address29 = "TNVTdTSPRMtpGNYRx98WkoqKnExU9pWDQjNPf"; static String address30 = "TNVTdTSPEn3kK94RqiMffiKkXTQ2anRwhN1J9"; static String address31 = "TNVTdTSPRyiWcpbS65NmT5qyGmuqPxuKv8SF4"; private Chain chain; static int chainId = 5; static int assetId = 1; static int heterogeneousChainId = 101; static int bnbChainId = 102; static int heterogeneousAssetId = 1; static String version = "1.0"; static String password = "nuls123456";//"nuls123456"; @Before public void before() throws Exception { NoUse.mockModule(); ResponseMessageProcessor.syncKernel("ws://" + HostInfo.getLocalIP() + ":7771"); chain = new Chain(); chain.setConfig(new ConfigBean(chainId, assetId, "UTF-8")); } @Test public void importPriKeyTest() { // 公钥: 037fae74d15153c3b55857ca0abd5c34c865dfa1c0d0232997c545bae5541a0863 importPriKey("b54db432bba7e13a6c4a28f65b925b18e63bcb79143f7b894fa735d5d3d09db5", password);//种子出块地址 tNULSeBaMkrt4z9FYEkkR9D6choPVvQr94oYZp TNVTdTSPLEqKWrM7sXUciM2XbYPoo3xDdMtPd // 公钥: 036c0c9ae792f043e14d6a3160fa37e9ce8ee3891c34f18559e20d9cb45a877c4b // importPriKey("188b255c5a6d58d1eed6f57272a22420447c3d922d5765ebb547bc6624787d9f", password);//种子出块地址 tNULSeBaMoGr2RkLZPfJeS5dFzZeNj1oXmaYNe TNVTdTSPNeoGxTS92S2r1DZAtJegbeucL8tCT // 公钥: 028181b7534e613143befb67e9bd1a0fa95ed71b631873a2005ceef2774b5916df // importPriKey("fbcae491407b54aa3904ff295f2d644080901fda0d417b2b427f5c1487b2b499", password);//种子出块地址 tNULSeBaMmShSTVwbU4rHkZjpD98JgFgg6rmhF TNVTdTSPLpegzD3B6qaVKhfj6t8cYtnkfR7Wx importPriKey("9ce21dad67e0f0af2599b41b515a7f7018059418bab892a7b68f283d489abc4b", password);//20 tNULSeBaMvEtDfvZuukDf2mVyfGo3DdiN8KLRG TNVTdTSPVcqUCdfVYWwrbuRtZ1oM6GpSgsgF5 importPriKey("477059f40708313626cccd26f276646e4466032cabceccbf571a7c46f954eb75", password);//21 tNULSeBaMnrs6JKrCy6TQdzYJZkMZJDng7QAsD TNVTdTSPNEpLq2wnbsBcD8UDTVMsArtkfxWgz importPriKey("8212e7ba23c8b52790c45b0514490356cd819db15d364cbe08659b5888339e78", password);//22 tNULSeBaMrbMRiFAUeeAt6swb4xVBNyi81YL24 TNVTdTSPRyJgExG4HQu5g1sVxhVVFcpCa6fqw importPriKey("4100e2f88c3dba08e5000ed3e8da1ae4f1e0041b856c09d35a26fb399550f530", password);//23 tNULSeBaMu38g1vnJsSZUCwTDU9GsE5TVNUtpD TNVTdTSPUR5vYdstWDHfn5P8MtHB6iZZw3Edv importPriKey("bec819ef7d5beeb1593790254583e077e00f481982bce1a43ea2830a2dc4fdf7", password);//24 tNULSeBaMp9wC9PcWEcfesY7YmWrPfeQzkN1xL TNVTdTSPPXtSg6i5sPPrSg3TfFrhYHX5JvMnD importPriKey("ddddb7cb859a467fbe05d5034735de9e62ad06db6557b64d7c139b6db856b200", password);//25 tNULSeBaMshNPEnuqiDhMdSA4iNs6LMgjY6tcL TNVTdTSPT5KdmW1RLzRZCa5yc7sQCznp6fES5 importPriKey("4efb6c23991f56626bc77cdb341d64e891e0412b03cbcb948aba6d4defb4e60a", password);//26 tNULSeBaMoodYW7AqyJrgYdWiJ6nfwfVHHHyXm TNVTdTSPPBao2pGRc5at7mSdBqnypJbMqrKMg importPriKey("3dadac00b523736f38f8c57deb81aa7ec612b68448995856038bd26addd80ec1", password);//27 tNULSeBaMmTNYqywL5ZSHbyAQ662uE3wibrgD1 TNVTdTSPLqKoNh2uiLAVB76Jyq3D6h3oAR22n importPriKey("27dbdcd1f2d6166001e5a722afbbb86a845ef590433ab4fcd13b9a433af6e66e", password);//28 tNULSeBaMoNnKitV28JeuUdBaPSR6n1xHfKLj2 TNVTdTSPNkjaFbabm5P73m7VHBRQef4NDsgYu importPriKey("76b7beaa98db863fb680def099af872978209ed9422b7acab8ab57ad95ab218b", password);//29 tNULSeBaMqywZjfSrKNQKBfuQtVxAHBQ8rB2Zn TNVTdTSPRMtpGNYRx98WkoqKnExU9pWDQjNPf importPriKey("50a0631304ba75b1519c96169a0250795d985832763b06862167aa6bbcd6171f", password);// 出块 tNULSeBaMrbmG67VrTJeZswv4P2uXXKoFMa6RH TNVTdTSPRyiWcpbS65NmT5qyGmuqPxuKv8SF4 0x18354c726a3ef2b7da89def0fce1d15d679ae16a importPriKey("b36097415f57fe0ac1665858e3d007ba066a7c022ec712928d2372b27e8513ff", password);//ETH 测试网地址 tNULSeBaMfQ6VnRxrCwdU6aPqdiPii9Ks8ofUQ TNVTdTSPEn3kK94RqiMffiKkXTQ2anRwhN1J9 } public static void importPriKey(String priKey, String pwd) { try { // 账户已存在则覆盖 If the account exists, it covers. Map<String, Object> params = new HashMap<>(); params.put(Constants.VERSION_KEY_STR, "1.0"); params.put(Constants.CHAIN_ID, chainId); params.put("priKey", priKey); params.put("password", pwd); params.put("overwrite", true); Response cmdResp = ResponseMessageProcessor.requestAndResponse(ModuleE.AC.abbr, "ac_importAccountByPriKey", params); HashMap result = (HashMap) ((HashMap) cmdResp.getResponseData()).get("ac_importAccountByPriKey"); String address = (String) result.get("address"); Log.debug("importPriKey success! address-{}", address); } catch (Exception e) { e.printStackTrace(); } } @Test public void getVirtualBank() throws Exception { //ConverterCmdConstant.VIRTUAL_BANK_INFO Map<String, Object> params = new HashMap<>(); params.put(Constants.VERSION_KEY_STR, "1.0"); params.put(Constants.CHAIN_ID, chainId); params.put("balance", true); Response cmdResp = ResponseMessageProcessor.requestAndResponse(ModuleE.CV.abbr, ConverterCmdConstant.VIRTUAL_BANK_INFO, params); System.out.println(JSONUtils.obj2PrettyJson(cmdResp)); } @Test public void ledgerAssetQueryAll() throws Exception { Map<String, Object> params = new HashMap<>(); params.put(Constants.VERSION_KEY_STR, "1.0"); params.put(Constants.CHAIN_ID, chainId); Response cmdResp = ResponseMessageProcessor.requestAndResponse(ModuleE.LG.abbr, "lg_get_all_asset", params); System.out.println(JSONUtils.obj2PrettyJson(cmdResp)); } @Test public void getBalance() throws Exception { NonceBalance balance = LedgerCall.getBalanceNonce(chain, chainId, 2, address30); System.out.println("ETH:" + balance.getAvailable()); NonceBalance balance3 = LedgerCall.getBalanceNonce(chain, chainId, 3, address30); System.out.println("BNB:" + balance3.getAvailable()); // NonceBalance balance0 = LedgerCall.getBalanceNonce(chain, chainId, 3, address25); // System.out.println(address25 + " USDX:" + balance0.getAvailable()); NonceBalance balance4 = LedgerCall.getBalanceNonce(chain, chainId, 4, address30); System.out.println("USDX:" + balance4.getAvailable()); NonceBalance balance5 = LedgerCall.getBalanceNonce(chain, chainId, 1, address30); System.out.println("NVT:" + balance5.getAvailable()); NonceBalance balance6 = LedgerCall.getBalanceNonce(chain, chainId, 5, address30); System.out.println("USDI:" + balance6.getAvailable()); NonceBalance balance7 = LedgerCall.getBalanceNonce(chain, chainId, 6, address30); System.out.println("ENVT:" + balance7.getAvailable()); } @Test public void withdrawalNVT() throws Exception { //账户已存在则覆盖 If the account exists, it covers. for (int i = 1; i <= 1; i++) { Map<String, Object> params = new HashMap<>(); params.put(Constants.VERSION_KEY_STR, "1.0"); params.put(Constants.CHAIN_ID, chainId); // 提现金额ETH String amount = "100000"; BigDecimal am = new BigDecimal(amount).movePointRight(8); amount = am.toPlainString(); params.put("assetChainId", chainId); params.put("assetId", 1); params.put("heterogeneousAddress", "0xfa27c84eC062b2fF89EB297C24aaEd366079c684"); params.put("distributionFee", new BigInteger("1000000000")); params.put("amount", amount); params.put("remark", "提现"); params.put("address", address30); params.put("password", password); Response cmdResp = ResponseMessageProcessor.requestAndResponse(ModuleE.CV.abbr, "cv_withdrawal", params); HashMap result = (HashMap) ((HashMap) cmdResp.getResponseData()).get("cv_withdrawal"); String hash = (String) result.get("value"); String txHex = (String) result.get("hex"); Log.debug("number:{}, hash:{}", i, hash); } /** * cmd * redeem 2 0xfa27c84eC062b2fF89EB297C24aaEd366079c684 0.3 tNULSeBaMfQ6VnRxrCwdU6aPqdiPii9Ks8ofUQ */ } @Test public void withdrawalETH() throws Exception { //账户已存在则覆盖 If the account exists, it covers. for (int i = 1; i <= 10; i++) { Map<String, Object> params = new HashMap<>(); params.put(Constants.VERSION_KEY_STR, "1.0"); params.put(Constants.CHAIN_ID, chainId); // 提现金额ETH String amount = "0.2"; BigDecimal am = new BigDecimal(amount).movePointRight(18); amount = am.toPlainString(); params.put("assetChainId", chainId); params.put("assetId", 2); params.put("heterogeneousAddress", "0xfa27c84eC062b2fF89EB297C24aaEd366079c684"); params.put("distributionFee", new BigInteger("1000000000")); params.put("amount", amount); params.put("remark", "提现"); params.put("address", address30); params.put("password", password); Response cmdResp = ResponseMessageProcessor.requestAndResponse(ModuleE.CV.abbr, "cv_withdrawal", params); HashMap result = (HashMap) ((HashMap) cmdResp.getResponseData()).get("cv_withdrawal"); String hash = (String) result.get("value"); String txHex = (String) result.get("hex"); Log.debug("number:{}, hash:{}", i, hash); } /** * cmd * redeem 2 0xfa27c84eC062b2fF89EB297C24aaEd366079c684 0.3 tNULSeBaMfQ6VnRxrCwdU6aPqdiPii9Ks8ofUQ */ } @Test public void withdrawalERC20() throws Exception { for (int i = 1; i <= 1; i++) { Map<String, Object> params = new HashMap<>(); params.put(Constants.VERSION_KEY_STR, "1.0"); params.put(Constants.CHAIN_ID, chainId); // 提现金额ERC20 String amount = "10"; int decimal = 6; //小数位 BigDecimal am = new BigDecimal(amount).movePointRight(decimal); amount = am.toPlainString(); params.put("assetChainId", chainId); params.put("assetId", 5); params.put("heterogeneousAddress", "0xfa27c84eC062b2fF89EB297C24aaEd366079c684"); params.put("distributionFee", new BigInteger("100000000")); params.put("amount", amount); params.put("remark", "提现"); params.put("address", address30); params.put("password", password); Response cmdResp = ResponseMessageProcessor.requestAndResponse(ModuleE.CV.abbr, "cv_withdrawal", params); HashMap result = (HashMap) ((HashMap) cmdResp.getResponseData()).get("cv_withdrawal"); String hash = (String) result.get("value"); String txHex = (String) result.get("hex"); Log.debug("number:{}, hash:{}", i, hash); } /** * cmd * redeem 3 0xfa27c84eC062b2fF89EB297C24aaEd366079c684 100 tNULSeBaMfQ6VnRxrCwdU6aPqdiPii9Ks8ofUQ */ } @Test public void withdrawalAdditionalFee() throws Exception { Map<String, Object> params = new HashMap<>(); params.put(Constants.VERSION_KEY_STR, "1.0"); params.put(Constants.CHAIN_ID, chainId); // 追加nvt手续费 // 提现金额ETH String amount = "100"; BigDecimal am = new BigDecimal(amount).movePointRight(8); amount = am.toPlainString(); params.put("txHash", "5515d3af62b402560040f46b96e4caf5b84a6cd96da6f5a34f13e487d78e6dce"); params.put("amount", amount); params.put("remark", "追加手续费"); params.put("address", address30); params.put("password", password); Response cmdResp = ResponseMessageProcessor.requestAndResponse(ModuleE.CV.abbr, "cv_withdrawal_additional_fee", params); HashMap result = (HashMap) ((HashMap) cmdResp.getResponseData()).get("cv_withdrawal_additional_fee"); String hash = (String) result.get("value"); String txHex = (String) result.get("hex"); Log.debug("txHex:{}", txHex); Log.debug("hash:{}", hash); } @Test public void createAgent() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("agentAddress", address29); params.put(Constants.CHAIN_ID, chainId); params.put("deposit", "40000000000000"); // 50W // 私钥:50a0631304ba75b1519c96169a0250795d985832763b06862167aa6bbcd6171f params.put("packingAddress", address30); params.put("password", password); params.put("rewardAddress", address29); Response cmdResp = ResponseMessageProcessor.requestAndResponse(ModuleE.CS.abbr, "cs_createAgent", params); System.out.println(cmdResp.getResponseData()); } /** * 追加保证金 */ @Test public void appendAgentDeposit() throws Exception { Map<String, Object> params = new HashMap<>(); params.put(Constants.CHAIN_ID, chainId); params.put("address", address29); params.put("password", password); params.put("amount", "10000000000000");// 10W params.put("agentHash", "daa0902b5f1528805d00c65dabc3c381dbbb2470d1fe1b7980479e3db9a17426"); Response cmdResp = ResponseMessageProcessor.requestAndResponse(ModuleE.CS.abbr, "cs_appendAgentDeposit", params); System.out.println(cmdResp.getResponseData()); //5f03675051ad879731627a1a6a10cf82bea52e0baa527b55d776416847adaa4f } @Test public void stopAgent() throws Exception { Map<String, Object> params = new HashMap<>(); params.put(Constants.CHAIN_ID, 2); params.put("address", address29); params.put("password", password); Response cmdResp = ResponseMessageProcessor.requestAndResponse(ModuleE.CS.abbr, "cs_stopAgent", params); System.out.println(cmdResp.getResponseData()); } @Test public void proposal() throws Exception { //账户已存在则覆盖 If the account exists, it covers. Map<String, Object> params = new HashMap<>(); params.put(Constants.VERSION_KEY_STR, "1.0"); params.put(Constants.CHAIN_ID, chainId); params.put("type", ProposalTypeEnum.EXPELLED.value()); params.put("content", "这是一个提案的内容..."); //params.put("heterogeneousChainId", bnbChainId); //params.put("heterogeneousTxHash", "0x178373fc06f888487790b9d7fa256f4a166451c5f3facf17a65fb250a7cd2ea1"); params.put("businessAddress", "TNVTdTSPQvEngihwxqwCNPq3keQL1PwrcLbtj"); //params.put("hash", "fac6cf4924910b3d30ff2509d43420bf34c030f6c4869e14bb5d94ed12d370a0"); params.put("voteRangeType", ProposalVoteRangeTypeEnum.BANK.value()); params.put("remark", "提案"); params.put("address", address20); params.put("password", password); Response cmdResp = ResponseMessageProcessor.requestAndResponse(ModuleE.CV.abbr, "cv_proposal", params); HashMap result = (HashMap) ((HashMap) cmdResp.getResponseData()).get("cv_proposal"); String hash = (String) result.get("value"); String txHex = (String) result.get("hex"); Log.debug("hash:{}", hash); Log.debug("txHex:{}", txHex); // upgradeProposal <heterogeneousId> <newContractAddress> <address> // upgradeProposal 101 0xdcb777E7491f03D69cD10c1FeE335C9D560eb5A2 TNVTdTSPVcqUCdfVYWwrbuRtZ1oM6GpSgsgF5 // upgradeProposal 101 0xD02a06065596b48174A37087ea93fE9889E84636 TNVTdTSPVcqUCdfVYWwrbuRtZ1oM6GpSgsgF5 } @Test public void voteProposal() throws Exception { //账户已存在则覆盖 If the account exists, it covers. Map<String, Object> params = new HashMap<>(); params.put(Constants.VERSION_KEY_STR, "1.0"); params.put(Constants.CHAIN_ID, chainId); params.put("proposalTxHash", "b4ae0561ebf1a196706960cc20c90f34400b2ee7f440ef4675cf7e84a1b0d485"); params.put("choice", ProposalVoteChoiceEnum.FAVOR.value()); params.put("remark", "投票remark"); params.put("address", "TNVTdTSPLEqKWrM7sXUciM2XbYPoo3xDdMtPd"); params.put("password", password); Response cmdResp = ResponseMessageProcessor.requestAndResponse(ModuleE.CV.abbr, "cv_voteProposal", params); HashMap result = (HashMap) ((HashMap) cmdResp.getResponseData()).get("cv_voteProposal"); String hash = (String) result.get("value"); String txHex = (String) result.get("hex"); Log.debug("hash:{}", hash); Log.debug("txHex:{}", txHex); // vote <proposalTxHash> <choice> <address> [remark] --vote // vote da2062df25220c390b74fa362fab43232068bf7c4e4cbcd2c59100f97f19bb17 1 tNULSeBaMkrt4z9FYEkkR9D6choPVvQr94oYZp // vote <proposalTxHash> 1 tNULSeBaMkrt4z9FYEkkR9D6choPVvQr94oYZp 投票 } @Test public void TxInstance() throws Exception { // AddressTool.addPrefix(5, "NERVE"); // String str ="2d002b4a6c5f06e68f90e6a1889c071ee8bf99e698afe4b880e4b8aae68f90e6a188e79a84e58685e5aeb92e2e2e65004230783235393065306439343535383061346237363365636139616531386166653539373064643333343134343466303033626332363964313635386366623566386614dcb777e7491f03d69cd10c1fee335c9d560eb5a220fac6cf4924910b3d30ff2509d43420bf34c030f6c4869e14bb5d94ed12d370a0018c0117050001f7ec6473df12e751d64cf20a8baa7edd50810f810500010040d79d3b000000000000000000000000000000000000000000000000000000000800000000000000000001170500018ec4cf3ee160b054e0abb6f5c8177b9ee56fa51e0500010000ca9a3b000000000000000000000000000000000000000000000000000000000000000000000000692103958b790c331954ed367d37bac901de5c2f06ac8368b37d7bd6cd5ae143c1d7e3463044022075b8265017dce68982308b7af691c440dbcaafd3aeb85b3694d3c2bcc15190c202202f68676f6ff217373dc54e8cb9782a9b5461116e48d2939d73d89d81693b2024"; // Transaction tx = ConverterUtil.getInstance(str, Transaction.class); // System.out.println(tx.getHash().toHex()); // System.out.println(tx.format(ProposalTxData.class)); //06889e8ac40c14d3f4e83a58f78986b29522c742f8c483d1fe088fec2501d3e0 /* AddressTool.addPrefix(9, "NERVE"); String str = "210369865ab23a1e4f3434f85cc704723991dbec1cb9c33e93aa02ed75151dfe49c54630440220268f58cd001602bc291e4a207461b50091a3661c86b4e72f8e47cbac90beaa7f0220758c55209bf489613f3b9e7269e139e546a848084c1e00aaaa7ee119d3261e9e21035fe7599a7b39ad69fbd243aac7cfb93055f8f0827c6b08057874877cb890b80346304402200dc97ae858097570b43d85d4afe8b02a97f4f6a5e8704ee6e7461305b83384ab02205d2738a060b8279df6fce64c8a9067420c4e2f8a9e5cf112a2877cf6fbef8ef62102ac31c213b1dc1d2fd55d7751326b4f07b4a5b4ecb2ce3f214cafb7832fd211b946304402202e6be474267c601457858ef4253b218c1ccb918e74ec4a9fdbf801bc6a22121702205f8dc844cda548aa560680b3e38f784b391408366a37f6a3444f60af620070ab210351a8fc85a6c475b102f3fe5bd2479c1d08e58237463f6c6ccf84e95ad396b783463044022055c2eac0081d300a8c851630b1283a0cca0f2a800d84034848cc947803d891b902204b9ce06d1858d25ed48c2d3723e8f62b35a0b147c53f97a7ffbe80f6d47952982103c363f44196aa1a57ef7e14c19845acad721c9eefd837dacdf3fe3af1ba08ee2147304502210088be74db21ddcace414e466d722b4d7bd98d996c234a482b4e84c855be9dc84a022057d45015158f9eb2e34c0bde2eaafe9a299df06a35618706584f5bea23a4f9c22103ac396ab4bc360610058d04940c879e0da57ea1b4a541b75df6989a6c3d5081c946304402206382c9cd84b5918e9b4029b81eb1eea8f888c5b74242d68fef023763fc9360e802204dff1389f05a29d4266b0a0c062eaee88a868a0b8b33fbb80c1ac1b58bffd0f32102dda7bf54b7843aef842222f5c79405ca91313ac8c59296cf7b38203c09b40ba846304402206b2324f9d44a015a45a43aa513c531c2857cd3ecb3ec65f2329997e284ef154c022042a9cde9459aeb04ca3623ec120049c3257872c8d605a000ec60d4b1c45703c721020c60dd7e0016e174f7ba4fc0333052bade8c890849409de7b6f3d26f0ec64528473045022100bd8204aaa79c5f1cf59e321899cceafc646c55936b5d2a266dcf46526ec33a0802203c08aa0f33728eb5f1310464b0c3d76a2cb3ea6256abcde85cc76488861b2667210308ad97a2bf08277be771fc5450b6a0fa26fbc6c1e57c402715b9135d5388594b473045022100f0fa5aebcf61c75a23359ddf193d50729c71b2cb0c4a8efa99580cd1c4b956bf02202e943b76f993267d3e0ea16f7a12211b0196162b445428d1d0f0fe4dbbfcd2982102c8ab66541215350c4e82073c825d0d96dfe21aed1acfca3bdd91ac4d48cb3499473045022100b70c9e1749073f3ded48e34e7d5a3bb71fd76aac184d4af7c6a0904f04ddbf26022061e1a7b32acca7d663530b33276145769aec547f689d02bac5c511798451c1f5"; TransactionSignature instance = ConverterUtil.getInstance(str, TransactionSignature.class); for (P2PHKSignature signature : instance.getP2PHKSignatures()) { byte[] address = AddressTool.getAddress(signature.getPublicKey(), 9); String addr = AddressTool.getStringAddressByBytes(address); System.out.println(addr); }*/ // // String signStr = "21037fae74d15153c3b55857ca0abd5c34c865dfa1c0d0232997c545bae5541a086346304402201c2a12016971ba7045c83e164648705c7e073813b90d3b56fe77db549604b7920220236f13bcb01cac09d4fedad70c740805bc22325b05fa0695225b8e37178af276"; // P2PHKSignature sign = ConverterUtil.getInstance(signStr, P2PHKSignature.class); // byte[] address = AddressTool.getAddress(sign.getPublicKey(), 5); // String addr = AddressTool.getStringAddressByBytes(address); // System.out.println(addr); String str1="2d002b4a6c5f06e68f90e6a1889c071ee8bf99e698afe4b880e4b8aae68f90e6a188e79a84e58685e5aeb92e2e2e65004230783235393065306439343535383061346237363365636139616531386166653539373064643333343134343466303033626332363964313635386366623566386614dcb777e7491f03d69cd10c1fee335c9d560eb5a220fac6cf4924910b3d30ff2509d43420bf34c030f6c4869e14bb5d94ed12d370a0018c0117050001f7ec6473df12e751d64cf20a8baa7edd50810f810500010040d79d3b000000000000000000000000000000000000000000000000000000000800000000000000000001170500018ec4cf3ee160b054e0abb6f5c8177b9ee56fa51e0500010000ca9a3b000000000000000000000000000000000000000000000000000000000000000000000000692103958b790c331954ed367d37bac901de5c2f06ac8368b37d7bd6cd5ae143c1d7e3463044022075b8265017dce68982308b7af691c440dbcaafd3aeb85b3694d3c2bcc15190c202202f68676f6ff217373dc54e8cb9782a9b5461116e48d2939d73d89d81693b2024"; String str2="2d002b4a6c5f06e68f90e6a1889c071ee8bf99e698afe4b880e4b8aae68f90e6a188e79a84e58685e5aeb92e2e2e65004230783235393065306439343535383061346237363365636139616531386166653539373064643333343134343466303033626332363964313635386366623566386614dcb777e7491f03d69cd10c1fee335c9d560eb5a220fac6cf4924910b3d30ff2509d43420bf34c030f6c4869e14bb5d94ed12d370a0018c0117050001f7ec6473df12e751d64cf20a8baa7edd50810f810500010040d79d3b000000000000000000000000000000000000000000000000000000000800000000000000000001170500018ec4cf3ee160b054e0abb6f5c8177b9ee56fa51e0500010000ca9a3b000000000000000000000000000000000000000000000000000000000000000000000000692103958b790c331954ed367d37bac901de5c2f06ac8368b37d7bd6cd5ae143c1d7e3463044022075b8265017dce68982308b7af691c440dbcaafd3aeb85b3694d3c2bcc15190c202202f68676f6ff217373dc54e8cb9782a9b5461116e48d2939d73d89d81693b2024"; String str3="2d002b4a6c5f06e68f90e6a1889c071ee8bf99e698afe4b880e4b8aae68f90e6a188e79a84e58685e5aeb92e2e2e65004230783235393065306439343535383061346237363365636139616531386166653539373064643333343134343466303033626332363964313635386366623566386614dcb777e7491f03d69cd10c1fee335c9d560eb5a220fac6cf4924910b3d30ff2509d43420bf34c030f6c4869e14bb5d94ed12d370a0018c0117050001f7ec6473df12e751d64cf20a8baa7edd50810f810500010040d79d3b000000000000000000000000000000000000000000000000000000000800000000000000000001170500018ec4cf3ee160b054e0abb6f5c8177b9ee56fa51e0500010000ca9a3b000000000000000000000000000000000000000000000000000000000000000000000000692103958b790c331954ed367d37bac901de5c2f06ac8368b37d7bd6cd5ae143c1d7e3463044022075b8265017dce68982308b7af691c440dbcaafd3aeb85b3694d3c2bcc15190c202202f68676f6ff217373dc54e8cb9782a9b5461116e48d2939d73d89d81693b2024"; System.out.println(str1.equals(str2)); System.out.println(str1.equals(str3)); AddressTool.addPrefix(5, "NERVE"); Transaction tx1 = ConverterUtil.getInstance(str1, Transaction.class); System.out.println(tx1.getHash().toHex()); Transaction tx2 = ConverterUtil.getInstance(str2, Transaction.class); System.out.println(tx2.getHash().toHex()); Transaction tx3 = ConverterUtil.getInstance(str3, Transaction.class); System.out.println(tx3.getHash().toHex()); // System.out.println(tx.format(ProposalTxData.class)); } // resetbank 101 tNULSeBaMkrt4z9FYEkkR9D6choPVvQr94oYZp @Test public void createWithdrawal() throws Exception { Transaction tx = new Transaction(TxType.WITHDRAWAL); tx.setTxData(new WithdrawalTxData("0xfa27c84eC062b2fF89EB297C24aaEd366079c684").serialize()); WithdrawalTxDTO txDTO = new WithdrawalTxDTO(); txDTO.setAmount(new BigInteger("1000000")); txDTO.setAssetChainId(5); txDTO.setAssetId(3); txDTO.setSignAccount(new SignAccountDTO(address30, password)); tx.setCoinData(assembleWithdrawalCoinData(chain, txDTO)); tx.setTime(NulsDateUtils.getCurrentTimeSeconds()); sign(tx, txDTO.getSignAccount().getAddress(), txDTO.getSignAccount().getPassword()); newTx(tx); } private void newTx(Transaction tx) throws Exception { Map<String, Object> params = new HashMap<>(); params.put(Constants.VERSION_KEY_STR, "1.0"); params.put(Constants.CHAIN_ID, chainId); params.put("tx", RPCUtil.encode(tx.serialize())); HashMap result = (HashMap) BaseCall.requestAndResponse(ModuleE.TX.abbr, "tx_newTx", params); System.out.println(result.get("hash")); } /** * 对交易hash签名(在线) * @param tx * @param address * @param password */ public void sign(Transaction tx, String address, String password) throws Exception { TransactionSignature transactionSignature = new TransactionSignature(); List<P2PHKSignature> p2PHKSignatures = new ArrayList<>(); Map<String, Object> params = new HashMap<>(); params.put(Constants.VERSION_KEY_STR, "1.0"); params.put(Constants.CHAIN_ID, chainId); params.put("address", address); params.put("password", password); params.put("data", RPCUtil.encode(tx.getHash().getBytes())); HashMap result = (HashMap) BaseCall.requestAndResponse(ModuleE.AC.abbr, "ac_signDigest", params); String signatureStr = (String) result.get("signature"); P2PHKSignature signature = new P2PHKSignature(); signature.parse(new NulsByteBuffer(RPCUtil.decode(signatureStr))); p2PHKSignatures.add(signature); //交易签名 transactionSignature.setP2PHKSignatures(p2PHKSignatures); tx.setTransactionSignature(transactionSignature.serialize()); } private byte[] assembleWithdrawalCoinData(Chain chain, WithdrawalTxDTO withdrawalTxDTO) throws NulsException { int withdrawalAssetId = withdrawalTxDTO.getAssetId(); int withdrawalAssetChainId = withdrawalTxDTO.getAssetChainId(); int chainId = chain.getConfig().getChainId(); int assetId = chain.getConfig().getAssetId(); BigInteger amount = withdrawalTxDTO.getAmount(); String address = withdrawalTxDTO.getSignAccount().getAddress(); //提现资产from CoinFrom withdrawalCoinFrom = getWithdrawalCoinFrom(chain, address, amount, withdrawalAssetChainId, withdrawalAssetId); List<CoinFrom> listFrom = new ArrayList<>(); listFrom.add(withdrawalCoinFrom); if(withdrawalAssetChainId != chainId || assetId != withdrawalAssetId) { // 只要不是当前链主资产 都要组装额外的coinFrom CoinFrom withdrawalFeeCoinFrom = null; //手续费from 包含异构链补贴手续费 withdrawalFeeCoinFrom = getWithdrawalFeeCoinFrom(chain, address, DISTRIBUTION_FEE_10); listFrom.add(withdrawalFeeCoinFrom); } //------------------------------------------------------------------ // BigInteger amount2 = new BigInteger("1000000000000000000"); // CoinFrom withdrawalCoinFrom2 = getWithdrawalCoinFrom(chain, address, amount2, withdrawalAssetChainId, 5); // listFrom.add(withdrawalCoinFrom2); //------------------------------------------------------------------ String fee = "111111111111111111111111111111111111111111111111111111111111111111"; String black = "000000000000000000000000000000000000000000000000000000000000000000"; //组装to List<CoinTo> listTo = new ArrayList<>(); //============== CoinTo withdrawalCoinTo3 = new CoinTo( AddressTool.getAddress(HexUtil.decode(black), chain.getChainId()), withdrawalAssetChainId, 5, new BigInteger("1000000000000000000")); listTo.add(withdrawalCoinTo3); //============== CoinTo withdrawalCoinTo = new CoinTo( AddressTool.getAddress(HexUtil.decode(black), chain.getChainId()), withdrawalAssetChainId, withdrawalAssetId, amount); listTo.add(withdrawalCoinTo); // 判断组装异构链补贴手续费暂存to CoinTo withdrawalFeeCoinTo = new CoinTo( AddressTool.getAddress(HexUtil.decode(fee), chain.getChainId()), chainId, assetId, DISTRIBUTION_FEE_10); listTo.add(withdrawalFeeCoinTo); CoinData coinData = new CoinData(listFrom, listTo); try { return coinData.serialize(); } catch (IOException e) { throw new NulsException(ConverterErrorCode.SERIALIZE_ERROR); } } private CoinFrom getWithdrawalCoinFrom( Chain chain, String address, BigInteger amount, int withdrawalAssetChainId, int withdrawalAssetId) throws NulsException { //提现资产 if (BigIntegerUtils.isEqualOrLessThan(amount, BigInteger.ZERO)) { chain.getLogger().error("提现金额不能小于0, amount:{}", amount); throw new NulsException(ConverterErrorCode.PARAMETER_ERROR); } NonceBalance withdrawalNonceBalance = LedgerCall.getBalanceNonce( chain, withdrawalAssetChainId, withdrawalAssetId, address); BigInteger withdrawalAssetBalance = withdrawalNonceBalance.getAvailable(); if (BigIntegerUtils.isLessThan(withdrawalAssetBalance, amount)) { chain.getLogger().error("提现资产余额不足 chainId:{}, assetId:{}, withdrawal amount:{}, available balance:{} ", withdrawalAssetChainId, withdrawalAssetId, amount, withdrawalAssetBalance); throw new NulsException(ConverterErrorCode.INSUFFICIENT_BALANCE); } if(withdrawalAssetChainId == chain.getConfig().getChainId() && chain.getConfig().getAssetId() == withdrawalAssetId) { // 异构转出链内主资产, 直接合并到一个coinFrom // 总手续费 = 链内打包手续费 + 异构链转账(或签名)手续费[都以链内主资产结算] BigInteger totalFee = TransactionFeeCalculator.NORMAL_PRICE_PRE_1024_BYTES.add(DISTRIBUTION_FEE_10); amount = totalFee.add(amount); if (BigIntegerUtils.isLessThan(withdrawalAssetBalance, amount)) { chain.getLogger().error("Insufficient balance of withdrawal fee. amount to be paid:{}, available balance:{} ", amount, withdrawalAssetBalance); throw new NulsException(ConverterErrorCode.INSUFFICIENT_BALANCE); } } return new CoinFrom( AddressTool.getAddress(address), withdrawalAssetChainId, withdrawalAssetId, amount, withdrawalNonceBalance.getNonce(), (byte) 0); } private CoinFrom getWithdrawalFeeCoinFrom(Chain chain, String address, BigInteger withdrawalSignFeeNvt) throws NulsException { int chainId = chain.getConfig().getChainId(); int assetId = chain.getConfig().getAssetId(); NonceBalance currentChainNonceBalance = LedgerCall.getBalanceNonce( chain, chainId, assetId, address); // 本链资产余额 BigInteger balance = currentChainNonceBalance.getAvailable(); // 总手续费 = 链内打包手续费 + 异构链转账(或签名)手续费[都以链内主资产结算] BigInteger totalFee = TransactionFeeCalculator.NORMAL_PRICE_PRE_1024_BYTES.add(withdrawalSignFeeNvt); if (BigIntegerUtils.isLessThan(balance, totalFee)) { chain.getLogger().error("Insufficient balance of withdrawal fee. amount to be paid:{}, available balance:{} ", totalFee, balance); throw new NulsException(ConverterErrorCode.INSUFFICIENT_BALANCE); } // 查询账本获取nonce值 byte[] nonce = currentChainNonceBalance.getNonce(); return new CoinFrom(AddressTool.getAddress(address), chainId, assetId, totalFee, nonce, (byte) 0); } }
package com.chw.manager.servlet; import java.util.LinkedHashMap; import java.util.Map; import javax.servlet.Filter; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.realm.Realm; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.apache.shiro.web.servlet.SimpleCookie; import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ShiroConfiguration { /** * 凭证匹配器 * * @return */ @Bean public HashedCredentialsMatcher hashedCredentialsMatcher() { HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); hashedCredentialsMatcher.setHashAlgorithmName("md5");// 散列算法:这里使用md5算法; hashedCredentialsMatcher.setHashIterations(1);// 散列的次数,比如散列1次,相当于 md5( // md5("")); return hashedCredentialsMatcher; } /** * 自定义realm,将凭证匹配器设置到realm中,realm按照凭证匹配器的要求进行散列 * * @return */ @Bean public Realm myShiroRealm() { AuthorityRealm authorityRealm = new AuthorityRealm(); authorityRealm.setCredentialsMatcher(hashedCredentialsMatcher()); return authorityRealm; } /** * shiro 安全管理器,核心安全管理接口 * * @return */ @Bean public DefaultWebSecurityManager securityManager() { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(myShiroRealm()); securityManager.setSessionManager(shiroSessionManager()); return securityManager; } @Bean public SimpleCookie sharesession() { SimpleCookie simpleCookie = new SimpleCookie(); simpleCookie.setName("SHAREJSESSIONID"); simpleCookie.setPath("/"); simpleCookie.setHttpOnly(true); return simpleCookie; } @Bean public DefaultWebSessionManager shiroSessionManager() { DefaultWebSessionManager shiroSessionManager = new DefaultWebSessionManager(); // 去掉JSESSIONID小尾巴 shiroSessionManager.setSessionIdUrlRewritingEnabled(false); shiroSessionManager.setSessionValidationSchedulerEnabled(true); shiroSessionManager.setGlobalSessionTimeout(1800000); shiroSessionManager.setDeleteInvalidSessions(true); shiroSessionManager.setSessionIdCookie(sharesession()); return shiroSessionManager; } @Bean public ShiroFilterFactoryBean shiroFilter() { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); // 设置安全管理器 shiroFilterFactoryBean.setSecurityManager(securityManager()); // loginUrl认证提交地址,如果没有认证将会请求此地址进行认证,请求此地址将由formAuthenticationFilter进行表单认证 shiroFilterFactoryBean.setLoginUrl("/system/login"); // 认证成功统一跳转到first.action,建议不配置,shiro认证成功自动到上一个请求路径 shiroFilterFactoryBean.setSuccessUrl("/system/main"); // 通过unauthorizedUrl指定没有权限操作时跳转页面 shiroFilterFactoryBean.setUnauthorizedUrl("/system/noAuthority"); // 自定义过滤器 Map<String, Filter> filterMap = new LinkedHashMap<>(); shiroFilterFactoryBean.setFilters(filterMap); // 权限控制map,先进先出 Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>(); // 配置不会被拦截的链接 顺序判断(静态资源过滤) filterChainDefinitionMap.put("/static/**", "anon"); //验证码过滤 filterChainDefinitionMap.put("/validate/validateCode", "anon"); // 配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了 filterChainDefinitionMap.put("/logout", "logout"); filterChainDefinitionMap.put("/**", "authc"); //authc 所有url都必须认证通过才可以访问 //anon 所有url都都可以匿名访问 shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } }
package net.kkolyan.elements.engine.core.templates; import net.kkolyan.elements.engine.utils.Function; /** * @author nplekhanov */ public class IdentityFunction<T> implements Function<T,T> { @Override public T apply(T t) { return t; } }
package com.example.demo.strategy2; import com.example.demo.strategy2.Data; @Data public class MessageInfo { private Integer type; private String content; public MessageInfo(Integer type, String content) { super(); this.type = type; this.content = content; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
package com.beike.util.background; import java.sql.Timestamp; public class LogVo { //log的id public long log_id; //log的记录时间,日志记录源的时间 public Timestamp log_time = new Timestamp(System.currentTimeMillis()); //log的级别:一般信息 0,重要信息 1,警告 2,错误3 public String loglevel; //log的系统来源 public String log_system; //log的产生来源:如操作者,类模块等 public String log_source; //日志的内容 public String log_content; }
/* MultiCache.java Purpose: Description: History: Wed Aug 29 17:29:45 2007, Created by tomyeh Copyright (C) 2007 Potix Corporation. All Rights Reserved. {{IS_RIGHT This program is distributed under LGPL Version 2.1 in the hope that it will be useful, but WITHOUT ANY WARRANTY. }}IS_RIGHT */ package org.zkoss.util; import org.zkoss.lang.Objects; /** * A {@link CacheMap}-based cache. * It creates multiple instances of {@link CacheMap}, called * the internal caches, and then distributes the access across them. * Thus, the performance is porportional to the number of internal caches. * * <p>Thread safe. * * @author tomyeh * @since 3.0.0 */ public class MultiCache implements Cache, java.io.Serializable, Cloneable { private final CacheMap[] _caches; private int _maxsize, _lifetime; /** Constructs a multi cache with 17 inital caches. */ public MultiCache() { this(17); } /** Constucts a multi cache with the specified number of internal caches, * the max size and the lifetime. * * @param nCache the postive number of the internal caches. * The large the number the fast the performance. * @param maxSize the maximal allowed size of each cache */ public MultiCache(int nCache, int maxSize, int lifetime) { if (nCache <= 0) throw new IllegalArgumentException(); _caches = new CacheMap[nCache]; _maxsize = maxSize; _lifetime = lifetime; } /** Constructs a multi cache with the specified number of internal caches. * * <p>The default lifetime is {@link #DEFAULT_LIFETIME}, and * the default maximal allowed size of each cache is * ({@link #DEFAULT_MAX_SIZE} / 10). * * @param nCache the postive number of the internal caches. * The large the number the fast the performance. */ public MultiCache(int nCache) { this(nCache, DEFAULT_MAX_SIZE / 10, DEFAULT_LIFETIME); } /** @deprecated As of release 5.0.0, replaced with {@link #MultiCache(int)} */ public MultiCache(int nCache, int initSize) { this(nCache); } //Cache// public boolean containsKey(Object key) { final CacheMap cache = getCache(key); synchronized (cache) { return cache.containsKey(key); } } public Object get(Object key) { final CacheMap cache = getCache(key); synchronized (cache) { return cache.get(key); } } public Object put(Object key, Object value) { final CacheMap cache = getCache(key); synchronized (cache) { return cache.put(key, value); } } public Object remove(Object key) { final CacheMap cache = getCache(key); synchronized (cache) { return cache.remove(key); } } public void clear() { synchronized (this) { for (int j = 0; j < _caches.length; ++j) _caches[j] = null; } } private CacheMap getCache(Object key) { int j = Objects.hashCode(key); j = (j >= 0 ? j: -j) % _caches.length; CacheMap cache = _caches[j]; if (cache == null) synchronized (this) { cache = _caches[j]; if (cache == null) { cache = new CacheMap(4); cache.setMaxSize(_maxsize); cache.setLifetime(_lifetime); _caches[j] = cache; } } return cache; } public int getLifetime() { return _lifetime; } public void setLifetime(int lifetime) { _lifetime = lifetime; for (int j = 0; j < _caches.length; ++j) if (_caches[j] != null) synchronized (_caches[j]) { _caches[j].setLifetime(lifetime); } } public int getMaxSize() { return _maxsize; } public void setMaxSize(int maxsize) { _maxsize = maxsize; for (int j = 0; j < _caches.length; ++j) if (_caches[j] != null) synchronized (_caches[j]) { _caches[j].setMaxSize(maxsize); } } //Cloneable// public Object clone() { MultiCache clone = new MultiCache(_caches.length, _maxsize, _lifetime); for (int j = 0; j < _caches.length; ++j) if (_caches[j] != null) synchronized (_caches[j]) { clone._caches[j] = (CacheMap)_caches[j].clone(); } return clone; } }
package com.vicutu.batchdownload.service; import com.vicutu.batchdownload.domain.DownloadDetail; public interface DownloadDetailService { void saveOrUpdateDownloadDetail(DownloadDetail downloadDetail); }
package pers.lyr.demo.controller; import lombok.extern.slf4j.Slf4j; import pers.lyr.demo.common.factory.ServiceFactory; import pers.lyr.demo.common.util.WebUtil; import pers.lyr.demo.pojo.po.Student; import pers.lyr.demo.service.StudentService; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Date; /** * @Author lyr * @create 2020/9/14 13:13 */ @Slf4j @WebServlet(urlPatterns = "/editStudent") public class EditStudentViewController extends BaseController{ StudentService studentService = ServiceFactory.getStudentService(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String studentId = req.getParameter("studentId"); if(studentId!=null) { req.setAttribute("student",studentService.selectStudentById(studentId)); } renderView(req,"editStudent.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Student student = WebUtil.getForm(req,Student.class); log.info("student {}",student); if(student.getStudentId()==null) { //如果没有 ,插入 studentService.addOneStudent(student.setGmtCreate(new Date()).setGmtModified(new Date())); }else { //如果有 ,就更新 studentService.updateById(student); } renderView(req,"success.jsp"); } }
package com.privilege.app.models.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "modulos") public class Modulo{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long idModulo; @Column(name="nombreModulo") private String nombreModulo; String blabla; @ManyToOne @JoinColumn(name = "fkFuncionalidad", nullable = false, updatable = false) private Funcionalidad funcionalidades; public Modulo() { } public Modulo(Long idModulo, String nombreModulo, Funcionalidad funcionalidades) { this.idModulo = idModulo; this.nombreModulo = nombreModulo; this.funcionalidades = funcionalidades; } public Long getIdModulo() { return idModulo; } public void setIdModulo(Long idModulo) { this.idModulo = idModulo; } public String getNombreModulo() { return nombreModulo; } public void setNombreModulo(String nombreModulo) { this.nombreModulo = nombreModulo; } public Funcionalidad getFuncionalidades() { return funcionalidades; } public void setFuncionalidades(Funcionalidad funcionalidades) { this.funcionalidades = funcionalidades; } }
package boundedqueue; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; /** * This class contains unit tests for the ListQueue class. It purpose is to * test all constructors and methods of the ListQueue class. * * @author Mike Parrish * @version 2016.09.25 */ public class ListQueueTest { //================================================== // Private Member Variables //================================================== private Queue<String> q0; private Queue<String> q4; //================================================== // Constructor Tests //================================================== /** * Place a description of your method here. * @throws java.lang.Exception */ @Before public void setUp() throws Exception { q0 = new ListQueue<>(10); q4 = new ListQueue<>(10); q4.enqueue("A"); q4.enqueue("B"); q4.enqueue("C"); q4.enqueue("D"); } /** * Test method for {@link boundedqueue.ListQueue#ListQueue(int)}. */ @Test public void testListQueue() { assertTrue(q0.isEmpty()); assertFalse(q4.isEmpty()); assertTrue(q0.length() == 0); assertTrue(q4.length() == 4); } /** * Test method for {@link boundedqueue.ListQueue#ListQueue(int)}. */ @Test(expected=IllegalArgumentException.class) public void testListQueueIAE() { q0 = new ListQueue<>(-5); fail(); } /** * Test method for {@link boundedqueue.ListQueue#ListQueue(int)}. */ @Test(expected=IllegalArgumentException.class) public void testListQueueIAE2() { q0 = new ListQueue<>(0); fail(); } //================================================== // Accessor Tests //================================================== // NOTE: The following accessor methods are not tested // directly because they are tested in adjacent accessor // and mutator tests: // 1. length() // 2. capacity() // 3. isEmpty() /** * Test method for {@link boundedqueue.ListQueue#iterator()}. */ @Test public void testIterator() { int count = 0; for (String s : q4) { count++; } assertEquals(4, count); } /** * Test method for {@link boundedqueue.ListQueue#newInstance()}. */ @Test public void testNewInstance() { Queue<String> q = q4.newInstance(); assertTrue(q.isEmpty()); assertEquals(q.capacity(), q4.capacity()); } /** * Test method for {@link boundedqueue.AbstractQueue#isFull()}. */ @Test public void testIsFull() { assertFalse(q4.isFull()); q4.enqueue("E"); q4.enqueue("F"); q4.enqueue("G"); q4.enqueue("H"); q4.enqueue("I"); q4.enqueue("J"); assertTrue(q4.isFull()); } /** * Test method for {@link boundedqueue.AbstractQueue#hashCode()}. */ @Test public void testHashCode() { Queue<String> q = new ListQueue<>(10); assertEquals(q0.hashCode(), q.hashCode()); q.enqueue("A"); q.enqueue("B"); q.enqueue("C"); q.enqueue("D"); assertEquals(q4.hashCode(), q.hashCode()); } /** * Test method for {@link boundedqueue.AbstractQueue#equals(java.lang.Object)}. */ @Test public void testEqualsObject() { assertTrue(q0.equals(q0)); Queue<String> q; q = new ListQueue<>(10); assertTrue(q0.equals(q)); q.enqueue("A"); q.enqueue("B"); assertFalse(q4.equals(q)); q.enqueue("C"); q.enqueue("D"); assertTrue(q4.equals(q)); q.dequeue(); q.enqueue("E"); assertFalse(q4.equals(q)); assertFalse(q0.equals(null)); q = new ListQueue<>(20); assertFalse(q0.equals(q)); assertFalse(q0.equals("A")); } /** * Test method for {@link boundedqueue.AbstractQueue#toString()}. */ @Test public void testToString() { assertEquals("[]:10", q0.toString()); assertEquals("[A, B, C, D]:10", q4.toString()); } //================================================== // Mutator Tests //================================================== /** * Test method for {@link boundedqueue.ListQueue#enqueue(java.lang.Object)}. */ @Test public void testEnqueue() { assertEquals(4, q4.length()); } /** * Test method for {@link boundedqueue.ListQueue#enqueue(java.lang.Object)}. */ @Test(expected=IllegalArgumentException.class) public void testEnqueueIAE() { q4.enqueue(null); fail(); } /** * Test method for {@link boundedqueue.ListQueue#enqueue(java.lang.Object)}. */ @Test(expected=IllegalStateException.class) public void testEnqueueISE() { q4.enqueue("E"); q4.enqueue("F"); q4.enqueue("G"); q4.enqueue("H"); q4.enqueue("I"); q4.enqueue("J"); q4.enqueue("K"); fail(); } /** * Test method for {@link boundedqueue.ListQueue#dequeue()}. */ @Test public void testDequeue() { String str = q4.dequeue(); assertEquals("A", str); assertEquals(3, q4.length()); } /** * Test method for {@link boundedqueue.ListQueue#dequeue()}. */ @Test public void testDequeue3Times() { String str1 = q4.dequeue(); assertEquals("A", str1); assertEquals(3, q4.length()); String str2 = q4.dequeue(); assertEquals("B", str2); assertEquals(2, q4.length()); String str3 = q4.dequeue(); assertEquals("C", str3); assertEquals(1, q4.length()); } /** * Test method for {@link boundedqueue.ListQueue#dequeue()}. */ @Test(expected=IllegalStateException.class) public void testDequeueISE() { q0.dequeue(); fail(); } /** * Test method for {@link boundedqueue.ListQueue#clear()}. */ @Test public void testClear() { q4.clear(); assertTrue(q4.isEmpty()); } /** * Test method for {@link boundedqueue.AbstractQueue#append(boundedqueue.Queue)}. */ @Test public void testAppend() { Queue<String> q = new ListQueue<>(10); q.enqueue("E"); q.enqueue("F"); q.enqueue("G"); q4.append(q); assertEquals(7, q4.length()); } /** * Test method for {@link boundedqueue.AbstractQueue#append(boundedqueue.Queue)}. */ @Test(expected=IllegalStateException.class) public void testAppendISE() { Queue<String> q = new ListQueue<>(10); q.enqueue("E"); q.enqueue("f"); q.enqueue("G"); q.enqueue("H"); q.enqueue("I"); q.enqueue("J"); q.enqueue("k"); q4.append(q); fail(); } /** * Test method for {@link boundedqueue.AbstractQueue#copy()}. */ @Test public void testCopy() { Queue<String> q = q4.copy(); assertEquals(q4.length(), q.length()); String str1 = q4.dequeue(); String str2 = q.dequeue(); assertTrue(str1 == str2); } }
package io.jee.alaska.alibaba.alipay; import org.springframework.util.StringUtils; import com.alipay.api.AlipayApiException; import com.alipay.api.AlipayClient; import com.alipay.api.DefaultAlipayClient; import com.alipay.api.domain.AlipayTradePagePayModel; import com.alipay.api.request.AlipayTradePagePayRequest; public class AlipayServiceImpl implements AlipayService { static boolean sandbox; public AlipayServiceImpl(String appId, String merchantPrivateKey, String alipayPublicKey, boolean sandbox) { AlipayConfig.app_id = appId; AlipayConfig.merchant_private_key = merchantPrivateKey; AlipayConfig.alipay_public_key = alipayPublicKey; AlipayServiceImpl.sandbox = sandbox; } @Override public String pay(String notify_url, String return_url, String out_trade_no, String subject, String body, String total_amount, String qr_pay_mode, Long qrcodeWidth) { //获得初始化的AlipayClient AlipayClient alipayClient = new DefaultAlipayClient(sandbox?AlipayConfig.gatewayUrl_sandbox:AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type); //设置请求参数 AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); alipayRequest.setReturnUrl(return_url); alipayRequest.setNotifyUrl(notify_url); AlipayTradePagePayModel pagePayModel = new AlipayTradePagePayModel(); pagePayModel.setOutTradeNo(out_trade_no); pagePayModel.setTotalAmount(total_amount); pagePayModel.setSubject(subject); pagePayModel.setBody(body); pagePayModel.setTimeoutExpress("30m"); pagePayModel.setProductCode("FAST_INSTANT_TRADE_PAY"); if(StringUtils.hasText(qr_pay_mode)){ pagePayModel.setQrPayMode(qr_pay_mode); } if(qrcodeWidth!=null) { pagePayModel.setQrcodeWidth(qrcodeWidth); } alipayRequest.setBizModel(pagePayModel); //若想给BizContent增加其他可选请求参数,以增加自定义超时时间参数timeout_express来举例说明 // alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\"," // + "\"total_amount\":\""+ total_amount +"\"," // + "\"subject\":\""+ subject +"\"," // + "\"body\":\""+ body +"\"," // + "\"timeout_express\":\"10m\"," // + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}"); //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节 //请求 String result = null; try { result = alipayClient.pageExecute(alipayRequest).getBody(); } catch (AlipayApiException e) { } //输出 return result; } }
package com.ut.healthelink.controller; import com.ut.healthelink.model.User; import com.ut.healthelink.model.mailMessage; import com.ut.healthelink.model.newsArticle; import com.ut.healthelink.model.newsletterSignup; import com.ut.healthelink.model.userAccess; import com.ut.healthelink.service.emailMessageManager; import com.ut.healthelink.service.newsArticleManager; import com.ut.healthelink.service.newsletterManager; import com.ut.healthelink.service.userManager; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Random; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.util.ResourceUtils; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.view.RedirectView; /** * The mainController class will handle all URL requests that fall outside of specific user or admin controllers * * eg. login, logout, about, etc * * @author chadmccue * */ @Controller public class mainController { @Autowired private userManager usermanager; @Autowired private emailMessageManager emailMessageManager; @Autowired private newsArticleManager newsarticlemanager; @Autowired private newsletterManager newslettermanager; @RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET) public void getFile(@PathVariable("file_name") String fileName, HttpServletResponse response) throws FileNotFoundException { try { File file = ResourceUtils.getFile("classpath:files/"+fileName+".docx"); // get your file as InputStream InputStream is = new FileInputStream(file); // copy it to response's OutputStream org.apache.commons.io.IOUtils.copy(is, response.getOutputStream()); response.flushBuffer(); } catch (IOException ex) { throw new RuntimeException("IOError writing file to output stream"); } } /** * The '/login' request will serve up the login page. * * @param request * @param response * @return the login page view * @throws Exception */ @RequestMapping(value = "/login", method = RequestMethod.GET) public ModelAndView login() throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/login"); return mav; } /** * The '/loginfailed' request will serve up the login page displaying the login failed error message * * @param request * @param response * @return the error object and the login page view * @throws Exception */ @RequestMapping(value = "/loginfailed", method = RequestMethod.GET) public ModelAndView loginerror(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/login"); mav.addObject("error", "true"); return mav; } /** * The '/logout' request will handle a user logging out of the system. The request will handle front-end users or administrators logging out. * * @param request * @param response * @return the login page view * @throws Exception */ @RequestMapping(value = "/logout", method = RequestMethod.GET) public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) throws Exception { return new ModelAndView("/login"); } /** * The '/' request will be the default request of the translator. The request will serve up the home page of the translator. * * @param request * @param response * @return the home page view * @throws Exception */ @RequestMapping(value = "/", method = {RequestMethod.GET, RequestMethod.POST}) public ModelAndView welcome() throws Exception { /* Get a list of active news articles */ List<newsArticle> newsArticles = newsarticlemanager.listAllActiveNewsArticles(); ModelAndView mav = new ModelAndView(); mav.setViewName("/home"); mav.addObject("newsArticles", newsArticles); return mav; } /** * The '/' head request * @param request * @param response * @return the login page * @throws Exception */ @RequestMapping(value = "/", method = {RequestMethod.HEAD}) public ModelAndView headRequest() throws Exception { ModelAndView mav = new ModelAndView(new RedirectView("/home")); return mav; } /** * The '/about' GET request will display the about page. */ @RequestMapping(value = "/about", method = RequestMethod.GET) public ModelAndView aboutPage() throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/about"); mav.addObject("pageTitle", "About Health-e-Link"); return mav; } /** * The '/about/Network-Capabilities' GET request will display the Network Capabilities page. */ @RequestMapping(value = "/about/network-capabilities", method = RequestMethod.GET) public ModelAndView networkcapabilitiesPage() throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/networkcapabilities"); mav.addObject("pageTitle", "Network Capabilities"); return mav; } /** * The '/privacy' GEt request will display the privacy page. */ @RequestMapping(value = "/privacy", method = RequestMethod.GET) public ModelAndView privacyPage() throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/privacy"); mav.addObject("pageTitle", "Privacy"); return mav; } /** * The '/contact' GEt request will display the contact page. */ @RequestMapping(value = "/contact", method = RequestMethod.GET) public ModelAndView contactPage() throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/contact"); mav.addObject("pageTitle", "Contact Us"); return mav; } /** * The '/contact' POST request will display the contact page. */ @RequestMapping(value = "/contact", method = RequestMethod.POST) public ModelAndView contactPageSend(@RequestParam String name, @RequestParam String company, @RequestParam String address, @RequestParam String city, @RequestParam String state, @RequestParam String zip, @RequestParam String phone, @RequestParam String ext, @RequestParam String fax, @RequestParam String email, @RequestParam String interestedIn, @RequestParam String comments) throws Exception { StringBuilder sb = new StringBuilder(); mailMessage messageDetails = new mailMessage(); messageDetails.settoEmailAddress("information@health-e-link.net"); messageDetails.setfromEmailAddress("support@health-e-link.net"); messageDetails.setmessageSubject("Health-e-Link Contact Form Submission"); sb.append("Name: "+ name); sb.append("<br /><br />"); sb.append("Company / Organization: " + company); sb.append("<br /><br />"); sb.append("Address: " + address); sb.append("<br /><br />"); sb.append("City: " + city); sb.append("<br /><br />"); sb.append("State: " + state); sb.append("<br /><br />"); sb.append("Zip: " + zip); sb.append("<br /><br />"); sb.append("Phone: " + phone); sb.append("<br /><br />"); sb.append("Ext: " + ext); sb.append("<br /><br />"); sb.append("Fax: " + fax); sb.append("<br /><br />"); sb.append("Email: " + email); sb.append("<br /><br />"); sb.append("Interested In: " + interestedIn); sb.append("<br /><br />"); sb.append("Comments: " + comments); sb.append("<br /><br />"); messageDetails.setmessageBody(sb.toString()); emailMessageManager.sendEmail(messageDetails); ModelAndView mav = new ModelAndView(); mav.setViewName("/contact"); mav.addObject("pageTitle", "Contact Us"); mav.addObject("sent","sent"); return mav; } /** * The '/partners' GEt request will display the partner request page. */ @RequestMapping(value = "/partners", method = RequestMethod.GET) public ModelAndView partnersPage() throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/partners"); mav.addObject("pageTitle", "Partners"); return mav; } /** * The '/partners' POST request will submit the parner request form. */ @RequestMapping(value = "/partners", method = RequestMethod.POST) public ModelAndView partnerPageSend(@RequestParam String name, @RequestParam String title, @RequestParam String company, @RequestParam String URL, @RequestParam String address, @RequestParam String city, @RequestParam String state, @RequestParam String zip, @RequestParam String phone, @RequestParam String ext, @RequestParam String fax, @RequestParam String email, @RequestParam String comments) throws Exception { StringBuilder sb = new StringBuilder(); mailMessage messageDetails = new mailMessage(); messageDetails.settoEmailAddress("information@health-e-link.net"); messageDetails.setfromEmailAddress("support@health-e-link.net"); messageDetails.setmessageSubject("Health-e-Link Partner Request Form Submission"); sb.append("Name: "+ name); sb.append("<br /><br />"); sb.append("Title: "+ title); sb.append("<br /><br />"); sb.append("Company / Organization: " + company); sb.append("<br /><br />"); sb.append("URL: "+ URL); sb.append("<br /><br />"); sb.append("Address: " + address); sb.append("<br /><br />"); sb.append("City: " + city); sb.append("<br /><br />"); sb.append("State: " + state); sb.append("<br /><br />"); sb.append("Zip: " + zip); sb.append("<br /><br />"); sb.append("Phone: " + phone); sb.append("<br /><br />"); sb.append("Ext: " + ext); sb.append("<br /><br />"); sb.append("Fax: " + fax); sb.append("<br /><br />"); sb.append("Email: " + email); sb.append("<br /><br />"); sb.append("Comments: " + comments); sb.append("<br /><br />"); messageDetails.setmessageBody(sb.toString()); emailMessageManager.sendEmail(messageDetails); ModelAndView mav = new ModelAndView(); mav.setViewName("/partners"); mav.addObject("pageTitle", "Partners"); mav.addObject("sent","sent"); return mav; } /** * The '/forgotPassword' GET request will be used to display the forget password form (In a modal) * * * @return The forget password form page * * */ @RequestMapping(value = "/forgotPassword", method = RequestMethod.GET) public ModelAndView forgotPassword(HttpSession session) throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/forgotPassword"); return mav; } /** * The '/forgotPassword.do' POST request will be used to find the account information for the user and send an email. * * */ @RequestMapping(value = "/forgotPassword.do", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody Integer findPassword(@RequestParam String identifier) throws Exception { Integer userId = usermanager.getUserByIdentifier(identifier); if (userId == null) { return 0; } else { return userId; } } /** * The '/sendPassword.do' POST request will be used to send the reset email to the user. * * @param userId The id of the return user. */ @RequestMapping(value = "/sendPassword.do", method = RequestMethod.POST) public void sendPassword(@RequestParam Integer userId, HttpServletRequest request) throws Exception { String randomCode = generateRandomCode(); User userDetails = usermanager.getUserById(userId); userDetails.setresetCode(randomCode); //Return the sections for the clicked user List<userAccess> userSections = usermanager.getuserSections(userId); List<Integer> userSectionList = new ArrayList<Integer>(); for (int i = 0; i < userSections.size(); i++) { userSectionList.add(userSections.get(i).getFeatureId()); } userDetails.setsectionList(userSectionList); usermanager.updateUser(userDetails); /* Sent Reset Email */ mailMessage messageDetails = new mailMessage(); messageDetails.settoEmailAddress(userDetails.getEmail()); messageDetails.setmessageSubject("Health-e-Link Reset Password"); String resetURL = request.getRequestURL().toString().replace("sendPassword.do", "resetPassword?b="); StringBuilder sb = new StringBuilder(); sb.append("Dear " + userDetails.getFirstName() + ",<br />"); sb.append("You have recently asked to reset your Health-e-Link password.<br /><br />"); sb.append("<a href='" + resetURL + randomCode + "'>Click here to reset your password.</a>"); messageDetails.setmessageBody(sb.toString()); messageDetails.setfromEmailAddress("support@health-e-link.net"); emailMessageManager.sendEmail(messageDetails); } /** * The '/resetPassword' GET request will be used to display the reset password form * * * @return The forget password form page * * */ @RequestMapping(value = "/resetPassword", method = RequestMethod.GET) public ModelAndView resetPassword(@RequestParam(value = "b", required = false) String resetCode, HttpSession session) throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/resetPassword"); mav.addObject("resetCode", resetCode); return mav; } /** * The '/resetPassword' POST request will be used to display update the users password * * @param resetCode The code that was set to reset a user for. * @param newPassword The password to update the user to * */ @RequestMapping(value = "/resetPassword", method = RequestMethod.POST) public ModelAndView resetPassword(@RequestParam String resetCode, @RequestParam String newPassword, HttpSession session, RedirectAttributes redirectAttr) throws Exception { User userDetails = usermanager.getUserByResetCode(resetCode); if (userDetails == null) { redirectAttr.addFlashAttribute("msg", "notfound"); ModelAndView mav = new ModelAndView(new RedirectView("/login")); return mav; } else { userDetails.setresetCode(null); userDetails.setPassword(newPassword); userDetails = usermanager.encryptPW(userDetails); //Return the sections for the clicked user List<userAccess> userSections = usermanager.getuserSections(userDetails.getId()); List<Integer> userSectionList = new ArrayList<Integer>(); for (int i = 0; i < userSections.size(); i++) { userSectionList.add(userSections.get(i).getFeatureId()); } userDetails.setsectionList(userSectionList); usermanager.updateUser(userDetails); redirectAttr.addFlashAttribute("msg", "updated"); ModelAndView mav = new ModelAndView(new RedirectView("/login")); return mav; } } /** * The 'generateRandomCode' function will be used to generate a random access code to reset a users password. The function will call itself until it gets a unique code. * * @return This function returns a randomcode as a string */ public String generateRandomCode() { Random random = new Random(); String randomCode = new BigInteger(130, random).toString(32); /* Check to make sure there is not reset code already generated */ User usedCode = usermanager.getUserByResetCode(randomCode); if (usedCode == null) { return randomCode; } else { return generateRandomCode(); } } /** * The '/emailSignUp.do' function will save the email form. * * @param emailAddress The email address being signed up * @param result The validation result * * @throws Exception */ @RequestMapping(value = "/emailSignUp.do", method = RequestMethod.POST) public @ResponseBody Integer emailSignUp(@RequestParam(value = "emailAddress", required = true) String emailAddress, @RequestParam(value = "unsubscribe", required = true) boolean unsubscribe) throws Exception { if(unsubscribe == true) { newslettermanager.removeEmailAddress(emailAddress); return 3; } else { /* Need to check to see if the email address is already in the system */ List<newsletterSignup> emailSignUps = newslettermanager.emailExists(emailAddress); if(emailSignUps.size() > 0) { return 2; } else { newsletterSignup emailSignup = new newsletterSignup(); emailSignup.setEmailAddress(emailAddress); newslettermanager.saveEmailAddress(emailSignup); return 1; } } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.tfar.daoImpl; /** * * @author hatem */ import com.tfar.dao.HopitalDao; import com.tfar.entity.Hopitale; //import Entity.Service; import java.util.List; import org.hibernate.Criteria; //import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; /** * * @author Asus */ public class HopitalDaoImpl implements HopitalDao{ private Hopitale newhopital; private Hopitale hopital; Configuration configuration = new Configuration().configure("hibernate.cfg.xml"); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); @Autowired private SessionFactory sessionFactory= configuration.buildSessionFactory(builder.build()); @Override public void add(Hopitale newhopital) { Session session = sessionFactory.openSession(); try { // begin a transaction session.beginTransaction(); session.saveOrUpdate(newhopital); session.flush(); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); } session.close(); } @Override public void update(Hopitale hopital) { Session session = sessionFactory.openSession(); try { // begin a transaction session.beginTransaction(); session.update(hopital); session.flush(); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); } session.close(); } @Override public Hopitale getHopitalParNom(String nomHop) { Hopitale hopital=null; Session session = sessionFactory.openSession(); try { session.beginTransaction(); Criteria criteria = session.createCriteria(Hopitale.class); criteria.add(Restrictions.eq("Nom_Hopitale", nomHop)); hopital = (Hopitale) criteria.uniqueResult(); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); } session.close(); return hopital; } @Override public List<Hopitale> getAllHopital() { @SuppressWarnings("unchecked") List <Hopitale> DaoAllHopital = null; Session session = sessionFactory.openSession(); try { session.beginTransaction(); DaoAllHopital = (List<Hopitale>) session.createCriteria(Hopitale.class).list(); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); } session.close(); return DaoAllHopital; } @Override public Hopitale getHopitalParNum(Integer numHop) { System.out.println("HopitalDao - numHopital : " + numHop); Hopitale hopital=null; Session session = sessionFactory.openSession(); try { session.beginTransaction(); Criteria criteria = session.createCriteria(Hopitale.class); System.out.println("HopitalDao - Code_hopitale 1"); criteria.add(Restrictions.eq("codehopitale", numHop)); System.out.println("HopitalDao - Code_hopitale 2"); hopital = (Hopitale) criteria.uniqueResult(); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); } session.close(); return hopital; } @Override public void delete(Hopitale hopital) { Session session = sessionFactory.openSession(); try { session.beginTransaction(); session.delete(hopital); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); } session.close(); } }
package database; /** * Agency Data Access class * * @author Quynh Nguyen (Queenie) * Created: 04/15/2019 */ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import model.Agency; public class DBAgency { private static final Logger LOGGER = Logger.getLogger(DBAgency.class.getName()); public DBAgency() { // TODO Auto-generated constructor stub } /* * get all Agencies */ public static List<Agency> getAgencies() { List<Agency> agencies = new ArrayList<Agency>(); String sql = "SELECT * FROM Agencies "; try { Connection conn = DBConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); // loop through the result set while (rs.next()) { Agency ele = new Agency(); ele.setAgencyId(rs.getInt("AgencyId")); ele.setAgncyAddress(rs.getString("AgncyAddress")); ele.setAgncyCity(rs.getString("AgncyCity")); ele.setAgncyProv(rs.getString("AgncyProv")); ele.setAgncyPostal(rs.getString("AgncyPostal")); ele.setAgncyCountry(rs.getString("AgncyCountry")); ele.setAgncyPhone(rs.getString("AgncyPhone")); ele.setAgncyFax(rs.getString("AgncyFax")); agencies.add(ele); } } catch (SQLException e) { LOGGER.log(Level.SEVERE, "DBAgency.getAgencies: " + e.getMessage()); } finally { DBConnection.closeConnection(); } return agencies; } /* * get Agency by AgencyId */ public static Agency getAgency(int agencyId) { Agency ele = new Agency(); String sql = "SELECT * FROM Agencies WHERE AgencyId=?"; try { Connection conn = DBConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); stmt.setInt(1, agencyId); ResultSet rs = stmt.executeQuery(); // loop through the result set while (rs.next()) { ele.setAgencyId(rs.getInt("AgencyId")); ele.setAgncyAddress(rs.getString("AgncyAddress")); ele.setAgncyCity(rs.getString("AgncyCity")); ele.setAgncyProv(rs.getString("AgncyProv")); ele.setAgncyPostal(rs.getString("AgncyPostal")); ele.setAgncyCountry(rs.getString("AgncyCountry")); ele.setAgncyPhone(rs.getString("AgncyPhone")); ele.setAgncyFax(rs.getString("AgncyFax")); } } catch (SQLException e) { LOGGER.log(Level.SEVERE, "DBAgency.getAgency: " + e.getMessage()); } finally { DBConnection.closeConnection(); } return ele; } /* * update Agency */ public static boolean updateAgency(Agency agency) { boolean result = true; String sql = "UPDATE Agencies SET AgncyAddress = ?, AgncyCity = ?," + " AgncyProv = ?, AgncyPostal = ?, AgncyCountry = ?, " + "AgncyPhone = ?, AgncyFax = ? WHERE AgencyId = ?"; try { Connection conn = DBConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, agency.getAgncyAddress()); stmt.setString(2, agency.getAgncyCity()); stmt.setString(3, agency.getAgncyProv()); stmt.setString(4, agency.getAgncyPostal()); stmt.setString(5, agency.getAgncyCountry()); stmt.setString(6, agency.getAgncyPhone()); stmt.setString(7, agency.getAgncyFax()); stmt.setInt(8, agency.getAgencyId()); result = stmt.executeUpdate() == 1; } catch (SQLException e) { LOGGER.log(Level.SEVERE, "DBAgency.updateAgency: " + e.getMessage()); } finally { DBConnection.closeConnection(); } return result; } /* * delete Agency by agencyId */ public static boolean deleteAgency(int agencyId) { boolean result = true; Connection conn = DBConnection.getConnection(); String sql = "DELETE FROM Agencies WHERE AgencyId = ?"; PreparedStatement stmt = null; try { conn.setAutoCommit(false); stmt = conn.prepareStatement(sql); stmt.setInt(1, agencyId); result = stmt.execute(); conn.commit(); } catch (SQLException e) { LOGGER.log(Level.SEVERE, "DBAgency.deleteAgency: " + e.getMessage()); try { conn.rollback(); } catch (SQLException e1) { LOGGER.log(Level.SEVERE, "DBAgency.deleteAgency: " + e.getMessage()); } } finally { try { conn.setAutoCommit(true); stmt.close(); } catch (SQLException e) { LOGGER.log(Level.SEVERE, "DBAgency.deleteAgency: " + e.getMessage()); } DBConnection.closeConnection(); } return result; } }
package com.sencha.gxt.desktopapp.client.event; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.GwtEvent; import com.sencha.gxt.desktopapp.client.event.PropertyEvent.PropertyHandler; public class PropertyEvent extends GwtEvent<PropertyHandler> { public interface PropertyHandler extends EventHandler { void onProperty(PropertyEvent event); } public static Type<PropertyHandler> TYPE = new Type<PropertyHandler>(); private Object bean; public PropertyEvent(Object bean) { this.bean = bean; } @Override public Type<PropertyHandler> getAssociatedType() { return TYPE; } public Object getBean() { return bean; } @Override protected void dispatch(PropertyHandler handler) { handler.onProperty(this); } @Override public String toString() { return bean.toString(); } }
package com.appspot.smartshop.mock; import java.util.Date; import java.util.LinkedList; import java.util.List; import android.util.Log; import com.appspot.smartshop.dom.SmartshopNotification; public class MockNotification { public static final String TAG = "[MockNotification]"; public static final int NUM_OF_NOTIFICATION = 10; public static List<SmartshopNotification> getInstance() { Log.d(TAG, "MockNotification has created"); List<SmartshopNotification> list = new LinkedList<SmartshopNotification>(); for (int i = 0; i < NUM_OF_NOTIFICATION; i++) { // SmartshopNotification notification = new SmartshopNotification("Co " + i // + " san pham may tinh hop voi nhu cau cua ban", new Date( // 89, 11, 11), "loi"); // list.add(notification); Log.d(TAG, list.get(i).content); } return list; } }
/* * 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 scheduledexecutor; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * * @author blaszczyk */ public class CheckReachable implements Runnable{ private final HostsList list; public CheckReachable(HostsList list) { this.list = list; } @Override public void run() { String hostPattern = "10.0.118.%d"; System.out.println("Tworzę listę obiektór Future"); List<Future<Host>> futureList = new ArrayList(); System.out.println("Tworzę obiekt wykonawcy z pulą max 254 wątków"); ExecutorService executor = Executors.newFixedThreadPool(254); System.out.println("Czyszczę listę"); list.clear(); list.setLastCheck(new Date()); try { System.out.println("Sprawdzam hosty"); for(int i = 0; i <255; i++) { String hostAddress = String.format(hostPattern, i); Host host = new Host(hostAddress); futureList.add(executor.submit(new IsReachable(host))); } for(Future<Host> future : futureList) { Host host = future.get(); list.add(host); } System.out.println("Zakończono sprawdzanie"); } catch(UnknownHostException | InterruptedException | ExecutionException e) { System.out.println(String.format("%s, Wystąpił błąd aplikacji", CheckReachable.class)); System.err.println(e.getLocalizedMessage()); } finally { executor.shutdown(); } } }
//Figure 2-23 static final int N = 100; // Size of the buffer static int count = 0; // Number of items in buffer static void producer(){ Item item; while(true) { // Loop forever item = produce_item(); // Generate the next item if(count == N) sleep(); // If the buffer is full, go to // sleep insert_item(item); // Add the item to the buffer count++; // Increment count of items in // buffer if(count == 1) wakeup(consumerThread); // Was the buffer empty? } static void consumer(){ Item item; while(true) { // Loop forever if(count == 0) sleep(); // If the buffer is empty, go to // sleep item = remove_item(); // Get the item from the buffer count--; // Decrement count of items in //buffer if(count == N-1) wakeup(producerThread); // Was the buffer full? consume_item(item); // Do something with the item }
package org.squonk.util; import java.io.IOException; import java.util.stream.Stream; /** * Wraps an Stream&lt;MoleculeObject&gt; to allow stronger typing and allow some * flexibility in the type of Stream generated. * Note that some stream implementations will need to be closed as they use underlying resources * The golden run is if you are performing the terminal operation on the stream you MUST * close it. A good way to do this is in a try-with-resources statement. * * @author timbo */ public interface StreamGenerator<T> extends StreamProvider<T> { Stream<T> getStream(boolean parallel, int batchSize) throws IOException; Stream<T> getStream(boolean parallel) throws IOException; }
import javax.swing.*; /** * Created by Vala on 3/12/2016. */ public class DSH { public static double[] vektordef() //deklarimi i vektorit { int k = new Integer(JOptionPane.showInputDialog("Jep gjatesine e vektorit")).intValue(); double[] v = new double[k]; return v; } public static double[][] matricedef() //deklarimi i matrices { int n = new Integer(JOptionPane.showInputDialog("Jep dimensionet e matrices katrore", "P.sh.2")).intValue(); double[][] m = new double[n][n]; return m; } public static double[] vektorin(double[] v) // inicializimi i vektorit { for(int i=0; i<v.length; i++) { double num= new Double(JOptionPane.showInputDialog("Jep elementet e vektorit:")).doubleValue(); v[i]=num; } return v; } public static double[][] matricein(double[][] m) // inicializimi i matrices { for(int i=0; i<m.length;i++) { for(int j=0; j<m[0].length;j++) { double el = new Double(JOptionPane.showInputDialog("Sheno elementin ne rreshtin e " + (i+1) + " dhe shtyllen e " + (j+1) + " te matrices")).doubleValue(); m[i][j]=el; } } return m; } public static double[] mbledhja(double[] a, double[] b) //mbledhja e dy vektoreve { double[] rez=new double[a.length]; for(int i=0; i<rez.length; i++) { rez[i] = a[i] + b[i]; } return rez; } public static double[] zbritja(double[] a, double[] b) // zbritja e dy vektoreve { double[] ndryshimi = new double[a.length]; for(int i=0;i<ndryshimi.length;i++) { ndryshimi[i] = a[i] - b[i]; } return ndryshimi; } public static double l2(double[] v) //l2 norma e vektorit { double l2=0; for(int i=0; i<v.length;i++) { l2=l2 + Math.pow(v[i],2); } return Math.sqrt(l2); } public static double linfi(double[] v) //l-infinit norma e vektorit { double max = 0; int i = 0; while (i<v.length-1) { if(Math.abs(v[i]) > max) { max=Math.abs(v[i]); } i++; } return max; } public static double dEuklidiane(double[] v, double[] r) //distanca Euklidiane { double distanca = 0; double[] m = zbritja(v,r); for(int i=0; i<m.length; i++) { distanca=distanca + Math.pow(m[i],2); } return Math.sqrt(distanca); } public static double distancaMax(double[] e, double[] f)//distanca maksimale { double max =0; double[] g = zbritja(e,f); int i=0; while(i<g.length-1) { if(Math.abs(g[i]) > max) { max = Math.abs(g[i]); } i++; } return max; } public static double linfiMatrice(double[][] mat)// l-infinit norma e matrices { double max = 0; double shuma=0; for(int i=0; i<mat.length;i++) { for(int j=0; j<mat.length; j++) { shuma=shuma+Math.abs(mat[i][j]); if(shuma > max) { max = shuma; } } shuma=0; } return max; } public static double Frobenius(double[][] ayy)//Frobenius norma e matrices { double rez =0; for(int i=0; i<ayy.length;i++) { for(int j=0; j<ayy[0].length;j++) { rez = rez + Math.pow(ayy[i][j],2); } } return Math.sqrt(rez); } public static String shtypVektor(double[] v) // metoda per shtypjen e vektoreve { String vektori = ""; for(int i=v.length-1;i>=0;i--) { if(i==0) { vektori= v[i] + vektori; } else { vektori = ", " + v[i] + vektori; } } return vektori; } public static void main(String[] args) { double[] v1 = vektorin(vektordef()); double[] v2 = vektorin(vektordef()); double[] a1 = mbledhja(v1,v2); double[] a2 = zbritja(v1,v2); double a3 = l2(v1); double a4 = linfi(v1); double a5 =dEuklidiane(v1,v2); double a6 = distancaMax(v1,v2); System.out.println("Shuma e vektoreve te dhene eshte: shuma={" +shtypVektor(a1)+ "}"); System.out.println("Ndryshimi i vektoreve te dhene eshte: v2={" +shtypVektor(a2)+ "}" ); System.out.println("L2 norma e vektorit te pare eshte: ||v||₂ = " +a3); System.out.println("LInfinit norma e vektorit te pare eshte ||v||∞ = " +a4); System.out.println("Distanca Euklidiane e dy vektoreve te dhene eshte ||v-v2||₂ = " +a5); System.out.println("Distanca maksimale e dy vektoreve te dhene eshte ||v-v2||∞ = " +a6); double[][] m1 = matricein(matricedef()); double a7 = linfiMatrice(m1); double a8 = Frobenius(m1); System.out.println("Linfinit norma e matrices se dhene eshte ||A||∞ = " +a7); System.out.println("Frobenius norma e matrices se dhene eshte ||A|| = " +a8); } }
/* * 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 recursividad; import java.util.Scanner; /** * * @author Pablo */ public class Rombo { public static void logica(int tamanio) { char espacio = ' '; char asterisco = '*'; for (int i = 1; i <= tamanio; i++) { for (int espacios = tamanio - i; espacios > 0; espacios--) { System.out.print(espacio); } for (int lineas = 1; lineas < 2 * i; lineas++) { System.out.print(asterisco); } System.out.println(""); } for (int i = tamanio-1; i >= 1; i--) { for (int espacios = tamanio - i; espacios > 0; espacios--) { System.out.print(espacio); } for (int lineas = 1; lineas < 2 * i; lineas++) { System.out.print(asterisco); } System.out.println(""); } } public static void main(String[] args) { int valor; Scanner dato = new Scanner(System.in); System.out.println("Ingresa el tamaño del rombo: "); valor = dato.nextInt(); logica(valor); } }
package particle; import java.awt.Graphics2D; import java.awt.Image; import main.Game; import main.Pictures; import main.World; public class Spark extends Particle { public Spark(long x, long y, World world) { super(x, y, world); lifeTime = 50; } @Override public void tick() { super.tick(); vy-=0.1; } @Override public void draw(Graphics2D g) { super.draw(g); Image value = Pictures.spark; g.drawImage(value, (int) (x - Game.x - value.getWidth(null)/2), (int) (y - Game.y - value.getHeight(null)), null); } @Override protected double getSpeed() { return 3; } }
import java.util.Comparator; import java.util.Random; /** * Write a description of class Jugador here. * * @author (your name) * @version (a version number or a date) */ public abstract class Jugador implements Comparable<Jugador>, Cloneable { private final String nombre; private int edad; private int dorsal; private int estadoDeForma; private boolean titular; private static final int MIN_EDAD = 18; private static final int MAX_EDAD = 40; private static final int MIN_ESTADISTICAS = 0; private static final int MAX_ESTADISTICAS = 10; @Override public int compareTo(Jugador j1) { int compare = 0; if (j1 instanceof JugadorDeCampo || j1 instanceof Portero || j1 instanceof Capitan) { compare = new Float(valoracion()).compareTo(new Float(j1.valoracion())); } return compare; } /** * Constructor for objects of class Jugador */ public Jugador(String nombre, int edad) { Random rnd = new Random(); this.nombre = nombre; this.edad = edad; dorsal = -1; titular = false; estadoDeForma = rnd.nextInt((MAX_ESTADISTICAS + 1) - MIN_ESTADISTICAS) + MIN_ESTADISTICAS; } public String getNombre() { return nombre; } public int getEdad() { return edad; } public void setEdad(int edad) { this.edad = edad; } public int getDorsal() { return dorsal; } public void setDorsal(int dorsal) { this.dorsal = dorsal; } public int getEstadoDeForma() { return estadoDeForma; } public boolean setEstadoDeForma(int nuevoValor) { boolean set = false; if (nuevoValor >= MIN_ESTADISTICAS && nuevoValor <= MAX_ESTADISTICAS) { this.estadoDeForma = nuevoValor; set = true; } return set; } public boolean titular() { return titular; } public void isTitular(boolean titular) { this.titular = titular; } public static int getMIN_EDAD() { return MIN_EDAD; } public static int getMAX_EDAD() { return MAX_EDAD; } public static int getMIN_ESTADISTICAS() { return MIN_ESTADISTICAS; } public static int getMAX_ESTADISTICAS() { return MAX_ESTADISTICAS; } public abstract float valoracion(); @Override public String toString() { String cadena = String.format("%s %2d%s ", "Dorsal", dorsal, "."); cadena += String.format("%-29s", (nombre + " (Edad " + edad + ")")); cadena += String.format("%s: %-2d", "Forma", estadoDeForma); return cadena; } public Object clone(){ Object obj=null; try{ obj=super.clone(); }catch(CloneNotSupportedException ex){} return obj; } }
package com.game.service; import com.game.biz.model.R2LastWeekReportLine; import java.util.List; import java.util.Optional; /** * Service Interface for managing {@link R2LastWeekReportLine}. */ public interface R2LastWeekReportLineService { /** * Save a r2LastWeekReportLine. * * @param r2LastWeekReportLine the entity to save. * @return the persisted entity. */ R2LastWeekReportLine save(R2LastWeekReportLine r2LastWeekReportLine); /** * Get all the r2LastWeekReportLines. * * @return the list of entities. */ List<R2LastWeekReportLine> findAll(); /** * Get the "id" r2LastWeekReportLine. * * @param id the id of the entity. * @return the entity. */ Optional<R2LastWeekReportLine> findOne(Long id); /** * Delete the "id" r2LastWeekReportLine. * * @param id the id of the entity. */ void delete(Long id); }
/** * Copyright (C) Alibaba Cloud Computing, 2012 * All rights reserved. * * 版权所有 (C)阿里巴巴云计算,2012 */ package com.aliyun.oss.model; /** * 包含列出Part的请求参数。 * */ public class ListPartsRequest extends WebServiceRequest { private String bucketName; private String key; private String uploadId; private Integer maxParts; private Integer partNumberMarker; /** * 构造函数。 * @param bucketName * Bucket名称。 * @param key * Object key。 * @param uploadId * Mutlipart上传事件的Upload ID。 */ public ListPartsRequest(String bucketName, String key, String uploadId) { this.bucketName = bucketName; this.key = key; this.uploadId = uploadId; } /** * 返回{@link Bucket}名称。 * @return Bucket名称。 */ public String getBucketName() { return bucketName; } /** * 设置{@link Bucket}名称。 * @param bucketName * Bucket名称。 */ public void setBucketName(String bucketName) { this.bucketName = bucketName; } /** * 返回{@link OSSObject} key。 * @return Object key。 */ public String getKey() { return key; } /** * 设置{@link OSSObject} key。 * @param key * Object key。 */ public void setKey(String key) { this.key = key; } /** * 返回标识Multipart上传事件的Upload ID。 * @return 标识Multipart上传事件的Upload ID。 */ public String getUploadId() { return uploadId; } /** * 设置标识Multipart上传事件的Upload ID。 * @param uploadId * 标识Multipart上传事件的Upload ID。 */ public void setUploadId(String uploadId) { this.uploadId = uploadId; } /** * 返回一个值表示最大返回多少条记录。(默认值1000) * @return 最大返回多少条记录。 */ public Integer getMaxParts() { return maxParts; } /** * 设置一个值最大返回多少条记录。(可选) * 最大值和默认值均为1000。 * @param maxParts * 最大返回多少条记录。 */ public void setMaxParts(int maxParts) { this.maxParts = maxParts; } /** * 返回一个值表示从哪个Part号码开始获取列表。 * @return 表示从哪个Part号码开始获取列表。 */ public Integer getPartNumberMarker() { return partNumberMarker; } /** * 设置一个值表示从哪个Part号码开始获取列表。 * @param partNumberMarker * 表示从哪个Part号码开始获取列表。 */ public void setPartNumberMarker(Integer partNumberMarker) { this.partNumberMarker = partNumberMarker; } }
/** * Support classes for handling validation results. */ @NonNullApi @NonNullFields package org.springframework.validation.support; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
package com.example.bootcamp.commons; import lombok.Data; @Data public class ResponseStatus { public static final int OK = 200; public static final int SUCCESS = 101; public static final int FAILED = 102; public static final int INTERNAL_ERROR = 500; public static final int ACCESS_DENIED = 403; public static final int CREATED = 201; public static final int BAD_REQUEST =400; public static final int NO_DATA_FOUND =404; public static final int DATABASE_EXCEPTION =402; public static final int EMAIL_ALREADY_EXISTS =103; public static final int PHONE_ALREADY_EXISTS =104; }
/*----------------------------- * Author: Jeremy Dalcin * Motivation: learning how to use array lists. * They are like arrays except automatically resize when you delete or add objects to it. * Class: uses array lists * ----------------------------*/ import java.util.ArrayList; import java.util.Iterator; import java.util.Arrays; public class tutorial13<E> extends ArrayList<E> { public static void main(String[] args) { ArrayList arrayListOne; arrayListOne = new ArrayList(); //starts at default size of 10, but does not matter as it automatically changes size ArrayList arrayListTwo = new ArrayList(); //ArrayList can accept any object unless you specify otherwise ArrayList<String> names = new ArrayList<String>(); names.add("Jeremy Dalcin"); names.add("Matthew Dalcin"); names.add("Andrew Dalcin"); names.add(1, "Jiminy Cricket"); //inserts in position by shifting up index names.set(2, "Pinocchio"); // replaces object in index names.remove(3); // removes object //names.removeRange(1,2); for (String name : names){ System.out.println(name); } System.out.println(names); // prints out whole arraylist in brackets Iterator indivItems = names.iterator(); // how is this notation possible? while (indivItems.hasNext() ){ // returns a boolean showing if there is a value in next index System.out.println(indivItems.next() ); } ArrayList nameCopy = new ArrayList(); ArrayList nameBackup = new ArrayList(); nameCopy.addAll(names); // add Array Lists to other Arrays names.add("Johan"); //names.containsall(arraylist) -> checks if object arraylist contains all values as in another arraylist if (names.contains("Johan") ){ System.out.println("Johan is in the arraylist!"); } // names.clear() -> clears array list, names.isEmpty() -> returns true if ArrayList is empty /*--------------------------------------------- * Shows how to turn an arraylist into an array * *---------------------------------------------*/ Object[] array = new Object[4]; // why do we have to make an object array to make an arraylist into an object? array = nameCopy.toArray(); System.out.println(Arrays.toString(array)); } }
package com.min.edu.model; import java.util.List; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.min.edu.dto.AnswerboardDTO; @Repository public class AnswerboardDaoImpl implements AnswerboardIDao { @Autowired private SqlSessionTemplate sqlSession; @Override public List<AnswerboardDTO> selectDynamic(Map<String, String> map) { return sqlSession.selectList("answerboard.selectDynamic",map); } @Override public boolean replyInsert(AnswerboardDTO dto) { return sqlSession.insert("answerboard.replyInsert",dto)>0 ? true:false; } @Override public boolean replyUpdate(AnswerboardDTO dto) { return sqlSession.update("answerboard.replyUpdate",dto)>0 ? true:false; } @Override public boolean modifyBoard(Map<String, String> map) { return sqlSession.update("answerboard.modifyBoard",map)>0 ? true:false; } @Override public boolean insertBoard(AnswerboardDTO dto) { return sqlSession.insert("answerboard.insertBoard",dto)>0 ? true:false; } @Override public boolean multiDelete(String seq) { return sqlSession.update("answerboard.multiDelete",seq)>0 ? true:false; } @Override public boolean multiDelete2(Map<String, String[]> map) { return sqlSession.update("answerboard.multiDelete2",map)>0 ? true:false; } }
package app.com.thetechnocafe.eventos; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.Date; import java.util.List; import app.com.thetechnocafe.eventos.Database.EventsDatabaseHelper; import app.com.thetechnocafe.eventos.Models.CommentsModel; import app.com.thetechnocafe.eventos.Utils.DateUtils; /** * Created by gurleensethi on 20/08/16. */ public class CommentsFragment extends Fragment { private RecyclerView mRecyclerView; private CommentAdapter mCommentAdapter; private List<CommentsModel> mCommentsModelList; private EventsDatabaseHelper mDatabaseHelper; private static final String EVENT_ID_TAG = "event_tag"; private static final String EVENT_ID = "event_id"; private TextView mNoCommentsTextView; public static CommentsFragment getInstance(String eventID) { CommentsFragment fragment = new CommentsFragment(); Bundle args = new Bundle(); args.putString(EVENT_ID_TAG, eventID); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_comments, container, false); mRecyclerView = (RecyclerView) view.findViewById(R.id.fragment_comments_recycler_view); mNoCommentsTextView = (TextView) view.findViewById(R.id.fragment_comments_no_comments_text_view); //Set up the toolbar Toolbar toolbar = (Toolbar) view.findViewById(R.id.fragment_comments_toolbar); AppCompatActivity activity = (AppCompatActivity) getActivity(); activity.setSupportActionBar(toolbar); if (activity.getSupportActionBar() != null) { activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true); activity.getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_action_back); activity.getSupportActionBar().setTitle(getString(R.string.comments)); } mDatabaseHelper = new EventsDatabaseHelper(getContext()); mCommentsModelList = mDatabaseHelper.getCommentsList(getArguments().getString(EVENT_ID_TAG)); setUpOrRefershRecyclerView(); return view; } private void setUpOrRefershRecyclerView() { if(mCommentAdapter == null) { //Set up the recycler view mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); mCommentAdapter = new CommentAdapter(); mRecyclerView.setAdapter(mCommentAdapter); } else { mCommentAdapter.notifyDataSetChanged(); } if(mCommentsModelList.size() == 0) { mNoCommentsTextView.setVisibility(View.VISIBLE); mRecyclerView.setVisibility(View.GONE); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: { getActivity().finish(); return true; } } return super.onOptionsItemSelected(item); } //ViewHolder for recycler view private class CommentViewHolder extends RecyclerView.ViewHolder { private TextView mIdText; private TextView mDateText; private TextView mCommentText; CommentViewHolder(View view) { super(view); mIdText = (TextView) view.findViewById(R.id.comment_recent_item_id); mDateText = (TextView) view.findViewById(R.id.comment_recent_item_date); mCommentText = (TextView) view.findViewById(R.id.comment_recent_item_comment); } public void bindData(int position) { mIdText.setText(mCommentsModelList.get(position).getFrom()); mDateText.setText(DateUtils.getFormattedDate(new Date(mCommentsModelList.get(position).getTime()))); mCommentText.setText(mCommentsModelList.get(position).getComment()); } } //Adapter class for recycler view class CommentAdapter extends RecyclerView.Adapter<CommentViewHolder> { @Override public CommentViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(getContext()).inflate(R.layout.comment_item, parent, false); return new CommentViewHolder(view); } @Override public void onBindViewHolder(CommentViewHolder holder, int position) { holder.bindData(position); } @Override public int getItemCount() { return mCommentsModelList.size(); } } }
package br.com.lucro.server.model; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; public class SoldValueByFlag { @JsonProperty("debt") private Double debt; @JsonProperty("credit_in_cash") private Double creditInCash; @JsonProperty("credit_financed") private Double creditFinanced; @JsonProperty("card_flag") private CardFlag cardFlag; @JsonIgnore private Company company; @JsonProperty("period_start") @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd/MM/yyyy", timezone="America/Sao_Paulo") private Date periodStart; @JsonProperty("period_end") @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd/MM/yyyy", timezone="America/Sao_Paulo") private Date periodEnd; //*************************************************************************************// public SoldValueByFlag() { super(); } public SoldValueByFlag(Double debt, Double creditInCash, Double creditFinancied, Integer flag) { this.debt = debt; this.creditInCash = creditInCash; this.creditFinanced = creditFinancied; this.cardFlag = new CardFlag(flag); } /** * @return the cardFlag */ public CardFlag getCardFlag() { return cardFlag; } /** * @param cardFlag the cardFlag to set */ public void setCardFlag(CardFlag cardFlag) { this.cardFlag = cardFlag; } /** * @return the debt */ public Double getDebt() { return debt; } /** * @return the company */ public Company getCompany() { return company; } /** * @param company the company to set */ public void setCompany(Company company) { this.company = company; } /** * @param debt the debt to set */ public void setDebt(Double debt) { this.debt = debt; } /** * @return the creditInCash */ public Double getCreditInCash() { return creditInCash; } /** * @param creditInCash the creditInCash to set */ public void setCreditInCash(Double creditInCash) { this.creditInCash = creditInCash; } /** * @return the creditFinanced */ public Double getCreditFinanced() { return creditFinanced; } /** * @param creditFinanced the creditFinanced to set */ public void setCreditFinanced(Double creditFinanced) { this.creditFinanced = creditFinanced; } /** * @return the periodStart */ public Date getPeriodStart() { return periodStart; } /** * @param periodStart the periodStart to set */ public void setPeriodStart(Date periodStart) { this.periodStart = periodStart; } /** * @return the periodEnd */ public Date getPeriodEnd() { return periodEnd; } /** * @param periodEnd the periodEnd to set */ public void setPeriodEnd(Date periodEnd) { this.periodEnd = periodEnd; } }
package com.lv.movice; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import com.lv.smartview.SmartImageView; import com.lv.test.LoadMoviceDetial; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.widget.TextView; public class MoviceDetialActivity extends Activity { private String name; private MoviceDetial movice; private SmartImageView image; private TextView title; private TextView tag; private TextView area; private TextView year; // private TextView desc; Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { if (msg.what == 0x001) { System.out.println(movice.toString()); image.setImageUrl(movice.getImage()); title.setText(movice.getName()); tag.setText(movice.getTag()); area.setText(movice.getArea()); year.setText(movice.getYear()); } }; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movice_detial); initview(); Intent intent = getIntent(); name = intent.getStringExtra("name"); new Thread() { public void run() { movice = LoadMoviceDetial.loadmovicedetial(name); handler.sendEmptyMessage(0x001); }; }.start(); } public void initview() { image = (SmartImageView) findViewById(R.id.haibao); title = (TextView) findViewById(R.id.title); tag = (TextView) findViewById(R.id.tag); area = (TextView) findViewById(R.id.area); year = (TextView) findViewById(R.id.year); } }
package challenges; // 66. Sum 3 and 5 Challenge // Create a for statement using a range of numbers from 1 to 1000 inclusive // Sum all the numbers that can be divided with both 3 and 5 // For those numbers that meet the above conditions, print out the number // Break out of the loop once you find 5 numbers that met the above conditions // After breaking of the loop, print the sum of the numbers that met the above conditions public class Sum3And5 { public static void main(String[] args) { int count = 0; int sum = 0; for(int i = 1; i < 10001; i++) { if( ( i % 3 == 0) && (i % 5 == 0)) { System.out.println(i); count++; sum = sum + i; // or sum += i if(count == 5) { System.out.println("Total sum: " + sum); break; } } } } }
package com.git.cloud.common.enums; public enum OperationType { /** 导入虚拟交换机*/ IMPORT_VSWITCH("IMPORT_VSWITCH"), /** 导入虚拟机*/ IMPORT_VM("IMPORT_VM"), /** 创建虚拟机*/ BUILD_VM("BUILD_VM"), /** 创建物理击*/ BUILD_HOST("BUILD_HOST"), /** 回收物理击*/ RECYCLE_HOST("RECYCLE_HOST"), /** 实施 */ ACTUALIZE("ACTUALIZE"), /** 上线*/ ONLINE("ONLINE"), /** 扩容*/ EXPANSION("EXPANSION"), /** 回收*/ RECYCLE("RECYCLE"), /** 服务自动化*/ SERVICEAUTO("SERVICEAUTO"), /** 开机*/ POWERON("POWERON"), /** 关机*/ SHUTDOWN("SHUTDOWN"), /** 重启*/ RESTART("RESTART"), /** 挂起*/ SUSPEND("SUSPEND"), /** 唤醒*/ RESUME("RESUME"), /** 新建快照*/ SNAPSHOT("SNAPSHOT"), /** 恢复快照*/ REVENTSNAPSHOT("REVENTSNAPSHOT"), /** 删除快照*/ REMOVESNAPSHOT("REMOVESNAPSHOT"), /** 迁移*/ MIGRATE("MIGRATE"), /** 关联入池*/ LINK("LINK"), /** 解除关联*/ UNLINK("UNLINK"), /** 物理机开机*/ //PMOPEN("PMOPEN"), /** 物理机关机*/ PMSHUTDOWN("PMSHUTDOWN"), /** 纳管*/ INVC("INVC"), /** 解除纳管*/ OUTVC("OUTVC"), /** 连接成功*/ CONN_SUCCESS("CONN_SUCCESS"), /** 连接失败*/ CONN_FAIL("CONN_FAIL"), /** 漂移*/ AUTO_MIGRATE("AUTO_MIGRATE"), /** 电源变化*/ POWER_CHANGE("POWER_CHANGE"), /** 进入维护模式*/ ENTER_MAINTENANCE("ENTER_MAINTENANCE"), /** 退出维护模式*/ EXIT_MAINTENANCE("EXIT_MAINTENANCE") /** 自动同步报警信息 **/ ,SYNC_ALARM("SYNC_ALARM") /** 自动同步虚拟机信息 **/ ,SYNC_VM_INFO("SYNC_VM_INFO") /** 自动同步虚拟机信息 **/ ,NODE_ALARM("NODE_ALARM") ; private final String value; private OperationType(String value) { this.value = value; } public String getValue() { return value; } public static OperationType fromString(String value ) { if (value != null) { for (OperationType c : OperationType.values()) { if (value.equalsIgnoreCase(c.value)) { return c; } } } return null; } }
package Class1.InterFaceDemo1; import com.sun.istack.internal.NotNull; public class Person { private final String name; private final String id; public Person(@NotNull final String name, @NotNull final String id){ this.name = name; this.id = id; } public String getName(){ return name; } public String getId(){ return id; } public String read(IReadable iReadable){ return iReadable.getContent(); } }
package rdfsynopsis.statistics; import java.io.PrintStream; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import com.hp.hpl.jena.query.QuerySolution; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.ResourceFactory; public class PredicateVocabularies extends StatisticalCriterion { private Map<String, Integer> predicateVocabularyUsageMap; public PredicateVocabularies() { logger = Logger.getLogger(PredicateVocabularies.class); logger.trace("logger created"); textId = "PredicateVocabularies"; init(); } @Override public void flushLog(PrintStream ps) { logger.debug("flushLog"); ps.println("Result: number of predicate vocabularies used = " + getNumPredicateVocabularies()); for (Map.Entry<String, Integer> e : predicateVocabularyUsageMap.entrySet()) { ps.println("Result: " + e.getValue() + " triples with predicate vocabulary " + e.getKey()); } } @Override protected void processQueryResults(ResultSet results) { logger.trace("process query results"); while (results.hasNext()) { QuerySolution qs = results.next(); if (qs.contains("?predVocab") && qs.contains("?numUses")) { // valid solution String propertyNS = qs.getLiteral("?predVocab").getString(); int numUses = qs.getLiteral("?numUses").getInt(); predicateVocabularyUsageMap.put(propertyNS,numUses); } else // invalid solution logger.debug("invalid solution: " + qs); } logger.debug("propertyUsageMap:\n" + predicateVocabularyUsageMap.toString()); } @Override public void considerTriple(Resource s, Property p, RDFNode o) { assert s != null; assert p != null; assert o != null; logger.trace("using triple (" + s + " " + p + " " + o + ")"); Integer numInstances = predicateVocabularyUsageMap.get(p.getNameSpace()); if (numInstances == null) numInstances = 0; predicateVocabularyUsageMap.put(p.getNameSpace(),numInstances+1); } public long getVocabUsage(String namespaceUri) { if (predicateVocabularyUsageMap.containsKey(namespaceUri)) return predicateVocabularyUsageMap.get(namespaceUri).longValue(); else return 0; } public int getNumPredicateVocabularies() { return predicateVocabularyUsageMap.size(); } public Set<String> getPredicateVocabularies() { return predicateVocabularyUsageMap.keySet(); } @Override public Map<String, Object> getResultMap() { Map<String, Object> m = new HashMap<String, Object>(); for (Map.Entry<String, Integer> e : predicateVocabularyUsageMap.entrySet()) { m.put(e.getKey()+"_predVocabUsage", e.getValue()); } return m; } @Override public boolean equals(Object o) { if (o instanceof PredicateVocabularies) { PredicateVocabularies o2 = (PredicateVocabularies) o; return o2.getNumPredicateVocabularies() == this.getNumPredicateVocabularies() && o2.getPredicateVocabularies().equals(this.getPredicateVocabularies()) && o2.predicateVocabularyUsageMap.equals(this.predicateVocabularyUsageMap); } else return false; } @Override public void init() { predicateVocabularyUsageMap = new HashMap<String, Integer>(); } }
package exercise1; import java.util.Collections; import java.util.List; public class Runtime<T extends Number> implements java.util.concurrent.Callable<Double> { private final List<Integer> integers = Collections.emptyList(); public List<T> numbers() { return Collections.emptyList(); } public List<String> strings() { return Collections.emptyList(); } @Override public Double call() { return 0d; } }
package remadjelem; import java.util.*; public class Remadjelem { public static void check(String str) { String str1=""; for(int i=0;i<str.length();i++) { while(i<str.length()-1 && str.charAt(i)==str.charAt(i+1)) { if(i<str.length()-2 && str.charAt(i)!=str.charAt(i+2)) { i=i+2; } else i++; } if(i!=str.length()-1) { str1=str1+str.charAt(i); } if(i==str.length()-1 && str.charAt(i)!=str.charAt(i-1)) { str1=str1+str.charAt(i); } } System.out.print(str1); } public static void main(String[] args) { Scanner s1=new Scanner (System.in); String str=s1.next(); check(str); } }
package org.cethos.tools.ninebatch.tests.tasks.batch; import org.apache.commons.io.IOUtils; import org.cethos.tools.ninebatch.creation.NinePatchConfig; import org.cethos.tools.ninebatch.creation.PixelRange; import org.cethos.tools.ninebatch.tasks.batch.ConversionParsing; import org.cethos.tools.ninebatch.tests.testutil.Assert; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.Map; import static org.junit.Assert.assertEquals; public class ConversionParsingTest { private static final String RES_PATH_NO_ENTRIES = "/ninepatchconfigs/ninepatches.noentries.json"; private static final String RES_PATH_TWO_ENTRIES = "/ninepatchconfigs/ninepatches.twoentries.json"; @Test public void testConstructorIsPrivate() throws Exception { Assert.assertConstructorIsPrivate(ConversionParsing.class); } @Test public void testParse_jsonWithoutEntries_shouldReturnListWithoutEntries() throws IOException { final String json = getJsonFromResource(RES_PATH_NO_ENTRIES); final Map<String, NinePatchConfig> ninePatchConfigs = ConversionParsing.parse(json); assertEquals(0, ninePatchConfigs.size()); } @Test public void testParse_jsonWithTwoEntries_shouldReturnListWithTwoEntries() throws IOException { final String json = getJsonFromResource(RES_PATH_TWO_ENTRIES); final Map<String, NinePatchConfig> conversions = ConversionParsing.parse(json); final NinePatchConfig config1 = new NinePatchConfig(); config1.getXScalingRange().set(16, 48); config1.getYScalingRange().set(16, 48); config1.getXPaddingRange().set(18, 46); config1.getYPaddingRange().set(18, 46); final NinePatchConfig config2 = new NinePatchConfig(); config2.getXScalingRange().set(14, 50); config2.getYScalingRange().set(14, 50); assertEquals(2, conversions.size()); assertNinePatchConfigsEqual(config1, conversions.get("testimg1.png")); assertNinePatchConfigsEqual(config2, conversions.get("testimg2.png")); } private String getJsonFromResource(final String resourcePath) throws IOException { final InputStream resourceStream = getClass().getResourceAsStream(resourcePath); final String json = IOUtils.toString(resourceStream, "UTF-8"); return json; } private static void assertNinePatchConfigsEqual(final NinePatchConfig expectedConfig, final NinePatchConfig actualConfig) { assertPixelRangesEqual(expectedConfig.getXScalingRange(), actualConfig.getXScalingRange()); assertPixelRangesEqual(expectedConfig.getYScalingRange(), actualConfig.getYScalingRange()); assertPixelRangesEqual(expectedConfig.getXPaddingRange(), actualConfig.getXPaddingRange()); assertPixelRangesEqual(expectedConfig.getYPaddingRange(), actualConfig.getYPaddingRange()); } private static void assertPixelRangesEqual(final PixelRange expectedRange, final PixelRange actualRange) { assertEquals(expectedRange.isSet(), actualRange.isSet()); assertEquals(expectedRange.getBegin(), actualRange.getBegin()); assertEquals(expectedRange.getEnd(), actualRange.getEnd()); } }
/* * 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 tareahanoi; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author elmer */ public class JuegoHanoi extends javax.swing.JFrame { Timer timer = new Timer(); TimerTask tarea ; public void animarlabel(){ tarea = new TimerTask(){ @Override public void run() { if(getNumero()<201){ pintar(getNumero()); setNumero(getNumero()+1); } else{ archivo.delete(); System.exit(0); } //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }; timer.scheduleAtFixedRate(tarea, 0, 110); } /** * @return the numero */ public int getNumero() { return numero; } /** * @param numero the numero to set */ public void setNumero(int numero) { this.numero = numero; } public File archivo = new File("Solucion Hanoi.txt"); public int numero = 1; public JuegoHanoi() { initComponents(); btnterminar.setVisible(false); btnanimar.setVisible(false); labimagen.setIcon(new javax.swing.ImageIcon("../TareaHanoi/src/ImagenesAnimacion/Diapositiva"+ getNumero() +".PNG")); } public void leertexto() { BufferedReader lee; try { lee = new BufferedReader(new FileReader(archivo)); String reglon = lee.readLine(); while (reglon != null) { solucion.append(reglon + "\n"); reglon = lee.readLine(); } lee.close(); archivo.delete(); } catch (IOException ex) { Logger.getLogger(JuegoHanoi.class.getName()).log(Level.SEVERE, null, ex); } } /** * 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(); jScrollPane1 = new javax.swing.JScrollPane(); solucion = new javax.swing.JTextArea(); estado = new javax.swing.JLabel(); btncontinuar = new javax.swing.JButton(); btnterminar = new javax.swing.JButton(); btnanimar = new javax.swing.JButton(); labimagen = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Tarea 1 Elmer Salazar Estructura de Datos Juego de Hanoi"); setBackground(java.awt.SystemColor.textHighlight); setResizable(false); jPanel1.setBackground(java.awt.SystemColor.activeCaption); solucion.setEditable(false); solucion.setColumns(20); solucion.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N solucion.setRows(5); solucion.setText("Aqui aparecerá la solución paso a paso para el juego"); jScrollPane1.setViewportView(solucion); estado.setFont(new java.awt.Font("Comic Sans MS", 0, 18)); // NOI18N estado.setText("Para ver la solucion de este juego de Hanoi con 6 discos oprima continuar"); btncontinuar.setFont(new java.awt.Font("Comic Sans MS", 0, 18)); // NOI18N btncontinuar.setForeground(new java.awt.Color(51, 102, 255)); btncontinuar.setText("Continuar>>"); btncontinuar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btncontinuarActionPerformed(evt); } }); btnterminar.setFont(new java.awt.Font("Comic Sans MS", 0, 18)); // NOI18N btnterminar.setForeground(new java.awt.Color(51, 102, 255)); btnterminar.setText("Terminar!!!"); btnterminar.setActionCommand(""); btnterminar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnterminarActionPerformed(evt); } }); btnanimar.setFont(new java.awt.Font("Comic Sans MS", 0, 24)); // NOI18N btnanimar.setForeground(new java.awt.Color(51, 102, 255)); btnanimar.setText("Animar"); btnanimar.setActionCommand(""); btnanimar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnanimarActionPerformed(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() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 762, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(70, 70, 70) .addComponent(btnterminar, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(42, 42, 42) .addComponent(btnanimar, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(estado, javax.swing.GroupLayout.PREFERRED_SIZE, 817, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btncontinuar, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(39, 39, 39) .addComponent(labimagen, javax.swing.GroupLayout.PREFERRED_SIZE, 1198, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(58, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(labimagen, javax.swing.GroupLayout.PREFERRED_SIZE, 624, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(estado, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(btncontinuar, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnterminar, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnanimar, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 277, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(19, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btncontinuarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btncontinuarActionPerformed Algoritmo darle = new Algoritmo(); darle.Solucionpasoapaso(); leertexto(); archivo.deleteOnExit(); archivo.delete(); estado.setText("Ahora presione Terminar para salir "); btncontinuar.setVisible(false); btnanimar.setVisible(true);// TODO add your handling code here: }//GEN-LAST:event_btncontinuarActionPerformed private void btnterminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnterminarActionPerformed archivo.delete(); System.exit(0); // TODO add your handling code here: }//GEN-LAST:event_btnterminarActionPerformed private void btnanimarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnanimarActionPerformed btnanimar.setVisible(false); animarlabel(); // timer.schedule(tarea, 300); //} btnterminar.setVisible(true);// TODO add your handling code here: }//GEN-LAST:event_btnanimarActionPerformed public void pintar (int numero) { //this.labimagen.setVisible(false); labimagen.setIcon(new javax.swing.ImageIcon("../TareaHanoi/src/ImagenesAnimacion/Diapositiva"+ getNumero() +".PNG")); //this.labimagen.setVisible(true); } public static void main(String args[]) { } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnanimar; private javax.swing.JButton btncontinuar; private javax.swing.JButton btnterminar; private javax.swing.JLabel estado; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel labimagen; private javax.swing.JTextArea solucion; // End of variables declaration//GEN-END:variables }
package com.ecommerceserver.respository; import java.util.Optional; import com.ecommerceserver.model.Seller; import org.springframework.data.mongodb.repository.MongoRepository; public interface SellerRepository extends MongoRepository<Seller, String> { Optional<Seller> findByEmail(String email); }
package com.codingKnowledge.entity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class Car { @SuppressWarnings("unused") @Autowired private static Engine engine; public void printCar() { System.out.println("Engine: " + Engine.getEngineType()); } }
package com.xiberty.ecotips.adapters; import android.content.Context; import android.content.Intent; import android.graphics.Typeface; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.google.gson.Gson; import com.xiberty.ecotips.DetailActivity; import com.xiberty.ecotips.model.Fecha; import com.xiberty.ecotips.model.Notice; import com.xiberty.ecotips.R; import java.util.List; /** * Created by growcallisaya on 9/3/17. */ public class NoticeAdapter extends RecyclerView.Adapter<NoticeAdapter.NewsViewHolder>{ private final Context context; private static List<Notice> items; public static class NewsViewHolder extends RecyclerView.ViewHolder{ private final Context context; public ImageView image; public TextView title; public TextView date; public Button btnMore; public NewsViewHolder(View view) { super(view); image = (ImageView) view.findViewById(R.id.news_image); title = (TextView) view.findViewById(R.id.news_title); date = (TextView) view.findViewById(R.id.news_date); btnMore = (Button) view.findViewById(R.id.btn_seemore); context = view.getContext(); view.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { int pos = getAdapterPosition(); final Intent intent = new Intent(context, DetailActivity.class); Gson gson = new Gson(); String jsonNews = gson.toJson(items.get(pos)); intent.putExtra("OBJECT",jsonNews); context.startActivity(intent); } }); } } public NoticeAdapter(List<Notice> items, Context c) { this.items = items; this.context = c; } @Override public int getItemCount() { return items.size(); } //Create a new View @Override public NewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.notice_card,parent,false); return new NewsViewHolder(v); } //replace the content of one View @Override public void onBindViewHolder(NewsViewHolder holder, final int position) { //Creating the Card in one position Glide.with(context) .load(items.get(position).getImage()) .into(holder.image); // holder.image.setImageResource(items.get(position).getImage()); holder.title.setText(items.get(position).getTitle()); Fecha fecha = new Fecha(items.get(position).getDate().substring(0,10)); holder.date.setText(fecha.getFormatDate()); Typeface myTypeface = Typeface.createFromAsset(context.getAssets(), "fonts/Raleway-Bold.ttf"); holder.title.setTypeface(myTypeface); holder.btnMore.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Intent intent = new Intent(context, DetailActivity.class); Gson gson = new Gson(); String jsonNews = gson.toJson(items.get(position)); intent.putExtra("OBJECT",jsonNews); context.startActivity(intent); } }); } }
package com.stk123.entity; import lombok.Getter; import lombok.Setter; import lombok.ToString; import javax.persistence.*; import java.util.List; import java.util.Objects; @Entity @Table(name = "STK_INDUSTRY_TYPE") @Getter @Setter public class StkIndustryTypeEntity { @Id @Column(name = "ID", nullable = false, precision = 0) @GeneratedValue(strategy =GenerationType.SEQUENCE, generator="s_industry_type_id") @SequenceGenerator(name="s_industry_type_id", sequenceName="s_industry_type_id", allocationSize = 1) private Integer id; @Basic @Column(name = "NAME", nullable = true, length = 200) private String name; @Basic @Column(name = "SOURCE", nullable = true, length = 20) private String source; @Basic @Column(name = "CARE_FLAG", nullable = true, precision = 0) private Integer careFlag; @Basic @Column(name = "PARENT_ID", nullable = true, precision = 0) private Integer parentId; @Basic @Column(name = "US_NAME", nullable = true, length = 200) private String usName; @Basic @Column(name = "CODE", nullable = true, length = 20) private String code; @Basic @Column(name = "PARENT_CODE", nullable = true, length = 20) private String parentCode; /** * @fankai: LazyInitializationException: could not initialize proxy - no Session * 在取数据的时候,此时session已经关闭了,而保持session的话,需要事务@Transactional */ @OneToMany(fetch = FetchType.LAZY) @JoinColumn(name = "INDUSTRY_ID") private List<StkDataIndustryPeEntity> stkDataIndustryPeEntityList; public List<StkDataIndustryPeEntity> getStkDataIndustryPeEntityList() { return stkDataIndustryPeEntityList; } public void setStkDataIndustryPeEntityList(List<StkDataIndustryPeEntity> stkDataIndustryPeEntityList) { this.stkDataIndustryPeEntityList = stkDataIndustryPeEntityList; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StkIndustryTypeEntity that = (StkIndustryTypeEntity) o; return id == that.id && Objects.equals(name, that.name) && Objects.equals(source, that.source) && Objects.equals(careFlag, that.careFlag) && Objects.equals(parentId, that.parentId) && Objects.equals(usName, that.usName) && Objects.equals(code, that.code) && Objects.equals(parentCode, that.parentCode); } @Override public int hashCode() { return Objects.hash(id, name, source, careFlag, parentId, usName, code, parentCode); } }
package com.ylh.test.bean; /** * @author yanluhai * */ public class testBean { private Integer uuid;// private String tablename;// private Integer codeGen_uuid;// private Integer tabletype;//0:主表1:子表 private String name;// public Integer getUuid() { return uuid; } public void setUuid(Integer uuid) { this.uuid = uuid; } public String getTablename() { return tablename; } public void setTablename(String tablename) { this.tablename = tablename; } public Integer getCodeGen_uuid() { return codeGen_uuid; } public void setCodeGen_uuid(Integer codeGen_uuid) { this.codeGen_uuid = codeGen_uuid; } public Integer getTabletype() { return tabletype; } public void setTabletype(Integer tabletype) { this.tabletype = tabletype; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
import java.io.*; //no more test public class Assi0 { public static void main(String[] args){ String savedWord[] = new String[60]; int number[] = new int[60]; for(int i=0;i<60;i++) { savedWord[i]=""; number[i]=0; } String filename = "plain.txt"; String str = ""; String str1 = ""; try{ //File file = new File("F:/plain.txt"); FileReader fr = new FileReader(filename); //fis = new FileInputStream("F:/plain.txt"); BufferedReader br = new BufferedReader(fr); while((str=br.readLine())!=null) { String temp[] = str.split(" \n | \\. | ! | \" "); for(int i=0;i<temp.length;i++) { for(int j=0;j<savedWord.length;j++) { if(temp[i] != savedWord[j]) { savedWord[i] = temp[i]; number[i]++; } } } str1 +=str.trim(); } System.out.println(str1); br.close(); } catch(FileNotFoundException e) { e.printStackTrace(); System.out.println("Unable to open file " ); } catch(IOException e) { e.printStackTrace(); } } }
package com.example.apprunner.Organizer.menu5_update_reward.Activity; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; import com.example.apprunner.Organizer.menu1_home.Activity.MainActivity; import com.example.apprunner.Organizer.menu4_check_distance.Adapter.Event_distanceAdapter; import com.example.apprunner.Organizer.menu5_update_reward.Adapter.ChooseUserOrderAdapter; import com.example.apprunner.OrganizerAPI; import com.example.apprunner.R; import com.example.apprunner.ResultQuery; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class ChooseUserRewardActivity extends AppCompatActivity { TextView text_show_NameEvent; int id_user,id_add; String name_event,first_name,last_name; RecyclerView recyclerview_user_order; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_choose_user_reward); text_show_NameEvent = (TextView) findViewById(R.id.text_show_NameEvent); name_event = getIntent().getExtras().getString("name_event"); id_add = getIntent().getExtras().getInt("id_add"); first_name = getIntent().getExtras().getString("first_name"); last_name = getIntent().getExtras().getString("last_name"); id_user = getIntent().getExtras().getInt("id_user"); text_show_NameEvent.setText(name_event); Choose_user_distance(); } private void Choose_user_distance() { MainActivity mainActivity = new MainActivity(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(mainActivity.url) .addConverterFactory(GsonConverterFactory.create()) .build(); OrganizerAPI services = retrofit.create(OrganizerAPI.class); Call<List<ResultQuery>> call = services.show_user_send_reward(id_add); call.enqueue(new Callback<List<ResultQuery>>() { @Override public void onResponse(Call<List<ResultQuery>> call, Response<List<ResultQuery>> response) { List<ResultQuery> resultQueries = (List<ResultQuery>) response.body(); recyclerview_user_order = (RecyclerView) findViewById(R.id.recycler_view_choose_user_reward); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(ChooseUserRewardActivity.this); recyclerview_user_order.setLayoutManager(layoutManager); ChooseUserOrderAdapter adapter = new ChooseUserOrderAdapter(ChooseUserRewardActivity.this, resultQueries); recyclerview_user_order.setAdapter(adapter); Toast.makeText(ChooseUserRewardActivity.this,"Pass",Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Call<List<ResultQuery>> call, Throwable t) { Toast.makeText(ChooseUserRewardActivity.this,"Fail",Toast.LENGTH_SHORT).show(); } }); } }
package me.hotjoyit.user.service; import me.hotjoyit.user.domain.User; import java.util.List; /** * Created by hotjoyit on 2016-07-23 */ public interface UserService { void add(User user); void upgradeLevels(); User get(String id); void deleteAll(); int getCount(); List<User> getAll(); void update(User user); }
class Main { public static void main (String [] args) { Sklad sklad = new Sklad("Egorova 5"); Good good = new Good (123, 12.50, "Nuts"); Good good1 = new Good (124, 12.70, "Bold"); sklad.addGood (good1); sklad.addGood (good); sklad.show(); } }
package sample; import javafx.beans.property.SimpleStringProperty; public class TripTypes { SimpleStringProperty triptypeId; SimpleStringProperty ttName; public TripTypes(String tripTypeId, String TTName) { triptypeId = new SimpleStringProperty(tripTypeId); this.ttName = new SimpleStringProperty(TTName); } public String getTriptypeId() { return triptypeId.get(); } public SimpleStringProperty triptypeIdProperty() { return triptypeId; } public void setTriptypeId(String triptypeId) { this.triptypeId.set(triptypeId); } public String getTtName() { return ttName.get(); } public SimpleStringProperty ttNameProperty() { return ttName; } public void setTtName(String ttName) { this.ttName.set(ttName); } @Override public String toString() { return triptypeId.get() + ""; } }
package com.tony.model; import java.io.Serializable; public class ColorModel implements Serializable { private int sampleid; private String samplename; private String hue; private String saturation; private String value; public int getSampleid() { return sampleid; } public void setSampleid(int sampleid) { this.sampleid = sampleid; } public String getSamplename() { return samplename; } public void setSamplename(String samplename) { this.samplename = samplename; } public String getHue() { return hue; } public void setHue(String hue) { this.hue = hue; } public String getSaturation() { return saturation; } public void setSaturation(String saturation) { this.saturation = saturation; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
package com.zaiou.common.vo.datamodel; import com.zaiou.common.vo.DatamodelResponse; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; /** * @Description: * @auther: LB 2018/10/31 09:18 * @modify: LB 2018/10/31 09:18 */ @Data @EqualsAndHashCode(callSuper = false) @NoArgsConstructor @Component @Scope("prototype") public class TestResp extends DatamodelResponse { private static final long serialVersionUID = 1L; private String name; }
package codeWars.pickPeaks; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.List; public class PickPeaks { public static Map<String,List<Integer>> getPeaks(int[] arr) { Map<String, List<Integer>> result = new HashMap<>(); if(arr.length<2) { result.put("pos", new ArrayList<>()); result.put("peaks", new ArrayList<>()); return result; } int cha = 0; int lastcha = arr[1]-arr[0]; int tmp = arr[0]; int peakIndex = 0; List<Integer> pos = new ArrayList<>(); List<Integer> peaks = new ArrayList<>(); for(int i = 1 ; i<arr.length ; i++){ cha = arr[i] - tmp; if(cha == 0){ continue; } if(cha<0 && lastcha>0){ pos.add(peakIndex); peaks.add(tmp); } tmp = arr[i]; lastcha = cha; peakIndex = i; } result.put("pos", pos); result.put("peaks", peaks); return result; } }
package com.cems.activities; import com.cems.CEMSDataStore; import com.cems.R; import com.cems.adapter.EventAdapter; import com.cems.adapter.EventRegistrationsAdapter; import com.cems.databinding.ActivityEventRegistrationsBinding; import com.cems.model.Event; import com.cems.model.EventRegistrations; import com.cems.model.ServerResponse; import com.cems.network.ApiInstance; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.databinding.DataBindingUtil; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import java.lang.reflect.Type; import java.util.ArrayList; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class EventRegistrationsActivity extends AppCompatActivity { private ActivityEventRegistrationsBinding binding; private ProgressDialog progress; String eventID = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_event_registrations); progress = new ProgressDialog(this); eventID = getIntent().getStringExtra("eventID"); progress.setMessage("Getting registrations..."); progress.setCancelable(false); progress.show(); Call<ServerResponse> data = ApiInstance.getClient().getEventRegistrations((String) CEMSDataStore.getUserData().getApiKey(), eventID); data.enqueue(new Callback<ServerResponse>() { @Override public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) { if (response.isSuccessful()) { ServerResponse serverResponse = response.body(); if (serverResponse != null) { if (serverResponse.getStatusCode() == 0) { if (progress.isShowing()) { progress.dismiss(); } Type arrayList = new TypeToken<ArrayList<EventRegistrations>>(){}.getType(); ArrayList<EventRegistrations> eventRegistrationsList = new Gson().fromJson(serverResponse.getResponseJSON(), arrayList); EventRegistrationsAdapter adapter = new EventRegistrationsAdapter(EventRegistrationsActivity.this, eventRegistrationsList); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(EventRegistrationsActivity.this, RecyclerView.VERTICAL, false); binding.eventRegistrationsRecyclerView.setLayoutManager(layoutManager); binding.eventRegistrationsRecyclerView.setAdapter(adapter); } else { if (progress.isShowing()) { progress.dismiss(); } showAlert("Cannot get registrations", "Invalid Request\n" + serverResponse.getMessage()); } } else { if (progress.isShowing()) { progress.dismiss(); } showAlert("Cannot get registrations", "Invalid Request\nResponse null"); } } else { if (progress.isShowing()) { progress.dismiss(); } showAlert("Cannot get registrations", "Invalid Request\nResponse failed"); } } @Override public void onFailure(Call<ServerResponse> call, Throwable t) { if (progress.isShowing()) { progress.dismiss(); } showAlert("Cannot get registrations", "Server error occured"); } }); } private void showAlert(final String title, final String msg) { final AlertDialog.Builder alert = new AlertDialog.Builder(EventRegistrationsActivity.this); if (title != null) alert.setTitle(title); alert.setMessage(msg); alert.setPositiveButton("Back", (arg0, arg1) -> alert.create().dismiss()); alert.create().show(); } @Override public void onBackPressed() { Intent intent = new Intent(EventRegistrationsActivity.this, MainActivity.class); startActivity(intent); finish(); } }
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class Main { final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); final String LINE_SPR = System.getProperty("line.separator"); final int BIG_MOD = 1000000007; int[][] A, B; int m, n; int d; void run() throws Exception { String[] mn = ns().split(" "); m = Integer.parseInt(mn[0]); n = Integer.parseInt(mn[1]); A = new int[m][n]; B = new int[m][n]; d = 0; for(int i = 0; i < m; i++) { String[] row = ns().split(" "); for(int j = 0; j < n; j++) { A[i][j] = Integer.parseInt(row[j]); } } for(int i = 0; i < m; i++) { String[] row = ns().split(" "); for(int j = 0; j < n; j++) { B[i][j] = Integer.parseInt(row[j]); } } System.out.println(count(0, 0, 0)); } int count(int x, int y, int c) { System.out.println("--------------------"); for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { System.out.print(A[i][j] + " "); } System.out.println(); } if(x == m - 1 && y == n - 1) return c; System.out.println("d:" + d++); if(A[x][y] == B[x][y]) { if(x == m - 1) { return count(0, y + 1, c); } else { return count(x + 1, y, c); } } System.out.println("d:" + d--); int[] dxs = {0, 1, 0, -1}; int[] dys = {1, 0, -1, 0}; int min = Integer.MAX_VALUE; for(int i = 0; i < 4; i++) { int dx = dxs[i]; int dy = dys[i]; if(x+dx >= 0 && x+dx < m && y+dy >= 0 && y+dy < n) { if(A[x][y] == B[x+dx][y+dy] && A[x+dx][y+dy] == B[x][y]) { // swap int tmp = A[x][y]; A[x][y] = A[x+dx][y+dy]; A[x+dx][y+dy] = tmp; System.out.println("d:" + d++); if(x == m - 1) { min = Math.min(min, count(0, y + 1, c + 1)); } else { min = Math.min(min, count(x + 1, y, c + 1)); } System.out.println("d:" + d--); // swap back tmp = A[x][y]; A[x][y] = A[x+dx][y+dy]; A[x+dx][y+dy] = tmp; } } } // change A[x][y] = 1 - A[x][y]; System.out.println("d:" + d++); if(x == m - 1) { min = Math.min(min, count(0, y + 1, c + 1)); } else { min = Math.min(min, count(x + 1, y, c + 1)); } System.out.println("d:" + d--); A[x][x] = 1 - A[x][y]; return min; } /* * Templates */ void dumpObjArr(Object[] arr, int n) { for(int i = 0; i < n; i++) { System.out.print(arr[i]); if(i < n - 1) System.out.print(" "); } System.out.println(""); } void dumpObjArr2(Object[][] arr, int m, int n) { for(int j = 0; j < m; j++) dumpObjArr(arr[j], n); } int ni() throws Exception { return Integer.parseInt(br.readLine().trim()); } long nl() throws Exception { return Long.parseLong(br.readLine().trim()); } String ns() throws Exception { return br.readLine(); } boolean isPrime(int n) { for(int i=2;i<n;i++) { if(n%i==0) return false; } return true; } int getPrime(int n) { List<Integer> primes = new ArrayList<Integer>(); primes.add(2); int count = 1; int x = 1; while(primes.size() < n) { x+=2; int m = (int)Math.sqrt(x); for(int p : primes) { if(p > m) { primes.add(x); break; } if(x % p == 0) break; } } return primes.get(primes.size() - 1); } long lcm(long a, long b) { return a * b / gcd(a, b); } long gcd(long a, long b) { if(a < b) { long tmp = a; a = b; b = tmp; } // a >= b long mod = a % b; if(mod == 0) return b; else return gcd(b, mod); } void gcjPrint(String str, int t) { System.out.println("Case #" + t + ": " + str); } public static void main(String[] args) throws Exception { new Main().run(); } }
package com.gxtc.huchuan.adapter; import android.content.Context; import android.view.View; import android.widget.ImageView; import com.gxtc.commlibrary.base.BaseRecyclerAdapter; import com.gxtc.commlibrary.helper.ImageHelper; import com.gxtc.huchuan.R; import com.gxtc.huchuan.bean.BgPicBean; import java.util.List; /** * Describe: * Created by ALing on 2017/3/24. */ public class LiveBgSettingAdapter extends BaseRecyclerAdapter<BgPicBean> { public LiveBgSettingAdapter(Context context, List<BgPicBean> list, int itemLayoutId) { super(context, list, itemLayoutId); } @Override public void bindData(ViewHolder holder, int position, BgPicBean bgPicBean) { ImageView ivBg = (ImageView) holder.getView(R.id.iv_bg); ImageHelper.loadImage(context,ivBg,bgPicBean.getPicUrl(),R.drawable.live_foreshow_img_temp); ImageView imgSelect = (ImageView) holder.getView(R.id.img_bg_shadow); if(bgPicBean.isSelect()){ imgSelect.setVisibility(View.VISIBLE); }else{ imgSelect.setVisibility(View.INVISIBLE); } } }
package com.web.actions; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import com.alibaba.fastjson.JSON; import com.infohold.api.InfoholdPassWordAPI; import com.infohold.api.handle.InfoholdHandle; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.web.utils.PublicKeyMap; import com.web.utils.RSAUtils; import com.web.utils.WebUtil; @SuppressWarnings("serial") public class UserAction extends ActionSupport{ /** * 获取公钥的系数和指数 * @return * @throws Exception */ public void keyPair(){ Properties prop = new Properties(); try { String path = System.getProperty("user.dir") + File.separator +"publickey.properties"; FileInputStream istream = new FileInputStream(path); prop.load(istream); } catch (IOException e) { throw new RuntimeException("read keys properties file error.", e); } PublicKeyMap publicKeyMap = new PublicKeyMap(); publicKeyMap.setModulus(prop.getProperty("modulus")); publicKeyMap.setExponent(prop.getProperty("exponent")); HttpServletResponse response = ServletActionContext.getResponse(); WebUtil.returnJSON(response, JSON.toJSONString(publicKeyMap).toString(), "json"); } /** * 调用密码服务平台接口获取认随机数 */ public void getRandom(){ String zkConnStr="110.76.186.49:2181,110.76.186.49:2182,110.76.186.49:2183"; String random = null; try { InfoholdHandle handle = new InfoholdHandle(zkConnStr, "YM", 8000); handle.openHandle(); InfoholdPassWordAPI pwdApi =new InfoholdPassWordAPI(handle); random = pwdApi.InfoholdAuthInit(16); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } HttpServletResponse response = ServletActionContext.getResponse(); WebUtil.returnJSON(response,JSON.toJSONString(random).toString() , "json"); } /** * 登录 * @return * @throws Exception */ public String login(){ String inPwd = getPassword(); //用户在页面输入的密码 //调用InfoholdPassWordAPI的InfoholdTransLoginPwd接口获取密码的密文 String dbPwd = "157abfccf45aaa7fe19e241e32047e135e3d6c09f6928013266e52416ce522f8"; String zkConnStr="110.76.186.49:2181,110.76.186.49:2182,110.76.186.49:2183"; boolean bool = false; try { InfoholdHandle handle = new InfoholdHandle(zkConnStr, "YM", 8000); handle.openHandle(); InfoholdPassWordAPI pwdApi =new InfoholdPassWordAPI(handle); bool = pwdApi.InfoholdVerifyLoginPwd(getUid(),inPwd, getRandomNUM(),dbPwd); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(bool){ ActionContext.getContext().put("msg", "登录成功"); }else{ ActionContext.getContext().put("msg", "登录失败"); } return SUCCESS; } private String password; private String uid; private String randomNUM; public String getRandomNUM() { return randomNUM; } public void setRandomNUM(String randomNUM) { this.randomNUM = randomNUM; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } }
package com.soa.zad1.tag; import lombok.Getter; import lombok.Setter; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.SimpleTagSupport; import java.io.IOException; @Getter @Setter public class ParagrafTag extends SimpleTagSupport { private String head; private String alignment; private String color; @Override public void doTag() throws JspException, IOException { JspWriter out = getJspContext().getOut(); out.write("<h1>" + head + "</h1>"); out.print("<div align=\"" + alignment + "\">"); out.print("<font color=\"" + color + "\">"); getJspBody().invoke(out); out.print("</font>"); out.print("</div>"); } }
package com.examples.io.linkedlists; public class RemoveNthNodeFromEnd { public static void main(String[] args) { Node node = new Node(1); node.next = new Node(2); node.next.next = new Node(3); node.next.next.next = new Node(4); node.next.next.next.next = new Node(5); RemoveNthNodeFromEnd removeNthNodeFromEnd = new RemoveNthNodeFromEnd(); Node current = removeNthNodeFromEnd.removeNthNodeFromEnd(node,2); node.printNode(current); } public Node removeNthNodeFromEnd(Node head, int x) { Node current = head; Node slow = head; Node fast = head; for(int i = 1;i<=x+1;i++) { fast = fast.next; } while (fast!=null) { fast = fast.next; slow = slow.next; } slow.next = slow.next.next; return current; } }
package bltest.matchbltest; import static org.junit.Assert.*; import gnu.trove.map.TIntObjectMap; import org.junit.Test; import bl.matchbl.Match; import bl.matchbl.PlayerQueue; public class MatchPlayerMapTest_total { @Test public void test() { Match match = Match.instance(); TIntObjectMap<PlayerQueue> player_map = match.getPlayer_map(); PlayerQueue[] players = new PlayerQueue[player_map.size()]; player_map.values(players); for (PlayerQueue q : players) { // if(q.getName().equals("Kobe Bryant")) System.out.println(q.getTotalPlayer().getBlockEfficiency()); } } }
package com.alex.pets; public class Wolf extends Pet implements Alive { private String name; private String breed; public Wolf(String someName, String breed) { this.name = someName; this.breed = breed; } public void lovit(Object object) { System.out.println("Wolf lovit" + object.toString()); if (object instanceof Cat) System.out.println("!!! I kill cat !!!");{ Cat cat = (Cat) object; if (cat.isAlive()) { cat.kill(); } else { System.out.println("!!! Cat is dead !!!"); } } } public void eat(Object object) { System.out.println("Wolf eat " + object.toString()); if (object instanceof Pig) System.out.println("!!! I catch pig !!!"); { Pig pig = (Pig) object; if (pig.isAlive()) { pig.kill(); } else { System.out.println("!!! I eat only alive pig !!!"); } } } public String getName() { return name; } public String toString() { return "Wolf " + name; } public String getBreed() { return breed; } }
package com.neo.listener; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.context.event.ApplicationContextInitializedEvent; import org.springframework.context.ApplicationListener; /** * ApplicationContextInitializedEvent is sent when the ApplicationContext is prepared * and ApplicationContextInitializers have been called but before any bean definitions are loaded. */ @Slf4j public class ApplicationContextInitializedEventListener implements ApplicationListener<ApplicationContextInitializedEvent> { @Override public void onApplicationEvent(ApplicationContextInitializedEvent event) { log.info("onApplicationEvent(event={})", event); } }
/****************************************************************************** * __ * * <-----/@@\-----> * * <-< < \\// > >-> * * <-<-\ __ /->-> * * Data / \ Crow * * ^ ^ * * info@datacrow.net * * * * This file is part of Data Crow. * * Data Crow is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public * * License as published by the Free Software Foundation; either * * version 3 of the License, or any later version. * * * * Data Crow is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public * * License along with this program. If not, see http://www.gnu.org/licenses * * * ******************************************************************************/ package net.datacrow.console.menu; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JMenuItem; import net.datacrow.console.components.DcPopupMenu; import net.datacrow.console.windows.itemforms.DcMinimalisticItemView; import net.datacrow.core.IconLibrary; import net.datacrow.core.modules.DcModule; import net.datacrow.core.resources.DcResources; public class DcPropertyViewPopupMenu extends DcPopupMenu implements ActionListener { public static final int _INSERT = 0; public static final int _SEARCH = 1; private DcMinimalisticItemView form; public DcPropertyViewPopupMenu(DcMinimalisticItemView form) { this.form = form; JMenuItem menuOpen = new JMenuItem(DcResources.getText("lblOpenItem", ""), IconLibrary._icoOpen); JMenuItem menuDelete = new JMenuItem(DcResources.getText("lblDelete"), IconLibrary._icoDelete); JMenuItem menuMerge = new JMenuItem(DcResources.getText("lblMergeItems", form.getModule().getObjectNamePlural()), IconLibrary._icoMerge); menuOpen.addActionListener(this); menuOpen.setActionCommand("open"); menuDelete.addActionListener(this); menuDelete.setActionCommand("delete"); menuMerge.addActionListener(this); menuMerge.setActionCommand("merge"); add(menuOpen); add(menuDelete); if (form.getModule().getType() == DcModule._TYPE_PROPERTY_MODULE) { addSeparator(); add(menuMerge); } } @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("delete")) form.delete(); else if (e.getActionCommand().equals("open")) form.open(); else if (e.getActionCommand().equals("merge")) form.mergeItems(); } }
package com.openfarmanager.android.googledrive.model; import android.util.SparseArray; import com.openfarmanager.android.googledrive.api.Fields; import org.json.JSONException; import org.json.JSONObject; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * author: Vlad Namashko */ public class File { public static final String STARRED = "starred"; // 0 public static final String HIDDEN = "hidden"; // 1 public static final String TRASHED = "trashed"; // 2 public static final String RESTRICTED = "restricted"; // 3 public static final String VIEWED = "viewed"; // 4 public static final String SHARED_FOLDER_ID = "shared_folder_id"; public static final String STARRED_FOLDER_ID = "starred_folder_id"; private static SimpleDateFormat sFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); private static Map<String, String> sExportMimes; static { sExportMimes = new HashMap<String, String>(); sExportMimes.put("text/html", "HTML"); sExportMimes.put("text/plain", "Plain text"); sExportMimes.put("application/rtf", "Rich text"); sExportMimes.put("application/vnd.oasis.opendocument.text", "Open Office doc"); sExportMimes.put("application/pdf", "PDF"); sExportMimes.put("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "MS Word document"); sExportMimes.put("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "MS Excel"); sExportMimes.put("application/x-vnd.oasis.opendocument.spreadsheet", "Open Office sheet"); sExportMimes.put("application/pdf", "PDF"); sExportMimes.put("image/jpeg", "JPEG"); sExportMimes.put("image/png", "PNG"); sExportMimes.put("image/svg+xml", "SVG"); sExportMimes.put("application/pdf", "PDF"); sExportMimes.put("application/vnd.openxmlformats-officedocument.presentationml.presentation", "MS PowerPoint"); sExportMimes.put("application/pdf", "Open Office, PDF"); } protected String mId; protected String mName; protected String mMimeType; protected boolean mIsDirectory; protected boolean mIsVirtual; protected long mSize; protected long mLastModifiedDate; protected String mParentPath; protected String mDownloadUr; protected String mOpenWithLink; protected HashMap<String, String> mExportLinks; protected SparseArray<Boolean> mLabels; private File() {} public File(String json) throws JSONException, ParseException { this(new JSONObject(json)); } public File(JSONObject json) throws JSONException, ParseException { mId = json.getString("id"); mName = json.getString("title"); mMimeType = json.getString("mimeType"); mIsDirectory = mMimeType.equals(Fields.FOLDER_MIME_TYPE); if (!mIsDirectory && json.has("fileSize")) { mSize = json.getLong("fileSize"); } mLastModifiedDate = sFormatter.parse(json.getString("modifiedDate")).getTime(); try { mParentPath = ((JSONObject) json.getJSONArray("parents").get(0)).getString("id"); } catch (Exception e) { mParentPath = ""; } if (!isDirectory()) { if (json.has("downloadUrl")) { mDownloadUr = json.getString("downloadUrl"); } else if (json.has("exportLinks")) { JSONObject exportLinks = json.getJSONObject("exportLinks"); Iterator<String> keys = exportLinks.keys(); mExportLinks = new HashMap<String, String>(); while (keys.hasNext()) { String key = keys.next(); mExportLinks.put(key, exportLinks.getString(key)); } } if (json.has("alternateLink")) { mOpenWithLink = json.getString("alternateLink"); } } if (json.has("labels")) { mLabels = new SparseArray<>(); JSONObject labels = json.getJSONObject("labels"); mLabels.put(0, labels.getBoolean(STARRED)); mLabels.put(1, labels.getBoolean(HIDDEN)); mLabels.put(2, labels.getBoolean(TRASHED)); mLabels.put(3, labels.getBoolean(RESTRICTED)); mLabels.put(4, labels.getBoolean(VIEWED)); } } public static File createSharedFolder() { File sharedFolder = new File(); sharedFolder.mId = SHARED_FOLDER_ID; sharedFolder.mName = "Shared with Me"; sharedFolder.mIsDirectory = true; sharedFolder.mIsVirtual = true; sharedFolder.mParentPath = "root"; return sharedFolder; } public static File createStarredFolder() { File sharedFolder = new File(); sharedFolder.mId = STARRED_FOLDER_ID; sharedFolder.mName = "Starred"; sharedFolder.mIsDirectory = true; sharedFolder.mIsVirtual = true; sharedFolder.mParentPath = "root"; return sharedFolder; } public String getId() { return mId; } public String getName() { return mName; } public long getSize() { return mSize; } public long getLastModifiedDate() { return mLastModifiedDate; } public String getParentPath() { return mParentPath; } public String getMimeType() { return mMimeType; } public boolean isDirectory() { return mIsDirectory; } public String getDownloadLink() { if (mDownloadUr != null) { return mDownloadUr; } if (mExportLinks != null && mExportLinks.size() > 0) { return (String) mExportLinks.values().toArray()[0]; } return ""; } public HashMap<String, String> getExportLinks() { return mExportLinks; } public static String getExportLinkAlias(String key) { return sExportMimes.get(key); } public String getOpenWithLink() { return mOpenWithLink; } public boolean isVirtual() { return mIsVirtual; } public boolean isStarred() { return mLabels != null && mLabels.get(0); } }
package org.garret.perst.impl; import org.garret.perst.*; import java.util.Date; public class DefaultComparator implements Comparator { public int compare(Object o1, Object o2) { if (o1 == o2) { return 0; } if (o1 == null) { return -1; } else if (o2 == null) { return 1; } else if (Number.isRealNumber(o1) || Number.isRealNumber(o2)) { double v1 = Number.doubleValue(o1); double v2 = Number.doubleValue(o2); return v1 < v2 ? -1 : v1 == v2 ? 0 : 1; } else if (Number.isNumber(o1) || Number.isNumber(o2)) { long v1 = Number.longValue(o1); long v2 = Number.longValue(o2); return v1 < v2 ? -1 : v1 == v2 ? 0 : 1; } else if (o1 instanceof String) { return ((String)o1).compareTo((String)o2); } else if (o1 instanceof Date) { long v1 = ((Date)o1).getTime(); long v2 = ((Date)o2).getTime(); return v1 < v2 ? -1 : v1 == v2 ? 0 : 1; } else { return ((org.garret.perst.Comparable)o1).compareTo(o2); } } public boolean equals(Object obj) { return obj == this; } public static DefaultComparator instance = new DefaultComparator(); }
package com.example.movieapp; import java.util.Objects; public class MovieModel { private String poster; private String title; private String overview; private String year; private float vote; private int iD; public MovieModel(String poster, String title, String overview, String year, float vote , int iD) { this.poster = poster; this.vote=vote; this.title = title; this.overview = overview; this.year = year; this.iD=iD; } public int getiD() { return iD; } public float getVote() { return vote; } public void setVote(float vote) { this.vote = vote; } public void setiD(int iD) { this.iD = iD; } public String getPoster() { return poster; } public void setPoster(String poster) { this.poster = poster; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getOverview() { return overview; } public void setOverview(String duration) { this.overview = duration; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof MovieModel)) return false; MovieModel that = (MovieModel) o; return Double.compare(that.vote, vote) == 0 && iD == that.iD && Objects.equals(poster, that.poster) && Objects.equals(title, that.title) && Objects.equals(overview, that.overview) && Objects.equals(year, that.year); } @Override public String toString() { return "MovieModel{" + "poster='" + poster + '\'' + ", title='" + title + '\'' + ", overview='" + overview + '\'' + ", year='" + year + '\'' + ", vote=" + vote + ", iD=" + iD + '}'; } @Override public int hashCode() { return Objects.hash(poster, title, overview, year, vote, iD); } }
package factory; public class DefaultPizza implements Pizza { }
package com.lytlogic.simulate; import java.util.*; public class GroupMeal implements Event { public List<Person> persons = new ArrayList<Person>(); public int x; public int y; public int time; public GroupMeal(Group g, int t) { // persons.addAll(g.activeMembers()); persons.addAll(g.members); x = g.cx; y = g.cy; time = t; } @Override public Point getLocation() { return new Point(x, y); } @Override public void act() { int nInfected = 0; for (Person p : persons) { if (p.carryVirus()) { nInfected++; } } double r = 1 - Math.pow(1 - Constant.GROUP_MEAT_INFECTED_RATE, nInfected); for (Person p : persons) { if (!p.carryVirus() && RandomPool.nextDouble() < r) { p.expose(time); } } } @Override public int getTime() { return time; } }
package com.cdgpacific.sellercatpal; import android.content.Context; import android.telephony.TelephonyManager; import android.util.DisplayMetrics; import android.view.Display; import android.view.WindowManager; import java.util.ArrayList; /** * Created by kingp on 10/5/2016. */ public class Helpers { public static String YardId; public static String Host = "https://sca-live-api.2kpa.me"; public static String QR_BOX_ID = null; public static String QR_BOX_SHOW_ID = null; public static ArrayList<ImageGalleryItem> ImageGalleryContainer; public static String[] ImageUrlList; public static boolean isTabletDevice(Context mContext) { TelephonyManager telephony = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); int type = telephony.getPhoneType(); if (type == TelephonyManager.PHONE_TYPE_NONE) { return true; } return false; } public static int getScreenOfTablet(Context context) { WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); int width = metrics.widthPixels; int height = metrics.heightPixels; int screen_id = 0; if(width >= 1900 && width < 2000) { screen_id = 1; } else if(width >= 2000 && width < 2500) { screen_id = 2; } return screen_id; } }
package com.mpowa.android.powapos.apps.powatools; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TabHost; import android.widget.TextView; import com.mpowa.android.powapos.apps.powatools.common.FragmentBase; import com.mpowa.android.powapos.apps.powatools.common.PowaPosInterface; import com.mpowa.android.sdk.powapos.PowaPOS; import com.mpowa.android.sdk.powapos.common.base.PowaEnums; import com.mpowa.android.sdk.powapos.core.PowaPOSEnums; import com.mpowa.android.sdk.powapos.core.callbacks.PowaPOSCallback; import com.mpowa.android.sdk.powapos.core.dataobjects.PowaFirmwareInfo; import com.mpowa.android.sdk.powapos.core.dataobjects.PowaUSBDeviceInfo; import com.mpowa.android.sdk.powapos.drivers.s10.PowaS10Scanner; import com.mpowa.android.sdk.powapos.drivers.tseries.PowaTSeries; import java.util.ArrayList; import java.util.Map; public class ActivityMain extends Activity implements PowaPosInterface, FragmentSystem.Callbacks, FragmentSettings.Callbacks, FragmentHelp.Callbacks, FragmentUpdate.Callbacks, TabHost.OnTabChangeListener, View.OnClickListener { private static final String SYSTEM_TAG = "system"; private static final String SETTINGS_TAG = "settings"; private static final String UPDATE_TAG = "update"; private static final String HELP_TAG = "help"; private static final String WEB_HELP_TAG = "webhelp"; private FragmentBase currentFragment = null; private Fragment fragmentWebHelp = null; private FrameLayout splash; private TabHost tabHost; //private Button btnBack; private PowaPOS powaPOS; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /*splash = (FrameLayout)findViewById(R.id.splash); splash.setVisibility(View.VISIBLE); new Handler().postDelayed(new Runnable() { public void run() { splash.setVisibility(View.GONE); } }, getSplashTime());*/ /*btnBack = (Button)findViewById(R.id.btn_back); btnBack.setOnClickListener(this); btnBack.setVisibility(View.INVISIBLE);*/ setupTabHost(); showFragment(SYSTEM_TAG); } private int getSplashTime(){ return getResources().getInteger(R.integer.splash_time_mls); } @Override protected void onResume() { super.onResume(); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); PowaPOS.onNewIntent(this.getApplicationContext(), intent); } @Override protected void onDestroy() { powaPOS.dispose(); super.onDestroy(); } PowaPOSCallback powaPOSCallback = new PowaPOSCallback() { /* * MCU CONNECTION */ @Override public void onMCUInitialized(PowaPOSEnums.InitializedResult result) { currentFragment.onMCUInitialized(result); } @Override public void onMCUConnectionStateChanged(PowaEnums.ConnectionState newState) { currentFragment.onMCUConnectionStateChanged(newState); } @Override public void onMCUSystemConfiguration(Map<String, String> configuration) { currentFragment.onMCUSystemConfiguration(configuration); } @Override public void onUSBDeviceInformation(boolean deviceIsAttached, PowaUSBDeviceInfo info) { currentFragment.onUSBDeviceInformation(deviceIsAttached, info); } /* * MCU FIRMWARE */ @Override public void onMCUFirmwareDownloaded(PowaPOSEnums.PowaFirmwareDownloadResult result, PowaFirmwareInfo firmware, byte[] bytes) { currentFragment.onMCUFirmwareDownloaded(result, firmware, bytes); } @Override public void onMCUFirmwareHistoryResult(PowaPOSEnums.PowaFirmwareHistoryResult result, ArrayList<PowaFirmwareInfo> history) { currentFragment.onMCUFirmwareHistoryResult(result, history); } @Override public void onMCUAvailableFirmwareResult(PowaPOSEnums.PowaFirmwareAvailableResult result, PowaFirmwareInfo lastFirmware) { currentFragment.onMCUAvailableFirmwareResult(result, lastFirmware); } @Override public void onMCUFirmwareUpdateStarted() { currentFragment.onMCUFirmwareUpdateStarted(); } @Override public void onMCUFirmwareUpdateProgress(int progress) { currentFragment.onMCUFirmwareUpdateProgress(progress); } @Override public void onMCUFirmwareUpdateFinished() { currentFragment.onMCUFirmwareUpdateFinished(); } @Override public void onMCUBootloaderUpdateStarted() { currentFragment.onMCUBootloaderUpdateStarted(); } @Override public void onMCUBootloaderUpdateProgress(int progress) { currentFragment.onMCUBootloaderUpdateProgress(progress); } @Override public void onMCUBootloaderUpdateFinished() { currentFragment.onMCUBootloaderUpdateFinished(); } @Override public void onMCUBootloaderUpdateFailed(PowaPOSEnums.BootloaderUpdateError error) { currentFragment.onMCUBootloaderUpdateFailed(error); } /* * PRINTER */ @Override public void onPrintJobResult(PowaPOSEnums.PrintJobResult result) { currentFragment.onPrintJobResult(result); } @Override public void onPrinterOutOfPaper() { currentFragment.onPrinterOutOfPaper(); } /* * CASH DRAWER */ @Override public void onCashDrawerAttached() { currentFragment.onCashDrawerAttached(); } @Override public void onCashDrawerDetached() { currentFragment.onCashDrawerDetached(); } @Override public void onCashDrawerStatus(PowaPOSEnums.CashDrawerStatus status) { currentFragment.onCashDrawerStatus(status); } /* * ROTATION */ @Override public void onRotationSensorStatus(PowaPOSEnums.RotationSensorStatus status) { currentFragment.onRotationSensorStatus(status); } /* * CDC */ @Override public void onUSBDeviceAttached(PowaPOSEnums.PowaUSBCOMPort port) { currentFragment.onUSBDeviceAttached(port); } @Override public void onUSBDeviceDetached(PowaPOSEnums.PowaUSBCOMPort port) { currentFragment.onUSBDeviceDetached(port); } @Override public void onUSBReceivedData(PowaPOSEnums.PowaUSBCOMPort port, byte[] data) { currentFragment.onUSBReceivedData(port, data); } /* * FTDI */ @Override public void onFTDIPortConfiguration(PowaPOSEnums.PowaFTDIPort ftdiPort , PowaPOSEnums.PowaFTDIBaud baud, PowaPOSEnums.PowaFTDIDataBits dataBits , PowaPOSEnums.PowaFTDIParity parity, PowaPOSEnums.PowaFTDIStopBits stopBits) { currentFragment.onFTDIPortConfiguration(ftdiPort, baud, dataBits, parity, stopBits); } @Override public void onFTDIPortControlLineState(PowaPOSEnums.PowaFTDIPort ftdiPort, boolean rtsState , boolean dtrState, boolean rtsUsage, boolean dtrUsage) { currentFragment.onFTDIPortControlLineState(ftdiPort, rtsState, dtrState, rtsUsage, dtrUsage); } @Override public void onFTDIReceivedData(PowaPOSEnums.PowaFTDIPort ftdiPort, byte[] data) { currentFragment.onFTDIReceivedData(ftdiPort, data); } @Override public void onFTDIDeviceAttached(PowaPOSEnums.PowaFTDIPort ftdiPort) { currentFragment.onFTDIDeviceAttached(ftdiPort); } @Override public void onFTDIDeviceDetached(PowaPOSEnums.PowaFTDIPort ftdiPort) { currentFragment.onFTDIDeviceDetached(ftdiPort); } @Override public void onFTDIDeviceOpened(PowaPOSEnums.PowaFTDIPort ftdiPort) { currentFragment.onFTDIDeviceOpened(ftdiPort); } /* * HID */ @Override public void onHIDDeviceAttached(PowaPOSEnums.PowaHIDPort port, PowaPOSEnums.PowaHIDType type) { currentFragment.onHIDDeviceAttached(port, type); } @Override public void onHIDDeviceDetached(PowaPOSEnums.PowaHIDPort port, PowaPOSEnums.PowaHIDType type) { currentFragment.onHIDDeviceDetached(port, type); } @Override public void onHIDReceivedData(PowaPOSEnums.PowaHIDPort port, PowaPOSEnums.PowaHIDType type, byte[] data) { currentFragment.onHIDReceivedData(port, type, data); } @Override public void onAlert(String id, String data) { currentFragment.onAlert(id, data); } /* * SCANNER */ @Override public void onScannerConnectionStateChanged(PowaEnums.ConnectionState newState) { currentFragment.onScannerConnectionStateChanged(newState); } @Override public void onScannerInitialized(PowaPOSEnums.InitializedResult result) { currentFragment.onScannerInitialized(result); } @Override public void onScannerRead(String data) { currentFragment.onScannerRead(data); } @Override public void onScannerRead(byte[] data) { //currentFragment.onScannerRead(data); } }; @Override public void onTabChanged(String tabId) { showFragment(tabId); } private void setupTabHost() { tabHost = (TabHost) findViewById(R.id.tabhost); tabHost.setup(); tabHost.addTab(newTab(SYSTEM_TAG, R.drawable.tab_icon_system_style, R.string.tab_system, R.id.tab1)); tabHost.addTab(newTab(SETTINGS_TAG, R.drawable.tab_icon_settings_style, R.string.tab_settings, R.id.tab2)); tabHost.addTab(newTab(UPDATE_TAG, R.drawable.tab_icon_update_style, R.string.tab_update, R.id.tab3)); tabHost.addTab(newTab(HELP_TAG, R.drawable.tab_icon_help_style, R.string.tab_help, R.id.tab4)); tabHost.setOnTabChangedListener(this); tabHost.setCurrentTab(0); } private TabHost.TabSpec newTab(String tag, int iconId, int labelId,int tabContentId) { View indicator = LayoutInflater.from(this).inflate( R.layout.tab, null); ((TextView) indicator.findViewById(R.id.text)).setText(labelId); ((ImageView) indicator.findViewById(R.id.icon)).setImageResource(iconId); TabHost.TabSpec tabSpec = tabHost.newTabSpec(tag); tabSpec.setIndicator(indicator); tabSpec.setContent(tabContentId); return tabSpec; } private void showFragment(String name){ fragmentWebHelp = null; //btnBack.setVisibility(View.INVISIBLE); if(name.equals(SYSTEM_TAG)){ final FragmentSystem fragment = FragmentSystem.newInstance(); currentFragment = fragment; final FragmentTransaction ft = this.getFragmentManager().beginTransaction(); if(ft.isEmpty()) { ft.add(R.id.body_content, fragment); }else{ ft.replace(R.id.body_content, fragment); } ft.commit(); } if(name.equals(SETTINGS_TAG)){ final FragmentSettings fragment = FragmentSettings.newInstance(); currentFragment = fragment; final FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.body_content, fragment); ft.commit(); } if(name.equals(UPDATE_TAG)){ final FragmentUpdate fragment = FragmentUpdate.newInstance(); currentFragment = fragment; final FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.body_content, fragment); ft.commit(); } if(name.equals(HELP_TAG)){ final FragmentHelp fragment = FragmentHelp.newInstance(); currentFragment = fragment; final FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.body_content, fragment); ft.commit(); } } @Override public PowaPOS getPowaPOS() { if(powaPOS == null){ powaPOS = new PowaPOS(this, powaPOSCallback); PowaTSeries tseries = new PowaTSeries(this); powaPOS.addPeripheral(tseries); PowaS10Scanner s10 = new PowaS10Scanner(this); powaPOS.addPeripheral(s10); } return powaPOS; } @Override public void goHelp(String url) { fragmentWebHelp = FragmentWebHelp.newInstance(url); final FragmentTransaction ft = this.getFragmentManager().beginTransaction(); ft.replace(R.id.body_content, fragmentWebHelp); ft.commit(); //btnBack.setVisibility(View.VISIBLE); } @Override public void onClick(View v) { switch (v.getId()) { /*case R.id.btn_back: btnBack.setVisibility(View.INVISIBLE); final FragmentTransaction ft = this.getFragmentManager().beginTransaction(); ft.replace(R.id.content, currentFragment); ft.commit(); break;*/ } } @Override public void onBackPressed(){ if(fragmentWebHelp != null){ closeHelp(); }else { super.onBackPressed(); } } private void closeHelp() { fragmentWebHelp = null; //btnBack.setVisibility(View.INVISIBLE); final FragmentTransaction ft = this.getFragmentManager().beginTransaction(); ft.replace(R.id.body_content, currentFragment); ft.commit(); } }
package algo3.fiuba.modelo.campo; import algo3.fiuba.modelo.cartas.CartaCampo; public interface ZonaCartaCampo { ZonaCartaCampo agregarCartaCampo(CartaCampo cartaCampo); ZonaCartaCampo removerCartaCampo(CartaCampo cartaCampo); CartaCampo getCartaCampo(); boolean cartaEstaEnZona(CartaCampo cartaCampo); }
/* * Copyright 2016 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 * * 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 example.helloworld; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RestController; import javax.annotation.PostConstruct; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; /** * Sample Application using Spring Cloud Vault with Token authentication. * * @author Shyam */ @SpringBootApplication @RestController public class GreeterApplication { public static void main(String[] args) { SpringApplication.run(GreeterApplication.class, args); } @Value("${mykey}") String mykey; @Autowired DataSource dataSource; @PostConstruct private void postConstruct() throws Exception{ System.out.println("##########################"); System.out.println(mykey); System.out.println("##########################"); try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { ResultSet resultSet = statement.executeQuery("SELECT * FROM users;"); while (resultSet.next()){ System.out.println("Connection works with User: "+resultSet.getString(1)); } resultSet.close(); } System.out.println("##########################"); } }
/* just integrated this in Indices package org.aksw.autosparql.commons.index; import org.dllearner.common.index.SPARQLClassesIndex; import org.dllearner.common.index.SPARQLDatatypePropertiesIndex; import org.dllearner.common.index.SPARQLIndex; import org.dllearner.common.index.SPARQLObjectPropertiesIndex; import com.hp.hpl.jena.rdf.model.Model; public class ModelIndices extends Indices { public ModelIndices(Model model) { super(new SPARQLIndex(model), new SPARQLClassesIndex(model), new SPARQLObjectPropertiesIndex(model), new SPARQLDatatypePropertiesIndex(model)); } } */
package com.hendisantika.springbootmongodbsample.model; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Created by IntelliJ IDEA. * Project : spring-boot-mongodb-sample * User: hendisantika * Email: hendisantika@gmail.com * Telegram : @hendisantika34 * Date: 2019-01-25 * Time: 06:16 * To change this template use File | Settings | File Templates. */ @Document public class User { @Id private String userId; private String name; private Date creationDate = new Date(); private Map<String, String> userSettings = new HashMap<>(); public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public Map<String, String> getUserSettings() { return userSettings; } public void setUserSettings(Map<String, String> userSettings) { this.userSettings = userSettings; } }
package practise; //this is method hiding program //method resolution is decided on compile time based on reference type //durga sir video method hiding public class MethodHiding { public static void main(String[] args) { Parent1 p=new Parent1(); p.message();//hello parent // hello parent Child1 c=new Child1();//hello child // hello child c.message(); Parent1 p1=new Child1();//hello child //hello parent p1.message(); } } class Parent1 { public static void message() { System.out.println("hello parent"); } } class Child1 extends Parent1 { public static void message() { System.out.println("hello child"); } }
package com.trump.auction.back.rule.model; import lombok.Data; import lombok.ToString; import java.math.BigDecimal; import java.util.Date; /** * 规则 * * @author zhangliyan * @create 2018-01-02 17:11 **/ @Data @ToString public class AuctionRule { /** * 主键 */ private Integer id; /** * 规则名称 */ private String ruleName; /** * 差价购买标识(1.可以2.不可以) */ private Integer differenceFlag; /** * 每次可加价金额 */ private BigDecimal premiumAmount; /** * 计时描述 */ private Integer timingNum; /** * 退币比例 */ private BigDecimal refundMoneyProportion; /** * 起拍价 */ private BigDecimal openingBid; /** * 上架规则 1.定时 2.立即 3.暂不上架 */ private Integer shelvesRule; /** * 上架延迟时间 */ private Integer shelvesDelayTime; /** * 机器人出价权重(百分比) */ private Integer robotRule; /** * 机器人是否必中 */ private Integer robotTakenIn; /** * 最高价可得 */ private Long highestPrice; /** * 创建时间 */ private Date createTime; /** * 修改时间 */ private Date updateTime; /** * 操作人id */ private Integer userId; /** * 操作人ip */ private String userIp; /** * 类型状态 1启用 2禁用 */ private Integer status; /** * 手续费 */ private BigDecimal poundage; /** * 倒计时 */ private Integer countdown; /** * 起拍名称 */ private String startBidName; /** * 每次加价名称 */ private String increaseBidName; /** * 手续费名称 */ private String poundageName; /** * 倒计时名称 */ private String countdownName; /** * 差价购买名称 */ private String differenceName; /** * 退币比例名称 */ private String proportionName; /** * 上架时间 */ private Date onShelfTime; /** * 商品数量 */ private Integer productNum; }
package com.daydvr.store.presenter.video; import android.app.Activity; import android.os.Message; import com.daydvr.store.bean.VideoListBean; import com.daydvr.store.model.video.VideoModel; import com.daydvr.store.util.LoaderHandler; import java.util.ArrayList; import java.util.List; import static com.daydvr.store.base.BaseApplication.MultiThreadPool; import static com.daydvr.store.base.BaseConstant.VIDEO_LOADER_OK; /** * @author LoSyc * @version Created on 2017/12/28. 15:14 */ public class VideoDetailPresenter implements VideoDetailContract.Presenter { private VideoDetailContract.View mView; private LoaderHandler mHandler; private VideoModel mVideoModel; private List<String> mAdUrls = new ArrayList<>(); private List<VideoListBean> mVideoDatas = new ArrayList<>(); public VideoDetailPresenter(VideoDetailContract.View view) { mView = view; mView.setPresenter(this); mHandler = new LoaderHandler(); mHandler.setListener(mHandleListener); mVideoModel = new VideoModel(); mVideoModel.setHandler(mHandler); } @Override public void freeView() { mView = null; } @Override public void initUtils(Activity activity) { } @Override public void loadVideoRecommend() { MultiThreadPool.execute(new Runnable() { @Override public void run() { mVideoModel.getHotVideoListDatas(); } }); } @Override public void loadVideoDetail(int videoId) { } @Override public void intoVideoDetail(int videoId) { if (mView != null) { mView.jumpVideoDetail(null); } } private LoaderHandler.LoaderHandlerListener mHandleListener = new LoaderHandler.LoaderHandlerListener() { @Override public void handleMessage(Message msg) { switch (msg.what) { case VIDEO_LOADER_OK: mVideoDatas = (List<VideoListBean>) msg.obj; if (mVideoDatas != null && mView != null) { mView.showVideoRecommend(mVideoDatas); } break; default: break; } } }; }
/* * Copyright (C) 2017 GetMangos * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.mangos.dbc.model.character; import eu.mangos.dbc.utils.DBCUtils; import java.util.ArrayList; import java.util.List; /** * Entry representing the classes available in game. * @author GetMangos */ public class ChrClasses { /** * 0 - ID of the char class in DBC. */ private int id; /** * 3 - Power Type (1 = Rage, 3 = Energy, 0 = Mana) */ private int powerType; /** * 5 to 12 - Class Name using locales. */ private List<String> nameList; /** * 15 - Spell Class ID (3 = Mage, 4 = Warrior, 5 = Warlock, ...) */ private int spellFamilyID; /** * 16 - Has relic slot. */ private boolean hasRelic; public ChrClasses() { this.id = -1; this.powerType = -1; this.nameList = new ArrayList<>(); DBCUtils.initializeLocalizedList(nameList); this.spellFamilyID = -1; this.hasRelic = false; } public ChrClasses(int id, int powerType, List<String> name, int spellFamilyID, boolean hasRelic) { this.id = id; this.powerType = powerType; this.nameList = name; this.spellFamilyID = spellFamilyID; this.hasRelic = hasRelic; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getPowerType() { return powerType; } public void setPowerType(int powerType) { this.powerType = powerType; } public List<String> getNameList() { return nameList; } public void setNameList(List<String> name) { this.nameList = name; } public void addName(String name) { this.nameList.add(name); } public int getSpellFamilyID() { return spellFamilyID; } public void setSpellFamilyID(int spellFamilyID) { this.spellFamilyID = spellFamilyID; } public boolean isHasRelic() { return hasRelic; } public void setHasRelic(boolean hasRelic) { this.hasRelic = hasRelic; } public void insertName(int i, String get) { this.nameList.set(i, get); } }
package com.freeraven.datastructures.linkedlist.removeduplicates; import org.junit.Test; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import static org.hamcrest.core.Is.is; import static org.junit.Assert.*; /** * Created by zvlad on 7/5/16. */ public class RemoveDuplicatesTest { @Test public void removeFromTest1() throws Exception { List<Integer> list = new LinkedList<>(Arrays.asList(1, 4, 6, 4, 46, 65, 23, 23, 54, 543, 345, 23, 46)); RemoveDuplicates.removeFrom(list); assertThat(list.toString(), is("[1, 4, 6, 46, 65, 23, 54, 543, 345]")); } @Test public void removeFromTest2() throws Exception { List<Integer> list = new LinkedList<>(Arrays.asList(4, 4, 4, 4)); RemoveDuplicates.removeFrom(list); assertThat(list.toString(), is("[4]")); } @Test public void removeFromTest3() throws Exception { List<Integer> list = new LinkedList<>(Arrays.asList(0, 4, 0, 4, 0, 4, 0, 4, 0, 4)); RemoveDuplicates.removeFrom(list); assertThat(list.toString(), is("[0, 4]")); } @Test public void removeFromTest4() throws Exception { List<Integer> list = new LinkedList<>(Arrays.asList(0, 4, 0, 4, 0, 4, 0, 4, 0, 4, 7)); RemoveDuplicates.removeFrom(list); assertThat(list.toString(), is("[0, 4, 7]")); } }
/** * This class is generated by jOOQ */ package schema.tables.records; import java.math.BigDecimal; import java.sql.Timestamp; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.Record1; import org.jooq.Record7; import org.jooq.Row7; import org.jooq.impl.UpdatableRecordImpl; import schema.tables.ShoppingcartInvoiceitem; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.8.4" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class ShoppingcartInvoiceitemRecord extends UpdatableRecordImpl<ShoppingcartInvoiceitemRecord> implements Record7<Integer, Timestamp, Timestamp, Integer, BigDecimal, String, Integer> { private static final long serialVersionUID = -736491467; /** * Setter for <code>bitnami_edx.shoppingcart_invoiceitem.id</code>. */ public void setId(Integer value) { set(0, value); } /** * Getter for <code>bitnami_edx.shoppingcart_invoiceitem.id</code>. */ public Integer getId() { return (Integer) get(0); } /** * Setter for <code>bitnami_edx.shoppingcart_invoiceitem.created</code>. */ public void setCreated(Timestamp value) { set(1, value); } /** * Getter for <code>bitnami_edx.shoppingcart_invoiceitem.created</code>. */ public Timestamp getCreated() { return (Timestamp) get(1); } /** * Setter for <code>bitnami_edx.shoppingcart_invoiceitem.modified</code>. */ public void setModified(Timestamp value) { set(2, value); } /** * Getter for <code>bitnami_edx.shoppingcart_invoiceitem.modified</code>. */ public Timestamp getModified() { return (Timestamp) get(2); } /** * Setter for <code>bitnami_edx.shoppingcart_invoiceitem.qty</code>. */ public void setQty(Integer value) { set(3, value); } /** * Getter for <code>bitnami_edx.shoppingcart_invoiceitem.qty</code>. */ public Integer getQty() { return (Integer) get(3); } /** * Setter for <code>bitnami_edx.shoppingcart_invoiceitem.unit_price</code>. */ public void setUnitPrice(BigDecimal value) { set(4, value); } /** * Getter for <code>bitnami_edx.shoppingcart_invoiceitem.unit_price</code>. */ public BigDecimal getUnitPrice() { return (BigDecimal) get(4); } /** * Setter for <code>bitnami_edx.shoppingcart_invoiceitem.currency</code>. */ public void setCurrency(String value) { set(5, value); } /** * Getter for <code>bitnami_edx.shoppingcart_invoiceitem.currency</code>. */ public String getCurrency() { return (String) get(5); } /** * Setter for <code>bitnami_edx.shoppingcart_invoiceitem.invoice_id</code>. */ public void setInvoiceId(Integer value) { set(6, value); } /** * Getter for <code>bitnami_edx.shoppingcart_invoiceitem.invoice_id</code>. */ public Integer getInvoiceId() { return (Integer) get(6); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Record1<Integer> key() { return (Record1) super.key(); } // ------------------------------------------------------------------------- // Record7 type implementation // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Row7<Integer, Timestamp, Timestamp, Integer, BigDecimal, String, Integer> fieldsRow() { return (Row7) super.fieldsRow(); } /** * {@inheritDoc} */ @Override public Row7<Integer, Timestamp, Timestamp, Integer, BigDecimal, String, Integer> valuesRow() { return (Row7) super.valuesRow(); } /** * {@inheritDoc} */ @Override public Field<Integer> field1() { return ShoppingcartInvoiceitem.SHOPPINGCART_INVOICEITEM.ID; } /** * {@inheritDoc} */ @Override public Field<Timestamp> field2() { return ShoppingcartInvoiceitem.SHOPPINGCART_INVOICEITEM.CREATED; } /** * {@inheritDoc} */ @Override public Field<Timestamp> field3() { return ShoppingcartInvoiceitem.SHOPPINGCART_INVOICEITEM.MODIFIED; } /** * {@inheritDoc} */ @Override public Field<Integer> field4() { return ShoppingcartInvoiceitem.SHOPPINGCART_INVOICEITEM.QTY; } /** * {@inheritDoc} */ @Override public Field<BigDecimal> field5() { return ShoppingcartInvoiceitem.SHOPPINGCART_INVOICEITEM.UNIT_PRICE; } /** * {@inheritDoc} */ @Override public Field<String> field6() { return ShoppingcartInvoiceitem.SHOPPINGCART_INVOICEITEM.CURRENCY; } /** * {@inheritDoc} */ @Override public Field<Integer> field7() { return ShoppingcartInvoiceitem.SHOPPINGCART_INVOICEITEM.INVOICE_ID; } /** * {@inheritDoc} */ @Override public Integer value1() { return getId(); } /** * {@inheritDoc} */ @Override public Timestamp value2() { return getCreated(); } /** * {@inheritDoc} */ @Override public Timestamp value3() { return getModified(); } /** * {@inheritDoc} */ @Override public Integer value4() { return getQty(); } /** * {@inheritDoc} */ @Override public BigDecimal value5() { return getUnitPrice(); } /** * {@inheritDoc} */ @Override public String value6() { return getCurrency(); } /** * {@inheritDoc} */ @Override public Integer value7() { return getInvoiceId(); } /** * {@inheritDoc} */ @Override public ShoppingcartInvoiceitemRecord value1(Integer value) { setId(value); return this; } /** * {@inheritDoc} */ @Override public ShoppingcartInvoiceitemRecord value2(Timestamp value) { setCreated(value); return this; } /** * {@inheritDoc} */ @Override public ShoppingcartInvoiceitemRecord value3(Timestamp value) { setModified(value); return this; } /** * {@inheritDoc} */ @Override public ShoppingcartInvoiceitemRecord value4(Integer value) { setQty(value); return this; } /** * {@inheritDoc} */ @Override public ShoppingcartInvoiceitemRecord value5(BigDecimal value) { setUnitPrice(value); return this; } /** * {@inheritDoc} */ @Override public ShoppingcartInvoiceitemRecord value6(String value) { setCurrency(value); return this; } /** * {@inheritDoc} */ @Override public ShoppingcartInvoiceitemRecord value7(Integer value) { setInvoiceId(value); return this; } /** * {@inheritDoc} */ @Override public ShoppingcartInvoiceitemRecord values(Integer value1, Timestamp value2, Timestamp value3, Integer value4, BigDecimal value5, String value6, Integer value7) { value1(value1); value2(value2); value3(value3); value4(value4); value5(value5); value6(value6); value7(value7); return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached ShoppingcartInvoiceitemRecord */ public ShoppingcartInvoiceitemRecord() { super(ShoppingcartInvoiceitem.SHOPPINGCART_INVOICEITEM); } /** * Create a detached, initialised ShoppingcartInvoiceitemRecord */ public ShoppingcartInvoiceitemRecord(Integer id, Timestamp created, Timestamp modified, Integer qty, BigDecimal unitPrice, String currency, Integer invoiceId) { super(ShoppingcartInvoiceitem.SHOPPINGCART_INVOICEITEM); set(0, id); set(1, created); set(2, modified); set(3, qty); set(4, unitPrice); set(5, currency); set(6, invoiceId); } }
/* * 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 indexnilai; /** * * @author junandre */ public class Nilai { double nilai; public double getNilai() { return nilai; } public void setNilai(double nilai) { this.nilai = nilai; } public void cekIndex(){ if(this.nilai>80){ System.out.println("Index A"); }else if(this.nilai>75 && this.nilai<=80){ System.out.println("Index AB"); }else if(this.nilai>70 && this.nilai<=75){ System.out.println("Index B"); }else if(this.nilai>60 && this.nilai<=70){ System.out.println("Index BC"); }else if(this.nilai>50 && this.nilai<=60){ System.out.println("Index C"); }else if(this.nilai>40 && this.nilai<=50){ System.out.println("Index D"); }else{ System.out.println("Index E"); } } } /* * 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 indexnilai; import java.util.Scanner; /** * * @author junandre */ public class IndexNilai { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner s = new Scanner(System.in); Nilai n = new Nilai(); System.out.print("Nilai Mahasiswa N : "); double x = s.nextDouble(); n.setNilai(x); System.out.println("Nilai n : "+n.getNilai()); n.cekIndex(); } }
package ca.uwaterloo.stepcounter; import java.util.Arrays; import android.app.Activity; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; public class MainActivity extends Activity { int numberOfStep=0; TextView tv; Button button; LineGraphView graph; float direction; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LinearLayout layout1 = ((LinearLayout)findViewById(R.id.layout1)); //Register liner acceleration sensor and rotation sensor sensor. SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE); Sensor LinerAcceleratormeter = sm.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION); Sensor rotationvector = sm.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR); SensorEventListener a1 = new GeneralSensorEventListener(); sm.registerListener(a1, LinerAcceleratormeter,SensorManager.SENSOR_DELAY_FASTEST); sm.registerListener(a1, rotationvector,SensorManager.SENSOR_DELAY_NORMAL); //TextView setup tv = new TextView(this); layout1.addView(tv); tv.setText("Total number of steps: 0"); graph = new LineGraphView(getApplicationContext(),100,Arrays.asList("Peak","Trough","Acceleration")); layout1.addView(graph); //Set the button that clears the value when it is clicked. button = new Button(this); button.setText("Clear"); layout1.addView(button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { numberOfStep = 0; FiniteStateMachine.clear(); tv.setText("Total number of steps: "+numberOfStep); } }); } public class GeneralSensorEventListener implements SensorEventListener { float filtData[] = new float[3]; @Override public void onSensorChanged(SensorEvent event) { switch (event.sensor.getType()) { case (Sensor.TYPE_LINEAR_ACCELERATION): filtData[2] = Helper.LowPassFilter(event.values[2]); numberOfStep += FiniteStateMachine.changeState(filtData[2]); break; case (Sensor.TYPE_ROTATION_VECTOR): direction = Helper.getDirection(event.values); break; default: break; } tv.setText("Total number of steps: "+numberOfStep + "\nDirection: "+ (int)(direction*180/3.14)); filtData[0] = 0.5f; filtData[1] = -0.13f; graph.addPoint(filtData); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) {} } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package com.ifeng.recom.mixrecall.core.service; import com.ifeng.recom.mixrecall.common.model.RecordInfo; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by geyl on 2017/11/9. */ public class RecallNumberTest { private int recallNumber = 500; private double sumWeight; private List<RecordInfo> list; private Map<String, Double> tagWithWeightMap=new HashMap<>(); public RecallNumberTest(List<RecordInfo> list, int recallNumber) { this.list = list; this.recallNumber = recallNumber; init(); } private void init() { int count = list.size(); for (RecordInfo recordInfo : list) { double weight = Math.pow(count, 1.5); tagWithWeightMap.put(recordInfo.getRecordName(), weight); sumWeight += weight; count--; } } public int getRecallNumber(String tagName) { try { double s = (tagWithWeightMap.get(tagName)) / sumWeight; //归一化后的tag权重 return (int) (Math.round(s * recallNumber)); } catch (Exception e) { return 10; } } }
package com.eniso.regimi.repository; import java.util.Date; import java.util.List; import java.util.Optional; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import com.eniso.regimi.models.Partner; @Repository public interface PartnerRepository extends MongoRepository<Partner, String> { //Optional<Partner> findByEmail(String email); Partner findByName(String name); List<Partner> findByCity(String city); List<Partner> findByCategory(String category); //Boolean existsByEmail(String email); Boolean existsByName(String name); }
package stock.ecs739.minmax; import java.io.IOException; import java.util.StringTokenizer; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import stock.ecs739.DailyStock; public class DailyMaxMapper extends Mapper<Text, DailyStock, Text, DoubleWritable> { private final IntWritable one = new IntWritable(1); public void map(Text index, DailyStock value, Context context) throws IOException, InterruptedException { context.write(value.getCompany(), value.getClose()); } }
package com.choco.rpc.service.impl; import com.alibaba.dubbo.config.annotation.Service; import com.choco.common.result.ShopPageInfo; import com.choco.rpc.service.SearchService; import com.choco.rpc.vo.GoodsVo; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightField; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; /** * Created by choco on 2021/1/5 10:41 */ @Service(interfaceClass = SearchService.class) @Component public class SearchServiceImpl implements SearchService { @Autowired @Qualifier("restHighLevelClient") private RestHighLevelClient client; @Override public ShopPageInfo<GoodsVo> searchGoodsVo(String keyword, int pageNum, int pageSize) { ShopPageInfo<GoodsVo> shopPageInfo; try { //指定索引库 SearchRequest searchRequest = new SearchRequest("shop"); // SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); //构造分页条件 sourceBuilder.from((pageNum - 1) * pageSize).size(pageSize); //构造高亮builder HighlightBuilder highlightBuilder = new HighlightBuilder(); highlightBuilder.field("goodsName").preTags("<span style='color: red;'>").postTags("</span>"); sourceBuilder.highlighter(highlightBuilder); //关键词查询 sourceBuilder.query(QueryBuilders.multiMatchQuery(keyword, "goodsName")); searchRequest.source(sourceBuilder); ArrayList<GoodsVo> list = new ArrayList<>(); SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT); Long value = response.getHits().getTotalHits().value; //判断是否获取数据成功 if (0 >value ) { return null; } SearchHit[] hits = response.getHits().getHits(); for (SearchHit hit : hits) { //获取高亮字段 HighlightField content = hit.getHighlightFields().get("goodsName"); String newContent = String.valueOf(content.fragments()[0]); Integer goodsId = (Integer) hit.getSourceAsMap().get("goodsId"); String goodsName = (String) hit.getSourceAsMap().get("goodsName"); String originalImg = (String) hit.getSourceAsMap().get("originalImg"); BigDecimal marketPrice = new BigDecimal(String.valueOf(hit.getSourceAsMap().get("marketPrice"))); GoodsVo goodsVo = new GoodsVo(goodsId, goodsName, newContent, marketPrice, originalImg); list.add(goodsVo); //分页处理 shopPageInfo=new ShopPageInfo<GoodsVo>(pageNum,pageSize,value.intValue()); shopPageInfo.setResult(list); return shopPageInfo; } } catch (IOException e) { e.printStackTrace(); } return null; } }
package com.git.cloud.resmgt.compute.model.vo; import java.io.Serializable; import com.git.cloud.common.model.base.BaseBO; public class PhysicsMachineVo extends BaseBO implements Serializable { private static final long serialVersionUID = 1L; //名称 private String pname; //CPU数量 private String cpu; //内存数量 private String ram; //已使用CPU private String cpuUsed; //已使用内存 private String ramUsed; //IP地址 private String ip; //纳管 private String isNano; //数据中心ID private String did; //资源池ID private String rid; //虚拟机ID private String vid; //物理机ID private String devceId; //物理机名称 private String deviceName; //虚拟机数量 private String cmvmCount; //剩余CPU private String remainingCpu; //剩余MEM private String remainingMem; //已用CPU private String cmCpuUsed; //已用MEM private String cmMemUsed; //dataStoreId private String dataStoreId; private String dataStoreName; private String virtTypeCode; public String getVirtTypeCode() { return virtTypeCode; } public void setVirtTypeCode(String virtTypeCode) { this.virtTypeCode = virtTypeCode; } public String getDataStoreName() { return dataStoreName; } public void setDataStoreName(String dataStoreName) { this.dataStoreName = dataStoreName; } private String cdpId; public String getCdpId() { return cdpId; } public void setCdpId(String cdpId) { this.cdpId = cdpId; } public String getCpuUsed() { return cpuUsed; } public void setCpuUsed(String cpuUsed) { this.cpuUsed = cpuUsed; } public String getRamUsed() { return ramUsed; } public void setRamUsed(String ramUsed) { this.ramUsed = ramUsed; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getIsNano() { return isNano; } public void setIsNano(String isNano) { this.isNano = isNano; } public String getDid() { return did; } public void setDid(String did) { this.did = did; } public String getRid() { return rid; } public void setRid(String rid) { this.rid = rid; } public String getVid() { return vid; } public void setVid(String vid) { this.vid = vid; } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } public String getCpu() { return cpu; } public void setCpu(String cpu) { this.cpu = cpu; } public String getRam() { return ram; } public void setRam(String ram) { this.ram = ram; } public String getDevceId() { return devceId; } public void setDevceId(String devceId) { this.devceId = devceId; } public PhysicsMachineVo() { super(); } public String getDeviceName() { return deviceName; } public void setDeviceName(String deviceName) { this.deviceName = deviceName; } public String getCmvmCount() { return cmvmCount; } public void setCmvmCount(String cmvmCount) { this.cmvmCount = cmvmCount; } public String getRemainingCpu() { return remainingCpu; } public void setRemainingCpu(String remainingCpu) { this.remainingCpu = remainingCpu; } public String getRemainingMem() { return remainingMem; } public void setRemainingMem(String remainingMem) { this.remainingMem = remainingMem; } public String getCmCpuUsed() { return cmCpuUsed; } public void setCmCpuUsed(String cmCpuUsed) { this.cmCpuUsed = cmCpuUsed; } public String getCmMemUsed() { return cmMemUsed; } public void setCmMemUsed(String cmMemUsed) { this.cmMemUsed = cmMemUsed; } public String getDataStoreId() { return dataStoreId; } public void setDataStoreId(String dataStoreId) { this.dataStoreId = dataStoreId; } @Override public String getBizId() { return null; } public PhysicsMachineVo(String pname, String cpu, String ram,String cpuUsed, String ramUsed, String ip, String isNano,String devceId,String cmCpuUsed,String cmMemUsed,String did, String rid, String vid,String deviceName,String cmvmCount,String remainingCpu,String remainingMem,String dataStoreId) { super(); this.pname = pname; this.cpu = cpu; this.ram = ram; this.cpuUsed = cpuUsed; this.ramUsed = ramUsed; this.ip = ip; this.isNano = isNano; this.did = did; this.rid = rid; this.vid = vid; this.devceId = devceId; this.deviceName = deviceName; this.cmvmCount = cmvmCount; this.remainingCpu = remainingCpu; this.remainingMem = remainingMem; this.cmCpuUsed = cmCpuUsed; this.remainingMem = remainingMem; this.dataStoreId = dataStoreId; } }
/* * 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 duck_hunt; import java.util.Date; /** * * @author admin */ public class Ducks { public double angle; // angle public double speed; // pixel per frame public int randomability; // frames public int hitpoints; // integer public int leavetime; // frames public String bio; public String pic_location; public String name; public boolean is_alive; private int entry_frame; private int size; private int score; public int width_dec; private boolean has_left = false; private int type ; private Date entry_date ; public Date get_entry_date(){ return entry_date; } public void set_entry_date(Date de){ this.entry_date = de; } public int get_type(){ return this.type; } public void set_type(int t){ this.type = t; } public void set_has_left(boolean x){ this.has_left = x; } public boolean get_has_left(){ return this.has_left; } public int get_score(){ return this.score; } public void set_score(int x){ this.score = x; } public int get_entry_frame(){ return entry_frame; } public void set_entry_frame( int x){ this.entry_frame = x; } public void set_size(int s){ this.size = s; } public int get_size(){ return this.size; } public Ducks(double angle, double speed, int randomability, int HP, int LT, String b, String p, String name, int sc, int type){ this.angle = angle; this.speed = speed; this.randomability = randomability; this.hitpoints = HP; this.bio = b; this.leavetime = LT; this.pic_location = p; this.name = name; this.is_alive = true; this.size = 200; this.width_dec = 20; this.score = sc; this.has_left = false; this.type = type; } Ducks(Ducks a) { this.type = a.type; this.has_left = a.has_left; this.angle = a.angle; this.speed = a.speed; this.randomability = a.randomability; this.hitpoints = a.hitpoints; this.bio = a.bio; this.leavetime = a.leavetime; this.pic_location = a.pic_location; this.name = a.name; this.is_alive = true; this.size = a.size; this.score = a.score; this.width_dec = a.width_dec; } public void setter_obj (Ducks a) { this.type = a.type; this.has_left = a.has_left; this.angle = a.angle; this.speed = a.speed; this.randomability = a.randomability; this.hitpoints = a.hitpoints; this.bio = a.bio; this.leavetime = a.leavetime; this.pic_location = a.pic_location; this.name = a.name; this.is_alive = true; this.size = a.size; this.score = a.score; this.width_dec = a.width_dec; } }
package com.freeraven.algorithms.fibonacci; /** * Created by zvlades on 4/1/17. */ public class Fibonacci { public long getItemAtPositionRecursively(int position) { if (position < 0) throw new IllegalArgumentException("position < 0"); if (position < 2) { return position; } return getItemAtPositionRecursively(position - 1) + getItemAtPositionRecursively(position - 2); } public long getItemAtPosition(int position) { if (position < 0) throw new IllegalArgumentException("position < 0"); if (position < 2) { return position; } int previous = 0; int current = 1; int oldPrevious; for (int i = 1; i < position; i++) { oldPrevious = previous; previous = current; current = current + oldPrevious; } return current; } }
package com.dmtrdev.monsters.sprites.armors.ground; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.dmtrdev.monsters.DefenderOfNature; import com.dmtrdev.monsters.consts.ConstEnemies; import com.dmtrdev.monsters.screens.PlayScreen; import com.dmtrdev.monsters.sprites.armors.Armor; import com.dmtrdev.monsters.consts.ConstArmor; import com.dmtrdev.monsters.consts.ConstGame; import com.dmtrdev.monsters.sprites.armors.flyings.BirdArmor; public class CarnivorePlant extends Armor { private Animation<TextureRegion> mAttackAnimation; private Animation<TextureRegion> mIdleAnimation; private int mTakenDamage; private int mHp; private float attackTime; private Sound sound; public CarnivorePlant(final PlayScreen pPlayScreen, final float pX, final float pY, final boolean pDirection) { super(pPlayScreen, pX, pY, pDirection); setSize(ConstArmor.PLANT_SIZE - 0.7f, ConstArmor.PLANT_SIZE); setOriginCenter(); for (int j = 0; j < 4; j++) { for (int i = 0; i < 6; i++) { if (j == 3 && i == 1) { break; } frames.add(new TextureRegion(DefenderOfNature.getArmorsAtlas().findRegion("carnivorous_plant_idle"), i * 190, j * 158, 190, 158)); mIdleAnimation = new Animation<TextureRegion>(ConstArmor.PLANT_SPEED, frames, Animation.PlayMode.LOOP); } } frames.clear(); for (int j = 0; j < 2; j++) { for (int i = 0; i < 6; i++) { if (j == 1) { break; } frames.add(new TextureRegion(DefenderOfNature.getArmorsAtlas().findRegion("carnivorous_plant_attack"), i * 190, j * 158, 190, 158)); mAttackAnimation = new Animation<TextureRegion>(ConstArmor.PLANT_SPEED - 0.02f, frames, Animation.PlayMode.LOOP); } } frames.clear(); for (int j = 0; j < 22; j++) { frames.add(new TextureRegion(DefenderOfNature.getEffectsAtlas().findRegion("down_explode"), 0, j * 70, 354, 70)); destroyAnimation = new Animation<TextureRegion>(ConstArmor.EFFECT_SPEED, frames); } frames.clear(); mHp = ConstArmor.PLANT_HP; mTakenDamage = 0; attackTime = 0; direction = !(body.getPosition().x <= ConstGame.X / 2); sound = DefenderOfNature.getPlantSound(); if (playScreen.getOptions().getSoundCheck()) { sound.loop(); sound.play(playScreen.getOptions().getSoundVolume()); } } public void draw(final Batch pBatch) { if (!destroyed) { super.draw(pBatch); } if (ConstGame.GAME_STATE == ConstGame.State.PAUSE) { sound.pause(); } else if (playScreen.getOptions().getSoundCheck() && collisions != 0) { sound.resume(); } } @Override public void collisionEnemy() { } @Override public void collisionEnemy(final int pDamage, final boolean pCollision) { super.collisionEnemy(pDamage, pCollision); if (pCollision) { mTakenDamage += pDamage; } else { mTakenDamage -= pDamage; } } @Override public void collisionGround() { } @Override public int getArmorDamage() { return ConstArmor.CARNIVORE_PLANT_DAMAGE; } @Override public void update(final float delta) { if (setToDestroy && effects) { if (!destroy) { if (playScreen.getOptions().getSoundCheck()) { DefenderOfNature.getTomatoSound().play(playScreen.getOptions().getSoundVolume()); } setSize(ConstArmor.EFFECT_MEDIUM_SIZE + 1.7f, ConstArmor.EFFECT_MEDIUM_SIZE - 1.3f); setPosition(body.getPosition().x - getWidth() / 2, body.getPosition().y - 0.2f); world.destroyBody(body); time = 0; destroy = true; } else if (destroyAnimation.isAnimationFinished(time)) { destroyed = true; } setRegion(destroyAnimation.getKeyFrame(time)); time += delta; } else if (setToDestroy) { world.destroyBody(body); destroyed = true; } else if (collisions != 0) { sound.resume(); textureRegion = mAttackAnimation.getKeyFrame(attackTime); if (mHp <= 0) { setToDestroy = true; setSize(ConstArmor.EFFECT_BIG_SIZE, ConstArmor.EFFECT_BIG_SIZE); } else if (mAttackAnimation.isAnimationFinished(attackTime)) { mHp -= mTakenDamage; attackTime = 0; } else if (direction && !textureRegion.isFlipX()) { textureRegion.flip(true, false); } setPosition(body.getPosition().x - getWidth() / 2, body.getPosition().y - getHeight() / 3); setRegion(textureRegion); attackTime += delta; } else { sound.pause(); textureRegion = mIdleAnimation.getKeyFrame(time); if (direction && !textureRegion.isFlipX()) { textureRegion.flip(true, false); } setPosition(body.getPosition().x - getWidth() / 2, body.getPosition().y - getHeight() / 3); setRegion(textureRegion); time += delta; if (time >= 10f) { setToDestroy = true; time = 0; } } } @Override protected void defineArmor() { final BodyDef bodyDef = new BodyDef(); bodyDef.position.set(getX(), ConstEnemies.SPAWN_HEIGHT + ConstArmor.PLANT_BODY_HEIGHT); bodyDef.type = BodyDef.BodyType.StaticBody; body = world.createBody(bodyDef); final FixtureDef fixtureDef = new FixtureDef(); final PolygonShape shape = new PolygonShape(); shape.setAsBox(ConstArmor.PLANT_BODY_WIDTH, ConstArmor.PLANT_BODY_HEIGHT); fixtureDef.shape = shape; fixtureDef.filter.categoryBits = ConstGame.ARMOR_ENEMY_BIT; fixtureDef.filter.maskBits = ConstGame.ENEMY_DOWN_BIT | ConstGame.ENEMY_SHOTS_BIT; fixtureDef.density = ConstArmor.PLANT_DENSITY; body.createFixture(fixtureDef).setUserData(this); } }
package com.sinodynamic.hkgta.util; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import org.apache.log4j.DailyRollingFileAppender; import org.apache.log4j.helpers.LogLog; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class DDXAppender extends DailyRollingFileAppender { Date now = new Date(); SimpleDateFormat sdf; /**"文件名+上次最后更新时间"*/ private String scheduledFilename; /**不允许改写的datepattern */ private final String datePattern = "'.'yyyy-MM-dd"; private void init() { Resource res = new ClassPathResource("placeholder/dda_i.properties"); Properties ddxProp = new Properties(); try { ddxProp.load(res.getInputStream()); String fileName = (String)ddxProp.get("ddx.log.dir"); super.setFile(fileName); } catch (IOException e) { e.printStackTrace(); } } /** * 初始化本Appender对象的时候调用一次 */ public void activateOptions() { init(); super.activateOptions(); if(fileName != null) { //perf.log now.setTime(System.currentTimeMillis()); sdf = new SimpleDateFormat(datePattern); File file = new File(fileName); //获取最后更新时间拼成的文件名 scheduledFilename = fileName+sdf.format(new Date(file.lastModified())); } else { LogLog.error("File is not set for appender ["+name+"]."); } } }