text
stringlengths
10
2.72M
import java.util.Scanner; class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n= scanner.nextInt(); int m = scanner.nextInt(); int a[][] = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = scanner.nextInt(); } } int max[] = Max(a, n, m); for(int j = 0; j < n; j++) { System.out.println("max in " + (j+1) + " column = " + max[j]); } } public static int[] Max (int a[][], int n, int m) { int arr[] = new int[n]; for (int j = 0; j < n; j++) { arr[j] = a[0][j]; for(int i = 1; i < m; i++) { if(a[i][j] > arr[j]) { arr[j] = a[i][j]; } } } return arr; } }
package com.zym.blog.controller; import com.github.pagehelper.PageHelper; import com.zym.blog.service.BlogService; import org.springframework.beans.factory.annotation.Autowired; 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.RestController; /** * @author Gavin * @date 2016-09-05 */ @RestController @RequestMapping("/article") public class BlogController { @Autowired private BlogService blogService; @RequestMapping(value = "/{blogId}", method = RequestMethod.GET) public Object get(@PathVariable("blogId") int id) { return blogService.getById(id); } @RequestMapping(value = "", method = RequestMethod.GET) public Object getAll(Integer page, Integer perPage) { if (page == null) { page = 1; } if (perPage == null) { perPage = 4; } return blogService.getAll(page, perPage); } }
package com.horanet.BarbeBLE; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.bluetooth.le.BluetoothLeScanner; import android.bluetooth.le.ScanCallback; import android.bluetooth.le.ScanFilter; import android.bluetooth.le.ScanResult; import android.bluetooth.le.ScanSettings; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.Button; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import com.horanet.BarbeBLE.R; import static com.horanet.BarbeBLE.Constants.PARCEL_HORANET_UUID; public class CentralRoleActivity extends AppCompatActivity implements DevicesAdapter.DevicesAdapterListener { private RecyclerView mDevicesRecycler; private DevicesAdapter mDevicesAdapter; private ScanCallback mScanCallback; private Handler mHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_central_role); mDevicesRecycler = (RecyclerView) findViewById(R.id.devices_recycler_view); mDevicesRecycler.setHasFixedSize(true); mDevicesRecycler.setLayoutManager(new LinearLayoutManager(this)); mDevicesAdapter = new DevicesAdapter(this); mDevicesRecycler.setAdapter(mDevicesAdapter); mHandler = new Handler(Looper.getMainLooper()); startBLEScan(); } protected BluetoothAdapter getBluetoothAdapter() { BluetoothAdapter bluetoothAdapter; BluetoothManager bluetoothService = ((BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE)); if (bluetoothService != null) { bluetoothAdapter = bluetoothService.getAdapter(); if (bluetoothAdapter != null) { if (bluetoothAdapter.isEnabled()) { return bluetoothAdapter; } } } return null; } private void startBLEScan() { BluetoothAdapter bluetoothAdapter = getBluetoothAdapter(); if (bluetoothAdapter != null) { BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner(); if (bluetoothLeScanner != null) { if (mScanCallback == null) { // Kick off a new scan. mScanCallback = new SampleScanCallback(); bluetoothLeScanner.startScan(buildScanFilters(), buildScanSettings(), mScanCallback); } else { } return; } } } private List<ScanFilter> buildScanFilters() { List<ScanFilter> scanFilters = new ArrayList<>(); ScanFilter.Builder builder = new ScanFilter.Builder(); builder.setServiceUuid(PARCEL_HORANET_UUID); scanFilters.add(builder.build()); return scanFilters; } private ScanSettings buildScanSettings() { ScanSettings.Builder builder = new ScanSettings.Builder(); builder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY); return builder.build(); } public void stopScanning() { Log.d(MainActivity.TAG, "Stopping Scanning"); BluetoothAdapter bluetoothAdapter = getBluetoothAdapter(); if (bluetoothAdapter != null) { BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner(); if (bluetoothLeScanner != null) { // Stop the scan, wipe the callback. bluetoothLeScanner.stopScan(mScanCallback); mScanCallback = null; // Even if no new results, update 'last seen' times. mDevicesAdapter.notifyDataSetChanged(); return; } } } @Override public void onDeviceItemClick(String deviceName, String deviceAddress) { //stopScanning(); Intent intent = new Intent(this, DeviceConnectActivity.class); intent.putExtra(DeviceConnectActivity.EXTRAS_DEVICE_NAME, deviceName); intent.putExtra(DeviceConnectActivity.EXTRAS_DEVICE_ADDRESS, deviceAddress); startActivity(intent); } private class SampleScanCallback extends ScanCallback { @Override public void onBatchScanResults(List<ScanResult> results) { super.onBatchScanResults(results); mDevicesAdapter.add(results); } @Override public void onScanResult(int callbackType, ScanResult result) { super.onScanResult(callbackType, result); mDevicesAdapter.add(result); } @Override public void onScanFailed(int errorCode) { super.onScanFailed(errorCode); } } }
package br.com.maricamed.repositories; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import br.com.maricamed.entities.Medico; public interface MedicoRepository extends JpaRepository<Medico, Long> { /* @Query("select u FROM Usuario u " + "JOIN u.perfis p " + "WHERE u.email like :search% OR p.desc like :search% OR u.nome LIKE :search%") */ @Query("Select m FROM Medico m " + "JOIN m.usuario u " + "JOIN m.clinica c WHERE m.crm LIKE :search% " + "OR u.nome LIKE :search% " + "AND c.id = :idClinica") Page<Medico> findAllByNomeCrm(Long idClinica, String search, Pageable pageable); @Query("Select m FROM Medico m WHERE m.clinica.id = :idClinica") Page<Medico> findAllByIdClinica(Long idClinica, Pageable pageable); @Query("Select m FROM Medico m " + "JOIN m.clinica c WHERE c.id = :idClinica") List<Medico> findByIdClinica(Long idClinica); }
package com.example.demo.service; import com.example.demo.model.Giphy; import com.example.demo.model.Page; import org.junit.Assert; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.jupiter.api.Assertions.*; @RunWith(SpringRunner.class) @SpringBootTest class GiphyClientTest { @Autowired private GiphyClient giphyClient; @Test void giphyPic() { Giphy giphy = giphyClient.giphyPic("test"); Assert.assertNotNull(giphy); } }
package com.shop.serviceImpl; import com.shop.mapper.CouponMapper; import com.shop.model.Coupon; import com.shop.model.User; import com.shop.service.CouponService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service public class CouponServiceImpl implements CouponService { @Autowired private CouponMapper mapper; @Override @Transactional public boolean getCoupon(User user, Long couponId) { return mapper.getCoupon(user.getUserId(),couponId)==1; } @Override public List<Coupon> selectAllByUser(Long userId) { return mapper.getByUserId(userId); } @Override public List<Coupon> selectAll() { return mapper.getAll(); } @Override public Coupon getById(Long couponId) { return mapper.getById(couponId); } }
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.FindBys; import org.openqa.selenium.support.PageFactory; //import java.text.ParseException; import java.util.List; public class DisplaySearchResult { WebDriver driver; //@FindBy(css = "#lastNameGroup > label") //WebElement lastname_lbl; @FindBy(id = "owners") WebElement owner_table; @FindBys(value = @FindBy(id = "owners")) List<WebElement> is_resultTabPresent; //@FindBy(css = "#search-owner-form > div:nth-child(2) > div > button") //WebElement find_btn; //@FindBy(linkText = "Add Owner") //WebElement addOwner_btn; public DisplaySearchResult(WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); // This initElements method will create all WebElements } boolean is_ResultTablePresent() { return is_resultTabPresent.size() > 0; } // display result public int getResult() { List<WebElement> head = owner_table.findElements(By.xpath("//*[@id=\"owners\"]/thead")); List<WebElement> rows = owner_table.findElements(By.xpath("//*[@id=\"owners\"]/tbody/tr")); if (rows.size() >= 1) { System.out.println(owner_table.findElement(By.xpath("//*[@id=\"owners\"]/thead/tr")).getText()); //System.out.println(columns.size()); for (int j = 0; j < rows.size(); j++) { System.out.println(rows.get(j).getText()); } return 1; } else return 0; } // Match result based on name and phone public int clickFind(String name, String phone) { List<WebElement> rows = owner_table.findElements(By.xpath("//*[@id=\"owners\"]/tbody/tr")); for (int j = 1; j <= rows.size(); j++) { System.out.println(":" + owner_table.findElement(By.xpath("//*[@id=\"owners\"]/tbody/tr[" + j + "]/td[1]/a")).getText() + ":"); System.out.println(":" + owner_table.findElement(By.xpath("//*[@id=\"owners\"]/tbody/tr[" + j + "]/td[4]")).getText() + ":"); if (name.equals(owner_table.findElement(By.xpath("//*[@id=\"owners\"]/tbody/tr[" + j + "]/td[1]/a")).getText()) && phone.equals(owner_table.findElement(By.xpath("//*[@id=\"owners\"]/tbody/tr[" + j + "]/td[4]")).getText())) { System.out.println("Inside condition"); owner_table.findElement(By.xpath("//*[@id=\"owners\"]/tbody/tr[" + j + "]/td[1]/a")).click(); return 1; } } return 0; } /* public void click_addOwner() { addOwner_btn.click(); } public void findbyLastname(String strlname) { // Fill last name this.setlname(strlname); // Click find button this.clickFind(); } */ }
/* * 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 weekhours; /** * * @author emwhfm */ public class WeekHours { public static int[][] calcTotal(int[][] m) { int[][] tot = new int[m.length][2]; for (int r=0; r<m.length; r++) { tot[r][0] = r; for (int k=0; k<m[0].length; k++) { tot[r][1] += m[r][k]; } } return tot; } public static void printDecreasing(int[][] m) { //java.util.Arrays.sort(m, new ColumnComparator(1)); for (int r=0; r<m.length; r++) { int min = 0xFFFF; int index = 0; for (int i=0; i<m.length; i++) { if (m[i][1] < min) { min = m[i][1]; index = i; } } System.out.println("Employee " + index + " total hours: " + min); m[index][1] = 0XFFFF; } } /** * @param args the command line arguments */ public static void main(String[] args) { int[][] employee = { {2, 4, 3, 4, 5, 8, 8}, {7, 3, 4, 3, 3, 4, 4}, {3, 3, 4, 3, 3, 2, 2}, {9, 3, 4, 7, 3, 4, 1}, {3, 5, 4, 3, 6, 3, 8}, {3, 4, 4, 6, 3, 4, 4}, {3, 7, 4, 8, 3, 8, 4}, {6, 3, 5, 9, 2, 7, 9} }; int[][] total = calcTotal(employee); //System.out.println(java.util.Arrays.toString(total[0])); printDecreasing(total); } }
package J_51; /** * Created by IBM_ADMIN on 10/16/2016. */ public class FishTrainer implements Animal { public void move() { System.out.println("Swim Swim"); } public void eat() { System.out.println("Eat other fish"); } public void sleep() { System.out.println("Sleep in water"); } ; }
package com.metoo.foundation.dao; import org.springframework.stereotype.Repository; import com.metoo.core.base.GenericDAO; import com.metoo.foundation.domain.ActivityGoods; @Repository("activityGoodsDAO") public class ActivityGoodsDAO extends GenericDAO<ActivityGoods> { }
package me.levylin.lib.base.loader; import java.util.List; /** * ๆ•ฐๆฎๅบ“ๅŠ ่ฝฝๅˆ—่กจไธ“็”จ * Created by LinXin on 2017/1/13 15:14. */ public class PageVo<ITEM> { private List<ITEM> itemList; private int count; public List<ITEM> getItemList() { return itemList; } public void setItemList(List<ITEM> itemList) { this.itemList = itemList; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } }
package org.vanilladb.comm.protocols.floodingcons; import java.net.SocketAddress; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.vanilladb.comm.process.ProcessList; import org.vanilladb.comm.process.ProcessState; import org.vanilladb.comm.protocols.events.ProcessListInit; import org.vanilladb.comm.protocols.tcpfd.FailureDetected; import org.vanilladb.comm.protocols.tcpfd.ProcessConnected; import net.sf.appia.core.AppiaEventException; import net.sf.appia.core.Channel; import net.sf.appia.core.Direction; import net.sf.appia.core.Event; import net.sf.appia.core.Layer; import net.sf.appia.core.Session; /** * This implements Flooding Consensus Protocol. Note that this can only be run once. * * @author SLMT * */ public class FloodingConsensusSession extends Session { private static Logger logger = Logger.getLogger(FloodingConsensusSession.class.getName()); private ProcessList processList; private int roundId = 1; private boolean hasDecided = false; private List<Set<Value>> proposalsPerRound = new ArrayList<Set<Value>>(); private List<Set<Integer>> correctsPerRound = new ArrayList<Set<Integer>>(); FloodingConsensusSession(Layer layer) { super(layer); } @Override public void handle(Event event) { if (event instanceof ProcessListInit) handleProcessListInit((ProcessListInit) event); else if (event instanceof ProcessConnected) handleProcessConnected((ProcessConnected) event); else if (event instanceof FailureDetected) handleFailureDetected((FailureDetected) event); else if (event instanceof ConsensusRequest) handleConsensusRequest((ConsensusRequest) event); else if (event instanceof Propose) handlePropose((Propose) event); else if (event instanceof Decide) handleDecide((Decide) event); } private void handleProcessListInit(ProcessListInit event) { if (logger.isLoggable(Level.FINE)) logger.fine("Received ProcessListInit"); // Save the list this.processList = event.copyProcessList(); // Let the event continue try { event.go(); } catch (AppiaEventException e) { e.printStackTrace(); } // Initialize the first round correctsPerRound.add(new HashSet<Integer>()); } private void handleProcessConnected(ProcessConnected event) { if (logger.isLoggable(Level.FINE)) logger.fine("Received ProcessConnected"); // Let the event continue try { event.go(); } catch (AppiaEventException e) { e.printStackTrace(); } // Set the connected process ready processList.getProcess(event.getConnectedProcessId()) .setState(ProcessState.CORRECT); // Add the correct processes to the list of initial round (round 0) correctsPerRound.get(0).add(event.getConnectedProcessId()); } private void handleFailureDetected(FailureDetected event) { if (logger.isLoggable(Level.FINE)) logger.fine("Received FailureDetected (failed id = " + event.getFailedProcessId() + ")"); processList.getProcess(event.getFailedProcessId()).setState(ProcessState.FAILED); // Let the event continue try { event.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } private void handleConsensusRequest(ConsensusRequest event) { if (logger.isLoggable(Level.FINE)) logger.fine("Received ConsensusRequest"); // Note that we start from round one roundId = 1; // Create a new proposal Set<Value> proposal = new HashSet<Value>(); proposal.add(event.getValue()); // Propose propose(event.getChannel(), roundId, proposal); } // Note that we might receive a proposal from ourselves // since it is a broadcast. private void handlePropose(Propose event) { if (logger.isLoggable(Level.FINE)) logger.fine("Received Propose"); // Includes the proposal includePrposal(event.getRoundId(), event.getProposal()); // Record who sent the proposal int senderPid = processList.getId((SocketAddress) event.source); setCorrect(event.getRoundId(), senderPid); // See if we can decide a value tryDecide(event.getChannel()); } private void handleDecide(Decide event) { if (logger.isLoggable(Level.FINE)) logger.fine("Received Decide"); if (!hasDecided) { hasDecided = true; // Deliver the result deliverDecision(event.getChannel(), event.getValue()); // Relay the decision try { event.setDir(Direction.DOWN); event.setSourceSession(this); event.init(); event.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } } private void propose(Channel channel, int roundId, Set<Value> proposal) { // Send a Propose broadcast try { Propose propose = new Propose(channel, this, roundId, proposal); propose.init(); propose.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } private void includePrposal(int roundId, Set<Value> receivedProposal) { // Extends the proposal list to match the round while (proposalsPerRound.size() < roundId + 1) { proposalsPerRound.add(new HashSet<Value>()); } // Add the proposal to the list proposalsPerRound.get(roundId).addAll(receivedProposal); } private void setCorrect(int roundId, int pid) { // Extends the correct list to match the round while (correctsPerRound.size() < roundId + 1) { correctsPerRound.add(new HashSet<Integer>()); } // Add the correct process to the list correctsPerRound.get(roundId).add(pid); } private void tryDecide(Channel channel) { // Check if we have received all the proposal in the current round if (!hasDecided && correctsPerRound.get(roundId).containsAll(processList.getCorrectProcessIds())) { // Check if the view changes in this round if (correctsPerRound.get(roundId).containsAll(correctsPerRound.get(roundId - 1))) { decide(channel); } else { // Cannot decide, start a new round roundId++; propose(channel, roundId, proposalsPerRound.get(roundId - 1)); } } } private void decide(Channel channel) { // Make a decision Value decision = Collections.min(proposalsPerRound.get(roundId)); // Deliver the decision hasDecided = true; deliverDecision(channel, decision); // Send a decide broadcast try { Decide decide = new Decide(channel, this, decision); decide.init(); decide.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } private void deliverDecision(Channel channel, Value decision) { try { ConsensusResult result = new ConsensusResult(channel, this, decision); result.init(); result.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } }
/* * Copyright (c) 2004 Steve Northover and Mike Wilson * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ package part1; import org.eclipse.swt.*; import org.eclipse.swt.widgets.*; import org.eclipse.swt.events.*; public class Fragments1 { Composite parent; Text text; Shell shell; Widget widget; Event event; MenuItem item; int i; public void f1() { Text text = new Text(parent, SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER); } public void f2() { if ((text.getStyle () & SWT.SINGLE) != 0) { System.out.println ("Single Line Text"); } } public void f3() { Label label = new Label(shell, SWT.NONE) { protected void checkSubclass() { } public void setText(String string) { System.out.println("Setting the string"); super.setText(string); } }; } public void f4() { widget.addListener(SWT.Dispose, new Listener() { public void handleEvent(Event event) { // widget was disposed } }); } public void f5() { widget.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent event) { // widget was disposed } }); } public void f6() { Listener listener = new Listener() { public void handleEvent(Event event) { switch (event.type) { case SWT.Dispose: break; case SWT.MouseDown: break; case SWT.MouseUp: break; case SWT.MouseMove: break; } System.out.println("Something happened."); } }; shell.addListener(SWT.Dispose, listener); shell.addListener(SWT.MouseDown, listener); shell.addListener(SWT.MouseUp, listener); shell.addListener(SWT.MouseMove, listener); } public void f7 () { Listener listener = new Listener() { public void handleEvent(Event e) { switch (e.detail) { case SWT.TRAVERSE_ESCAPE: e.doit = false; /* Code to cancel edit goes here */ break; } } }; text.addListener(SWT.Traverse, listener); } public void f8 () { Listener listener = new Listener() { public void handleEvent(Event e) { switch (e.detail) { case SWT.TRAVERSE_ESCAPE: e.detail = SWT.TRAVERSE_NONE; e.doit = true; /* Code to cancel edit goes here */ break; case SWT.TRAVERSE_RETURN: e.detail = SWT.TRAVERSE_NONE; e.doit = true; /* Code to accept edit goes here */ break; } } }; text.addListener(SWT.Traverse, listener); } int getStyle() { return 0; } public void f9 () { Listener listener = new Listener() { public void handleEvent(Event e) { switch (e.detail) { case SWT.TRAVERSE_ESCAPE: case SWT.TRAVERSE_PAGE_NEXT: case SWT.TRAVERSE_PAGE_PREVIOUS: e.doit = true; break; case SWT.TRAVERSE_RETURN: case SWT.TRAVERSE_TAB_NEXT: case SWT.TRAVERSE_TAB_PREVIOUS: if ((getStyle() & SWT.SINGLE) != 0) { e.doit = true; } else { if ((e.stateMask & SWT.MODIFIER_MASK) != 0) { e.doit = true; } } break; } } }; text.addListener(SWT.Traverse, listener); } public void f10 () { //WRONG โ€“ broken when new modifier masks are added int bits = SWT.CONTROL | SWT.ALT | SWT.SHIFT | SWT.COMMAND; if ((event.stateMask & bits) == 0) { System.out.println("No modifiers are down"); } //CORRECT โ€“ works when new modifier masks are added if ((event.stateMask & SWT.MODIFIER_MASK) == 0) { System.out.println("No modifiers are down"); } } public void f11 () { item.setText("Select &All\tCtrl+A"); item.setAccelerator(SWT.MOD1 + 'A'); item.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { System.out.println("The item was selected."); } }); } public void f12 () { //WRONG โ€“ only draws last percentage text.setText("0 %"); for (int i=1; i<=100; i++) { try { Thread.sleep(100); } catch (Throwable th) {} text.setText(i + " %"); } } public void f13 () { //CORRECT โ€“ draws every percentage text.setText("0 %"); text.update(); for (int i=1; i<=100; i++) { try { Thread.sleep(100); } catch (Throwable th) {} text.setText(i + " %"); text.update(); } } }
package sessionBeans; import entites.Categorie; import entites.Offre; import entites.Produit; import java.util.ArrayList; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; @Stateless public class BeanMenu implements BeanMenuLocal { @PersistenceContext(unitName = "montgallette-ejbPU") private EntityManager em; @Override public void creerJeuxDonnees() { String descrCourte = "Suspendisse potenti. In hac habitasse platea dictumst."; String descrComplete = "Donec finibus laoreet finibus. Phasellus ut ante tincidunt, venenatis ante eget, volutpat risus."; // Sed viverra at justo vitae pulvinar. Curabitur facilisis lectus ac justo mollis luctus. Sed suscipit sapien et massa semper, nec interdum libero condimentum. Curabitur mi mauris, convallis feugiat enim posuere, accumsan rutrum quam. Aenean gravida libero lorem, nec sagittis justo molestie ut."; List<Produit> lp = new ArrayList(); List<Categorie> lc = new ArrayList(); List<Offre> lo = new ArrayList(); //Creer categories lc.add(new Categorie("Entree")); lc.add(new Categorie("Plat")); lc.add(new Categorie("Dessert")); lc.add(new Categorie("Boisson")); //Creer offres lo.add(new Offre("Entrรฉe + plat + boisson", "midi1", 13.95)); lo.add(new Offre("Entrรฉe + plat + dessert + boisson", "midi2", 15.95)); lo.add(new Offre("Plat + dessert + boisson", "midi3", 11.95)); //CREER PRODUITS //Creer entrees lp.add(new Produit("Soupe au poitiron au comptรฉ", true, true, 5.95, descrCourte, descrComplete, lc.get(0), "images/menu/soupepoitiron.jpg")); lp.add(new Produit("Grande assiette ร  partager", true, true, 12.95, descrCourte, descrComplete, lc.get(0), "images/menu/assietteparteger.jpg")); lp.add(new Produit("Terrine de champagne", true, true, 4.50, descrCourte, descrComplete, lc.get(0), "images/menu/terrinecampagne.jpg")); lp.add(new Produit("Faisselle de fromage blanc", true, true, 5.95, descrCourte, descrComplete, lc.get(0), "images/menu/faissellefblanc.jpg")); lp.add(new Produit("Tartare de saumon et tomate", true, true, 6.50, descrCourte, descrComplete, lc.get(0), "images/menu/tartaresaumon.jpg")); lp.add(new Produit("Tortilla espaรฑola", true, true, 5.50, descrCourte, descrComplete, lc.get(0), "images/menu/tortillaespanola.jpg")); //Creer plats lp.add(new Produit("Steak dans la hampe", true, true, 13.50, descrCourte, descrComplete, lc.get(1), "images/menu/steakhampe.jpg")); lp.add(new Produit("Tartare de boef", true, true, 12.50, descrCourte, descrComplete, lc.get(1), "images/menu/tartareboeuf.jpg")); lp.add(new Produit("Pavรฉ de rumsteak", true, true, 15.95, descrCourte, descrComplete, lc.get(1), "images/menu/paverumsteak.jpg")); lp.add(new Produit("Andouillette", true, true, 12.50, descrCourte, descrComplete, lc.get(1), "images/menu/andouillette.jpg")); lp.add(new Produit("Poulet a la normande", true, true, 12.50, descrCourte, descrComplete, lc.get(1), "images/menu/pouletnormande.jpg")); lp.add(new Produit("Bavette au poivre", true, true, 12.95, descrCourte, descrComplete, lc.get(1), "images/menu/bavettepoivre.jpg")); lp.add(new Produit("Daurade au citron", true, true, 13.95, descrCourte, descrComplete, lc.get(1), "images/menu/dauradecitron.jpg")); //Creer desserts lp.add(new Produit("Tiramisu", true, false, 4.95, descrCourte, descrComplete, lc.get(2), "images/menu/tiramisu.jpg")); lp.add(new Produit("Duo chocolat", true, true, 4.50, descrCourte, descrComplete, lc.get(2), "images/menu/duochocolat.jpg")); lp.add(new Produit("Coupe de pamplemousse", true, true, 4.99, descrCourte, descrComplete, lc.get(2), "images/menu/couplepamplemousse.jpg")); lp.add(new Produit("Gรคteau basque", true, true, 3.95, descrCourte, descrComplete, lc.get(2), "images/menu/gateaubasque.jpg")); lp.add(new Produit("Crรจme brรปlรฉe", true, true, 5.95, descrCourte, descrComplete, lc.get(2), "images/menu/cremebrulee.jpg")); lp.add(new Produit("Chocolate con churros", true, true, 4.95, descrCourte, descrComplete, lc.get(2), "images/menu/chocolatechurros.jpg")); //Creer boissons lp.add(new Produit("Mojito", true, true, 4.95, descrCourte, descrComplete, lc.get(3), "images/menu/mojito.jpg")); lp.add(new Produit("Cocacola", true, false, 2.50, descrCourte, descrComplete, lc.get(3), "images/menu/cocacola.jpg")); lp.add(new Produit("Piรฑa colada", true, true, 4.95, descrCourte, descrComplete, lc.get(3), "images/menu/pinacolada.jpg")); lp.add(new Produit("Perrier", true, false, 1.95, descrCourte, descrComplete, lc.get(3), "images/menu/perrier.jpg")); lp.add(new Produit("Nestea", true, false, 2.50, descrCourte, descrComplete, lc.get(3), "images/menu/nestea.jpg")); lp.add(new Produit("Jus d'orange", true, false, 2.95, descrCourte, descrComplete, lc.get(3), "images/menu/jusorange.jpg")); //LIER PRODUITS AUX OFFRES //Lier entrees lp.get(0).getOffres().add(lo.get(0)); lp.get(0).getOffres().add(lo.get(1)); lp.get(2).getOffres().add(lo.get(0)); lp.get(2).getOffres().add(lo.get(1)); lp.get(3).getOffres().add(lo.get(0)); lp.get(3).getOffres().add(lo.get(1)); lp.get(5).getOffres().add(lo.get(0)); lp.get(5).getOffres().add(lo.get(1)); //Lier plats lp.get(10).getOffres().add(lo.get(0)); lp.get(10).getOffres().add(lo.get(1)); lp.get(10).getOffres().add(lo.get(2)); lp.get(11).getOffres().add(lo.get(0)); lp.get(11).getOffres().add(lo.get(1)); lp.get(11).getOffres().add(lo.get(2)); lp.get(12).getOffres().add(lo.get(0)); lp.get(12).getOffres().add(lo.get(1)); lp.get(12).getOffres().add(lo.get(2)); //Lier desserts lp.get(13).getOffres().add(lo.get(1)); lp.get(13).getOffres().add(lo.get(2)); lp.get(14).getOffres().add(lo.get(1)); lp.get(14).getOffres().add(lo.get(2)); lp.get(15).getOffres().add(lo.get(1)); lp.get(15).getOffres().add(lo.get(2)); lp.get(16).getOffres().add(lo.get(1)); lp.get(16).getOffres().add(lo.get(2)); lp.get(17).getOffres().add(lo.get(1)); lp.get(17).getOffres().add(lo.get(2)); lp.get(18).getOffres().add(lo.get(1)); lp.get(18).getOffres().add(lo.get(2)); //Lier boissons lp.get(19).getOffres().add(lo.get(0)); lp.get(19).getOffres().add(lo.get(1)); lp.get(19).getOffres().add(lo.get(2)); lp.get(20).getOffres().add(lo.get(0)); lp.get(20).getOffres().add(lo.get(1)); lp.get(20).getOffres().add(lo.get(2)); lp.get(21).getOffres().add(lo.get(0)); lp.get(21).getOffres().add(lo.get(1)); lp.get(21).getOffres().add(lo.get(2)); lp.get(22).getOffres().add(lo.get(0)); lp.get(22).getOffres().add(lo.get(1)); lp.get(22).getOffres().add(lo.get(2)); lp.get(23).getOffres().add(lo.get(0)); lp.get(23).getOffres().add(lo.get(1)); lp.get(23).getOffres().add(lo.get(2)); lp.get(24).getOffres().add(lo.get(0)); lp.get(24).getOffres().add(lo.get(1)); lp.get(24).getOffres().add(lo.get(2)); lc.stream().forEach((c) -> { em.persist(c); }); lo.stream().forEach((o) -> { em.persist(o); }); lp.stream().forEach((p) -> { em.persist(p); }); } @Override public List<Produit> selectAllProduit(String categorie) { String req = "select p from Produit p where p.categorie.nom =:categorieParam"; Query qr = em.createQuery(req); qr.setParameter("categorieParam", categorie); return qr.getResultList(); } @Override public List<Produit> selectOffres() { String req = "select p from Produit p "; Query qr = em.createQuery(req); List<Produit> lp = qr.getResultList(); req = "select p.offres from Produit p where p = :paramProduit"; qr = em.createQuery(req); for (Produit p : lp) { qr.setParameter("paramProduit", p); List<Offre> lo = qr.getResultList(); p.setOffres(lo); } return lp; } }
package com.grocery.codenicely.vegworld_new.sub_category.view; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import java.util.ArrayList; import java.util.List; /** * Created by Meghal on 6/19/2016. */ class ViewPagerAdapter extends FragmentPagerAdapter { private List<Fragment> fragmentList = new ArrayList<>(); private List<String> fragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return fragmentList.get(position); } @Override public int getCount() { return fragmentList.size(); } public void setTabData(List<Fragment> fragmentList, List<String> fragmentTitleList) { this.fragmentList = fragmentList; this.fragmentTitleList = fragmentTitleList; } @Override public CharSequence getPageTitle(int position) { return fragmentTitleList.get(position); } @Override public int getItemPosition(Object object) { return POSITION_NONE; } }
package com.ranpeak.ProjectX.activity.lobby.forAuthorizedUsers.navigationFragment.profileNavFragment.myResumeFragment.resume; import android.arch.lifecycle.ViewModelProviders; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.r0adkll.slidr.Slidr; import com.ranpeak.ProjectX.R; import com.ranpeak.ProjectX.activity.interfaces.Activity; import com.ranpeak.ProjectX.dto.MyResumeDTO; import com.ranpeak.ProjectX.networking.IsOnline; import com.ranpeak.ProjectX.networking.retrofit.ApiService; import com.ranpeak.ProjectX.networking.retrofit.RetrofitClient; import com.ranpeak.ProjectX.networking.volley.Constants; import com.ranpeak.ProjectX.activity.lobby.forAuthorizedUsers.navigationFragment.profileNavFragment.viewModel.MyResumeViewModel; import java.util.Objects; import de.hdodenhof.circleimageview.CircleImageView; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; public class MyResumeViewActivity extends AppCompatActivity implements Activity { private static MyResumeDTO myResumeItem; private static MyResumeDTO resumeDTO; private MyResumeDTO myEditedResumeItem; private MyResumeViewModel resumeViewModel; private CompositeDisposable disposable = new CompositeDisposable(); private ApiService apiService = RetrofitClient.getInstance().create(ApiService.class); private TextView subject; private TextView opportunities; private TextView userName; private TextView userEmail; private TextView userCountry; private CircleImageView avatar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_resume_view); resumeViewModel = ViewModelProviders.of(this).get(MyResumeViewModel.class); toolbar(); findViewById(); initData(); onListener(); Slidr.attach(this); } @Override public void findViewById() { subject = findViewById(R.id.activity_my_resume_view_subject); opportunities = findViewById(R.id.activity_my_resume_view_opportunities); userName = findViewById(R.id.activity_my_resume_view_user_name); userEmail = findViewById(R.id.activity_my_resume_view_user_email); userCountry = findViewById(R.id.activity_my_resume_view_user_country); avatar = findViewById(R.id.activity_my_resume_view_avatar); } @Override public void onListener() { } private void toolbar() { Objects.requireNonNull(getSupportActionBar()).setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(getString(R.string.app_name)); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_my_task, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // back button on toolbar pressed case android.R.id.home: finish(); return true; case R.id.menu_my_task_edit: Intent intent = new Intent(getApplicationContext(), MyResumeEditActivity.class); intent.putExtra("MyResume", resumeDTO); // startActivity(intent); startActivityForResult(intent, Constants.Codes.EDIT_CODE); break; case R.id.menu_my_task_delete: if(IsOnline.getInstance().isConnectingToInternet(getApplicationContext())) { resumeViewModel.delete(resumeDTO); } else { Toast.makeText(this, getString(R.string.no_internet), Toast.LENGTH_SHORT).show(); } finish(); break; default: return super.onOptionsItemSelected(item); } return true; } private void initData() { myResumeItem = (MyResumeDTO) getIntent().getSerializableExtra("MyResume"); resumeDTO = myResumeItem; resumeViewModel = ViewModelProviders.of(this).get(MyResumeViewModel.class); disposable.add(resumeViewModel.getResumeById(myResumeItem.getId()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(val -> { resumeDTO = val; })); disposable.dispose(); setData(resumeDTO); } private void setData(MyResumeDTO resumeDTO) { // Glide.with(getApplicationContext()) // .load(resumeDTO.getUserAvatar()) // .into(avatar); subject.setText(resumeDTO.getSubject()); opportunities.setText(resumeDTO.getOpportunities()); userCountry.setText(resumeDTO.getUserCountry()); userName.setText(resumeDTO.getUserName()); userEmail.setText(resumeDTO.getUserEmail()); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if (requestCode == Constants.Codes.EDIT_CODE && resultCode == Constants.Codes.EDIT_CODE) { if (data != null) { myEditedResumeItem = (MyResumeDTO) data.getSerializableExtra("EditedResume"); setEditedData(myEditedResumeItem); } } } private void setEditedData(MyResumeDTO editedData) { myResumeItem = editedData; subject.setText(editedData.getSubject()); opportunities.setText(editedData.getOpportunities()); } }
package com.test.base; import java.util.Arrays; import com.test.SolutionA; import com.test.SolutionB; import junit.framework.TestCase; public class Example extends TestCase { private Solution solution; @Override protected void setUp() throws Exception { super.setUp(); } public void testSolutionA() { solution = new SolutionA(new int[] {1, 2, 3}); System.out.println("----------------testSolutionA--------------"); assertSolution(); } public void testSolutionB() { solution = new SolutionB(new int[] {1, 2, 3}); System.out.println("--------------testSolutionB----------------"); assertSolution(); } private void assertSolution() { for (int i = 0; i < 6; i++) { System.out.println(Arrays.toString(solution.shuffle())); } } @Override protected void tearDown() throws Exception { solution = null; super.tearDown(); } }
package InformationRetrieval.Index; import InformationRetrieval.Query.QueryResult; import java.util.ArrayList; import java.util.Iterator; public class PositionalPostingList { private ArrayList<PositionalPosting> postings; public PositionalPostingList(){ postings = new ArrayList<PositionalPosting>(); } public int size(){ return postings.size(); } public int getIndex(int docId){ int begin = 0, end = size() - 1, middle; while (begin <= end){ middle = (begin + end) / 2; if (docId == postings.get(middle).getDocId()){ return middle; } else { if (docId < postings.get(middle).getDocId()){ end = middle - 1; } else { begin = middle + 1; } } } return -1; } QueryResult toQueryResult(){ QueryResult result = new QueryResult(); for (PositionalPosting posting: postings){ result.add(posting.getDocId()); } return result; } void add(int docId, int position){ int index = getIndex(docId); if (index == -1){ postings.add(new PositionalPosting(docId)); postings.get(postings.size() - 1).add(position); } else { postings.get(index).add(position); } } PositionalPosting get(int index){ return postings.get(index); } PositionalPostingList intersection(PositionalPostingList secondList){ Iterator<PositionalPosting> iterator1 = postings.iterator(), iterator2 = secondList.postings.iterator(); PositionalPosting p1 = iterator1.next(), p2 = iterator2.next(); PositionalPostingList result = new PositionalPostingList(); Iterator<Posting> positions1, positions2; Posting positionPointer1, positionPointer2; while (iterator1.hasNext() && iterator2.hasNext()){ if (p1.getDocId() == p2.getDocId()){ positions1 = p1.getPositions().iterator(); positions2 = p2.getPositions().iterator(); positionPointer1 = positions1.next(); positionPointer2 = positions2.next(); while (positions1.hasNext() && positions2.hasNext()){ if (positionPointer1.getId() + 1 == positionPointer2.getId()){ result.add(p1.getDocId(), positionPointer2.getId()); positionPointer1 = positions1.next(); positionPointer2 = positions2.next(); } else { if (positionPointer1.getId() + 1 < positionPointer2.getId()){ positionPointer1 = positions1.next(); } else { positionPointer2 = positions2.next(); } } } p1 = iterator1.next(); p2 = iterator2.next(); } else { if (p1.getDocId() < p2.getDocId()){ p1 = iterator1.next(); } else { p2 = iterator2.next(); } } } return result; } }
package io.github.s8a.osubfinder; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.io.File; import java.io.InputStream; import java.net.URL; /** * Unit test for the OpenSubtitles.org hash function. * * @author Samuel Ochoa (S8A) */ public class OpenSubtitlesHasherTest extends TestCase { String hash = "8e245d9679d31e12"; /** * Create the test case * * @param testName Name of the test case */ public OpenSubtitlesHasherTest(String testName) { super(testName); } /** * @return The suite of tests being tested. */ public static Test suite() { return new TestSuite(OpenSubtitlesHasherTest.class); } /** * Tests the OpenSubtitles hash function for input streams. */ public void testStreamHasher() { String vid = "http://www.opensubtitles.org/addons/avi/breakdance.avi"; long length = 12909756L; URL url = new URL(vid); InputStream input = url.openStream(); String hasherResult = OpenSubtitlesHasher.computeHash(input, length); assertEquals(hasherResult, hash); } /** * Testes the OpenSubtitles hash function for files. */ public void testFileHasher() { URL url = getClass().getClassLoader().getResource("breakdance.avi"); File video = new File(url.toURI()); String hasherResult = OpenSubtitlesHasher.computeHash(video); assertEquals(hasherResult, hash); } }
package com.fbzj.track.model; /** * ่ดฆๅท */ public class Account { /** * id */ private String id; /** * ็™ปๅฝ•ๅ */ private String name; private String password; /** * ๆž„้€ ๅ‡ฝๆ•ฐ * @param name ่ดฆๅทๅ * @param password ๅฏ†็  */ public Account(String name, String password) { this.name = name; this.password = password; } /** * ๆ˜พ็คบๅ */ private String showName; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getShowName() { return showName; } public void setShowName(String showName) { this.showName = showName; } }
package code; import java.util.ArrayList; import java.util.List; //handles ace's high game public class Ace extends Solitaire { public List<Card> home=new ArrayList<Card>(); //holds the homecell pile public Ace(){ super(); tableau=new Card[4][13]; tableauTopIndex = new int [4]; //s for (int i=0; i<4;i++){ tableau[i][0]=gameDeck.getDeckList().remove(gameDeck.getDeckList().size()-1); //s tableauTopIndex[i]=0; } } //checks if adding from stock or tableau is legal public boolean add(int pileType, int inputPile, int outputPile){ if(pileType==0){ //tests adding from stock to tableau if(gameDeck.getDeckList().size()>=4){ return true; } } else { //check tableau to tableau if(checkTableauToTableau(inputPile,outputPile)){ return true; } } return false; } //checks if removing from tableau to tableau or tableau to homecell is legal public boolean remove(int pileType, int inputPile, int outputPile){ if(pileType==0){ //check tableau to homecell if(checkTableauToHomecell(inputPile)){ return true; } } else { //check tableau to tableau if(checkTableauToTableau(inputPile,outputPile)){ return true; } } return false; } //deals out the top 4 cards of the stock pile public void dealDeck(){ if (add(0,0,0)){ //s for (int i=0; i<4;i++){ if(tableau[i][tableauTopIndex[i]]!=null){ tableauTopIndex[i]=tableauTopIndex[i]+1; } tableau[i][tableauTopIndex[i]]=gameDeck.getDeckList().remove(gameDeck.getDeckList().size()-1); } } } //moves a card from a tableau pile to a tableau pile public void tableauToTableau(int inputPile,int outputPile){ if(add(1,inputPile,outputPile)&&remove(1,inputPile,outputPile)){ System.out.println("here"); tableau[outputPile][tableauTopIndex[outputPile]]=tableau[inputPile][tableauTopIndex[inputPile]]; tableau[inputPile][tableauTopIndex[inputPile]]=null; if(tableauTopIndex[inputPile]!=0){ tableauTopIndex[inputPile]--; } } } //returns if it is legal to move from tableau to homecell public boolean anywhereToHomecell(){ return true; } //returns if it is legal to move from homecell to anywhere public boolean homecellToNowhere(){ return false; } //returns if it is legal to move a card to stock public boolean anywhereToStock(){ return false; } //checks if a card can be moved from tableau to tableau public boolean checkTableauToTableau(int inputPile, int outputPile){ if(tableau[inputPile][tableauTopIndex[inputPile]]!=null&& tableau[outputPile][tableauTopIndex[outputPile]]==null){ return true; } return false; } //moves from tableau to homecell public void tabToHomecell(int inputPile){ if(add(0,inputPile,0)&&remove(0,inputPile,0)){ home.add(tableau[inputPile][tableauTopIndex[inputPile]]); tableau[inputPile][tableauTopIndex[inputPile]]=null; //System.out.println("here11"); if(tableauTopIndex[inputPile]!=0){ //System.out.println("here"); tableauTopIndex[inputPile]--; } } } //checks if a card can be moved from tableau to homecell public boolean checkTableauToHomecell(int inputPile) { if(tableau[inputPile][tableauTopIndex[inputPile]]!=null){ for(int i=0;i<4;i++){ //System.out.println("tableau top index "+ tableauTopIndex[i]); if(tableau[i][tableauTopIndex[i]]!=null){ if(tableau[i][tableauTopIndex[i]].getSuit()==tableau[inputPile][tableauTopIndex[inputPile]].getSuit()&& (tableau[i][tableauTopIndex[i]].getRank()==1 ||tableau[i][tableauTopIndex[i]].getRank()>tableau[inputPile][tableauTopIndex[inputPile]].getRank())) { if(tableau[inputPile][tableauTopIndex[inputPile]].getRank()==1){ return false; } return true; } } } } else { //System.out.println("it is null"); } return false; } }
package com.cn.ouyjs.calssLoad; /** * @author ouyjs * @date 2019/8/21 17:18 * ็ฑปๅŠ ่ฝฝ: ๅŠ ่ฝฝ->้ชŒ่ฏ->ๅ‡†ๅค‡->่งฃๆž->ๅˆๅง‹ๅŒ– * ๅˆๅง‹ๅŒ–้˜ถๆฎตไธญๅ››็ง็‰นๆฎŠ็š„ๅˆๅง‹ๅŒ– * 1.finalไฟฎ้ฅฐ็š„็ฑปไธไผšๅ‘็”Ÿๅˆๅง‹ๅŒ–,ๅœจ็ผ–่ฏ‘็š„ๆœŸ้—ดๅŠ ๅ…ฅๅˆฐไบ†ๅธธ้‡ๆฑ  * 2.ๅๅฐ„, ้€š่ฟ‡ๅๅฐ„ๆ‰พๅˆฐ็š„็ฑป,ๅฆ‚ๆžœๆฒกๆœ‰ๅŠ ่ฝฝ็š„่ฏ,้œ€่ฆๅ…ˆ็ฑปๅŠ ่ฝฝ * 3.็ปงๆ‰ฟ,ๅˆๅง‹ๅŒ–ไธ€ไธช็ฑป็š„ๆ—ถๅ€™,ๅฆ‚ๆžœ่ฟ™ไธช็ฑปๆœ‰็ˆถ็ฑป,ๅ…ˆๅˆๅง‹ๅŒ–็ˆถ็ฑป * 4.ๆ–นๆณ•ไพ่ต–ๅ…ถไป–็ฑป,ๅ…ˆๅˆๅง‹ๅŒ–ๆ–นๆณ•็ฑป,ๅœจๅˆๅง‹ๅŒ–"ๅ…ถไป–็ฑป" * 5.ๅŠจๆ€่ฏญ่จ€ๆ”ฏๆŒ */ public class ClassLoaderTest { public ClassLoaderTest() { System.out.println("ClassLoadTest"); } public static void classLoadTest(){ System.out.println("classLoadTest"); } }
class Static { int emp_id; // class memory loads only one time int emp_sal; static String ceo; // static variable is same for all objects static { ceo = "Sasidhar"; System.out.println("satic block loads only once because class memory loads only once"); } public Static() { emp_id = 0; emp_sal = 0; System.out.println("constructor is called whenever the object is called"); } public void show() { System.out.println(emp_id + ":" + emp_sal + ":" + ceo); } } public class StaticKey { public static void main(String[] args) { Static emp = new Static(); Static emp2 = new Static(); emp.emp_id = 55; emp.emp_sal = 60000; emp2.emp_id = 700000; emp.show() ; emp2.show(); } }
package DecoratorPattern10.exercise.component; /** * @Author Zeng Zhuo * @Date 2020/4/30 16:24 * @Describe */ public interface Component { String encryption(String password); }
package com.base.utils; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.telephony.TelephonyManager; import com.base.host.HostApplication; public class NetUtil { private static final String TAG = "NetUtil"; public static String WIFI = "wifi"; public static String G2 = "2g"; public static String G3 = "3g"; public static String G4 = "4g"; public static String UNKNOWN = "unknown"; public static String getWebType(Context context) { try { if (context == null) { context = HostApplication.getInstance(); } TelephonyManager telManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String name = telManager.getSimOperatorName(); String operator = telManager.getSimOperator(); if (operator != null) { if (operator.equals("46000") || operator.equals("46002") || operator.equals("46007")) { name = "ไธญๅ›ฝ็งปๅŠจ"; // ไธญๅ›ฝ็งปๅŠจ } else if (operator.equals("46001")) { name = "ไธญๅ›ฝ่”้€š"; // ไธญๅ›ฝ่”้€š } else if (operator.equals("46003")) { name = "ไธญๅ›ฝ็”ตไฟก"; // ไธญๅ›ฝ็”ตไฟก } } return name; } catch (Exception e) { e.printStackTrace(); } return UNKNOWN; } // ็ฝ‘็ปœไฝฟ็”จ่ฏข้—ฎ public static int isWeb(Context context) { int WIFI = 1, CMWAP = 2, CMNET = 3; try { NetworkInfo netInfo = NetUtil.hasNetwork(context); if (netInfo != null) { int nType = netInfo.getType(); if (nType == ConnectivityManager.TYPE_MOBILE) { if (netInfo.getExtraInfo() != null && netInfo.getExtraInfo().toLowerCase().equals("cmnet")) { nType = CMNET; } else { nType = CMWAP; } } else if (nType == ConnectivityManager.TYPE_WIFI) { nType = WIFI; } return nType; } } catch (Exception e) { } return -1; } private static String intToIp(int paramInt) { return (paramInt & 0xFF) + "." + (0xFF & paramInt >> 8) + "." + (0xFF & paramInt >> 16) + "." + (0xFF & paramInt >> 24); } public static String getSsidOrId(Context context, int tag) { if (context == null) { context = HostApplication.getInstance(); } if (isWeb(context) == 1) { try { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); // DhcpInfo dhcpInfo = wifiManager.getDhcpInfo(); // System.out.println(intToIp(dhcpInfo.dns1) + " dns==" + dhcpInfo.dns2); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (wifiInfo == null) return ""; if (tag == 0) { return wifiInfo.getSSID().replaceAll("\"", ""); } else { return wifiInfo.getIpAddress() + ""; } } catch (Exception e) { } } else if (tag == 0) { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress(); } } } } catch (SocketException ex) { } } return ""; } /** * ่Žทๅ–็ฝ‘็ปœ็ฑปๅž‹ * * @param context * @return */ public static String netType(Context context) { try { if (context == null) { context = HostApplication.getInstance(); } ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = manager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { String type = networkInfo.getTypeName(); if (type == null) { return UNKNOWN; } // LogUtils.d(TAG,"type:"+type); if (type.equalsIgnoreCase("WIFI")) { return WIFI; } else if (type.equalsIgnoreCase("MOBILE")) { return getSpecificMobileType(context); } else { return UNKNOWN; } } else { return UNKNOWN; } } catch (Exception e) { e.printStackTrace(); } return UNKNOWN; } /** * ๅˆคๆ–ญ็ฝ‘็ปœๆ˜ฏๅฆไธบๆผซๆธธ */ public static boolean isNetworkRoaming(Context context) { ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo info = connectivity.getActiveNetworkInfo(); if (info != null && info.getType() == ConnectivityManager.TYPE_MOBILE) { TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (tm != null && tm.isNetworkRoaming()) { return true; } } } return false; } /** * @param context * @return */ public static NetworkInfo hasNetwork(Context context) { if (context == null) { return null; } ConnectivityManager con = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (con == null) { return null; } NetworkInfo workinfo = con.getActiveNetworkInfo(); if (workinfo == null || !workinfo.isAvailable()) { return null; } return workinfo; } /** * ่Žทๅพ—็ฝ‘็ปœ่ฟžๆŽฅๆ˜ฏๅฆๅฏ็”จ * * @param context * @return */ public static boolean isHasNetwork(Context context) { ConnectivityManager con = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo workinfo = con.getActiveNetworkInfo(); if (workinfo == null || !workinfo.isAvailable()) { return false; } return true; } /** * ๆ นๆฎ็ฝ‘้€Ÿ่Žทๅ–ๅ…ทไฝ“็š„็งปๅŠจ็ฝ‘็ปœ็ฑปๅž‹ * * @param context * @return */ public static String getSpecificMobileType(Context context) { TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); switch (telephonyManager.getNetworkType()) { case TelephonyManager.NETWORK_TYPE_1xRTT : return G2; // ~ 50-100 kbps case TelephonyManager.NETWORK_TYPE_CDMA : return G2; // ~ 14-64 kbps case TelephonyManager.NETWORK_TYPE_EDGE : return G2; // ~ 50-100 kbps case TelephonyManager.NETWORK_TYPE_EVDO_0 : return G3; // ~ 400-1000 kbps case TelephonyManager.NETWORK_TYPE_EVDO_A : return G3; // ~ 600-1400 kbps case TelephonyManager.NETWORK_TYPE_GPRS : return G2; // ~ 100 kbps case TelephonyManager.NETWORK_TYPE_HSDPA : return G3; // ~ 2-14 Mbps case TelephonyManager.NETWORK_TYPE_HSPA : return G3; // ~ 700-1700 kbps case TelephonyManager.NETWORK_TYPE_HSUPA : return G3; // ~ 1-23 Mbps case TelephonyManager.NETWORK_TYPE_UMTS : return G3; // ~ 400-7000 kbps case TelephonyManager.NETWORK_TYPE_EHRPD : return G3; // ~ 1-2 Mbps case TelephonyManager.NETWORK_TYPE_EVDO_B : return G3; // ~ 5 Mbps case TelephonyManager.NETWORK_TYPE_HSPAP : return G3; // ~ 10-20 Mbps case TelephonyManager.NETWORK_TYPE_IDEN : return G2; // ~25 kbps case TelephonyManager.NETWORK_TYPE_LTE : return G4; // ~ 10+ Mbps case TelephonyManager.NETWORK_TYPE_UNKNOWN : return UNKNOWN; default: return UNKNOWN; } } }
package be.odisee.se4.hetnest.controllers; import be.odisee.se4.hetnest.domain.User; import be.odisee.se4.hetnest.service.HetNestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import java.util.Arrays; import java.util.List; @Controller @RequestMapping("/") public class HomeController { @Autowired private HetNestService hetNestService = null; /*@GetMapping() public String home() { return "home"; }*/ @GetMapping("/login-error") public String loginerror(Model model) { model.addAttribute("error", true); return "login"; } @RequestMapping("/") public String home(ModelMap model){ List<User> hetLijst = Arrays.asList( new User(1, "tibovds1", "test", "Tibo", "Van De Sijpe", "Administrator"), new User(2, "tibovds2", "test", "Tibo", "Van De Sijpe", "Administrator"), new User(3, "tibovds3", "test", "Tibo", "Van De Sijpe", "Administrator") ); List<User> deLijst = hetNestService.geefAllePersonen(); model.addAttribute("users", deLijst); return "/home"; } }
/* Copyright 2017 Stratumn SAS. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.stratumn.sdk.model.trace; import com.stratumn.sdk.TraceLink; /*** * Class to hold the traceId or prevLink used to identify the previous link. * @param <TLinkData> */ public class ParentLink<TLinkData> { private String traceId; private TraceLink<TLinkData> prevLink; public ParentLink(String traceId ) { if (traceId == null ) { throw new IllegalArgumentException("TraceId and PrevLink cannot be both null"); } this.traceId = traceId; } public ParentLink( TraceLink<TLinkData> prevLink) { if ( prevLink == null) { throw new IllegalArgumentException("TraceId and PrevLink cannot be both null"); } this.prevLink = prevLink; } public String getTraceId() { return this.traceId; } public void setTraceId(String traceId) { this.traceId = traceId; } public TraceLink<TLinkData> getPrevLink() { return this.prevLink; } public void setPrevLink(TraceLink<TLinkData> prevLink) { this.prevLink = prevLink; } }
package com.fetchrewards.demo.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler; @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { /** * We can have multiple resource servers in place. This ties this resource server to this application */ private static final String RESOURCE_ID = "resource_id"; @Override public void configure(ResourceServerSecurityConfigurer resources) { resources.resourceId(RESOURCE_ID) .stateless(false); } @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/", "/h2-console/**", "/swagger-resources/**", "/swagger-resource/**", "/swagger-ui.html", "/v2/api-docs", "/webjars/**", "/createnewuser", "/users/user") .permitAll() .and() .exceptionHandling() .accessDeniedHandler(new OAuth2AccessDeniedHandler()); // http.requiresChannel().anyRequest().requiresSecure(); required for https http.csrf() .disable(); http.headers() .frameOptions() .disable(); } }
package oo.abs1; public class Report { public void test(){ } public void print(){ } }
package Main; import com.google.gson.Gson; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import java.sql.*; import java.util.*; import static net.sf.json.JSONObject.*; public class Json_test { public static String test() { List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(); ConnectMysql.connect(); try { Connection connect = DriverManager.getConnection( "jdbc:mysql://localhost:3306/db_user?serverTimezone=UTC","root","root"); //่ฟžๆŽฅURLไธบ jdbc:mysql//ๆœๅŠกๅ™จๅœฐๅ€/ๆ•ฐๆฎๅบ“ๅ ๏ผŒๅŽ้ข็š„2ไธชๅ‚ๆ•ฐๅˆ†ๅˆซๆ˜ฏ็™ป้™†็”จๆˆทๅๅ’Œๅฏ†็  System.out.println("Success connect Mysql server!"); Statement stmt = connect.createStatement(); ResultSet rs = stmt.executeQuery("select * from ac_pw "); ResultSetMetaData md = rs.getMetaData(); int columnCount = md.getColumnCount(); while (rs.next()){ Map<String,Object> rowData = new HashMap<String, Object>(); for(int i =1;i<=columnCount;i++){ rowData.put(md.getColumnName(i),rs.getObject(i)); } list.add(rowData); } Gson gson = new Gson(); String json = gson.toJson(list); System.out.println(json); return json; } catch (Exception e) { System.out.print("get data error!"); e.printStackTrace(); } return "hollow"; } // public static void main(String[] args) { // test(); // } }
package exam.iz0_803; public class Exam_030 { } /* Given: public class Bark { // code 1 public abstract void bark(); } // code 2 public void bark() { System.out.println("Woof"); } } } What code should be inserted? A. code 1: class Dog { code 2: public class Poodle extends Dog { B. code 1: abstract Dog { code 2: public class Poodle extends Dog { C. code 1: abstract class Dog { code 2: public class Poodle extends Dog { D. code 1: class Dog { code 2: public class Poodle implements Dog { E. code 1: abstract Dog { code 2: public class Poodle implements Dog { F. abstract class Dog { public class Poodle implements Dog { Answer: C */
package com.rubic.demo.work; import com.lmax.disruptor.*; import com.lmax.disruptor.dsl.ProducerType; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; /** * Demo * * @author rubic * @since 2018-07-17 */ public class Demo { public static void main(String[] args) { int bufferSize = 16; LongEventFactory longEventFactory = new LongEventFactory(); ExecutorService executor = Executors.newCachedThreadPool(); RingBuffer ringBuffer = RingBuffer.create(ProducerType.SINGLE, longEventFactory, bufferSize, new SleepingWaitStrategy()); Producer producer = new Producer(ringBuffer); for (int i = 0; i < bufferSize; i++) { producer.onEvent(new Long(i)); } SequenceBarrier sequenceBarrier = ringBuffer.newBarrier(); Sequence consumerSequence = new Sequence(-1); LongEventHandler eventHandler = new LongEventHandler(new AtomicInteger()); IntEventExceptionHandler intEventExceptionHandler = new IntEventExceptionHandler(); MyWorkProcessor<LongEvent> wp1 = new MyWorkProcessor<LongEvent>(ringBuffer, sequenceBarrier, eventHandler, intEventExceptionHandler, consumerSequence); //ๆ‰ง่กŒๅค„็†็บฟ็จ‹ executor.execute(wp1); WorkProcessor<LongEvent> wp2 = new WorkProcessor<LongEvent>(ringBuffer, sequenceBarrier, eventHandler, intEventExceptionHandler, consumerSequence); executor.execute(wp2); WorkProcessor<LongEvent> wp3 = new WorkProcessor<LongEvent>(ringBuffer, sequenceBarrier, eventHandler, intEventExceptionHandler, consumerSequence); executor.execute(wp3); WorkProcessor<LongEvent> wp4 = new WorkProcessor<LongEvent>(ringBuffer, sequenceBarrier, eventHandler, intEventExceptionHandler, consumerSequence); executor.execute(wp4); wp1.halt(); wp2.halt(); wp3.halt(); wp4.halt(); System.out.println("wp1. " + wp1.isRunning()); executor.shutdown(); } }
package lawscraper.client.ui.panels.rolebasedwidgets; import lawscraper.shared.UserRole; /** * Created by erik, IT Bolaget Per & Per AB * Date: 5/16/12 * Time: 9:25 PM */ public interface RoleBasedWidget { void configureAsNoneVisisble(UserRole userRole); void configureAsEditable(UserRole userRole); void configureAsViewable(UserRole userRole); void setViewRequiresUserRole(String viewRequiresRole); void setEditRequiresUserRole(String editRequiresRole); UserRole getEditRequiresRole(); UserRole getViewRequiresRole(); void setRequiresUserRole(String requiresUserRole); }
package com.example.sarbagitadriver; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import java.util.Locale; import java.util.Map; public class MainActivity extends AppCompatActivity { public String userName; public String getUserName(){ return userName; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = getIntent(); userName = intent.getStringExtra("username"); } }
package com.Price.quotation.Controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; 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.SessionAttributes; import com.Price.quotation.Model.Vendor; import com.Price.quotation.Service.VendorService; @Controller @SessionAttributes({"name"}) public class VendorController { @Autowired private VendorService vendorService; @RequestMapping(value = "/vendor", method = RequestMethod.GET) public String VendorFront(@ModelAttribute("vendor") Vendor vendorView) { return "vendor"; } @RequestMapping(value="/vendorRegister",method = RequestMethod.POST) public String vendorRegistration(@ModelAttribute("vendor")Vendor vendorReg,ModelMap model){ if(vendorService.addVendor(vendorReg)) { model.put("vStatus", "Your details are submitted successfully"); } else { model.put("vStatus", "Vendor Id is already used"); } return "vendor"; } @RequestMapping(value="/vendorLogin", method=RequestMethod.GET) public String vendorLoginDisplay(@ModelAttribute("vendor") Vendor vendor) { return "vendorLogIn"; } @RequestMapping(value="/vendorSuccessLogin", method=RequestMethod.POST) public String vendorLogin(@ModelAttribute("vendor") Vendor vendor,BindingResult result,ModelMap model) { if(result.hasErrors()) { return "vendorLogIn"; } List<Vendor>vendorList = vendorService.read(); for(Vendor vendor1 : vendorList) { if(vendor1.getVendorId().equals(vendor.getVendorId()) && vendor1.getPassword().equals(vendor.getPassword())) { model.put("name", vendor.getVendorId()); return "vendorSuccessLogin"; } } model.put("error", "Wrong Credentials"); return "vendorLogIn"; } @RequestMapping(value = "/vendorLogOut", method = RequestMethod.GET) public String vendorLogout(@ModelAttribute("vendor") Vendor vendor) { return "vendorLogIn"; } @RequestMapping("/vendorList") public String vendorList(ModelMap m){ List<Vendor> list=vendorService.read(); m.addAttribute("list",list); return "vendorList"; } @RequestMapping(value="/deleteVendor/{vId}",method = RequestMethod.GET) public String delete(@PathVariable int vId){ vendorService.delete(vId); return "redirect:/vendorList"; } }
package utils; import java.awt.Component; import java.awt.event.ItemEvent; import java.util.Collection; import javax.swing.AbstractCellEditor; import javax.swing.JComboBox; import javax.swing.JTable; import javax.swing.table.TableCellEditor; public class EnumEditor extends AbstractCellEditor implements TableCellEditor { private static final long serialVersionUID = 1L; private Editor editor; public EnumEditor (final Object[] values) { editor = new Editor (values); } public EnumEditor (final Collection<? extends Object> values) { editor = new Editor (values.toArray()); } // This method is called when a cell value is edited by the user. public Component getTableCellEditorComponent (final JTable table, final Object value, final boolean isSelected, final int row, final int vCol) { editor.setSelectedItem (value); return editor; } // This method is called when editing is completed. // It must return the new value to be stored in the cell. public Object getCellEditorValue() { return editor.getSelectedItem(); } private class Editor extends JComboBox { private static final long serialVersionUID = 1L; Editor (final Object[] values) { super (values); } @Override protected void fireItemStateChanged (final ItemEvent e) { super.fireItemStateChanged (e); fireEditingStopped(); } } }
package maxDepth104; import java.util.LinkedList; import java.util.Queue; import dataStructure.*; /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { /** * ้€’ๅฝ’ๅฎž็Žฐ * @param root * @return */ public int maxDepth(TreeNode root) { if(root == null) return 0; int maxleft = maxDepth(root.left) + 1; int maxright = maxDepth(root.right) + 1; return (maxleft > maxright ? maxleft : maxright); } /** * BFS * @param root * @return */ public int maxDepth2(TreeNode root) { Queue<TreeNode> queue = new LinkedList<>(); int deepth = 0; int i = 0; int size = 0; TreeNode node = null; if(root != null) queue.add(root); while (!queue.isEmpty()){ size = queue.size(); ++deepth; //ๆ‰ฉๅฑ•ๅฝ“ๅ‰ๅฑ‚ๆฌกๆ‰€ๆœ‰่Š‚็‚น for (i = 0; i < size; ++i){ node = queue.remove(); if(node.left != null) queue.add(node.left); if(node.right != null) queue.add(node.right); } } return deepth; } }
package net.mapthinks.domain; import net.mapthinks.domain.base.AbstractBaseEntity; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.springframework.data.elasticsearch.annotations.Document; import javax.persistence.*; import javax.validation.constraints.*; import java.io.Serializable; import java.util.Objects; /** * A Company. */ @Entity @Table(name = "company") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @Document(indexName = "company") public class Company extends AbstractBaseEntity { private static final long serialVersionUID = 1L; @NotNull @Column(name = "name", nullable = false) private String name; @NotNull @Column(name = "short_name", nullable = false) private String shortName; @Column(name = "vkn") private String vkn; @Column(name = "phone") private String phone; @Column(name = "phone_second") private String phoneSecond; @Column(name = "email") private String email; @Column(name = "email_second") private String emailSecond; @Column(name = "address") private String address; @Column(name = "address_second") private String addressSecond; @Column(name = "web_site") private String webSite; @ManyToOne private Company parent; @ManyToOne private Town town; // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove public String getName() { return name; } public Company name(String name) { this.name = name; return this; } public void setName(String name) { this.name = name; } public String getShortName() { return shortName; } public Company shortName(String shortName) { this.shortName = shortName; return this; } public void setShortName(String shortName) { this.shortName = shortName; } public String getVkn() { return vkn; } public Company vkn(String vkn) { this.vkn = vkn; return this; } public void setVkn(String vkn) { this.vkn = vkn; } public String getPhone() { return phone; } public Company phone(String phone) { this.phone = phone; return this; } public void setPhone(String phone) { this.phone = phone; } public String getPhoneSecond() { return phoneSecond; } public Company phoneSecond(String phoneSecond) { this.phoneSecond = phoneSecond; return this; } public void setPhoneSecond(String phoneSecond) { this.phoneSecond = phoneSecond; } public String getEmail() { return email; } public Company email(String email) { this.email = email; return this; } public void setEmail(String email) { this.email = email; } public String getEmailSecond() { return emailSecond; } public Company emailSecond(String emailSecond) { this.emailSecond = emailSecond; return this; } public void setEmailSecond(String emailSecond) { this.emailSecond = emailSecond; } public String getAddress() { return address; } public Company address(String address) { this.address = address; return this; } public void setAddress(String address) { this.address = address; } public String getAddressSecond() { return addressSecond; } public Company addressSecond(String addressSecond) { this.addressSecond = addressSecond; return this; } public void setAddressSecond(String addressSecond) { this.addressSecond = addressSecond; } public String getWebSite() { return webSite; } public Company webSite(String webSite) { this.webSite = webSite; return this; } public void setWebSite(String webSite) { this.webSite = webSite; } public Company getParent() { return parent; } public Company parent(Company company) { this.parent = company; return this; } public void setParent(Company company) { this.parent = company; } public Town getTown() { return town; } public Company town(Town town) { this.town = town; return this; } public void setTown(Town town) { this.town = town; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override public boolean equals(Object o) { if (this == o) { return true; } return super.equals(o); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "Company{" + "id=" + getId() + ", name='" + getName() + "'" + ", shortName='" + getShortName() + "'" + ", vkn='" + getVkn() + "'" + ", phone='" + getPhone() + "'" + ", phoneSecond='" + getPhoneSecond() + "'" + ", email='" + getEmail() + "'" + ", emailSecond='" + getEmailSecond() + "'" + ", address='" + getAddress() + "'" + ", addressSecond='" + getAddressSecond() + "'" + ", webSite='" + getWebSite() + "'" + "}"; } }
package it.greenvulcano.gvesb.adapter.hdfs.operations; import java.io.IOException; import org.slf4j.Logger; import org.w3c.dom.Node; import it.greenvulcano.configuration.XMLConfig; import it.greenvulcano.configuration.XMLConfigException; import it.greenvulcano.gvesb.adapter.hdfs.HdfsAPI; import it.greenvulcano.gvesb.adapter.hdfs.HdfsCallOperation; import it.greenvulcano.gvesb.buffer.GVBuffer; import it.greenvulcano.gvesb.virtual.VCLException; import it.greenvulcano.util.metadata.PropertiesHandler; import it.greenvulcano.util.metadata.PropertiesHandlerException; public class BaseOperation { protected static final Logger logger = org.slf4j.LoggerFactory.getLogger(HdfsCallOperation.class); protected HdfsAPI hdfs = null; private String workDir = null; public void setClient(HdfsAPI hdfs) { this.hdfs = hdfs; } public void init(Node node) throws XMLConfigException { String endpoint = XMLConfig.get(node, "@endpoint"); if (endpoint != null && endpoint != "") { try { hdfs = new HdfsAPI(endpoint); } catch (IOException e) { throw new XMLConfigException(e.getMessage(), e); } } workDir = XMLConfig.get(node, "@working-directory"); } public GVBuffer perform(GVBuffer gvBuffer) throws PropertiesHandlerException, VCLException { if (workDir != null && workDir != "") { hdfs.setWD(PropertiesHandler.expand(workDir, gvBuffer)); } return gvBuffer; } public void cleanUp() throws IOException { hdfs.close(); } }
package test; import java.util.Iterator; import java.util.LinkedList; import org.junit.Test; import FourRowSolitaire.Card; import FourRowSolitaire.Deck; public class DeckTest { @Test public void testGetDeck() { Deck deck = new Deck(1); LinkedList<Integer> numbers = new LinkedList<Integer>(); LinkedList<Card> cardsOne; LinkedList<Card> cardsTwo; for (int i=0; i<53; i++) { numbers.add(i); } cardsOne = deck.getDeck(); cardsTwo = deck.getDeck(numbers); Iterator<Card> iterOne = cardsOne.iterator(); Iterator<Card> iterTwo = cardsTwo.iterator(); for (int i=0; i<52; i++) { iterOne.next().equals(iterTwo.next()); } } }
package com.mmrath.sapp.web.rest.rsql; import cz.jirutka.rsql.parser.RSQLParser; import cz.jirutka.rsql.parser.ast.Node; import org.springframework.data.jpa.domain.Specification; import org.springframework.util.StringUtils; import java.util.Optional; /** * Created by murali on 25/06/15. */ public class RsqlUtils { public static <T> Optional<Specification<T>> parse(String search, RsqlVisitor<T> visitor) { Specification<T> spec = null; if (StringUtils.hasText(search)) { Node rootNode = new RSQLParser().parse(search); spec = rootNode.accept(new RsqlVisitor<>()); } return Optional.ofNullable(spec); } public static <T> Optional<Specification<T>> parse(String search) { return parse(search, new RsqlVisitor<>()); } }
package String็ฑป; import org.testng.annotations.Test; import java.util.Arrays; /** * ๅญ—็ฌฆไธฒๅœจๅฆๅค–ไธ€ไธชๅญ—็ฌฆไธฒไธญๅ‡บ็Žฐๆฌกๆ•ฐใ€‚ๆฏ”ๅฆ‚โ€œabโ€ๅœจโ€œabkkcadkabkebfkabkskabโ€ๅ‡บ็Žฐๆฌกๆ•ฐ */ public class ้ข่ฏ•้ข˜3 { public static void main(String[] args) { System.out.println(stringCounts("abkkcadkabkebfkabkskab", "ab")); } public static int stringCounts(String longStr,String shortStr){ int count = 0; for (int i = 0;i<longStr.length()-1;i++){ if (shortStr.equals(longStr.substring(i,i+2))){ count ++; } } return count; } @Test //่ถ…็บงๆผ‚ไบฎ็š„ๆ€่ทฏ๏ผ๏ผ๏ผ public void stringCounts2() { // ๆฑ‚โ€œabโ€ๅœจโ€œabkkcadkabkebfkabkskabโ€ๅ‡บ็Žฐๆฌกๆ•ฐ String str1 = "ab", str2 = "abkkcadkabkebfkabkskab"; String[] split = str2.split("ab"); System.out.println(Arrays.toString(split)); System.out.println(split.length); } // ๆ–นๆณ•2๏ผš็”จindexOf() public int getCount(String mainStr, String subStr) { int mainLength = mainStr.length(); int subLength = subStr.length(); if (mainLength >= subLength) { int count = 0; int index; while ((index = mainStr.indexOf(subStr)) != -1) { count++; mainStr = mainStr.substring(index + subLength); } return count; } else return 0; } }
package swissre.parser; import swissre.persistence.DataStore; import swissre.model.ExchangeRateChange; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.SignStyle; import java.util.NoSuchElementException; import java.util.Scanner; import java.util.concurrent.atomic.AtomicInteger; import static java.text.MessageFormat.format; import static java.time.temporal.ChronoField.*; import static swissre.parser.LineMarker.*; /** * Implementation of the {@link Parser} for the type {@link String} * * Please note that this class is not thread safe. * * As this is a string processor we can assume the entire file fits in memory. * * @author Duncan Atkinson */ public class StringParser implements Parser<String> { private final DataStore dataStore; private Scanner scanner; private AtomicInteger lineCounter; private final DateTimeFormatter exchangeRateDateTimeFormat; private String currentLine = ""; public StringParser(DataStore dataStore) { this.dataStore = dataStore; exchangeRateDateTimeFormat = new DateTimeFormatterBuilder() .appendValue(HOUR_OF_DAY) .appendLiteral(':') .appendValue(MINUTE_OF_HOUR) .appendLiteral(':') .appendValue(SECOND_OF_MINUTE) .appendLiteral(' ') .appendValue(MONTH_OF_YEAR) .appendLiteral('/') .appendValue(DAY_OF_MONTH, 2) .appendLiteral('/') .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD) .toFormatter(); } private void prepareToProcessFile() { scanner.useDelimiter("\\n"); // default is newlines AND whitespace lineCounter = new AtomicInteger(0); } private void initializeNewScanner(String file) { scanner = new Scanner(file); prepareToProcessFile(); } /** * @param file is a state of the art exchange rate file. * @throws InvalidExchangeRateFileException if there was an error detected during parsing for example non well formed. */ @Override public void receiveFile(String file) throws InvalidExchangeRateFileException { initializeNewScanner(file); processFile(); } /** * Added to this class to allow it to be used directly from the command line * instead of via {@link #receiveFile(String)} * * @param scanner which is expected to receive an exchange rate changes file. */ public void receive(Scanner scanner){ this.scanner = scanner; prepareToProcessFile(); processFile(); } /** * {@link #prepareToProcessFile()} should be called before this method. */ private void processFile() { ensureNextLineMatches(START_OF_FILE); while (!currentLineMatches(START_OF_EXCHANGE_RATES)) { scanNextLine(); } scanNextLine(); while (!currentLineMatches(END_OF_EXCHANGE_RATES)) { ExchangeRateChange exchangeRateChange = getExchangeRateChangeFromCurrentLine(); dataStore.record(exchangeRateChange); scanNextLine(); } ensureNextLineMatches(END_OF_FILE); } private ExchangeRateChange getExchangeRateChangeFromCurrentLine() { String[] parts = currentLine.split("\\|"); if (parts.length != 3) { String message = "Unexpected exchange rate format found unable to parse '" + currentLine + "' on line " + lineCounter.get(); throw new InvalidExchangeRateFileException(message); } String currency = parts[0]; Double exchangeRateVsDollar = Double.parseDouble(parts[1]); LocalDateTime timestamp = LocalDateTime.parse(parts[2], exchangeRateDateTimeFormat); return new ExchangeRateChange(currency, timestamp, exchangeRateVsDollar); } private boolean currentLineMatches(LineMarker lineMarker) { return lineMarker.asString().equals(currentLine); } private void scanNextLine() { try { do { currentLine = scanner.next(); lineCounter.incrementAndGet(); } while (currentLine.equals("")); } catch (NoSuchElementException noSuchElementException) { throw new InvalidExchangeRateFileException("Unexpected end of file"); } currentLine = currentLine.replaceAll("\r", ""); } private void ensureNextLineMatches(LineMarker lineMarker) throws InvalidExchangeRateFileException { scanNextLine(); if (!lineMarker.asString().equals(currentLine)) { String message = format("Expected ''{0}'' on line {1}, found ''{2}''", lineMarker, lineCounter.get(), currentLine); throw new InvalidExchangeRateFileException(message); } } }
package com.monkey1024.controller; import com.monkey1024.bean.User; import com.monkey1024.util.DataUtil; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import java.util.HashMap; /* * ๅฎž็Žฐ็ฎ€ๅ•็š„็ญ‰ๅˆ ๆ”นๆŸฅ * */ @Controller public class UserController { @RequestMapping("/findAll.do") public ModelAndView findAll()throws Exception{ HashMap<String, User> allUser = DataUtil.findAll(); ModelAndView mv = new ModelAndView(); mv.addObject("allUser",allUser); mv.setViewName("user_list"); return mv; } @RequestMapping("/create.do") public String create(User user)throws Exception{ DataUtil.create(user); return "redirect:findAll.do"; } @RequestMapping("/findById.do") public ModelAndView findById(String id) throws Exception{ ModelAndView mv = new ModelAndView(); User user = DataUtil.findUserById(id); HashMap<String,User> allUser = new HashMap<>(); allUser.put(id,user); mv.addObject("id",id); mv.addObject("allUser",user); mv.setViewName("user_list"); return mv; } }
package Modelo; public class mov_Caixa { private int cod; private int cod_caixa; private int cod_ace; private double valor; private char tipo; public mov_Caixa() { } public mov_Caixa(int cod, int cod_caixa, int cod_ace, double valor, char tipo) { this.cod = cod; this.cod_caixa = cod_caixa; this.cod_ace = cod_ace; this.valor = valor; this.tipo = tipo; } public int getCod() { return cod; } public void setCod(int cod) { this.cod = cod; } public int getCod_caixa() { return cod_caixa; } public void setCod_caixa(int cod_caixa) { this.cod_caixa = cod_caixa; } public int getCod_ace() { return cod_ace; } public void setCod_ace(int cod_ace) { this.cod_ace = cod_ace; } public double getValor() { return valor; } public void setValor(double valor) { this.valor = valor; } public char getTipo() { return tipo; } public void setTipo(char tipo) { this.tipo = tipo; } }
package com.ht.event.model; import org.hibernate.search.annotations.*; import lombok.Getter; import lombok.Setter; import org.hibernate.search.annotations.Analyze; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.Index; import org.hibernate.search.annotations.Indexed; import org.hibernate.search.annotations.Store; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.*; import java.io.Serializable; import java.util.Date; import java.util.HashSet; import java.util.Set; //import org.hibernate.search.annotations.*; //import org.hibernate.search.annotations.Index; @Getter @Setter @Indexed @Entity @Table(name = "event") public class Event implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @Field(index= Index.YES, analyze= Analyze.YES, store= Store.NO) private String name; private String description; @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) private Date date; private String day; private String duration; // private Time time; private String address; private String city; private String country; private String pincode; private String imgURL; private float latitude; //google api geo location private float longitude; //google api geo location @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinTable(name = "event_category", joinColumns = {@JoinColumn(name = "event_id")}, inverseJoinColumns = {@JoinColumn(name = "category_id")}) private Set<Category> categories = new HashSet<Category>(0); private float fees; }
package barqsoft.footballscores; import android.content.Context; import android.content.res.Resources; import android.support.v4.view.PagerTabStrip; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.View; import android.view.accessibility.AccessibilityEvent; /** * Created by htan on 27/08/2015. */ public class A11yPagerTabStrip extends PagerTabStrip { private static String LOG_TAG = "A11yPagerTabStrip"; private Context mContext; public A11yPagerTabStrip(Context context) { super(context); mContext = context; } public A11yPagerTabStrip(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; } @Override public boolean onRequestSendAccessibilityEvent(View child, AccessibilityEvent event) { final ViewPager viewPager = (ViewPager) this.getParent(); final int itemIndex = viewPager.getCurrentItem(); String title = viewPager.getAdapter().getPageTitle(itemIndex).toString(); Resources res = mContext.getResources(); child.setContentDescription(res.getString(R.string.tabstrip_content_description,title)); return super.onRequestSendAccessibilityEvent(child, event); } }
package fr.fireblaim.javafxhelper.utils; import javafx.event.EventHandler; import javafx.scene.input.MouseEvent; import javafx.stage.Stage; import java.awt.*; public class WindowMover { //Code by Trxyy thx ! Point dragPoint = new Point(); public WindowMover(Stage stage) { stage.getScene().setOnMousePressed(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { dragPoint.x = (int) (stage.getX() - event.getScreenX()); dragPoint.y = (int) (stage.getY() - event.getScreenY()); } }); stage.getScene().setOnMouseDragged(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { stage.setX(event.getScreenX() + dragPoint.x); stage.setY(event.getScreenY() + dragPoint.y); } }); } }
import gov.nih.mipav.plugins.*; // needed to load PlugInAlgorithm / PlugInView / PlugInFile interface /** * This is simple plugin that sweeps the images with sets of 16 parallel lines to find all red, blue, green synapses. * * @see PlugInGeneric */ public class PlugInLargeSynapse implements PlugInGeneric { //~ Methods -------------------------------------------------------------------------------------------------------- public void run() { new PlugInDialogLargeSynapse(false); } }
package snabbkรถp.state; public class CustomerFactory { private int customerId = 0; CustomerFactory(){} public Customer makeNewCustomer(double arrivalTime) { Customer newCustomer = new Customer(customerId, arrivalTime); customerId++; return newCustomer; } public int getCustomerId(Customer c) { return c.getCustomerId(); } public double getCustomerTimeInStore(Customer c) { return c.getCustomerTimeInStore(); } private class Customer{ private int id; private double arrivalTime; private double timeSpentInStore = 0; Customer(int id, double arrivalTime){ this.id = id; this.arrivalTime = arrivalTime; } private int getCustomerId() { return id; } private double getCustomerTimeInStore() { return timeSpentInStore; } } }
package pl.pawel.weekop.controller; import pl.pawel.weekop.model.User; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/login") public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getUserPrincipal() != null) { System.out.println(request.getUserPrincipal().getName()); request.getSession().setAttribute("username",request.getUserPrincipal().getName()); if (request.getUserPrincipal().getName().equals("admin")) { response.sendRedirect(request.getContextPath()+ "/adminPage"); } else response.sendRedirect(request.getContextPath() + "/"); } else { response.sendError(403); } } }
package djudge.judge; public enum InteractionType { NONE, NEERC_INTERACTOR }
package com.project.entities; public enum UserType { ADMIN, CUSTOMER, COURIER }
package exception; public class MemberAlreadyOpinion extends Exception{ public MemberAlreadyOpinion(String message) { super(message); } }
package fr.pco.accenture.factories; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import edu.stanford.smi.protegex.owl.model.OWLIndividual; import edu.stanford.smi.protegex.owl.model.OWLModel; import edu.stanford.smi.protegex.owl.model.RDFProperty; import edu.stanford.smi.protegex.owl.model.impl.DefaultOWLIndividual; import fr.pco.accenture.models.Instance; import fr.pco.accenture.utils.Helper; public class InstancesFactory { private static Map<String, Map<String, Instance>> instances; public static void init() { instances = new HashMap<String, Map<String, Instance>>(); loadAll(); } public static void loadAll() { for(String name : ModelsFactory.getNames()){ load(name); } } public static boolean has(String modelName){ return instances.containsKey(modelName); } public static boolean has(String modelName, String instanceName){ return (instances.containsKey(modelName) && instances.get(modelName) != null && instances.get(modelName).containsKey(instanceName)); } public static void load(String modelName) { instances.put(modelName, new HashMap<String, Instance>()); for(String className : ClassesFactory.getNames(modelName)) for(String instanceName : ClassesFactory.get(modelName, className).getInstances()) load(modelName, className, instanceName, true); } @SuppressWarnings("unchecked") public static Instance load(String modelName, String className, String instanceName, boolean withObjectValues) { OWLModel model = ModelsFactory.get(modelName); if(model == null) return null; Helper helper = new Helper(model); Map<String, Object> values = new HashMap<String, Object>(); OWLIndividual individual = model.getOWLIndividual(instanceName); if(individual == null) return null; for(RDFProperty p : helper.getProperties(className)){ // if(withObjectValues && p.getRangeDatatype() == null){ // Collection val = new ArrayList<Object>(); // for(Object o : individual.getPropertyValues(p)){ // try { // DefaultOWLIndividual temp = (DefaultOWLIndividual) o; // val.add(load(modelName, temp.getDirectType().getName(), temp.getName(), false)); // } catch(Exception e){ // String temp = o.toString(); // System.out.println("INSTANCE:: " + temp); // } // } // values.put(p.getName(), val); // } else { values.put(p.getName(), individual.getPropertyValues(p)); // } } Instance instance = new Instance(instanceName, className, values); instances.get(modelName).put(instanceName, instance); return instance; } public static Instance get(String modelName, String instanceName) { if(has(modelName, instanceName)) return instances.get(modelName).get(instanceName); return null; } public static Set<String> getNames(String modelName) { if(has(modelName)) return instances.get(modelName).keySet(); return null; } }
package pw.react.backend.service; import pw.react.backend.model.Company; public interface CompanyService { Company updateCompany(Long id, Company updatedCompany); boolean deleteCompany(Long companyId); }
/* * LcmsSeqRuleConditionController.java 1.00 2011-09-16 * * Copyright (c) 2011 ???? Co. All Rights Reserved. * * This software is the confidential and proprietary information * of um2m. You shall not disclose such Confidential Information * and shall use it only in accordance with the terms of the license agreement * you entered into with um2m. */ package egovframework.adm.lcms.cts.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.SessionStatus; import egovframework.com.cmm.EgovMessageSource; import egovframework.com.pag.controller.PagingManageController; import egovframework.rte.fdl.property.EgovPropertyService; import egovframework.com.utl.fcc.service.EgovStringUtil; import egovframework.adm.lcms.cts.service.LcmsSeqRuleConditionService; import egovframework.adm.lcms.cts.domain.LcmsSeqRuleCondition; /** * <pre> * system : * menu : * source : LcmsSeqRuleConditionController.java * description : * </pre> * @version * <pre> * 1.0 2011-09-16 created by ? * 1.1 * </pre> */ @Controller public class LcmsSeqRuleConditionController { /** log */ protected static final Log LOG = LogFactory.getLog( LcmsSeqRuleConditionController.class); /** EgovPropertyService */ @Resource(name = "propertiesService") protected EgovPropertyService propertiesService; /** EgovMessageSource */ @Resource(name="egovMessageSource") EgovMessageSource egovMessageSource; /** PagingManageController */ @Resource(name = "pagingManageController") private PagingManageController pagingManageController; /** LcmsSeqRuleCondition */ @Resource(name = "lcmsSeqRuleConditionService") private LcmsSeqRuleConditionService lcmsSeqRuleConditionService; @RequestMapping(value="/adm/cts/LcmsSeqRuleConditionPageList.do") public String pageList( HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { int totCnt = lcmsSeqRuleConditionService.selectLcmsSeqRuleConditionPageListTotCnt(commandMap); pagingManageController.PagingManage(commandMap, model, totCnt); List list = lcmsSeqRuleConditionService.selectLcmsSeqRuleConditionPageList(commandMap); model.addAttribute("list", list); model.addAllAttributes(commandMap); return "/adm/cts/LcmsSeqRuleConditionPageList"; } @RequestMapping(value="/adm/cts/LcmsSeqRuleConditionList.do") public String list( HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { List list = lcmsSeqRuleConditionService.selectLcmsSeqRuleConditionList(commandMap); model.addAttribute("list", list); model.addAllAttributes(commandMap); return "/adm/cts/LcmsSeqRuleConditionList"; } @RequestMapping(value="/adm/cts/LcmsSeqRuleConditionView.do") public String view( HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { Map output = new HashMap(); output.putAll((Map)lcmsSeqRuleConditionService.selectLcmsSeqRuleCondition(commandMap)); model.addAttribute("output",output); model.addAllAttributes(commandMap); return "/adm/cts/LcmsSeqRuleConditionView"; } @RequestMapping(value="/adm/cts/LcmsSeqRuleConditionInsertForm.do") public String insertForm( HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { model.addAllAttributes(commandMap); return "/adm/cts/LcmsSeqRuleConditionInsert"; } @RequestMapping(value="/adm/cts/LcmsSeqRuleConditionInsert.do") public String insert( HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { String resultMsg = ""; String forwardUrl = ""; Object output = lcmsSeqRuleConditionService.insertLcmsSeqRuleCondition( commandMap); commandMap.put("output"," output"); resultMsg = egovMessageSource.getMessage("success.common.insert"); model.addAttribute("resultMsg", resultMsg); model.addAllAttributes(commandMap); forwardUrl = "forward:/adm/cts/LcmsSeqRuleConditionPageList.do"; return forwardUrl; } @RequestMapping(value="/adm/cts/LcmsSeqRuleConditionUdateForm.do") public String updateForm( HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { Map output = new HashMap(); output.putAll((Map)lcmsSeqRuleConditionService.selectLcmsSeqRuleCondition(commandMap)); model.addAttribute("output",output); model.addAllAttributes(commandMap); return "/adm/cts/LcmsSeqRuleConditionUpdate"; } @RequestMapping(value="/adm/cts/LcmsSeqRuleConditionUpdate.do") public String update( HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { String resultMsg = ""; String forwardUrl = ""; int result = lcmsSeqRuleConditionService.updateLcmsSeqRuleCondition( commandMap); if(result > 0){ resultMsg = egovMessageSource.getMessage("success.common.update"); }else{ resultMsg = egovMessageSource.getMessage("fail.common.update"); } model.addAttribute("resultMsg", resultMsg); model.addAllAttributes(commandMap); forwardUrl = "forward:/adm/cts/LcmsSeqRuleConditionUdateForm.do"; return forwardUrl; } @RequestMapping(value="/adm/cts/LcmsSeqRuleConditionDelete.do") public String delete( HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { String resultMsg = ""; String forwardUrl = ""; int result = lcmsSeqRuleConditionService.deleteLcmsSeqRuleCondition( commandMap); if(result > 0){ resultMsg = egovMessageSource.getMessage("success.common.delete"); }else{ resultMsg = egovMessageSource.getMessage("fail.common.delete"); } model.addAttribute("resultMsg", resultMsg); model.addAllAttributes(commandMap); forwardUrl = "forward:/adm/cts/LcmsSeqRuleConditionPageListForm.do"; return forwardUrl; } @RequestMapping(value="/adm/cts/LcmsSeqRuleConditionDelete.do") public String deleteAll( HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { String resultMsg = ""; String forwardUrl = ""; commandMap.put("rcIdxNum", EgovStringUtil.getStringSequence(commandMap, "chk")); int result = lcmsSeqRuleConditionService.deleteLcmsSeqRuleConditionAll( commandMap); if(result > 0){ resultMsg = egovMessageSource.getMessage("success.common.delete"); }else{ resultMsg = egovMessageSource.getMessage("fail.common.delete"); } model.addAttribute("resultMsg", resultMsg); model.addAllAttributes(commandMap); forwardUrl = "forward:/adm/cts/LcmsSeqRuleConditionPageListForm.do"; return forwardUrl; } }
package service; import java.util.List; import dao.TestDao; import pojo.TestItems; public class InsertService { public void insert(List<TestItems> items){ TestDao testdao=new TestDao(); testdao.insert(items); }}
/** * Kenny Akers * Mr. Paige * Homework #12 * 12/1/17 */ public class Homework_12 { private static MinPriorityQueue<Integer> minQ; private static MaxPriorityQueue<Integer> maxQ; public static void main(String[] args) { if (StdIn.isEmpty()) { System.out.println("No numbers."); return; } int[] array = StdIn.readAllInts(); minQ = new MinPriorityQueue<>(array.length); maxQ = new MaxPriorityQueue<>(array.length); for (int num : array) { // Add each number to one of the heaps. add(num); } System.out.println("Median: " + getMedian()); } private static double getMedian() { if (maxQ.size() > minQ.size()) { return maxQ.max(); } else if (minQ.size() > maxQ.size()) { return minQ.min(); } return (maxQ.max() + minQ.min()) / 2.0; } private static void add(int item) { if (maxQ.size() == 0 || item < maxQ.max()) { // If this number is less than the root of the minQ, or it's the first number. maxQ.add(item); } else { minQ.add(item); } rebalance(); } private static void rebalance() { if (Math.abs(minQ.size() - maxQ.size()) >= 2) { // If there is a size difference of 2 or more... if (minQ.size() > maxQ.size()) { // And minQ is the bigger one... maxQ.add(minQ.removeMin()); // Add the root to the smaller queue (maxQ). } else { // Otherwise, maxQ is the bigger one. minQ.add(maxQ.removeMax()); // So add the root of maxQ to the smaller queue (minQ). } } } }
package com.jit.biconsumer02; import java.util.ArrayList; import java.util.function.BiConsumer; /*Increament employee salary */ public class Test { public static void main(String[] args) { ArrayList<Employee> l = new ArrayList<>(); populate(l); BiConsumer<Employee, Double> c = (e,d) -> e.salary = e.salary + d; for(Employee e : l) { c.accept(e, 500.0); } for(Employee e : l) { System.out.println(e.name+"\t"+e.salary); } } public static void populate(ArrayList<Employee> l) { l.add(new Employee("Durga", 1000)); l.add(new Employee("Bunny", 2000)); l.add(new Employee("Jitendra", 45000)); l.add(new Employee("Kumar", 60000)); } }
package com.finahub.coding.server.vo; public class BankInfo { private int bank_id; private String bankname=null; private String creditcardamount=null; private String debitcardamount=null; public int getBank_id() { return bank_id; } public void setBank_id(int bank_id) { this.bank_id = bank_id; } public String getBankname() { return bankname; } public void setBankname(String bankname) { this.bankname = bankname; } public String getCreditcardamount() { return creditcardamount; } public void setCreditcardamount(String creditcardamount) { this.creditcardamount = creditcardamount; } public String getDebitcardamount() { return debitcardamount; } public void setDebitcardamount(String debitcardamount) { this.debitcardamount = debitcardamount; } @Override public String toString() { return "BankInfo [bank_id=" + bank_id + ", bankname=" + bankname + ", creditcardamount=" + creditcardamount + ", debitcardamount=" + debitcardamount + "]"; } }
package org.wso2.carbon.identity.recovery.endpoint.dto; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; import javax.validation.constraints.NotNull; @ApiModel(description = "") public class ReCaptchaResponseTokenDTO { private String token = null; /** **/ @ApiModelProperty(value = "") @JsonProperty("token") public String getToken() { return token; } public void setToken(String token) { this.token = token; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ReCaptchaResponseTokenDTO {\n"); sb.append(" token: ").append(token).append("\n"); sb.append("}\n"); return sb.toString(); } }
package com.hr.checksystem.repository; import java.util.List; import com.hr.checksystem.model.Checksystem; import com.hr.schedule.model.FactSchedule; public interface CheckRepository { void saveChecksystem(Checksystem checksystem); List<Checksystem> findPartCheckSystem(String empNo,int days); List<Checksystem> findCheckSystemByEmp(String empNo); List<Checksystem> findAllCheckSystem(); Checksystem findTodayCheckSystemByEmpno(String empNo); Checksystem findYesterdayCheckSystemByEmpno(String empNo); Checksystem getCheckSystemByTime(String dateString ,String empNo); public FactSchedule findWorkTimeByEmpNo(int empID , String date); }
package com.bookmarkrn; import android.content.Intent; import android.os.Bundle; import com.facebook.react.ReactActivity; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "bookmarkrn"; } @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected void onResume(){ super.onResume(); // Get intent, action and MIME type Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType(); // Match the intent specified in AndroidManifest.xml if (Intent.ACTION_SEND.equals(action) && "text/plain".equals(type)) { String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT); if (sharedText != null) { // Update UI to reflect text being shared SharedData.incomingText = sharedText; } } } }
package functions; /** * Created by pavel on 04.10.16. */ public interface IFunction { float getLimit(); float getValue(int dimension, float[] values); }
package com.example.mdt; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.os.Bundle; import android.provider.Telephony; import android.text.Html; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import java.io.IOException; import java.util.List; import java.util.Locale; public class GPS extends AppCompatActivity { Button btn16; TextView tv61; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_g_p_s); btn16 = (Button) findViewById(R.id.btn16); tv61 = (TextView) findViewById(R.id.tv61); btn16.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent I1 = new Intent(GPS.this, Testgps.class); startActivity(I1); } }); } }
package arraylist; import java.util.ArrayList; import java.util.List; public class Capsules { private List<String> capsules = new ArrayList<>(); public void addLast(String capsuleColor) { this.capsules.add(capsuleColor); } public void addFirst(String capsuleColor) { this.capsules.add(0, capsuleColor); } public void removeFirst() { this.capsules.remove(0); } public void removeLast() { this.capsules.remove(capsules.size() - 1); } public List<String> getColors() { return capsules; } public static void main(String[] args) { Capsules capsules = new Capsules(); System.out.println("Capsules: " + capsules.getColors()); capsules.addFirst("First1"); capsules.addLast("Last"); System.out.println("Capsules: " + capsules.getColors()); capsules.addFirst("First0"); System.out.println("Capsules: " + capsules.getColors()); capsules.removeLast(); System.out.println("Capsules: " + capsules.getColors()); capsules.removeFirst(); System.out.println("Capsules: " + capsules.getColors()); List<String> capsulesTmp=capsules.getColors(); System.out.println("CapsulesTmp: " + capsulesTmp); capsulesTmp.clear(); System.out.println("CapsulesTmp: " +capsulesTmp); System.out.println("Capsules: " + capsules.getColors()); } }
/* Copyright 2015 Alfio Zappala Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package co.runrightfast.logging; import co.runrightfast.commons.utils.JsonUtils; import static com.google.common.base.Preconditions.checkArgument; import com.google.gson.Gson; import java.util.logging.Level; import static java.util.logging.Level.INFO; import static java.util.logging.Level.SEVERE; import static java.util.logging.Level.WARNING; import java.util.logging.Logger; import lombok.NonNull; import static org.apache.commons.lang3.StringUtils.isNotBlank; /** * Wraps a logger to enable logging messages as JSON * * @author alfio */ public final class JsonLog { public static JsonLog infoJsonLog(@NonNull final Logger logger, final String className) { return new JsonLog(logger, INFO, className); } public static JsonLog infoJsonLog(@NonNull final Logger logger, final String className, final Gson gson) { return new JsonLog(logger, INFO, className, gson); } public static JsonLog warningJsonLog(@NonNull final Logger logger, final String className, final Gson gson) { return new JsonLog(logger, WARNING, className, gson); } public static JsonLog warningJsonLog(@NonNull final Logger logger, final String className) { return new JsonLog(logger, WARNING, className); } public static JsonLog errorJsonLog(@NonNull final Logger logger, final String className) { return new JsonLog(logger, SEVERE, className); } public static JsonLog errorJsonLog(@NonNull final Logger logger, final String className, final Gson gson) { return new JsonLog(logger, SEVERE, className, gson); } private final Logger logger; private final Level level; private final String className; private final Gson gson; /** * * @param logger used as the underlying logger * @param level the log level that will be used for all log messages * @param className the name of the class where the log event occurred */ public JsonLog(@NonNull final Logger logger, @NonNull final Level level, final String className) { checkArgument(isNotBlank(className)); this.logger = logger; this.level = level; this.className = className; this.gson = JsonUtils.gson; } public JsonLog(@NonNull final Logger logger, @NonNull final Level level, final String className, @NonNull final Gson gson) { checkArgument(isNotBlank(className)); this.logger = logger; this.level = level; this.className = className; this.gson = gson; } /** * * @param method the name of the method where the log event occurred * @param message a simple POJO that will be converted to JSON */ public void log(final String method, @NonNull final Object message) { logger.logp(level, className, method, () -> gson.toJson(message)); } public void log(final String method, @NonNull final Object message, @NonNull final Throwable exception) { logger.logp(level, className, method, exception, () -> gson.toJson(message)); } }
package com.github.andlyticsproject.io; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.TimeZone; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import android.content.Context; import android.os.Environment; import android.util.Log; import au.com.bytecode.opencsv.CSVReader; import au.com.bytecode.opencsv.CSVWriter; import com.github.andlyticsproject.model.AppStats; import com.github.andlyticsproject.util.Utils; public class StatsCsvReaderWriter { private static final String TAG = StatsCsvReaderWriter.class.getSimpleName(); public static final String[] HEADER_LIST = new String[] { "PACKAGE_NAME", "DATE", "TOTAL_DOWNLOADS", "ACTIVE_INSTALLS", "NUMBER_OF_COMMENTS", "1_STAR_RATINGS", "2_STAR_RATINGS", "3_STAR_RATINGS", "4_STAR_RATINGS", "5_STAR_RATINGS", "VERSION_CODE" }; private static final String EXPORT_DIR = "andlytics/"; private static final String DEFAULT_EXPORT_ZIP_FILE = "andlytics.zip"; private static final String EXPORT_ZIP_FILE_TEMPLATE = "andlytics-%s.zip"; private static final String CSV_SUFFIX = ".csv"; static final SimpleDateFormat TIMESTAMP_FORMAT = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'"); { TIMESTAMP_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); } public static String getExportDirPath() { return getExportDir().getAbsolutePath(); } public static File getExportDir() { return new File(Environment.getExternalStorageDirectory(), EXPORT_DIR); } public static File getDefaultExportFile() { return new File(getExportDir(), DEFAULT_EXPORT_ZIP_FILE); } public static File getExportFileForAccount(String accountName) { return new File(getExportDir(), String.format(EXPORT_ZIP_FILE_TEMPLATE, accountName)); } public static String getAccountNameForExport(String filename) { int firstDashIdx = filename.indexOf('-'); int suffixIdx = filename.indexOf(".zip"); if (firstDashIdx == -1 || suffixIdx == -1) { return null; } return filename.substring(firstDashIdx + 1, suffixIdx); } public StatsCsvReaderWriter(Context context) { } public void writeStats(String packageName, List<AppStats> stats, ZipOutputStream zip) throws IOException { zip.putNextEntry(new ZipEntry(packageName + CSV_SUFFIX)); CSVWriter writer = new CSVWriter(new OutputStreamWriter(zip)); writer.writeNext(HEADER_LIST); String[] line = new String[HEADER_LIST.length]; for (AppStats stat : stats) { line[0] = packageName; line[1] = TIMESTAMP_FORMAT.format(stat.getRequestDate()); line[2] = stat.getTotalDownloads() + ""; line[3] = stat.getActiveInstalls() + ""; line[4] = stat.getNumberOfComments() + ""; line[5] = stat.getRating1() + ""; line[6] = stat.getRating2() + ""; line[7] = stat.getRating3() + ""; line[8] = stat.getRating4() + ""; line[9] = stat.getRating5() + ""; line[10] = stat.getVersionCode() + ""; writer.writeNext(line); } writer.flush(); } public static List<String> getImportFileNamesFromZip(String accountName, List<String> packageNames, String zipFilename) throws ServiceExceptoin { List<String> result = new ArrayList<String>(); try { if (!new File(zipFilename).exists()) { return result; } ZipFile zipFile = new ZipFile(zipFilename); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); InputStream in = zipFile.getInputStream(entry); if (isValidFile(accountName, in, packageNames)) { result.add(entry.getName()); } } return result; } catch (IOException e) { Log.e(TAG, "Error reading zip file: " + e.getMessage()); return new ArrayList<String>(); } } private static boolean isValidFile(String accountName, InputStream in, List<String> packageNames) throws ServiceExceptoin { if (packageNames.isEmpty()) { return true; } CSVReader reader = null; try { reader = new CSVReader(new InputStreamReader(in)); String[] firstLine = reader.readNext(); if (firstLine != null) { if (HEADER_LIST.length >= firstLine.length) { for (int i = 0; i < HEADER_LIST.length - 1; i++) { if (!HEADER_LIST[i].equals(firstLine[i])) { return false; } } // validate package name String[] secondLine = reader.readNext(); String packageName = secondLine[0]; if (secondLine != null) { return packageNames.contains(packageName); } } } } catch (FileNotFoundException e) { throw new ServiceExceptoin(e); } catch (IOException e) { throw new ServiceExceptoin(e); } finally { Utils.closeSilently(reader); } return false; } public static String getPackageName(String filename) { int suffixIdx = filename.indexOf(CSV_SUFFIX); if (suffixIdx == -1) { return null; } return filename.substring(0, suffixIdx); } public List<AppStats> readStats(InputStream in) throws ServiceExceptoin { List<AppStats> appStats = new ArrayList<AppStats>(); CSVReader reader; try { reader = new CSVReader(new InputStreamReader(in)); String[] firstLine = reader.readNext(); if (firstLine != null) { String[] nextLine = null; while ((nextLine = reader.readNext()) != null) { AppStats stats = new AppStats(); stats.setPackageName(nextLine[0]); stats.setRequestDate(TIMESTAMP_FORMAT.parse(nextLine[1])); stats.setTotalDownloads(Integer.parseInt(nextLine[2])); stats.setActiveInstalls(Integer.parseInt(nextLine[3])); stats.setNumberOfComments(Integer.parseInt(nextLine[4])); stats.setRating1(Integer.parseInt(nextLine[5])); stats.setRating2(Integer.parseInt(nextLine[6])); stats.setRating3(Integer.parseInt(nextLine[7])); stats.setRating4(Integer.parseInt(nextLine[8])); stats.setRating5(Integer.parseInt(nextLine[9])); if (nextLine.length > 10) { stats.setVersionCode(Integer.parseInt(nextLine[10])); } appStats.add(stats); } } } catch (FileNotFoundException e) { throw new ServiceExceptoin(e); } catch (IOException e) { throw new ServiceExceptoin(e); } catch (ParseException e) { throw new ServiceExceptoin(e); } return appStats; } public String readPackageName(String fileName) throws ServiceExceptoin { try { return readPackageName(new FileInputStream(new File(getExportDirPath(), fileName))); } catch (IOException e) { throw new ServiceExceptoin(e); } } public String readPackageName(InputStream in) throws ServiceExceptoin { String packageName = null; CSVReader reader; try { reader = new CSVReader(new InputStreamReader(in)); String[] firstLine = reader.readNext(); if (firstLine != null) { String[] nextLine = null; while ((nextLine = reader.readNext()) != null) { packageName = nextLine[0]; } } } catch (FileNotFoundException e) { throw new ServiceExceptoin(e); } catch (IOException e) { throw new ServiceExceptoin(e); } return packageName; } }
package main.Controller; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.control.TextField; import main.Controller.Util.GeneralController; import main.DAO.CountryDAO; import main.DAO.CustomerDAO; import main.DAO.FirstLevelDivisionDAO; import main.Exception.ValidationException; import main.Model.Country; import main.Model.Customer; import main.Model.FirstLevelDivision; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; /** * @author Michael Williams - 001221520 *<br> * This class controls and handles all processes related to the 'CustomerForm.fxml' page. * <br><br> * LAMBDA EXPRESSION 'updateCustomer' & 'addCustomer' are used to simplify the creation of Customer objects in the class. * This minimizes code and makes it easier to read and manage. */ public class CustomerFormController implements Initializable { public Label headerLbl; public TextField id_textfield; public TextField name_textfield; public TextField address_textfield; public TextField zipcode_textfield; public TextField phone_textfield; public ChoiceBox<Country> country_choicebox; public ChoiceBox<FirstLevelDivision> division_choicebox; public Customer customerToModify; public Label currentCountryLbl; public Label currentDivisionLbl; ObservableList<Country> countries =FXCollections.observableArrayList(); ObservableList<FirstLevelDivision> divisions = FXCollections.observableArrayList(); ObservableList<FirstLevelDivision> divisionsByCountryId = FXCollections.observableArrayList(); CustomerInterface updateCustomer = ()-> new Customer( Integer.parseInt(id_textfield.getText()), name_textfield.getText(), address_textfield.getText(), zipcode_textfield.getText(), phone_textfield.getText(), division_choicebox.getValue().getDivisionId() ); CustomerInterface addCustomer = ()-> new Customer( name_textfield.getText(), address_textfield.getText(), zipcode_textfield.getText(), phone_textfield.getText(), division_choicebox.getValue().getDivisionId() ); /** * Initializes the Customer Form view and populates the choice boxes with data from the Country and * FirstLevelDivision database tables. *<br><br> * LAMBDA EXPRESSION in this method filters divisions shown in the Division choicebox based on the selection * made in the Country choicebox * */ @Override public void initialize(URL url, ResourceBundle resourceBundle) { countries.setAll(CountryDAO.getAllCountries()); divisions.setAll(FirstLevelDivisionDAO.getAllDivisions()); for (Country c:countries){ country_choicebox.getItems().add(c); } for (FirstLevelDivision d: divisions){ division_choicebox.getItems().add(d); } setCustomerToModify(MainController.getModifyCustomer()); if (customerToModify != null){ headerLbl.setText("Update Customer"); id_textfield.setText(String.valueOf(customerToModify.getCustomerId())); name_textfield.setText(customerToModify.getCustomerName()); address_textfield.setText(customerToModify.getCustomerAddress()); zipcode_textfield.setText(customerToModify.getCustomerZipcode()); phone_textfield.setText(customerToModify.getCustomerPhone()); currentCountryLbl.setText("Country (Current Selection: "+customerToModify.getCustomerCountryText()+")"); country_choicebox.setValue(getCountryById(customerToModify.getCustomerCountry())); division_choicebox.setItems(getDivisionsByCountryId(customerToModify.getCustomerCountry())); division_choicebox.setValue(getDivisionById(customerToModify.getCustomerDivision())); currentDivisionLbl.setText("State/Division (Current Selection: "+customerToModify.getCustomerDivisionText()+")"); // Lambda Expression selects which divisions will be shown based on the country selection(observableValue). country_choicebox.getSelectionModel().selectedItemProperty().addListener((observableValue, country, t1) -> { divisionsByCountryId.setAll(getDivisionsByCountryId(observableValue.getValue().getCountryId())); division_choicebox.getItems().removeAll(); division_choicebox.setItems(divisionsByCountryId); }); } else { headerLbl.setText("Add Customer"); division_choicebox.setDisable(true); // Lambda Expression selects which divisions will be shown based on the country selection. country_choicebox.getSelectionModel().selectedItemProperty().addListener((observableValue, country, t1) -> { divisionsByCountryId.setAll(getDivisionsByCountryId(observableValue.getValue().getCountryId())); division_choicebox.setDisable(false); division_choicebox.getItems().removeAll(); division_choicebox.setItems(divisionsByCountryId); }); } } /** * This method validates form completion and saves a new customer to the database if no data was brought over * from the Main view. Otherwise, the user will be updated based on the information brought over from the main view. * * LAMBDA EXPRESSION in this method simplifies the creation of Customer objects to be stored or updated in the database. * @param actionEvent * @throws IOException */ public void save(ActionEvent actionEvent) throws IOException { if (customerToModify != null) { try{ isFormComplete(); Customer c = updateCustomer.newCustomer(); try { c.isValid(); CustomerDAO.updateCustomer(c); GeneralController.changePage(actionEvent,"Main"); }catch (ValidationException v){ Alert alert = GeneralController.alertUser(Alert.AlertType.ERROR,"Validation Error","Wrong Input", v.getMessage()); alert.showAndWait(); } }catch (NullPointerException n){ Alert alert = GeneralController.alertUser(Alert.AlertType.ERROR, "Validation Error", "Invalid Form Data", n.getMessage()); alert.showAndWait(); } } else { try { isFormComplete(); Customer c = addCustomer.newCustomer(); try { c.isValid(); CustomerDAO.addCustomer(c); GeneralController.changePage(actionEvent,"Main"); }catch (ValidationException v){ Alert alert = GeneralController.alertUser(Alert.AlertType.ERROR, "Validation Error", "Wrong Input", v.getMessage()); alert.showAndWait(); } }catch (NullPointerException n){ Alert alert = GeneralController.alertUser(Alert.AlertType.ERROR, "Validation Error", "Invalid Form Data", n.getMessage()); alert.showAndWait(); } } } /** * This method will cancel the addition of a new customer and move the user back to the main view. * @param actionEvent * @throws IOException */ public void cancel(ActionEvent actionEvent) throws IOException { GeneralController.changePage(actionEvent,"Main"); } // ================================================================================================================== // ==================Getters & Setters=============================================================================== // ================================================================================================================== /** * * @return customerToModify */ public Customer getCustomerToModify() { return customerToModify; } /** * * @param customerToModify customerToModify */ public void setCustomerToModify(Customer customerToModify) { this.customerToModify = customerToModify; } /** * This method checks that no form fields were left blank. * @return True is all form fields are filled. * @throws NullPointerException */ public boolean isFormComplete() throws NullPointerException{ if (name_textfield.getText().equals("")){ throw new NullPointerException("Name field cannot be empty"); } if (address_textfield.getText().equals("")){ throw new NullPointerException("Address field cannot be empty"); } if (zipcode_textfield.getText().equals("")){ throw new NullPointerException("Zipcode field cannot be empty"); } if (phone_textfield.getText().equals("")){ throw new NullPointerException("Phone field cannot be empty"); } if (country_choicebox.getValue().toString().equals("")){ throw new NullPointerException("Country choice field cannot be empty"); } if (division_choicebox.getValue().toString().equals("")){ throw new NullPointerException("Division choice field cannot be empty"); } return true; } /** * Filters through the countries ObservableList and returns the country with the provided Country_ID. * @param id ID of requested country. * @return Country with provided Country_ID. */ private Country getCountryById(int id){ Country country = null; for (Country c : countries) { if (c.getCountryId() != id){ continue; }else { country = c; } } return country; } /** * Filters through the divisions ObservableList and returns the division with the provided Division_ID. * @param id ID of requested division. * @return Division with provided Division_ID. */ private FirstLevelDivision getDivisionById(int id){ FirstLevelDivision fld = null; for (FirstLevelDivision f : divisions) { if (f.getDivisionId() != id){ continue; }else { fld = f; } } return fld; } /** * Filters through the divisions ObservableList and returns the divisions with the provided Country_ID. * @param id ID of requested Country. * @return Divisions with provided Country_ID. */ private ObservableList<FirstLevelDivision> getDivisionsByCountryId(int id){ ObservableList<FirstLevelDivision> fldList = FXCollections.observableArrayList(); for (FirstLevelDivision f: divisions ) { if (f.getCountryId() != id){ continue; }else { fldList.add(f); } } return fldList; } }
package com.shendrikov.alex.mynotes.fragment; import android.view.View; /** * Created by Alex on 25.04.2017. */ public interface OnSomeEventListener { void saveChanges(); }
package com.trump.auction.pals.service; import com.trump.auction.pals.api.model.alipay.AliPayQueryResponse; import com.trump.auction.pals.api.model.alipay.AlipayBackRequest; import com.trump.auction.pals.api.model.alipay.AlipayBackResponse; import com.trump.auction.pals.api.model.alipay.AlipayPayRequest; import com.trump.auction.pals.api.model.alipay.AlipayPayResponse; import com.trump.auction.pals.api.model.alipay.AlipayQueryRequest; /** * ็›Š็ ้€š็›ธๅ…ณAPI */ public interface AlipayService { AlipayPayResponse toAlipayPay(AlipayPayRequest apr); AliPayQueryResponse toAlipayQuery(AlipayQueryRequest aqr); AlipayBackResponse toAlipayBack(AlipayBackRequest abr); String queryBatchNoByOrderNo(String orderNo); }
package com.crackdevelopers.goalnepal.Volley; /** * Created by trees on 8/28/15. */ public class KEYS { public static final String GALLERY="galleries", VENUE="venue", IMAGE="img", DATE="pub_date"; ///KEYS OF }
package com.datastax.poc.log; import com.datastax.driver.core.utils.UUIDs; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.util.Date; import java.util.Map; import java.util.UUID; /** * Created by Patrick on 17/09/15. */ @Table(keyspace = "log_ks", name = "logs") public class Log { @PartitionKey(0) @Column(name = "source_id") private UUID sourceId; @PartitionKey(1) @Column(name = "bucket_ts") private Date bucketTs; @ClusteringColumn(0) @Column(name = "ts") private Date timestamp; @ClusteringColumn(1) @Column(name = "id") private UUID id; @Column(name = "type") private String type; @Column(name = "tags") private Map<String, String> tags; @Column(name = "timestamps") private Map<Date, String> timestamps; @Column(name = "raw") private String raw; public Log(UUID id) { this.id = id; } public Log() { this(UUIDs.random()); } public UUID getSourceId() { return sourceId; } public void setSourceId(UUID sourceId) { this.sourceId = sourceId; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public Date getBucketTs() { return bucketTs; } public void setBucketTs(int intervalInSeconds) { long bucketTime = this.timestamp.getTime() - this.timestamp.getTime() % (intervalInSeconds * 1000); this.bucketTs = new Date(bucketTime); } public String getType() { return type; } public void setType(String type) { this.type = type; } public void setBucketTs(Date bucketTs) { this.bucketTs = bucketTs; } public Map<String, String> getTags() { return tags; } public void addTag(String name, String value) { this.tags.put(name, value); } public void setTags(Map<String, String> tags) { this.tags = tags; } public void addTimestamp(Date ts, String name) { this.timestamps.put(ts, name); } public Map<Date, String> getTimestamps() { return timestamps; } public void setTimestamps(Map<Date, String> timestamps) { this.timestamps = timestamps; } public String getRaw() { return raw; } public void setRaw(String raw) { this.raw = raw.replaceAll(";",""); } public void setId(UUID id) { this.id = id; } public UUID getId() { return id; } @Override public String toString() { return String.format("%s;%s;%s;%s;%s", id, sourceId, new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ").format(this.timestamp), type, raw); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Log log = (Log) o; if (sourceId != null ? !sourceId.equals(log.sourceId) : log.sourceId != null) return false; if (bucketTs != null ? !bucketTs.equals(log.bucketTs) : log.bucketTs != null) return false; if (timestamp != null ? !timestamp.equals(log.timestamp) : log.timestamp != null) return false; if (id != null ? !id.equals(log.id) : log.id != null) return false; if (type != null ? !type.equals(log.type) : log.type != null) return false; if (tags != null ? !tags.equals(log.tags) : log.tags != null) return false; if (timestamps != null ? !timestamps.equals(log.timestamps) : log.timestamps != null) return false; return !(raw != null ? !raw.equals(log.raw) : log.raw != null); } @Override public int hashCode() { int result = sourceId != null ? sourceId.hashCode() : 0; result = 31 * result + (bucketTs != null ? bucketTs.hashCode() : 0); result = 31 * result + (timestamp != null ? timestamp.hashCode() : 0); result = 31 * result + (id != null ? id.hashCode() : 0); result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (tags != null ? tags.hashCode() : 0); result = 31 * result + (timestamps != null ? timestamps.hashCode() : 0); result = 31 * result + (raw != null ? raw.hashCode() : 0); return result; } }
package com.example.rock.harayo; /** * Created by User on 7/21/2019. */ public final class Constants { public static final String BASE_URL = "http://10.16.1.168:5000/"; }
package exercicio03; public class reta { public Ponto2D a,b; public reta(float ax,float ay,float bx,float by) { a=new Ponto2D(ax,ay); //chamadas dos contrutores da classe Ponto b=new Ponto2D(bx,by); } public void mostraCoeficiente() { a.mostraCoeficiente(); b.mostraCoeficiente(); } }
package com.example.appuel.modal; public class ThoiKhoaBieu { public int Id; public String tenmonhoc; public String thoigian; public String phong; public int ngayhoc; public ThoiKhoaBieu(int id, String tenmonhoc, String thoigian, String phong, int ngayhoc) { Id = id; this.tenmonhoc = tenmonhoc; this.thoigian = thoigian; this.phong = phong; this.ngayhoc = ngayhoc; } public int getId() { return Id; } public void setId(int id) { Id = id; } public String getTenmonhoc() { return tenmonhoc; } public void setTenmonhoc(String tenmonhoc) { this.tenmonhoc = tenmonhoc; } public String getThoigian() { return thoigian; } public void setThoigian(String thoigian) { this.thoigian = thoigian; } public String getPhong() { return phong; } public void setPhong(String phong) { this.phong = phong; } public int getNgayhoc() { return ngayhoc; } public void setNgayhoc(int ngayhoc) { this.ngayhoc = ngayhoc; } }
/* * @lc app=leetcode.cn id=87 lang=java * * [87] ๆ‰ฐไนฑๅญ—็ฌฆไธฒ */ // @lc code=start class Solution { public boolean isScramble(String s1, String s2) { int len1 = s1.length(); int len2 = s2.length(); if (len1 != len2) return false; boolean[][][] dp = new boolean[len1][len1][len1 + 1]; // ๅˆๅง‹ๅŒ–dp for (int i = 0; i < len1; i++) for (int j = 0; j < len1; j++) dp[i][j][1] = (s1.charAt(i) == s2.charAt(j)); // ไปŽlen=2ๅผ€ๅง‹่ง„ๅˆ’ for (int k = 2; k <= len1; k++) { for (int i = 0; i <= len1 - k; i++) { for (int j = 0; j <= len1 - k; j++) { // ไปŽ1ๅˆฐk-1ๅผ€ๅง‹ๅˆ‡ๅ‰ฒ for (int m = 1; m <= k - 1; m++) { if (dp[i][j][m] && dp[i + m][j + m][k - m] || dp[i][j + k - m][m] && dp[i + m][j][k - m]) { dp[i][j][k] = true; break; } } } } } return dp[0][0][len1]; } } // @lc code=end
package org.usfirst.frc.team5114.MyRobot2016.subsystems; import java.awt.Robot; import javax.management.timer.Timer; import org.usfirst.frc.team5114.MyRobot2016.RobotMap; import org.usfirst.frc.team5114.MyRobot2016.commands.*; import edu.wpi.first.wpilibj.VictorSP; import edu.wpi.first.wpilibj.CANTalon; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.Servo; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * */ public class BallIntake extends Subsystem { private final VictorSP victorSP7 = (VictorSP) RobotMap.ballIntakeVictor7; private final CANTalon outerIntake = RobotMap.ballIntakeTalon9; private double intakeSpeed = 0.5, shootSpeed = 1.0; private double outerIntakeSpd = 0.5, outerIntakeShootSpd; // Put methods for controlling this subsystem // here. Call these from Commands. public double getIntakeSpeed() { return intakeSpeed; } public double getLowGoalSpeed() { return shootSpeed; } public void intakeBall(double percentVolt) { victorSP7.set(-percentVolt); } public void shootLow(double percentVolt) { victorSP7.set(percentVolt); } public void startIntake() { intakeSpeed = SmartDashboard.getNumber("Intake Speed"); victorSP7.set(-intakeSpeed); outerIntakeSpd = SmartDashboard.getNumber("Outer Intake Speed"); outerIntake.set(-outerIntakeSpd); } public void startShoot() { shootSpeed = SmartDashboard.getNumber("Low Goal Speed"); victorSP7.set(shootSpeed); outerIntakeShootSpd = SmartDashboard.getNumber("Outer Intake Shoot Speed"); outerIntake.set(outerIntakeShootSpd); } public void stop() { victorSP7.set(0.0); outerIntake.set(0.0); } public void initDefaultCommand() { // Set the default command for a subsystem here. // setDefaultCommand(new MySpecialCommand()); } }
package com.github.hymanme.tagflowlayout; import android.view.View; /** * /** * Author :hyman * Email :hymanme@163.com * Create at 2016/9/4 * Description: */ public interface OnTagClickListener { void onClick(View view, int position); void onLongClick(View view, int position); }
package com.mcl.mancala.beans; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /* * Bean used for storing Player state and utility methods that will modify the state of pit related properties. * * @author Maxim N * */ @AllArgsConstructor @Getter @Setter @EqualsAndHashCode public class Player { private int id; private int largePit; private int[] smallPits; private boolean move; public void incrementLargePit() { largePit++; } public void incrementSmallPit(int position) { smallPits[position]++; } public void addToLargePit(int pebbles) { largePit += pebbles; } public void setPebblesToSmallPit(int position, int pebbles) { smallPits[position] = pebbles; } public void emptySmallPit(int position) { smallPits[position] = 0; } public void emptySmallPits() { smallPits = new int[6]; } public int getSmallPitValue(int position) { return smallPits[position]; } }
package com.aidigame.hisun.imengstar.widget.fragment; import java.util.ArrayList; import me.maxwin.view.XListView; import me.maxwin.view.XListView.IXListViewListener; import me.maxwin.view.XListViewHeader; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.aidigame.hisun.imengstar.adapter.HomeArticleListAdapter; import com.aidigame.hisun.imengstar.bean.Article; import com.aidigame.hisun.imengstar.bean.Gift; import com.aidigame.hisun.imengstar.bean.PetPicture; import com.aidigame.hisun.imengstar.bean.Article.ArticleComment; import com.aidigame.hisun.imengstar.http.HttpUtil; import com.aidigame.hisun.imengstar.ui.ArticleActivity; import com.aidigame.hisun.imengstar.util.HandleHttpConnectionException; import com.aidigame.hisun.imengstar.util.LogUtil; import com.aidigame.hisun.imengstar.R; import com.huewu.pla.lib.internal.PLA_AdapterView; import com.huewu.pla.lib.internal.PLA_AdapterView.OnItemClickListener; public class HomeArticleFragment extends Fragment implements IXListViewListener{ private View view; private XListView xListView; private Handler handler; ArrayList<Article> articleList; private HomeArticleListAdapter homeArticleListAdapter; int page=0; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub view=inflater.inflate(R.layout.widget_home_pet_pictures, null); initView(); return view; } private void initView() { // TODO Auto-generated method stub handler=HandleHttpConnectionException.getInstance().getHandler(getActivity()); xListView=(XListView)view.findViewById(R.id.listview); xListView.setPullLoadEnable(true); xListView.setPullRefreshEnable(true); articleList=new ArrayList<Article>(); homeArticleListAdapter=new HomeArticleListAdapter(getActivity(), articleList); xListView.setAdapter(homeArticleListAdapter); xListView.setXListViewListener(this); pullRefresh(); /*xListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(PLA_AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub LogUtil.i("me", "position="+position); } });*/ } boolean isRefresh=false; public void pullRefresh(){ if(isRefresh)return; if(xListView!=null){ xListView.updateHeaderHeight(xListView.mHeaderViewHeight); xListView.mHeaderView.setVisibility(View.VISIBLE); xListView.mPullRefreshing = true; xListView.mEnablePullRefresh=true; xListView.mHeaderView.setState(XListViewHeader.STATE_REFRESHING); if (xListView.mListViewListener != null) { isRefresh=true; xListView.mListViewListener.onRefresh(); } xListView.resetHeaderHeight(); } } @Override public void onViewCreated(View view, Bundle savedInstanceState) { // TODO Auto-generated method stub super.onViewCreated(view, savedInstanceState); } @Override public void onRefresh() { // TODO Auto-generated method stub page=0; articleList=new ArrayList<Article>(); homeArticleListAdapter.update(articleList); homeArticleListAdapter.notifyDataSetChanged(); new Thread(new Runnable() { ArrayList<Article> temp=new ArrayList<Article>(); @Override public void run() { // TODO Auto-generated method stub temp=HttpUtil.getArticleList(handler, page, getActivity()); if(getActivity()!=null) getActivity().runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub if(temp!=null/*&&temp.size()>articleList.size()*/){ articleList=temp; homeArticleListAdapter.update(temp); homeArticleListAdapter.notifyDataSetChanged(); } isRefresh=false; xListView.stopRefresh(); } }); } }).start(); } @Override public void onLoadMore() { // TODO Auto-generated method stub if(articleList.size()>0){ page++; }else{ } new Thread(new Runnable() { ArrayList<Article> temp=new ArrayList<Article>(); @Override public void run() { // TODO Auto-generated method stub temp=HttpUtil.getArticleList(handler, page, getActivity()); if(getActivity()!=null) getActivity().runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub if(temp!=null&&temp.size()>0){ for(int i=0;i<temp.size();i++){ articleList.add(temp.get(i)); } homeArticleListAdapter.update(articleList); homeArticleListAdapter.notifyDataSetChanged(); } xListView.stopRefresh(); } }); } }).start(); xListView.stopLoadMore();; } }
package com.alibaba.druid.mysql; import com.alibaba.druid.DbTestCase; import com.alibaba.druid.util.JdbcConstants; import com.alibaba.druid.util.JdbcUtils; import com.alibaba.druid.util.MySqlUtils; import com.alibaba.fastjson2.util.TypeUtils; //import com.mysql.jdbc.ConnectionImpl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; /** * Created by wenshao on 23/07/2017. */ public class MySql_Connect_test extends DbTestCase { public MySql_Connect_test() { super("pool_config/mysql_tddl.properties"); } public void test_oracle_2() throws Exception { for (int i = 0; i < 10; ++i) { Connection conn = getConnection(); Statement stmt = conn.createStatement(); int updateCnt = stmt.executeUpdate("update tb1 set fid = '3' where fid = '4'"); System.out.println("update : " + updateCnt); System.out.println( MySqlUtils.getLastPacketReceivedTimeMs(conn)); stmt.close(); // rs.close(); conn.close(); } } public void test_oracle() throws Exception { Connection conn = getConnection(); System.out.println( MySqlUtils.getLastPacketReceivedTimeMs(conn)); //String createTableScript = JdbcUtils.getCreateTableScript(conn, JdbcConstants.MYSQL); //System.out.println(createTableScript); Statement stmt = conn.createStatement(); int updateCnt = stmt.executeUpdate("update tb1 set fid = '3' where fid = '4'"); System.out.println("update : " + updateCnt); System.out.println( MySqlUtils.getLastPacketReceivedTimeMs(conn)); Thread.sleep(500); System.out.println( MySqlUtils.getLastPacketReceivedTimeMs(conn)); Class<?> class_connImpl_5 = TypeUtils.loadClass("com.mysql.jdbc.ConnectionImpl"); if (class_connImpl_5 != null) { conn.unwrap(class_connImpl_5); } dataSource.validateConnection(conn); System.out.println( MySqlUtils.getLastPacketReceivedTimeMs(conn)); stmt.close(); // rs.close(); conn.close(); } }
package com.alibaba.druid.bvt.sql.odps; import org.junit.Assert; import com.alibaba.druid.sql.SQLUtils; import junit.framework.TestCase; public class OdpsFormatCommentTest17 extends TestCase { public void test_column_comment() throws Exception { String sql = "set xxx=aaa;--ssss"; Assert.assertEquals("SET xxx = aaa;-- ssss", SQLUtils.formatOdps(sql)); } }
/* Framework for MDP Solver Stephen Majercik */ import java.io.*; import java.util.Arrays; public class MDP { // number of states and actions in the MDP private static final int NUM_STATES = 65; private static final int NUM_ACTIONS = 4; // N = go-north, E = go-east, S = go-south, W = go-west private static final int N = 0; private static final int E = 1; private static final int S = 2; private static final int W = 3; // how many decimal places to print for the utilities // in the printUtilitiesAndPolicy method private static final int PRINT_UTILITY_PRECISION = 2; /* These are the necessary doubles to carry out the MDP, which are specified by the user in the command line: discountFactor: discount for rewards maxStateUtilityError: maximum error allowed in the utility of any state keyLossProbability: probability that agent will lose key in Lose-Key? square positiveTerminalReward: reward for transitions into +1-with-key state negativeTerminalReward: reward for transitions into -1 state stepCost: reward for all other transitions (step cost) */ private static double discountFactor, maxStateUtilityError, keyLossProbability, positiveTerminalReward, negativeTerminalReward, stepCost; // solution technique private static String solutionTechnique = ""; // arrays for transition and reward functions private static double[][][] T = new double[NUM_STATES][NUM_ACTIONS][NUM_STATES]; private static double[] R = new double[NUM_STATES]; // arrays for state utilities and the current policy private static double[] utility = new double[NUM_STATES]; private static int[] policy = new int[NUM_STATES]; // array of coefficients for the linear equation private static double[][] ma = new double[NUM_STATES][NUM_STATES]; // array of constants for the linear equation private static double[][] mb = new double[NUM_STATES][1]; // variable to store number of iterations of solution technique private static int numIterations; // variables to calculate the time to execute MDP private static double startTime, endTime; public static void main (String[] args) { // Initialize the MDP with given arguments initializeWithArgs(args); initializeMDP(T, R); // With arg v, execute valueIteration() if(solutionTechnique.charAt(0) == 'v' || solutionTechnique.charAt(0) == 'V') { // Start the timer startTime = System.nanoTime(); valueIteration(); endTime = System.nanoTime(); // Stop the timer so we can calculate // how long valueIteration() took } // Else if the user enters arg p, execute policyIteration(); else if (solutionTechnique.charAt(0) == 'p' || solutionTechnique.charAt(0) == 'P') { // Calculate the start time of polcyIteration(); startTime = System.nanoTime(); policyIteration(); // Stop the timer so we can calculate how long // the policyIteration() process took endTime = System.nanoTime(); } else{ // Throw an error code for any invalid input System.out.println("Error: invalid argument for solution technique. Must type 'v' or 'p'."); return; } // Show method that prints utilities and policy printUtilitiesAndPolicy(utility, policy); // Print the specified arguments as well as the // statistics generated by the solution method printArgs(); printStats(); } /* The printStats() method is used after the user specifies what option they are choosing in the main, and then prints the statistics generated by the solution of the MDP. The number of iterations is generated by either the value_iteration or policy_iteration methods, and the time is marked in the main. */ public static void printStats() { double time = (endTime-startTime)*Math.pow(10,-9); System.out.println(); System.out.println("********************************************"); System.out.println("Solution Statistics: "); System.out.println(); System.out.println("Number of iteration: " + numIterations); System.out.println("Time to execute: " + time + " seconds"); System.out.println(); } /* Prints the arguments that were specified by the user in the following order: Solution Technique: Value Iteration/Policy Iteration Discount Factor: _________ Max State Utility Error: _________ Key Loss Probability: _________ Positive Terminal Reward: _________ Negative Terminal Reward: ________ Step Cost: _________ */ public static void printArgs() { String sT; if(solutionTechnique.charAt(0) == 'v' || solutionTechnique.charAt(0) == 'V') { sT= "Value Iteration"; } else { // solutionTechnique.charAt(0) == 'p' || solutionTechnique.charAt(0) == 'P' sT= "Policy Iteration"; } System.out.println(); System.out.println(); System.out.println("********************************************"); System.out.println("Solution Technique: " + sT); System.out.println(); System.out.println("Discount Factor: " + discountFactor); System.out.println("Max State Utility Error: " + maxStateUtilityError); System.out.println("Key Loss Probability: " + keyLossProbability); System.out.println("Positive Terminal Reward: " + positiveTerminalReward); System.out.println("Negative Terminal Reward: " + negativeTerminalReward); System.out.println("Step Cost: " + stepCost); } /* Stores the entered arguments for the MDP as the specified static doubles for each argument. */ public static void initializeWithArgs(String[] args) { discountFactor = Double.parseDouble(args[0]); maxStateUtilityError = Double.parseDouble(args[1]); keyLossProbability = Double.parseDouble(args[2]); positiveTerminalReward = Double.parseDouble(args[3]); negativeTerminalReward = Double.parseDouble(args[4]); stepCost = Double.parseDouble(args[5]); solutionTechnique = args[6]; } /* The valueIteration() method iterates through a do-while loop to calculate utilities for all states. Outside the loop, initialize the iteration counter, as well as a double called maxStateChange, which will help us calculate the stopping criterion for the do-while. First, iterate through all of the initial states, and at the start of this loop initialize a double called maxSum, which will be used to store the maximum calculated utility of a state given an action. Then, iterate through each action, and declare currSum, which will be the current utility of a state given the action. Then, iterate through all of the transition states, and sum over their utilies, storing it in currSum. We then check currSum against maxSum, and if it is greater, we set maxSum = currSum, and then put that action into the policy. After all of this, we update the utility for the initial state using Bellman backups (our newly calculated maxSum is the maximum utility of the state. Then, check to see whether another iteration can be executed. */ public static void valueIteration() { double maxStateChange; numIterations = 0; int policy1[] = new int[NUM_STATES]; // Calculate the utility for all states do{ policy1 = policy.clone(); numIterations++; // Reset the amount of state change on each iteration of the do-while loop maxStateChange = 0.0; // Iterate through each initial state for(int s = 0; s < NUM_STATES; s++) { // Initialize maxSum as a negative number to be used // to store the maximum utility of a state double maxSum = -Double.MAX_VALUE; // Iterate through each action at the initial state for(int a = 0; a < NUM_ACTIONS; a++) { // Initialize double currSum, which will be used in summing utilities double currSum = 0.0; // Iterate through the transition states for(int i = 0; i < NUM_STATES; i++) { // Calculate the utility by summing over the transition // states given an initial state and action currSum = currSum + (T[s][a][i] * utility[i]); } // If the currSum > maxSum, then we know that the utility of the state // given the specific action is greater than the calculated max utility. // So we set maxSum equal to currSum, and then we store the action as a // part of our policy. Then, we compute the utilities of the same state // for the next action, repeating the process. if(currSum > maxSum) { policy[s] = a; maxSum = currSum; } } // Store the previous utility of the state double prevUtility = utility[s]; // Set the new utility to what we calculated using Bellman backups utility[s] = R[s] + (discountFactor * maxSum); // Check to see if the current change in state utility is greater // than the maximum calculated state change. If so, set the new // maxStateChange to the calculated state change if(Math.abs(utility[s] - prevUtility) > maxStateChange) { maxStateChange = Math.abs(utility[s] - prevUtility); } } if(Arrays.equals(policy, policy1) == false) { System.out.println(numIterations); } // Specify the stopping criterion for the value iteration process } while(maxStateChange > ((maxStateUtilityError * (1 - discountFactor))/discountFactor)); } /* The policyIteration() utilizes a do-while loop. First in the do while, the current policy is evaluated and utilities are updated with a linear matrix equation. Next, given those utilities, the policy is evaluated in a series of for-loops. In these loops, if a better policy is found than the current policy, that policy is updated, and the do-while loop is guarenteed to iterate again. This is repeated until the policy does not change after the policy evaluation and policy update steps. */ public static void policyIteration() { // Create a boolean to see if the policy has been changed boolean policyChanged; // Initialize the iteration counter numIterations = 0; // Initialize the 2-D array of constants (rewards) for the linear equation initializeMB(); int policy1[] = new int[NUM_STATES]; do { policy1 = policy.clone(); // Set changed? to false at the start of every iteration of the do-while loop policyChanged = false; // Evaluate the current policy and update utilities policyEvaluation(); // Increment the iteration counter numIterations++; // Iterate through all states for(int s = 0; s < NUM_STATES; s++) { // Initialize an index of the 'best' action given current utilities, // and then initialize maxSum as a large negative number int bestAction = 0; double maxSum = -Double.MAX_VALUE; // Iterate through each action for(int a = 0; a < NUM_ACTIONS; a++) { // Initialize the double currSum, which will be used to // sum over the transition states given initial state and action double currSum = 0.0; // Iterate through the transition states for(int i = 0; i < NUM_STATES; i++) { // Sum over the transition states given the initial state and action currSum = currSum + (T[s][a][i] * utility[i]); } // If currSum > maxSum, update maxSum, and set // the bestAction to the current action integer (0-3) if(currSum > maxSum) { bestAction = a; maxSum = currSum; } } double policySum = 0.0; // Sum over all possibe transition states given initial state and the current policy for(int s2 = 0; s2 < NUM_STATES; s2++) { policySum = policySum + (T[s][policy[s]][s2] * utility[s2]); } // Update the policy if the maxSum > policySum, meaning that // bestAction is a better action than the current policy if(maxSum > policySum) { policy[s] = bestAction; // Set changed? to true so we know to continue // iterating through the do-while loop policyChanged = true; } } if(Arrays.equals(policy, policy1) == false) { System.out.println(numIterations); } } // Continue the execution of the do-while loop until the boolean changed? remains false, // which means the policy wasn't changed throughout the entire process (calculations, update) while(policyChanged == true); } /* initializeMB() creates the array of constants that will be used when we are solving the linear equation. The rewards are stored in a 2-D array w/ only one columm. Rewards are constatn the entire time, so this method is only called once. */ public static void initializeMB() { for(int s = 0; s < NUM_STATES; s++) { mb[s][0] = R[s]; } } /* In the policyEvaluation() method, we take the current policy, and set up a linear matrix equation with n equations and n unknowns. The equations are derived from a rearrangement of the Bellman equation. The coefficients (in this case, coefficients are the discount factor multiplied by the state transition probability with the current specified policy) associated with each utility are put into a matrix A and the constants (which are all the reward values at each state) are put into matrix B. The equation Ax = B is solved for x and all utilities are updated from the matrix x. */ public static void policyEvaluation() { // ma is the 65x65 matrix. It is a private static array so it does not need initializing // Iterate through the initial states for(int s1 = 0; s1 < NUM_STATES; s1++) { // Iterate through the transition states for(int s2 = 0; s2 < NUM_STATES; s2++) { if(s1 == s2) { // Set the entire diagonal of the matrix to 1 ma[s1][s2] = 1.0; } else { // Initialize all other values to 0 ma[s1][s2] = 0.0; } // Update the matrix according to given policy and transition probabilities ma[s1][s2] = ma[s1][s2] - (discountFactor * T[s1][policy[s1]][s2]); } } // Convert the 2-D arrays to matricies Matrix A = new Matrix(ma); Matrix B = new Matrix(mb); // Solve Ax = B and store the result in x, a 2-D array double [][] x = A.solve(B).getArray(); for(int s = 0; s < NUM_STATES; s++) { // Update the utilities according the the values stored in x utility[s] = x[s][0]; } } /* print out the current utilities and action choices for all states given the utility function and policy passed in. the utility function is specified as an array of doubles representing utilities for the states, and the policy is specified as an array of integers representing optimal actions for the states */ public static void printUtilitiesAndPolicy(double[] utility, int[] policy) { /* formateString is a C-style format string to use with Java's printf-wannabe method; the format string specifies what the output should look like, including format specifications for values, and the actual items to be printed are the arguments to printf that come after the format string. in the following, if PRINT_UTILITY_PRECISION is 2, the format string would be: "%s%2d%s %.2f %s " This means that the output will be: a string, an integer that should be printed in 2 spaces, a string, a space (spaces in the format string are printed literally), a floating-point number printed in 5 spaces with PRINT_UTILITY_PRECISION digits after the decimal point, a space, a string, and 4 spaces. The arguments that come after specify *what* string, *what* integer, etc. */ String formatString = "%s%2d%s %5." + PRINT_UTILITY_PRECISION + "f %s "; for(int s = 58 ; s <= 64 ; s += 2) System.out.printf(formatString, "(", s, ")", utility[s], "(" + action(policy[s]) + ")"); System.out.println(); for(int s = 59 ; s <= 63 ; s += 2) System.out.printf(formatString, "(", s, ")", utility[s], "(" + action(policy[s]) + ")"); System.out.println(); System.out.println(); for(int s = 50 ; s <= 56 ; s += 2) System.out.printf(formatString, "(", s, ")", utility[s], "(" + action(policy[s]) + ")"); System.out.println(); for(int s = 51 ; s <= 57 ; s += 2) System.out.printf(formatString, "(", s, ")", utility[s], "(" + action(policy[s]) + ")"); System.out.println(); System.out.println(); for(int s = 40 ; s <= 48 ; s += 2) System.out.printf(formatString, "(", s, ")", utility[s], "(" + action(policy[s]) + ")"); System.out.println(); for(int s = 41 ; s <= 49 ; s += 2) System.out.printf(formatString, "(", s, ")", utility[s], "(" + action(policy[s]) + ")"); System.out.println(); System.out.println(); for(int s = 30 ; s <= 38 ; s += 2) System.out.printf(formatString, "(", s, ")", utility[s], "(" + action(policy[s]) + ")"); System.out.println(); for(int s = 31 ; s <= 39 ; s += 2) System.out.printf(formatString, "(", s, ")", utility[s], "(" + action(policy[s]) + ")"); System.out.println(); System.out.println(); for(int s = 0 ; s <= 14 ; s += 2) { if (s < 10) System.out.printf(formatString, "(", s, ")", utility[s], "(" + action(policy[s]) + ")"); else System.out.printf(formatString, "(", s, ")", utility[s], "(" + action(policy[s]) + ")"); } System.out.println(); for(int s = 1 ; s <= 15 ; s += 2) { if (s < 10) System.out.printf(formatString, "(", s, ")", utility[s], "(" + action(policy[s]) + ")"); else System.out.printf(formatString, "(", s, ")", utility[s], "(" + action(policy[s]) + ")"); } System.out.println(); System.out.println(); System.out.println(); System.out.print(" "); for(int s = 16 ; s <= 28 ; s += 2) System.out.printf(formatString, "(", s, ")", utility[s], "(" + action(policy[s]) + ")"); System.out.println(); System.out.print(" "); for(int s = 17 ; s <= 29 ; s += 2) System.out.printf(formatString, "(", s, ")", utility[s], "(" + action(policy[s]) + ")"); System.out.println(); System.out.println(); } // printUtilitiesAndPolicy // return appropriate string given action number // public static String action(int a) { switch (a) { case N: return "N"; case E: return "E"; case S: return "S"; case W: return "W"; default: return "X"; } } // action /* initialize T, the 3-dimensional array representing the transition function, and R, the 1-dimensional array representing the reward function */ public static void initializeMDP(double[][][] T, double[] R) { /* set up reward function format = R[state] specifies reward you get given the state you're starting out in BEFORE a transition */ for(int s = 0 ; s < NUM_STATES ; ++s) R[s] = stepCost; // reset the rewards for terminal states R[44] = negativeTerminalReward; R[45] = negativeTerminalReward; R[48] = negativeTerminalReward; R[49] = negativeTerminalReward; R[28] = positiveTerminalReward; // set up transition function // format = T[state][action][state'] // initialize all transition probabilities to 0.0 for(int s1 = 0 ; s1 < NUM_STATES ; ++s1) for(int a = 0 ; a < NUM_ACTIONS ; ++a) for(int s2 = 0 ; s2 < NUM_STATES ; ++s2) T[s1][a][s2] = 0.0; // reset those transition probabilities that are NOT 0 T[0][N][0] = 0.1; T[0][N][30] = 0.8; T[0][N][2] = 0.1; T[0][E][30] = 0.1; T[0][E][2] = 0.8; T[0][E][0] = 0.1; T[0][S][2] = 0.1; T[0][S][0] = 0.9; T[0][W][0] = 0.9; T[0][W][30] = 0.1; T[1][N][1] = 0.1; T[1][N][31] = 0.8; T[1][N][3] = 0.1; T[1][E][31] = 0.1; T[1][E][3] = 0.8; T[1][E][1] = 0.1; T[1][S][3] = 0.1; T[1][S][1] = 0.9; T[1][W][1] = 0.9; T[1][W][31] = 0.1; T[2][N][0] = 0.1; T[2][N][32] = 0.8; T[2][N][4] = 0.1; T[2][E][32] = 0.1; T[2][E][4] = 0.8; T[2][E][2] = 0.1; T[2][S][4] = 0.1; T[2][S][2] = 0.8; T[2][S][0] = 0.1; T[2][W][2] = 0.1; T[2][W][0] = 0.8; T[2][W][32] = 0.1; T[3][N][1] = 0.1; T[3][N][33] = 0.8; T[3][N][5] = 0.1; T[3][E][33] = 0.1; T[3][E][5] = 0.8; T[3][E][3] = 0.1; T[3][S][5] = 0.1; T[3][S][3] = 0.8; T[3][S][1] = 0.1; T[3][W][3] = 0.1; T[3][W][1] = 0.8; T[3][W][33] = 0.1; T[4][N][2] = 0.1; T[4][N][34] = 0.8; T[4][N][6] = 0.1; T[4][E][34] = 0.1; T[4][E][6] = 0.8; T[4][E][4] = 0.1; T[4][S][6] = 0.1; T[4][S][4] = 0.8; T[4][S][2] = 0.1; T[4][W][4] = 0.1; T[4][W][2] = 0.8; T[4][W][34] = 0.1; T[5][N][3] = 0.1; T[5][N][35] = 0.8; T[5][N][7] = 0.1; T[5][E][35] = 0.1; T[5][E][7] = 0.8; T[5][E][5] = 0.1; T[5][S][7] = 0.1; T[5][S][5] = 0.8; T[5][S][3] = 0.1; T[5][W][5] = 0.1; T[5][W][3] = 0.8; T[5][W][35] = 0.1; T[6][N][4] = 0.1; T[6][N][36] = 0.8; T[6][N][8] = 0.1; T[6][E][36] = 0.1; T[6][E][8] = 0.8; T[6][E][6] = 0.1; T[6][S][8] = 0.1; T[6][S][6] = 0.8; T[6][S][4] = 0.1; T[6][W][6] = 0.1; T[6][W][4] = 0.8; T[6][W][36] = 0.1; T[7][N][5] = 0.1; T[7][N][37] = 0.8; T[7][N][9] = 0.1; T[7][E][37] = 0.1; T[7][E][9] = 0.8; T[7][E][7] = 0.1; T[7][S][9] = 0.1; T[7][S][7] = 0.8; T[7][S][5] = 0.1; T[7][W][7] = 0.1; T[7][W][5] = 0.8; T[7][W][37] = 0.1; T[8][N][6] = 0.1; T[8][N][38] = 0.8; T[8][N][10] = 0.1; T[8][E][38] = 0.1; T[8][E][10] = 0.8; T[8][E][8] = 0.1; T[8][S][10] = 0.1; T[8][S][8] = 0.8; T[8][S][6] = 0.1; T[8][W][8] = 0.1; T[8][W][6] = 0.8; T[8][W][38] = 0.1; T[9][N][7] = 0.1; T[9][N][39] = 0.8; T[9][N][11] = 0.1; T[9][E][39] = 0.1; T[9][E][11] = 0.8; T[9][E][9] = 0.1; T[9][S][11] = 0.1; T[9][S][9] = 0.8; T[9][S][7] = 0.1; T[9][W][9] = 0.1; T[9][W][7] = 0.8; T[9][W][39] = 0.1; T[10][N][8] = 0.1; T[10][N][10] = 0.8; T[10][N][12] = 0.1; T[10][E][10] = 0.2; T[10][E][12] = 0.8; T[10][S][12] = 0.1; T[10][S][10] = 0.8; T[10][S][8] = 0.1; T[10][W][10] = 0.2; T[10][W][8] = 0.8; T[11][N][9] = 0.1; T[11][N][11] = 0.8; T[11][N][13] = 0.1; T[11][E][11] = 0.2; T[11][E][13] = 0.8; T[11][S][13] = 0.1; T[11][S][11] = 0.8; T[11][S][9] = 0.1; T[11][W][11] = 0.2; T[11][W][9] = 0.8; T[12][N][10] = 0.1; T[12][N][12] = 0.8; T[12][N][14] = 0.1; T[12][E][12] = 0.2; T[12][E][14] = 0.8; T[12][S][14] = 0.1; T[12][S][12] = 0.8; T[12][S][10] = 0.1; T[12][W][12] = 0.2; T[12][W][10] = 0.8; T[13][N][11] = 0.1; T[13][N][13] = 0.8; T[13][N][15] = 0.1; T[13][E][13] = 0.2; T[13][E][15] = 0.8; T[13][S][15] = 0.1; T[13][S][13] = 0.8; T[13][S][11] = 0.1; T[13][W][13] = 0.2; T[13][W][11] = 0.8; T[14][N][12] = 0.1; T[14][N][14] = 0.8; T[14][N][16] = 0.1; T[14][E][14] = 0.2; T[14][E][16] = 0.8; T[14][S][16] = 0.1; T[14][S][14] = 0.8; T[14][S][12] = 0.1; T[14][W][14] = 0.2; T[14][W][12] = 0.8; T[15][N][13] = 0.1; T[15][N][15] = 0.8; T[15][N][17] = 0.1; T[15][E][15] = 0.2; T[15][E][17] = 0.8; T[15][S][17] = 0.1; T[15][S][15] = 0.8; T[15][S][13] = 0.1; T[15][W][15] = 0.2; T[15][W][13] = 0.8; T[16][N][14] = 0.1; T[16][N][16] = 0.8; T[16][N][18] = 0.1; T[16][E][16] = 0.2; T[16][E][18] = 0.8; T[16][S][18] = 0.1; T[16][S][16] = 0.8; T[16][S][14] = 0.1; T[16][W][16] = 0.2; T[16][W][14] = 0.8; T[17][N][15] = 0.1; T[17][N][17] = 0.8; T[17][N][19] = 0.1; T[17][E][17] = 0.2; T[17][E][19] = 0.8; T[17][S][19] = 0.1; T[17][S][17] = 0.8; T[17][S][15] = 0.1; T[17][W][17] = 0.2; T[17][W][15] = 0.8; T[18][N][16] = 0.1; T[18][N][18] = 0.8; T[18][N][20] = 0.1; T[18][E][18] = 0.2; T[18][E][20] = 0.8; T[18][S][20] = 0.1; T[18][S][18] = 0.8; T[18][S][16] = 0.1; T[18][W][18] = 0.2; T[18][W][16] = 0.8; T[19][N][17] = 0.1; T[19][N][19] = 0.8; T[19][N][21] = 0.1; T[19][E][19] = 0.2; T[19][E][21] = 0.8; T[19][S][21] = 0.1; T[19][S][19] = 0.8; T[19][S][17] = 0.1; T[19][W][19] = 0.2; T[19][W][17] = 0.8; T[20][N][18] = 0.1; T[20][N][20] = 0.8; T[20][N][22] = 0.1; T[20][E][20] = 0.2; T[20][E][22] = 0.8; T[20][S][22] = 0.1; T[20][S][20] = 0.8; T[20][S][18] = 0.1; T[20][W][20] = 0.2; T[20][W][18] = 0.8; T[21][N][19] = 0.1; T[21][N][21] = 0.8; T[21][N][23] = 0.1; T[21][E][21] = 0.2; T[21][E][23] = 0.8; T[21][S][23] = 0.1; T[21][S][21] = 0.8; T[21][S][19] = 0.1; T[21][W][21] = 0.2; T[21][W][19] = 0.8; T[22][N][20] = 0.1; T[22][N][22] = 0.8; T[22][N][24] = 0.1; T[22][E][22] = 0.2; T[22][E][24] = 0.8; T[22][S][24] = 0.1; T[22][S][22] = 0.8; T[22][S][20] = 0.1; T[22][W][22] = 0.2; T[22][W][20] = 0.8; T[23][N][21] = 0.1; T[23][N][23] = 0.8; T[23][N][25] = 0.1; T[23][E][23] = 0.2; T[23][E][25] = 0.8; T[23][S][25] = 0.1; T[23][S][23] = 0.8; T[23][S][21] = 0.1; T[23][W][23] = 0.2; T[23][W][21] = 0.8; T[24][N][22] = 0.1; T[24][N][24] = 0.8; T[24][N][26] = 0.1; T[24][E][24] = 0.2; T[24][E][26] = 0.8; T[24][S][26] = 0.1; T[24][S][24] = 0.8; T[24][S][22] = 0.1; T[24][W][24] = 0.2; T[24][W][22] = 0.8; T[25][N][23] = 0.1; T[25][N][25] = 0.8; T[25][N][27] = 0.1; T[25][E][25] = 0.2; T[25][E][27] = 0.8; T[25][S][27] = 0.1; T[25][S][25] = 0.8; T[25][S][23] = 0.1; T[25][W][25] = 0.2; T[25][W][23] = 0.8; T[26][N][24] = 0.1; T[26][N][26] = 0.8; T[26][N][28] = 0.1; T[26][E][26] = 0.2; T[26][E][28] = 0.8; T[26][S][28] = 0.1; T[26][S][26] = 0.8; T[26][S][24] = 0.1; T[26][W][26] = 0.2; T[26][W][24] = 0.8; T[27][N][25] = 0.1; T[27][N][27] = 0.8; T[27][N][29] = 0.1; T[27][E][27] = 0.2; T[27][E][29] = 0.8; T[27][S][29] = 0.1; T[27][S][27] = 0.8; T[27][S][25] = 0.1; T[27][W][27] = 0.2; T[27][W][25] = 0.8; // no transitions from states 28 and 29 T[30][N][30] = 0.1; T[30][N][40] = 0.8 * (1.0 - keyLossProbability); T[30][N][41] = 0.8 * keyLossProbability; T[30][N][32] = 0.1; T[30][E][40] = 0.1 * (1.0 - keyLossProbability); T[30][E][41] = 0.1 * keyLossProbability; T[30][E][32] = 0.8; T[30][E][0] = 0.1; T[30][S][32] = 0.1; T[30][S][0] = 0.8; T[30][S][30] = 0.1; T[30][W][0] = 0.1; T[30][W][30] = 0.8; T[30][W][40] = 0.1 * (1.0 - keyLossProbability); T[30][W][41] = 0.1 * keyLossProbability; T[31][N][31] = 0.1; T[31][N][41] = 0.8; T[31][N][33] = 0.1; T[31][E][41] = 0.1; T[31][E][33] = 0.8; T[31][E][1] = 0.1; T[31][S][33] = 0.1; T[31][S][1] = 0.8; T[31][S][31] = 0.1; T[31][W][1] = 0.1; T[31][W][31] = 0.8; T[31][W][41] = 0.1; T[32][N][30] = 0.1; T[32][N][42] = 0.8; T[32][N][34] = 0.1; T[32][E][42] = 0.1; T[32][E][34] = 0.8; T[32][E][2] = 0.1; T[32][S][34] = 0.1; T[32][S][2] = 0.8; T[32][S][30] = 0.1; T[32][W][2] = 0.1; T[32][W][30] = 0.8; T[32][W][42] = 0.1; T[33][N][31] = 0.1; T[33][N][43] = 0.8; T[33][N][35] = 0.1; T[33][E][43] = 0.1; T[33][E][35] = 0.8; T[33][E][3] = 0.1; T[33][S][35] = 0.1; T[33][S][3] = 0.8; T[33][S][31] = 0.1; T[33][W][3] = 0.1; T[33][W][31] = 0.8; T[33][W][43] = 0.1; T[34][N][32] = 0.1; T[34][N][44] = 0.8; T[34][N][36] = 0.1; T[34][E][44] = 0.1; T[34][E][36] = 0.8; T[34][E][4] = 0.1; T[34][S][36] = 0.1; T[34][S][4] = 0.8; T[34][S][32] = 0.1; T[34][W][4] = 0.1; T[34][W][32] = 0.8; T[34][W][44] = 0.1; T[35][N][33] = 0.1; T[35][N][45] = 0.8; T[35][N][37] = 0.1; T[35][E][45] = 0.1; T[35][E][37] = 0.8; T[35][E][5] = 0.1; T[35][S][37] = 0.1; T[35][S][5] = 0.8; T[35][S][33] = 0.1; T[35][W][5] = 0.1; T[35][W][33] = 0.8; T[35][W][45] = 0.1; T[36][N][34] = 0.1; T[36][N][46] = 0.8; T[36][N][38] = 0.1; T[36][E][46] = 0.1; T[36][E][38] = 0.8; T[36][E][6] = 0.1; T[36][S][38] = 0.1; T[36][S][6] = 0.8; T[36][S][34] = 0.1; T[36][W][6] = 0.1; T[36][W][34] = 0.8; T[36][W][46] = 0.1; T[37][N][35] = 0.1; T[37][N][47] = 0.8; T[37][N][39] = 0.1; T[37][E][47] = 0.1; T[37][E][39] = 0.8; T[37][E][7] = 0.1; T[37][S][39] = 0.1; T[37][S][7] = 0.8; T[37][S][35] = 0.1; T[37][W][7] = 0.1; T[37][W][35] = 0.8; T[37][W][47] = 0.1; T[38][N][36] = 0.1; T[38][N][48] = 0.8; T[38][N][38] = 0.1; T[38][E][48] = 0.1; T[38][E][38] = 0.8; T[38][E][8] = 0.1; T[38][S][38] = 0.1; T[38][S][8] = 0.8; T[38][S][36] = 0.1; T[38][W][8] = 0.1; T[38][W][36] = 0.8; T[38][W][48] = 0.1; T[39][N][37] = 0.1; T[39][N][49] = 0.8; T[39][N][39] = 0.1; T[39][E][49] = 0.1; T[39][E][39] = 0.8; T[39][E][9] = 0.1; T[39][S][39] = 0.1; T[39][S][9] = 0.8; T[39][S][37] = 0.1; T[39][W][9] = 0.1; T[39][W][37] = 0.8; T[39][W][49] = 0.1; T[40][N][40] = 0.1 * (1.0 - keyLossProbability); T[40][N][41] = 0.1 * keyLossProbability; T[40][N][50] = 0.8; T[40][N][42] = 0.1; T[40][E][50] = 0.1; T[40][E][42] = 0.8; T[40][E][30] = 0.1; T[40][S][42] = 0.1; T[40][S][30] = 0.8; T[40][S][40] = 0.1 * (1.0 - keyLossProbability); T[40][S][41] = 0.1 * keyLossProbability; T[40][W][30] = 0.1; T[40][W][40] = 0.8 * (1.0 - keyLossProbability); T[40][W][41] = 0.8 * keyLossProbability; T[40][W][50] = 0.1; T[41][N][41] = 0.1; T[41][N][51] = 0.8; T[41][N][43] = 0.1; T[41][E][51] = 0.1; T[41][E][43] = 0.8; T[41][E][31] = 0.1; T[41][S][43] = 0.1; T[41][S][31] = 0.8; T[41][S][41] = 0.1; T[41][W][31] = 0.1; T[41][W][41] = 0.8; T[41][W][51] = 0.1; T[42][N][40] = 0.1 * (1.0 - keyLossProbability); T[42][N][41] = 0.1 * keyLossProbability; T[42][N][52] = 0.8; T[42][N][44] = 0.1; T[42][E][52] = 0.1; T[42][E][44] = 0.8; T[42][E][32] = 0.1; T[42][S][44] = 0.1; T[42][S][32] = 0.8; T[42][S][40] = 0.1 * (1.0 - keyLossProbability); T[42][S][41] = 0.1 * keyLossProbability; T[42][W][32] = 0.1; T[42][W][40] = 0.8 * (1.0 - keyLossProbability); T[42][W][41] = 0.8 * keyLossProbability; T[42][W][52] = 0.1; T[43][N][41] = 0.1; T[43][N][53] = 0.8; T[43][N][45] = 0.1; T[43][E][53] = 0.1; T[43][E][45] = 0.8; T[43][E][33] = 0.1; T[43][S][45] = 0.1; T[43][S][33] = 0.8; T[43][S][41] = 0.1; T[43][W][33] = 0.1; T[43][W][41] = 0.8; T[43][W][53] = 0.1; // no transitions from states 44 and 45 T[46][N][44] = 0.1; T[46][N][56] = 0.8; T[46][N][48] = 0.1; T[46][E][56] = 0.1; T[46][E][48] = 0.8; T[46][E][36] = 0.1; T[46][S][48] = 0.1; T[46][S][36] = 0.8; T[46][S][44] = 0.1; T[46][W][36] = 0.1; T[46][W][44] = 0.8; T[46][W][56] = 0.1; T[47][N][45] = 0.1; T[47][N][57] = 0.8; T[47][N][49] = 0.1; T[47][E][57] = 0.1; T[47][E][49] = 0.8; T[47][E][37] = 0.1; T[47][S][49] = 0.1; T[47][S][37] = 0.8; T[47][S][45] = 0.1; T[47][W][37] = 0.1; T[47][W][45] = 0.8; T[47][W][57] = 0.1; // no transitions from states 48 and 49 T[50][N][50] = 0.1; T[50][N][58] = 0.8; T[50][N][52] = 0.1; T[50][E][58] = 0.1; T[50][E][52] = 0.8; T[50][E][40] = 0.1 * (1.0 - keyLossProbability); T[50][E][41] = 0.1 * keyLossProbability; T[50][S][52] = 0.1; T[50][S][40] = 0.8 * (1.0 - keyLossProbability); T[50][S][41] = 0.8 * keyLossProbability; T[50][S][50] = 0.1; T[50][W][40] = 0.1 * (1.0 - keyLossProbability); T[50][W][41] = 0.1 * keyLossProbability; T[50][W][50] = 0.8; T[50][W][58] = 0.1; T[51][N][51] = 0.1; T[51][N][59] = 0.8; T[51][N][53] = 0.1; T[51][E][59] = 0.1; T[51][E][53] = 0.8; T[51][E][41] = 0.1; T[51][S][53] = 0.1; T[51][S][41] = 0.8; T[51][S][51] = 0.1; T[51][W][41] = 0.1; T[51][W][51] = 0.8; T[51][W][59] = 0.1; T[52][N][50] = 0.1; T[52][N][60] = 0.8; T[52][N][54] = 0.1; T[52][E][60] = 0.1; T[52][E][54] = 0.8; T[52][E][42] = 0.1; T[52][S][54] = 0.1; T[52][S][42] = 0.8; T[52][S][50] = 0.1; T[52][W][42] = 0.1; T[52][W][50] = 0.8; T[52][W][60] = 0.1; T[53][N][51] = 0.1; T[53][N][61] = 0.8; T[53][N][55] = 0.1; T[53][E][61] = 0.1; T[53][E][55] = 0.8; T[53][E][43] = 0.1; T[53][S][55] = 0.1; T[53][S][43] = 0.8; T[53][S][51] = 0.1; T[53][W][43] = 0.1; T[53][W][51] = 0.8; T[53][W][61] = 0.1; T[54][N][52] = 0.1; T[54][N][62] = 0.8; T[54][N][56] = 0.1; T[54][E][62] = 0.1; T[54][E][56] = 0.8; T[54][E][44] = 0.1; T[54][S][56] = 0.1; T[54][S][44] = 0.8; T[54][S][52] = 0.1; T[54][W][44] = 0.1; T[54][W][52] = 0.8; T[54][W][62] = 0.1; T[55][N][53] = 0.1; T[55][N][63] = 0.8; T[55][N][57] = 0.1; T[55][E][63] = 0.1; T[55][E][57] = 0.8; T[55][E][45] = 0.1; T[55][S][57] = 0.1; T[55][S][45] = 0.8; T[55][S][53] = 0.1; T[55][W][45] = 0.1; T[55][W][53] = 0.8; T[55][W][63] = 0.1; T[56][N][54] = 0.1; T[56][N][64] = 0.8; T[56][N][56] = 0.1; T[56][E][64] = 0.1; T[56][E][56] = 0.8; T[56][E][46] = 0.1; T[56][S][56] = 0.1; T[56][S][46] = 0.8; T[56][S][54] = 0.1; T[56][W][46] = 0.1; T[56][W][54] = 0.8; T[56][W][64] = 0.1; T[57][N][55] = 0.1; T[57][N][64] = 0.8; T[57][N][57] = 0.1; T[57][E][64] = 0.1; T[57][E][57] = 0.8; T[57][E][47] = 0.1; T[57][S][57] = 0.1; T[57][S][47] = 0.8; T[57][S][55] = 0.1; T[57][W][47] = 0.1; T[57][W][55] = 0.8; T[57][W][64] = 0.1; T[58][N][58] = 0.9; T[58][N][60] = 0.1; T[58][E][58] = 0.1; T[58][E][60] = 0.8; T[58][E][50] = 0.1; T[58][S][60] = 0.1; T[58][S][50] = 0.8; T[58][S][58] = 0.1; T[58][W][50] = 0.1; T[58][W][58] = 0.9; T[59][N][59] = 0.9; T[59][N][61] = 0.1; T[59][E][59] = 0.1; T[59][E][61] = 0.8; T[59][E][51] = 0.1; T[59][S][61] = 0.1; T[59][S][51] = 0.8; T[59][S][59] = 0.1; T[59][W][51] = 0.1; T[59][W][59] = 0.9; T[60][N][58] = 0.1; T[60][N][60] = 0.8; T[60][N][62] = 0.1; T[60][E][60] = 0.1; T[60][E][62] = 0.8; T[60][E][52] = 0.1; T[60][S][62] = 0.1; T[60][S][52] = 0.8; T[60][S][58] = 0.1; T[60][W][52] = 0.1; T[60][W][58] = 0.8; T[60][W][60] = 0.1; T[61][N][59] = 0.1; T[61][N][61] = 0.8; T[61][N][63] = 0.1; T[61][E][61] = 0.1; T[61][E][63] = 0.8; T[61][E][53] = 0.1; T[61][S][63] = 0.1; T[61][S][53] = 0.8; T[61][S][59] = 0.1; T[61][W][53] = 0.1; T[61][W][59] = 0.8; T[61][W][61] = 0.1; T[62][N][60] = 0.1; T[62][N][62] = 0.8; T[62][N][64] = 0.1; T[62][E][62] = 0.1; T[62][E][64] = 0.8; T[62][E][54] = 0.1; T[62][S][64] = 0.1; T[62][S][54] = 0.8; T[62][S][60] = 0.1; T[62][W][54] = 0.1; T[62][W][60] = 0.8; T[62][W][62] = 0.1; T[63][N][61] = 0.1; T[63][N][63] = 0.8; T[63][N][64] = 0.1; T[63][E][63] = 0.1; T[63][E][64] = 0.8; T[63][E][55] = 0.1; T[63][S][64] = 0.1; T[63][S][55] = 0.8; T[63][S][61] = 0.1; T[63][W][55] = 0.1; T[63][W][61] = 0.8; T[63][W][63] = 0.1; T[64][N][62] = 0.1; T[64][N][64] = 0.9; T[64][E][64] = 0.9; T[64][E][56] = 0.1; T[64][S][64] = 0.1; T[64][S][56] = 0.8; T[64][S][62] = 0.1; T[64][W][56] = 0.1; T[64][W][62] = 0.8; T[64][W][64] = 0.1; } // initMDP }
package com.tecsup.cps.lab02b_git; public class Vista { int cla; int ga; }
package zhuoxin.com.viewpagerdemo.activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.Switch; import zhuoxin.com.viewpagerdemo.R; import zhuoxin.com.viewpagerdemo.utils.MyNotification; import zhuoxin.com.viewpagerdemo.utils.sharedAuto; public class SettingActivity extends AppCompatActivity implements View.OnClickListener { private Switch s_auto; private Switch s_tz; private Toolbar toolbar; private static Boolean flag, flag1; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setting); initView(); } private void initView() { s_auto = (Switch) findViewById(R.id.setting_sw_auto); s_tz= (Switch) findViewById(R.id.setting_sw_tz); toolbar = (Toolbar) findViewById(R.id.setting_toolBar); toolbar.setTitle(""); toolbar.setNavigationIcon(R.drawable.btn_return); toolbar.setNavigationOnClickListener(new View.OnClickListener() { public void onClick(View view) { finish(); } }); flag = sharedAuto.get(this, "s_auto"); flag1 = sharedAuto.get(this, "s_tz"); s_auto.setChecked(flag); s_tz.setChecked(flag1); s_auto.setOnClickListener(this); s_tz.setOnClickListener(this); } public void onClick(View view) { switch (view.getId()) { case R.id.setting_sw_auto: Log.i("AAA","sw_auto"); flag = !flag; s_auto.setChecked(flag); sharedAuto.save(this, "s_auto", flag); break; case R.id.setting_sw_tz: Log.i("AAA","sw_tz"); flag1 = !flag1; s_tz.setChecked(flag1); sharedAuto.save(this, "s_tz", flag1); if (flag1) { Log.i("AAA","sw_tz+yes"); MyNotification.openNotification(this); } else { Log.i("AAA","sw_tz_no"); MyNotification.closeNotification(this); } break; } } }
package com.g74.rollersplat.viewer.game; import com.g74.rollersplat.viewer.gui.GUI; import com.g74.rollersplat.model.elements.Element; public class PlayerViewer implements ElementViewer { public void drawElement(Element player, GUI gui) { gui.drawPlayer(player.getPosition()); } }
public class Third extends Declension { Third() { name="Third"; Behavior= (BetterBehavior) new notCom(); Behavior2= (BestBehavior) new notSup(); } public static void isGenderT() { System.out.println("Third Declension"); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println(Runner.input.substring(0,Runner.input.length()-2)+Runner.input.substring(Runner.input.length()-2)+ " "+Runner.root+"es"); System.out.println(Runner.root+"is"+ " "+Runner.root+"um"); System.out.println(Runner.root+"i"+ " "+Runner.root+"ibus"); System.out.println(Runner.root+"em"+ " "+Runner.root+"es"); System.out.println(Runner.root+"e"+ " "+Runner.root+"ibus"); } public static void isNeuterT() { System.out.println("Third Declension Neuter"); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println(Runner.input.substring(0,Runner.input.length()-2)+Runner.input.substring(Runner.input.length()-2)+ " "+Runner.root+"a"); System.out.println(Runner.root+"is"+ " "+Runner.root+"um"); System.out.println(Runner.root+"i"+ " "+Runner.root+"ibus"); System.out.println(Runner.input.substring(0,Runner.input.length()-2)+Runner.input.substring(Runner.input.length()-2)+ " "+Runner.root+"a"); System.out.println(Runner.root+"e"+ " "+Runner.root+"ibus"); } }
package pl.manufacturer.object.example.pojo.extended; import pl.manufacturer.object.example.pojo.simple.SimpleBooleanObject; import pl.manufacturer.object.example.pojo.simple.SimpleStringObject; public class ExtendedBooleanStringObject { private String simpleString; private Boolean simpleBoolean; private SimpleStringObject simpleStringObject; private SimpleBooleanObject simpleBooleanObject; public String getSimpleString() { return simpleString; } public void setSimpleString(String simpleString) { this.simpleString = simpleString; } public Boolean getSimpleBoolean() { return simpleBoolean; } public void setSimpleBoolean(Boolean simpleBoolean) { this.simpleBoolean = simpleBoolean; } public SimpleStringObject getSimpleStringObject() { return simpleStringObject; } public void setSimpleStringObject(SimpleStringObject simpleStringObject) { this.simpleStringObject = simpleStringObject; } public SimpleBooleanObject getSimpleBooleanObject() { return simpleBooleanObject; } public void setSimpleBooleanObject(SimpleBooleanObject simpleBooleanObject) { this.simpleBooleanObject = simpleBooleanObject; } }
package dao; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import hibernate.HibernateUtil; import model.Team; import sun.tools.jar.Main; public class TeamDAO implements TeamInterface{ private Session session; private Transaction transaction; public void openSession() { session = HibernateUtil.getSessionFactory().openSession(); } public void openSessionWithBeginTransaction() { session = HibernateUtil.getSessionFactory().openSession(); transaction = session.beginTransaction(); } public void commit() { transaction.commit(); } public void rollback() { transaction.rollback(); } public void closeSession () { session.close(); } @Override public Team FindTeam(String teamName) { try { openSession(); Team team = (Team)session.get(Team.class, teamName); return team; } catch (HibernateException e) { System.out.println("Failed when to Find Team!"); e.printStackTrace(); } finally { closeSession(); } return null; } @Override public void deleteTeam(Team team) { // TODO Auto-generated method stub } @Override public void insertTeam(Team team) { try { openSessionWithBeginTransaction(); session.saveOrUpdate(team); commit(); } catch (HibernateException e) { System.out.println("Failed when to insert Address Lookup!"); e.printStackTrace(); rollback(); } finally { closeSession(); } } @Override public List<Team> getAllTeam() { try { openSession();; @SuppressWarnings("unchecked") List<Team> team = session.createCriteria(Team.class).list(); return team; } catch (HibernateException e) { System.out.println("Failed when to get list Address Lookup!"); e.printStackTrace(); rollback(); } finally { closeSession(); } return null; } public List<Team> getTeam(){ try { openSession();; @SuppressWarnings("unchecked") List<Team> team = session.createCriteria(Team.class) .add(Restrictions.eq("status", true)).list(); return team; } catch (HibernateException e) { System.out.println("Failed when to get list Address Lookup!"); e.printStackTrace(); rollback(); } finally { closeSession(); } return null; } @Override public void updateTeam(Team team) { try { openSessionWithBeginTransaction(); Team oldTeam = (Team)session.get(Team.class, team.getTeamName()); oldTeam.setTeamName(team.getTeamName()); oldTeam.setShortDes(team.getShortDes()); oldTeam.setLeadContact(team.getLeadContact()); oldTeam.setAddress(team.getAddress()); oldTeam.setStatus(team.isStatus()); oldTeam.setPostCode(team.getPostCode()); oldTeam.setTown(team.getTown()); oldTeam.setCounty(team.getCounty()); oldTeam.setNation(team.getNation()); oldTeam.setTypeOfBu(team.getTypeOfBu()); oldTeam.setSicCode(team.getSicCode()); oldTeam.setFullDes(team.getFullDes()); oldTeam.setPhone(team.getPhone()); oldTeam.setFax(team.getFax()); oldTeam.setMail(team.getMail()); oldTeam.setWA(team.getWA()); commit(); } catch (Exception e) { try { session.saveOrUpdate(team); commit(); } catch (Exception e2) { System.out.println("Failed when to insert Address Lookup!"); e2.printStackTrace(); rollback(); } } finally { closeSession(); } } public static void main(String[] args) { TeamDAO dao = new TeamDAO(); // dao.insertTeam(new Team("cu sen", "mau trang", "ngon")); Team team = new Team("cu sen", "mau trang trang", "ngon"); dao.updateTeam(team); List<Team> list =dao.getAllTeam(); for (Team string : list) { System.out.println(string.getTeamName() + "lead"+ string.getLeadContact()); } } }
package com.skp.test.greedy; import static org.junit.Assert.assertEquals; import java.util.Map; import org.junit.Test; public class GreedyTest { @Test public void test() { Greedy sut = new Greedy(); Map<Integer, Integer> changes = sut.buy(2000, 10000); assertEquals(changes.get(5000).intValue(), 1); assertEquals(changes.get(1000).intValue(), 3); } }
package com.trump.auction.back.rule.service; import com.cf.common.util.page.Paging; import com.trump.auction.back.product.vo.ParamVo; import com.trump.auction.back.rule.model.AuctionRule; import java.util.List; import java.util.Map; /** * ็ซžๆ‹่ง„ๅˆ™็ฎก็† * * @author zhangliyan * @create 2018-01-03 14:59 **/ public interface AuctionRuleService { /** * ๅˆ†้กตๆŸฅ่ฏข่ง„ๅˆ™ๅˆ—่กจ * @param params * @return */ Paging<AuctionRule> findAuctionRulePage(ParamVo paramVo); /** * ๆŸฅ่ฏข * @return */ List<AuctionRule> findAuctionRuleList(); /** * ๆ นๆฎidๆŸฅ่ฏข่ง„ๅˆ™ๅˆ—่กจ * @param id * @return */ AuctionRule findAuctionRuleById(Integer id); /** * ่Žทๅ–id * @param id * @return */ AuctionRule getAuctionRule(Integer id); /** * ๆ นๆฎidๆŸฅ่ฏข * @param ruleId * @return */ AuctionRule queryRuleById(int ruleId); }
package com.leyton.flow.activator.imple; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.integration.annotation.MessageEndpoint; import org.springframework.integration.annotation.ServiceActivator; import org.springframework.messaging.Message; import com.leyton.flow.activator.inter.CustomActivator; @MessageEndpoint public class CustomActivatorImp implements CustomActivator { private static final Logger LOGGER = LoggerFactory.getLogger(CustomActivatorImp.class); @Override @ServiceActivator( inputChannel = "endChannel") public void print(Message<Integer> message) { LOGGER.info("PAYLOAD: [{}], HEADERS: [{}]", message.getPayload(), message.getHeaders()); } }
class Solution { public int numJewelsInStones(String J, String S) { int count = 0; for(int i =0; i < J.length(); i++) { char ch = J.charAt(i); for(int j =0; j < S.length(); j++) { if (ch == S.charAt(j)) { count++; } } } return count; } }
package com.example.administrator.panda_channel_app.Activity; import android.content.Intent; import android.view.View; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.administrator.panda_channel_app.MVP_Framework.base.BaseActivity; import com.example.administrator.panda_channel_app.R; import com.umeng.socialize.ShareAction; import com.umeng.socialize.UMShareListener; import com.umeng.socialize.bean.SHARE_MEDIA; import com.umeng.socialize.media.UMImage; import com.umeng.socialize.utils.Log; import butterknife.BindView; import butterknife.OnClick; /** * Created by Administrator on 2017/7/15 0015. */ public class WebviewActivity extends BaseActivity { @BindView(R.id.activity_webview) WebView activityWebview; @BindView(R.id.home_webview_back) ImageView homeWebviewBack; @BindView(R.id.home_webview_share) ImageView homeWebviewShare; @BindView(R.id.home_webview_title) TextView homeWebviewTitle; private WebSettings settings; private String stringurl; @Override protected void initView() { settings = activityWebview.getSettings(); stringurl = getIntent().getStringExtra("url"); Intent intent = getIntent(); String title = intent.getStringExtra("title"); homeWebviewTitle.setText(title); // ๅฏไปฅไธŽไป€ไนˆไบคไบ’ settings.setJavaScriptEnabled(true); // ๅฐ†ๅ›พ็‰‡ๆŽงๅˆถๅˆฐ้€‚ๅˆwebview็š„ๅคงๅฐ settings.setUseWideViewPort(true); // ็ผฉๆ”พ่‡ณๅฑๅน•ๅคงๅฐ settings.setLoadWithOverviewMode(true); activityWebview.loadUrl(stringurl); } @Override protected int getLayoutId() { return R.layout.webviewactivity; } @OnClick({R.id.home_webview_back, R.id.home_webview_share}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.home_webview_back: finish(); break; case R.id.home_webview_share: UMImage image = new UMImage(WebviewActivity.this,R.mipmap.about_sign); new ShareAction(WebviewActivity.this).setDisplayList(SHARE_MEDIA.SINA, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.FACEBOOK, SHARE_MEDIA.TWITTER) .withText(homeWebviewTitle.getText().toString()+stringurl) .withMedia(image) .setCallback(new UMShareListener() { @Override public void onStart(SHARE_MEDIA share_media) { Log.e("TAG", share_media.toString()); } @Override public void onResult(SHARE_MEDIA share_media) { Log.d("share_media", "share_media" + share_media); Toast.makeText(WebviewActivity.this, share_media + " ๅˆ†ไบซๆˆๅŠŸๅ•ฆ", Toast.LENGTH_SHORT).show(); } @Override public void onError(SHARE_MEDIA share_media, Throwable throwable) { Toast.makeText(WebviewActivity.this, share_media + " ๅˆ†ไบซๅคฑ่ดฅๅ•ฆ", Toast.LENGTH_SHORT).show(); if (throwable != null) { Log.d("throw", "throw:" + throwable.getMessage()); } } @Override public void onCancel(SHARE_MEDIA share_media) { Toast.makeText(WebviewActivity.this, share_media + " ๅˆ†ไบซๅ–ๆถˆไบ†", Toast.LENGTH_SHORT).show(); } }) .open(); break; } } }
/** * COPYRIGHT (C) 2013 KonyLabs. All Rights Reserved. * * @author rbanking */ package com.classroom.services.facade.dto.entities; import java.util.UUID; import javax.xml.bind.annotation.XmlRootElement; import com.classroom.services.facade.dto.IUserDependent; /** * Transfer object for user detail information * * JSON example: * * <pre> * { "firstName":"first name", * "middleName":"middle name", * "lastName":"last name", * "primaryPhone":"phone number", * "mobilePhone":"phone number", * "homePhone":"phone number", * "workPhone":"phone number", * "fax":"phone number", * "gender":"male", * "uniqueId":"unique identifier", * "userId":"user id"} * </pre> * * XML example: * * <pre> * {@code * <detail> * <firstName> * first name * </firstName> * <middleName> * middle name * </middleName> * <lastName> * last name * </lastName> * <primaryPhone> * phone number * </primaryPhone> * <mobilePhone> * phone number * </mobilePhone> * <homePhone> * phone number * </homePhone> * <workPhone> * phone number * </workPhone> * <fax> * phone number * </fax> * <gender> * male * </gender> * <uniqueId> * unique identifier * </uniqueId> * <userId> * user id * </userId> * </detail> * } * </pre> */ @XmlRootElement(name = "detail") public class UserDetailDTO implements IUserDependent { private String firstName; private String middleName; private String lastName; private String primaryPhone; private String mobilePhone; private String homePhone; private String workPhone; private String fax; private String gender; private String uniqueId; private UUID userId; /** * The Constructor. */ public UserDetailDTO() { } /** * The Constructor. * * @param firstName * the first name * @param middleName * the middle name * @param lastName * the last name * @param primaryPhone * the primary phone * @param mobilePhone * the mobile phone * @param homePhone * the home phone * @param workPhone * the work phone * @param fax * the fax * @param gender * the gender * @param uniqueId * the unique id * @param userId * the user id */ public UserDetailDTO(String firstName, String middleName, String lastName, String primaryPhone, String mobilePhone, String homePhone, String workPhone, String fax, String gender, String uniqueId, UUID userId) { this.firstName = firstName; this.middleName = middleName; this.lastName = lastName; this.primaryPhone = primaryPhone; this.mobilePhone = mobilePhone; this.homePhone = homePhone; this.workPhone = workPhone; this.fax = fax; this.gender = gender; this.uniqueId = uniqueId; this.userId = userId; } /** * Gets the first name. * * @return the first name */ public String getFirstName() { return firstName; } /** * Sets the first name. * * @param firstName * the first name */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * Gets the middle name. * * @return the middle name */ public String getMiddleName() { return middleName; } /** * Sets the middle name. * * @param middleName * the middle name */ public void setMiddleName(String middleName) { this.middleName = middleName; } /** * Gets the last name. * * @return the last name */ public String getLastName() { return lastName; } /** * Sets the last name. * * @param lastName * the last name */ public void setLastName(String lastName) { this.lastName = lastName; } /** * Gets the primary phone. * * @return the primary phone */ public String getPrimaryPhone() { return primaryPhone; } /** * Sets the primary phone. * * @param primaryPhone * the primary phone */ public void setPrimaryPhone(String primaryPhone) { this.primaryPhone = primaryPhone; } /** * Gets the mobile phone. * * @return the mobile phone */ public String getMobilePhone() { return mobilePhone; } /** * Sets the mobile phone. * * @param mobilePhone * the mobile phone */ public void setMobilePhone(String mobilePhone) { this.mobilePhone = mobilePhone; } /** * Gets the home phone. * * @return the home phone */ public String getHomePhone() { return homePhone; } /** * Sets the home phone. * * @param homePhone * the home phone */ public void setHomePhone(String homePhone) { this.homePhone = homePhone; } /** * Gets the work phone. * * @return the work phone */ public String getWorkPhone() { return workPhone; } /** * Sets the work phone. * * @param workPhone * the work phone */ public void setWorkPhone(String workPhone) { this.workPhone = workPhone; } /** * Gets the fax. * * @return the fax */ public String getFax() { return fax; } /** * Sets the fax. * * @param fax * the fax */ public void setFax(String fax) { this.fax = fax; } /* * (non-Javadoc) * * @see com.classroom.services.facade.dto.IUserDependent#getUserId() */ public UUID getUserId() { return userId; } /** * Sets the user id. * * @param userId * the user id */ public void setUserId(UUID userId) { this.userId = userId; } /** * Gets the gender. * * @return the gender */ public String getGender() { return gender; } /** * Sets the gender. * * @param gender * the gender */ public void setGender(String gender) { this.gender = gender; } /** * Gets the unique id. * * @return the unique id */ public String getUniqueId() { return uniqueId; } /** * Sets the unique id. * * @param uniqueId * the unique id */ public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } }
package it.sevenbits.codecorrector.formatter.javaformatter; /** * Created by remmele on 05.07.16. */ public enum State { Word, Space, NewLine, EndLine }
package net.awesomekorean.podo.lesson.lessons; import net.awesomekorean.podo.R; import java.io.Serializable; public class Lesson20 extends LessonInit_Lock implements Lesson, LessonItem, Serializable { private String lessonId = "L_20"; private String lessonTitle = "wish"; private String lessonSubTitle = "~์•˜/์—ˆ์œผ๋ฉด ์ข‹๊ฒ ์–ด์š”"; private LessonItem specialLesson = new S_Lesson13(); private String[] wordFront = {"๋ฅ๋‹ค", "์‹œ์›ํ•˜๋‹ค", "๊ณณ", "๋“ค์–ด๊ฐ€๋‹ค", "์ €๊ธฐ", "ํฌ๋‹ค", "์˜ˆ์˜๋‹ค", "์œ ๋ช…ํ•˜๋‹ค", "๋งˆ์‹œ๋‹ค"}; private String[] wordBack = {"hot", "cool", "place", "enter", "there", "big", "pretty", "famous", "drink"}; private String[] wordPronunciation = {"[๋ฅ๋”ฐ]", "-", "[๊ณง]", "[๋“œ๋Ÿฌ๊ฐ€๋‹ค]", "-", "-", "-", "-", "-"}; private String[] sentenceFront = { "๋„ˆ๋ฌด ๋”์›Œ์š”.", "์—ฌ๊ธฐ ๋„ˆ๋ฌด ๋”์›Œ์š”.", "๋“ค์–ด๊ฐ”์œผ๋ฉด ์ข‹๊ฒ ์–ด์š”.", "์‹œ์›ํ•œ ๊ณณ์— ๋“ค์–ด๊ฐ”์œผ๋ฉด ์ข‹๊ฒ ์–ด์š”.", "ํฐ ์‡ผํ•‘๋ชฐ", "ํฐ ์‡ผํ•‘๋ชฐ์— ๋“ค์–ด๊ฐ€์š”.", "์ €๊ธฐ ํฐ ์‡ผํ•‘๋ชฐ์— ๋“ค์–ด๊ฐ€์š”.", "์œ ๋ช…ํ•œ ์นดํŽ˜", "์˜ˆ์˜๊ณ  ์œ ๋ช…ํ•œ ์นดํŽ˜", "์˜ˆ์˜๊ณ  ์œ ๋ช…ํ•œ ์นดํŽ˜๊ฐ€ ์žˆ์–ด์š”.", "๊ฑฐ๊ธฐ์— ์˜ˆ์˜๊ณ  ์œ ๋ช…ํ•œ ์นดํŽ˜๊ฐ€ ์žˆ์–ด์š”.", "์‹œ์›ํ•œ ์ฃผ์Šค", "์‹œ์›ํ•œ ์ฃผ์Šค ๋งˆ์…”์š”.", "๊ฑฐ๊ธฐ์—์„œ ์‹œ์›ํ•œ ์ฃผ์Šค ๋งˆ์…”์š”.", "์ข‹์•„์š”. ๊ฑฐ๊ธฐ์—์„œ ์‹œ์›ํ•œ ์ฃผ์Šค ๋งˆ์…”์š”." }; private String[] sentenceBack = { "It's too hot.", "It's too hot here.", "I want to go inside.", "I want to go to a cool place.", "big shopping mall", "Let's go into the big shopping mall.", "Let's go into the big shopping mall there.", "famous cafe", "pretty and famous cafe", "There's a pretty and famous cafe.", "There's a pretty and famous cafe.", "cold juice", "Let's drink a cold juice.", "Let's drink a cold juice there.", "Great. Let's drink a cold juice there." }; private String[] sentenceExplain = { "'๋ฅ๋‹ค' -> '๋ฅ์–ด์š”' -> '๋”์›Œ์š”' (irregular)", "-", "conjugate 'V-์•˜/์—ˆ์œผ๋ฉด ์ข‹๊ฒ ์–ด์š”'\n'๋“ค์–ด๊ฐ€๋‹ค' -> '๋“ค์–ด๊ฐ”๋‹ค'\n'๋“ค์–ด๊ฐ”๋‹ค' -> '๋“ค์–ด๊ฐ”' + '์œผ๋ฉด ์ข‹๊ฒ ์–ด์š”' = '๋“ค์–ด๊ฐ”์œผ๋ฉด ์ข‹๊ฒ ์–ด์š”'", "We can use 'A-(์œผ)ใ„ด' form when the adjective modifies a noun.\n'์‹œ์›ํ•˜๋‹ค' -> '์‹œ์›ํ•˜' + 'ใ„ด' = '์‹œ์›ํ•œ'", "-", "-", "-", "'์œ ๋ช…ํ•˜๋‹ค' -> '์œ ๋ช…ํ•˜' + 'ใ„ด' = '์œ ๋ช…ํ•œ'", "'~๊ณ ' form is used.", "-", "'์—ฌ๊ธฐ' : here\n'์ €๊ธฐ' : there\n'๊ฑฐ๊ธฐ' : there", "'์‹œ์›ํ•˜๋‹ค' -> '์‹œ์›ํ•˜' + 'ใ„ด' = '์‹œ์›ํ•œ'", "-", "-", "-" }; private String[] dialog = { "์—ฌ๊ธฐ ๋„ˆ๋ฌด ๋”์›Œ์š”. \n ์‹œ์›ํ•œ ๊ณณ์— ๋“ค์–ด๊ฐ”์œผ๋ฉด ์ข‹๊ฒ ์–ด์š”.", "์ €๊ธฐ ํฐ ์‡ผํ•‘๋ชฐ์— ๋“ค์–ด๊ฐ€์š”. \n ๊ฑฐ๊ธฐ์— ์˜ˆ์˜๊ณ  ์œ ๋ช…ํ•œ ์นดํŽ˜๊ฐ€ ์žˆ์–ด์š”.", "์ข‹์•„์š”. \n ๊ฑฐ๊ธฐ์—์„œ ์‹œ์›ํ•œ ์ฃผ์Šค ๋งˆ์…”์š”." }; private int[] peopleImage = {R.drawable.male_b,R.drawable.female_p}; private int[] reviewId = {3,10}; @Override public String getLessonSubTitle() { return lessonSubTitle; } @Override public String getLessonId() { return lessonId; } @Override public String[] getWordFront() { return wordFront; } @Override public String[] getWordPronunciation() { return wordPronunciation; } @Override public String[] getSentenceFront() { return sentenceFront; } @Override public String[] getDialog() { return dialog; } @Override public int[] getPeopleImage() { return peopleImage; } @Override public String[] getWordBack() { return wordBack; } @Override public String[] getSentenceBack() { return sentenceBack; } @Override public String[] getSentenceExplain() { return sentenceExplain; } @Override public int[] getReviewId() { return reviewId; } // ๋ ˆ์Šจ์–ด๋ށํ„ฐ ์•„์ดํ…œ @Override public String getLessonTitle() { return lessonTitle; } @Override public LessonItem getSLesson() { return specialLesson; } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.test.context.env; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.io.support.PropertySourceFactory; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link TestPropertySource @TestPropertySource} support * with a custom YAML {@link PropertySourceFactory}. * * @author Sam Brannen * @since 6.1 */ @SpringJUnitConfig @YamlTestProperties("test-properties.yaml") class YamlTestPropertySourceTests { @ParameterizedTest @CsvSource(delimiterString = "->", textBlock = """ environments.dev.url -> https://dev.example.com environments.dev.name -> 'Developer Setup' environments.prod.url -> https://prod.example.com environments.prod.name -> 'My Cool App' """) void propertyIsAvailableInEnvironment(String property, String value, @Autowired ConfigurableEnvironment env) { assertThat(env.getProperty(property)).isEqualTo(value); } @Configuration static class Config { /* no user beans required for these tests */ } }