text
stringlengths
10
2.72M
package edu.mit.cci.simulation.client.comm; import edu.mit.cci.simulation.client.Scenario; import edu.mit.cci.simulation.client.Simulation; import edu.mit.cci.simulation.client.Tuple; import edu.mit.cci.simulation.client.TupleStatus; import edu.mit.cci.simulation.client.Variable; import org.junit.Assert; import org.junit.Test; import javax.persistence.TupleElement; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * User: jintrone * Date: 3/21/11 * Time: 1:13 AM */ /** * Note that these tests depend upon specific db configuration; * * @TODO create necessary DB configuration scripts to isolate test */ public class TestLiveService { @Test public void testPangaea() throws IOException, MetaDataNotFoundException, ScenarioNotFoundException, ModelNotFoundException { ClientRepository repo = ClientRepository.instance("localhost",8080); Simulation sim = repo.getSimulation(1L); Assert.assertNotNull(sim); Map<String, Object> inputs = new HashMap<String, Object>(); //developed inputs.put("Developed start year", "2012"); //start year inputs.put("Developed target year", "2050"); //target year inputs.put("Pct change in Developed FF emissions", "200"); //target //developing a inputs.put("Developing A start year", "2012"); inputs.put("Developing A target year", "2050"); inputs.put("Pct change in Developing A FF emissions", "200"); //developing b inputs.put("Developing B start year", "2012"); inputs.put("Developing B target year", "2050"); inputs.put("Pct change in Developing B FF emissions", "200"); inputs.put("Target Sequestration", "0.50"); //sequestration (afforestation) inputs.put("Global land use emissions change", "0.50"); //deforestation Scenario scenario = repo.runModelWithInputNames(sim, inputs, 546L, true); Assert.assertNotNull(scenario); } @Test public void testErrorScenario() throws IOException, MetaDataNotFoundException, ScenarioNotFoundException, ModelNotFoundException { ClientRepository repo = ClientRepository.instance("localhost",8080); Scenario scenario = repo.getScenario(25L); Variable var = null; for (Variable v:scenario.getOutputSet()) { if (v.getMetaData().getId() == 12L) { var = v; break; } } assert var != null; for (Tuple t:var.getValue()) { Assert.assertTrue(t.getStatus(1).equals(TupleStatus.OUT_OF_RANGE)); } } @Test public void testDOEModel() throws IOException, MetaDataNotFoundException, ScenarioNotFoundException, ModelNotFoundException { ClientRepository repo = ClientRepository.instance("localhost",8080); Simulation sim = repo.getSimulation(18L); Assert.assertNotNull(sim); Map<String, Object> inputs = new HashMap<String, Object>(); inputs.put("Coal-based_electricity_in_2050","48"); inputs.put("Natural_gas-based_electricity_in_2050","99"); inputs.put("Nuclear_electricity_in_2050","16"); inputs.put("Renewable_electricity_in_2050","14"); inputs.put("Share_of_fossil_CCS_in_2050","2"); inputs.put("Industry_energy_effeciency_increase_by_2050","43"); inputs.put("Low_carbon_fuel_mix_in_2050","50"); inputs.put("Biomass_feedstock_in_2050","50"); inputs.put("New_building_improvements_by_2030","75"); inputs.put("Residential_building_retrofits_by_2050","100"); inputs.put("Retrofit_improvements_in_2050","12"); inputs.put("Appliance_and_equipment_efficicency_increase_by_2050","52"); inputs.put("Electrification_share_of_heating_and_cooking_in_2050","91"); inputs.put("LDV_fleet_MPG_in_2050","36"); inputs.put("Non-LDV_efficiency_improvements_by_2050","0"); inputs.put("Biofuels_production_in_2050","50"); inputs.put("LDV_miles_travelled_in_2050","9600"); Scenario scenario = repo.runModelWithInputNames(sim, inputs, 546L, true); Assert.assertNotNull(scenario); System.err.println("----------INPUTS-----------"); for (Variable v:scenario.getInputSet()) { System.err.println(v.getMetaData().getName()+":"+createValueString(v.getValue())); } System.err.println("----------OUTPUTS-----------"); for (Variable v:scenario.getOutputSet()) { System.err.println(v.getMetaData().getName()+":"+createValueString(v.getValue())); }; } public static String createValueString(List<Tuple> values) { StringBuilder builder = new StringBuilder(); for (Tuple t:values) { builder.append("["); for (String v:t.getValues()) { builder.append(v).append(";"); } builder.append("]"); } return builder.toString(); } // @Test // public void testRepositoryRetrieval_Simulations() throws IOException { // ClientRepository repo = ClientRepository.instance("localhost", 8080); // Collection<Simulation> sims = repo.getAllSimulations(); // log.info("Retrieved " + sims.size() + " simulations:"); // for (Simulation sim : sims) { // log.info(sim.getName()); // StringBuffer buf = new StringBuffer(); // buf.append("-- Inputs\n"); // for (MetaData md : sim.getInputs()) { // buf.append("---- ").append(md.getId()).append(":").append(md.getName()).append(" - ").append(md.getDescription()); // buf.append("\n"); // } // log.info(buf.toString()); // buf = new StringBuffer(); // buf.append("-- Outputs\n"); // for (MetaData md : sim.getOutputs()) { // buf.append("---- ").append(md.getId()).append(":").append(md.getName()).append(" - ").append(md.getDescription()); // buf.append(" : isIndex - ").append(md.getIndex()); // buf.append(" : indexingmd - "+(md.getIndexingMetaData()!=null?md.getIndexingMetaData().getId():"<none>")); // // buf.append("\n"); // } // buf.append("\n"); // log.info(buf); // } // // } // // @Test // public void testRepositoryRetrieval_Scenario() throws IOException { // ClientRepository repo = ClientRepository.instance("localhost", 8080); // // Scenario s = repo.getScenario(2703l); // Assert.assertNotNull(s); // log.info("Scenario: " + s.getName()); // log.info(getScenarioString(s)); // // } // // // @Test // public void testCompositeModelRun() throws IOException, ScenarioNotFoundException, ModelNotFoundException, MetaDataNotFoundException { // ClientRepository repo = ClientRepository.instance("localhost", 8080); // Scenario scenario = TestHelper.runCompositeOne(repo); // log.info("Scenario: "+scenario.getName()+" id:"+scenario.getId()); // log.info(getScenarioString(scenario)); // Assert.assertEquals(EntityState.TEMPORARY,scenario.getState()); // // } // @Test // public void testCompositeModelRun2() throws IOException, ScenarioNotFoundException, ModelNotFoundException, MetaDataNotFoundException { // ClientRepository repo = ClientRepository.instance("localhost", 8080); // Scenario scenario = TestHelper.runCompositeTwo(repo); // log.info("Scenario: "+scenario.getName()+" id:"+scenario.getId()); // log.info(getScenarioString(scenario)); // Assert.assertEquals(EntityState.TEMPORARY,scenario.getState()); // // } // // @Test // public void testTypeField() throws IOException { // ClientRepository repo = ClientRepository.instance("localhost", 8080); // Collection<Simulation> sims = repo.getAllSimulations(); // log.info("Retrieved " + sims.size() + " simulations:"); // for (Simulation s:repo.getAllSimulations()) { // log.info("Retrieved: "+s.getName()+" - "+s.getId()); // } // Simulation sim = repo.getSimulation(920L); // Assert.assertNotNull(sim); // Assert.assertEquals("test test",sim.getType()); // } // @Test // public void testModelUpdate() throws IOException, ScenarioNotFoundException, ModelNotFoundException { // ClientRepository repo = ClientRepository.instance("localhost", 8080); // Simulation s = repo.getSimulation(621L); // String name = s.getName(); // s.setName("fooey"); // repo.updateSimulation(s); // // s = repo.getSimulation(621L); // Assert.assertEquals("fooey",s.getName()); // // s.setName(name); // repo.updateSimulation(s); // // s = repo.getSimulation(621L); // Assert.assertEquals(name,s.getName()); // // } // private static String getScenarioString(Scenario s) { // List<DefaultVariable> inputs = s.getInputSet(); // StringBuffer buf = new StringBuffer(); // buf.append("Inputs\n"); // for (DefaultVariable v : inputs) { // buf.append(v.getMetaData().getName()).append(":").append(v.getMetaData().getId()).append(":"); // buf.append(v.getValue().toString()); // buf.append("\n"); // } // buf.append("\n"); // List<DefaultVariable> outputs = s.getOutputSet(); // buf.append("Outputs\n"); // for (DefaultVariable v : outputs) { // buf.append(v.getMetaData().getName()).append(":").append(v.getMetaData().getId()).append(":"); // buf.append(v.getValue().toString()).append(":"); // buf.append("\n"); // } // return buf.toString(); // } }
/* * LcmsOrganizationController.java 1.00 2011-09-05 * * 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.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; 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.cmm.service.EgovProperties; import egovframework.com.cmm.service.Globals; import egovframework.com.file.controller.FileController; import egovframework.com.pag.controller.PagingManageController; import egovframework.rte.fdl.property.EgovPropertyService; import egovframework.com.utl.fcc.service.EgovStringUtil; import egovframework.adm.lcms.cts.model.LcmsScormModel; import egovframework.adm.lcms.cts.service.LcmsOrganizationService; import egovframework.adm.lcms.cts.domain.LcmsOrganization; /** * <pre> * system : * menu : * source : LcmsOrganizationController.java * description : * </pre> * @version * <pre> * 1.0 2011-09-05 created by ? * 1.1 * </pre> */ @Controller public class LcmsOrganizationController { /** log */ protected static final Log log = LogFactory.getLog( LcmsOrganizationController.class); /** EgovPropertyService */ @Resource(name = "propertiesService") protected EgovPropertyService propertiesService; /** EgovMessageSource */ @Resource(name="egovMessageSource") EgovMessageSource egovMessageSource; /** PagingManageController */ @Resource(name = "pagingManageController") private PagingManageController pagingManageController; /** LcmsOrganizationService */ @Resource(name = "lcmsOrganizationService") private LcmsOrganizationService lcmsOrganizationService; @RequestMapping(value="/adm/lcms/cts/LcmsOrganizationPageList.do") public String pageList( HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { int totCnt = lcmsOrganizationService.selectLcmsOrganizationPageListTotCnt(commandMap); pagingManageController.PagingManage(commandMap, model, totCnt); List list = lcmsOrganizationService.selectLcmsOrganizationPageList(commandMap); model.addAttribute("list", list); model.addAllAttributes(commandMap); return "/adm/lcms/cts/LcmsOrganizationPageList"; } @RequestMapping(value="/adm/clcms/ts/LcmsOrganizationList.do") public String list( HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { List list = lcmsOrganizationService.selectLcmsOrganizationList(commandMap); model.addAttribute("list", list); model.addAllAttributes(commandMap); return "/adm/lcms/cts/LcmsOrganizationList"; } @RequestMapping(value="/adm/lcms/cts/LcmsOrganizationView.do") public String view( HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { Map output = new HashMap(); output.putAll((Map)lcmsOrganizationService.selectLcmsOrganization(commandMap)); model.addAttribute("output",output); model.addAllAttributes(commandMap); return "/adm/lcms/cts/LcmsOrganizationView"; } @RequestMapping(value="/adm/lcms/cts/LcmsOrganizationInsertForm.do") public String insertForm( HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { model.addAllAttributes(commandMap); return "/adm/lcms/cts/LcmsOrganizationInsert"; } @RequestMapping(value="/adm/lcms/cts/LcmsOrganizationInsert.do") public String insert( HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { int result = 0; String resultMsg = ""; ArrayList imsPath = new ArrayList(); ArrayList zFile = new ArrayList(); FileController file = new FileController(); String strSavePath = EgovProperties.getProperty("Globals.contentFileStore")+commandMap.get("userid")+"/"+commandMap.get("subj"); // tempํด๋” ์‚ญ์ œ ( imsmanifest.xml์„ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ์œ„ํ•œ ์ž„์‹œํด๋” ) boolean deleteResult = file.deleteDirector(strSavePath+"/tmp"); commandMap.put("strSavePath", strSavePath); // ์••์ถ•ํŒŒ์ผ ํ•ด์ œ String contents[] = (new File(strSavePath)).list(); for(int j=0; j<contents.length; j++){ String saveFile = contents[j]; if( !(new File(strSavePath+"/"+saveFile)).isDirectory() ){ imsPath = file.fileUnZip(strSavePath, saveFile); } } Collections.sort(imsPath); LcmsScormModel scorm = new LcmsScormModel(); ArrayList dataList = scorm.getData(request, commandMap, imsPath); result = lcmsOrganizationService.insertLcmsOrganization(dataList); if( result == 1 ){ resultMsg = egovMessageSource.getMessage("success.common.insert"); }else{ if( result == 10 ){ resultMsg = "Title ์ด ํ…Œ์ด๋ธ” ์นผ๋Ÿผ์˜ Max ๊ฐ’์„ ์ดˆ๊ณผํ•ฉ๋‹ˆ๋‹ค."; }else if( result == 20 ){ resultMsg = "Organization Id ๊ฐ’์ด ์ค‘๋ณต๋˜์—ˆ์Šต๋‹ˆ๋‹ค. manifest file ์˜ ํ•ญ๋ชฉ์„ ํ™•์ธํ•˜์‹ญ์‹œ์˜ค."; }else if( result == 30 ){ resultMsg = "Parameter Attribute ์˜ ๊ธธ์ด๊ฐ€ ํ…Œ์ด๋ธ” ์นผ๋Ÿผ์˜ Max ๊ฐ’์„ ์ดˆ๊ณผํ•ฉ๋‹ˆ๋‹ค."; }else if( result == 40 ){ resultMsg = "Item Title ์ด ํ…Œ์ด๋ธ” ์นผ๋Ÿผ์˜ Max ๊ฐ’์„ ์ดˆ๊ณผํ•ฉ๋‹ˆ๋‹ค."; }else if( result == 50 ){ resultMsg = "dataFromLMS์˜ ๊ฐ’์ด ํ…Œ์ด๋ธ” ์นผ๋Ÿผ์˜ Max ๊ฐ’์„ ์ดˆ๊ณผํ•ฉ๋‹ˆ๋‹ค."; }else if( result == 60 ){ resultMsg = "Item Id ๊ฐ’์ด ์ค‘๋ณต๋˜์—ˆ์Šต๋‹ˆ๋‹ค. manifest file ์˜ ํ•ญ๋ชฉ์„ ํ™•์ธํ•˜์‹ญ์‹œ์˜ค."; }else{ resultMsg = egovMessageSource.getMessage("fail.common.insert"); } for( int i=0; i<imsPath.size(); i++ ){ file.deleteDirector((String)imsPath.get(i)); } } model.addAttribute("resultMsg", resultMsg); model.addAllAttributes(commandMap); return "adm/lcms/ims/imsManifestList"; } @RequestMapping(value="/adm/lcms/cts/LcmsOrganizationCancel.do") public String cancel( HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { String resultMsg = ""; FileController file = new FileController(); String strSavePath = Globals.CONTNET_REAL_PATH+commandMap.get("SubDir"); // tempํด๋” ์‚ญ์ œ ( imsmanifest.xml์„ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ์œ„ํ•œ ์ž„์‹œํด๋” ) boolean deleteResult = file.deleteDirector(strSavePath+"/tmp"); file.deleteZipFile(strSavePath, "zip"); if( deleteResult ){ resultMsg = "์ทจ์†Œ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค."; }else{ resultMsg = "์ทจ์†Œ์ฒ˜๋ฆฌ์ค‘ ์˜ค๋ฅ˜๋กœ ์ธํ•˜์—ฌ ํŒŒ์ผ์ด ์ •์ƒ์ ์œผ๋กœ ์‚ญ์ œ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค."; } model.addAttribute("resultMsg", resultMsg); model.addAllAttributes(commandMap); return "adm/lcms/ims/imsManifestList"; } @RequestMapping(value="/adm/lcms/cts/LcmsOrganizationUdateForm.do") public String updateForm( HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { Map output = new HashMap(); output.putAll((Map)lcmsOrganizationService.selectLcmsOrganization(commandMap)); model.addAttribute("output",output); model.addAllAttributes(commandMap); return "/adm/lcms/cts/LcmsOrganizationUpdate"; } @RequestMapping(value="/adm/lcms/cts/LcmsOrganizationUpdate.do") public String update( HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { String resultMsg = ""; String forwardUrl = ""; int result = lcmsOrganizationService.updateLcmsOrganization( 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/lcms/cts/LcmsOrganizationUdateForm.do"; return forwardUrl; } @RequestMapping(value="/adm/lcms/cts/LcmsOrganizationDelete.do") public String delete( HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { String resultMsg = ""; String forwardUrl = ""; int check = lcmsOrganizationService.checkCourseMapping(commandMap); if( check == 0 ){ String[] orgSeq = EgovStringUtil.getStringSequence(commandMap,"chk"); commandMap.put("orgSeq", orgSeq); List filePath = lcmsOrganizationService.selectOrganizationPathList(commandMap); int result = lcmsOrganizationService.deleteLcmsOrganization( commandMap); // FileController file = new FileController(); // for( int i=0; i<filePath.size(); i++ ){ // //์„ ํƒ์ฐจ์‹œ ์ปจํ…์ธ ํŒŒ์ผ ์‚ญ์ œ // boolean deleteResult = file.deleteDirector(Globals.CONTNET_REAL_PATH+((Map)filePath.get(i)).get("baseDir")); // } // if(result > 0){ resultMsg = egovMessageSource.getMessage("success.common.delete"); // }else{ // resultMsg = egovMessageSource.getMessage("fail.common.delete"); // } }else{ resultMsg = "์ด๋ฏธ ์‚ฌ์šฉ์ค‘์ธ ๊ต๊ณผ๋Š” ์ˆ˜์ •ํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."; } model.addAttribute("resultMsg", resultMsg); model.addAllAttributes(commandMap); forwardUrl = "forward:/adm/lcms/sco/scormScoList.do"; return forwardUrl; } }
package templateMethod; public abstract class ClassicCarStartingSequence { public void startTheCar(){ fastenSeatBelts(); startTheIgnition(); setTheGear(); go(); } private void go() { System.out.println("Jedลบ"); } private void setTheGear() { System.out.println("Ustaw bieg"); } private void startTheIgnition() { System.out.println("Przekrec kluczyk"); } private void fastenSeatBelts() { System.out.println("Zapnij pasy"); } }
package seleniumPack; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class Test04 { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub System.setProperty(Data.Key, Data.Value); WebDriver driver = new ChromeDriver(); driver.get("http:\\www.google.com") ; List<WebElement> alllinks = driver.findElements(By.xpath("//a")); int countlinks= alllinks.size(); System.out.println(countlinks); int j =0; for(int i =0 ;i < countlinks ;i++){ WebElement link = alllinks.get(i); String linktext = link.getText(); int linksize = linktext.length(); // System.out.println(linktext); if(linksize >0){ j+=1 ; System.out.println(linktext); } } System.out.println(j); driver.close(); } }
package Question1_25; public class _13_IntRoman { public static void main(String[] args) { // TODO Auto-generated method stub romanToInt("MCMXCIV"); } public static int romanToInt(String s) { if(s==null|| s.length()==0) { return 0; } int num = 0; int arr[] = {1000,900,500,400,100,90,50,40,10,9,5,4,1}; String Roman[] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; int i = 0; int j = 0; int length = s.length(); while(i < length) { int k = 0; for( k = j ; k < 13;k++) { if(s.substring(i,length).startsWith(Roman[k])) { num+=arr[k]; break; } } i=i+Roman[k].length();; } return num; } }
package com.role.game.launcher; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.junit.Test; public class GameLauncherTest { // StartGame.txt contains the sequence of input stream actions that will be // given by the user when he starts a new game. @Test public void lauchNewGame() throws IOException { String fileName = "src/test/resources/StartGame.txt"; InputStream is = new FileInputStream(new File(fileName)); System.setIn(is); GameLauncher.launchGame(); is.close(); } }
package br.com.webstore.config; import br.com.webstore.service.CustomUserDetailsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.web.cors.CorsConfiguration; import static br.com.webstore.config.SecurityConstants.SIGN_UP_URL; /** * @author Lucas Kanรด de Oliveira (lucaskano) * @project api-webstore * @since 23/04/2020 */ @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CustomUserDetailsService customUserDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/*/protected/**").hasRole("USER") .antMatchers("/*/admin/**").hasRole("ADMIN") .and() .httpBasic() .and() .csrf().disable(); //desabilita protecao CSFR. Sรถ pra testar no localhost, porque se nao fica travando minhas requisicoes no local } // @Override // protected void configure(HttpSecurity http) throws Exception { // // http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues()) // .and().csrf().disable() // .authorizeRequests() // .antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll() // .antMatchers("/*/protected/**").hasRole("USER") // .antMatchers("/*/admin/**").hasRole("ADMIN") // .and() // .addFilter(new JWTAuthenticationFilter(authenticationManager())) // .addFilter(new JWTAuthorizationFilter(authenticationManager(), customUserDetailsService)); // // } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(customUserDetailsService).passwordEncoder(new BCryptPasswordEncoder()); } }
package com.houzhi.retrofitdemo.fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.houzhi.retrofitdemo.R; import com.houzhi.retrofitdemo.model.HttpbinRequest; import com.squareup.okhttp.FormEncodingBuilder; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.RequestBody; import butterknife.Bind; import butterknife.OnClick; import retrofit.Call; /** * @author houzhi */ public class ExampleMultiPartFragment extends BaseRequestExampleFragment { @Bind(R.id.et_value1) TextView etValue1; @Bind(R.id.body) TextView body; public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8"); @OnClick(R.id.bt_request) void request() { // String postBody = "" // + "MultiPart\n" // + "--------\n" // + "\n" // + " * _1.0_ May 6, 2015\n" // + " * _1.1_ June 15, 2015\n" // + " * _1.2_ August 11, 2015\n"; String postBody = body.getText().toString(); RequestBody part1 = RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody); RequestBody formBody = new FormEncodingBuilder() .add("log", etValue1.getText().toString()) .build(); Call<HttpbinRequest> call = httpbinService.postMultiPart(part1, formBody); processCall(call); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_example_multipart, container, false); return view; } }
/* * 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 lab_3_2; import java.util.*; /** * * @author valen */ public class Lab_3_2 { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); String isFast; String isBig; String stringMessage; System.out.println("Are you fast? (y/n)"); isFast = keyboard.nextLine(); System.out.println("Are you big? (y/n)"); isBig = keyboard.nextLine(); if(isBig.equals("y") || isFast.equals("n")) { stringMessage = "You are cut from the team"; } else{ stringMessage = "You are on the team!"; } System.out.println(stringMessage); // TODO code application logic here } }
package com.cg.repo; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.cg.entity.Movie; //import com.cg.entity.Product; import com.cg.service.InvalidMovieException; @Repository public class MovieDaoImpl implements MovieDao { @Autowired private EntityManager mgr; @Override public Movie save(Movie movie) { mgr.persist(movie); return movie; } @Override public Movie fetch(int id) throws InvalidMovieException { Movie m = (Movie) mgr.find(Movie.class, id); if(m==null) throw new InvalidMovieException("Invalid Movie ID"); return m; } @Override public List<Movie> getAll() { TypedQuery<Movie> query = mgr.createNamedQuery("findAll", Movie.class); List<Movie> results = query.getResultList(); return results; } @Override public boolean delete(int id) throws InvalidMovieException { Movie m = mgr.find(Movie.class, id); if(m==null) throw new InvalidMovieException("Invalid movie ID, cannot Delete."); mgr.remove(m); return true; } @Override public Movie update(Movie movie) { return mgr.merge(movie); } @Override public List<Movie> findByGenre(String gen) { return mgr.createNamedQuery("byGenre").setParameter("gen",gen).getResultList(); } }
package com.imaprofessional.niko.projectmaplesyrip; import android.app.Activity; import android.os.Handler; import android.os.SystemClock; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { private CanvasView canvasView; private Handler h; private final int FRAME_RATE = 30; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); canvasView = (CanvasView)findViewById(R.id.canvas); h = new Handler(); h.postAtTime(r, SystemClock.uptimeMillis() + 400); } private Runnable r = new Runnable() { @Override public void run() { canvasView.invalidate(); h.postDelayed(r, FRAME_RATE); } }; }
package helperFunctions; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import org.apache.commons.lang.StringUtils; /** * * @author Hendrik */ public class PGPMail { public static String PGPEncrypt(PrivateKey myPrivateKey, PublicKey recieverPublicKey, String message) throws NoSuchAlgorithmException { String messageHash = ShaHash.getHash(message); String encryptedMessageHash = RSAEncryption.encryptPrivateKey(messageHash, myPrivateKey); String messageKey = OneTimeKeyGenerator.getKey(128); String encryptedMessage = EncryptionHelper.encrypt(message, messageKey); String encryptedMessageKey = RSAEncryption.encryptPublicKey(messageKey, recieverPublicKey); encryptedMessage += "messageKey"+encryptedMessageKey+"messageHash"+encryptedMessageHash; return encryptedMessage; } public static String PGPDecrypt(PrivateKey myPrivateKey, PublicKey senderPublicKey, String message) throws NoSuchAlgorithmException { int location1= message.indexOf("messageKey"); int location2= message.indexOf("messageHash"); //if message not encrypted if(location1 ==-1 || location2 ==-1){ return message; } String recievedEncryptedMessage = message.substring(0, location1); String recievedEncryptedMessageKey = message.substring(location1+10, location2); String recievedEncryptedMessageHash = message.substring(location2+11); recievedEncryptedMessageHash = recievedEncryptedMessageHash.substring(0,recievedEncryptedMessageHash.length()-2); String decryptedMessageKey = RSAEncryption.decryptPrivateKey(recievedEncryptedMessageKey, myPrivateKey); String decryptedMessage = EncryptionHelper.decrypt(recievedEncryptedMessage, decryptedMessageKey); String decryptedMessageHash = RSAEncryption.decryptPublicKey(recievedEncryptedMessageHash, senderPublicKey); String RecievedMessageHash = ShaHash.getHash(decryptedMessage); if(decryptedMessageHash.equals(RecievedMessageHash)) { System.out.println("The message is authentic"); return decryptedMessage; }else{ System.out.println("This message has been tampered with"); return "TAMPERED MESSAGE!!! ---"+ decryptedMessage; } } }
class Trapecio extends Masdisparejos{ protected float lado4; public void setLado4(float lado4){ this.lado4=lado4; } public float getLado4(){ return lado4; } public double Perimetrotrapecio(){ perimetro=lado1+lado2+lado3+lado4; return perimetro; } public double Areatrapecio(){ area=((lado1+lado2)/2)*altura; return area; } }
package ru.fargus.testapp.ui.map; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; import org.parceler.Parcels; import java.util.List; import butterknife.BindBitmap; import butterknife.ButterKnife; import butterknife.Unbinder; import ru.fargus.testapp.R; import ru.fargus.testapp.helpers.ToastHelper; import ru.fargus.testapp.model.City; import ru.fargus.testapp.ui.map.constants.MapConfig; public class MapActivity extends AppCompatActivity implements IMapView, OnMapReadyCallback { GoogleMap mMapView; private City mArrivalCity; private City mDepartureCity; private Marker mPlaneMarker; private Unbinder mViewsUnbinder; private MapPresenter mMapPresenter; @BindBitmap(R.mipmap.ic_plane) Bitmap mMapMarker; public static void buildIntent(Activity activity, Bundle extraParams) { if (activity != null) { Intent intent = new Intent(activity, MapActivity.class); intent.putExtras(extraParams); activity.startActivity(intent); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); mViewsUnbinder = ButterKnife.bind(this); Intent intent = getIntent(); mMapPresenter = new MapPresenter(this); if (intent != null && intent.getExtras() != null) { Bundle arguments = intent.getExtras(); mArrivalCity = Parcels.unwrap(arguments.getParcelable(MapConfig.MAP_ARRIVAL_PARAM)); mDepartureCity = Parcels.unwrap(arguments.getParcelable(MapConfig.MAP_DEPARTURE_PARAM)); } SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap googleMap) { mMapView = googleMap; LatLng mArrivalPoint = mMapPresenter.getArrivalPoint(mArrivalCity); LatLng mDeparturePoint = mMapPresenter.getDeparturePoint(mDepartureCity); mMapView.moveCamera(CameraUpdateFactory.newLatLngZoom(mDeparturePoint, 3)); View planeLayout = getLayoutInflater().inflate(R.layout.plane_marker_layout, null); View arrivalLayout = getLayoutInflater().inflate(R.layout.airport_marker_layout, null); View departureLayout = getLayoutInflater().inflate(R.layout.airport_marker_layout, null); mPlaneMarker = mMapView.addMarker(mMapPresenter.setPlaneMarker(mDeparturePoint, planeLayout)); mMapView.addMarker(mMapPresenter.setAirportMarker(mArrivalPoint, mMapPresenter.getIataCode(mArrivalCity), arrivalLayout)); mMapView.addMarker(mMapPresenter.setAirportMarker(mDeparturePoint, mMapPresenter.getIataCode(mDepartureCity), departureLayout)); mMapPresenter.buildRoutePoints(mDeparturePoint, mArrivalPoint); } @Override protected void onDestroy() { super.onDestroy(); mViewsUnbinder.unbind(); } @Override public void showToastMessage(String errorMessage) { ToastHelper.showToastMessage(this, errorMessage); } @Override public void buildRouteOnMap(List<LatLng> points) { Polyline polyline = mMapView.addPolyline(new PolylineOptions().addAll(points)); mMapPresenter.setPolylineStyle(polyline); mMapPresenter.animateMarkerMoveAlongRoute(mPlaneMarker, points); } }
package files; import java.util.Scanner; public class PathToFile { String fromFile() { String toDirectory = ""; System.out.println("Please insert the path to your file"); Scanner fromDirectoryToCopy = new Scanner(System.in); toDirectory += fromDirectoryToCopy.nextLine(); return toDirectory; } String toFile() { String toNewDirectory = ""; System.out.println("Please insert the path to new directory with File Name and File Extension"); Scanner fromNewDirectoryToCopy = new Scanner(System.in); toNewDirectory += fromNewDirectoryToCopy.nextLine(); return toNewDirectory; } }
package kr.or.ddit.basic; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /* * ๋ถ€๋ชจ ํด๋ž˜์Šค๊ฐ€ Serializable ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ตฌํ˜„ํ•˜๊ณ  ์ž์‹ ํด๋ž˜์Šค๊ฐ€ ์ด๋ฅผ ์ƒ์†๋ฐ›์„ ๊ฒฝ์šฐ * ์ž๋™์ ์œผ๋กœ ์ž์‹ ํด๋ž˜์Šค๋Š” Serializable์„ ์ƒ์† ๋ฐ›๋Š”๋‹ค * ------------------------------------------------------------------------ * ๋ถ€๋ชจ ํด๋ž˜์Šค๊ฐ€ Serializable ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ๊ตฌํ˜„ํ•˜๊ณ  ์žˆ์ง€ ์•Š์€ ๊ฒฝ์šฐ * ๋ถ€๋ชจ ๊ฐ์ฒด์˜ ํ•„๋“œ๊ฐ’ ์ฒ˜๋ฆฌ ๋ฐฉ๋ฒ• * 1.๋ถ€๋ชจ ํด๋ž˜์Šค๊ฐ€ Serializable์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ตฌํ˜„ํ•˜๋„๋ก ํ•ด์•ผํ•œ๋‹ค. - ์ด๋ฅผ ์ƒ์†ํ•œ ์ž์‹ ํด๋ž˜์Šค๋Š” ๋ชจ๋‘ Serializable * 2. ์ž์‹ ํด๋ž˜์Šค์— writeObject()์™€ readObject()๋ฉ”์†Œ๋“œ๋ฅผ ์ด์šฉํ•ด * ๋ถ€๋ชจ ๊ฐ์ฒด์˜ ํ•„๋“œ๊ฐ’์„ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋„๋ก ์ง์ ‘ ๊ตฌํ˜„ */ public class T16_NonSerializableParentTest { public static void main(String[] args) throws IOException, ClassNotFoundException { FileOutputStream fos = new FileOutputStream("d:/D_Other/nonSerialTest.bin"); ObjectOutputStream oos= new ObjectOutputStream(fos); Child child = new Child(); child.setParentName("๋ถ€๋ชจ"); child.setChildName("์ž์‹"); oos.writeObject(child);// ๋ฐ‘์— ๋ฉ”์†Œ๋“œ ์‹คํ–‰ , object์˜ writeObject๊ฐ€ ์‹คํ–‰๋˜๋Š” ๊ฒƒ์ด ์•„๋‹˜ oos.flush(); // ์ƒ๋žต ๊ฐ€๋Šฅ oos.close(); //--------------------------------------- FileInputStream fis = new FileInputStream("d:/D_Other/nonSerialTest.bin"); ObjectInputStream ois = new ObjectInputStream(fis); Child child2 = (Child) ois.readObject(); System.out.println("parentName:" + child2.getParentName()); System.out.println("ChildName:" + child2.getChildName()); } } /* * Serializable ์„ ๊ตฌํ˜„ํ•˜์ง€ ์•Š์€ ๋ถ€๋ชจ ํด๋ž˜์Šค * */ class Parent{ private String parentName; public String getParentName() { return parentName; } public void setParentName(String parentName) { this.parentName = parentName; } } /* * Serializable์„ ๊ตฌํ˜„ํ•œ ์ž์‹ ํด๋ž˜์Šค */ class Child extends Parent implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private String childName; public String getChildName() { return childName; } public void setChildName(String childName) { this.childName = childName; } //์ง๋ ฌํ™” ๋  ๋•Œ ์ž๋™์œผ๋กœ ํ˜ธ์ถœ๋œ๋‹ค // ์ ‘๊ทผ์ œํ•œ์ž๊ฐ€ private์ด ์•„๋‹ˆ๋ฉด ์ž๋™ ํ˜ธ์ถœ ๋˜์ง€ ์•Š๋Š”๋‹ค // ์—†์œผ๋ฉด parentName = null, ChildName = ์„ธํŒ…๊ฐ’ // ์›๋ž˜ ๊ฐ์ฒด๋ฅผ ์ฝ์–ด๋“ค์ด๋Š” writeObject๋ฅผ ์žฌ์ •์˜(์™€ ๋น„์Šทํ•œ ๋ฐฉ๋ฒ•)ํ•˜์—ฌ ์‚ฌ์šฉ private void writeObject(ObjectOutputStream out) throws IOException{ // ์ผ์ข…์˜ ์žฌ์ •์˜ //ObjectOutputStream ๊ฐ์ฒด์˜ ๋ฉ”์†Œ๋“œ๋ฅผ ์ด์šฉํ•ด ๋ถ€๋ชจ๊ฐ์ฒด ํ•„๋“œ๊ฐ’ ์ฒ˜๋ฆฌ out.writeUTF(getParentName()); // ์ƒ์†๋ฐ›์€ ๋ถ€๋ชจ ๊ฐ’์„ ์ˆ˜๋™์œผ๋กœ ์ถ”๊ฐ€ out.defaultWriteObject(); // ๋” ์ด์ƒ ์“ธ ๊ฒƒ์ด ์—†๋‹ค๋ฉด ์‹คํ–‰๋จ } //์—ญ์ง๋ ฌํ™” ๋  ๋•Œ ์ž๋™์œผ๋กœ ํ˜ธ์ถœ๋œ๋‹ค // ์ ‘๊ทผ์ œํ•œ์ž๊ฐ€ private์ด ์•„๋‹ˆ๋ฉด ์ž๋™ ํ˜ธ์ถœ ๋˜์ง€ ์•Š๋Š”๋‹ค private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{ // ์ผ์ข…์˜ ์žฌ์ •์˜ // ObjectInputStream๊ฐ์ฒด์˜ ๋ฉ”์†Œ๋“œ๋ฅผ ์ด์šฉํ•ด ๋ถ€๋ชจ๊ฐ์ฒด ํ•„๋“œ๊ฐ’ ์ฒ˜๋ฆฌ setParentName(in.readUTF()); in.defaultReadObject(); } }
package com.tony.pandemic.hospital; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import javax.transaction.Transactional; @Repository public interface IHospitalRepository extends JpaRepository<Hospital, Long> { @Transactional @Modifying @Query("UPDATE Hospital h SET h.percentageOfOccupation=?1, h.registrationTime=CURRENT_TIMESTAMP WHERE h.id=?2") void updateOccupation(Double PercentageOfOccupation, long id); }
package com.citibank.ods.entity.pl; import java.math.BigInteger; import java.util.Date; import com.citibank.ods.entity.pl.valueobject.TplCustomerBrokerEntityVO; import com.citibank.ods.entity.pl.valueobject.TplCustomerBrokerMovEntityVO; /** * Classe que instancia a entidade correspondente a tabela : TplCustomerBroker * @author Hamilton Matos */ public class TplCustomerBrokerEntity extends BaseTplCustomerBrokerEntity { public TplCustomerBrokerEntity() { m_data = new TplCustomerBrokerEntityVO(); } public TplCustomerBrokerEntity( TplCustomerBrokerMovEntity tplCustomerBrokerMovEntity_, Date lastAuthDate_, String lastAuthUserId_, String recStatCode_ ) { m_data = new TplCustomerBrokerEntityVO(); TplCustomerBrokerEntityVO tplCustomerBrokerEntityVO = ( TplCustomerBrokerEntityVO ) m_data; TplCustomerBrokerMovEntityVO tplCustomerBrokerMovEntityVO = ( TplCustomerBrokerMovEntityVO ) tplCustomerBrokerMovEntity_.getData(); tplCustomerBrokerEntityVO.setBkrCnpjNbr( tplCustomerBrokerMovEntityVO.getBkrCnpjNbr() ); tplCustomerBrokerEntityVO.setLastUpdDate( tplCustomerBrokerMovEntityVO.getLastUpdDate() ); tplCustomerBrokerEntityVO.setLastUpdUserId( tplCustomerBrokerMovEntityVO.getLastUpdUserId() ); tplCustomerBrokerEntityVO.setLastAuthDate( lastAuthDate_ ); tplCustomerBrokerEntityVO.setLastAuthUserId( lastAuthUserId_ ); tplCustomerBrokerEntityVO.setRecStatCode( recStatCode_ ); } public TplCustomerBrokerEntity( TplBrokerEntity tplBrokerEntity_, BigInteger custNbr_, BigInteger bkrCustNbr_ ) { m_data = new TplCustomerBrokerEntityVO(); TplCustomerBrokerEntityVO tplCustomerBrokerEntityVO = ( TplCustomerBrokerEntityVO ) m_data; tplCustomerBrokerEntityVO.setCustNbr( custNbr_ ); tplCustomerBrokerEntityVO.setBkrCnpjNbr( tplBrokerEntity_.getData().getBkrCnpjNbr() ); tplCustomerBrokerEntityVO.setBkrCustNbr( bkrCustNbr_ ); tplCustomerBrokerEntityVO.setBkrNameText( tplBrokerEntity_.getData().getBkrNameText() ); tplCustomerBrokerEntityVO.setBkrAddrText( tplBrokerEntity_.getData().getBkrAddrText() ); } }
package com.example.okta_cust_sign_in.pojo; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.okta.sdk.resource.group.GroupList; import com.okta.sdk.resource.user.AppLinkList; import com.okta.sdk.resource.user.ChangePasswordRequest; import com.okta.sdk.resource.user.ForgotPasswordResponse; import com.okta.sdk.resource.user.ResetPasswordToken; import com.okta.sdk.resource.user.Role; import com.okta.sdk.resource.user.RoleList; import com.okta.sdk.resource.user.TempPassword; import com.okta.sdk.resource.user.User; import com.okta.sdk.resource.user.UserActivationToken; import com.okta.sdk.resource.user.UserCredentials; import com.okta.sdk.resource.user.UserStatus; import com.okta.sdk.resource.user.factor.Factor; import com.okta.sdk.resource.user.factor.FactorList; import com.okta.sdk.resource.user.factor.SecurityQuestionList; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; public class UserLocal implements com.okta.sdk.resource.user.User { @Override public Map<String, Object> getEmbedded() { return null; } @Override public Map<String, Object> getLinks() { return null; } @Override public Date getActivated() { return null; } @Override public Date getCreated() { return null; } @Override public UserCredentials getCredentials() { return null; } @Override public com.okta.sdk.resource.user.User setCredentials(UserCredentials credentials) { return null; } @Override public String getId() { return null; } @Override public Date getLastLogin() { return null; } @Override public Date getLastUpdated() { return null; } @Override public Date getPasswordChanged() { return null; } @Override public UserProfileLocal getProfile() { return null; } @Override public User setProfile(com.okta.sdk.resource.user.UserProfile profile) { return null; } @Override public UserStatus getStatus() { return null; } @Override public Date getStatusChanged() { return null; } @Override public UserStatus getTransitioningToStatus() { return null; } @Override public void deactivate(Boolean sendEmail) { } @Override public void deactivate() { } @Override public ResetPasswordToken resetPassword(String provider, Boolean sendEmail) { return null; } @Override public ResetPasswordToken resetPassword() { return null; } @Override public FactorList listFactors() { return null; } @Override public GroupList listGroupTargetsForRole(String roleId) { return null; } @Override public ForgotPasswordResponse forgotPassword(UserCredentials userCredentials, Boolean sendEmail) { return null; } @Override public ForgotPasswordResponse forgotPassword() { return null; } @Override public void removeRole(String roleId) { } @Override public TempPassword expirePassword(Boolean tempPassword) { return null; } @Override public TempPassword expirePassword() { return null; } @Override public UserActivationToken activate(Boolean sendEmail) { return null; } @Override public UserCredentials changeRecoveryQuestion(UserCredentials userCredentials) { return null; } @Override public void unsuspend() { } @Override public Factor addFactor(Factor body, Boolean updatePhone, String templateId, Integer tokenLifetimeSeconds, Boolean activate) { return null; } @Override public Factor addFactor(Factor body) { return null; } @Override public Factor addFactor(Factor body, Boolean updatePhone, String templateId) { return null; } @Override public GroupList listGroups() { return null; } @Override public void removeGroupTargetFromRole(String roleId, String groupId) { } @Override public FactorList listSupportedFactors() { return null; } @Override public void delete(Boolean sendEmail) { } @Override public void delete() { } @Override public void resetFactors() { } @Override public void suspend() { } @Override public RoleList listRoles(String expand) { return null; } @Override public RoleList listRoles() { return null; } @Override public void unlock() { } @Override public com.okta.sdk.resource.user.User update() { return null; } @Override public Factor getFactor(String factorId) { return null; } @Override public UserCredentials changePassword(ChangePasswordRequest changePasswordRequest) { return null; } @Override public AppLinkList listAppLinks(Boolean showAll) { return null; } @Override public AppLinkList listAppLinks() { return null; } @Override public void addGroupTargetToRole(String roleId, String groupId) { } @Override public SecurityQuestionList listSupportedSecurityQuestions() { return null; } @Override public void endAllSessions(Boolean oAuthTokens) { } @Override public void endAllSessions() { } @Override public void addToGroup(String groupId) { } @Override public Role addRole(Role role) { return null; } @Override public Factor addFactor(Boolean updatePhone, String templateId, Integer tokenLifetimeSeconds, Boolean activate, Factor body) { return null; } @Override public Factor addFactor(Boolean updatePhone, String templateId, Factor body) { return null; } @Override public ForgotPasswordResponse forgotPassword(Boolean sendEmail, UserCredentials userCredentials) { return null; } @Override public String getString(String key) { return null; } @Override public Double getNumber(String key) { return null; } @Override public Boolean getBoolean(String key) { return null; } @Override public Integer getInteger(String key) { return null; } @Override public List<String> getStringList(String key) { return null; } @Override public List<Double> getNumberList(String key) { return null; } @Override public List<Integer> getIntegerList(String key) { return null; } @Override public String getResourceHref() { return null; } @Override public void setResourceHref(String href) { } @Override public int size() { return 0; } @Override public boolean isEmpty() { return false; } @Override public boolean containsKey(@Nullable Object key) { return false; } @Override public boolean containsValue(@Nullable Object value) { return false; } @Nullable @Override public Object get(@Nullable Object key) { return null; } @Nullable @Override public Object put(String key, Object value) { return null; } @Nullable @Override public Object remove(@Nullable Object key) { return null; } @Override public void putAll(@NonNull Map<? extends String, ?> m) { } @Override public void clear() { } @NonNull @Override public Set<String> keySet() { return null; } @NonNull @Override public Collection<Object> values() { return null; } @NonNull @Override public Set<Entry<String, Object>> entrySet() { return null; } }
package com.alvarado.dev.platzigram.model; /** * Created by dev on 9/03/18. */ public class Picture { private String imagen; private String usuario; private String tiempo; private String numLike = "0"; public Picture(String imagen, String usuario, String tiempo, String numLike) { this.imagen = imagen; this.usuario = usuario; this.tiempo = tiempo; this.numLike = numLike; } public String getImagen() { return imagen; } public void setImagen(String imagen) { this.imagen = imagen; } public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public String getTiempo() { return tiempo; } public void setTiempo(String tiempo) { this.tiempo = tiempo; } public String getNumLike() { return numLike; } public void setNumLike(String numLike) { this.numLike = numLike; } }
package utng.edu.mx.aprendersoap; import android.content.Intent; import android.media.MediaPlayer; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageButton; public class PantallaOpciones extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener { ImageButton imvAcercaDe; ImageButton imvTemario; private MediaPlayer sound; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pantalla_opciones); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); imvAcercaDe =(ImageButton)findViewById(R.id.imv_acercade); imvAcercaDe.setOnClickListener(this); sound = MediaPlayer.create(this,R.raw.button22); imvTemario = (ImageButton)findViewById(R.id.imv_temario); imvTemario.setOnClickListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.pantalla_opciones, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { startActivity(new Intent(PantallaOpciones.this, Ayuda.class)); return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_temas) { startActivity(new Intent(PantallaOpciones.this, TemarioCurso.class)); } else if (id == R.id.nav_avance) { startActivity(new Intent(PantallaOpciones.this, Grafica.class)); } else if (id == R.id.nav_videos) { startActivity(new Intent(PantallaOpciones.this, MainVideos.class)); } else if (id == R.id.nav_manage) { startActivity(new Intent(PantallaOpciones.this, SeleccionaTema.class)); } else if (id == R.id.nav_games) { startActivity(new Intent(PantallaOpciones.this, Games.class)); } else if (id == R.id.nav_send) { startActivity(new Intent(PantallaOpciones.this, Correo.class)); }else if (id == R.id.nav_ubicacion) { startActivity(new Intent(PantallaOpciones.this, MapsActivity.class)); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.imv_acercade: sound.start(); startActivity(new Intent(this, AcercaDe.class)); break; case R.id.imv_temario: sound.start(); startActivity(new Intent(this, TemarioCurso.class)); break; } } }
package com.lmz.selenilum; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class Download { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "D:\\chromedriver\\chromedriver.exe"); WebDriver driver = new ChromeDriver() ; //ๅ—ๆณจ้‡ŠCtrl+Shift+/๏ผŒ่กŒๆณจ้‡ŠCtrl+/ //ๅŽป้™คๅ—ๆณจ้‡Š็š„ๆ—ถๅ€™๏ผŒไธ้œ€่ฆๅ…จ้ƒจ้€‰ไธญ่ฟ™ๅ—ไปฃ็ ๏ผŒๅช็”จๅ…‰ๆ ‡ๅœจๆณจ้‡Šๅ†…ๅฎนไธŠๆŒ‰Ctrl+Shift+/ๅณๅฏ //ๅ†ๆฌกๆŒ‰Ctrl+/๏ผŒๅฏไปฅๅŽปๆމ่ฏฅ่กŒๆณจ้‡Š /* driver.get("http://bbs.51testing.com/thread-992274-1-1.html"); String now_handle= driver.getWindowHandle(); System.out.println(now_handle); try { Thread.sleep(2000); } catch (InterruptedException e) { } driver.findElement(By.xpath("//*[@id=\"lsform\"]/div/div[2]/p[1]/a")).click(); try { Thread.sleep(2000); } catch (InterruptedException e) { } String new_handle= driver.getWindowHandle(); System.out.println(new_handle); driver.switchTo().window(new_handle);*/ // driver.get(now_handle); driver.get("https://graph.qq.com/oauth2.0/show?which=Login&display=pc&response_type=code&client_id=310671978&redirect_uri=http%3A%2F%2Fbbs.51testing.com%2Fconnect.php%3Fmod%3Dlogin%26op%3Dcallback%26referer%3Dforum.php%253Fmod%253Dviewthread%2526tid%253D992274%2526extra%253Dpage%25253D1%2526page%253D1&state=6f624ac662430b80f674d3dce30cc0e7&scope=get_user_info%2Cadd_share%2Cadd_t%2Cadd_pic_t%2Cget_repost_list"); try { Thread.sleep(4000); } catch (InterruptedException e) { } WebElement display=driver.findElement(By.xpath("//*[@id=\"switcher_plogin\"]")); System.out.println(display.isDisplayed()); // driver.findElement(By.xpath("//*[@id=\"img_out_378535180\"]")).click(); } }
package com.ocraftyone.MoreEverything.blocks; import java.util.Random; import com.ocraftyone.MoreEverything.Reference; import com.ocraftyone.MoreEverything.init.ModItems; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.item.Item; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class BlockSprinklesOre extends Block { public BlockSprinklesOre(String name) { super (Material.ROCK); this.setUnlocalizedName(name); this.setRegistryName(new ResourceLocation(Reference.modid, name)); this.setHardness(3); this.setResistance(15); this.setHarvestLevel("pickaxe", 2); } @Override public Item getItemDropped(IBlockState state, Random rand, int fortune) { return ModItems.itemSprinkles; } public static int toolFortune; @Override public int quantityDroppedWithBonus(int fortune, Random random) { toolFortune = fortune; return toolFortune * 2 + 1; } }
package org.dew.xcomm.util; import java.util.*; import org.apache.log4j.*; import org.dew.xcomm.messaging.XMessagingClient; public class CheckTimerTask extends TimerTask { protected transient Logger logger = Logger.getLogger(getClass()); protected boolean firstTime = true; public void run() { try { XMessagingClient client = XMessagingClient.getInstance(); if(client.isConnected()) { if(firstTime) { // Si evita di intasare il log in caso di esito OK. logger.debug("client.isConnected() -> true"); } } else { logger.warn("client.isConnected() -> false"); logger.warn("client.connect()..."); client.connect(); } firstTime = false; } catch(Exception ex) { logger.error("Eccezione in CheckConnectionsTimerTask.run", ex); } } }
/* * 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.beans.factory.aot; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.BiConsumer; import java.util.function.Predicate; import java.util.function.Supplier; import javax.lang.model.element.Modifier; import javax.xml.parsers.DocumentBuilderFactory; import org.junit.jupiter.api.Test; import org.springframework.aot.generate.GeneratedMethod; import org.springframework.aot.generate.GenerationContext; import org.springframework.aot.generate.MethodReference; import org.springframework.aot.generate.MethodReference.ArgumentCodeGenerator; import org.springframework.aot.test.generate.TestGenerationContext; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.ConstructorArgumentValues.ValueHolder; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.InstanceSupplier; import org.springframework.beans.factory.support.ManagedList; import org.springframework.beans.factory.support.RegisteredBean; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.testfixture.beans.AnnotatedBean; import org.springframework.beans.testfixture.beans.GenericBean; import org.springframework.beans.testfixture.beans.TestBean; import org.springframework.beans.testfixture.beans.factory.aot.InnerBeanConfiguration; import org.springframework.beans.testfixture.beans.factory.aot.MockBeanRegistrationsCode; import org.springframework.beans.testfixture.beans.factory.aot.SimpleBean; import org.springframework.beans.testfixture.beans.factory.aot.TestHierarchy; import org.springframework.beans.testfixture.beans.factory.aot.TestHierarchy.Implementation; import org.springframework.beans.testfixture.beans.factory.aot.TestHierarchy.One; import org.springframework.beans.testfixture.beans.factory.aot.TestHierarchy.Two; import org.springframework.core.ResolvableType; import org.springframework.core.test.io.support.MockSpringFactoriesLoader; import org.springframework.core.test.tools.CompileWithForkedClassLoader; import org.springframework.core.test.tools.Compiled; import org.springframework.core.test.tools.SourceFile; import org.springframework.core.test.tools.TestCompiler; import org.springframework.javapoet.CodeBlock; import org.springframework.javapoet.MethodSpec; import org.springframework.javapoet.ParameterizedTypeName; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link BeanDefinitionMethodGenerator} and * {@link DefaultBeanRegistrationCodeFragments}. * * @author Phillip Webb * @author Stephane Nicoll * @author Sebastien Deleuze */ class BeanDefinitionMethodGeneratorTests { private final TestGenerationContext generationContext; private final DefaultListableBeanFactory beanFactory; private final MockBeanRegistrationsCode beanRegistrationsCode; private final BeanDefinitionMethodGeneratorFactory methodGeneratorFactory; BeanDefinitionMethodGeneratorTests() { this.generationContext = new TestGenerationContext(); this.beanFactory = new DefaultListableBeanFactory(); this.methodGeneratorFactory = new BeanDefinitionMethodGeneratorFactory( AotServices.factoriesAndBeans(new MockSpringFactoriesLoader(), this.beanFactory)); this.beanRegistrationsCode = new MockBeanRegistrationsCode(this.generationContext); } @Test void generateBeanDefinitionMethodWithOnlyTargetTypeDoesNotSetBeanClass() { RootBeanDefinition beanDefinition = new RootBeanDefinition(); beanDefinition.setTargetType(TestBean.class); RegisteredBean registeredBean = registerBean(beanDefinition); BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, registeredBean, null, Collections.emptyList()); MethodReference method = generator.generateBeanDefinitionMethod( this.generationContext, this.beanRegistrationsCode); compile(method, (actual, compiled) -> { SourceFile sourceFile = compiled.getSourceFile(".*BeanDefinitions"); assertThat(sourceFile).contains("Get the bean definition for 'testBean'"); assertThat(sourceFile).contains("new RootBeanDefinition()"); assertThat(sourceFile).contains("setTargetType(TestBean.class)"); assertThat(sourceFile).contains("setInstanceSupplier(TestBean::new)"); assertThat(actual).isInstanceOf(RootBeanDefinition.class); }); } @Test void generateBeanDefinitionMethodSpecifiesBeanClassIfSet() { RootBeanDefinition beanDefinition = new RootBeanDefinition(TestBean.class); RegisteredBean registeredBean = registerBean(beanDefinition); BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, registeredBean, null, Collections.emptyList()); MethodReference method = generator.generateBeanDefinitionMethod( this.generationContext, this.beanRegistrationsCode); compile(method, (actual, compiled) -> { SourceFile sourceFile = compiled.getSourceFile(".*BeanDefinitions"); assertThat(sourceFile).contains("Get the bean definition for 'testBean'"); assertThat(sourceFile).contains("new RootBeanDefinition(TestBean.class)"); assertThat(sourceFile).doesNotContain("setTargetType("); assertThat(sourceFile).contains("setInstanceSupplier(TestBean::new)"); assertThat(actual).isInstanceOf(RootBeanDefinition.class); }); } @Test void generateBeanDefinitionMethodSpecifiesBeanClassAndTargetTypIfDifferent() { RootBeanDefinition beanDefinition = new RootBeanDefinition(One.class); beanDefinition.setTargetType(Implementation.class); beanDefinition.setResolvedFactoryMethod(ReflectionUtils.findMethod(TestHierarchy.class, "oneBean")); RegisteredBean registeredBean = registerBean(beanDefinition); BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, registeredBean, null, Collections.emptyList()); MethodReference method = generator.generateBeanDefinitionMethod( this.generationContext, this.beanRegistrationsCode); compile(method, (actual, compiled) -> { SourceFile sourceFile = compiled.getSourceFile(".*BeanDefinitions"); assertThat(sourceFile).contains("Get the bean definition for 'testBean'"); assertThat(sourceFile).contains("new RootBeanDefinition(TestHierarchy.One.class)"); assertThat(sourceFile).contains("setTargetType(TestHierarchy.Implementation.class)"); assertThat(actual).isInstanceOf(RootBeanDefinition.class); }); } @Test void generateBeanDefinitionMethodUSeBeanClassNameIfNotReachable() { RootBeanDefinition beanDefinition = new RootBeanDefinition(PackagePrivateTestBean.class); beanDefinition.setTargetType(TestBean.class); RegisteredBean registeredBean = registerBean(beanDefinition); BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, registeredBean, null, Collections.emptyList()); MethodReference method = generator.generateBeanDefinitionMethod( this.generationContext, this.beanRegistrationsCode); compile(method, (actual, compiled) -> { SourceFile sourceFile = compiled.getSourceFile(".*BeanDefinitions"); assertThat(sourceFile).contains("Get the bean definition for 'testBean'"); assertThat(sourceFile).contains("new RootBeanDefinition(\"org.springframework.beans.factory.aot.PackagePrivateTestBean\""); assertThat(sourceFile).contains("setTargetType(TestBean.class)"); assertThat(sourceFile).contains("setInstanceSupplier(TestBean::new)"); assertThat(actual).isInstanceOf(RootBeanDefinition.class); }); } @Test // gh-29556 void generateBeanDefinitionMethodGeneratesMethodWithInstanceSupplier() { RegisteredBean registeredBean = registerBean(new RootBeanDefinition(TestBean.class, TestBean::new)); BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, registeredBean, null, List.of((generationContext, beanRegistrationCode) -> { })); MethodReference method = generator.generateBeanDefinitionMethod( this.generationContext, this.beanRegistrationsCode); compile(method, (actual, compiled) -> { SourceFile sourceFile = compiled.getSourceFile(".*BeanDefinitions"); assertThat(sourceFile).contains("Get the bean definition for 'testBean'"); assertThat(sourceFile).contains("setInstanceSupplier(TestBean::new)"); assertThat(actual).isInstanceOf(RootBeanDefinition.class); }); } @Test void generateBeanDefinitionMethodWhenHasInnerClassTargetMethodGeneratesMethod() { this.beanFactory.registerBeanDefinition("testBeanConfiguration", new RootBeanDefinition( InnerBeanConfiguration.Simple.class)); RootBeanDefinition beanDefinition = new RootBeanDefinition(SimpleBean.class); beanDefinition.setFactoryBeanName("testBeanConfiguration"); beanDefinition.setFactoryMethodName("simpleBean"); RegisteredBean registeredBean = registerBean(beanDefinition); BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, registeredBean, null, Collections.emptyList()); MethodReference method = generator.generateBeanDefinitionMethod( this.generationContext, this.beanRegistrationsCode); compile(method, (actual, compiled) -> { SourceFile sourceFile = compiled.getSourceFile(".*BeanDefinitions"); assertThat(sourceFile.getClassName()).endsWith("InnerBeanConfiguration__BeanDefinitions"); assertThat(sourceFile).contains("public static class Simple") .contains("Bean definitions for {@link InnerBeanConfiguration.Simple}") .doesNotContain("Another__BeanDefinitions"); }); } @Test void generateBeanDefinitionMethodWhenHasNestedInnerClassTargetMethodGeneratesMethod() { this.beanFactory.registerBeanDefinition("testBeanConfiguration", new RootBeanDefinition( InnerBeanConfiguration.Simple.Another.class)); RootBeanDefinition beanDefinition = new RootBeanDefinition(SimpleBean.class); beanDefinition.setFactoryBeanName("testBeanConfiguration"); beanDefinition.setFactoryMethodName("anotherBean"); RegisteredBean registeredBean = registerBean(beanDefinition); BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, registeredBean, null, Collections.emptyList()); MethodReference method = generator.generateBeanDefinitionMethod( this.generationContext, this.beanRegistrationsCode); compile(method, (actual, compiled) -> { SourceFile sourceFile = compiled.getSourceFile(".*BeanDefinitions"); assertThat(sourceFile.getClassName()).endsWith("InnerBeanConfiguration__BeanDefinitions"); assertThat(sourceFile).contains("public static class Simple") .contains("Bean definitions for {@link InnerBeanConfiguration.Simple}") .contains("public static class Another") .contains("Bean definitions for {@link InnerBeanConfiguration.Simple.Another}"); }); } @Test void generateBeanDefinitionMethodWhenHasGenericsGeneratesMethod() { RootBeanDefinition beanDefinition = new RootBeanDefinition(); beanDefinition.setTargetType(ResolvableType.forClassWithGenerics(GenericBean.class, Integer.class)); RegisteredBean registeredBean = registerBean(beanDefinition); BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, registeredBean, null, Collections.emptyList()); MethodReference method = generator.generateBeanDefinitionMethod( this.generationContext, this.beanRegistrationsCode); compile(method, (actual, compiled) -> { assertThat(actual.getResolvableType().resolve()).isEqualTo(GenericBean.class); SourceFile sourceFile = compiled.getSourceFile(".*BeanDefinitions"); assertThat(sourceFile).contains("Get the bean definition for 'testBean'"); assertThat(sourceFile).contains( "setTargetType(ResolvableType.forClassWithGenerics(GenericBean.class, Integer.class))"); assertThat(sourceFile).contains("setInstanceSupplier(GenericBean::new)"); assertThat(actual).isInstanceOf(RootBeanDefinition.class); }); } @Test void generateBeanDefinitionMethodWhenHasExplicitResolvableType() { RootBeanDefinition beanDefinition = new RootBeanDefinition(One.class); beanDefinition.setResolvedFactoryMethod(ReflectionUtils.findMethod(TestHierarchy.class, "oneBean")); beanDefinition.setTargetType(Two.class); RegisteredBean registeredBean = registerBean(beanDefinition); BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, registeredBean, null, Collections.emptyList()); MethodReference method = generator.generateBeanDefinitionMethod( this.generationContext, this.beanRegistrationsCode); compile(method, (actual, compiled) -> assertThat(actual.getResolvableType().resolve()).isEqualTo(Two.class)); } @Test void generateBeanDefinitionMethodWhenHasInstancePostProcessorGeneratesMethod() { RegisteredBean registeredBean = registerBean(new RootBeanDefinition(TestBean.class)); BeanRegistrationAotContribution aotContribution = (generationContext, beanRegistrationCode) -> { GeneratedMethod generatedMethod = beanRegistrationCode.getMethods().add("postProcess", method -> method.addModifiers(Modifier.STATIC) .addParameter(RegisteredBean.class, "registeredBean") .addParameter(TestBean.class, "testBean") .returns(TestBean.class).addCode("return new $T($S);", TestBean.class, "postprocessed")); beanRegistrationCode.addInstancePostProcessor(generatedMethod.toMethodReference()); }; List<BeanRegistrationAotContribution> aotContributions = Collections.singletonList(aotContribution); BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, registeredBean, null, aotContributions); MethodReference method = generator.generateBeanDefinitionMethod( this.generationContext, this.beanRegistrationsCode); compile(method, (actual, compiled) -> { assertThat(actual.getBeanClass()).isEqualTo(TestBean.class); InstanceSupplier<?> supplier = (InstanceSupplier<?>) actual.getInstanceSupplier(); try { TestBean instance = (TestBean) supplier.get(registeredBean); assertThat(instance.getName()).isEqualTo("postprocessed"); } catch (Exception ex) { } SourceFile sourceFile = compiled.getSourceFile(".*BeanDefinitions"); assertThat(sourceFile).contains("instanceSupplier.andThen("); }); } @Test // gh-28748 void generateBeanDefinitionMethodWhenHasInstancePostProcessorAndFactoryMethodGeneratesMethod() { this.beanFactory.registerBeanDefinition("testBeanConfiguration", new RootBeanDefinition(TestBeanConfiguration.class)); RootBeanDefinition beanDefinition = new RootBeanDefinition(TestBean.class); beanDefinition.setFactoryBeanName("testBeanConfiguration"); beanDefinition.setFactoryMethodName("testBean"); RegisteredBean registeredBean = registerBean(beanDefinition); BeanRegistrationAotContribution aotContribution = (generationContext, beanRegistrationCode) -> { GeneratedMethod generatedMethod = beanRegistrationCode.getMethods().add("postProcess", method -> method.addModifiers(Modifier.STATIC) .addParameter(RegisteredBean.class, "registeredBean") .addParameter(TestBean.class, "testBean") .returns(TestBean.class).addCode("return new $T($S);", TestBean.class, "postprocessed")); beanRegistrationCode.addInstancePostProcessor(generatedMethod.toMethodReference()); }; List<BeanRegistrationAotContribution> aotContributions = Collections.singletonList(aotContribution); BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, registeredBean, null, aotContributions); MethodReference method = generator.generateBeanDefinitionMethod( this.generationContext, this.beanRegistrationsCode); compile(method, (actual, compiled) -> { assertThat(compiled.getSourceFile(".*BeanDefinitions")).contains("BeanInstanceSupplier"); assertThat(actual.getBeanClass()).isEqualTo(TestBean.class); InstanceSupplier<?> supplier = (InstanceSupplier<?>) actual .getInstanceSupplier(); try { TestBean instance = (TestBean) supplier.get(registeredBean); assertThat(instance.getName()).isEqualTo("postprocessed"); } catch (Exception ex) { } SourceFile sourceFile = compiled.getSourceFile(".*BeanDefinitions"); assertThat(sourceFile).contains("instanceSupplier.andThen("); }); } @Test void generateBeanDefinitionMethodWhenHasCodeFragmentsCustomizerGeneratesMethod() { RegisteredBean registeredBean = registerBean(new RootBeanDefinition(TestBean.class)); BeanRegistrationAotContribution aotContribution = BeanRegistrationAotContribution.withCustomCodeFragments(this::customizeBeanDefinitionCode); List<BeanRegistrationAotContribution> aotContributions = Collections.singletonList(aotContribution); BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, registeredBean, null, aotContributions); MethodReference method = generator.generateBeanDefinitionMethod( this.generationContext, this.beanRegistrationsCode); compile(method, (actual, compiled) -> { assertThat(actual.getBeanClass()).isEqualTo(TestBean.class); SourceFile sourceFile = compiled.getSourceFile(".*BeanDefinitions"); assertThat(sourceFile).contains("I am custom"); }); } private BeanRegistrationCodeFragments customizeBeanDefinitionCode(BeanRegistrationCodeFragments codeFragments) { return new BeanRegistrationCodeFragmentsDecorator(codeFragments) { @Override public CodeBlock generateNewBeanDefinitionCode(GenerationContext generationContext, ResolvableType beanType, BeanRegistrationCode beanRegistrationCode) { CodeBlock.Builder code = CodeBlock.builder(); code.addStatement("// I am custom"); code.add(super.generateNewBeanDefinitionCode(generationContext, beanType, beanRegistrationCode)); return code.build(); } }; } @Test void generateBeanDefinitionMethodDoesNotGenerateAttributesByDefault() { RootBeanDefinition beanDefinition = new RootBeanDefinition(TestBean.class); beanDefinition.setAttribute("a", "A"); beanDefinition.setAttribute("b", "B"); RegisteredBean registeredBean = registerBean(beanDefinition); BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, registeredBean, null, Collections.emptyList()); MethodReference method = generator.generateBeanDefinitionMethod( this.generationContext, this.beanRegistrationsCode); compile(method, (actual, compiled) -> { assertThat(actual.hasAttribute("a")).isFalse(); assertThat(actual.hasAttribute("b")).isFalse(); }); } @Test void generateBeanDefinitionMethodWhenHasAttributeFilterGeneratesMethod() { RootBeanDefinition beanDefinition = new RootBeanDefinition(TestBean.class); beanDefinition.setAttribute("a", "A"); beanDefinition.setAttribute("b", "B"); RegisteredBean registeredBean = registerBean(beanDefinition); BeanRegistrationAotContribution aotContribution = BeanRegistrationAotContribution.withCustomCodeFragments(this::customizeAttributeFilter); List<BeanRegistrationAotContribution> aotContributions = Collections.singletonList(aotContribution); BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, registeredBean, null, aotContributions); MethodReference method = generator.generateBeanDefinitionMethod( this.generationContext, this.beanRegistrationsCode); compile(method, (actual, compiled) -> { assertThat(actual.getAttribute("a")).isEqualTo("A"); assertThat(actual.getAttribute("b")).isNull(); }); } private BeanRegistrationCodeFragments customizeAttributeFilter(BeanRegistrationCodeFragments codeFragments) { return new BeanRegistrationCodeFragmentsDecorator(codeFragments) { @Override public CodeBlock generateSetBeanDefinitionPropertiesCode(GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode, RootBeanDefinition beanDefinition, Predicate<String> attributeFilter) { return super.generateSetBeanDefinitionPropertiesCode(generationContext, beanRegistrationCode, beanDefinition, "a"::equals); } }; } @Test void generateBeanDefinitionMethodWhenInnerBeanGeneratesMethod() { RegisteredBean parent = registerBean(new RootBeanDefinition(TestBean.class)); RegisteredBean innerBean = RegisteredBean.ofInnerBean(parent, new RootBeanDefinition(AnnotatedBean.class)); BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, innerBean, "testInnerBean", Collections.emptyList()); MethodReference method = generator.generateBeanDefinitionMethod( this.generationContext, this.beanRegistrationsCode); compile(method, (actual, compiled) -> { assertThat(compiled.getSourceFile(".*BeanDefinitions")) .contains("Get the inner-bean definition for 'testInnerBean'"); assertThat(actual).isInstanceOf(RootBeanDefinition.class); }); } @Test void generateBeanDefinitionMethodWhenHasInnerBeanPropertyValueGeneratesMethod() { RootBeanDefinition innerBeanDefinition = (RootBeanDefinition) BeanDefinitionBuilder .rootBeanDefinition(AnnotatedBean.class) .setRole(BeanDefinition.ROLE_INFRASTRUCTURE).setPrimary(true) .getBeanDefinition(); RootBeanDefinition beanDefinition = new RootBeanDefinition(TestBean.class); beanDefinition.getPropertyValues().add("name", innerBeanDefinition); RegisteredBean registeredBean = registerBean(beanDefinition); BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, registeredBean, null, Collections.emptyList()); MethodReference method = generator.generateBeanDefinitionMethod( this.generationContext, this.beanRegistrationsCode); compile(method, (actual, compiled) -> { RootBeanDefinition actualInnerBeanDefinition = (RootBeanDefinition) actual .getPropertyValues().get("name"); assertThat(actualInnerBeanDefinition.isPrimary()).isTrue(); assertThat(actualInnerBeanDefinition.getRole()) .isEqualTo(BeanDefinition.ROLE_INFRASTRUCTURE); Supplier<?> innerInstanceSupplier = actualInnerBeanDefinition .getInstanceSupplier(); try { assertThat(innerInstanceSupplier.get()).isInstanceOf(AnnotatedBean.class); } catch (Exception ex) { throw new IllegalStateException(ex); } }); } @SuppressWarnings("unchecked") @Test void generateBeanDefinitionMethodWhenHasListOfInnerBeansPropertyValueGeneratesMethod() { RootBeanDefinition firstInnerBeanDefinition = (RootBeanDefinition) BeanDefinitionBuilder .rootBeanDefinition(TestBean.class).addPropertyValue("name", "one") .getBeanDefinition(); RootBeanDefinition secondInnerBeanDefinition = (RootBeanDefinition) BeanDefinitionBuilder .rootBeanDefinition(TestBean.class).addPropertyValue("name", "two") .getBeanDefinition(); ManagedList<RootBeanDefinition> list = new ManagedList<>(); list.add(firstInnerBeanDefinition); list.add(secondInnerBeanDefinition); RootBeanDefinition beanDefinition = new RootBeanDefinition(TestBean.class); beanDefinition.getPropertyValues().add("someList", list); RegisteredBean registeredBean = registerBean(beanDefinition); BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, registeredBean, null, Collections.emptyList()); MethodReference method = generator.generateBeanDefinitionMethod( this.generationContext, this.beanRegistrationsCode); compile(method, (actual, compiled) -> { ManagedList<RootBeanDefinition> actualPropertyValue = (ManagedList<RootBeanDefinition>) actual .getPropertyValues().get("someList"); assertThat(actualPropertyValue).hasSize(2); assertThat(actualPropertyValue.get(0).getPropertyValues().get("name")).isEqualTo("one"); assertThat(actualPropertyValue.get(1).getPropertyValues().get("name")).isEqualTo("two"); assertThat(compiled.getSourceFileFromPackage(TestBean.class.getPackageName())) .contains("getSomeListBeanDefinition()", "getSomeListBeanDefinition1()"); }); } @Test void generateBeanDefinitionMethodWhenHasInnerBeanConstructorValueGeneratesMethod() { RootBeanDefinition innerBeanDefinition = (RootBeanDefinition) BeanDefinitionBuilder .rootBeanDefinition(String.class) .setRole(BeanDefinition.ROLE_INFRASTRUCTURE).setPrimary(true) .getBeanDefinition(); RootBeanDefinition beanDefinition = new RootBeanDefinition(TestBean.class); ValueHolder valueHolder = new ValueHolder(innerBeanDefinition); valueHolder.setName("second"); beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, valueHolder); RegisteredBean registeredBean = registerBean(beanDefinition); BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, registeredBean, null, Collections.emptyList()); MethodReference method = generator.generateBeanDefinitionMethod( this.generationContext, this.beanRegistrationsCode); compile(method, (actual, compiled) -> { RootBeanDefinition actualInnerBeanDefinition = (RootBeanDefinition) actual .getConstructorArgumentValues() .getIndexedArgumentValue(0, RootBeanDefinition.class).getValue(); assertThat(actualInnerBeanDefinition.isPrimary()).isTrue(); assertThat(actualInnerBeanDefinition.getRole()) .isEqualTo(BeanDefinition.ROLE_INFRASTRUCTURE); Supplier<?> innerInstanceSupplier = actualInnerBeanDefinition .getInstanceSupplier(); try { assertThat(innerInstanceSupplier.get()).isInstanceOf(String.class); } catch (Exception ex) { throw new IllegalStateException(ex); } assertThat(compiled.getSourceFile(".*BeanDefinitions")) .contains("getSecondBeanDefinition()"); }); } @Test void generateBeanDefinitionMethodWhenHasAotContributionsAppliesContributions() { RegisteredBean registeredBean = registerBean( new RootBeanDefinition(TestBean.class)); List<BeanRegistrationAotContribution> aotContributions = new ArrayList<>(); aotContributions.add((generationContext, beanRegistrationCode) -> beanRegistrationCode.getMethods().add("aotContributedMethod", method -> method.addComment("Example Contribution"))); BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, registeredBean, null, aotContributions); MethodReference method = generator.generateBeanDefinitionMethod( this.generationContext, this.beanRegistrationsCode); compile(method, (actual, compiled) -> { SourceFile sourceFile = compiled.getSourceFile(".*BeanDefinitions"); assertThat(sourceFile).contains("AotContributedMethod()"); assertThat(sourceFile).contains("Example Contribution"); }); } @Test @CompileWithForkedClassLoader void generateBeanDefinitionMethodWhenPackagePrivateBean() { RegisteredBean registeredBean = registerBean(new RootBeanDefinition(PackagePrivateTestBean.class)); BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, registeredBean, null, Collections.emptyList()); MethodReference method = generator.generateBeanDefinitionMethod( this.generationContext, this.beanRegistrationsCode); compile(method, (actual, compiled) -> { DefaultListableBeanFactory freshBeanFactory = new DefaultListableBeanFactory(); freshBeanFactory.registerBeanDefinition("test", actual); Object bean = freshBeanFactory.getBean("test"); assertThat(bean).isInstanceOf(PackagePrivateTestBean.class); assertThat(compiled.getSourceFileFromPackage( PackagePrivateTestBean.class.getPackageName())).isNotNull(); }); } @Test void generateBeanDefinitionMethodWhenBeanIsInJavaPackage() { RootBeanDefinition beanDefinition = (RootBeanDefinition) BeanDefinitionBuilder .rootBeanDefinition(String.class).addConstructorArgValue("test").getBeanDefinition(); testBeanDefinitionMethodInCurrentFile(String.class, beanDefinition); } @Test void generateBeanDefinitionMethodWhenBeanIsInJavaxPackage() { RootBeanDefinition beanDefinition = (RootBeanDefinition) BeanDefinitionBuilder .rootBeanDefinition(DocumentBuilderFactory.class).setFactoryMethod("newDefaultInstance").getBeanDefinition(); testBeanDefinitionMethodInCurrentFile(DocumentBuilderFactory.class, beanDefinition); } @Test void generateBeanDefinitionMethodWhenBeanIsOfPrimitiveType() { RootBeanDefinition beanDefinition = (RootBeanDefinition) BeanDefinitionBuilder .rootBeanDefinition(Boolean.class).setFactoryMethod("parseBoolean").addConstructorArgValue("true").getBeanDefinition(); testBeanDefinitionMethodInCurrentFile(Boolean.class, beanDefinition); } @Test // gh-29556 void throwExceptionWithInstanceSupplierWithoutAotContribution() { RegisteredBean registeredBean = registerBean(new RootBeanDefinition(TestBean.class, TestBean::new)); assertThatIllegalArgumentException().isThrownBy(() -> new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, registeredBean, null, Collections.emptyList())); } private void testBeanDefinitionMethodInCurrentFile(Class<?> targetType, RootBeanDefinition beanDefinition) { RegisteredBean registeredBean = registerBean(new RootBeanDefinition(beanDefinition)); BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator( this.methodGeneratorFactory, registeredBean, null, Collections.emptyList()); MethodReference method = generator.generateBeanDefinitionMethod( this.generationContext, this.beanRegistrationsCode); compile(method, (actual, compiled) -> { DefaultListableBeanFactory freshBeanFactory = new DefaultListableBeanFactory(); freshBeanFactory.registerBeanDefinition("test", actual); Object bean = freshBeanFactory.getBean("test"); assertThat(bean).isInstanceOf(targetType); assertThat(compiled.getSourceFiles().stream().filter(sourceFile -> sourceFile.getClassName().startsWith(targetType.getPackageName()))).isEmpty(); }); } private RegisteredBean registerBean(RootBeanDefinition beanDefinition) { String beanName = "testBean"; this.beanFactory.registerBeanDefinition(beanName, beanDefinition); return RegisteredBean.of(this.beanFactory, beanName); } private void compile(MethodReference method, BiConsumer<RootBeanDefinition, Compiled> result) { this.beanRegistrationsCode.getTypeBuilder().set(type -> { CodeBlock methodInvocation = method.toInvokeCodeBlock(ArgumentCodeGenerator.none(), this.beanRegistrationsCode.getClassName()); type.addModifiers(Modifier.PUBLIC); type.addSuperinterface(ParameterizedTypeName.get(Supplier.class, BeanDefinition.class)); type.addMethod(MethodSpec.methodBuilder("get") .addModifiers(Modifier.PUBLIC) .returns(BeanDefinition.class) .addCode("return $L;", methodInvocation).build()); }); this.generationContext.writeGeneratedContent(); TestCompiler.forSystem().with(this.generationContext).compile(compiled -> result.accept((RootBeanDefinition) compiled.getInstance(Supplier.class).get(), compiled)); } }
package com.orlanth23.popularmovie.utils; import android.content.ContentValues; import com.orlanth23.popularmovie.data.MovieContract; import com.orlanth23.popularmovie.model.Movie; public class Utils { public static ContentValues transformMovieToContentValues(Movie movie){ ContentValues cv = new ContentValues(); cv.put(MovieContract.MovieEntry._ID, movie.getId()); cv.put(MovieContract.MovieEntry.COLUMN_BACKDROP_PATH, movie.getBackdrop_path()); cv.put(MovieContract.MovieEntry.COLUMN_VOTE_AVERAGE, movie.getVote_average()); cv.put(MovieContract.MovieEntry.COLUMN_RELEASE_DATE, movie.getRelease_date()); cv.put(MovieContract.MovieEntry.COLUMN_POSTER_PATH, movie.getPoster_path()); cv.put(MovieContract.MovieEntry.COLUMN_OVERVIEW, movie.getOverview()); cv.put(MovieContract.MovieEntry.COLUMN_ORIGINAL_TITLE, movie.getOriginal_title()); cv.put(MovieContract.MovieEntry.COLUMN_IMDB_ID, movie.getImdb_id()); return cv; } }
package com.gy.service.impl; import com.gy.entity.User; import com.gy.mapper.UserMapper; import com.gy.service.UserService; import com.gy.util.MD5Util; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @Author: liumin * @Description: * @Date: Created in 2018/3/23 10:39 */ @Service public class UserServiceImpl implements UserService{ @Autowired private UserMapper userMapper; @Override public User getUserByLoginNameAndPassword(String userId,String password) { String passwordStr = MD5Util.MD5Encode(userId+password,"utf-8",false); return userMapper.getUserByLoginNameAndPassword(userId,passwordStr); } @Override public List<User> findList() { return userMapper.findList(); } }
package bpmis.pxc.system.controller.core; import org.htmlparser.NodeFilter; import org.htmlparser.Parser; import org.htmlparser.filters.NodeClassFilter; import org.htmlparser.filters.TagNameFilter; import org.htmlparser.tags.ImageTag; import org.htmlparser.tags.LinkTag; import org.htmlparser.tags.TableColumn; import org.htmlparser.tags.TableRow; import org.htmlparser.tags.TableTag; import org.htmlparser.util.NodeList; public class Weather { // main ๆ–นๆณ•ๅ…ฅๅฃ public static void main(String[] args) { Weather crawler = new Weather(); crawler.wheather(); } // ๆŠ“ๅคฉๆฐ” public void wheather() { try { String content = ""; Parser parser = new Parser( "http://www.weather.com.cn/weather/101210401.shtml?");// ็”ฑไธญๅ›ฝๅคฉๆฐ”ๆไพ› NodeFilter nodeF = new NodeClassFilter(TableTag.class); NodeList nodeList = parser.parse(nodeF); for (int i = 0; i <= 2; i++) { if (nodeList.elementAt(i) instanceof TableTag) { TableTag tag = (TableTag) nodeList.elementAt(i); TableRow[] rows = tag.getRows(); for (int j = 0; j < rows.length; j++) { TableRow tr = (TableRow) rows[j]; TableColumn[] td = tr.getColumns(); for (int k = 0; k < td.length; k++) { content += td[k].toHtml(); } } } } Parser con = new Parser(content);// ็”ฑไธญๅ›ฝๅคฉๆฐ”ๆไพ› TagNameFilter filter = new TagNameFilter("a"); NodeList nodes = con.parse(filter); if (nodes.size() != 0) { LinkTag node = (LinkTag) nodes.elementAt(0); String today = node.getLinkText(); LinkTag node1 = (LinkTag) nodes.elementAt(2); String tianqi = node1.toPlainTextString(); LinkTag node2 = (LinkTag) nodes.elementAt(3); String high = node2.toPlainTextString(); LinkTag node3 = (LinkTag) nodes.elementAt(8); String low = node3.toPlainTextString(); System.out.println(today + " ," + tianqi + " " + low.trim() + "~" + high.trim()); LinkTag node01 = (LinkTag) nodes.elementAt(11); String today1 = node01.getLinkText(); LinkTag node11 = (LinkTag) nodes.elementAt(13); String tianqi1 = node11.toPlainTextString(); LinkTag node21 = (LinkTag) nodes.elementAt(14); String high1 = node21.toPlainTextString(); LinkTag node31 = (LinkTag) nodes.elementAt(19); String low1 = node31.toPlainTextString(); System.out.println(today1 + " ," + tianqi1 + " " + low1.trim() + "~" + high1.trim()); } Parser img = new Parser(content);// ็”ฑไธญๅ›ฝๅคฉๆฐ”ๆไพ› TagNameFilter img1 = new TagNameFilter("img"); NodeList imgnodes = img.parse(img1); if (imgnodes.size() != 0) { ImageTag imgtag = (ImageTag) imgnodes.elementAt(0); String src = imgtag.getImageURL(); System.out.println("src=http://www.weather.com.cn" + src); ImageTag imgtag1 = (ImageTag) imgnodes.elementAt(2); String src1 = imgtag1.getImageURL(); System.out.println("src=http://www.weather.com.cn" + src1); } } catch (Exception e) { // TODO: handle exception } } }
package org.beanone.xlogger; import org.slf4j.Logger; /** * Encapsulates the handling of logging on behalf of a logger. * * @author Hongyan Li * */ @FunctionalInterface public interface LoggingHandler { /** * Handles logging on behalf of the passed in logger. * * @param logger * a {@link Logger}. * @param snf * a {@link Stringnifier} that encapsulates the logic to turn * something to String. * @param t * the exception to include in logging. */ void handle(Logger logger, Stringnifier snf, Throwable t); }
package com.utiitsl.service; import java.util.List; import com.utiitsl.entity.FinancialDetailsEntity; import com.utiitsl.pojo.FinancialDetailsPojo; public interface FinancialDetailsService { public void savefinancialDetailsData(FinancialDetailsPojo financialDetailsPojo); public List<FinancialDetailsPojo> getfinancialDetailsData(); }
package com.mobdeve.ramos.isa; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import androidx.annotation.Nullable; public class DBHelper extends SQLiteOpenHelper { public static final String DBNAME = "Login.db"; public DBHelper( Context context) { super(context, "Login.db", null, 1); } @Override public void onCreate(SQLiteDatabase MyDB) { MyDB.execSQL("create Table users(username TEXT primary key, password TEXT )"); MyDB.execSQL("create Table images(imagename TEXT, image BLOB, username TEXT)"); MyDB.execSQL("create Table texts(text_type TEXT, text TEXT, date TEXT, username TEXT)"); // db for speech to text } @Override public void onUpgrade(SQLiteDatabase MyDB, int oldVersion, int newVersion) { MyDB.execSQL("drop Table if exists users"); MyDB.execSQL("drop Table if exists images"); MyDB.execSQL("drop Table if exists texts"); } public Boolean insertData(String username, String password){ SQLiteDatabase MyDB = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("username", username); //0 contentValues.put("password", password); //1 long result = MyDB.insert("users", null, contentValues); if(result ==-1) return false; else return true; } public Boolean insertImage(String imagename, byte[] image, String username){ SQLiteDatabase MyDB = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("imagename", imagename); contentValues.put("image", image); contentValues.put("username", username); long result = MyDB.insert("images", null, contentValues); //insert to images table if(result ==-1) return false; else return true; } public Boolean insertText(String text_type, String text, String date, String username){ SQLiteDatabase MyDB = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("text_type", text_type); //0 contentValues.put("text", text); //1 contentValues.put("date", date); //2 contentValues.put("username", username); //3 long result = MyDB.insert("texts", null, contentValues); if(result ==-1) return false; else return true; } public Cursor getText(String text_type, String username){ SQLiteDatabase MyDB = this.getWritableDatabase(); Cursor cursor = MyDB.rawQuery("Select * from texts where text_type = ? AND username = ?", new String[] {text_type, username}); return cursor; } public Cursor getimage(String imagename, String username){ SQLiteDatabase MyDB = this.getWritableDatabase(); Cursor cursor = MyDB.rawQuery("Select * from images where imagename = ? AND username = ?", new String[] {imagename, username}); return cursor; } public Boolean checkusername(String username){ SQLiteDatabase MyDB = this.getWritableDatabase(); Cursor cursor = MyDB.rawQuery("Select * from users where username = ?", new String[] {username}); if(cursor.getCount() > 0 ) return true; else return false; } public Boolean checkusernamepassword(String username, String password){ SQLiteDatabase MyDB = this.getWritableDatabase(); Cursor cursor = MyDB.rawQuery("Select * from users where username = ? and password = ?", new String[] {username,password}); if(cursor.getCount() > 0 ) return true; else return false; } public Cursor getUserCred(String username){ SQLiteDatabase MyDB = this.getWritableDatabase(); Cursor cursor = MyDB.rawQuery("Select * from users where username = ?", new String[] {username}); return cursor; } public Boolean updateCreds(String username, String password){ SQLiteDatabase MyDB = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); if(username.isEmpty()){// update password only contentValues.put("password", password); //1 MyDB.update("users",contentValues,"username = ?", new String[] {username}); return true; } else{//update everything contentValues.put("username", username); //0 contentValues.put("password", password); //1 MyDB.update("users",contentValues,"username = ?", new String[] {username}); return true; } } public Cursor viewImages(String username){ SQLiteDatabase MyDB = this.getWritableDatabase(); Cursor cursor = MyDB.rawQuery("Select * from images WHERE username = ? ", new String[] {username}); return cursor; } }
/*Polymorphism: *A DeliveryBoys[Postman]Deliverd Letter, *A DeliveryBoYS[Zamato]Deliverd Fooood *A DeliveryBoys[flipkart]Deliverd parsal */ package com.journaldev; import java.util.Random; class DeliveryBoy { void deliver() { System.out.println("Delivering Item"); } public static void main(String[]args) { DeliveryBoy db= getDeliveryBoy(); db.deliver(); } private static DeliveryBoy getDeliveryBoy() { Random rand = new Random(); int num = rand.nextInt(10); return num %2 == 0 ? new PizzaDeliveryBoy():new Postman(); } } class PizzaDeliveryBoy extends DeliveryBoy { // @override void deliver() { System.out.println("Delivering Pizza"); } } class Postman extends DeliveryBoy { // @override void deliver() { System.out.println("Delivering Letters"); } }
import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TestGUI { public class TestGui extends GUI { public void clickSubmit() { submit.doClick(); } public void clickClear() { clear.doClick(); } public String getInput() { return input.getText(); } public void setInput(String text) { input.setText(text); } public String getOutput() { return output.getText(); } } public TestGui testGui; @Before public void init() { testGui = new TestGui(); testGui.setVisible(true); } @Test public void test1() throws Exception { String text = "df"; testGui.setInput(text); Assert.assertEquals(text, testGui.getInput()); } @Test public void test2() throws Exception { String text = "df"; testGui.setInput(text); testGui.clickClear(); Assert.assertTrue(testGui.getInput().isEmpty()); } @Test public void test3() throws Exception { for (int i = 0; i < 3; ++i) { String send = String.valueOf(i); testGui.setInput(send); testGui.clickSubmit(); Assert.assertEquals("balance", testGui.getOutput()); } } @Test public void test4() throws Exception { testGui.setInput("-1"); testGui.clickSubmit(); Assert.assertEquals("Not correct value", testGui.getOutput()); } @Test public void test5() throws Exception { testGui.setInput("5"); testGui.clickSubmit(); Assert.assertEquals("Not correct value", testGui.getOutput()); } @Test public void test6() throws Exception { testGui.setInput("5sdasd"); testGui.clickSubmit(); Assert.assertEquals("Input error", testGui.getOutput()); } }
package com.deepakm.impl.model; import com.deepakm.impl.Key; import java.util.*; /** * Created by dmarathe on 11/10/16. */ public class NoteFactory { private static Map<Key, NoteVertex> noteFactory = new HashMap<>(); static { noteFactory = new HashMap<>(); for (Key key : Key.values()) { noteFactory.put(key, new NoteVertex(key)); } for (Key key : Key.values()) { noteFactory.get(key).initialiseAdjecencyList(); } } public static NoteVertex get(Key note) { if (!noteFactory.containsKey(note)) { noteFactory.put(note, new NoteVertex(note)); } return noteFactory.get(note); } public static void main(String[] args) { NoteVertex vertex = NoteFactory.get(Key.C); System.out.println(vertex.getNote()); for (int i = 0; i < 12; i++) { System.out.println(vertex.getFastCache(i).getNote()); } } }
package com.jinglangtech.teamchat.activity; import android.app.Notification; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.os.Vibrator; import android.support.v4.app.NotificationCompat; import android.text.InputFilter; import android.text.InputType; import android.text.Spanned; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import com.jinglangtech.teamchat.App; import com.jinglangtech.teamchat.R; import com.jinglangtech.teamchat.listener.BaseListener; import com.jinglangtech.teamchat.model.LoginUser; import com.jinglangtech.teamchat.network.CommonModel; import com.jinglangtech.teamchat.network.NetWorkInterceptor; import com.jinglangtech.teamchat.util.ActivityContainer; import com.jinglangtech.teamchat.util.ConfigUtil; import com.jinglangtech.teamchat.util.Constant; import com.jinglangtech.teamchat.util.Key; import com.jinglangtech.teamchat.util.ToastUtil; import com.jinglangtech.teamchat.util.ToastUtils; import com.jinglangtech.teamchat.util.UuidUtil; import com.umeng.message.UTrack; import butterknife.BindView; import cn.jpush.android.api.JPushInterface; public class LoginActivity extends BaseActivity{ @BindView(R.id.editLoginName) EditText mEtName; @BindView(R.id.editPwd) EditText mEtPwd; @BindView(R.id.btn_login) Button mBtnLogin; @BindView(R.id.iv_lock) ImageView mIvOpen; private String mId; private String mName; private String mPwd; private String mAccount; private String mToken; private boolean mPwdOpen = false; private boolean mIsNotifyOpen = false; private ChatGroupActivity mGroupActivity; @Override public int getLayoutResourceId() { return R.layout.activity_login; } @Override public void initVariables() { mBtnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //test(); userLogin(); } }); } @Override public void initStatusColor(){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().setStatusBarColor(getResources().getColor(R.color.common_status_color)); } } // ๆ•่Žท่ฟ”ๅ›ž้”ฎ็š„ๆ–นๆณ•2 @Override public void onBackPressed() { Log.d("", "onBackPressed()"); //System.exit(0); super.onBackPressed(); ActivityContainer.getInstance().finishAllActivity(); //android.os.Process.killProcess(android.os.Process.myPid()); //่Žทๅ–PID } @Override public void initViews() { String userAccount = ConfigUtil.getInstance(this).get(Key.USER_ACCOUNT, ""); mEtName.setText(userAccount); mIvOpen.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mPwdOpen){ mPwdOpen = false; mEtPwd.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD); mIvOpen.setImageResource(R.mipmap.logologin_key_unlook); }else{ mPwdOpen = true; mEtPwd.setInputType(InputType.TYPE_CLASS_TEXT); mIvOpen.setImageResource(R.mipmap.logologin_key_look); } } }); mEtPwd.setFilters(new InputFilter[] { filter }); mEtName.setFilters(new InputFilter[] { filter }); } private final String FILTER_ASCII = "\\A\\p{ASCII}*\\z"; InputFilter filter = new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { if (!(source + "").matches(FILTER_ASCII)){ return ""; } return null; } }; @Override public void loadData() { //String uuid2 = UuidUtil.get24UUID(); //sendNotify(); mId = ConfigUtil.getInstance(this).get(Key.ID, ""); String userToken = ConfigUtil.getInstance(this).get(Key.TOKEN, ""); if (!TextUtils.isEmpty(userToken) && !TextUtils.isEmpty(mId)){ NetWorkInterceptor.setToken(userToken); setJPushAlias(); startChatPage(); } } private void userLogin(){ mName = mEtName.getText().toString(); if (TextUtils.isEmpty(mName)){ ToastUtils.showToast(LoginActivity.this, "่ฏท่พ“ๅ…ฅ็”จๆˆทๅ"); return; } mPwd = mEtPwd.getText().toString(); if (TextUtils.isEmpty(mPwd)){ ToastUtils.showToast(LoginActivity.this,"่ฏท่พ“ๅ…ฅๅฏ†็ "); return; } appLogin(mName, mPwd); } private void appLogin(String name, String pwd){ CommonModel.getInstance().login(name, pwd, new BaseListener(LoginUser.class){ @Override public void responseResult(Object infoObj, Object listObj, int code, boolean status) { super.responseResult(infoObj, listObj, code, status); LoginUser user = (LoginUser)infoObj; if (user != null){ NetWorkInterceptor.setToken(user.token); mAccount = user.account; mName = user.name; mId = user._id; mToken = user.token; mIsNotifyOpen = user.notification; ConfigUtil.getInstance(LoginActivity.this).put(Key.NOTICE_OPEN, mIsNotifyOpen); ConfigUtil.getInstance(LoginActivity.this).commit(); saveSp(); setJPushAlias(); startChatPage(); } } @Override public void requestFailed(boolean status, int code, String errorMessage) { super.requestFailed(status, code, errorMessage); ToastUtils.showToast(LoginActivity.this,"็™ปๅฝ•ๅคฑ่ดฅ" + (TextUtils.isEmpty(errorMessage)?"":errorMessage)); } }); } private void setJPushAlias(){ JPushInterface.setAlias(this, 888, mId); App mApp = (App)this.getApplication(); if (mApp != null && mApp.mPushAgent != null){ mApp.mPushAgent.addAlias(mId, "user_id", new UTrack.ICallBack() { @Override public void onMessage(boolean isSuccess, String message) { Log.e("AppStartActivity", "#### umeng push setAlias result: " + isSuccess ); Log.e("AppStartActivity", "#### umeng push setAlias message: " + message ); } }); // mApp.mPushAgent.setAlias(mId, "user_id", // new UTrack.ICallBack() { // @Override // public void onMessage(boolean isSuccess, String message) { // Log.e("LoginActivity", "#### umeng push setAlias result: " + isSuccess ); // Log.e("LoginActivity", "#### umeng push setAlias message: " + message ); // } // }); } } public void saveSp(){ ConfigUtil.getInstance(this).put(Key.ID, mId); ConfigUtil.getInstance(this).put(Key.USER_ACCOUNT, mAccount); ConfigUtil.getInstance(this).put(Key.USER_NAME, mName); ConfigUtil.getInstance(this).put(Key.USER_PWD, mPwd); ConfigUtil.getInstance(this).put(Key.TOKEN, mToken); ConfigUtil.getInstance(this).commit(); } public void startChatPage(){ Intent intent = new Intent(); intent.setClass(LoginActivity.this, ChatGroupActivity.class); startActivity(intent); finish(); } }
package br.com.bscpaz.organizador.vos; import java.time.LocalDate; public class PeriodoVO { private String pasta; private LocalDate inicio; private LocalDate fim; public PeriodoVO(String pasta, LocalDate inicio, LocalDate fim) { this.pasta = pasta; this.inicio = inicio; this.fim = fim; } public String getPasta() { return pasta; } public LocalDate getInicio() { return inicio; } public LocalDate getFim() { return fim; } }
package com.esum.wp.ims.monbatchinfo.base; import org.apache.commons.lang.StringUtils; import com.esum.appframework.dmo.BaseDMO; public abstract class BaseMonBatchInfo extends BaseDMO { public BaseMonBatchInfo() { initialize(); } protected void initialize() { batchId = ""; nodeId = ""; cronPattern = ""; useFlag = ""; batchClass = ""; regDate = ""; modDate = ""; } // primary key protected String batchId; protected String nodeId; // fields protected String cronPattern; protected String useFlag; protected String batchClass; protected String regDate; protected String modDate; public String getBatchId() { return batchId; } public void setBatchId(String batchId) { this.batchId = batchId; } public String getNodeId() { return nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } public String getCronPattern() { return cronPattern; } public void setCronPattern(String cronPattern) { this.cronPattern = cronPattern; } public String getUseFlag() { return useFlag; } public void setUseFlag(String useFlag) { this.useFlag = useFlag; } public String getBatchClass() { return batchClass; } public void setBatchClass(String batchClass) { this.batchClass = batchClass; } public String getRegDate() { return regDate; } public void setRegDate(String regDate) { this.regDate = regDate; } public String getModDate() { return modDate; } public void setModDate(String modDate) { this.modDate = modDate; } }
package forms; import core.ActionManager; import documents.Copy; import javafx.collections.FXCollections; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.layout.GridPane; import javafx.stage.Stage; import javafx.util.Callback; import storage.DatabaseManager; import users.Session; import users.UserCard; public class UserInfoForm { private Stage stage; private Scene scene; private Session session; private DatabaseManager databaseManager; private ActionManager actionManager; private int openUserCardID = -1; @FXML private GridPane userInfoPane; @FXML private ListView<UserCard> userListView; @FXML private Label nameLbl; @FXML private Label addressLbl; @FXML private Label phoneNumLbl; @FXML private Label idLbl; @FXML private Label typeLbl; @FXML private Label checkedOutLbl; @FXML private Label fineLbl; /** * Initialization and run new scene on the primary stage * @param primaryStage != null; * @param currentSession != null */ public void startForm(Stage primaryStage, Session currentSession, DatabaseManager databaseManager, ActionManager actionManager) throws Exception{ this.session = currentSession; this.stage = primaryStage; this.databaseManager = databaseManager; this.actionManager = actionManager; sceneInitialization(); stage.setScene(scene); stage.show(); } /** * Initialization scene and scene's elements * All elements will be initialized */ private void sceneInitialization() throws Exception { FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLFiles/UserInfoForm.fxml")); loader.setController(this); GridPane root = loader.load(); this.scene = new Scene(root,1000,700); elementsInitialization(); userListView.setItems(FXCollections.observableArrayList(databaseManager.getAllUsers())); userListView.setCellFactory(new Callback<ListView<UserCard>, ListCell<UserCard>>() { public ListCell<UserCard> call(ListView<UserCard> userListView) { return new ListCell<UserCard>() { @Override protected void updateItem(UserCard user, boolean flag) { super.updateItem(user, flag); if (user != null) { setText(user.name + " " + user.surname); } } }; } }); } private void elementsInitialization(){ userListView = (ListView<UserCard>) scene.lookup("#userListView"); userInfoPane = (GridPane) scene.lookup("#userInfoPane"); nameLbl = (Label) scene.lookup("#nameLbl"); addressLbl = (Label) scene.lookup("#addressLbl"); typeLbl = (Label) scene.lookup("#typeLbl"); phoneNumLbl = (Label) scene.lookup("#phoneNumLbl"); idLbl = (Label) scene.lookup("#idLbl"); checkedOutLbl = (Label) scene.lookup("#checkedOutLbl"); fineLbl = (Label) scene.lookup("#fineLbl"); } public UserCard selectUserCard(int id){ openUserCardID = id; return databaseManager.getUserCard(databaseManager.getUserCardsID()[openUserCardID]); } /** * Select element of Document List View Event */ @FXML public void selectUserListView(){ //get selected element if(userListView.getSelectionModel().getSelectedIndex() > -1) { //If no document was opened if(openUserCardID == -1){ userInfoPane.setVisible(true); } //Set document info UserCard chosenUser = selectUserCard(userListView.getSelectionModel().getSelectedIndex()); nameLbl.setText(chosenUser.name); addressLbl.setText(chosenUser.address); phoneNumLbl.setText(chosenUser.phoneNumb); idLbl.setText(Integer.toString(chosenUser.getId())); typeLbl.setText(chosenUser.userType.getClass().getName().replace("users.", "")); fineLbl.setText(Integer.toString(chosenUser.getFine(chosenUser, session,databaseManager))); StringBuilder stringBuilder = new StringBuilder(); for(Copy c:chosenUser.checkedOutCopies){ stringBuilder.append(databaseManager.getDocuments(c.getDocumentID()).title); stringBuilder.append("(" + c.getDueDate()); stringBuilder.append("), "); } checkedOutLbl.setText(stringBuilder.toString()); } } @FXML public void clickOnBackBtn() throws Exception { MainForm mainForm = new MainForm(); mainForm.startForm(stage, session, databaseManager, actionManager); } }
package Problem_1806; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String buf = br.readLine(); long N = Long.parseLong(buf.split(" ")[0]); long S = Long.parseLong(buf.split(" ")[1]); long[] arr = new long[(int)N]; buf = br.readLine(); StringTokenizer st = new StringTokenizer(buf); for(int i = 0; i<N;i++) { arr[i] = Long.parseLong(st.nextToken()); } int pl=0; int sum = 0; int answer = Integer.MAX_VALUE; for(int pr = 0; pr <N; pr++) { sum+=arr[pr]; while(sum >= S) { if(answer > pr-pl+1) { answer = pr-pl+1; } sum-=arr[pl]; pl++; } } if(answer != Integer.MAX_VALUE) System.out.println(answer); else System.out.println(0); } }
package com.pwq.Callable; import java.util.concurrent.Callable; /** * @Author๏ผšWenqiangPu * @Description * @Date๏ผšCreated in 9:41 2017/8/4 * @Modified By๏ผš */ public class TaskWithResult implements Callable<String> { private int id; public TaskWithResult(int id) { this.id = id; } @Override public String call() throws Exception { System.out.println("call()ๆ–นๆณ•่ขซ่ฐƒ็”จ"+Thread.currentThread().getName()); for(int i=99999;i>0;i--); return "call()่ขซ่‡ชๅŠจ่ฐƒ็”จ๏ผŒไปปๅŠก็ป“ๆžœไธบ:"+id+" "+Thread.currentThread().getName(); } }
package com.example.calujord.iotapp; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Handler; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import com.parse.Parse; import com.parse.ParseException; import com.parse.ParseInstallation; import com.parse.ParseObject; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; import java.util.Set; import java.util.UUID; public class MainActivity extends AppCompatActivity { private static final int REQUEST_ENABLE_BT = 10; private ArrayList<String> mDeviceList = new ArrayList<String>(); BluetoothAdapter mBluetoothAdapter; BluetoothSocket mmSocket; BluetoothDevice mmDevice; OutputStream mmOutputStream; InputStream mmInputStream; Thread workerThread; byte[] readBuffer; int readBufferPosition; int counter; volatile boolean stopWorker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if(savedInstanceState == null){ try { Parse.initialize(new Parse.Configuration.Builder(getApplicationContext()) .applicationId(getResources().getString(R.string.parse_app_id)) .clientKey(getResources().getString(R.string.parse_app_key)) .server(getResources().getString(R.string.parse_server_url)) .build()); ParseInstallation.getCurrentInstallation().saveInBackground(); }catch (Exception e) { e.printStackTrace(); } } try{ find_bluetooth_devices(); open_bluetooth(); } catch (Exception ex){ } } private void open_bluetooth() throws IOException { UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid); mmSocket.connect(); mmOutputStream = mmSocket.getOutputStream(); mmInputStream = mmSocket.getInputStream(); beginListenForData(); } void beginListenForData(){ final Handler handler = new Handler(); final byte delimiter = 10; //This is the ASCII code for a newline character stopWorker = false; readBufferPosition = 0; readBuffer = new byte[1024]; workerThread = new Thread(new Runnable() { public void run() { while(!Thread.currentThread().isInterrupted() && !stopWorker) { try { int bytesAvailable = mmInputStream.available(); if(bytesAvailable > 0) { byte[] packetBytes = new byte[bytesAvailable]; mmInputStream.read(packetBytes); for(int i=0;i<bytesAvailable;i++) { byte b = packetBytes[i]; if(b == delimiter) { byte[] encodedBytes = new byte[readBufferPosition]; System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length); final String data = new String(encodedBytes, "US-ASCII"); readBufferPosition = 0; handler.post(new Runnable() { public void run() { publicar_parse(Double.parseDouble(data)); } }); } else { readBuffer[readBufferPosition++] = b; } } } } catch (IOException ex) { stopWorker = true; } } } }); workerThread.start(); } private void find_bluetooth_devices() { mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if(mBluetoothAdapter == null) { // myLabel.setText("No bluetooth adapter available"); } if(!mBluetoothAdapter.isEnabled()) { Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBluetooth, 0); } Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); if(pairedDevices.size() > 0) { for(BluetoothDevice device : pairedDevices){ mmDevice = device; } } // myLabel.setText("Bluetooth Device Found"); } public void publicar_parse(Double temperature){ ParseObject temp = new ParseObject("Temperatura"); Date d = new Date(); temp.put("fecha", d); temp.put("device", "Android"); temp.put("temperature", temperature); temp.saveInBackground(); Toast.makeText(this.getBaseContext(), "Transfiriendo a servidor "+temperature, Toast.LENGTH_LONG).show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package com.mycompany.time_table_management_system.componentconntroller; import java.sql.ResultSet; import java.sql.SQLException; import java.text.NumberFormat; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Admin */ public class AutoGenerate { public static String getNextID(JdbcTemplate jdbcTemplate,String table,String column,String prefix) { String id = prefix+"0000"; String sql= "SELECT "+column+" FROM "+table+" ORDER BY 1 DESC Limit 1"; List<String> list = jdbcTemplate.query(sql, new RowMapper<String>() { @Override public String mapRow(ResultSet rs, int rowNum) throws SQLException { return rs.getString(1); } }); try { if(!list.isEmpty()){ id=list.get(0); } System.out.println(id); int index = 0; for (int i = id.length() - 1; i >= 0; i--) { try { Integer.parseInt(id.substring(i)); } catch (Exception e) { index = i + 1; break; } System.out.println(id+" "+ index); } String newID = id.substring(index); int n = Integer.parseInt(newID); n++; NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumIntegerDigits(4); nf.setGroupingUsed(false);//no more 100,000 // nf.setMaximumFractionDigits(2); nf.setMinimumFractionDigits(2) ;// id=id.substring(0, index) + nf.format(n); } catch (Exception ex) { Logger.getLogger(AutoGenerate.class.getName()).log(Level.SEVERE, null, ex); } return id; } }
package net.mapthinks.web.rest; import net.mapthinks.domain.Maintenance; import net.mapthinks.repository.MaintenanceRepository; import net.mapthinks.repository.search.MaintenanceSearchRepository; import net.mapthinks.web.rest.common.AbstractPageableResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * REST controller for managing Maintenance. */ @RestController @RequestMapping("/api/maintenances") public class MaintenanceResource extends AbstractPageableResource<Maintenance,MaintenanceRepository,MaintenanceSearchRepository> { private final Logger log = LoggerFactory.getLogger(MaintenanceResource.class); private static final String ENTITY_NAME = "maintenance"; public MaintenanceResource(MaintenanceRepository maintenanceRepository, MaintenanceSearchRepository maintenanceSearchRepository) { super(maintenanceRepository,maintenanceSearchRepository); } }
package Graph_structural_descriptor; public interface graph_face { void setparam(String name, String nhash); }
/* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { StringBuffer sb = new StringBuffer(); String Serialize(TreeNode root) { // ๅช่ฆไฟๅญ˜ไธ‹ๆฅ็ฉบ่Š‚็‚นๅฐฑ่กŒ if (root==null){ sb.append("*,"); return null; } // ๅ‰ๅบ้ๅކ sb.append(root.val); sb.append(","); Serialize(root.left); Serialize(root.right); return sb.toString(); } private int i = 0; TreeNode Deserialize(String str) { if (str == null) return null; if (str.equals("*,")) return null; String[] strs = str.split(","); // int i = 0; TreeNode root = new TreeNode(Integer.parseInt(strs[i])); root.left = constructTree(strs); root.right = constructTree(strs); return root; } private TreeNode constructTree(String[] strs) { i++; if (strs[i].equals("*")) return null; TreeNode root = new TreeNode(Integer.parseInt(strs[i])); root.left = constructTree(strs); root.right = constructTree(strs); return root; } public static void main(String[] args) { Solution solution = new Solution(); // System.out.println(solution.); MyTree myTree = new MyTree(); String serialize = solution.Serialize(myTree.getRoot()); System.out.println(serialize); TreeNode deserialize = solution.Deserialize(serialize); System.out.println(deserialize.val); System.out.println(deserialize.left.val); } }
package com.beike.wap.dao; import java.util.List; import com.beike.dao.GenericDao; import com.beike.entity.merchant.MerchantProfileType; import com.beike.wap.entity.MMerchant; import com.beike.wap.entity.MMerchantProfileType; public interface MMerchantDao extends GenericDao<MMerchant, Long>{ /** * ๆ นๆฎid่Žทๅ–ๅ“็‰Œ * @param brandId * @return */ public MMerchant getBrandById(long brandId); /** * ๆ นๆฎๅ•†ๆˆทId่Žทๅ–ๅˆ†ๅบ— */ public List<MMerchant> getBranchIdByParentId(long brandId); /** * ่Žทๅพ—ๆŸไธชๅ•†ๆˆท็š„ๆ‰ฉๅฑ•ๅฑžๆ€ง * * @param merchantId * ๅ•†ๅฎถid * @param propertyname * ๅ•†ๅฎถๆ‰ฉๅฑ•ๅฑžๆ€งๅ็งฐ * @return */ public MMerchantProfileType getMerchantAvgEvationScoresByMerchantId(Long merchantId); public MMerchantProfileType getMerchantLogoByMerchantId(Long merchantId); /** * ๆ นๆฎๅ“็‰Œidๅˆ—่กจ่Žทๅ–ๅ“็‰Œๅˆ—่กจ * @param brandIds * @return */ public List<MMerchant> getBrandListByIds(String brandIds); /** * Desceription : ๆ นๆฎๅ•†ๅ“IDๅŽปๆŸฅ่ฏขๅ•†ๅ“ๆ‰€ๅฑžๅ“็‰Œ * @param goodsId * @return */ public MMerchant getBrandByGoodId(String goodsId); }
package com.school.sms.dao.impl; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.school.sms.dao.PurchaseDao; import com.school.sms.model.Customer; import com.school.sms.model.GeneralLedgerEntry; import com.school.sms.model.GradeMaster; import com.school.sms.model.Product; import com.school.sms.model.PurchaseReceipt; import com.school.sms.model.SalesReceipt; @Service("purchaseDaoService") @Transactional public class PurchaseDaoImpl implements PurchaseDao { private EntityManager entityManager; @PersistenceContext public void setEntityManager(EntityManager entityManager){ this.entityManager = entityManager; } @Override public void updateCustomer(Customer customer) { entityManager.merge(customer); entityManager.flush(); } @Override public List<Customer> loadCustomerList() { Query query = entityManager.createQuery("FROM Customer c order by c.customerCode ASC"); return query.getResultList(); } @Override public void deleteCustomer(Customer customer) { Customer grade = entityManager.find(Customer.class,customer.getCustomerCode()); entityManager.remove(grade); entityManager.flush(); } @Override public Customer findCustomer(String customerCode) { List list= entityManager.createQuery("FROM Customer c WHERE c.customerCode="+"'"+customerCode+"'").getResultList(); if(list.size()>0){ return (Customer) list.get(0); } return null; } @Override public List<Product> loadProductList() { Query query = entityManager.createQuery("FROM Product p order by p.productParentCode ASC"); return query.getResultList(); } @Override public Product findProduct(String productParentCode) { List list= entityManager.createQuery("FROM Product p WHERE p.productParentCode="+"'"+productParentCode+"'").getResultList(); if(list.size()>0){ return (Product) list.get(0); } return null; } @Override public void updateProduct(Product product) { entityManager.merge(product); entityManager.flush(); } @Override public void deleteProduct(Product product) { Product grade = entityManager.find(Product.class,product.getProductParentCode()); entityManager.remove(grade); entityManager.flush(); } @Override public void updatePurchaseReceipt(PurchaseReceipt purchaseReceipt) { entityManager.merge(purchaseReceipt); entityManager.flush(); } @Override public void deletePurchaseReceipt(PurchaseReceipt purchaseReceipt) { PurchaseReceipt purchaseReceipt1 = entityManager.find(PurchaseReceipt.class,purchaseReceipt.getReceiptNo()); entityManager.remove(purchaseReceipt1); entityManager.flush(); } @Override public PurchaseReceipt findPurchaseReceipt(Integer receiptNo) { List list= entityManager.createQuery("FROM PurchaseReceipt p WHERE p.receiptNo="+"'"+receiptNo+"'").getResultList(); if(list.size()>0){ return (PurchaseReceipt) list.get(0); } return null; } @Override public Integer getcurrentReceiptNo() { Integer max = (Integer) entityManager.createQuery("select max(p.receiptNo) from PurchaseReceipt p").getSingleResult(); if(max==null){ max=0; } return max; } @Override public Integer getCurrentCustomerCode() { Integer max = (Integer) entityManager.createQuery("select max(p.customerCode) from Customer p").getSingleResult(); if(max==null){ max=0; } return max; } @Override public Integer getCurrentProductCode() { Integer max = (Integer) entityManager.createQuery("select max(p.productParentCode) from Product p").getSingleResult(); if(max==null){ max=0; } return max; } @Override public Integer getcurrentChallanNo() { Integer max = (Integer) entityManager.createQuery("select max(p.challanNo) from SalesReceipt p").getSingleResult(); if(max==null){ max=0; } return max; } @Override public void updateSalesReceipt(SalesReceipt salesReceipt) { entityManager.merge(salesReceipt); entityManager.flush(); } @Override public void deleteSalesReceipt(SalesReceipt salesReceipt) { SalesReceipt salesReceipt1 = entityManager.find(SalesReceipt.class,salesReceipt.getChallanNo()); entityManager.remove(salesReceipt1); entityManager.flush(); } @Override public SalesReceipt findSalesReceipt(Integer challanNo) { List list= entityManager.createQuery("FROM SalesReceipt p WHERE p.challanNo="+"'"+challanNo+"'").getResultList(); if(list.size()>0){ return (SalesReceipt) list.get(0); } return null; } @Override public List<PurchaseReceipt> loadPurchaseReceipts() { Query query = entityManager.createQuery("FROM PurchaseReceipt p order by p.receiptNo DESC"); return query.getResultList(); } @Override public List<SalesReceipt> loadSalesReceipts() { Query query = entityManager.createQuery("FROM SalesReceipt p order by p.challanNo DESC"); return query.getResultList(); } @Override public List<GeneralLedgerEntry> loadGeneralLedgers() { Query query = entityManager.createQuery("FROM GeneralLedgerEntry p order by p.glCode DESC"); return query.getResultList(); } @Override public GeneralLedgerEntry findGeneralLedgerEntry(Integer glCode) { List list= entityManager.createQuery("FROM GeneralLedgerEntry p WHERE p.glCode="+"'"+glCode+"'").getResultList(); if(list.size()>0){ return (GeneralLedgerEntry) list.get(0); } return null; } @Override public GeneralLedgerEntry updateSalesReceipt(GeneralLedgerEntry entry) { GeneralLedgerEntry entry2 = entityManager.merge(entry); entityManager.flush(); return entry2; } @Override public void deleteGeneralLedgerEntry(GeneralLedgerEntry generalLedger) { GeneralLedgerEntry entry = entityManager.find(GeneralLedgerEntry.class,generalLedger.getGlCode()); entityManager.remove(entry); entityManager.flush(); } }
package symapQuery; import java.awt.Color; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import symap.projectmanager.common.Project; import util.Utilities; import java.util.Collections; import java.util.Vector; import backend.Utils; public class LocalQueryPanel extends JPanel { private static final long serialVersionUID = 2804096298674364175L; private static final String [] HELP_COL = { "General","","", "","","","","","","","","", "1. Annotation String search:", "2. Include/Exclude", "3. Only synteny hits", "4. Show only hits to"," included species", "5. Show orhpan genes","", "6. Show only hits in a "," collinear gene pair", "7. Show only groups having"," no annotation to"," included species", "8. Require complete interlinking"," of included species", }; private static final String [] HELP_VAL = { "The query returns hits (anchors) between genomes.", "The hits are grouped into cross-species groups ", "based on sequence overlap.", "Filters 1,3,6 filter the hits before grouping.", "Filter 4 filters hits after grouping, i.e. groups", "are built, but not all their hits are shown.", "Filters 2,7,8 filter groups as a whole, i.e. no", "hits in the group are shown if group does not pass.", "Filter 5 causes single-species annotations to be shown", "in addition to hits.", "", "Filters:", "Only use hits annotated with the given keyword", "Only show groups that include/do not include this species", "Only use hits which are in synteny blocks", "Only show hits involving at least one of the included", " species (note that groups are formed before this filter)", "Show annotations which do not overlap a hit in the result", " list. Keyword filter is applied to annotations" , "Only use hits which are part of a collinear set of ", " two or more homologous genes", "Only show groups for which no hit has an annotation", " to an included species", "", "Only show groups for which all included species pairs are", " linked by hits", }; public LocalQueryPanel(SyMAPQueryFrame parentFrame) { theParentFrame = parentFrame; pnlStepOne = new CollapsiblePanel("1. Filter hits", ""); pnlStepTwo = new CollapsiblePanel("2. Filter putative gene families (PgeneFs)", ""); pnlStepThree = new CollapsiblePanel("3. Filter displayed hits", ""); createSpeciesPanel(); setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); setBackground(Color.WHITE); JPanel searchPanel = createStringSearchPanel(); JPanel buttonPanel = createButtonPanel(searchPanel.getPreferredSize().width); add(buttonPanel); add(Box.createVerticalStrut(25)); pnlStepOne.add(Box.createVerticalStrut(10)); pnlStepOne.add(searchPanel); pnlStepOne.add(Box.createVerticalStrut(25)); pnlStepOne.add(speciesPanel); pnlStepOne.add(createFilterPanel()); pnlStepOne.collapse(); pnlStepOne.expand(); pnlStepTwo.add(createFilterGroupPanel()); pnlStepTwo.collapse(); pnlStepTwo.expand(); pnlStepThree.add(createFilterHitPanel()); pnlStepThree.collapse(); pnlStepThree.expand(); add(pnlStepOne); add(Box.createVerticalStrut(5)); add(pnlStepTwo); add(Box.createVerticalStrut(5)); add(pnlStepThree); add(Box.createVerticalStrut(5)); } public String getSubQuery() { String retVal = ""; //Species selection int numSpecies = speciesPanel.getNumSpecies(); if(numSpecies > 0) { // retVal = combineBool(retVal, getRefGroupQuery(), true); retVal = combineBool(retVal, getAnnoLocalFilter(), true); if (isNonself()) retVal = combineBool(retVal, " PH.proj1_idx != PH.proj2_idx ", true); retVal = combineBool(retVal, getPairGroupQuery(), true); } return retVal; } public String getAnnotSubQuery() { String retVal = ""; //Species selection int numSpecies = speciesPanel.getNumSpecies(); if(numSpecies > 0) { // retVal = combineBool(retVal, getRefGroupQuery(), true); retVal = combineBool(retVal, getAnnoLocalFilter(), true); retVal = combineBool(retVal, getAnnotGroupQueryAll(), true); } return retVal; } public String getSubQuerySummary() { String retVal = "", temp = ""; //Species selection int numSpecies = speciesPanel.getNumSpecies(); if(numSpecies > 0) { // temp = getRefGroupQuerySummary(); // if(temp.length() > 0) // retVal += "[" + temp + "]"; temp = getAnnoLocalFilterSummary(); if(temp.length() > 0) retVal += "[" + temp + "]"; temp = getPairGroupQuerySummary(); if(temp.length() > 0) retVal += "[" + temp + "]"; if(isSynteny()) retVal += "[Only synteny hits]"; } return retVal; } public boolean isSynteny() { return chkSynteny.isSelected(); } public boolean isCollinear() { return chkCollinear.isSelected(); } public boolean isClique() { return chkClique.isSelected(); } public boolean isUnannot() { return chkUnannot.isSelected(); } public boolean isOnlyIncluded() { return chkIncludeOnly.isSelected(); } public boolean isOrphan() { return chkOrphan.isSelected(); } public boolean isNonself() { return true; } //chkNonself.isSelected(); } private String getAnnoLocalFilter() { return getAnnotationNameFilter(); } private String getAnnoLocalFilterSummary() { return getAnnotationNameFilterSummary(); } private String getAnnotationNameFilter() { String text = txtAnnotation.getText(); if(text.length() == 0) return ""; return "PA.name LIKE '%" + text + "%'"; } private String getAnnotationNameFilterSummary() { String text = txtAnnotation.getText(); if(text.length() == 0) return ""; return "Annotation contains: " + text; } // private String getRefGroupQuery() { //If searching all, no reference in the query // if(btnAnnoAll.isSelected()) return ""; // int index =speciesPanel.getChromosomeIndex(speciesPanel.getReferenceIndex()); // if(index < 0) // { // int idx = speciesPanel.getSpeciesIndex(speciesPanel.getReferenceIndex()); // return " (PH.proj1_idx = " + idx + " OR PH.proj2_idx = " + idx + ") "; // } // return " (PH.grp1_idx = " + index + " OR PH.grp2_idx = " + index + ") "; // } /* private String getRefGroupQuery2() { //If searching all, no reference in the query if(btnAnnoAll.isSelected()) return ""; int index =speciesPanel.getChromosomeIndex(speciesPanel.getReferenceIndex()); if(index < 0) return "G.proj_idx = " + speciesPanel.getSpeciesIndex(speciesPanel.getReferenceIndex()); return "G.idx = " + index; } */ // private String getRefGroupQuerySummary() { // String retVal = "Reference: "; // if(btnAnnoAll.isSelected()) return ""; // String theChrom = speciesPanel.getChromosome(speciesPanel.getReferenceIndex()); // String theSpecies = speciesPanel.getSpecies(speciesPanel.getReferenceIndex()); // // retVal += "Species: " + theSpecies; // if(theChrom.length() > 0) // retVal += ", Chr: " + theChrom; // return retVal; // } private String getPairGroupQuery() { return getPairGroupQueryAll(); } private String getPairGroupQuerySummary() { // if(btnAnnoRef.isSelected()) // return getPairGroupQueryRefSummary(); return getPairGroupQueryAllSummary(); } // If changed, must change getAnnotGroupQueryAll()!!! private String getPairGroupQueryAll() { String retVal = ""; int numSpecies = speciesPanel.getNumSpecies(); Vector<String> speciesIn = new Vector<String>(); Vector<String> grpIn = new Vector<String>(); Vector<String> locList = new Vector<String>(); // Vector<String> locList2 = new Vector<String>(); // Vector<String> clauses = new Vector<String>(); for(int x=0; x<numSpecies; x++) { int index = speciesPanel.getChromosomeIndex(x); //Species selected only, no chromosome if(index < 0) { int idx = speciesPanel.getSpeciesIndex(x); speciesIn.add(String.valueOf(idx)); } else { grpIn.add(String.valueOf(index)); String start = speciesPanel.getChromosomeStart(x); String stop = speciesPanel.getChromosomeStop(x); if(start.length() > 0 && stop.length() > 0) { String tempLeft = "PH.grp1_idx != " + index; String tempRight = "PH.grp2_idx != " + index; tempLeft = "(" + combineBool(tempLeft, "greatest(" + start + ", PH.start1) <= least(" + stop + ", PH.end1)", false) + ")"; tempRight = "(" + combineBool(tempRight, "greatest(" + start + ", PH.start2) <= least(" + stop + ", PH.end2)", false) + ")"; locList.add(tempLeft); locList.add(tempRight); } } } Vector<String> allClauses = new Vector<String>(); String specInClause = null; String grpInClause = null; if (speciesIn.size() > 0) { specInClause = "(" + Utils.join(speciesIn, ",") + ")"; } if (grpIn.size() > 0) { grpInClause = "(" + Utils.join(grpIn, ",") + ")"; } String inClause = null; if (specInClause != null) { if (grpInClause != null) { inClause = " ( "; inClause += "((PH.proj1_idx IN " + specInClause + ") OR (PH.grp1_idx IN " + grpInClause + "))"; inClause += " AND "; inClause += "((PH.proj2_idx IN " + specInClause + ") OR (PH.grp2_idx IN " + grpInClause + "))"; inClause += " ) "; } else { inClause = " ( "; inClause += " (PH.proj1_idx IN " + specInClause + ") "; inClause += " AND "; inClause += "(PH.proj2_idx IN " + specInClause + ")"; inClause += " ) "; } } else { inClause = " ( "; inClause += " (PH.grp1_idx IN " + grpInClause + ") "; inClause += " AND "; inClause += "(PH.grp2_idx IN " + grpInClause + ")"; inClause += " ) "; } if (inClause != null) allClauses.add(inClause); String locClause = null; if (locList.size() > 0) { locClause = Utils.join(locList, " AND "); } if (locClause != null) allClauses.add(locClause); retVal = (allClauses.size() > 0 ? "(" + Utils.join(allClauses, " AND ") + ")" : ""); return retVal; } // Chrom/Location part of the orphan query, exactly parallel to getPairGroupQueryAll()!!! private String getAnnotGroupQueryAll() { String retVal = ""; int numSpecies = speciesPanel.getNumSpecies(); Vector<String> speciesIn = new Vector<String>(); Vector<String> grpIn = new Vector<String>(); Vector<String> locList = new Vector<String>(); // Vector<String> locList2 = new Vector<String>(); // Vector<String> clauses = new Vector<String>(); for(int x=0; x<numSpecies; x++) { int index = speciesPanel.getChromosomeIndex(x); //Species selected only, no chromosome if(index < 0) { int idx = speciesPanel.getSpeciesIndex(x); speciesIn.add(String.valueOf(idx)); } else { grpIn.add(String.valueOf(index)); String start = speciesPanel.getChromosomeStart(x); String stop = speciesPanel.getChromosomeStop(x); if(start.length() > 0 && stop.length() > 0) { String tempLeft = "PA.grp_idx != " + index; tempLeft = "(" + combineBool(tempLeft, "greatest(" + start + ", PA.start) <= least(" + stop + ", PA.end)", false) + ")"; locList.add(tempLeft); } } } Vector<String> allClauses = new Vector<String>(); String specInClause = null; String grpInClause = null; if (speciesIn.size() > 0) { specInClause = "(" + Utils.join(speciesIn, ",") + ")"; } if (grpIn.size() > 0) { grpInClause = "(" + Utils.join(grpIn, ",") + ")"; } String inClause = null; if (specInClause != null) { if (grpInClause != null) { inClause = "((G1.proj_idx IN " + specInClause + ") OR (PA.grp_idx IN " + grpInClause + "))"; } else { inClause = " (G1.proj_idx IN " + specInClause + ") "; } } else { inClause = " (PA.grp_idx IN " + grpInClause + ") "; } if (inClause != null) allClauses.add(inClause); String locClause = null; if (locList.size() > 0) { locClause = Utils.join(locList, " AND "); } if (locClause != null) allClauses.add(locClause); allClauses.add(" (PA.type='gene') "); retVal = (allClauses.size() > 0 ? "(" + Utils.join(allClauses, " AND ") + ")" : ""); return retVal; } private String getPairGroupQueryAllSummary() { int numSpecies = speciesPanel.getNumSpecies(); String retVal = "Paired with "; //If by reference, only need to search all other species for(int x=0; x<numSpecies; x++) { String species = speciesPanel.getSpecies(x); String chroms = speciesPanel.getChromosome(x); if(!chroms.equals("All")) retVal += "(Species: " + species + ", Chr: " + chroms + ")"; else retVal += "(Species: " + species + ")"; } return retVal; } private String getPairGroupQueryRefSummary() { int numSpecies = speciesPanel.getNumSpecies(); String retVal = "Paired with "; //If by reference, only need to search all other species for(int x=1; x<numSpecies; x++) { String species = speciesPanel.getSpecies(x); String chroms = speciesPanel.getChromosome(x); if(!chroms.equals("All")) retVal += "(Species: " + species + ", Chr: " + chroms + ")"; else retVal += "(Species: " + species + ")"; } return retVal; } private static String combineBool(String left, String right, boolean isAND) { if(left.length() == 0) return right; if(right.length() == 0) return left; if(isAND) return left + " AND " + right; return left + " OR " + right; } public void addExecuteListener(ActionListener l) { btnExecute.addActionListener(l); } private JPanel createFilterPanel() { JPanel retVal = new JPanel(); retVal.setLayout(new BoxLayout(retVal, BoxLayout.PAGE_AXIS)); retVal.setAlignmentX(Component.LEFT_ALIGNMENT); retVal.setBackground(Color.WHITE); chkSynteny = new JCheckBox("Only synteny hits"); chkSynteny.setAlignmentX(Component.LEFT_ALIGNMENT); chkSynteny.setBackground(Color.WHITE); chkCollinear = new JCheckBox("Only hits in a collinear gene pair"); chkCollinear.setAlignmentX(Component.LEFT_ALIGNMENT); chkCollinear.setBackground(Color.WHITE); chkOrphan = new JCheckBox("Show orphan genes"); chkOrphan.setAlignmentX(Component.LEFT_ALIGNMENT); chkOrphan.setBackground(Color.WHITE); retVal.add(chkSynteny); retVal.add(chkCollinear); retVal.add(chkOrphan); return retVal; } private JPanel createFilterGroupPanel() { JPanel retVal = new JPanel(); retVal.setLayout(new BoxLayout(retVal, BoxLayout.PAGE_AXIS)); retVal.setAlignmentX(Component.LEFT_ALIGNMENT); retVal.setBackground(Color.WHITE); Vector<Project> theProjects = theParentFrame.getProjects(); incSpecies = new JCheckBox[theProjects.size()]; for(int x=0; x<incSpecies.length; x++) { incSpecies[x] = new JCheckBox(theProjects.get(x).getDisplayName()); incSpecies[x].setBackground(Color.WHITE); } exSpecies = new JCheckBox[theProjects.size()]; for(int x=0; x<exSpecies.length; x++) { exSpecies[x] = new JCheckBox(theProjects.get(x).getDisplayName()); exSpecies[x].setBackground(Color.WHITE); } Vector<String> sortedGroups = new Vector<String> (); for(int x=0; x<theProjects.size(); x++) { if(!sortedGroups.contains(theProjects.get(x).getCategory())) sortedGroups.add(theProjects.get(x).getCategory()); } Collections.sort(sortedGroups); for(int grpIdx=0; grpIdx<sortedGroups.size(); grpIdx++) { String groupName = sortedGroups.get(grpIdx); boolean firstOne = true; JPanel tempRow = new JPanel(); tempRow.setLayout(new BoxLayout(tempRow, BoxLayout.LINE_AXIS)); tempRow.setBackground(Color.WHITE); tempRow.setAlignmentX(Component.LEFT_ALIGNMENT); tempRow.add(new JLabel("Include: ")); for(int x=0; x<incSpecies.length; x++) { if(groupName.equals(theProjects.get(x).getCategory())) { if(firstOne) { retVal.add(Box.createVerticalStrut(10)); if(sortedGroups.size() > 1) retVal.add(new JLabel(groupName)); firstOne = false; } tempRow.add(incSpecies[x]); tempRow.add(Box.createHorizontalStrut(5)); } } retVal.add(tempRow); tempRow = new JPanel(); tempRow.setLayout(new BoxLayout(tempRow, BoxLayout.LINE_AXIS)); tempRow.setBackground(Color.WHITE); tempRow.setAlignmentX(Component.LEFT_ALIGNMENT); tempRow.add(new JLabel("Exclude: ")); for(int x=0; x<exSpecies.length; x++) { if(groupName.equals(theProjects.get(x).getCategory())) { if(firstOne) { retVal.add(Box.createVerticalStrut(10)); if(sortedGroups.size() > 1) retVal.add(new JLabel(groupName)); firstOne = false; } tempRow.add(exSpecies[x]); tempRow.add(Box.createHorizontalStrut(5)); } } retVal.add(tempRow); } chkUnannot = new JCheckBox("No annotation to included species"); chkClique = new JCheckBox("Complete linkage of included species"); chkUnannot.setAlignmentX(Component.LEFT_ALIGNMENT); chkUnannot.setBackground(Color.WHITE); chkClique.setAlignmentX(Component.LEFT_ALIGNMENT); chkClique.setBackground(Color.WHITE); retVal.add(Box.createVerticalStrut(10)); retVal.add(chkUnannot); retVal.add(chkClique); retVal.setMaximumSize(retVal.getPreferredSize()); return retVal; } private JPanel createFilterHitPanel() { JPanel retVal = new JPanel(); retVal.setLayout(new BoxLayout(retVal, BoxLayout.PAGE_AXIS)); retVal.setAlignmentX(Component.LEFT_ALIGNMENT); retVal.setBackground(Color.WHITE); chkIncludeOnly = new JCheckBox("Show only hits to the included species"); chkIncludeOnly.setBackground(Color.WHITE); retVal.add(chkIncludeOnly); retVal.setMaximumSize(retVal.getPreferredSize()); return retVal; } public boolean isInclude(int species) { return incSpecies[species].isSelected(); } public boolean isExclude(int species) { return exSpecies[species].isSelected(); } private JPanel createButtonPanel(int width) { int totalWidth = 0; JPanel retVal = new JPanel(); retVal.setLayout(new BoxLayout(retVal, BoxLayout.LINE_AXIS)); retVal.setAlignmentX(Component.LEFT_ALIGNMENT); retVal.setBackground(Color.WHITE); JButton btnExpand = new JButton("Expand All"); btnExpand.setBackground(Color.white); btnExpand.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { pnlStepOne.expand(); pnlStepTwo.expand(); pnlStepThree.expand(); } }); JButton btnCollapse = new JButton("Collapse All"); btnCollapse.setBackground(Color.white); btnCollapse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { pnlStepOne.collapse(); pnlStepTwo.collapse(); pnlStepThree.collapse(); } }); retVal.add(btnExpand); retVal.add(Box.createHorizontalStrut(5)); retVal.add(btnCollapse); retVal.add(Box.createHorizontalStrut(30)); btnExecute = new JButton("Do Search"); btnExecute.setAlignmentX(Component.CENTER_ALIGNMENT); btnExecute.setBackground(Color.WHITE); retVal.add(btnExecute); totalWidth += btnExecute.getPreferredSize().width; btnHelp = new JButton("Help"); btnHelp.setAlignmentX(Component.RIGHT_ALIGNMENT); btnHelp.setBackground(UserPrompt.PROMPT); totalWidth += btnHelp.getPreferredSize().width; retVal.add(Box.createHorizontalStrut(30)); btnHelp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { // UserPrompt.displayInfo("Query Help", HELP_TEXT); Utilities.showHTMLPage(null, "SyMAP Query Help", "/html/QueryHelp.html"); //UserPrompt.displayInfo(theParentFrame, "Query Help", HELP_COL, HELP_VAL, true); } }); retVal.add(btnHelp); retVal.setMaximumSize(retVal.getPreferredSize()); return retVal; } private JPanel createStringSearchPanel() { JPanel retVal = new JPanel(); retVal.setLayout(new BoxLayout(retVal, BoxLayout.PAGE_AXIS)); retVal.setBackground(Color.WHITE); JPanel annoPanel = new JPanel(); annoPanel.setLayout(new BoxLayout(annoPanel, BoxLayout.LINE_AXIS)); annoPanel.setBackground(Color.WHITE); annoPanel.add(new JLabel("Annotation String Search")); annoPanel.add(Box.createHorizontalStrut(10)); txtAnnotation = new JTextField(30); annoPanel.add(txtAnnotation); annoPanel.setMaximumSize(annoPanel.getPreferredSize()); annoPanel.setAlignmentX(LEFT_ALIGNMENT); retVal.add(annoPanel); return retVal; } private void createSpeciesPanel() { speciesPanel = new SpeciesSelectPanel(theParentFrame); } private SyMAPQueryFrame theParentFrame = null; //Search type controls private JTextField txtAnnotation = null; //Species public SpeciesSelectPanel speciesPanel = null; //Species Include/Exclude private JCheckBox [] incSpecies = null; private JCheckBox [] exSpecies = null; private CollapsiblePanel pnlStepOne = null, pnlStepTwo = null, pnlStepThree = null; //Other private JCheckBox chkSynteny = null, chkIncludeOnly = null, chkOrphan = null, chkCollinear = null, chkUnannot = null, chkClique = null; private JButton btnExecute = null; private JButton btnHelp = null; }
package guillaumeagis.perk4you; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.transition.ArcMotion; import android.view.View; import android.view.ViewGroup; import android.view.animation.AnimationUtils; import android.view.animation.Interpolator; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.zxing.WriterException; import java.math.BigInteger; import java.security.SecureRandom; import guillaumeagis.perk4you.utils.MorphButtonToDialog; import guillaumeagis.perk4you.utils.MorphDialogToButton; import guillaumeagis.perk4you.utils.Utils; public class PopupActivity extends Activity { boolean isDismissing = false; private ViewGroup container; private LinearLayout llCodeWebsite; private LinearLayout llQRCode; private String name; public static Intent getStartIntent(Context context, String type) { Intent intent = new Intent(context, PopupActivity.class); intent.putExtra(context.getString(R.string.mode), type); return intent; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_popup); String type = getIntent().getStringExtra(getString(R.string.mode)); name = getIntent().getStringExtra(getString(R.string.param_name)); if (name == null) name = getString(R.string.default_shop_name); // check type setupSharedElementTransitionsButton(this, container); container = (ViewGroup) findViewById(R.id.container); llCodeWebsite = (LinearLayout) findViewById(R.id.llCodeWebsite); llQRCode = (LinearLayout) findViewById(R.id.llQRCode); if (type.equals(getString(R.string.online_shopping_mode))) setupOnlineShopping(); else if (type.equals(getString(R.string.qr_code_mode))) setupQRCode(); TextView tvTitle = (TextView) findViewById(R.id.tvTitle); String text = String.format(getResources().getString(R.string.promo_code_title), name); tvTitle.setText(text); } private void setupOnlineShopping() { int percent = getIntent().getIntExtra("percent", 10); llCodeWebsite.setVisibility(View.VISIBLE); llQRCode.setVisibility(View.GONE); TextView tvPercentOff = (TextView) findViewById(R.id.tvPercentOff); String percentOff = String.format(getResources().getString(R.string.promo_code), percent + "%"); tvPercentOff.setText(percentOff); } private void setupQRCode() { llCodeWebsite.setVisibility(View.GONE); llQRCode.setVisibility(View.VISIBLE); ImageView imageView = (ImageView) findViewById(R.id.ivQRCode); try { Bitmap bitmap = Utils.encodeAsBitmap(name); imageView.setImageBitmap(bitmap); } catch (WriterException e) { e.printStackTrace(); } } public void setupSharedElementTransitionsButton(@NonNull Activity activity, @Nullable View target) { ArcMotion arcMotion = new ArcMotion(); arcMotion.setMinimumHorizontalAngle(50f); arcMotion.setMinimumVerticalAngle(50f); int color = ContextCompat.getColor(activity, R.color.colorAccent); Interpolator easeInOut = AnimationUtils.loadInterpolator(activity, android.R.interpolator.fast_out_slow_in); MorphButtonToDialog sharedEnter = new MorphButtonToDialog(color); sharedEnter.setPathMotion(arcMotion); sharedEnter.setInterpolator(easeInOut); MorphDialogToButton sharedReturn = new MorphDialogToButton(color); sharedReturn.setPathMotion(arcMotion); sharedReturn.setInterpolator(easeInOut); if (target != null) { sharedEnter.addTarget(target); sharedReturn.addTarget(target); } activity.getWindow().setSharedElementEnterTransition(sharedEnter); activity.getWindow().setSharedElementReturnTransition(sharedReturn); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); } public void dismiss(View view) { isDismissing = true; setResult(Activity.RESULT_CANCELED); finishAfterTransition(); } @Override public void onBackPressed() { dismiss(null); } }
package com.hillsidewatchers.connector.widget; import android.opengl.GLES20; import android.util.Log; import com.hillsidewatchers.connector.utils.Shader; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; /** * Created by ๆ›พ็ฟ”้’ฐ on 2016/7/31. */ public class Line { private int mProgram; private static final String TAG = "Line"; private float centerX; private float centerY; //ไธ€็›ด่ตทๅง‹็‚น private float startX = 0.0f; private float startY = 0.0f; private float endX = 0.0f; private float endY = 0.0f; private float unit; private float width = 100.0f; private float[] coorArr = { -0.1f, 0.1f, 0f,//ๅทฆไธŠ -0.1f, -0.1f, 0f,//ๅทฆไธ‹ 0.1f, -0.1f, 0f,//ๅณไธ‹ 0.1f, 0.1f, 0f,//ๅณไธŠ }; private FloatBuffer vertexBuffer; private final int COORDS_PER_VERTEX = 3; private final int vertexStride = COORDS_PER_VERTEX * 4; private final int vertexCount = coorArr.length / COORDS_PER_VERTEX; float color[] = {0.63671875f, 0.76953125f, 0.22265625f, 1.0f}; int flagX; int flagY; public Line(float centerX, float centerY) { vertexBuffer = (FloatBuffer) getVertexBuffer(coorArr); unit = centerY; this.centerX = centerX; this.centerY = centerY; initProgram(); } private void initProgram() { //่Žทๅ–็‚น็€่‰ฒๅ™จ int vertexShader = Shader.getVertexShader(); //่Žทๅ–็‰‡ๆฎต็€่‰ฒๅ™จ int fragmentShader = Shader.getFragmentShader(); // ๅˆ›ๅปบไธ€ไธช็ฉบ็š„OpenGL ES Program mProgram = GLES20.glCreateProgram(); // ๅฐ†vertexShaderๅ’Œfragment shaderๅŠ ๅ…ฅ่ฟ™ไธชprogram GLES20.glAttachShader(mProgram, vertexShader); // add the fragment shader to program GLES20.glAttachShader(mProgram, fragmentShader); // ่ฎฉprogramๅฏๆ‰ง่กŒ GLES20.glLinkProgram(mProgram); } public void draw(float[] mMVPMatrix) { GLES20.glUseProgram(mProgram); int vertexHandle = GLES20.glGetAttribLocation(mProgram, "vertexPosition"); GLES20.glVertexAttribPointer(vertexHandle, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, vertexStride, vertexBuffer); GLES20.glEnableVertexAttribArray(vertexHandle); int mvpMatrixHandle = GLES20.glGetUniformLocation(mProgram, "modelViewProjectionMatrix"); GLES20.glUniformMatrix4fv(mvpMatrixHandle, 1, false, mMVPMatrix, 0); int mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor"); GLES20.glUniform4fv(mColorHandle, 1, color, 0); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 0, vertexCount); GLES20.glDisableVertexAttribArray(vertexHandle); } /** * ่ฎพ็ฝฎ็บฟๆฎต็š„็ปˆ็‚นๅๆ ‡ * @param endX x * @param endY y */ public void setEndDrawCoor(float endX, float endY) { this.endX = endX; this.endY = endY; Log.e("endDraw", "" + endX + ", " + endY); double temp = Math.pow((startX - endX), 2) + Math.pow((endY - startY), 2); float distanceY = (float) ((Math.abs(endY - startY) * 0.5 * width) / (Math.sqrt(temp))); float distanceX = (float) ((Math.abs(endX - startX) * 0.5 * width) / (Math.sqrt(temp))); flagX = endX - startX < 0 ? -1 : 1; flagY = endY - startY < 0 ? -1 : 1; if (flagX * flagY > 0) { coorArr[0] = ((this.startX - distanceY) - centerX) / unit;//ๅทฆไธŠ-+ coorArr[1] = (-(this.startY + distanceX) + centerY) / unit; coorArr[3] = ((this.startX + distanceY) - centerX) / unit;//ๅทฆไธ‹-- coorArr[4] = (-(this.startY - distanceX) + centerY) / unit; coorArr[6] = ((this.endX + distanceY) - centerX) / unit;//ๅณไธ‹+- coorArr[7] = (-(this.endY - distanceX) + centerY) / unit; coorArr[9] = ((this.endX - distanceY) - centerX) / unit;//ๅณไธŠ++ coorArr[10] = (-(this.endY + distanceX) + centerY) / unit; } else { coorArr[0] = ((this.startX - distanceY) - centerX) / unit;//ๅทฆไธŠ-+ coorArr[1] = (-(this.startY - distanceX) + centerY) / unit; coorArr[3] = ((this.startX + distanceY) - centerX) / unit;//ๅทฆไธ‹-- coorArr[4] = (-(this.startY + distanceX) + centerY) / unit; coorArr[6] = ((this.endX + distanceY) - centerX) / unit;//ๅณไธ‹+- coorArr[7] = (-(this.endY + distanceX) + centerY) / unit; coorArr[9] = ((this.endX - distanceY) - centerX) / unit;//ๅณไธŠ++ coorArr[10] = (-(this.endY - distanceX) + centerY) / unit; } vertexBuffer = (FloatBuffer) getVertexBuffer(coorArr); } public void setStartDrawCoor(float startX, float startY) { this.startX = startX; this.startY = startY; Log.e("startDraw", "" + startX + ", " + startY); } public Buffer getVertexBuffer(float[] arr) { FloatBuffer mBuffer; //ๅ…ˆๅˆๅง‹ๅŒ–buffer,ๆ•ฐ็ป„็š„้•ฟๅบฆ*4,ๅ› ไธบไธ€ไธชintๅ 4ไธชๅญ—่Š‚ ByteBuffer qbb = ByteBuffer.allocateDirect(arr.length * 4); //ๆ•ฐ็ป„ๆŽ’ๅˆ—็”จnativeOrder qbb.order(ByteOrder.nativeOrder()); mBuffer = qbb.asFloatBuffer(); mBuffer.put(arr); mBuffer.position(0); return mBuffer; } public Buffer bufferUtilShort(short[] arr) { ShortBuffer mBuffer; ByteBuffer dlb = ByteBuffer.allocateDirect( // (# of coordinate values * 2 bytes per short) arr.length * 2); dlb.order(ByteOrder.nativeOrder()); mBuffer = dlb.asShortBuffer(); mBuffer.put(arr); mBuffer.position(0); return mBuffer; } }
package com.wangzhu.spring.bean; /** * Bean็š„ไฝœ็”จๅŸŸ๏ผš<br/> * singleton๏ผšๅ•ไพ‹๏ผŒๆŒ‡ไธ€ไธชBeanๅฎนๅ™จไธญๅชๅญ˜ๅœจไธ€ไปฝ<br/> * prototype๏ผšๆฏๆฌก่ฏทๆฑ‚๏ผˆๆฏๆฌกไฝฟ็”จ๏ผ‰ๅˆ›ๅปบๆ–ฐ็š„ๅฎžไพ‹๏ผŒDestroyๆ–นๅผไธ็”Ÿๆ•ˆ<br/> * * @author wangzhu * @date 2015-3-7ไธŠๅˆ1:06:27 * */ public class BeanScope { public void say() { System.out.println("BeanScope say: " + this.hashCode()); } }
package co.bucketstargram.command.library; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import co.bucketstargram.common.Command; import co.bucketstargram.common.HttpRes; import co.bucketstargram.dao.LibraryDao; import co.bucketstargram.dto.LibraryDto; public class LibraryUpdate implements Command { @Override public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //์ˆ˜์ • ํŽ˜์ด์ง€์—์„œ ๊ฐ€์ ธ์˜จ ์ •๋ณด request.getParameterํ•˜๊ณ  //dao.updateํ•˜๊ณ  LibraryDao dao = new LibraryDao(); LibraryDto library = new LibraryDto(); boolean result = false; //library.set~ํ•ด์„œ ์ •๋ณด ๋‹ด๊ณ  library.setLibId(request.getParameter("libraryId")); library.setLibTitle(request.getParameter("libraryTitle")); library.setLibContents(request.getParameter("libraryContent")); library.setLibImagePath(request.getParameter("imagePath")); library.setLibType(request.getParameter("libraryType")); System.out.println(library.getLibId()); System.out.println(library.getLibTitle()); System.out.println(library.getLibContents()); System.out.println(library.getLibImagePath()); //dao์‹คํ–‰ result = dao.update(library); String viewPage = "LibraryForm.do"; //์ˆ˜์ •ํ•  ์ •๋ณด ๊ฐ€์ง€๋กœ ์ˆ˜์ • ํŽ˜์ด์ง€๋กœ ๊ฐ„๋‹ค. HttpRes.forward(request, response, viewPage); } }
package com.example.starbucksmobilerecreate; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.viewpager.widget.ViewPager; public class Login_Activity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ViewPager viewPager = findViewById(R.id.view_pager); viewPager.setAdapter(new Login_ViewPagerAdapter(getSupportFragmentManager())); } }
package toasty.messageinabottle.exception; import java.util.ArrayList; import java.util.Collections; import java.util.List; import toasty.messageinabottle.io.ExceptionContext; public class GlobalExceptionCache { private static final List<ExceptionContext> exceptions = new ArrayList<>(); public static synchronized void post(String title, Exception e) { exceptions.add(new ExceptionContext(title, e)); } public static synchronized List<ExceptionContext> get() { return Collections.unmodifiableList(new ArrayList<>(exceptions)); } }
/* * /* * * Copyright (C) Henryk Timur Domagalski * * * * 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 net.henryco.opalette.application.programs.sub.programs.color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.view.View; import android.widget.Button; import android.widget.TextView; import net.henryco.opalette.R; import net.henryco.opalette.api.glES.render.graphics.shaders.textures.extend.EdTexture; import net.henryco.opalette.api.utils.OPallAnimated; import net.henryco.opalette.api.utils.views.OPallViewInjector; import net.henryco.opalette.application.programs.sub.programs.AppAutoSubControl; import net.henryco.opalette.application.proto.AppMainProto; /** * Created by HenryCo on 30/03/17. */ public class BlackWhiteControl extends AppAutoSubControl<AppMainProto> { private static final int img_button_res = R.drawable.ic_filter_b_and_w_white_24dp; private static final int txt_button_res = R.string.control_black_white; private final EdTexture texture; public BlackWhiteControl(EdTexture texture) { super(img_button_res, txt_button_res); this.texture = texture; } @Override protected void onFragmentCreate(View view, AppMainProto context, @Nullable Bundle savedInstanceState) { OPallViewInjector<AppMainProto> controls = new OPallViewInjector<AppMainProto>(view, R.layout.black_white_layout) { @Override protected void onInject(AppMainProto context, View view) { final int fca = ContextCompat.getColor(context.getActivityContext(), TEXT_COLOR_BLACK_OVERLAY); final int fcb = 0xFF000000; Button buttonOn = (Button) view.findViewById(R.id.bwButtonOn); Button buttonOff = (Button) view.findViewById(R.id.bwButtonOff); TextView textOn = (TextView) view.findViewById(R.id.bwTextOn); TextView textOff = (TextView) view.findViewById(R.id.bwTextOff); textOn.setTextColor(texture.isBwEnable() ? fcb : fca); textOff.setTextColor(texture.isBwEnable() ? fca : fcb); buttonOn.setOnClickListener(v -> OPallAnimated.pressButton75_225(context.getActivityContext(), v, () -> { textOn.setTextColor(fcb); textOff.setTextColor(fca); texture.setBwEnable(true); context.getRenderSurface().update(); })); buttonOff.setOnClickListener(v -> OPallAnimated.pressButton75_225(context.getActivityContext(), v, () -> { textOff.setTextColor(fcb); textOn.setTextColor(fca); texture.setBwEnable(false); context.getRenderSurface().update(); })); } }; OPallViewInjector.inject(context.getActivityContext(), controls); } }
package wyrazenia; public class False extends Wyrazenie { static False singleton = new False(); public static False daj() { return singleton; } @Override public boolean wartosc(boolean... wartosciowanie_zmiennych) { return false; } @Override public String toString() { return "F"; } @Override protected String toString(int parent_precedence) { return toString(); } }
/** * All rights Reserved, Designed By www.tydic.com * @Title: ItemController.java * @Package com.taotao.rest.controller * @Description: TODO(็”จไธ€ๅฅ่ฏๆ่ฟฐ่ฏฅๆ–‡ไปถๅšไป€ไนˆ) * @author: axin * @date: 2019ๅนด2ๆœˆ14ๆ—ฅ ไธ‹ๅˆ9:49:55 * @version V1.0 * @Copyright: 2019 www.hao456.top Inc. All rights reserved. */ package com.taotao.rest.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.taotao.common.pojo.TaotaoResult; import com.taotao.rest.service.ItemService; /** * @Description: TODO * @ClassName: ItemController * @author: Axin * @date: 2019ๅนด2ๆœˆ14ๆ—ฅ ไธ‹ๅˆ9:49:55 * @Copyright: 2019 www.hao456.top Inc. All rights reserved. */ @Controller @RequestMapping("/item") public class ItemController { @Autowired private ItemService itemService; /** * @Description: ๆ นๆฎๅ•†ๅ“idๆŸฅ่ฏขๅ•†ๅ“ๅŸบๆœฌไฟกๆฏ * @Title: getItemBaseInfo * @param: @param itemId * @param: @return * @return: TaotaoResult * @throws */ @RequestMapping("/info/{itemId}") @ResponseBody public TaotaoResult getItemBaseInfo(@PathVariable("itemId") Long itemId){ return this.itemService.getItemBaseInfo(itemId); } /** * * @Description: ๆ นๆฎๅ•†ๅ“idๆŸฅ่ฏขๅ•†ๅ“ๆ่ฟฐ * @Title: getItemDesc * @param: @param itemId * @param: @return * @return: TaotaoResult * @throws */ @RequestMapping("/desc/{itemId}") @ResponseBody public TaotaoResult getItemDesc(@PathVariable("itemId") Long itemId){ return this.itemService.getItemDesc(itemId); } /** * @Description: ๆ นๆฎๅ•†ๅ“idๆŸฅ่ฏขๅ•†ๅ“่ง„ๆ ผ * @Title: getItemParam * @param: @param itemId * @param: @return * @return: TaotaoResult * @throws */ @RequestMapping("/param/{itemId}") @ResponseBody public TaotaoResult getItemParam(@PathVariable("itemId") Long itemId){ return this.itemService.getItemParam(itemId); } }
"Source Code" "Bad changes"
package com.example.demo; import java.io.File; import java.util.ArrayList; import java.util.List; public class Attempt { private File file; private boolean success; private boolean systemError; private List<String> errors; public Attempt(File file) { this.file = file; this.success = Boolean.TRUE; this.systemError = Boolean.FALSE; this.errors = new ArrayList<String>(); } public boolean isSuccess() { return this.success; } public boolean hasSystemError() { return this.systemError; } public List<String> getErrors() { return this.errors; } public File getFile() { return this.file; } public void addError(String error) { this.success = Boolean.FALSE; this.errors.add(error); } public void addSystemError(String systemError) { addError(systemError); this.systemError = Boolean.FALSE; } @Override public String toString() { return "Attempt["+this.file.getName()+ ", " + this.success+"]"; } }
package com.example.spring.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.example.spring.model.Employee; import com.example.spring.service.EmployeeService; @Controller public class EmployeeController { @Autowired EmployeeService empServices; @RequestMapping("/") public ModelAndView homePage() { ModelAndView mv = new ModelAndView(); mv.addObject("listEmployees",empServices.getAllEmployees()); mv.setViewName("index"); return mv; } @RequestMapping("/showNewEmployeeForm") public ModelAndView addEmployeePage() { ModelAndView mv = new ModelAndView(); Employee employee = new Employee(); mv.addObject("employee",employee); mv.setViewName("new_employee"); return mv; } @PostMapping("/saveEmployee") public ModelAndView saveEmployeeButton(@ModelAttribute("employee") Employee employee) { ModelAndView mv = new ModelAndView(); //Save the Employee to the DB empServices.saveEmployee(employee); mv.setViewName("redirect:/"); return mv; } @RequestMapping("/showFormForUpdate/{eid}") public ModelAndView upddateEmployeeButton(@PathVariable(value="eid")long eid) { ModelAndView mv = new ModelAndView(); //get employee from the service Employee employeeById = empServices.getEmployeeById(eid); //set employee as model attribute to pre-populate the form mv.addObject("employee", employeeById); mv.setViewName("update_employee"); return mv; } @GetMapping("/deleteEmployee/{eid}") public ModelAndView deleteEmployeeButton(@PathVariable(value="eid")long eid) { ModelAndView mv = new ModelAndView(); //call delete employee method empServices.deleteEmployeeById(eid); mv.setViewName("redirect:/"); return mv; } }
/* * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit. * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. * Vestibulum commodo. Ut rhoncus gravida arcu. */ package cn.huangqiqiang.halbum.entity; import android.os.Parcel; import android.os.Parcelable; /** * ๅœจๆญคๅ†™็”จ้€” * * @version V1.0 <ๆ่ฟฐๅฝ“ๅ‰็‰ˆๆœฌๅŠŸ่ƒฝ> * @FileName: cn.huangqiqiang.halbum.entity.LocalMedia.java * @author: ้ป„ๅ…ถๅผบ * @date: 2017-05-04 20:17 */ public class LocalMedia implements Parcelable { private String path; // ็‰ฉ็†ๅœฐๅ€ private String compressPath; private String cutPath; private long duration; private long lastUpdateAt; private boolean isChecked; private boolean isCut; public int position; private int num; private int type; private boolean compressed; public LocalMedia(String path, long lastUpdateAt, long duration, int type) { this.path = path; this.duration = duration; this.lastUpdateAt = lastUpdateAt; this.type = type; } public LocalMedia(String path, long duration, long lastUpdateAt, boolean isChecked, int position, int num, int type) { this.path = path; this.duration = duration; this.lastUpdateAt = lastUpdateAt; this.isChecked = isChecked; this.position = position; this.num = num; this.type = type; } public LocalMedia() { } protected LocalMedia(Parcel in) { path = in.readString(); compressPath = in.readString(); cutPath = in.readString(); duration = in.readLong(); lastUpdateAt = in.readLong(); isChecked = in.readByte() != 0; isCut = in.readByte() != 0; position = in.readInt(); num = in.readInt(); type = in.readInt(); compressed = in.readByte() != 0; } public static final Creator<LocalMedia> CREATOR = new Creator<LocalMedia>() { @Override public LocalMedia createFromParcel(Parcel in) { return new LocalMedia(in); } @Override public LocalMedia[] newArray(int size) { return new LocalMedia[size]; } }; public String getCutPath() { return cutPath; } public void setCutPath(String cutPath) { this.cutPath = cutPath; } public boolean isCut() { return isCut; } public void setCut(boolean cut) { isCut = cut; } public boolean isCompressed() { return compressed; } public void setCompressed(boolean compressed) { this.compressed = compressed; } public String getCompressPath() { return compressPath; } public void setCompressPath(String compressPath) { this.compressPath = compressPath; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public int getType() { return type; } public void setType(int type) { this.type = type; } public boolean isChecked() { return isChecked; } public void setChecked(boolean checked) { isChecked = checked; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public long getDuration() { return duration; } public void setDuration(long duration) { this.duration = duration; } public long getLastUpdateAt() { return lastUpdateAt; } public void setLastUpdateAt(long lastUpdateAt) { this.lastUpdateAt = lastUpdateAt; } public boolean getIsChecked() { return this.isChecked; } public void setIsChecked(boolean isChecked) { this.isChecked = isChecked; } public int getPosition() { return this.position; } public void setPosition(int position) { this.position = position; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeString(path); parcel.writeString(compressPath); parcel.writeString(cutPath); parcel.writeLong(duration); parcel.writeLong(lastUpdateAt); parcel.writeByte((byte) (isChecked ? 1 : 0)); parcel.writeByte((byte) (isCut ? 1 : 0)); parcel.writeInt(position); parcel.writeInt(num); parcel.writeInt(type); parcel.writeByte((byte) (compressed ? 1 : 0)); } }
package com.robin.sf5advice.beforeadvice_xml; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by robin on 2017/7/30. */ public class Client { public static void main(String[] args){ ApplicationContext applicationContext=new ClassPathXmlApplicationContext("before_advice.xml"); //่ฟ™้‡Œๆ˜ฏ้ขๅ‘ๆŽฅๅฃ็ผ–็จ‹ HeroInterface hero=(HeroInterface)applicationContext.getBean("hero"); hero.helpPool(); hero.saveBeauty(); } }
package com.google.apiguide.userinterface.notification; import android.app.Notification; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.NotificationCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.RemoteViews; import com.google.apiguide.R; /** * ็”จๆˆท็•Œ้ข-้€š็Ÿฅ * Created by kangren on 2017/12/13. */ public class NotificationActivity extends AppCompatActivity { private NotificationManager manager; private Notification notification; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notification); manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); findViewById(R.id.send_neteasy).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(NotificationActivity.this, NetEasyService.class); intent.putExtra(NetEasyService.COMMAND, NetEasyService.Command.START); NotificationActivity.this.startService(intent); } }); findViewById(R.id.normal).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { notification = new Notification.Builder(NotificationActivity.this) .setSmallIcon(R.drawable.ic_launcher_background) .setContentTitle("่ฟ™ๆ˜ฏๆ ‡้ข˜") .setContentText("่ฟ™ๆ˜ฏๅ†…ๅฎน") .setDefaults(Notification.DEFAULT_ALL) .build(); manager.notify(1, notification); } }); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); } }
package com.breakpoint.service.impl; import com.breakpoint.dao.BlogTopicMapper; import com.breakpoint.dto.LoginUserDto; import com.breakpoint.entity.BlogTopic; import com.breakpoint.entity.BlogTopicExample; import com.breakpoint.exception.BlogException; import com.breakpoint.service.TopicService; import com.breakpoint.util.GenerateIDUtils; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.Date; import java.util.List; /** * ๅšๅฎข็š„ๅ†…ๅฎน * * @author breakpoint/่ตต็ซ‹ๅˆš * @date 2018/05/05 */ @Slf4j @Service public class TopicServiceImpl implements TopicService { @Resource private BlogTopicMapper blogTopicMapper; @Transactional(rollbackFor = Exception.class) @Override public Object insert(String topicTile, String topicDesc, String topicText, String topicCategory, LoginUserDto loginUserDto) throws BlogException { if (StringUtils.isEmpty(topicTile)) { log.error("ๆ–‡็ซ ๆ ‡้ข˜ไธ่ƒฝไธบ็ฉบ"); throw new BlogException("ๆ–‡็ซ ๆ ‡้ข˜ไธ่ƒฝไธบ็ฉบ"); } if (StringUtils.isEmpty(topicDesc)) { log.error("ๆ–‡็ซ ๆ่ฟฐไธ่ƒฝไธบ็ฉบ"); throw new BlogException("ๆ–‡็ซ ๆ่ฟฐไธ่ƒฝไธบ็ฉบ"); } if (StringUtils.isEmpty(topicText)) { log.error("ๆ–‡็ซ ๅ†…ๅฎนไธ่ƒฝไธบ็ฉบ"); throw new BlogException("ๆ–‡็ซ ๅ†…ๅฎนไธ่ƒฝไธบ็ฉบ"); } if (StringUtils.isEmpty(topicCategory)) { log.error("ๆ–‡็ซ ็ฑปๅˆซไธ่ƒฝไธบ็ฉบ"); throw new BlogException("ๆ–‡็ซ ็ฑปๅˆซไธ่ƒฝไธบ็ฉบ"); } BlogTopic blogTopic = new BlogTopic(); blogTopic.setTopicId(GenerateIDUtils.generateId()); blogTopic.setTopicCategory(topicCategory); blogTopic.setTopicTitle(topicTile); blogTopic.setTopicDesc(topicDesc); blogTopic.setTopicText(topicText); blogTopic.setUserId(loginUserDto.getBlogUser().getUserNo()); Date nowTime = new Date(); blogTopic.setGmtCreate(nowTime); blogTopic.setGmtModified(nowTime); blogTopicMapper.insertSelective(blogTopic); return "SUCCESS"; } @Override public List<BlogTopic> selectByDateDesc() throws BlogException { BlogTopicExample blogTopicExample = new BlogTopicExample(); blogTopicExample.setOrderByClause("gmt_create desc"); return blogTopicMapper.selectByExampleWithBLOBs(blogTopicExample); } @Override public BlogTopic selectOneById(long topicId) throws BlogException { return blogTopicMapper.selectByTopicId(topicId); } }
package fr.pco.accenture.handler; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.Part; import com.google.gson.JsonIOException; import com.google.gson.JsonSyntaxException; 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.RDFResource; import fr.pco.accenture.factories.ClassesFactory; import fr.pco.accenture.factories.InstancesFactory; import fr.pco.accenture.factories.ModelsFactory; import fr.pco.accenture.factories.ProjectsFactory; import fr.pco.accenture.models.Class; import fr.pco.accenture.models.ClassSettings; import fr.pco.accenture.models.Instance; import fr.pco.accenture.models.Project; import fr.pco.accenture.models.PropertySettings; import fr.pco.accenture.utils.Files; import fr.pco.accenture.utils.Helper; import fr.pco.accenture.utils.JSON; /** * C'est la classe qui exรฉcute et construit la reponse de chaque requรชte */ public class Handler { private Map< String, String[]> params; // paramรจtres de la requรชte private String projectName; private Project project; private String className; private Class classe; private String instanceName; private Instance instance; /** * Cette mรฉthode est appelรฉe ร  chaque requรจte pour initialiser * le project, la classe et l'instance sur lesquels agit la requรจte */ public void init(Map< String, String[]> params){ this.params = params; if(params.containsKey("project")){ // Si un projet est spรฉcifiรฉ projectName = params.get("project")[0]; project = ProjectsFactory.get(projectName); if(project != null){ // Si le projet existe if(params.containsKey("class")){ // Si une classe est spรฉcifiรฉe className = params.get("class")[0]; classe = ClassesFactory.get(projectName, className); } else { className = null; classe = null; } if(params.containsKey("instance")){ // Si une instance est spรฉcifiรฉe instanceName = params.get("instance")[0]; instance = InstancesFactory.get(projectName, instanceName); } else { instanceName = null; instance = null; } } } else { projectName = null; project = null; className = null; classe = null; instanceName = null; instance = null; } } /** * Traitement de la requรจte * GET /api/projects * * Retourne la liste des projets */ public List<Project> getProjects(){ List<Project> result = new ArrayList<Project>(); for(String name : ProjectsFactory.getNames()) result.add(ProjectsFactory.get(name)); return result; } /** * Traitement de la requรจte * GET /api/classes * Paramรจtres de la requรจte: * project: le nom du project * * Retourne la liste des classes du projet */ public List<Class> getClasses(){ if(project == null) return null; List<Class> result = new ArrayList<Class>(); for(String name : ClassesFactory.getNames(projectName)){ result.add(ClassesFactory.get(projectName, name)); } return result; } /** * Traitement de la requรจte * GET /api/instances * Paramรจtres de la requรจte: * project: le nom du project * class: le nom de la classe * * Retourne la liste des instances de la classe spรฉcifiรฉe. * Si aucune classe n'est spรฉcifiรฉe; retourne toutes les instances du projet */ public List<Instance> getInstances(){ if(project == null || ( className != null && classe == null) ) return null; List<Instance> result = new ArrayList<Instance>(); if(className == null){ // Retourner toutes les instances for(String name : InstancesFactory.getNames(projectName)) result.add(InstancesFactory.get(projectName, name)); } else { for(String name : ClassesFactory.get(projectName, className).getInstances()) result.add(InstancesFactory.get(projectName, name)); } return result; } /** * Traitement de la requรจte * GET /api/class-settings * Paramรจtres de la requรจte: * project: le nom du project * class: le nom de la classe * * Retourne les prรฉfรฉrences de la classe */ public ClassSettings getClassSettings(){ if(project == null || classe == null) return null; return classe.getSetts(); } /** * Traitement de la requรจte * GET /api/instance * Paramรจtres de la requรจte: * project: le nom du project * instance: le nom de l'instance * * Retourne l'instance */ public Instance getInstance(){ return instance; } /** * Traitement de la requรจte * POST /api/projects * Paramรจtres de la requรจte: * name: le nom du project ร  crรฉer * file1, file2, file3: les fichiers du projet * * Crรฉe le dossier du projet et upload les fichiers puis le charge. * La rรฉponse prรฉcise si l'ajout a รฉtรฉ bien fait ou si une erreur s'est produit */ public Map<String, Object> addProject(String name, Part[] files) throws IOException { Map<String, Object> result = new HashMap<String, Object>(); if(ProjectsFactory.get(name) != null){ result.put("done", false); result.put("erreur", "Duplicated project name"); } else { String foldername = Files.projectFolderPath(name); File folder = new File(foldername); if( ! folder.mkdir() ){ result.put("done", false); result.put("erreur", "Cannot create the folder : " + foldername); } else { new File(Files.classesFolderPath(name)).mkdir(); for(int i = 0; i < 3; i ++){ InputStream in = files[i].getInputStream(); String filename = foldername + File.separator + Files.getFileNameFromPart(files[i]); OutputStream out = new FileOutputStream(new File(filename)); int read = 0; byte[] buffer = new byte[1024]; while((read = in.read(buffer)) != -1) out.write(buffer, 0, read); out.close(); } ModelsFactory.loadAll(); ProjectsFactory.loadAll(); ClassesFactory.loadAll(); InstancesFactory.loadAll(); if(ModelsFactory.get(name) != null && ProjectsFactory.get(name) != null) result.put("done", true); else { result.put("done", false); result.put("erreur", "Cannot load the project '" + name + "'"); } } } return result; } /** * Traitement de la requรจte * POST /api/instances * Paramรจtres de la requรจte: * project: le nom du project * class: le nom de la classe ร  laquelle on veut ajouter l'instance * instance: nom de l'instance ร  crรฉer * action: "create" * * Crรฉe une nouvelle instance. * La rรฉponse prรฉcise si la crรฉation a รฉtรฉ bien faite ou si une erreur s'est produit */ public Map<String, Object> addInstance() throws JsonIOException, JsonSyntaxException, FileNotFoundException { Map<String, Object> result = new HashMap<String, Object>(); if(project != null && classe != null && instanceName != null){ RDFResource r = ModelsFactory.get(projectName).getOWLNamedClass(className).createInstance(instanceName); ClassesFactory.load(projectName, ModelsFactory.get(projectName)); InstancesFactory.load(projectName); result.put("done", (r != null)); if(r == null) result.put("error", "Cannot create the instance '"+instanceName+"' for the class '"+className+"' of project '"+projectName+"'"); } else { result.put("done", false); result.put("error", "Missing project or class or instance names"); } return result; } /** * Traitement de la requรจte * POST /api/instances * Paramรจtres de la requรจte: * project: le nom du project * instance: nom de l'instance ร  supprimer * action: "remove" * * Supprime une instance. * La rรฉponse prรฉcise si la crรฉation a รฉtรฉ bien faite ou si une erreur s'est produit */ public Map<String, Object> removeInstance() throws JsonIOException, JsonSyntaxException, FileNotFoundException { Map<String, Object> result = new HashMap<String, Object>(); if(project != null && instanceName != null){ OWLIndividual instance = ModelsFactory.get(projectName).getOWLIndividual(instanceName); instance.delete(); ClassesFactory.load(projectName, ModelsFactory.get(projectName)); InstancesFactory.load(projectName); result.put("done", true); } else { result.put("done", false); result.put("error", "Missing project or instance name"); } return result; } /** * Traitement de la requรจte * POST /api/values * Paramรจtres de la requรจte: * project: le nom du project * instance: nom de l'instance * property: nom de la propriรฉtรฉ * value: la valeur de la propriรฉtรฉ * * Sauvegarde les valeurs de l'instance. * La rรฉponse prรฉcise si la sauvegarde a รฉtรฉ bien faite ou si une erreur s'est produit */ public Map<String, Object> saveValue() { Map<String, Object> result = new HashMap<String, Object>(); if(project != null && instanceName != null){ OWLModel model = ModelsFactory.get(projectName); Helper helper = new Helper(model); if(params.containsKey("property")){ OWLIndividual instance = model.getOWLIndividual(instanceName); if(instance != null){ RDFProperty p = model.getRDFProperty(params.get("property")[0]); if(p.getRangeDatatype() != null) { if(p.isFunctional()){ String val = ""; if(params.containsKey("value")) val = params.get("value")[0]; helper.removeValuesOfDatatypeProperty(instance, p.getName()); helper.addValueToDatatypeProperty(instance, p.getName(), val); } else { if(params.containsKey("value")){ helper.removeValuesOfDatatypeProperty(instance, p.getName()); for(String val : params.get("value")){ helper.addValueToDatatypeProperty(instance, p.getName(), val); System.out.println("Adding Value: " + val); } } else { // ... } } } else { helper.removeValuesOfObjectProperty(instance, p.getName()); if(params.containsKey("value")){ for(String value : params.get("value")) helper.addValueToObjectProperty(instance, p.getName(), value); } } InstancesFactory.load(projectName); result.put("done", true); } else { result.put("done", false); result.put("error", "Instance '" + instanceName + "' not found"); } } else { result.put("done", false); result.put("error", "Missing property name"); } } else { result.put("done", false); result.put("error", "Missing project or instance name"); } return result; } /** * Traitement de la requรจte * POST /api/class-settings * Paramรจtres de la requรจte: * project: le nom du project * class: nom de la classe * filters: liste des filtres ร  appliquer au instances de cette classe * separators: liste des separateurs des filtres * * Sauvegarde les prรฉfรฉrences de la classe * La rรฉponse prรฉcise si la sauvegarde a รฉtรฉ bien faite ou si une erreur s'est produit * @throws IOException */ public Map<String, Object> saveClassSettings() throws IOException{ Map<String, Object> result = new HashMap<String, Object>(); if(project == null){ result.put("done", false); result.put("error", "Missing project name"); } else if(className == null){ result.put("done", false); result.put("error", "Missing class name"); } else if(classe == null){ result.put("done", false); result.put("error", "Class '" + className + "' not found"); // } else if(!params.containsKey("filters") || !params.containsKey("separators")){ // result.put("done", false); // result.put("error", "Some request parameters are missing"); } else { List<String> filters = null; if(params.get("filters") != null) filters = Arrays.asList(params.get("filters")); List<String> separators = null; if(params.get("separators") != null) separators = Arrays.asList(params.get("separators")); ClassSettings cs = new ClassSettings(filters, separators); String path = Files.classSettingsFilePath(projectName, className); JSON.write(cs, path); System.out.println("filters: " + filters); System.out.println("separators: " + separators); System.out.println("Settings saved !"); ClassesFactory.loadOne(projectName, className); result.put("done", true); } return result; } public Object savePropertySettings() throws IOException { Map<String, Object> result = new HashMap<String, Object>(); if(project == null){ result.put("done", false); result.put("error", "Missing project name"); } else if(className == null){ result.put("done", false); result.put("error", "Missing class name"); } else if(classe == null){ result.put("done", false); result.put("error", "Class '" + className + "' not found"); } else if(!params.containsKey("property")){ result.put("done", false); result.put("error", "The property is missing"); } else { String propertyName = params.get("property")[0]; int x = Integer.parseInt(params.get("x")[0]); int y = Integer.parseInt(params.get("y")[0]); int w = Integer.parseInt(params.get("w")[0]); int h = Integer.parseInt(params.get("h")[0]); PropertySettings ps = new PropertySettings(x, y, w, h); String path = Files.propertySettingsFilePath(projectName, className, propertyName); JSON.write(ps, path); ClassesFactory.loadOne(projectName, className); result.put("done", true); } return result; } }
package com.egova.eagleyes; import com.egova.baselibrary.application.EgovaApplication; import com.egova.baselibrary.handler.UncaughtExceptionHandlerImpl; import com.egova.baselibrary.retrofit.RetrofitClient; import com.egova.baselibrary.util.SharedPreferencesUtil; import com.egova.eagleyes.constants.Constants; public class App extends EgovaApplication { @Override public void onCreate() { super.onCreate(); //ๆ–‡ไปถๅญ˜ๅ‚จๅˆๅง‹ๅŒ– SharedPreferencesUtil.init(this, Constants.SHARED_PREFERENCE_FILE_NAME); //้”™่ฏฏๆ—ฅๅฟ—ๆŠ“ๅ–ๅˆๅง‹ๅŒ– UncaughtExceptionHandlerImpl.getInstance().init(this, Constants.errorLogFolder, false, MainActivity.class); //็ฝ‘็ปœretrofit ้…็ฝฎๅˆๅง‹ๅŒ– RetrofitClient.getInstance().init(Constants.baseUrl, null).buildRetrofit(BuildConfig.DEBUG); } }
package com.kingnode.gou.entity; import java.math.BigDecimal; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import com.kingnode.xsimple.entity.AuditEntity; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; /** * @author 58120775@qq.com (chenchao) * ่ฎขๅ•ๆ˜Ž็ป†่กจ */ @Entity @Table(name="order_detail") public class OrderDetail extends AuditEntity{ private Long productId;//ไบงๅ“id private OrderHead orderHead;//่ฎขๅ•ๅคด่กจๅฏน่ฑก private String orderNo;//่ฎขๅ•็ผ–ๅท private BigDecimal price;//ไปทๆ ผ private BigDecimal orgPrice;//ๅŽŸๅง‹ไปทๆ ผ private Integer quatity;//ๆ•ฐ้‡ private String guige;//่ง„ๆ ผ public String getGuige(){ return guige; } public void setGuige(String guige){ this.guige=guige; } public Long getProductId(){ return productId; } public void setProductId(Long productId){ this.productId=productId; } public String getOrderNo(){ return orderNo; } public void setOrderNo(String orderNo){ this.orderNo=orderNo; } public BigDecimal getPrice(){ return price; } public void setPrice(BigDecimal price){ this.price=price; } public BigDecimal getOrgPrice(){ return orgPrice; } public void setOrgPrice(BigDecimal orgPrice){ this.orgPrice=orgPrice; } public Integer getQuatity(){ return quatity; } public void setQuatity(Integer quatity){ this.quatity=quatity; } @ManyToOne @JoinColumn(nullable=false, name="orderHead_id") @Cache(usage=CacheConcurrencyStrategy.READ_WRITE) public OrderHead getOrderHead(){ return orderHead; } public void setOrderHead(OrderHead orderHead){ this.orderHead=orderHead; } }
/* * Main is the entry point to the system. It asks the user to enter * a path for a source file to parse, and then parses the file at * that path. An error message is displayed to the console if an * error occurs during parsing. */ package edu.purduecal.compiler.main; import java.io.FileNotFoundException; import java.io.IOException; import edu.purduecal.compiler.console.Console; import edu.purduecal.compiler.console.IConsole; import edu.purduecal.compiler.error_handling.InvalidTokenException; import edu.purduecal.compiler.error_handling.ParsingException; import edu.purduecal.compiler.parser.IParser; import edu.purduecal.compiler.parser.ParseTable; import edu.purduecal.compiler.parser.TopDownParser; import edu.purduecal.compiler.scanner.IScanner; import edu.purduecal.compiler.scanner.Scanner; import edu.purduecal.compiler.scanner.TransitionTable; public class Main { public static void main(String[] args) { IConsole console = new Console(); String path = ""; if (args.length == 0) { //read path from user console.write("Enter the path of the file to parse:"); path = console.read(); } else if (args.length == 1) //get path as a command line argument path = args[0]; else { console.write("Usage: Either run the program with no arguments or supply a single path to the source file via a command line argument"); } IScanner scanner = null; try { scanner = new Scanner(path, new TransitionTable()); } catch (FileNotFoundException e) { console.write("File not found"); return; } IParser parser = new TopDownParser(scanner, new ParseTable()); try { parser.parse(); console.write("Source file accepted by parser"); } catch (IOException e) { console.write("Failed to read file"); } catch (InvalidTokenException e) { console.write(e.getMessage()); } catch (ParsingException e) { console.write(e.getMessage()); } } }
package hr.bosak_turk.planetdemo.fragments; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Html; import android.util.Base64; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import hr.bosak_turk.planetdemo.activities.MainActivity; import hr.bosak_turk.planetdemo.R; import hr.bosak_turk.planetdemo.StringHandling; public class ArticleFragment extends Fragment { private ImageView articleImage; private TextView articleTitle, articleContent, articleDate, articleAuthor; private WebView webView; private LinearLayout linearLayout; public ArticleFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_article, container, false); initWidgets(view); String image = getArguments().getString(MainActivity.IMAGE_URL); Glide.with(this).load(image).into(articleImage); String title = getArguments().getString(MainActivity.TITLE); articleTitle.setText(StringHandling.html2text(title)); String content = getArguments().getString(MainActivity.CONTENT); initWebview(view, content); // articleContent.setText(Html.fromHtml(content)); String date = StringHandling.modifyDate(getArguments().getString(MainActivity.DATE)); articleDate.setText(date); String author = getArguments().getString(MainActivity.AUTHOR); articleAuthor.setText(author); linearLayout.requestFocus(); return view; } public void initWebview(View view, String content){ webView = view.findViewById(R.id.webview); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { webView.setNestedScrollingEnabled(false); } WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setLoadWithOverviewMode(true); webSettings.setUseWideViewPort(true); webSettings.setMinimumFontSize(16); webSettings.setDefaultTextEncodingName("utf-8"); webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); webView.loadDataWithBaseURL(null, "<html> <meta name='viewport' content='width=device-width, initial-scale=1'>" + "<head>" + "<style> body { background: white; } a { word-wrap:break-word;} " + "p { color: #262626; font-family: 'Sans-Serif';} " + "h5{text-align:left; word-wrap:break-word;} " + "img { display: inline; height: auto; max-width: auto;} " + "iframe { max-width: 100%; max-height: 100%; display: block; padding:none; margin:none; border:none; line-height: 0; left:0; position:relative; overflow: hidden;}" + " </style></head><body style='margin:0; padding:0;'><img align=\\\"left\\\" > " + "<p><div dir='rtl'><center></center></div><p></body></html>" + content,"text/html","utf-8", null); } private void initWidgets(View view) { articleImage = view.findViewById(R.id.article_iv_img); articleTitle = view.findViewById(R.id.article_tv_blog_title); // articleContent = view.findViewById(R.id.article_tv_content); articleDate = view.findViewById(R.id.article_tv_uploadDate); articleAuthor = view.findViewById(R.id.article_tv_author); webView = view.findViewById(R.id.webview); linearLayout = view.findViewById(R.id.ll_articleFragment); } }
package januaryChallenge2018; import java.util.Scanner; public class MaximumScore { public static void main(String[] args) { Scanner scan= new Scanner(System.in); int t=scan.nextInt(); for(int i=0;i<t;i++) { int n=scan.nextInt(); int a[]= new int[n]; for(int j=0;j<n;j++) { a[j]=scan.nextInt(); } } } }
package com.clinic.dentist.services; import com.clinic.dentist.api.dao.IAppointmentDao; import com.clinic.dentist.api.dao.IClinicDao; import com.clinic.dentist.api.service.IClinicServices; import com.clinic.dentist.models.Clinic; import com.clinic.dentist.models.Dentist; import com.clinic.dentist.models.Maintenance; import com.clinic.dentist.repositories.ClinicRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import java.util.List; @Service @Component("clinicService") public class ClinicService implements IClinicServices { @Autowired @Qualifier("clinicDao") private IClinicDao clinicDao; public List<Clinic> findAll() { return clinicDao.getAll(); } public Clinic findClinicByAddress(String address) { return clinicDao.findClinicByAddress(address); } public Iterable<Maintenance> findMaintenancesByClinic(Long ClinicId) { return clinicDao.findMaintenancesByClinic(ClinicId); } public boolean checkExist(long id) { return clinicDao.checkExist(id); } public Clinic findById(Long id) { return clinicDao.findById(id); } public List<Dentist> findDentistsByClinic(Long clinicId) { return clinicDao.findDentistsByClinic(clinicId); } }
/* * 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 TiraLab.MetaStrat; import TiraLab.Controllers.Move; /** * * @author ColdFish */ public class P1 extends MetaStrategy { /** * Returns a move rotated by one * @param defaultMove the move to be rotated * @return the move gotten after rotation by one */ @Override public Move getMove(Move defaultMove) { super.previousMove = super.getMoveByRotating(1, defaultMove); return super.previousMove; } }
package Thread; public class Battle implements Runnable{ //2. ๅฎž็ŽฐRunnableๆŽฅๅฃ private final Hero hero1; private final Hero hero2; public Battle(Hero h1, Hero h2) { this.hero1 = h1; this.hero2 = h2; } @Override public void run() { while (!hero2.isDead()) { hero1.attackHero(hero2); } } }
package com.itsoul.lab.generalledger.exception; /** * Business exception thrown if a monetary transaction request legs are unbalanced, * e.g. the sum of all leg amounts does not equal zero (double-entry principle). * * */ public class UnbalancedLegsException extends BusinessException { private static final long serialVersionUID = 1L; public UnbalancedLegsException(String message) { super(message); } }
/* * Copyright 1999-2017 Alibaba Group Holding Ltd. * * 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.alibaba.druid.wall.spi; import com.alibaba.druid.DbType; import com.alibaba.druid.sql.ast.SQLObject; import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr; import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr; import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr; import com.alibaba.druid.sql.ast.statement.*; import com.alibaba.druid.sql.dialect.mysql.ast.expr.MySqlOutFileExpr; import com.alibaba.druid.sql.dialect.mysql.ast.statement.*; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; import com.alibaba.druid.wall.WallProvider; import com.alibaba.druid.wall.WallVisitor; import com.alibaba.druid.wall.spi.WallVisitorUtils.WallTopStatementContext; import com.alibaba.druid.wall.violation.ErrorCode; import com.alibaba.druid.wall.violation.IllegalSQLObjectViolation; public class MySqlWallVisitor extends WallVisitorBase implements WallVisitor, MySqlASTVisitor { public MySqlWallVisitor(WallProvider provider) { super(provider); } @Override public DbType getDbType() { return DbType.mysql; } @Override public boolean visit(MySqlSelectQueryBlock x) { WallVisitorUtils.checkSelelct(this, x); return true; } @Override public boolean visit(MySqlDeleteStatement x) { WallVisitorUtils.checkReadOnly(this, x.getFrom()); return visit((SQLDeleteStatement) x); } @Override public boolean visit(MySqlUpdateStatement x) { return visit((SQLUpdateStatement) x); } @Override public boolean visit(MySqlInsertStatement x) { return visit((SQLInsertStatement) x); } public boolean visit(SQLIdentifierExpr x) { return true; } public boolean visit(SQLPropertyExpr x) { if (x.getOwner() instanceof SQLVariantRefExpr) { SQLVariantRefExpr varExpr = (SQLVariantRefExpr) x.getOwner(); SQLObject parent = x.getParent(); String varName = varExpr.getName(); if (varName.equalsIgnoreCase("@@session") || varName.equalsIgnoreCase("@@global")) { if (!(parent instanceof SQLSelectItem) && !(parent instanceof SQLAssignItem)) { violations.add(new IllegalSQLObjectViolation(ErrorCode.VARIANT_DENY, "variable in condition not allow", toSQL(x))); return false; } if (!checkVar(x.getParent(), x.getName())) { boolean isTop = WallVisitorUtils.isTopNoneFromSelect(this, x); if (!isTop) { boolean allow = true; if (isDeny(varName) && (WallVisitorUtils.isWhereOrHaving(x) || WallVisitorUtils.checkSqlExpr(varExpr))) { allow = false; } if (!allow) { violations.add(new IllegalSQLObjectViolation(ErrorCode.VARIANT_DENY, "variable not allow : " + x.getName(), toSQL(x))); } } } return false; } } WallVisitorUtils.check(this, x); return true; } public boolean checkVar(SQLObject parent, String varName) { if (varName == null) { return false; } if (varName.equals("?")) { return true; } if (!config.isVariantCheck()) { return true; } if (varName.startsWith("@@")) { if (!(parent instanceof SQLSelectItem) && !(parent instanceof SQLAssignItem)) { return false; } varName = varName.substring(2); } if (config.getPermitVariants().contains(varName)) { return true; } return false; } public boolean isDeny(String varName) { if (varName.startsWith("@@")) { varName = varName.substring(2); } varName = varName.toLowerCase(); return config.getDenyVariants().contains(varName); } public boolean visit(SQLVariantRefExpr x) { String varName = x.getName(); if (varName == null) { return false; } if (varName.startsWith("@@") && !checkVar(x.getParent(), x.getName())) { final WallTopStatementContext topStatementContext = WallVisitorUtils.getWallTopStatementContext(); if (topStatementContext != null && (topStatementContext.fromSysSchema() || topStatementContext.fromSysTable())) { return false; } boolean isTop = WallVisitorUtils.isTopNoneFromSelect(this, x); if (!isTop) { boolean allow = true; if (isDeny(varName) && (WallVisitorUtils.isWhereOrHaving(x) || WallVisitorUtils.checkSqlExpr(x))) { allow = false; } if (!allow) { violations.add(new IllegalSQLObjectViolation(ErrorCode.VARIANT_DENY, "variable not allow : " + x.getName(), toSQL(x))); } } } return false; } @Override public boolean visit(MySqlOutFileExpr x) { if (!config.isSelectIntoOutfileAllow() && !WallVisitorUtils.isTopSelectOutFile(x)) { violations.add(new IllegalSQLObjectViolation(ErrorCode.INTO_OUTFILE, "into out file not allow", toSQL(x))); } return true; } @Override public boolean isDenyTable(String name) { if (!config.isTableCheck()) { return false; } return !this.provider.checkDenyTable(name); } @Override public boolean visit(MySqlCreateTableStatement x) { WallVisitorUtils.check(this, x); return true; } }
package InformationRetrieval.Index; import java.util.Comparator; public class PostingListComparator implements Comparator<PostingList> { public int compare(PostingList listA, PostingList listB){ if (listA.size() < listB.size()){ return -1; } else { if (listA.size() > listB.size()){ return 1; } else { return 0; } } } }
package com.example.aanchal.legistify; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by aanchal on 9/10/15. */ public class LawyerDBHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 10; public static final String DATABASE_NAME = "LawyerDB.db"; public LawyerDBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL("CREATE TABLE Lawyer_DataBase (" + LawyerDBContract._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + LawyerDBContract.COLOUMN_NAME + " TEXT, " + LawyerDBContract.COLOUMN_FIELD + " TEXT, " + LawyerDBContract.COLOUMN_CONTACT_NUMBER + " TEXT, " + LawyerDBContract.COLOUMN_ADDRESS + " TEXT, " + LawyerDBContract.COLOUMN_CITY + " TEXT, " + LawyerDBContract.COLOUMN_STATE + " TEXT ); " ); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } }
/** * This class creates a B-tree that stores aBall objects * * @author tamara * */ public class bTree { //Instance variables and parameters aBall root=null; private double DeltaSize=0.1; double lastSize=0; double X; double Y; aBall ball; /** * addNode method - Wrapper method for makeNode and enter * adds aBall as a node in the tree * @param iBall */ public void addNode(aBall iBall) { //if the tree is empty create a node and set it as the root if (root == null) { root = makeNode(iBall); } else { //if the tree is not empty, add the ball created enter(iBall); } } /** * The makeNode method makes the aBall a node * @param iBall * @return the new node (tNode) */ public aBall makeNode( aBall iBall) { aBall tNode= iBall; tNode.right= null; //sets the right successor of the node to null tNode.left= null; //sets the left successor of the node to null return tNode; } /** * The method enter inserts the aBalls created to the tree * depending on their size * @param iBall */ public void enter (aBall iBall) { ball = root; while (true) { //loop to store the nodes in the tree depending on their ball sizes if (iBall.getbSize() < ball.getbSize()) { //if the data of the new node is less than the data of the root, if (ball.left==null) { //traverse to the left and store the new node ball.left=makeNode(iBall); break; } else { ball = ball.left; } } else { //if the data of the new node is greater than or equal to the data of the if(ball.right==null){ //root, then traverse to the right and store the new node ball.right= makeNode(iBall); break; } else { ball = ball.right; } } } } /** * inorder method - inorder traversal via call to recursive method */ public void inorder() { // Hides recursion from user traverse_inorder(root); } /** * traverse_inorder method - recursively traverses tree in order (LEFT-Root-RIGHT) */ private void traverse_inorder(aBall root) { if (root.left != null) traverse_inorder(root.left); if ((root.getbSize()-this.lastSize)> DeltaSize) { //condition to create a new Stack X+= lastSize +root.getbSize(); //X position for a new stack of balls lastSize=root.getbSize(); //update last size Y=root.getbSize(); //change of Y for different balls in the same stack root.moveTo(X,Y); } else { //if the stack exists already Y=Y+root.getbSize() + lastSize; //Stacking the balls lastSize= root.getbSize(); root.moveTo(X,Y); } if (root.right != null) traverse_inorder(root.right); } /** * isRunning is the Wrapper method for isRunningRec * @return isRunningRec(this.root) */ boolean isRunning() { //determines if the simulation is running (if the balls stopped or no) return isRunningRec(this.root); } public boolean isRunningRec (aBall root) { //check if the simulation is running by checking boolean right= false; //the nodes in the tree boolean left= false; if (root.left!= null) { left = isRunningRec (root.left); } if (root.SIMRunning == true) { return true; } if (root.right != null) { right=isRunningRec(root.right); } return (right||left); } //Stacking the bSim balls method public void stackBalls(bSim link) { traverse_inorder (link.myTree.root); X = 0; Y = 0; lastSize = 0; } /** * the pauseTraversal method traverses the tree and stops the balls from * moving. It changes the root(ball)'s state to false * @param root */ public void pauseTraversal(aBall root) { if (root.left != null) pauseTraversal(root.left); root.setBallState(false); if (root.right != null) pauseTraversal(root.right); } /** * stopSim() is the Wrapper method for pauseTraversal * it hides the recursion from the user */ public void stopSim() { this.pauseTraversal(this.root); } } //nested class class bNode { double Size; bNode left; bNode right; }
package com.bunq.sdk.model.generated.object; import com.bunq.sdk.model.core.BunqModel; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; /** * */ public class RegistryEntryReference extends BunqModel { /** * The object type that will be linked to the RegistryEntry. */ @Expose @SerializedName("type_field_for_request") private String typeFieldForRequest; /** * The ID of the object that will be used for the RegistryEntry. */ @Expose @SerializedName("id_field_for_request") private Integer idFieldForRequest; public RegistryEntryReference() { this(null, null); } public RegistryEntryReference(String type) { this(type, null); } public RegistryEntryReference(String type, Integer id) { this.typeFieldForRequest = type; this.idFieldForRequest = id; } /** * */ public static RegistryEntryReference fromJsonReader(JsonReader reader) { return fromJsonReader(RegistryEntryReference.class, reader); } /** * */ public boolean isAllFieldNull() { return true; } }
package com.example.mytodolistapp; import android.content.Intent; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; public class MainActivity<string> extends AppCompatActivity { ListView listView; ArrayList<string>arrayList; ArrayAdapter<string>arrayAdapter; String messageText; int position; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView=(ListView) findViewById(R.id.listview); arrayList=new ArrayList<>(); arrayAdapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arrayList); listView.setAdapter(arrayAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(); intent.setClass(MainActivity.this,EditMessageClass.class); intent.putExtra(intent_constant.INTENT_MESSAGE_DATA,arrayList.get(position).toString()); intent.putExtra(intent_constant.INTENT_ITEM_POSITION,position); startActivityForResult(intent,intent_constant.INTENT_REQUEST_CODE_TWO); } }); } public void onClick(View v){ Intent intent = new Intent(); intent.setClass(MainActivity.this,EditfieldClass.class); startActivityForResult(intent,intent_constant.INTENT_REQUEST_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if (resultCode == intent_constant.INTENT_RESULT_CODE) { messageText = data.getStringExtra(intent_constant.INTENT_MESSAGE_FIELD); arrayList.add((string) messageText); arrayAdapter.notifyDataSetChanged(); } else if(requestCode==intent_constant.INTENT_REQUEST_CODE_TWO){ messageText = data.getStringExtra(intent_constant.INTENT_CHANGED_MESSAGE); position = data.getIntExtra(intent_constant.INTENT_ITEM_POSITION,-1); arrayList.remove(position); arrayList.add(position, (string) messageText); arrayAdapter.notifyDataSetChanged(); } } }
/* Automatic generated by DeviceToClazz */ package com.example.xiaomi.upnp.apis.media.projection.source.device.source.control; import android.os.Parcel; import android.util.Log; import upnps.api.manager.ctrlpoint.device.AbstractDevice; import upnp.typedef.device.Device; import upnp.typedef.device.Service; public class SourceDevice extends AbstractDevice { private static final String TAG = SourceDevice.class.getSimpleName(); private MediaProjection _MediaProjection; private SessionManager _SessionManager; public MediaProjection getMediaProjection() { return _MediaProjection; } public SessionManager getSessionManager() { return _SessionManager; } private static final Object classLock = SourceDevice.class; private static final String DEVICE_TYPE = "SourceDevice"; private static final String ID_MediaProjection = "urn:upnp-org:serviceId:MediaProjection"; private static final String ID_SessionManager = "urn:upnp-org:serviceId:SessionManager"; public static SourceDevice create(Device device) { Log.d(TAG, "create"); synchronized (classLock) { SourceDevice thiz = new SourceDevice(device); do { if (! DEVICE_TYPE.equals(device.getDeviceType().getName())) { Log.d(TAG, "deviceType invalid: " + device.getDeviceType()); thiz = null; break; } if (! thiz.initialize()) { Log.d(TAG, "initialize failed"); thiz = null; break; } } while (false); return thiz; } } private SourceDevice(Device device) { this.device = device; } private boolean initialize() { boolean ret = false; do { Service theMediaProjection = device.getService(ID_MediaProjection); if (theMediaProjection == null) { Log.d(TAG, "service not found: " + ID_MediaProjection); break; } Service theSessionManager = device.getService(ID_SessionManager); if (theSessionManager == null) { Log.d(TAG, "service not found: " + ID_SessionManager); break; } _MediaProjection = new MediaProjection(theMediaProjection); _SessionManager = new SessionManager(theSessionManager); ret = true; } while (false); return ret; } public static final Creator<SourceDevice> CREATOR = new Creator<SourceDevice>() { @Override public SourceDevice createFromParcel(Parcel in) { return new SourceDevice(in); } @Override public SourceDevice[] newArray(int size) { return new SourceDevice[size]; } }; private SourceDevice(Parcel in) { readFromParcel(in); } public void readFromParcel(Parcel in) { device = in.readParcelable(Device.class.getClassLoader()); initialize(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel out, int flags) { out.writeParcelable(device, flags); } }
package com.hcl.neo.eloader.dao; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Query; import com.hcl.neo.eloader.dao.IGenericMongoDAO; public class GenericMongoDAO<T,I extends Serializable> implements IGenericMongoDAO<T, I> { private Class<T> type; @Autowired MongoTemplate mongoTemplate; @Override public T find(I id) { return mongoTemplate.findById(id, getType()); } @Override public List<T> findAll() { return mongoTemplate.findAll(getType()); } @Override public void delete(T obj) { mongoTemplate.remove(obj); } @Override public void save(T obj) { mongoTemplate.save(obj); } private Class<T> getType() { return type; } @SuppressWarnings("unchecked") public GenericMongoDAO() { this.type = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; } @Override public T findOne(I id) { return mongoTemplate.findById(id, getType()); } @Override public boolean exists(I id) { return (mongoTemplate.findById(id, getType())== null) ? false : true; } @Override public long count() { return mongoTemplate.count(new Query(), getType()); } @Override public void deleteAll() { mongoTemplate.remove(new Query(), getType()); } @Override public T findOne(Query query) { return mongoTemplate.findOne(query, getType()); } @Override public List<T> find(Query query) { return mongoTemplate.find(query, getType()); } }
package at.fhv.itm14.fhvgis.persistence.dao; import at.fhv.itm14.fhvgis.domain.AnalyseResults; import at.fhv.itm14.fhvgis.persistence.dao.interfaces.IAnalyseResultsDao; public class AnalyseResultsDao extends GenericDao<AnalyseResults> implements IAnalyseResultsDao{ private static AnalyseResultsDao _instance; public static AnalyseResultsDao getInstance() { if (_instance == null) { _instance = new AnalyseResultsDao(); } _instance.setClazz(AnalyseResults.class); return _instance; } }
package userInput; public class InputState { private static float mouseX; private static float mouseY; private static boolean[] keyHeld = new boolean[256*2]; private static boolean[] mouseButtonHeld = new boolean[16]; static { mouseX = 0; mouseY = 0; for (int i = 0; i < keyHeld.length; i++) { keyHeld[i] = false; } for (int i = 0; i < mouseButtonHeld.length; i++) { mouseButtonHeld[i] = false; } } public static float getMouseX() { return mouseX; } public static float getMouseY() { return mouseY; } public static boolean isMousePressed( int mouseButton ) { return mouseButtonHeld[mouseButton]; } public static boolean isKeyboardPressed( int keyCode) { return keyHeld[keyCode]; } static void setMouseX( float x ) { mouseX = x; } static void setMouseY( float y ) { mouseY = y; } static void setMousePressed( int mouseButton, boolean value ) { mouseButtonHeld[mouseButton] = value; } static void setKeyboardPressed( int keyCode, boolean value ) { keyHeld[keyCode] = value; } }
/* $Id$ */ package djudge.acmcontester.admin; import java.awt.Color; import djudge.acmcontester.structures.RemoteTableSubmissions; import djudge.gui.Formatter; public class JudgementCellRenderer extends DefaultSubmissionsModelCellRenderer { private static final long serialVersionUID = 1L; public JudgementCellRenderer(RemoteTableSubmissions sdm) { super(sdm); } public JudgementCellRenderer() { super(null); } @Override protected void setTextAndColor(Object value, int row, int column) { String data = (String) value; if ("AC".equalsIgnoreCase(data)) { setBackground(Color.GREEN); } else if ("WA".equalsIgnoreCase(data) || "TLE".equalsIgnoreCase(data) || "RE".equalsIgnoreCase(data) || "MLE".equalsIgnoreCase(data)) { setBackground(Color.RED); } else if ("N/A".equalsIgnoreCase(data)) { setBackground(Color.YELLOW); } else if ("CE".equalsIgnoreCase(data)) { setBackground(Color.LIGHT_GRAY); } else { setBackground(Color.WHITE); } setText(Formatter.formatJudgement(data)); } }
package com.fumei.bg.mapper; import com.fumei.bg.domain.web.GroupInfo; import java.util.List; /** * @author zkh */ public interface GroupInfoMapper { /** * ๆŸฅ่ฏข้›†ๅ›ข็ฎ€ไป‹ไฟกๆฏๅˆ—่กจ * @param info ๆกไปถ * @return ้›†ๅ›ข็ฎ€ไป‹ไฟกๆฏๅˆ—่กจ */ List<GroupInfo> selectGroupInfoList(GroupInfo info); /** * ไฟๅญ˜้›†ๅ›ข่ฏฆๆƒ…ไฟกๆฏ * @param info ้›†ๅ›ข็ฎ€ไป‹ไฟกๆฏ * @return ๆ‰ง่กŒ็ป“ๆžœ 1ๆˆๅŠŸ 0ๅคฑ่ดฅ */ int insert(GroupInfo info); /** * ไฟฎๆ”น้›†ๅ›ข่ฏฆๆƒ…ไฟกๆฏ * @param info ้›†ๅ›ข็ฎ€ไป‹ไฟกๆฏ * @return ๆ‰ง่กŒ็ป“ๆžœ 1ๆˆๅŠŸ 0ๅคฑ่ดฅ */ int updateByPrimaryKey(GroupInfo info); /** * ๅˆ ้™ค้›†ๅ›ข่ฏฆๆƒ…ไฟกๆฏ * @param infoId ้›†ๅ›ข็ฎ€ไป‹id * @return ๆ‰ง่กŒ็ป“ๆžœ 1ๆˆๅŠŸ 0ๅคฑ่ดฅ */ int deleteByPrimaryKey(Long infoId); /** * ่Žทๅ–้ฆ–้กต้›†ๅ›ข็ฎ€ไป‹ * * @return ้›†ๅ›ข็ฎ€ไป‹ */ GroupInfo selectIndexGroupInfo(); }
public class LinkParser { String unparsed = ""; String parsed = ""; private char separator = '/'; public LinkParser(String URL) { unparsed = URL; } public String parse() { int sep = unparsed.lastIndexOf(separator); parsed = unparsed.substring(sep + 1); parsed = parsed.replace("-", " "); return parsed.toUpperCase(); } }
package commands; import model.ListingContext; public class ChangeDirectory implements Command { private ListingContext listingContext; private String path; public ChangeDirectory(ListingContext listingContext, String path) { this.listingContext = listingContext; this.path = path; } @Override public void execute() { listingContext.setCurrentPath(path); } }
package com.edu.realestate.model; import java.util.Arrays; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import org.bson.internal.Base64; @Entity public class Picture { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; private int codage; @Column(name="content") private byte[] data; public Picture() { } public Picture(int id, int codage, byte[] data) { this.id = id; this.codage = codage; this.data = data; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getCodage() { return codage; } public void setCodage(int codage) { this.codage = codage; } public String getData() { return "data:image/jpeg;base64," + Base64.encode(data); } public byte[] getDataBytes() { return data; } public void setData(byte[] data) { this.data = data; } @Override public String toString() { return "Picture [id=" + id + ", codage=" + codage + ", data=" + Arrays.toString(data) + "]"; } }
package com.Flyweight; /** * Created by Valentine on 2018/5/12. */ public abstract class Shape { public abstract void draw(); }
package ua.dao; import org.springframework.stereotype.Repository; import ua.domain.Category; import ua.domain.Product; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import java.util.List; @Repository public class ProductDAOImpl implements ProductDAO{ @PersistenceContext private EntityManager entityManager; @Override public void add(Product product) { entityManager.merge(product); } @Override public void delete(long id) { Query query; query = entityManager.createQuery("SELECT c FROM Product c WHERE c.id = :id", Product.class); query.setParameter("id", id); Product p = (Product) query.getSingleResult(); entityManager.remove(p); } @Override public Product findOne(long id) { Query query; query = entityManager.createQuery("SELECT c FROM Product c WHERE c.id = :id", Product.class); query.setParameter("id", id); return (Product) query.getSingleResult(); } @Override public List<Product> list(Category category) { Query query; query = entityManager.createQuery("SELECT c FROM Product c WHERE c.category = :category", Product.class); query.setParameter("category", category); return (List<Product>) query.getResultList(); } @Override public List<Product> list() { Query query = entityManager.createQuery("SELECT g FROM Product g", Product.class); return (List<Product>) query.getResultList(); } @Override public List<Product> list(String pattern) { Query query = entityManager.createQuery("SELECT c FROM Product c WHERE c.name LIKE :pattern", Product.class); query.setParameter("pattern", "%" + pattern + "%"); return (List<Product>) query.getResultList(); } }
package com.ccnx_sb15gr3_Courier.model; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import org.ccnx.android.ccnlib.JsonMessage; public class User extends JsonMessage implements Serializable{ /** * */ private static final long serialVersionUID = -373945999108016882L; private String login; private String password; private Integer userId; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Set<RouteInformation> getRouteInformations() { return routeInformations; } public void setRouteInformations(Set<RouteInformation> routeInformations) { this.routeInformations = routeInformations; } public Set<Car> getCars() { return cars; } public void setCars(Set<Car> cars) { this.cars = cars; } private String email; private String type; private Set<RouteInformation> routeInformations = new HashSet<RouteInformation>( 0); private Set<Car> cars = new HashSet<Car>(0); public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
package com.example.login.controller; import com.example.login.model.LoginRequest; import com.example.login.model.LoginResponse; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class LoginController { @PostMapping(path = "/login", consumes = MediaType.APPLICATION_JSON_VALUE) public LoginResponse login(@RequestBody LoginRequest req) { if ("phu".equals(req.getUsername()) && "123".equals(req.getPassword())) { LoginResponse resp = new LoginResponse(); resp.setToken("some_token"); return resp; } throw new RuntimeException("Login Failed!"); } }
package com.zantong.mobilecttx.weizhang.activity; import android.content.Context; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.view.Window; import android.view.inputmethod.InputMethodManager; import android.widget.TextView; import com.zantong.mobilecttx.common.PublicData; import com.zantong.mobilecttx.R; import com.zantong.mobilecttx.weizhang.bean.QueryHistoryBean; import com.zantong.mobilecttx.utils.RefreshNewTools.UserInfoRememberCtrl; import com.zantong.mobilecttx.utils.StateBarSetting; import com.zantong.mobilecttx.weizhang.fragment.QueryFragment; import com.zantong.mobilecttx.weizhang.fragment.QueryHistory; import java.util.LinkedList; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; public class QueryActivity extends FragmentActivity { @Bind(R.id.illegal_query_title) TextView illegalQueryTitle; @Bind(R.id.query_history_title) TextView queryHistoryTitle; private QueryFragment mQueryFragment; private QueryHistory mQueryHistory; private FragmentManager mFragmentManager; private FragmentTransaction mFragmentTransaction; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.query_activity); ButterKnife.bind(this); StateBarSetting.settingBar(this); PublicData.getInstance().mQueryHistoryBean = (QueryHistoryBean) UserInfoRememberCtrl.readObject("QueryHistory"); if(null == PublicData.getInstance().mQueryHistoryBean){ PublicData.getInstance().mQueryHistoryBean = new QueryHistoryBean(); PublicData.getInstance().mQueryHistoryBean.setQueryCar(new LinkedList<QueryHistoryBean.QueryCarBean>()); } illegalQueryTitle.setSelected(true); queryHistoryTitle.setSelected(false); mQueryFragment = new QueryFragment(); mFragmentManager = getSupportFragmentManager(); mFragmentManager.beginTransaction().replace(R.id.fragment_content, mQueryFragment).commit(); } @OnClick({R.id.illegal_query_title, R.id.query_history_title, R.id.tv_back}) public void onClick(View view) { switch (view.getId()) { case R.id.illegal_query_title: illegalQueryTitle.setSelected(true); queryHistoryTitle.setSelected(false); choseCurrentItem(0); break; case R.id.query_history_title: illegalQueryTitle.setSelected(false); queryHistoryTitle.setSelected(true); choseCurrentItem(1); break; case R.id.tv_back: InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE); if (imm.isActive() && this.getCurrentFocus() != null) { if (this.getCurrentFocus().getWindowToken() != null) { imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } finish(); break; } } private void choseCurrentItem(int item){ mFragmentTransaction = mFragmentManager.beginTransaction(); hideFragments(mFragmentTransaction); if(item == 0){ if(mQueryFragment == null){ mQueryFragment = new QueryFragment(); mFragmentTransaction.add(R.id.fragment_content, mQueryFragment); }else{ mFragmentTransaction.show(mQueryFragment); } }else if(item == 1){ if(mQueryHistory == null){ mQueryHistory = new QueryHistory(); mFragmentTransaction.add(R.id.fragment_content, mQueryHistory); }else{ mFragmentTransaction.show(mQueryHistory); } } mFragmentTransaction.commit(); } private void hideFragments(FragmentTransaction transaction){ if(mQueryFragment != null){ transaction.hide(mQueryFragment); } if(mQueryHistory != null){ transaction.hide(mQueryHistory); } } }
package cyfixusBot.game.players; import java.awt.Graphics; import java.awt.Rectangle; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Random; import java.util.Scanner; import cyfixusBot.game.entities.Avatar; import cyfixusBot.game.entities.ObjectID; public class Player extends Avatar{ // private StatGenerator statGen; private int index; private int tickets = 0; private int playerClass; private Random random = new Random(); public Player(float x, float y, ObjectID id, String name) { super(x, y, id); this.setName(name); this.setTitle(""); } public Player(ObjectID id, String playerString, String delimiter){ super(0, 0, id); Scanner sc = new Scanner(playerString).useDelimiter(delimiter); setName(sc.next()); setTitle(sc.next()); setCurrency(Double.parseDouble(sc.next())); setLevel(Byte.parseByte(sc.next())); setExp(Integer.parseInt(sc.next())); setHealth(Byte.parseByte(sc.next())); setMana(Byte.parseByte(sc.next())); setStrength(Byte.parseByte(sc.next())); setStamina(Byte.parseByte(sc.next())); setIntelligence(Byte.parseByte(sc.next())); setWill(Byte.parseByte(sc.next())); setPlayerClass(Integer.parseInt(sc.next())); } public void setPlayerClass(int playerClass){ this.playerClass = playerClass; } public int getPlayerClass(){ return playerClass; } @Override public String toString(){ StringBuilder playerData = new StringBuilder(); playerData.append(name + "\t" + title + "\t" + currency + "\t" + level + "\t" + exp + "\t" + health + "\t" + mana + "\t" + strength + "\t" + stamina + "\t" + intelligence + "\t" + will + "\t" + playerClass); return playerData.toString(); } private void writeObject(ObjectOutputStream o) throws IOException { o.defaultWriteObject(); o.writeObject(getName()); } private void readObject(ObjectInputStream o) throws IOException, ClassNotFoundException { o.defaultReadObject(); name = (String) o.readObject(); } public void printAttributes() { System.out.println("Name: " + name); System.out.println("Health: " + health); System.out.println("Mana: " + mana); System.out.println("Level: " + level); System.out.println("exp: " + exp); System.out.println("strength: " + strength); System.out.println("stamina: " + stamina); System.out.println("intelligence: " + intelligence); System.out.println("will: " + will); System.out.println("class: " + playerClass); } public boolean equals(Object o){ if(o == this){ return true; } if((o instanceof Player)){ Player player = (Player)o; return this.name == player.getName(); } return false; } public void setIndex(int index){ this.index = index; } public int getIndex(){ return index; } public int getTickets(){ return tickets; } public int setTickets(){ return ++tickets; } public void resetTickets(){ tickets = 0; } @Override public void move() { // TODO Auto-generated method stub } @Override public void render(Graphics g) { // TODO Auto-generated method stub } @Override public Rectangle getBounds() { // TODO Auto-generated method stub return null; } @Override public Rectangle getBoundsTop() { // TODO Auto-generated method stub return null; } @Override public Rectangle getBoundsBottom() { // TODO Auto-generated method stub return null; } @Override public Rectangle getBoundsLeft() { // TODO Auto-generated method stub return null; } @Override public Rectangle getBoundsRight() { // TODO Auto-generated method stub return null; } }
package compiler; import compiler.compileLists.CompileListFactory; import compiler.tokenizer.Node; import compiler.tokenizer.NodeType; import compiler.tokenizer.linked_list; public class Compiler { private CompileList list; private CompileList sublist; private Node node; private int lastAssignedVariableName = 0; public Compiler() { list = new CompileList(); } public String getNextVariableName(){ return "$" + lastAssignedVariableName++; } public CompileList getCompiledListFromTokenList(linked_list tokenList){ node = tokenList.getFirst(); CompileListFactory factory = new CompileListFactory(); boolean endText = false; do{ sublist = factory.getCompileList(node, this); list.add(sublist); endText = skipToNextItem(); } while(!endText); return list; } private boolean skipToNextItem(){ //skip to next item if(node.getToken() == NodeType.VARIABELE || node.getToken() == NodeType.FUNCTION){ //Go until ; boolean found = false; while(!found){ if(node.getToken() == NodeType.SEMICOLON) found = true; else node = node.getNext(); } } else if(node.getToken() == NodeType.IF || node.getToken() == NodeType.ELSE || node.getToken() == NodeType.WHILE){ //Go until } boolean found = false; while(!found){ if(node.getToken() == NodeType.BRACKETSCLOSE) found = true; else node = node.getNext(); } } node = node.getNext(); if(node == null) return true; if(node.getToken() == NodeType.ELSE){ return skipToNextItem(); } return false; } }
package cr.ac.tec.ce1103.structures.simple; /** * * Clase listas enlazadas * */ class Nodo{ Object dato; Nodo siguiente; public Nodo(Object elem){ dato=elem; siguiente=null; } } public class ListaEnlazada { private Nodo cabeza; private int numElementos; public ListaEnlazada(){ cabeza=null; numElementos=0; } public void add(Object elem){ if (numElementos==0){ cabeza = new Nodo(elem); } else{ obtenerNodo(numElementos-1).siguiente = new Nodo(elem); } numElementos++; } private Nodo obtenerNodo(int indice){ if(indice>= numElementos || indice <0){ throw new IndexOutOfBoundsException("Indice incorrecto:"+indice); } Nodo actual=cabeza; for (int i=0; i<indice; i++) actual=actual.siguiente; return actual; } public int indexOf(Object elem){ int indice; boolean encuentra=false; Nodo actual=cabeza; for(indice=0; actual!=null; indice++, actual=actual.siguiente){ if((actual.dato!=null && actual.dato.equals(elem))||((actual.dato==null)&&(elem==null))){ encuentra=true; break; } } if(encuentra==false) indice=-1; return indice; } public Object remove(int indice){ Nodo actual=null; Nodo anterior=null; if(indice>0){ anterior =obtenerNodo(indice-1); actual=anterior.siguiente; anterior.siguiente=actual.siguiente; numElementos--; } if(indice==0){ actual=cabeza; cabeza=cabeza.siguiente; numElementos--; } if(actual!=null) return actual.dato; else return null; } public int remove(Object elem){ int actual=indexOf(elem); if(actual!=-1) remove(actual); return actual; } public Object get(int indice){ return obtenerNodo(indice).dato; } public int size(){ return numElementos; } public void removeAll(){ for(int i=0;i<numElementos;i++){ remove(i); } } }
package uquest.com.bo.models.services.listeners; import org.springframework.context.ApplicationEvent; import uquest.com.bo.models.entity.Usuario; public class OnRegistrationCompleteEvent extends ApplicationEvent { private String appUrl; private Usuario user; public OnRegistrationCompleteEvent( Usuario user, String appUrl) { super(user); this.user = user; this.appUrl = appUrl; } public String getAppUrl() { return appUrl; } public void setAppUrl(String appUrl) { this.appUrl = appUrl; } public Usuario getUser() { return user; } public void setUser(Usuario user) { this.user = user; } }
package com.openfarmanager.android.di; import android.os.Handler; import com.openfarmanager.android.controllers.FileSystemController; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; /** * @author Vlad Namashko */ @Module @Singleton public class FileSystemControllerModule { private FileSystemController mFileSystemController; public FileSystemControllerModule(FileSystemController controller) { mFileSystemController = controller; } @Provides Handler providePanelHandler() { return mFileSystemController.getPanelHandler(); } }
package com.nisira.core.entity; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.Date; /** * Created by aabad on 10/08/2017. */ public class Dato { @SerializedName("idempresa") @Expose private String idempresa; @SerializedName("idordenservicio") @Expose private String idordenservicio; @SerializedName("iddocumento") @Expose private String iddocumento; @SerializedName("serie") @Expose private String serie; @SerializedName("numero") @Expose private String numero; @SerializedName("nromanual") @Expose private String nromanual; @SerializedName("idclieprov") @Expose private String idclieprov; @SerializedName("fecha") @Expose private String fecha; @SerializedName("tipo_servicio") @Expose private String tipoServicio; @SerializedName("ambito_servicio") @Expose private String ambitoServicio; @SerializedName("idestado") @Expose private String idestado; @SerializedName("sincroniza") @Expose private String sincroniza; @SerializedName("fechacreacion") @Expose private String fechacreacion; @SerializedName("nrocontenedor") @Expose private String nrocontenedor; @SerializedName("nroprecinto") @Expose private String nroprecinto; @SerializedName("nro_oservicio") @Expose private String nroOservicio; @SerializedName("idmotivo") @Expose private String idmotivo; @SerializedName("glosa") @Expose private String glosa; @SerializedName("idoperario") @Expose private String idoperario; @SerializedName("idoperario2") @Expose private String idoperario2; @SerializedName("razonsocial") @Expose private String razonsocial; @SerializedName("estado") @Expose private String estado; @SerializedName("operario") @Expose private String operario; @SerializedName("operario2") @Expose private String operario2; /*** THIS DATA IS FOR DORDENSERVICIOCLIENTE ****/ @SerializedName("item") @Expose private String item; @SerializedName("idvehiculo") @Expose private String idvehiculo; @SerializedName("placa_cliente") @Expose private String placa_cliente; @SerializedName("hora_req") @Expose private Double hora_req; @SerializedName("fecha_fin_servicio") @Expose private String fecha_fin_servicio; @SerializedName("idreferencia") @Expose private String idreferencia; @SerializedName("itemreferencia") @Expose private String itemreferencia; @SerializedName("idservicio") @Expose private String idservicio; @SerializedName("conductor_cliente") @Expose private String conductor_cliente; @SerializedName("hora_rc") @Expose private Double hora_rc; @SerializedName("codoperaciones") @Expose private String codoperaciones; @SerializedName("idruta_ec") @Expose private String idruta_ec; @SerializedName("idconsumidor") @Expose private String idconsumidor; @SerializedName("descripcion_vehiculo") @Expose private String descripcion_vehiculo; @SerializedName("descripcion_servicio") @Expose private String descripcion_servicio; /**** THIS DATA FOR PERSONAL_CLIENTE ****/ @SerializedName("item2") @Expose private String item2; @SerializedName("idpersonal") @Expose private String idpersonal; @SerializedName("dni") @Expose private String dni; @SerializedName("nombres") @Expose private String nombres; @SerializedName("fechaoperacion") @Expose private String fechaoperacion; @SerializedName("idcargo") @Expose private String idcargo; @SerializedName("fechafin") @Expose private String fechafin; @SerializedName("checklist") @Expose private String checklist; @SerializedName("brevete_cliente") @Expose private String brevete_cliente; @SerializedName("descripcion_cargo") @Expose private String descripcion_cargo; /*** THIS DATA FOR DPERSONAL_CLIENTE ***/ @SerializedName("item_dordenservicio") @Expose private String item_dordenservicio; @SerializedName("hora_llegada") @Expose private Double hora_llegada; @SerializedName("hora_inicio_serv") @Expose private Double hora_inicio_serv; @SerializedName("hora_fin_serv") @Expose private Double hora_fin_serv; @SerializedName("hora_liberacion") @Expose private Double hora_liberacion; @SerializedName("fecharegistro") @Expose private String fecharegistro; @SerializedName("fechafinregistro") @Expose private String fechafinregistro; /*************************** SETTERS AND GETTERS ********************************************/ public String getIdempresa() { return idempresa; } public void setIdempresa(String idempresa) { this.idempresa = idempresa; } public String getIdordenservicio() { return idordenservicio; } public void setIdordenservicio(String idordenservicio) { this.idordenservicio = idordenservicio; } public String getIddocumento() { return iddocumento; } public void setIddocumento(String iddocumento) { this.iddocumento = iddocumento; } public String getSerie() { return serie; } public void setSerie(String serie) { this.serie = serie; } public String getNumero() { return numero; } public void setNumero(String numero) { this.numero = numero; } public String getNromanual() { return nromanual; } public void setNromanual(String nromanual) { this.nromanual = nromanual; } public String getIdclieprov() { return idclieprov; } public void setIdclieprov(String idclieprov) { this.idclieprov = idclieprov; } public String getFecha() { return fecha; } public void setFecha(String fecha) { this.fecha = fecha; } public String getTipoServicio() { return tipoServicio; } public void setTipoServicio(String tipoServicio) { this.tipoServicio = tipoServicio; } public String getAmbitoServicio() { return ambitoServicio; } public void setAmbitoServicio(String ambitoServicio) { this.ambitoServicio = ambitoServicio; } public String getIdestado() { return idestado; } public void setIdestado(String idestado) { this.idestado = idestado; } public String getSincroniza() { return sincroniza; } public void setSincroniza(String sincroniza) { this.sincroniza = sincroniza; } public String getFechacreacion() { return fechacreacion; } public void setFechacreacion(String fechacreacion) { this.fechacreacion = fechacreacion; } public String getNrocontenedor() { return nrocontenedor; } public void setNrocontenedor(String nrocontenedor) { this.nrocontenedor = nrocontenedor; } public String getNroprecinto() { return nroprecinto; } public void setNroprecinto(String nroprecinto) { this.nroprecinto = nroprecinto; } public String getNroOservicio() { return nroOservicio; } public void setNroOservicio(String nroOservicio) { this.nroOservicio = nroOservicio; } public String getIdmotivo() { return idmotivo; } public void setIdmotivo(String idmotivo) { this.idmotivo = idmotivo; } public String getGlosa() { return glosa; } public void setGlosa(String glosa) { this.glosa = glosa; } public String getIdoperario() { return idoperario; } public void setIdoperario(String idoperario) { this.idoperario = idoperario; } public String getIdoperario2() { return idoperario2; } public void setIdoperario2(String idoperario2) { this.idoperario2 = idoperario2; } public String getRazonsocial() { return razonsocial; } public void setRazonsocial(String razonsocial) { this.razonsocial = razonsocial; } public String getEstado() { return estado; } public void setEstado(String estado) { this.estado = estado; } public String getOperario() { return operario; } public void setOperario(String operario) { this.operario = operario; } public String getOperario2() { return operario2; } public void setOperario2(String operario2) { this.operario2 = operario2; } /*** ADD SETTER AND GETTER FOR DORDENSERVICIOCLIENTE ***/ public String getItem() { return item; } public void setItem(String item) { this.item = item; } public String getIdvehiculo() { return idvehiculo; } public void setIdvehiculo(String idvehiculo) { this.idvehiculo = idvehiculo; } public String getPlaca_cliente() { return placa_cliente; } public void setPlaca_cliente(String placa_cliente) { this.placa_cliente = placa_cliente; } public Double getHora_req() { return hora_req; } public void setHora_req(Double hora_req) { this.hora_req = hora_req; } public String getFecha_fin_servicio() { return fecha_fin_servicio; } public void setFecha_fin_servicio(String fecha_fin_servicio) { this.fecha_fin_servicio = fecha_fin_servicio; } public String getIdreferencia() { return idreferencia; } public void setIdreferencia(String idreferencia) { this.idreferencia = idreferencia; } public String getItemreferencia() { return itemreferencia; } public void setItemreferencia(String itemreferencia) { this.itemreferencia = itemreferencia; } public String getIdservicio() { return idservicio; } public void setIdservicio(String idservicio) { this.idservicio = idservicio; } public String getConductor_cliente() { return conductor_cliente; } public void setConductor_cliente(String conductor_cliente) { this.conductor_cliente = conductor_cliente; } public Double getHora_rc() { return hora_rc; } public void setHora_rc(Double hora_rc) { this.hora_rc = hora_rc; } public String getCodoperaciones() { return codoperaciones; } public void setCodoperaciones(String codoperaciones) { this.codoperaciones = codoperaciones; } public String getIdruta_ec() { return idruta_ec; } public void setIdruta_ec(String idruta_ec) { this.idruta_ec = idruta_ec; } public String getIdconsumidor() { return idconsumidor; } public void setIdconsumidor(String idconsumidor) { this.idconsumidor = idconsumidor; } public String getDescripcion_vehiculo() { return descripcion_vehiculo; } public void setDescripcion_vehiculo(String descripcion_vehiculo) { this.descripcion_vehiculo = descripcion_vehiculo; } public String getDescripcion_servicio() { return descripcion_servicio; } public void setDescripcion_servicio(String descripcion_servicio) { this.descripcion_servicio = descripcion_servicio; } /***************** ADD SETTER AND GETTER FOR PERSONAL_SERVICIO ******************/ public String getItem2() { return item2; } public void setItem2(String item2) { this.item2 = item2; } public String getIdpersonal() { return idpersonal; } public void setIdpersonal(String idpersonal) { this.idpersonal = idpersonal; } public String getDni() { return dni; } public void setDni(String dni) { this.dni = dni; } public String getNombres() { return nombres; } public void setNombres(String nombres) { this.nombres = nombres; } public String getFechaoperacion() { return fechaoperacion; } public void setFechaoperacion(String fechaoperacion) { this.fechaoperacion = fechaoperacion; } public String getIdcargo() { return idcargo; } public void setIdcargo(String idcargo) { this.idcargo = idcargo; } public String getFechafin() { return fechafin; } public void setFechafin(String fechafin) { this.fechafin = fechafin; } public String getChecklist() { return checklist; } public void setChecklist(String checklist) { this.checklist = checklist; } public String getBrevete_cliente() { return brevete_cliente; } public void setBrevete_cliente(String brevete_cliente) { this.brevete_cliente = brevete_cliente; } public String getDescripcion_cargo() { return descripcion_cargo; } public void setDescripcion_cargo(String descripcion_cargo) { this.descripcion_cargo = descripcion_cargo; } /*************** ADD SETTER AND GETTER FOR DPERSONAL_SERVICIO *********************/ public String getItem_dordenservicio() { return item_dordenservicio; } public void setItem_dordenservicio(String item_dordenservicio) { this.item_dordenservicio = item_dordenservicio; } public Double getHora_llegada() { return hora_llegada; } public void setHora_llegada(Double hora_llegada) { this.hora_llegada = hora_llegada; } public Double getHora_inicio_serv() { return hora_inicio_serv; } public void setHora_inicio_serv(Double hora_inicio_serv) { this.hora_inicio_serv = hora_inicio_serv; } public Double getHora_fin_serv() { return hora_fin_serv; } public void setHora_fin_serv(Double hora_fin_serv) { this.hora_fin_serv = hora_fin_serv; } public Double getHora_liberacion() { return hora_liberacion; } public void setHora_liberacion(Double hora_liberacion) { this.hora_liberacion = hora_liberacion; } public String getFecharegistro() { return fecharegistro; } public void setFecharegistro(String fecharegistro) { this.fecharegistro = fecharegistro; } public String getFechafinregistro() { return fechafinregistro; } public void setFechafinregistro(String fechafinregistro) { this.fechafinregistro = fechafinregistro; } }