text
stringlengths
10
2.72M
package com.stackroute.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class UserController { @RequestMapping(value = "/", method = RequestMethod.GET) public ModelAndView welcomeUser() { User user = new User(); user.setUname("Saurabh"); ModelAndView modelAndView = new ModelAndView("index"); modelAndView.addObject("uname", user); return modelAndView; } }
package men.brakh.kasiski; import java.util.*; public class GcdsTable { // Таблица Наибольший общий делитель --- Число его повторений private Map<Integer, Integer> gcds = new HashMap<>(); /** * Добавление наибольшего общего делителя вв хеш-таблицу * @param gcd НОД */ public void addGcd(int gcd) { if(gcds.containsKey(gcd)) { gcds.put(gcd, gcds.get(gcd)+1); } else { gcds.put(gcd, 1); } } /** * Презобразование hash-map в отсортированный список * @return отспортированный список */ private ArrayList<Map.Entry<Integer, Integer>> getSortedGCDs() { ArrayList<Map.Entry<Integer, Integer> > list = new ArrayList(gcds.entrySet()); Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() { @Override public int compare(Map.Entry<Integer, Integer> a, Map.Entry<Integer, Integer> b) { return b.getValue() - a.getValue(); } }); return list; } /** * Получение первых N по повторениям НОДов * @param n число N * @return первые N по повторениям НОДов (первых по вероятностей ключей) */ public int[] getFirstNKeys(int n) { ArrayList<Map.Entry<Integer, Integer> > sortedGcd = getSortedGCDs(); int[] firstNKeys = new int[n]; for(int i = 0; i < n; i++) { firstNKeys[i] = sortedGcd.get(i).getKey(); } return firstNKeys; } /** * Получение наиболее вероятного ключ * @return наиболее вероятный ключ */ public int getFirstKey(){ return getFirstNKeys(1)[0]; } public int size() { return gcds.size(); } }
package fj.swsk.cn.eqapp.subs.more.C; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import java.util.ArrayList; import java.util.List; import fj.swsk.cn.eqapp.R; import fj.swsk.cn.eqapp.main.C.BaseTopbarActivity; import fj.swsk.cn.eqapp.subs.more.M.DocFile; import fj.swsk.cn.eqapp.subs.more.V.EmergencyAdapter; import fj.swsk.cn.eqapp.util.AppUtil; import fj.swsk.cn.eqapp.util.CommonUtils; /** * Created by apple on 16/7/20. */ public class EmergencyPrescript extends BaseTopbarActivity implements AdapterView.OnItemClickListener, View.OnClickListener { private ListView lv; private EmergencyAdapter adapt; @Override protected void onCreate(Bundle savedInstanceState) { layoutRes = R.layout.emergencypres_activity; super.onCreate(savedInstanceState); mTopbar.setRightButtonIsvisable(false); lv = (ListView) findViewById(R.id.pinnedlv); lv.setBackgroundResource(R.color.listviewbg); List<DocFile> list = new ArrayList<>(); list.add(DocFile.getDefault()); list.add(DocFile.getDefault()); list.add(DocFile.getDefault()); list.add(DocFile.getDefault()); list.add(DocFile.getDefault()); list.add(DocFile.getDefault()); list.add(DocFile.getDefault()); lv.setAdapter(adapt = new EmergencyAdapter(this, list)); adapt.mListener = this; lv.setOnItemClickListener(this); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { } @Override public void onClick(View v) { if (v.getId() == R.id.btn) { int pos = (int) v.getTag(); DocFile df = adapt.getItem(pos); if (df.path == null) return; Intent intent = AppUtil.openFile(df.path); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } else { CommonUtils.toast("无可打开此种类型文件的应用"); } } } }
package com.bazmehdi.pjb.view; import android.os.Bundle; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.bazmehdi.pjb.R; import org.json.JSONException; import org.json.JSONObject; public class PaymentDetails extends AppCompatActivity { TextView paymentId, paymentAmount, paymentStatus; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.payment_details); paymentId = findViewById(R.id.paymentId); paymentAmount = findViewById(R.id.paymentAmount); paymentStatus = findViewById(R.id.paymentStatus); //Get Intent Intent intent = getIntent(); try { JSONObject jsonObject = new JSONObject(intent.getStringExtra("PaymentDetails")); showDetails(jsonObject.getJSONObject("response"),intent.getStringExtra("PaymentAmount")); } catch (JSONException e) { e.printStackTrace(); } } private void showDetails(JSONObject response, String pAmount) { try { paymentId.setText(response.getString("id")); paymentAmount.setText("£" + pAmount); paymentStatus.setText(response.getString("state")); } catch (JSONException e) { e.printStackTrace(); } } }
package com.designpattern.dp8strategypattern.v1; public class GroupbuyStrategy implements SaleStrategy { @Override public void doSale() { System.out.println("团购策略"); } }
package com.cloudaping.cloudaping.entity.productType; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Computer extends ProductType{ @Id private Integer computerId; private String computerBrand; private String computerCase; private String computerScreen; private String computerCpu; private String computerGraphicsCard; private Integer productId; public Computer() { } public Integer getComputerId() { return computerId; } public void setComputerId(Integer computerId) { this.computerId = computerId; } public String getComputerBrand() { return computerBrand; } public void setComputerBrand(String computerBrand) { this.computerBrand = computerBrand; } public String getComputerCase() { return computerCase; } public void setComputerCase(String computerCase) { this.computerCase = computerCase; } public String getComputerScreen() { return computerScreen; } public void setComputerScreen(String computerScreen) { this.computerScreen = computerScreen; } public String getComputerCpu() { return computerCpu; } public void setComputerCpu(String computerCpu) { this.computerCpu = computerCpu; } public String getComputerGraphicsCard() { return computerGraphicsCard; } public void setComputerGraphicsCard(String computerGraphicsCard) { this.computerGraphicsCard = computerGraphicsCard; } public Integer getProductId() { return productId; } public void setProductId(Integer productId) { this.productId = productId; } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * */ /** * @author Aloy Aditya Sen * */class b{ static int maze[][];public b() { // TODO Auto-generated constructor stub }static int r;static int c; public static void main (String ... orange) throws NumberFormatException, IOException{ //create the closed maze BufferedReader br =new BufferedReader (new InputStreamReader(System.in)); System.out.println("input the dimensions of the maze"); System.out.println("no of rows"); r= Integer.parseInt( br.readLine()); System.out.println("no of columns"); c= Integer.parseInt( br.readLine()); maze=new int[r][c]; //make the maze with walls //input '0'no blck --'1'block System.out.println("input the maze"); for(int i=0;i<r;i++){ System.out.println("input data for row"); for(int j=0;j<c;j++){ maze[i][j]=Integer.parseInt( br.readLine()); } } //let the maze runner start from the top left corner //that is maze[0][0]to right bottom corner ie maze[r-1][c-1] int did=forward(0,0); if (did==1){ System.out.println("the maze is run sucessfully"); } } private static int forward(int a ,int b){ int move =0; if (a==r-1&&b==c-1) { return 1; } else { if (a==0 || b==c-1) { if (a==0) { if (maze[a][b-1]==0)//left { move=4; } if (maze[a][b+1]==0)//right { move=2; } if (maze[a+1][b]==0)//bottom { move=3; } } else if (b==c-1) { if (maze[a-1][b]==0)//top { move=1; } if (maze[a][b-1]==0)//left { move=4; } if (maze[a+1][b]==0)//bottom { move=3; } } } else if (a==r-1 || b==0) { if (b==0) { if (maze[a-1][b]==0)//top { move=1; } if (maze[a][b+1]==0)//right { move=2; } if (maze[a+1][b]==0)//bottom { move=3; } } else if (a==r-1){ if (maze[a-1][b]==0)//top { move=1; } if (maze[a][b-1]==0)//left { move=4; } if (maze[a][b+1]==0)//right { move=2; } } } else if (a>0 && a<r-1 && b>0 && b<c-1){ if (maze[a-1][b]==0)//top { move=1; } if (maze[a][b-1]==0)//left { move=4; } if (maze[a][b+1]==0)//right { move=2; } if (maze[a+1][b]==0)//bottom { move=3; } } } switch (move) { case 1: forward(a-1, b); break; case 2: forward(a, b+1); break; case 3: forward(a+1, b); break; case 4: forward(a, b-1); break; case 0: break; } return move; } }
package com.twitter.component_test.rest; import static com.jayway.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import java.util.Optional; import javax.annotation.Resource; import javax.inject.Inject; import javax.ws.rs.core.MediaType; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.junit4.SpringRunner; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; import com.twitter.TwitterApplication; import com.twitter.controller.rest.UserRESTServiceImpl; import com.twitter.dto.UserDTO; import com.twitter.model.User; import com.twitter.persistence.UserRepository; /** * @author gauri sawant * */ @RunWith(SpringRunner.class) @SpringBootTest(classes = TwitterApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class UserRestServiceTest { private static final String HEADER_KEY = "x-jwt-assertion"; private static final String HEADER_VALUE = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1HWmlObUU1WVdaaE5qVmpOekUxTVdJMllqUmtPVGczWkRaaE1URmpPR05oT1Roa05tRTRZUSJ9.eyJzdWIiOiJwZ2Fpa0BuZXRzLmV1IiwiaHR0cDpcL1wvd3NvMi5vcmdcL2NsYWltc1wvYXBwbGljYXRpb250aWVyIjoiVW5saW1pdGVkIiwiaHR0cDpcL1wvd3NvMi5vcmdcL2NsYWltc1wva2V5dHlwZSI6IlBST0RVQ1RJT04iLCJodHRwOlwvXC93c28yLm9yZ1wvY2xhaW1zXC92ZXJzaW9uIjoiMS4yIiwiaXNzIjoid3NvMi5vcmdcL3Byb2R1Y3RzXC9hbSIsImh0dHA6XC9cL3dzbzIub3JnXC9jbGFpbXNcL2FwcGxpY2F0aW9ubmFtZSI6Ik5BQS1BZG1pbi1VSSIsImh0dHA6XC9cL3dzbzIub3JnXC9jbGFpbXNcL2VuZHVzZXIiOiJwZ2Fpa0BuZXRzLmV1QGNhcmJvbi5zdXBlciIsImh0dHA6XC9cL3dzbzIub3JnXC9jbGFpbXNcL2VuZHVzZXJUZW5hbnRJZCI6Ii0xMjM0IiwiaHR0cDpcL1wvd3NvMi5vcmdcL2NsYWltc1wvYXBwbGljYXRpb25VVUlkIjoiMTc0NmM2MjctYmM5NS00MTEzLTg4ZjAtOWU1Y2IwM2M2ZjUyIiwiaHR0cDpcL1wvd3NvMi5vcmdcL2NsYWltc1wvc3Vic2NyaWJlciI6Ik5FVFMuRVVcL2lsb3JpQG5ldHMuZXUiLCJodHRwOlwvXC93c28yLm9yZ1wvY2xhaW1zXC90aWVyIjoiR29sZCIsImV4cCI6MTU1NzMxMDYxMSwiaHR0cDpcL1wvd3NvMi5vcmdcL2NsYWltc1wvYXBwbGljYXRpb25pZCI6IjEzNjEiLCJodHRwOlwvXC93c28yLm9yZ1wvY2xhaW1zXC91c2VydHlwZSI6IkFQUExJQ0FUSU9OX1VTRVIiLCJNdWx0aUF0dHJpYnV0ZVNlcGFyYXRvciI6W10sImVtYWlsIjoicGdhaWtAbmV0cy5ldSIsImh0dHA6XC9cL3dzbzIub3JnXC9jbGFpbXNcL2FwaWNvbnRleHQiOiJcL21zXC9hYXBheVwvcmVwb3J0aW5nXC8xLjIifQ==.NBZG8Yea0DCU1gLKYXFQC15ThfGLoQ5Jfhc290hoHD9Umjs3OqB8GmZUkfS8zjFMgfj7rD8b9G8Z1Ytnduox3d+uzi3sfisbFidw2T4pXm1j/J+RVoehe5K4unISnhtedzAokpJsUlKa6HHUzu8mREF2XKNzhNiSP/8nsU7uyysSpfQbu7AancVOMAL6P2zBGld+UcRz0vQlWigBTJr1N3XGyIU54FvRCu15JT+SLYX6jDH6w80BAohj/lay/FzBz+cZxOlSftc2/KFQyR5ZM4rbHDkacFXKeawgla1Odztm+83gknr2zhDxFhao1kmmeM6LGMi3NcEtizUAiwzAUrhQNRCSEwv4sN1Up2IAiSlDJu4ttZ2J+Y6LjIKaA7nELcTJcQyPXeG70sgt3IKnMjujrOrw6D6N5eLrZ9J9+tIgb1YnmafqpvpdysF09bI01vo8K7qggKFy745a412jFGhVikgf8E4+yrOlk8eHZXM7UZrxJOBzO4izQeevtEIhvZ/EyYmFbGjnvh1szNaCvwICZvihbsEbz+rp3uR020JJJoy5pNh2alcGwMyL7r4cVZksuJ10xGhgOwn7aCMjxj/nIPcYCFmJ7uwtqckwol1s00w0nZJ352OVlAH8xKLlOsFN5jAvh0oevnMWKRgm7s9WuHKGXv0nAuAq8Y7ZvpI="; private static String userPayload = "{\n" + " \"user-name\": \"Some Username\",\n" + " \"first-name\": \"Some firstname\",\n" + " \"last-name\": \"Some lastname\"\n" + "}"; private static String existingUserNamePayload = "{\n" + " \"user-name\": \"gasaw\",\n" + " \"first-name\": \"Some firstname\",\n" + " \"last-name\": \"Some lastname\"\n" + "}"; @Resource private UserRepository userRepository; @Inject UserRESTServiceImpl userRESTServiceImpl; @Autowired private ObjectMapper objectMapper; @LocalServerPort protected int port; @Before public void setup() { RestAssured.baseURI = "http://localhost"; RestAssured.basePath = "/twitter"; RestAssured.port = port; given().when() .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header(HEADER_KEY, HEADER_VALUE) .post("/user/follow/follower/2/follow/1") .then() .statusCode(200) .log() .body().extract() .response(); } @Test public void shouldGiveUnauthorizedAccessWhenHeaderNotPresent() throws JsonMappingException, JsonProcessingException { given().when() .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .get("/user/getUsers") .then() .statusCode(401) .log() .body() .extract().response(); } @Test public void shouldGetUsers() throws JsonMappingException, JsonProcessingException { Response response = given().when() .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header(HEADER_KEY, HEADER_VALUE) .get("/user/getUsers") .then() .statusCode(200) .log() .body().extract() .response(); UserDTO[] userDTOs = objectMapper.readValue(response.getBody().asString(), UserDTO[].class); assertThat(userDTOs).isNotNull(); } @Test public void shouldCreateUser() throws JsonMappingException, JsonProcessingException { given().when() .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header(HEADER_KEY, HEADER_VALUE) .body(userPayload) .post("/user/createUser") .then() .statusCode(201) .log() .body().extract() .response(); Response userReponse = given().when() .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header(HEADER_KEY, HEADER_VALUE) .get("/user/getUsers") .then() .statusCode(200) .log() .body().extract() .response(); UserDTO[] userDTOs = objectMapper.readValue(userReponse.getBody().asString(), UserDTO[].class); assertThat(userDTOs.length).isEqualTo(5); } @Test public void shouldNotCreateUserIfUsernameExists() throws JsonMappingException, JsonProcessingException { given().when() .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header(HEADER_KEY, HEADER_VALUE) .body(existingUserNamePayload) .post("/user/createUser") .then() .statusCode(409) .log() .body().extract() .response(); } @Test public void shouldFollowUser() throws JsonMappingException, JsonProcessingException { given().when() .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header(HEADER_KEY, HEADER_VALUE) .post("/user/follow/follower/3/follow/1") .then() .statusCode(200) .log() .body().extract() .response(); Optional<User> user = userRESTServiceImpl.findUser(1L); assertThat(user.get().getFollowerUser()).isNotNull(); assertThat(user.get().getFollowerUser().size()).isEqualTo(2); } @Test public void shouldNotFollowUserWhenWrongUserId() throws JsonMappingException, JsonProcessingException { given().when() .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header(HEADER_KEY, HEADER_VALUE) .post("/user/follow/follower/ÅÅ/follow/PP") .then() .statusCode(400) .log() .body().extract() .response(); } @Test public void shouldNotFollowSameUserId() throws JsonMappingException, JsonProcessingException { given().when() .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header(HEADER_KEY, HEADER_VALUE) .post("/user/follow/follower/1/follow/1") .then() .statusCode(403) .log() .body().extract() .response(); } @Test public void shouldUnFollowUser() throws JsonMappingException, JsonProcessingException { given().when() .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header(HEADER_KEY, HEADER_VALUE) .post("/user/unfollow/follower/2/unfollow/1") .then() .statusCode(200) .log() .body().extract() .response(); Optional<User> user = userRESTServiceImpl.findUser(1L); assertThat(user.get().getFollowerUser().size()).isEqualTo(0); } @Test public void shouldNotUnFollowUserWhenWrongUserId() throws JsonMappingException, JsonProcessingException { given().when() .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header(HEADER_KEY, HEADER_VALUE) .post("/user/unfollow/follower/ÅÅ/unfollow/PP") .then() .statusCode(400) .log() .body().extract() .response(); } @Test public void shouldNotFollowUserWhenUserNotPresent() throws JsonMappingException, JsonProcessingException { given().when() .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header(HEADER_KEY, HEADER_VALUE) .post("/user/follow/follower/9/follow/1") .then() .statusCode(404) .log() .body().extract() .response(); } @Test public void shouldNotUnFollowUserWhenUserNotPresent() throws JsonMappingException, JsonProcessingException { given().when() .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header(HEADER_KEY, HEADER_VALUE) .post("/user/unfollow/follower/9/unfollow/1") .then() .statusCode(404) .log() .body().extract() .response(); } @Test public void shouldNotUnFollowUserWhenFollowerNotFound() throws JsonMappingException, JsonProcessingException { given().when() .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header(HEADER_KEY, HEADER_VALUE) .post("/user/unfollow/follower/3/unfollow/1") .then() .statusCode(403) .log() .body().extract() .response(); } @Test public void shouldGetFollowers() throws JsonMappingException, JsonProcessingException { Response response = given().when() .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header(HEADER_KEY, HEADER_VALUE) .get("/user/getfollowers/1") .then() .statusCode(200) .log() .body().extract() .response(); UserDTO[] userDTOs = objectMapper.readValue(response.getBody().asString(), UserDTO[].class); assertThat(userDTOs).isNotNull(); assertThat(userDTOs.length).isEqualTo(1); } @Test public void shouldDeleteUser() throws JsonMappingException, JsonProcessingException { given().when() .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header(HEADER_KEY, HEADER_VALUE) .delete("/user/deleteUser/4") .then() .statusCode(204) .log() .body().extract() .response(); Optional<User> user = userRESTServiceImpl.findUser(4L); assertThat(user.isPresent()).isEqualTo(false); } @Test public void shouldNotDeleteUserWhenUserNotFound() throws JsonMappingException, JsonProcessingException { given().when() .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header(HEADER_KEY, HEADER_VALUE) .delete("/user/deleteUser/99") .then() .statusCode(500) .log() .body().extract() .response(); } @Test public void shouldNotDeleteUserWhenBadUserId() throws JsonMappingException, JsonProcessingException { given().when() .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header(HEADER_KEY, HEADER_VALUE) .delete("/user/deleteUser/PP") .then() .statusCode(400) .log() .body().extract() .response(); } }
package com.sunny.rpc.socket; import java.io.IOException; import java.net.Socket; import java.util.Date; import java.util.concurrent.TimeUnit; /** * <Description> <br> * * @author Sunny<br> * @version 1.0<br> * @taskId: <br> * @createDate 2018/10/11 23:23 <br> * @see com.sunny.rpc.socket <br> */ public class IOClient { public static void main(String[] args) throws IOException, InterruptedException { Socket socket = new Socket("127.0.0.1", 8000); while(true) { socket.getOutputStream().write((new Date() + ": hello world ").getBytes()); //Thread.sleep(2000); TimeUnit.MILLISECONDS.sleep(2000); } } }
package slimeknights.tconstruct.plugin.jei.casting; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.lang3.tuple.Triple; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.Fluid; import slimeknights.tconstruct.library.TinkerRegistry; import slimeknights.tconstruct.library.smeltery.Cast; import slimeknights.tconstruct.library.smeltery.CastingRecipe; import slimeknights.tconstruct.library.smeltery.ICastingRecipe; import slimeknights.tconstruct.plugin.jei.JEIPlugin; public class CastingRecipeChecker { private static CastingRecipeWrapper recipeWrapper; public static List<CastingRecipeWrapper> getCastingRecipes() { List<CastingRecipeWrapper> recipes = new ArrayList<>(); Map<Triple<Item, Item, Fluid>, List<ItemStack>> castDict = Maps.newHashMap(); for(ICastingRecipe irecipe : TinkerRegistry.getAllTableCastingRecipes()) { if(irecipe instanceof CastingRecipe) { CastingRecipe recipe = (CastingRecipe) irecipe; if(recipe.cast != null && recipe.getResult() != null && recipe.getResult().getItem() instanceof Cast) { Triple<Item, Item, Fluid> output = Triple.of(recipe.getResult().getItem(), Cast.getPartFromTag(recipe.getResult()), recipe.getFluid().getFluid()); if(!castDict.containsKey(output)) { List<ItemStack> list = Lists.newLinkedList(); castDict.put(output, list); recipeWrapper = new CastingRecipeWrapper(list, recipe, JEIPlugin.castingCategory.castingTable); if(recipeWrapper.isValid(false)) { recipes.add(recipeWrapper); } } castDict.get(output).addAll(recipe.cast.getInputs()); } else { recipeWrapper = new CastingRecipeWrapper(recipe, JEIPlugin.castingCategory.castingTable); if(recipeWrapper.isValid(true)) { recipes.add(recipeWrapper); } } } } for(ICastingRecipe irecipe : TinkerRegistry.getAllBasinCastingRecipes()) { if(irecipe instanceof CastingRecipe) { CastingRecipe recipe = (CastingRecipe) irecipe; recipeWrapper = new CastingRecipeWrapper(recipe, JEIPlugin.castingCategory.castingBasin); if(recipeWrapper.isValid(true)) { recipes.add(recipeWrapper); } } } return recipes; } }
package org.maple.jdk8.stream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @Author Mapleins * @Date 2019-04-06 2:09 * @Description flatMap */ public class Test7 { public static void main(String[] args) { // 将集合中的元素转换成大写,然后输出 Stream<String> stream = Stream.of("hello ", "world ", "hello world", "test"); stream.map(String::toUpperCase).collect(Collectors.toList()).forEach(System.out::println); System.out.println("---------------------------------"); // 求出集合中每个数字的平方,打印 Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5); integerStream.map(x -> x * x).collect(Collectors.toList()).forEach(System.out::println); System.out.println("---------------------------------"); /** * flatmap: 如果是一个 arraylist -> 那么进入 map 映射就是 值 -> 值 * 如果是多个 arraylist -> 那么进去 map 映射后 依然是 一个 list 值 ->值 * 而使用 flatmap 映射 则是把所有 arraylist 中的值 -> 映射为一个集合中的值 */ // 将 ArrayList 中的每个元素平方,之后作为一个整体输出 Stream<List<Integer>> listStream = Stream.of(Arrays.asList(1), Arrays.asList(2, 3), Arrays.asList(4, 5)); // 把集合变成流,然后映射为一个整体集合 listStream.flatMap(Collection::stream).map(x -> x * x).collect(Collectors.toList()).forEach(System.out::println); } }
package com.example.Lookify.controllers; import java.util.List; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.example.Lookify.models.lookify; import com.example.Lookify.services.lookifyService; @RestController public class LookifyApi { private final lookifyService lookyService; public LookifyApi(lookifyService lookyService){ this.lookyService = lookyService; } @RequestMapping("/api/lookify") public List<lookify> index() { return lookyService.alllookify(); } @RequestMapping(value="/api/lookify", method=RequestMethod.POST) public lookify create(@RequestParam(value="title") String title, @RequestParam(value="artist") String artist, @RequestParam(value="rating") int rating) { lookify looky = new lookify(title, artist , rating); return lookyService.createLookify(looky); } @RequestMapping("/api/lookify/{id}") public lookify show(@PathVariable("id") Long id) { lookify looky = lookyService.findLookify(id); return looky; } @RequestMapping(value="/api/lookify/{id}", method=RequestMethod.PUT) public lookify update(@PathVariable("id") Long id, @RequestParam(value="title") String title, @RequestParam(value="artist") String artist, @RequestParam(value="rating") int rating){ lookify looky = lookyService.updateLookify(id, title, artist, rating ); return looky; } @RequestMapping(value="/api/lookify/{id}", method=RequestMethod.DELETE) public void destroy(@PathVariable("id") Long id) { lookyService.deleteLookify(id); } }
package gina.nikol.qnr.demo.entity; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "EMPLOYEES") public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "Emp_ID") private int id; @Column(name = "Firstname") private String firstName; @Column(name = "Lastname") private String lastName; @Column(name = "Job") private String job; @Column(name = "Hiredate") private Date hireDate; @Column(name = "Salary") private double salary; @Column(name = "Comm") private int commission; @ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH }) @JoinColumn(name = "DEPARTMENTS_Dept_ID") // From Employee table private Department department; // mappedBy in Department @ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH }) @JoinColumn(name = "MANAGER_Mng_ID") // From Employee table private Manager manager; // mappedBy in Manager public Employee() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public Date getHireDate() { return hireDate; } public void setHireDate(Date hireDate) { this.hireDate = hireDate; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public int getCommission() { return commission; } public void setCommission(int commission) { this.commission = commission; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } public Manager getManager() { return manager; } public void setManager(Manager manager) { this.manager = manager; } @Override public String toString() { return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", job=" + job + ", hireDate=" + hireDate + ", salary=" + salary + ", commission=" + commission + ", department=" + department + ", manager=" + manager + "]"; } }
package lefkatis.personalityapp.Controllers; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import lefkatis.personalityapp.App; import lefkatis.personalityapp.Models.GoogleAnalyticsHelper; import lefkatis.personalityapp.R; public class AboutActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); setupToolbar(); } private void setupToolbar(){ //set up the toolbar Toolbar toolbar = (Toolbar) findViewById(R.id.mainToolbar); setSupportActionBar(toolbar); toolbar.setTitle("About"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); } @Override protected void onPostResume() { super.onPostResume(); App app = (App) getApplication(); GoogleAnalyticsHelper.getInstance().sendScreenEvent(app, "Entered Profile Activity"); } }
package com.example.smdemo1.service; import javax.annotation.Resource; import com.example.smdemo1.dao.UserMapper2; import com.example.smdemo1.model.User; import org.springframework.stereotype.Service; /** * @author xp-dc * @date 2018/12/25 */ @Service public class UserService2 { @Resource private UserMapper2 userMapper2; public int insertUser(User user){ if(user == null){ return -1; } if(user.getName() == null || "".equals(user.getName())){ return 0; } return userMapper2.insert(user); } public User fetch(Integer id){ if(id == null || id <= 0){ return null; } return userMapper2.fetch(id); } }
package it.unimi.di.tsp20.TailCallOptimization; /** * Colors used to format strings in the console. */ public class ConsoleColors { // Reset public static final String RESET = "\033[0m"; // Text Reset // Regular Colors public static final String YELLOW = "\033[0;33m"; // YELLOW //Bold Colors public static final String GREEN_BOLD = "\033[1;32m"; // GREEN public static final String RED_BOLD = "\033[1;31m"; // RED public static final String BLUE_BOLD = "\033[1;34m"; // BLUE public static final String CYAN_BOLD = "\033[1;36m"; // CYAN }
package logica; import java.io.Serializable; public class MemoriaRam extends Producto implements Serializable{ private static final long serialVersionUID = 1L; private String cantidadMemoria; private String tipoMemoria; public MemoriaRam(double precio, int cantInicial, String numeroSerie, String marca, String modelo, String cantidadMemoria, String tipoMemoria) { super(precio, cantInicial, numeroSerie, marca, modelo); this.cantidadMemoria = cantidadMemoria; this.tipoMemoria = tipoMemoria; } public String getCantidadMemoria() { return cantidadMemoria; } public void setCantidadMemoria(String cantidadMemoria) { this.cantidadMemoria = cantidadMemoria; } public String getTipoMemoria() { return tipoMemoria; } public void setTipoMemoria(String tipoMemoria) { this.tipoMemoria = tipoMemoria; } }
/* * 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 conteudo; import java.util.Vector; /** * * @author Mayco, Matheus, Henrique */ public class ConjuntoImagem { private int id; private String descricao; private Vector< Vector<Imagem>> imagens; /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @return the imagens */ public Vector< Vector<Imagem>> getImagens() { return imagens; } /** * @param imagens the imagens to set */ public void setImagens(Vector< Vector<Imagem>> imagens) { this.imagens = imagens; } /** * @return the descricao */ public String getDescricao() { return descricao; } /** * @param descricao the descricao to set */ public void setDescricao(String descricao) { this.descricao = descricao; } }
package com.durgesh.schoolassist.Adapters; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import com.durgesh.schoolassist.R; public class qViewHolder extends RecyclerView.ViewHolder { ImageView imageView; EditText editText; Button button; String username; public qViewHolder(@NonNull View itemView, String username, Context context) { super(itemView); imageView = itemView.findViewById(R.id.downloaded_image); editText = itemView.findViewById(R.id.editText); button=itemView.findViewById(R.id.submit_button); this.username=username; } }
package fi.lyma.minesweeper.logic; import static org.junit.Assert.*; import fi.lyma.minesweeper.logic.Tile; import org.junit.Before; import org.junit.Test; /** * Created by lyma on 24.1.2017. */ public class TileTest { Tile tile; @Before public void setup() { tile = new Tile(0, 0); } @Test public void defaultValuesAreSet() { assertEquals(Tile.TileStatus.CLOSED, tile.getStatus()); assertFalse(tile.containsBomb()); } @Test public void settersWork() { tile.flag(); assertEquals(Tile.TileStatus.FLAG, tile.getStatus()); tile.open(); assertEquals(Tile.TileStatus.OPEN, tile.getStatus()); tile.placeBomb(); assertTrue(tile.containsBomb()); } @Test public void flaggingWorks() { assertTrue(tile.canBeOpened()); assertEquals(Tile.TileStatus.CLOSED, tile.getStatus()); tile.flag(); assertFalse(tile.canBeOpened()); assertEquals(Tile.TileStatus.FLAG, tile.getStatus()); tile.flag(); assertTrue(tile.canBeOpened()); assertEquals(Tile.TileStatus.QUESTION, tile.getStatus()); tile.flag(); assertEquals(Tile.TileStatus.CLOSED, tile.getStatus()); } }
package com.fanfte.designPattern.dynamicProxy; public interface FishSeller { int sellFish(); }
package com.zhanwei.java.test2; public class ThreadDemo extends Thread{ private Sequence sequence; public ThreadDemo(Sequence sequence) { this.sequence = sequence; } public void run() { for(int i=0;i<3;i++){ System.out.println("Thread :" + Thread.currentThread().getName() + ",number : " + sequence.getNumber()); } } }
package py.edu.facitec.psmsystem.abm; import java.awt.Color; import java.awt.Font; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.List; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.SwingConstants; import py.com.cs.xnumberfield.component.NumberTextField; import py.edu.facitec.psmsystem.app.VentanaPrincipal; import py.edu.facitec.psmsystem.dao.ConfiguracionDao; import py.edu.facitec.psmsystem.entidad.Configuracion; public class VentanaConfiguracion extends JDialog { private JTextField tfNombre; private JTextField tfRuc; private JTextField tfTelefono; private JTextField tfEmail; private Configuracion configuracion; private ConfiguracionDao dao; private List<Configuracion> configuraciones; private JButton btnActualizar; public NumberTextField tfInteres; private JButton btnCancelar; private JButton btnBorrar; private List<Configuracion> campos; private JLabel lblValidarTelefono; private JComponent ventanaConfiguracion; private JLabel lblValidarRuc; private JLabel lblValidarNombre; protected void setUpControlador() { } public VentanaConfiguracion() { setTitle("Configuración"); setResizable(false); setIconImage(Toolkit.getDefaultToolkit().getImage(VentanaConfiguracion.class.getResource("/img/ventanas/icono.png"))); setBounds(100, 100, 396, 276); getContentPane().setLayout(null); setLocationRelativeTo(this); setModal(true); setResizable(false); JLabel lblNombre = new JLabel("Nombre o raz\u00F3n social :"); lblNombre.setHorizontalAlignment(SwingConstants.LEFT); lblNombre.setFont(new Font("Tahoma", Font.PLAIN, 14)); lblNombre.setBounds(10, 14, 176, 20); getContentPane().add(lblNombre); JLabel lblRuc = new JLabel("R.U.C. :"); lblRuc.setHorizontalAlignment(SwingConstants.LEFT); lblRuc.setFont(new Font("Tahoma", Font.PLAIN, 14)); lblRuc.setBounds(10, 48, 176, 20); getContentPane().add(lblRuc); JLabel lblTelefono = new JLabel("Tel\u00E9fono :"); lblTelefono.setHorizontalAlignment(SwingConstants.LEFT); lblTelefono.setFont(new Font("Tahoma", Font.PLAIN, 14)); lblTelefono.setBounds(10, 82, 176, 20); getContentPane().add(lblTelefono); JLabel lblEmail = new JLabel("Email :"); lblEmail.setHorizontalAlignment(SwingConstants.LEFT); lblEmail.setFont(new Font("Tahoma", Font.PLAIN, 14)); lblEmail.setBounds(10, 116, 176, 20); getContentPane().add(lblEmail); JLabel lblTazaInteres = new JLabel("Taza de inter\u00E9s :"); lblTazaInteres.setHorizontalAlignment(SwingConstants.LEFT); lblTazaInteres.setFont(new Font("Tahoma", Font.PLAIN, 14)); lblTazaInteres.setBounds(10, 150, 176, 20); getContentPane().add(lblTazaInteres); JLabel label = new JLabel("%"); label.setBounds(230, 155, 27, 14); getContentPane().add(label); tfNombre = new JTextField(); tfNombre.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { lblValidarNombre.setVisible(false); } }); tfNombre.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { char c = e.getKeyChar(); if (c == e.VK_ENTER) { tfRuc.requestFocus(); tfRuc.selectAll(); } } @Override public void keyTyped(KeyEvent e) { if (tfNombre.getText().length() == 40) { lblValidarNombre.setVisible(true); e.consume(); } } }); tfNombre.setBounds(185, 14, 195, 20); getContentPane().add(tfNombre); tfNombre.setColumns(10); tfRuc = new JTextField(); tfRuc.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { lblValidarRuc.setVisible(false); } }); tfRuc.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { char c = e.getKeyChar(); int k = (int) e.getKeyChar(); if (!Character.isDigit(c) & c != e.VK_ENTER & c != e.VK_BACK_SPACE & k !=45) { e.consume(); lblValidarRuc.setVisible(true); }else{ lblValidarRuc.setVisible(false); } if (tfTelefono.getText().length() == 20) { e.consume(); } } @Override public void keyPressed(KeyEvent e) { char c = e.getKeyChar(); if (c == e.VK_ENTER) { tfTelefono.requestFocus(); tfTelefono.selectAll(); } } }); tfRuc.setBounds(185, 48, 195, 20); getContentPane().add(tfRuc); tfRuc.setColumns(10); tfTelefono = new JTextField(); tfTelefono.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { lblValidarTelefono.setVisible(false); } }); tfTelefono.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { char c = e.getKeyChar(); int k = (int) e.getKeyChar(); //32= ESPACIO, 40= (, 41= ), 43= +, 45= - if (!Character.isDigit(c) & c != e.VK_ENTER & c != e.VK_BACK_SPACE & k !=32 & k !=43 & k !=40 & k !=41 & k !=45) { e.consume(); lblValidarTelefono.setVisible(true); }else{ lblValidarTelefono.setVisible(false); } if (tfTelefono.getText().length() == 20) { e.consume(); } } @Override public void keyPressed(KeyEvent e) { char c = e.getKeyChar(); if (c == e.VK_ENTER) { tfEmail.requestFocus(); tfEmail.selectAll(); } } }); tfTelefono.setBounds(185, 82, 195, 20); getContentPane().add(tfTelefono); tfTelefono.setColumns(10); tfEmail = new JTextField(); tfEmail.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { char c = e.getKeyChar(); if (c == e.VK_ENTER) { tfInteres.requestFocus(); tfInteres.selectAll(); } } }); tfEmail.setText(""); tfEmail.setBounds(185, 116, 195, 20); getContentPane().add(tfEmail); tfEmail.setColumns(10); tfInteres = new NumberTextField(); tfInteres.setHorizontalAlignment(SwingConstants.RIGHT); tfInteres.setBounds(185, 150, 44, 20); tfInteres.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { char c = e.getKeyChar(); if (c == e.VK_ENTER) { btnActualizar.requestFocus(); } } }); getContentPane().add(tfInteres); tfInteres.setColumns(10); btnActualizar = new JButton("Actualizar"); btnActualizar.setFont(new Font("Tahoma", Font.PLAIN, 15)); btnActualizar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int respuesta = JOptionPane.showConfirmDialog(null, "Estas seguro que deseas actualizar los datos de la empresa?", "Atención!", JOptionPane.YES_NO_OPTION); if (respuesta==JOptionPane.YES_OPTION) { actualizar(); } } }); btnActualizar.setBounds(24, 194, 97, 34); getContentPane().add(btnActualizar); btnBorrar = new JButton("Borrar"); btnBorrar.setFont(new Font("Tahoma", Font.PLAIN, 15)); btnBorrar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { vaciarFormulario(); } }); btnBorrar.setBounds(145, 194, 97, 34); getContentPane().add(btnBorrar); btnCancelar = new JButton("Cancelar"); btnCancelar.setFont(new Font("Tahoma", Font.PLAIN, 15)); btnCancelar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); btnCancelar.setBounds(266, 194, 97, 34); getContentPane().add(btnCancelar); lblValidarTelefono = new JLabel("*Solo n\u00FAmeros"); lblValidarTelefono.setVisible(false); lblValidarTelefono.setForeground(Color.RED); lblValidarTelefono.setFont(new Font("Tahoma", Font.PLAIN, 11)); lblValidarTelefono.setBounds(185, 101, 178, 14); getContentPane().add(lblValidarTelefono); lblValidarRuc = new JLabel("*Caracter no permitido"); lblValidarRuc.setVisible(false); lblValidarRuc.setForeground(Color.RED); lblValidarRuc.setBounds(184, 68, 154, 15); getContentPane().add(lblValidarRuc); lblValidarNombre = new JLabel("*No se permite m\u00E1s caracteres"); lblValidarNombre.setVisible(false); lblValidarNombre.setForeground(Color.RED); lblValidarNombre.setBounds(185, 32, 195, 20); getContentPane().add(lblValidarNombre); datosActuales(); } //-------------------------FIN DEL CONSTRUCTOR-------------------------------- private void cargarDatos() { configuracion = new Configuracion(); configuracion.setId(1); configuracion.setNombre(tfNombre.getText()); configuracion.setRuc(tfRuc.getText()); configuracion.setTelefono(tfTelefono.getText()); configuracion.setEmail(tfEmail.getText()); configuracion.setInteres(Double.parseDouble(tfInteres.getText())); } private void actualizar(){ if(validarCampos()) { return; } cargarDatos(); dao = new ConfiguracionDao(); dao.insertarOModificar(configuracion); try { dao.commit(); } catch (Exception e) { e.printStackTrace(); dao.rollback(); } actualizarPantalla(); dispose(); } private void actualizarPantalla(){ dao = new ConfiguracionDao(); configuracion = dao.recuperarPorId(1); VentanaPrincipal.lblNombre.setText(configuracion.getNombre()); VentanaPrincipal.lblRuc.setText(configuracion.getRuc()); VentanaPrincipal.lblTelefono.setText(configuracion.getTelefono()); VentanaPrincipal.lblEmail.setText(configuracion.getEmail()); } private void datosActuales() { dao = new ConfiguracionDao(); configuraciones = dao.recuperarTodo(); if (configuraciones.size()==0) return; tfNombre.setText(configuraciones.get(0).getNombre()); tfRuc.setText(configuraciones.get(0).getRuc()); tfTelefono.setText(configuraciones.get(0).getTelefono()); tfEmail.setText(configuraciones.get(0).getEmail()); tfInteres.setText(configuraciones.get(0).getInteres()+""); } private void vaciarFormulario() { dao = new ConfiguracionDao(); tfNombre.setText(""); tfRuc.setText(""); tfTelefono.setText(""); tfEmail.setText(""); tfInteres.setText(""); } //-----------------------------------VALIDAR CAMPOS------------------------------------- private boolean validarCampos() { dao = new ConfiguracionDao(); campos = dao.recuperarTodo(); if (tfInteres.getText().isEmpty() || tfInteres.getValue() < 1){ JOptionPane.showMessageDialog(null, "Informe valor del \"Interés\" \nInterés mínimo es de 1%", "Atención!", JOptionPane.INFORMATION_MESSAGE); tfInteres.requestFocus(); tfInteres.setValue((double) 1); tfInteres.selectAll(); return true; } return false; } //-----------------------------------INICIALIZAR BASE DE DATOS------------------------------------- public void inicializarConfiguracion() { String tabla = "tb_configuracion"; dao.eliminarTodos(tabla); try { dao.commit(); } catch (Exception e) { dao.rollback(); } VentanaPrincipal.lblNombre.setText(""); VentanaPrincipal.lblRuc.setText(""); VentanaPrincipal.lblTelefono.setText(""); VentanaPrincipal.lblEmail.setText(""); } public JTextField gettfNombre() { return tfNombre; } public JTextField gettfRuc() { return tfRuc; } public JTextField gettfTelefono() { return tfTelefono; } public JTextField gettfEmail() { return tfEmail; } public JTextField getTfNombre() { return tfNombre; } public JTextField getTfRuc() { return tfRuc; } public JTextField getTfTelefono() { return tfTelefono; } public JTextField getTfEmail() { return tfEmail; } public Configuracion getConfiguracion() { return configuracion; } public ConfiguracionDao getDao() { return dao; } public List<Configuracion> getConfiguraciones() { return configuraciones; } public JButton getBtnActualizar() { return btnActualizar; } public NumberTextField getTfInteres() { return tfInteres; } public JButton getBtnCancelar() { return btnCancelar; } public JButton getBtnBorrar() { return btnBorrar; } public List<Configuracion> getCampos() { return campos; } public void setCampos(List<Configuracion> campos) { this.campos = campos; } public void setTfNombre(JTextField tfNombre) { this.tfNombre = tfNombre; } public void setTfRuc(JTextField tfRuc) { this.tfRuc = tfRuc; } public void setTfTelefono(JTextField tfTelefono) { this.tfTelefono = tfTelefono; } public void setTfEmail(JTextField tfEmail) { this.tfEmail = tfEmail; } public void setConfiguracion(Configuracion configuracion) { this.configuracion = configuracion; } public void setDao(ConfiguracionDao dao) { this.dao = dao; } public void setConfiguraciones(List<Configuracion> configuraciones) { this.configuraciones = configuraciones; } public void setBtnActualizar(JButton btnActualizar) { this.btnActualizar = btnActualizar; } public void setTfInteres(NumberTextField tfInteres) { this.tfInteres = tfInteres; } public void setBtnCancelar(JButton btnCancelar) { this.btnCancelar = btnCancelar; } public void setBtnBorrar(JButton btnBorrar) { this.btnBorrar = btnBorrar; } }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.concurrent.RecursiveTask; public class ForkAndJoin { private static final ForkJoinPool POOL = new ForkJoinPool(2); public static void main(String[] args) { ComputeSumTasks mainTask = new ComputeSumTasks(new Long[]{1l,2l,3l,4l,5l,6l,7l,8l,9l,10l,11l,12l,13l,14l,15l,16l,17l,18l,19l,20l,21l,22l,23l,24l,25l,26l,27l,28l,29l,30l}); Long result = POOL.invoke(mainTask); System.out.println(result); Fibonacci fibo = new Fibonacci(6); int number = POOL.invoke(fibo); System.out.println(number); System.out.println(1<<3); } } class ComputeSumTasks extends RecursiveTask<Long>{ private final Long[] data; private static final int THRESHOLD = 10; ComputeSumTasks(Long[] data){ this.data = data; } @Override protected Long compute() { if(this.data.length > THRESHOLD){ ForkJoinTask.invokeAll(createSubTasks()); } Long result = Arrays.stream(this.data) .mapToLong(Long::valueOf) .sum(); return result; } private List<ComputeSumTasks> createSubTasks(){ ComputeSumTasks taskOne = new ComputeSumTasks(Arrays.copyOfRange(this.data, 0, (this.data.length/2))); ComputeSumTasks taskTwo = new ComputeSumTasks(Arrays.copyOfRange(this.data, (this.data.length/2), this.data.length)); List<ComputeSumTasks> tasks = new ArrayList<>(); tasks.add(taskOne); tasks.add(taskTwo); return tasks; } } class Fibonacci extends RecursiveTask<Integer> { final int n; Fibonacci(int n) { this.n = n; } protected Integer compute() { if (n <= 1) return n; Fibonacci f1 = new Fibonacci(n - 1); f1.fork(); Fibonacci f2 = new Fibonacci(n - 2); return f2.compute() + f1.join(); } }
package com.bofsoft.laio.customerservice.DataClass.erweima; import com.bofsoft.laio.data.BaseData; public class ShareCodeAndInfo extends BaseData { public String invitecode;//优惠码 public String invitehtml;//分享展示html public String shareinfo;//分享文本内容 public String inviteurl;//分享的连接 public String sharetitle;//分享标题内容 public String qrcodeurl;//二维码URL }
package FolkPaaUni; public class Person { private int ID; private String fornavn; private String etternavn; private int fodselsaar; public Person(int id, String fnavn,String enavn, int faar) { ID = id; fornavn = fnavn; etternavn = enavn; fodselsaar = faar; } public Person() { } public int getId() { return ID; } public String getFnavn() { return fornavn; } public String getEtternavn() { return etternavn; } public int getFaar() { return fodselsaar; } public void setID( int nyID) { ID = nyID; } public void setFaar(int nyttFAar) { fodselsaar = nyttFAar; } public String toString() { return "Navnet til personen med id "+ ID + " er " + fornavn + " " + etternavn +" og fodselsaaret er "+ fodselsaar; } public static void main(String [] args) { Person david = new Person(5, "David", "Harestad", 1987); System.out.println(david.toString()); david.setFaar(1988); System.out.println(david.toString()); } }
package bg.swift.HW17; public class Address { private String streetAddress; private String city; private String state; private int postalCode; public Address(String streetAddress, String city, String state, int postalCode) { this.streetAddress = streetAddress; this.city = city; this.state = state; this.postalCode = postalCode; } public String getStreetAddress() { return streetAddress; } public String getCity() { return city; } public String getState() { return state; } public int getPostalCode() { return postalCode; } @Override public String toString() { String output = String.format("street: %s%ncity: %s%nstate: %s%npostal code: %d%n", this.streetAddress, this.city, this.state, this.postalCode); return output; } }
package com.appsala.app.controllers; import java.util.List; import com.appsala.app.entities.Regional; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import com.appsala.app.services.RegionalService; import org.springframework.web.bind.annotation.*; import org.springframework.beans.factory.annotation.Autowired; @RestController @RequestMapping("/regional") public class RegionalController { @Autowired private RegionalService regionalService; @RequestMapping(value = "/{id}", method = RequestMethod.GET) public ResponseEntity<?> findById(@PathVariable Integer id) { Regional regional= regionalService.findById(id); return new ResponseEntity<>(regional, HttpStatus.OK); } @RequestMapping(method = RequestMethod.GET) public ResponseEntity<List<Regional>> findAll() { List<Regional> regionalList = regionalService.findAll(); return new ResponseEntity<>(regionalList, HttpStatus.OK); } @RequestMapping(value = "/{id}", method = RequestMethod.PUT) public ResponseEntity<Void> update(@PathVariable Integer id, @RequestBody Regional regional) { regional = regionalService.update(regional); return ResponseEntity.noContent().build(); } @RequestMapping(method = RequestMethod.POST) public ResponseEntity<Void> create(@RequestBody Regional regional) { regional = regionalService.create(regional); return ResponseEntity.noContent().build(); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public ResponseEntity<Void> deleteById(@PathVariable Integer id) { regionalService.deleteById(id); return ResponseEntity.noContent().build(); } }
package duverger.lib; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Optional; import java.util.function.*; public class InstanceHolder<T> { private final T value; private final boolean isPresent; private InstanceHolder(final T value_p, final boolean isPresent_p) { this.value = value_p; this.isPresent = isPresent_p; } private static final InstanceHolder<?> EMPTY = new InstanceHolder<>(null, false); public static<X> InstanceHolder<X> empty() { return (InstanceHolder<X>)EMPTY; } public static<X> InstanceHolder<X> of(X val) { return val == null ? empty() : ofNullable(val); } public static<X> InstanceHolder<X> of(Optional<X> opt) { return of(opt.orElse(null)); } public static<X> InstanceHolder<X> ofNullable(X val) { return new InstanceHolder<>(val, true); } public static<X> InstanceHolder<X> ofNullable(Optional<X> opt) { return ofNullable(opt.orElse(null)); } public boolean isPresent() { return this.isPresent; } public boolean isNull() { return this.value == null; } // ********** CONSUMER public InstanceHolder<T> doIf(Consumer<? super T> action, boolean flag) { if (this.isPresent() && flag) action.accept(this.value); return this; } public InstanceHolder<T> doIf(Consumer<? super T> action, Supplier<Boolean> flag) { if (this.isPresent() && flag.get()) action.accept(this.value); return this; } public InstanceHolder<T> doIf(Consumer<? super T> action, Function<? super T, Boolean> flag) { if (this.isPresent() && flag.apply(this.value)) action.accept(this.value); return this; } public InstanceHolder<T> doIfPresent(Consumer<? super T> action) { return this.doIf(action, true); } public InstanceHolder<T> doIfNonnull(Consumer<? super T> action) { return this.doIf(action, !this.isNull()); } public InstanceHolder<T> loopIfPresent(int init, BiFunction<Integer, T, Boolean> stop, Consumer<T> action) { if (this.isPresent()) { int i = 0; while (!stop.apply(i, this.value)) action.accept(this.value); } return this; } public InstanceHolder<T> loopIfPresent(int init, int max, Consumer<T> action) { return this.loopIfPresent(init, (Integer i, T t)-> i < max, action); } public InstanceHolder<T> loopIfNonnull(int init, BiFunction<Integer, T, Boolean> stop, Consumer<T> action) { if (this.isNull()) { int i = 0; while (!stop.apply(i, this.value)) action.accept(this.value); } return this; } public InstanceHolder<T> loopIfNonnull(int init, int max, Consumer<T> action) { return this.loopIfNonnull(init, (Integer i, T t)-> i < max, action); } // ********** FILTER public InstanceHolder<T> filter(Predicate<? super T> predicate) { return !this.isPresent() ? this : ( predicate.test(this.value) ? this : empty() ); } public InstanceHolder<T> filter(Supplier<Boolean> flag) { return this.filter( (T t)-> flag.get() ); } public InstanceHolder<T> filter(boolean flag) { return this.filter( (T t)-> flag ); } // ********** MAPPING public<U> InstanceHolder<U> map(Function<? super T, ? extends U> mapper) { return !this.isPresent() ? empty() : InstanceHolder.ofNullable(mapper.apply(this.value)); } public<U> InstanceHolder<U> map(Function<? super T, ? extends U> mapperA, Function<? super T, ? extends U> mapperB, boolean flag) { return !this.isPresent() ? empty() : InstanceHolder.ofNullable( (flag ? mapperA.apply(this.value) : mapperB.apply(this.value))); } public<U> InstanceHolder<U> map(Function<? super T, ? extends U> mapperA, Function<? super T, ? extends U> mapperB, Supplier<Boolean> flag) { return !this.isPresent() ? empty() : InstanceHolder.ofNullable( (flag.get() ? mapperA.apply(this.value) : mapperB.apply(this.value))); } public<U> InstanceHolder<U> map(Function<? super T, ? extends U> mapperA, Function<? super T, ? extends U> mapperB, Function<? super T, Boolean> flag) { return !this.isPresent() ? empty() : InstanceHolder.ofNullable( (flag.apply(this.value) ? mapperA.apply(this.value) : mapperB.apply(this.value))); } // ********** FLAT MAPPING public<U> InstanceHolder<U> flatMap(Function<? super T, InstanceHolder<U>> mapper) { return this.isPresent() ? Optional.ofNullable(mapper.apply(this.value)).orElseGet(InstanceHolder::empty) : empty(); } // ********** NULL MANAGER public InstanceHolder<T> setNonnull() { return this.filter( (x)-> x != null); } public<X extends T> InstanceHolder<T> setNonnull(X other) { return !this.isNull() ? this : of(other); } public<X extends T> InstanceHolder<T> setPresent(X other) { return this.isPresent() ? this : ofNullable(other); } public<X extends T> InstanceHolder<T> setNonnull(Supplier<X> other) { return !this.isNull() ? this : of(other.get()); } public<X extends T> InstanceHolder<T> setPresent(Supplier<X> other) { return this.isPresent() ? this : of(other.get()); } // ********** GETTER public T get() { if (!this.isPresent()) throw new NoSuchElementException("No value present"); return this.value; } public T orElse(T other) { return this.isPresent() ? this.value : other; } public T orElseGet(Supplier<? extends T> other) { return this.isPresent() ? this.value : other.get(); } public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X { if (!this.isPresent()) throw exceptionSupplier.get(); return this.value; } public <X extends Throwable> T orElseThrow(X exception) throws X { if (!this.isPresent()) throw exception; return this.value; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof InstanceHolder)) return false; return Objects.equals(this.value, ((InstanceHolder<?>) obj).value); } @Override public int hashCode() { return Objects.hashCode(value); } @Override public String toString() { return this.isPresent() ? String.format("InstanceHolder[%s]", this.value) : "InstanceHolder.empty"; } }
package com.lenovohit.hcp.pharmacy.manager; import java.util.List; import com.lenovohit.hcp.base.model.HcpUser; import com.lenovohit.hcp.pharmacy.model.PhaCheckInfo; /** * * 类描述: 盘点结存更新库存表和库存汇总表 *@author GW *@date 2017年5月28日 * */ public interface PhaCheckInfoManager { /** * 功能描述: *@param matBuyBill *@param hcpUser *@author GW *@date 2017年5月28日 */ void updateStockInfo(List<PhaCheckInfo> checkList, HcpUser hcpUser); }
package com.programapprentice.app; /** * User: program-apprentice * Date: 10/4/15 * Time: 9:58 PM */ public class HouseRobberII_213 { public int rob(int[] nums) { if (nums == null || nums.length == 0) { return 0; } if(nums.length == 1) { return nums[0]; } if(nums.length == 2) { return Math.max(nums[0], nums[1]); } int n = nums.length; int[] rec = new int[n]; rec[0] = nums[0]; for(int i = 1; i < n; i++) { if(i == 1) { rec[i] = Math.max(rec[0], nums[i]); } else if(i == n-1) { rec[i] = rec[i-1]; } else { rec[i] = Math.max(rec[i - 1], rec[i - 2] + nums[i]); } } int[] rec2 = new int[n]; rec2[0] = 0; rec2[1] = nums[1]; for(int i = 2; i < n; i++) { rec2[i] = Math.max(rec2[i - 1], rec2[i - 2] + nums[i]); } return Math.max(rec[n-1], rec2[n-1]); } }
import java.util.*; public class POJ3579 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); while (sc.hasNextInt()) { int n = sc.nextInt(); int[] num = new int[n]; int[] diffs = new int[n * (n-1) / 2]; for (int i = 0; i < n; ++i) num[i] = sc.nextInt(); int p = 0; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { diffs[p++] = Math.abs(num[i] - num[j]); } } Arrays.sort(diffs); System.out.println(diffs[(diffs.length-1) / 2]); } } }
/*** * Message * Date: 23/10/2020 * @author: B3-10 / ESSAYED Sana, MATOKA Lea ***/ package history; public class Message { protected String user; protected String message; /** * constructor Message * @param user * @param message * **/ public Message(String user, String message) { this.user = user; this.message = message; } /** * constructor Message * @param line depuis fichier persistant **/ public Message(String line) { String[] array = line.split("-#", 2); this.user = array[0]; this.message = array[1]; } // getter // attribute user public String getUser () { return user; } // getter // attribute message public String getMessageOnly () { return message; } /** * constructor getMessage * affichage d'un message côté client **/ public String getMessage () { int size = user.length(); size = 12 - size; String spaces = ""; for(int i = 0; i<size; i++) spaces += " "; return (" - "+user + spaces +" -> " + message); } /** * methode toString * pour écriture dans le fichier persistant **/ public String toString () { return (user+"-#"+message); } }
package com.proxiad.games.extranet.controller.websocket; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.handler.annotation.Header; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.web.bind.annotation.RestController; import com.proxiad.games.extranet.controller.ClientController; import com.proxiad.games.extranet.dto.TerminalCommandDto; import com.proxiad.games.extranet.dto.TokenDto; import com.proxiad.games.extranet.model.Room; import com.proxiad.games.extranet.repository.RoomRepository; import com.proxiad.games.extranet.service.AuthService; @RestController public class TerminalWSController { @Autowired private AuthService authService; @Autowired private ClientController wsUserController; @Autowired private RoomRepository roomRepository; @MessageMapping("/terminalCommand") @SendTo("/topic/riddle/terminalCommand") public TerminalCommandDto newTerminalCommand(@Header(value = "authorization") String authorizationToken, TerminalCommandDto terminalCommandDto) { Optional<TokenDto> validToken = authService.validateToken(authorizationToken); if (!validToken.isPresent()) { throw new RuntimeException("Invalid token : " + authorizationToken); } wsUserController.addCommandToUser(authorizationToken, terminalCommandDto); Optional<Room> optRoom = roomRepository.findByToken(authorizationToken); terminalCommandDto.setRoomId(optRoom.orElse(new Room()).getId()); terminalCommandDto.setToken(authorizationToken); return terminalCommandDto; } }
package com.teamkassvi.ascend; import android.app.Application; import com.microsoft.projectoxford.face.FaceServiceClient; import com.microsoft.projectoxford.face.FaceServiceRestClient; /** * Created by kartik1 on 17-04-2018. */ public class SampleApp extends Application { @Override public void onCreate() { super.onCreate(); sFaceServiceClient = new FaceServiceRestClient(getString(R.string.endpoint), getString(R.string.subscription_key)); } public static FaceServiceClient getFaceServiceClient() { return new FaceServiceRestClient("https://westcentralus.api.cognitive.microsoft.com/face/v1.0", "c467e48cfe3e418da2643039f68c4dcd"); } private static FaceServiceClient sFaceServiceClient; }
package com.example.configurations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component public class AppProperties { @Autowired private Environment environment; public String getProperty(String key){ return environment.getProperty(key); } }
package com.sizatn.sort; import java.util.Arrays; /** * * @desc 插入排序的算法描述是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。 * 一般来说,插入排序都采用in-place在数组上实现。具体算法描述如下: * 1.从第一个元素开始,该元素可以认为已经被排序; * 2.取出下一个元素,在已经排序的元素序列中从后向前扫描; * 3.如果该元素(已排序)大于新元素,将该元素移到下一位置; * 4.重复步骤3,直到找到已排序的元素小于或者等于新元素的位置; * 5.将新元素插入到该位置后; * 6.重复步骤2~5。 * @author sizatn * @date Jun 19, 2019 */ public class InsertSort { public static void insertSort(int[] arrs) { // 前一个值的索引 int preIndex = 0; // 保存第i个值 int current = 0; for (int i = 1; i < arrs.length; i++) { // 前一个值的索引 preIndex = i - 1; // 保存第i个值(当前值) current = arrs[i]; // 前一个值的索引大于等于0,且前一个值大于第i个值(当前值) while (preIndex >= 0 && arrs[preIndex] > current) { // 前一个值与后一个值互换 arrs[preIndex + 1] = arrs[preIndex]; preIndex--; } // 最后一个值等于第i个值(当前值) arrs[preIndex + 1] = current; } } public static void main(String[] args) { int[] arrs = {2, 1, 3, 2, -5, 0, 7, -1, 14, 20, 12}; insertSort(arrs); System.out.print(Arrays.toString(arrs)); } }
package com.tony.pandemic.builders; import com.tony.pandemic.hospital.Hospital; import java.text.ParseException; import java.time.LocalDateTime; public class HospitalBuilder { public static Hospital createHospital() throws ParseException { return Hospital.builder() .name("Hospital Samaritano") .address("Av. Santa Júlia") .cnpj("23425345") .percentageOfOccupation(60) .localization(null) .registrationTime(LocalDateTime.now()) .resource(null) .build(); } }
package com.sinodynamic.hkgta.dao.crm; import java.util.List; import org.springframework.stereotype.Repository; import com.sinodynamic.hkgta.dao.GenericDao; import com.sinodynamic.hkgta.entity.crm.HkArea; import com.sinodynamic.hkgta.entity.crm.HkDistrict; @SuppressWarnings("rawtypes") @Repository public class HKAreaDistrictDaoImpl extends GenericDao implements HKAreaDistrictDao { public List<HkArea> getHKArea(){ return getByHql(" from HkArea h order by h.areaCode, h.areaName "); } public List<HkDistrict> getHKDistrict(){ //update by vicky wang on 2015-10-29 to change the sort order. return getByHql(" from HkDistrict h order by h.district, h.hkArea.areaCode "); // return getByHql(" from HkDistrict h order by h.hkArea.areaCode, h.district "); } }
package leetCode; import java.util.Arrays; import java.util.List; /** * There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0 Example 2: nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5 * * @createTime 2018年4月19日 下午11:09:28 * @author MrWang */ class Solution { public static void main(String[] args) { int[] nums1 = { 1, 3 }; int[] nums2 = { 2, 4,7,8}; double mediumNum = findMedianSortedArrays(nums1, nums2); System.out.println(mediumNum); String str = "abc0j1*j3#"; str = str.replaceAll("1|\\*|0|#", ""); System.out.println(str); letterCombinations("268"); } public static double findMedianSortedArrays(int[] nums1, int[] nums2) { if(nums1.length == 0 && nums2.length != 0){ if(nums2.length % 2 == 0){ return (1.0 * nums2[nums2.length /2 - 1] + nums2[nums2.length /2]) / 2; } else { return nums2[nums2.length /2]; } } else if(nums1.length != 0 && nums2.length == 0){ if(nums1.length % 2 == 0){ return (1.0 * nums1[nums1.length /2 - 1] + nums1[nums1.length /2]) / 2; } else { return nums1[nums1.length /2]; } } else if (nums1.length == 0 && nums2.length == 0){ return -1; } int totalLength = nums1.length + nums2.length; int index = 0; int index1 = 0; int index2 = 0; if (totalLength % 2 == 0) { int mediumNum1 = nums1[0]; int mediumNum2 = nums2[0]; int mediumIndex = totalLength / 2; while (index <= mediumIndex - 1) { if (index1 < nums1.length && index2 < nums2.length) { if (nums1[index1] < nums2[index2]) { mediumNum1 = nums1[index1]; index1++; } else { mediumNum1 = nums2[index2]; index2++; } } else if (index1 < nums1.length) { mediumNum1 = nums1[index1]; index1++; } else { mediumNum1 = nums2[index2]; index2++; } index++; } if(index1 < nums1.length && index2 < nums2.length){ mediumNum2 = nums1[index1] < nums2[index2] ? nums1[index1] : nums2[index2]; } else if (index1 < nums1.length) { mediumNum2 = nums1[index1]; } else { mediumNum2 = nums2[index2]; } return (mediumNum1 * 1.0 + mediumNum2) / 2; } else { int flag = nums1[0] < nums2[0] ? 1 : 2; int mediumNum1 = nums1[0]; int mediumIndex = totalLength / 2; while (index <= mediumIndex) { if (index1 < nums1.length && index2 < nums2.length) { if (nums1[index1] < nums2[index2]) { flag = 1; mediumNum1 = nums1[index1]; index1++; } else { flag = 2; mediumNum1 = nums2[index2]; index2++; } } else if (index1 < nums1.length) { flag = 1; mediumNum1 = nums1[index1]; index1++; } else { flag = 2; mediumNum1 = nums2[index2]; index2++; } index++; } return mediumNum1; } } public static List<String> letterCombinations(String digits) { String[] digitMap = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; digits.replaceAll("1|\\*|0|#", ""); char[] charArray = digits.toCharArray(); char[][] tempStr = new char[charArray.length][]; int resultLength = 1; for(int i = 0; i < charArray.length; i++){ tempStr[i] = digitMap[charArray[i] - 2 - 48].toCharArray(); resultLength *= tempStr[i].length; } for (char[] cs : tempStr) { System.out.println(Arrays.toString(cs)); } String[] resultTemp = new String[resultLength]; return null; } }
package za.ac.cput.views.person.lecturer; /** * GetAllLecturer.java * Author: Shane Knoll (218279124) * Date: 20 October 2021 */ import com.google.gson.Gson; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import org.json.JSONArray; import org.json.JSONObject; import za.ac.cput.entity.person.Lecturer; import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; public class GetAllLecturer extends JFrame implements ActionListener { private static OkHttpClient client = new OkHttpClient(); private JTable lecturerTable; private JLabel lblHeading; private JPanel panelCenter; private JPanel panelSouth; private JPanel panelNorth; private JButton btnExit; public GetAllLecturer() { super("Display all lecturers"); lecturerTable = new JTable(); lblHeading= new JLabel("GET ALL LECTURER TABLE"); panelNorth = new JPanel(); panelSouth = new JPanel(); panelCenter = new JPanel(); btnExit= new JButton("Exit"); } public void setGUI() { panelNorth.setLayout(new FlowLayout()); panelCenter.setLayout(new GridLayout(1,1)); panelSouth.setLayout(new GridLayout(1,1)); panelNorth.add(lblHeading); panelCenter.add(lecturerTable); panelSouth.add(btnExit); this.add(panelNorth,BorderLayout.NORTH); this.add(panelCenter, BorderLayout.CENTER); this.add(panelSouth, BorderLayout.SOUTH); lblHeading.setForeground(Color.RED); panelNorth.setBackground(Color.green); btnExit.addActionListener(this); getAll(); lecturerTable.setRowHeight(40); this.add(new JScrollPane(lecturerTable)); this.pack(); this.setSize(1200, 500); this.setLocationRelativeTo(null); this.setVisible(true); } public void getAll() { DefaultTableModel model = (DefaultTableModel) lecturerTable.getModel(); model.addColumn("Lecturer ID"); model.addColumn("Lecturer's First Name"); model.addColumn("Lecturer's Last Name"); model.addColumn("Lecturer's Age"); model.addColumn("Lecturer's Email Address"); model.addColumn("Lecturer's Phone Number"); try { final String URL = "http://localhost:8080/lecturer/getall"; String responseBody = run(URL); JSONArray lecturer= new JSONArray(responseBody); for (int i = 0; i < lecturer.length(); i++) { JSONObject lect = lecturer.getJSONObject(i); Gson g = new Gson(); Lecturer le = g.fromJson(lect.toString(), Lecturer.class); Object[] rowData = new Object[6]; rowData[0] = le.getLecturerID(); rowData[1] = le.getFirstName(); rowData[2] = le.getLastName(); rowData[3] = le.getAge(); rowData[4] = le.getEmailAddress(); rowData[5] = le.getContactNo(); model.addRow(rowData); } } catch (Exception e) { System.out.println(e.getMessage()); } } private static String run(String url) throws IOException { Request request = new Request.Builder().url(url).build(); try (Response response = client.newCall(request).execute()) { return response.body().string(); } } @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==btnExit){ this.dispose(); new LecturerMenuGUI().setGUI(); } } public static void main(String[] args) { new GetAllLecturer().setGUI(); } }
package com.appspot.smartshop.utils; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import android.app.Activity; import android.app.NotificationManager; import android.graphics.drawable.Drawable; import android.hardware.SensorManager; import com.appspot.smartshop.dom.ProductInfo; import com.appspot.smartshop.dom.SmartshopNotification; import com.appspot.smartshop.dom.UserInfo; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class Global { public static final int SPLASH_SCREEN_TIMEOUT = 2000; /* * Update interval */ public static int UPDATE_INTERVAL = 30000; /* * User */ public static boolean isLogin = false; public static UserInfo userInfo = null; // public static long lastupdateNoti = 0; public static String getSession(){ return userInfo.sessionId; } public static volatile boolean isWaitingForNotifications = false; /* * Misc */ public static final int SUCCESS = 0; public static final int ERROR = 1; //Constant public static final String NORMAL_DATE = "dd/MM/yyyy"; public static final String NORMAL_DATE_WITH_HOUR = "dd/MM/yyyy hh:mm:ss"; public static final Gson gsonDateWithoutHour = new GsonBuilder() .setDateFormat(NORMAL_DATE).excludeFieldsWithExcludeAnnotation() .create(); public static final Gson gsonWithHour = new GsonBuilder().setDateFormat( NORMAL_DATE_WITH_HOUR).excludeFieldsWithExcludeAnnotation() .create(); public static Activity application = null; // point to HomeActivity public static DateFormat df = new SimpleDateFormat(NORMAL_DATE); public static DateFormat dfFull = new SimpleDateFormat( NORMAL_DATE_WITH_HOUR); public static DateFormat dfTimeStamp = new SimpleDateFormat( "yyyyMMddHHmmssSS"); public static Drawable drawableNoAvatar; public static NotificationManager notificationManager; public static List<SmartshopNotification> notifications = new LinkedList<SmartshopNotification>(); // (key_cat, name) of categories public static HashMap<String, String> mapParentCategories = new HashMap<String, String>(); public static HashMap<String, String> mapChildrenCategories = new HashMap<String, String>(); // (name, key_cat) of categories public static HashMap<String, String> mapChildrenCategoriesName = new HashMap<String, String>(); // (key_cat, child categories) public static LinkedList<String[]> listCategories = new LinkedList<String[]>(); //List subscribed product of user public static List<ProductInfo> listSubscribeProduct = new ArrayList<ProductInfo>(); public static SensorManager mSensorManager; /* * Intent key */ public static final String USER_INFO = "user_info"; public static final String CAN_EDIT_USER_INFO = "can_edit_user_profile"; public static final String PRODUCTS_OF_USER = "products_of_user"; public static final String PRODUCT_INFO = "product_info"; public static final String NOTIFICATION = "notification"; public static final String CAN_EDIT_PRODUCT_INFO = "can_edit_product_info"; public static final String PAGE = "page"; public static final String PAGES_TYPE = "pages_type"; public static final String PAGES_OF_USER = "pages_of_user"; public static final String PRODUCTS_TYPE = "products_ype"; public static final String USER_NAME = "user_name"; public static final String TYPE = "type"; public static final String LAT_OF_USER = "lat"; public static final String LONG_OF_USER = "lng"; public static final String ID_OF_COMMENTS = "id_of_comments"; public static final String TYPE_OF_COMMENTS = "type_of_comments"; public static final String CATEGORY_INFO = "category_info"; public static final String SELECTED_CATEGORIES = "selected_categories"; public static final String FILE_INTENT_ID = "file"; public static final String BYTE_ARRAY_INTENT_ID = "byte_array"; public static final String FILTER_FILE = "filter"; public static final String[] IMAGE_FILTER_EXTENSION = new String[] { "jpg", "jpeg", "jpg", "gif", "png" }; public static final String VATGIA_URL_LIST_SHOP = "vatgia_url_list_shop"; public static final String LOGIN_LAST_ACTIVITY = "last"; public static final String SUBCRIBE_ID = "subcribe_id"; public static final String SUBCRIBE_INFO = "subcribe_info"; public static final String PRODUCT_1 = "product_1"; public static final String PRODUCT_2 = "product_2"; public static final String PRODUCTS = "products"; public static final String IS_NORMAL_PAGE = "normal_page"; public static final String SENDER = "sender"; public static final String RECEIVER = "receiver"; public static final String NOTIFICATION_ID = "notification_id"; public static final String RELATED_PRODUCT_ID = "related_product_id"; /* * ACTIVITY ACTION NAME */ public static final String USER_ACTIVITY = "User"; public static final String LOGIN_ACTIVITY = "Login"; public static final String TEST_ACTIVITY = "Test"; public static final String POST_PRODUCT_ACTIVITY = "PostProduct"; public static final String POST_PRODUCT_ACTIVITY_BASIC_ATTRIBUTE = "PostProductBasicAttribute"; public static final String POST_PRODUCT_ACTIVITY_USER_DEFINE = "PostProductUserDefine"; public static final String SEARCH_PRODUCT_ACTIVITY = "SearchProduct"; public static final String SEARCH_BY_ACTIVITY = "SearchByCategory"; public static final String PAGE_ACTIVITY = "Page"; public static final String VIEW_PAGE_ACTIVITY = "ViewPage"; public static final String VIEW_COMMENTS_ACTIVITY = "ViewComments"; public static final String PRODUCTS_LIST_ACTIVITY = "ProductsList"; public static final String VIEW_SINGLE_ACTIVITY = "ViewSingle"; public static final String VIEW_BASIC_ATTRIBUTE_OF_PRODUCT = "ViewBasicAttributeOfProduct"; public static final String VIEW_ADVANCE_ATTRIBUTE_OF_PRODUCT = "ViewAdvanceAttributeOfProduct"; public static final String PAGES_LIST_ACTIVITY = "PagesList"; public static final String USER_PROFILE_ACTIVITY = "UserProfile"; public static final String USER_PRODUCT_LIST_ACTIVITY = "UserProductList"; public static final String IMAGE_FROM_URL_EXAMPLE = "ImageFromUrlExample"; public static final String SEARCH_PRODUCTS_ON_MAP_ACTIVITY = "SearchProductsOnMap"; public static final String MAIN_ACTIVITY = "Main"; public static final String DIRECTION_LIST_ACTIVITY = "DirectionList"; public static final String UPLOAD_ACTIVITY = "Upload"; public static final String FILE_BROWSER_ACTIVITY = "FileBrowser"; public static final String IMAGE_CAPURE_ACTIVITY = "ImageCapture"; public static final String VIEW_PROFILE_ACTIVITY = "ViewProfile"; public static final String TITLE_NOTIFICATION = "TitleNotification"; public static final String CONTENT_NOTIFICATION = "ContentNotification"; //public static FacebookUtils facebookUtils; }
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.appcloud.tierapi.server; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * Service class defines operations related to Plan related services. */ public interface PlanService { /** * Get all Plans. * * @return {@link Response} */ @GET @Produces({MediaType.APPLICATION_JSON}) public Response getPlans(); /** * Get Plan using Plan ID. * * @param planId Plan ID of the plan * @return {@link Response} */ @GET @Path("/{planId}") @Produces({MediaType.APPLICATION_JSON}) public Response getPlan(@PathParam("planId") int planId); /** * Get Plan using Plan name and cloud * * @param cloudType cloud type * @param planName name of the plan * @return {@link Response} */ @GET @Path("/{cloudType}/{planName}") @Produces({MediaType.APPLICATION_JSON}) public Response getPlan(@PathParam("cloudType") String cloudType, @PathParam("planName") String planName); /** * Get allowed container specifications using Plan ID. * * @param planId Plan ID of the plan * @return {@link Response} */ @GET @Path("/allowedSpecs/{planId}") @Produces({MediaType.APPLICATION_JSON}) public Response getAllowedConSpecs(@PathParam("planId") int planId); }
/** * Commands for Map-Reduce in Riak. * <h4>Map-Reduce</h4> * <ul> * <li>{@link com.basho.riak.client.api.commands.mapreduce.BucketMapReduce}</li> * <li>{@link com.basho.riak.client.api.commands.mapreduce.BucketKeyMapReduce}</li> * <li>{@link com.basho.riak.client.api.commands.mapreduce.IndexMapReduce}</li> * <li>{@link com.basho.riak.client.api.commands.mapreduce.SearchMapReduce}</li> * </ul> */ package com.basho.riak.client.api.commands.mapreduce;
package com.lidaye.shopIndex.domain.vo; import com.lidaye.shopIndex.domain.entity.SubMenu1; import lombok.Data; import java.io.Serializable; import java.util.List; @Data public class SubMenu1Vo extends SubMenu1 { private List<SubMenu2Vo> subMenu2Vos; }
package com.swm.wechat.core; import java.io.IOException; import java.util.Date; import net.sf.json.JSONObject; import com.swm.common.util.HttpTookit; public class WeChatAccessToken { private String access_token; private int expires_in; private Date time = new Date(); public boolean isExpires() { long secends = System.currentTimeMillis() - this.time.getTime(); return secends > this.expires_in * 1000 ? true : false; } // 类静态对象 private static WeChatAccessToken accessToken; // 单例模式实现 public static String getAccessToken() throws Exception { if (accessToken == null) { try { getWeChatAccessToken(); } catch (IOException e) { e.printStackTrace(); } } else if (accessToken.isExpires()) { try { getWeChatAccessToken(); } catch (IOException e) { e.printStackTrace(); } } return accessToken.getAccess_token(); } @Override public String toString() { return "WeChatAccessToken [access_token=" + access_token + ", expires_in=" + expires_in + ", time=" + time + ", isExpires()=" + isExpires() + "]"; } private static void getWeChatAccessToken() throws Exception { String grant_type = "client_credential";//获取access_token填写client_credential String AppId="wxb5322c4f25f4f776";//第三方用户唯一凭证 String secret="092c45adbb445a20492d18833a8f7b13";//第三方用户唯一凭证密钥,即appsecret //这个url链接地址和参数皆不能变 String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type="+grant_type+"&appid="+AppId+"&secret="+secret; JSONObject result = JSONObject.fromObject(HttpTookit.doGet(url, null, "utf-8", true)); if(result.containsKey("access_token")){ accessToken = new WeChatAccessToken(); accessToken.setAccess_token(result.getString("access_token")); accessToken.setExpires_in(result.getInt("expires_in")); } else { throw new Exception(result.get("access_token missing").toString()); } } public String getAccess_token() { return access_token; } public void setAccess_token(String access_token) { this.access_token = access_token; } public int getExpires_in() { return expires_in; } public void setExpires_in(int expires_in) { this.expires_in = expires_in; } public static void main(String[] args) { try { WeChatAccessToken.getAccessToken(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
/** * This method finds the closest element to a target in binary search tree * Reference: https://algorithmsandme.com/find-closest-element-in-binary-search-tree/ * */ class Node { Node left; Node right; int data; Node(int data) { left = null; right = null; this.data = data; } } public class FindClosestElementBinaryTree { // function to print inorder traversal public static void inOrder(Node node) { if(node == null) { return; } inOrder(node.left); System.out.println(node.data); inOrder(node.right); } // function to find closest element to a target value public static int findClosestElem(Node root, int target) { if(root == null) { return -1; } int currentVal = root.data; if(currentVal - target == 0) { return currentVal; } // if currentval is greate than target, then search on the left side as all right side values of currentval // will be greater than currentval if(currentVal > target) { if(root.left == null) return currentVal; // find closest on left side int closest = findClosestElem(root.left, target); if(Math.abs(closest - target) > Math.abs(currentVal - target)) { return currentVal; } return closest; } // if currentval is less than target, then search on the right side as all left side values of currentval // will be less than currentval else { if(root.right == null) { return currentVal; } // find closest on the right side int closest = findClosestElem(root.right, target); if(Math.abs(closest - target) > Math.abs(currentVal - target)) { return currentVal; } return closest; } } // main method public static void main(String args[]) { Node root = new Node(10); root.left = new Node(5); root.right = new Node(15); root.right.right = new Node(17); root.right.left = new Node(12); root.left.left = new Node(2); root.left.right = new Node(7); root.left.left.left = new Node(1); root.left.left.right = new Node(9); // inOrder(root); int val = findClosestElem(root, 4); System.out.println(val); } }
package com.hwj.service; import java.util.List; import com.hwj.entity.MindNode; public interface IMindNodeService extends IBaseService<MindNode> { List<MindNode> selectMindNode(Object value1, Integer currentPage, Integer pageSize); Long searchMindPage(Object value1); }
package vues; import controleur.Controleur; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.GridPane; import modele.Joueur; import java.io.IOException; import java.net.URL; import java.rmi.RemoteException; import java.util.ArrayList; /** * Created by reda on 14/01/2017. */ public class AttenteCompoVue { public GridPane getRacine() { return racine; } @FXML private GridPane racine ; @FXML private Label joueurCreateur; @FXML private Label joueurAdverse; @FXML private GridPane grilleInvitations; public GridPane getGrilleInvitations() { return grilleInvitations; } public void setGrilleInvitations(GridPane grilleInvitations) { this.grilleInvitations = grilleInvitations; } private Controleur monControleur; private Scene maScene; public void setMaScene(Scene maScene) { this.maScene = maScene; } public Scene getMaScene(){ return this.maScene; } public Label getJoueurCreateur() { return joueurCreateur; } public void setJoueurCreateur(Label joueurCreateur) { this.joueurCreateur = joueurCreateur; } public Label getJoueurAdverse() { return joueurAdverse; } public void setJoueurAdverse(Label joueurAdverse) { this.joueurAdverse = joueurAdverse; } public static AttenteCompoVue creerInstance(Controleur c) { URL location = AttenteCompoVue.class.getResource("/vues/AttenteCompoVue.fxml"); FXMLLoader fxmlLoader = new FXMLLoader(location); Parent root = null; try{ root = (Parent)fxmlLoader.load(); } catch(IOException e) { e.printStackTrace(); } AttenteCompoVue vue = fxmlLoader.getController(); vue.setMoncontroleur(c); vue.initialisation(); return vue; } public void initialisation() { int j = 1; try { for (Joueur joueurAInviter : monControleur.getGestionStrategoInterface().getLesJoueursConnectesSansPartie(monControleur.getJoueur())) { Label joueur = new Label(joueurAInviter.getPseudo()); // Liste des nodes pour cette ligne ArrayList<Node> toErase = new ArrayList<Node>(); toErase.add(joueur); j++; } } catch (RemoteException e) { e.printStackTrace(); } } public void update() { System.out.println("~~~~" + joueurCreateur + "~~~~"); } public void setMoncontroleur(Controleur moncontroleur){ this.monControleur = moncontroleur; } public Controleur getMonControleur(){ return monControleur; } }
package com.example.tushar.capture; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.provider.MediaStore; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; public class ShowImageActivity extends AppCompatActivity { Bitmap btImage = null; ProgressBar progressBar; TextView txtPercentage; Boolean check = true; int totalSize = 0; String filePath; final static String IP = "192.168.0.8"; String ServerUploadPath = "http://" + IP + "/FaceRec/SearchStore.php"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_image); ImageView image = (ImageView) findViewById(R.id.image); Button getInfo = (Button) findViewById(R.id.getInfo); Button cancel = (Button) findViewById(R.id.cancel); txtPercentage = (TextView) findViewById(R.id.txtPercentage); progressBar = (ProgressBar) findViewById(R.id.progressBar); Intent intent = getIntent(); Uri uri = Uri.parse(intent.getStringExtra("imageUri")); filePath = uri.getPath(); Log.d("ShowImageActivity", uri.toString()); Log.d("ShowImageActivity", uri.getPath()); if(uri != null) { try { btImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri); image.setImageBitmap(btImage); } catch (IOException e) { e.printStackTrace(); } } getInfo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "image will be sent to server and response will be shown in another activity", Toast.LENGTH_LONG).show(); //uploadMultipart(); new UploadFileToServer().execute(); } }); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK)); dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK)); } }); } /** * Uploading the file to server * */ private class UploadFileToServer extends AsyncTask<Void, Integer, String> { @Override protected void onPreExecute() { // setting progress bar to zero progressBar.setProgress(0); super.onPreExecute(); } @Override protected void onProgressUpdate(Integer... progress) { // Making progress bar visible progressBar.setVisibility(View.VISIBLE); // updating progress bar value progressBar.setProgress(progress[0]); // updating percentage value txtPercentage.setText(String.valueOf(progress[0]) + "%"); } @Override protected String doInBackground(Void... params) { return uploadFile(); } @SuppressWarnings("deprecation") private String uploadFile() { String responseString = null; HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(ServerUploadPath); try { AndroidMultiPartEntity entity = new AndroidMultiPartEntity( new AndroidMultiPartEntity.ProgressListener() { @Override public void transferred(long num) { publishProgress((int) ((num / (float) totalSize) * 100)); } }); File sourceFile = new File(filePath); // Adding file data to http body entity.addPart("image", new FileBody(sourceFile)); // Extra parameters if you want to pass to server //entity.addPart("email", new StringBody("abc@gmail.com")); totalSize = (int)entity.getContentLength(); httppost.setEntity(entity); // Making server call HttpResponse response = httpclient.execute(httppost); HttpEntity r_entity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { // Server response responseString = EntityUtils.toString(r_entity); } else { responseString = "Error occurred! Http Status Code: " + statusCode; } } catch (ClientProtocolException e) { responseString = e.toString(); } catch (IOException e) { responseString = e.toString(); } return responseString; } @Override protected void onPostExecute(String result) { Log.e("response", "Response from server: " + result); //super.onPostExecute(result); // showing the server response in an alert dialog //showAlert(result); super.onPostExecute(result); //* try { JSONObject obj = new JSONObject(result); if(obj.getBoolean("isuser")) { Intent intent = new Intent(getApplicationContext(), ResultActivity.class); intent.putExtra("response", result); finish(); startActivity(intent); } else { showAlert("No entry found"); } } catch (JSONException e) { e.printStackTrace(); } //*/ //Intent intent = new Intent(getApplicationContext(), ResultActivity.class); //intent.putExtra("response", result); //finish(); //startActivity(intent); } } /** * Method to show alert dialog * */ private void showAlert(String message) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(message).setTitle("Response from Servers") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // do nothing } }); AlertDialog alert = builder.create(); alert.show(); } }
package com.wkrzywiec.spring.library.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.Indexed; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @EqualsAndHashCode @ToString() @NoArgsConstructor @Entity @Table(name="isbn") @Indexed public class Isbn { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private int id; @Column(name="isbn_10", unique=true) @Field private String isbn10; @Column(name="isbn_13", unique=true) @Field private String isbn13; }
package com.meetingapp.android.fragments.home; import android.content.Context; import android.net.Uri; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.meetingapp.android.R; import com.meetingapp.android.util.CircleTransform; import com.meetingapp.android.util.TextUtils; import com.meetingapp.android.util.Utils; import com.meetingapp.android.model.Contact; import com.meetingapp.android.model.MeetingModels; import com.squareup.picasso.Picasso; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import butterknife.BindView; import butterknife.ButterKnife; import static com.meetingapp.android.MeetingApp.getApp; import static com.meetingapp.android.constants.Constants.DATE_FORMAT; /** * Created on 23.11.2017. */ public class MeetingsAdapter extends RecyclerView.Adapter<MeetingsAdapter.MeetingVH> { private List<MeetingModels> mMeetingModels; private OnMeetingClickListener mOnMeetingClickListener; private String currentUserPhone; private String currentUserName; private Context context; private HashMap<String, Contact> mListContactsPhone; public MeetingsAdapter(Context context, List<MeetingModels> meetingModels, String currentUSerPhone, String currentUserName, HashMap<String, Contact> mListContactsPhone) { this.context = context; this.mMeetingModels = meetingModels; this.currentUserPhone = currentUSerPhone; this.currentUserName = currentUserName; this.mListContactsPhone = mListContactsPhone; } public void setOnMeetingClickListener(OnMeetingClickListener onMeetingClickListener) { this.mOnMeetingClickListener = onMeetingClickListener; } @Override public MeetingVH onCreateViewHolder(ViewGroup parent, int viewType) { return new MeetingVH(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_meeting, parent, false)); } @Override public void onBindViewHolder(MeetingVH holder, int position) { holder.bind(mMeetingModels.get(position)); } @Override public int getItemCount() { return mMeetingModels == null ? 0 : mMeetingModels.size(); } class MeetingVH extends RecyclerView.ViewHolder { @BindView(R.id.meeting_name_tv) TextView meetingNameTv; @BindView(R.id.view) View viewDivider; @BindView(R.id.tv_info) TextView tv_info; @BindView(R.id.meeting_iv) ImageView meeting_iv; public MeetingVH(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } public void bind(final MeetingModels item) { SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH); SimpleDateFormat timeDateFormate = new SimpleDateFormat("HH:mm a"); meetingNameTv.setText(getCamelCaseTopic(item.getTopic())); Date startDate, endDate; String startTime = "", endTime = ""; try { startDate = dateFormat.parse(dateFormat.format(item.getDate())); endDate = dateFormat.parse(dateFormat.format(item.getDuration())); startTime = timeDateFormate.format(startDate.getTime()); endTime = timeDateFormate.format(endDate.getTime()); } catch (ParseException e) { e.printStackTrace(); } String participantsName = getParticipantsName(item); if (item.getParticipants().size() > 2) tv_info.setText(startTime + " - " + endTime + "- " + participantsName + " + " + (item.getParticipants().size() - 2)); else tv_info.setText(startTime + " - " + endTime + "- " + participantsName); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mOnMeetingClickListener != null) { mOnMeetingClickListener.onMeetingClick(item); } } }); viewDivider.setBackgroundColor(itemView.getResources().getColor(Utils.getMeetingColor(item))); if (participantsName.contains("You,")) { if (mListContactsPhone.containsKey(item.getAuthor())) { Uri path = mListContactsPhone.get(item.getAuthor()).getPhoto(); Picasso.get().load(path).error(R.drawable.meeting_creator_other).placeholder(R.drawable.meeting_creator_other).transform(new CircleTransform()).into(meeting_iv); } else { Picasso.get().load(R.drawable.meeting_creator_other).placeholder(R.drawable.meeting_creator_other).transform(new CircleTransform()).into(meeting_iv); } } else { String path = getApp().getAppPreference().getAvatar(); if (!TextUtils.isEmpty(path)) { Picasso.get().load(path).error(R.drawable.meeting_creator).placeholder(R.drawable.meeting_creator).transform(new CircleTransform()).into(meeting_iv); } else { meeting_iv.setImageResource(R.drawable.meeting_creator); } } } } private String getCamelCaseTopic(String topic) { return topic.substring(0, 1).toUpperCase() + topic.substring(1).toLowerCase(); } public interface OnMeetingClickListener { void onMeetingClick(MeetingModels meeting); } private String getParticipantsName(MeetingModels item) { String participantsName = ""; /*Meeting created by other users*/ for (int i = 0; i < item.getParticipants().size(); i++) { if (item.getParticipants().get(i).getPhone().equals(currentUserPhone)) { if (!item.getAuthor().equalsIgnoreCase(currentUserPhone)) participantsName = "You, "; break; } } /*Meeting created by user*/ for (int i = 0; i < item.getParticipants().size(); i++) { if (!item.getParticipants().get(i).getPhone().equals(currentUserPhone)) { participantsName = participantsName + item.getParticipants().get(i).getName(); break; } } return participantsName; } }
package practice.leetcode.algorithm; /** * 11. Container With Most Water * https://leetcode.com/problems/container-with-most-water/description/ */ public class ContainerWithMostWater { /** * * @param height the height * @return the int */ public int maxArea(int[] height) { int l = 0; int r = height.length - 1; int maxArea = 0; while (l < r) { maxArea = Math.max(maxArea, Math.min(height[l], height[r]) * (r - l)); if (height[l] < height[r]) { // 去短板 l++; } else { r--; } } return maxArea; } }
package com.example.rentacar.entitity; import java.util.Date; import java.util.Set; import java.util.TreeSet; import javax.persistence.*; import lombok.AllArgsConstructor; import lombok.Data; import org.hibernate.annotations.GenericGenerator; @Data @AllArgsConstructor @Entity @Table(name = "RATE_PRICE") public class RatePriceEntity { public RatePriceEntity(){} @Id @GeneratedValue(generator="increment") @GenericGenerator(name="incrementRate", strategy = "increment") private Integer id; private Integer price; private String startDate; private String endDate; private Integer activeRate; @ManyToMany(fetch = FetchType.LAZY) private Set<CarEntity> cars = new TreeSet<>(); }
package com.corejava.scjp; public class ICICIBank extends Rbi2Bank{ /** * @param args */ public static void main(String[] args) { ICICIBank icb = new ICICIBank(); icb.MiniStatement(); icb.PinChange(); } public void MiniStatement() { System.out.println("This is ICICI Bank MiniStatement Service..!"); } public void PinChange() { System.out.println("This is ICICI Bank PinChange Service..!"); } }
package com.javarush.test.level10.lesson03.task04; public class Solution { double d = 1; float f = (float) d; long l = (long) f; int i = (int) l; short s = (short) i; byte b = (byte) s; }
package com.legaoyi.protocol.up.messagebody; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.fasterxml.jackson.annotation.JsonProperty; import com.legaoyi.protocol.message.MessageBody; /** * 提问应答 * * @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a> * @version 1.0.0 * @since 2015-01-30 */ @Scope("prototype") @Component(MessageBody.MESSAGE_BODY_BEAN_PREFIX + "0302_2011" + MessageBody.MESSAGE_BODY_BEAN_SUFFIX) public class JTT808_0302_MessageBody extends MessageBody { private static final long serialVersionUID = 1580559134005988215L; public static final String MESSAGE_ID = "0302"; /** 应答流水号 **/ @JsonProperty("messageSeq") private int messageSeq; /** 答案id **/ @JsonProperty("answerId") private int answerId; public final int getMessageSeq() { return messageSeq; } public final void setMessageSeq(int messageSeq) { this.messageSeq = messageSeq; } public final int getAnswerId() { return answerId; } public final void setAnswerId(int answerId) { this.answerId = answerId; } }
package Model.impl; import Bean.Memory; import Bean.Message; import Configure.RouterAndHostConfigure; import Model.IRouteInterface; import com.sun.istack.internal.NotNull; /** * @author dmrfcoder * @date 2019-04-15 */ public class RouterInterface implements IRouteInterface { private Host host; private Memory memory; private int port; private UpdatePercentageListener updatePercentageListener; private UpdateInputMessageMomentListener updateInputMessageMomentListener; public Memory getMemory() { return memory; } public Host getHost() { return host; } public RouterInterface(Host host, int port, UpdateInputMessageMomentListener updateInputMessageMomentListener, int memorySize) { this.host = host; this.port = port; memory = new Memory(memorySize); this.updateInputMessageMomentListener = updateInputMessageMomentListener; } public RouterInterface(Host host, int port, UpdateInputMessageMomentListener updateInputMessageMomentListener) { this.host = host; this.port = port; memory = new Memory(RouterAndHostConfigure.routerInterfaceMemorySize); this.updateInputMessageMomentListener = updateInputMessageMomentListener; } public int getPort() { return port; } @Override public boolean inputMessage(Message message) { double percentage = memory.getMemoryPercentage(); if (updatePercentageListener != null) { updatePercentageListener.updatePercentage(host.getIp(), percentage, memory.getMemoryCurCount()); } if (memory.addContentToMemory(message)) { updateInputMessageMomentListener.inputMessageMoment(message, true); return true; } else { updateInputMessageMomentListener.inputMessageMoment(message, false); return false; } } @Override public boolean outputMessage(Message message) { double percentage = memory.getMemoryPercentage(); if (percentage > 1) { percentage = 1; } updatePercentageListener.updatePercentage(host.getIp(), percentage, memory.getMemoryCurCount()); return host.inputMessage(message); } @Override public void setUpdatePercentageListener(UpdatePercentageListener updatePercentageListener) { this.updatePercentageListener = updatePercentageListener; } }
package com.beike.dao.impl.user; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.springframework.jdbc.core.simple.ParameterizedRowMapper; import org.springframework.stereotype.Repository; import com.beike.dao.GenericDaoImpl; import com.beike.dao.user.UserAddressDao; import com.beike.entity.user.UserAddress; /** * project:beiker * Title: * Description: * Copyright:Copyright (c) 2011 * Company:Sinobo * @author qiaowb * @date Mar 16, 2012 10:25:04 AM * @version 1.0 */ @Repository("userAddressDao") public class UserAddressDaoImpl extends GenericDaoImpl<UserAddress, Long> implements UserAddressDao { @Override public Long addUserAddress(UserAddress address) { String sql = "insert into beiker_user_address (userid,province,city,area,address) values (?,?,?,?,?)"; int result = getSimpleJdbcTemplate().update(sql, address.getUserid(), address.getProvince(),address.getCity(), address.getArea(),address.getAddress()); if (result > 0) { return this.getLastInsertId(); } return 0L; } @Override public int updateUserAddress(UserAddress address) { String updSql = "update beiker_user_address set province=?,city=?,area=?,address=? where userid=?"; return getSimpleJdbcTemplate().update(updSql, address.getProvince(), address.getCity(), address.getArea(),address.getAddress(), address.getUserid()); } @Override public List<UserAddress> getUserAddressByUserId(Long userId) { String sql = "SELECT id,userid,province,city,area,address FROM beiker_user_address WHERE userid = ?"; return getSimpleJdbcTemplate().query(sql,new RowMapperImpl(), userId); } protected class RowMapperImpl implements ParameterizedRowMapper<UserAddress> { @Override public UserAddress mapRow(ResultSet rs, int rowNum) throws SQLException { UserAddress address = new UserAddress(); address.setId(rs.getLong("id")); address.setUserid(rs.getLong("userid")); address.setProvince(rs.getString("province")); address.setCity(rs.getString("city")); address.setArea(rs.getString("area")); address.setAddress(rs.getString("address")); return address; } } }
package com.sum.flowable.service; import org.flowable.engine.delegate.DelegateExecution; import org.flowable.engine.delegate.JavaDelegate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PublishArticleService implements JavaDelegate { private static final Logger log = LoggerFactory.getLogger(PublishArticleService.class); @Override public void execute(DelegateExecution arg0) { log.info("Publishing the approved article."); } }
package br.com.tt.petshop.repository; import br.com.tt.petshop.model.Cliente; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface RelatorioClienteRepository extends JpaRepository<Cliente, Integer> { @Query("select c.nome as nome, c.cpf as cpf, " + " count(a.id) as quantidade from Cliente c left join c.animais a" + " group by c.nome, c.cpf") List<ClienteRelatorioProjection> listarClientes(); @Query("from Cliente") //@Query("select c from Cliente c") List<ClienteSimplicadoProjection> listaSimplificada(); }
package com.stk123.util.baidu; import java.io.IOException; import java.net.URLEncoder; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.commons.httpclient.NoHttpResponseException; import org.apache.commons.lang.StringUtils; import org.htmlparser.Node; import com.stk123.util.ServiceUtils; import com.stk123.common.util.EmailUtils; import com.stk123.common.util.HtmlUtils; import com.stk123.util.HttpUtils; import com.stk123.common.CommonConstant; @SuppressWarnings("unchecked") public class BaiduSearch { public static boolean SearchSwitch = true; public static class SearchKeyword{ public String keyword; public boolean existing = false; String serchkeyword; boolean searchInTitle; int weight; public SearchKeyword(String keyword, String serchkeyword, boolean searchInTitle){ this(keyword, serchkeyword, searchInTitle, 1); } public SearchKeyword(String keyword, String serchkeyword, boolean searchInTitle, int weight){ this.keyword = keyword; this.serchkeyword = serchkeyword; this.searchInTitle = searchInTitle; this.weight = weight; } } public static void main(String[] args) throws Exception { //System.out.println(BaiduSearch.getKeywordsTotalWeight("中颖电子")); //System.out.println(BaiduSearch.getKeywordsTotalWeight("丹邦科技")); /*Date date = StkUtils.addDay(new Date(), -90); System.out.println(getBaiduNewsCount(date, "丹邦科技 新产品", false));*/ //(行业 | 收入 | 营收) 连续 (下降 | 下跌) List<String> results = getBaiduNews(ServiceUtils.addDay(new Date(), -10), "(行业 | 收入 | 营收) 连续 (下降 | 下跌)", true); System.out.println(results); EmailUtils.send("test", StringUtils.join(results, "")); } private static List<SearchKeyword> getKeywords() { List<SearchKeyword> BAIDU_NEWS_KEYWORDS = new ArrayList<SearchKeyword>(); BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("超预期/爆发", "{stk} 超预期 | {stk} 爆发", true, 2)); BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("高增长/高成长", "{stk} 高增长 | {stk} 高成长", true)); BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("提价", "{stk} 提价", true)); BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("强烈推荐/利好", "{stk} 强烈推荐 | {stk} 利好", true, 2)); BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("行业/产业", "{stk} 行业 | {stk} 产业", true)); BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("景气", "{stk} 景气", true)); //BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("竞争对手", "{stk} 竞争对手", false)); BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("上游/下游", "{stk} 上游 | {stk} 下游", true)); BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("龙头", "{stk} 龙头", true, 2)); BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("新产品/新业务", "{stk} 新产品 | {stk} 新业务", true, 2)); BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("产能释放/供不应求", "{stk} 产能释放 | {stk} 供不应求", true, 2)); //BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("转型", "{stk} 转型", true)); //BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("管理层", "{stk} 管理层", false)); BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("出货量/开工率", "{stk} 出货量 | {stk} 开工率", false, 2)); BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("订单/中标/合同", "{stk} 订单 | {stk} 中标 | {stk} 合同", true)); BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("市场占有率", "{stk} 市场占有率", false, 2)); //BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("核心技术", "{stk} 核心技术", true)); BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("重组/并购/收购", "{stk} 重组 | {stk} 并购 | {stk} 收购", true)); BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("股权激励", "{stk} 股权激励", true, 2)); BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("回购/增持", "{stk} 回购 | {stk} 增持", true, 2)); BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("增发", "{stk} 增发", true)); BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("非公开发行", "{stk} 非公开发行", true)); BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("举牌", "{stk} 举牌", true)); BAIDU_NEWS_KEYWORDS.add(new SearchKeyword("拐点", "{stk} 拐点", true, 2)); //垄断 return BAIDU_NEWS_KEYWORDS; } public static List<SearchKeyword> searchKeywords(final String stkName) throws Exception { List<SearchKeyword> BAIDU_NEWS_KEYWORDS = getKeywords(); if(!SearchSwitch){ return BAIDU_NEWS_KEYWORDS; } final Date date = ServiceUtils.addDay(new Date(), -90); final CountDownLatch countDownLatch = new CountDownLatch(BAIDU_NEWS_KEYWORDS.size()); ExecutorService exec = Executors.newFixedThreadPool(5); for(final SearchKeyword sk : BAIDU_NEWS_KEYWORDS){ Runnable run = new Runnable() { public void run() { try{ try { String s = StringUtils.replace(sk.serchkeyword, "{stk}", stkName); int n = BaiduSearch.getBaiduNewsCount(date , s, sk.searchInTitle); if(n == 2){ sk.existing = true; } } catch (Exception e) { if(e instanceof IOException || e instanceof NoHttpResponseException || e instanceof UnknownHostException){ try { Thread.currentThread().sleep(1000 * 300); } catch (InterruptedException e1) { } } e.printStackTrace(); } }finally{ countDownLatch.countDown(); } } }; exec.execute(run); } exec.shutdown(); countDownLatch.await(); return BAIDU_NEWS_KEYWORDS; } public static int getKeywordsTotalWeight(String stkName) throws Exception{ List<SearchKeyword> BAIDU_NEWS_KEYWORDS = BaiduSearch.searchKeywords(stkName); int total = 0; for(SearchKeyword sk : BAIDU_NEWS_KEYWORDS){ if(sk.existing){ total += sk.weight; } } return total; } public static String getBaiduNewsUrl(String searchWords, boolean inTitle){ return "http://news.baidu.com/ns?ct=0&rn=20&ie=utf-8&bs="+searchWords+"&rsv_bp=1&sr=0&cl=2&f=8&prevct=0&word="+searchWords+"&tn="+(inTitle?"newstitle":"news")+"&inputT=0"; } public static String getBaiduNewsSearch(String name, String id, String searchWord, String dispWord, boolean inTitle, int fontSize){ return "<a target=\"_blank\" name=\""+name+"\" id=\""+id+"\" keyword=\""+searchWord+"\" intitle=\""+inTitle+"\" href=\""+getBaiduNewsUrl(searchWord,inTitle)+"\" style=\"font-size: "+fontSize+"\">"+dispWord+"</a>"; } public static String getBaiduNewsSearch(String name, String id, String searchWord, String despWord, boolean inTitle){ return getBaiduNewsSearch(name, id, searchWord, despWord, inTitle, 12); } /** * @return 0:没有相关新闻; 1:有相关新闻; 2:date日之后有新闻 */ public static int getBaiduNewsCount(Date date,String searchword,boolean searchInTitle) throws Exception { String url = getBaiduNewsUrl(URLEncoder.encode(searchword, CommonConstant.ENCODING_UTF_8), searchInTitle); //System.out.println(url); String page = HttpUtils.get(url,CommonConstant.ENCODING_UTF_8); Node node = HtmlUtils.getNodeByAttribute(page, null, "id", "header_top_bar"); if(node == null){ return 0; } String div = node.toPlainTextString(); //System.out.println(searchword+"="+searchword+"="+StkUtils.getNumberFromString(div)); if(div.indexOf("找到相关新闻0篇") >= 0){ return 0; }else{ Node left = HtmlUtils.getNodeByAttribute(page, null, "id", "content_left"); //System.out.println(left.toHtml()); //List<Node> list = HtmlUtils.getNodeListByTagName(left, "li"); List<Node> list = HtmlUtils.getNodeListByTagNameAndAttribute(left, "div", "class", searchInTitle?"result title":"result"); for(Node li : list){ Node span = HtmlUtils.getNodeByAttribute(li.toHtml(), null, "class", searchInTitle?"c-title-author":"c-author"); if(span != null){ String text = span.toPlainTextString(); //System.out.println(text); String str = ServiceUtils.getMatchString(text, ServiceUtils.PATTERN_YYYYMMDD_HHMM_CHINESE); if(str == null && StringUtils.contains(str, "小时前")){ return 2; } if(str != null && str.length() > 0){ Date time = ServiceUtils.sf_ymd15.parse(str); if(date.after(time)){ return 2; } } } } return 1; } } public static List<String> getBaiduNews(Date date,String searchwordorUrl,boolean searchInTitle) throws Exception { String url = searchwordorUrl.startsWith("http")?searchwordorUrl:getBaiduNewsUrl(URLEncoder.encode(searchwordorUrl, CommonConstant.ENCODING_UTF_8), searchInTitle); //System.out.println(url); String page = HttpUtils.get(url,CommonConstant.ENCODING_UTF_8); Node node = HtmlUtils.getNodeByAttribute(page, null, "id", "header_top_bar"); List<String> results = new ArrayList<String>(); if(node == null){ return results; } String div = node.toPlainTextString(); //System.out.println(searchword+"="+searchword+"="+StkUtils.getNumberFromString(div)); if(div.indexOf("找到相关新闻0篇") >= 0){ return results; }else{ Node left = HtmlUtils.getNodeByAttribute(page, null, "id", "content_left"); //System.out.println(left.toHtml()); //List<Node> list = HtmlUtils.getNodeListByTagName(left, "li"); List<Node> list = HtmlUtils.getNodeListByTagNameAndAttribute(left, "div", "class", searchInTitle?"result title":"result"); for(Node li : list){ //System.out.println(li.toHtml()); Node span = HtmlUtils.getNodeByAttribute(li.toHtml(), null, "class", searchInTitle?"c-title-author":"c-author"); if(span != null){ String text = span.toPlainTextString(); if(StringUtils.contains(text, "前")){ results.add(li.toHtml()); }else{ String str = ServiceUtils.getMatchString(text, ServiceUtils.PATTERN_YYYYMMDD_HHMM_CHINESE); if(str != null && str.length() > 0){ Date time = ServiceUtils.sf_ymd15.parse(str); if(date.before(time)){ results.add(li.toHtml()); } } } //results.add(text); } } return results; } } private static boolean contain(List<String> list, String str){ for(String s : list){ if(StringUtils.contains(str, s)){ return true; } } return false; } }
package pe.edu.upc.profile.services; import pe.edu.upc.profile.entities.Administrator; import pe.edu.upc.profile.entities.PlanMember; import java.util.List; import java.util.Optional; public interface AdministratorService extends CrudService<Administrator, Long> { Optional<Administrator> auth(String email, String password) throws Exception; Optional<Integer> authToken(String token) throws Exception; Optional<List<PlanMember>> getPlanMemberByAdminId(Long id) throws Exception; Optional<PlanMember> getPlanMemberById(Long id) throws Exception; }
package boardPhysics; import java.util.ArrayList; import java.util.List; import physics.Circle; import physics.Geometry; import physics.Vect; public class CircularBumper implements Gadget, BoardObject { /** * List of gadgets whose triggers are connected to this gadget */ protected List<Gadget> triggers; /** * X coordinate of the upper left corner of this gadget */ protected final int xCoord; /** * Y coordinate of the upper left corner of this gadget */ protected final int yCoord; /** * The width of this gadget in units of L */ protected int width; /** * The height of this gadget in units of L */ protected int height; /** * The unique identifier of this wall */ protected final String id; /** * The reflection coefficient for this gadget */ protected final double reflecCoeff; /** * The circle representation for the bumper */ protected final Circle circleRep; public CircularBumper(String id, int x, int y){ this.xCoord = x; this.yCoord = y; this.width = 1; this.height = 1; this.id = id; this.reflecCoeff = 1.0; this.circleRep = new Circle(x+ 0.5, y + 0.5, 0.5); this.triggers = new ArrayList<Gadget>(); } @Override public boolean connect(Gadget g) { return triggers.add(g); } @Override public boolean disconnect(Gadget g) { return triggers.remove(g); } @Override public int getX() { return xCoord; } @Override public int getY() { return yCoord; } @Override public String getID() { return id; } @Override public int getWidth() { return 1; } @Override public int getHeight() { return 1; } @Override public double getReflec() { return reflecCoeff; } @Override public void action() { return; } @Override public void trigger() { action(); for (Gadget t : triggers){ t.trigger(); } } @Override public void progress(double timeStep) { return; } @Override public double[] impactCalc(Ball ball) { double timeUntilCollision = Geometry.timeUntilCircleCollision(circleRep, ball.toCircle(), ball.getVel()); Vect newVel = Geometry.reflectCircle(circleRep.getCenter(), ball.getPos(), ball.getVel(), reflecCoeff); return new double[]{timeUntilCollision, newVel.x(), newVel.y()}; } }
package com.chinese.culture.util; import android.content.Context; import android.speech.tts.TextToSpeech; public class TTSUtil { private TextToSpeech textToSpeech; }
package com.auro.scholr.home.presentation.viewmodel; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import com.auro.scholr.core.common.MessgeNotifyStatus; import com.auro.scholr.home.domain.usecase.HomeDbUseCase; import com.auro.scholr.home.domain.usecase.HomeRemoteUseCase; import com.auro.scholr.home.domain.usecase.HomeUseCase; import io.reactivex.disposables.CompositeDisposable; public class HomeViewDashBoardModel extends ViewModel { CompositeDisposable compositeDisposable = new CompositeDisposable(); HomeUseCase homeUseCase; HomeDbUseCase homeDbUseCase; HomeRemoteUseCase homeRemoteUseCase; private MutableLiveData<MessgeNotifyStatus> notifyLiveData = new MutableLiveData<>(); public HomeViewDashBoardModel(HomeUseCase homeUseCase, HomeDbUseCase homeDbUseCase, HomeRemoteUseCase homeRemoteUseCase) { this.homeUseCase = homeUseCase; this.homeDbUseCase = homeDbUseCase; this.homeRemoteUseCase = homeRemoteUseCase; } public MutableLiveData<MessgeNotifyStatus> getNotifyLiveData() { return notifyLiveData; } }
package com.tdd.romannumbers; public class RomanUnderTenConverter extends RomanConverter { @Override public int convert(int workingNumber, StringBuilder romanNumberBuilder) { romanNumberBuilder.append(conversionTable.get(workingNumber)); return workingNumber; } }
package com.example.myprog.java.examples.immutability; import java.util.ArrayList; import java.util.List; public class ImmutableObject { private final String name; private final List<Integer> numbers; public ImmutableObject(String name, List<Integer> numbers) { this.name = name; this.numbers = numbers; } public String getName() { return name; } // Exposing this would allow callers to modify the List! // public List<Integer> getNumbers() { // return numbers; // } // better to only expose what we need, for example: public Integer getNumber(int index) { return numbers.get(index); } public int getNumbersSize() { return numbers.size(); } } class ImmutableObjectRunner { public static void main(String[] args) { var list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); var a = new ImmutableObject("someone", list); a.getNumber(1); } }
package com.chengli.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; /** * Created by chengli on ${date} */ @WebListener public class MyListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("Listener contentInitialized~~~"); } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("contextDestoryed~~~"); } }
package com.codigo.smartstore.webapi.domain.idef; import java.time.LocalDate; import java.time.LocalTime; public interface IGovernmentIdentyficator { /** * Właściwość określa datę wydania * * @return */ default LocalDate getIssuedDate() { return LocalDate.now(); } /** * Właściwość określa czas wydania * * @return */ default LocalTime getIssuedIime() { return LocalTime.now(); } /** * Właściwość określa podmiot nadający numer * * @return */ String getIssuedBy(); /** * Właściwość określa datę ważności * * @return */ default LocalDate getExpireDate() { return LocalDate.MAX; } /** * Właściwość określa czas ważności * * @return */ default LocalTime getExpireTime() { return LocalTime.MAX; } }
package com.ironyard.repo; import com.ironyard.data.BarDrinks; import com.ironyard.data.BarInformation; import org.springframework.data.repository.CrudRepository; import java.util.List; /** * Created by rohanayub on 3/15/17. */ public interface BarInformationRepo extends CrudRepository<BarInformation,Long> { public BarInformation findByBarName(String barName); public List<BarInformation> findAlcoholByBarDrinkInformation(BarDrinks alcoholName); public List<BarInformation> findMixerByBarDrinkInformation(BarDrinks mixerName); public List<BarInformation> findMixerAndAlcoholByBarDrinkInformation(BarDrinks alcoholName, BarDrinks mixerName); public BarInformation findBarsAlcoholNameByBarDrinkInformation(BarDrinks alcoholName); }
package com.esum.framework.core.queue.provider; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.jms.Connection; import javax.jms.JMSException; import org.hornetq.api.core.TransportConfiguration; import org.hornetq.api.jms.HornetQJMSClient; import org.hornetq.api.jms.JMSFactoryType; import org.hornetq.core.remoting.impl.invm.InVMConnectorFactory; import org.hornetq.core.remoting.impl.netty.NettyConnectorFactory; import org.hornetq.jms.client.HornetQConnectionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.framework.core.config.Configurator; import com.esum.framework.core.exception.FrameworkException; import com.esum.framework.core.queue.QueueHandlerFactory; import com.esum.framework.core.queue.mq.JmsConnectorTypes; import com.esum.framework.core.queue.mq.pool.JmsConnectionFactory; import com.esum.framework.core.queue.mq.pool.JmsConnectionPool; /** * HornetQ Connection Provider. */ public class HornetQQueueProvider { private static Logger logger = LoggerFactory.getLogger(HornetQQueueProvider.class); private Configurator configurator = null; private String hornetQIp = null; private String hornetQPort = null; private boolean embeddedUse = false; private JmsConnectorTypes connectorMode = JmsConnectorTypes.CONNECTOR_ALL; /** * Queue Connection Factory. */ private HornetQConnectionFactory queueConnectionFactory; /** * Topic Connection Factory. */ private HornetQConnectionFactory topicConnectionFactory; private String configId; public HornetQQueueProvider(String configId) throws FrameworkException { this.configId = configId; if(!Configurator.containConfigId(configId)) { try { Configurator.init(configId, Configurator.getInstance().getString("queue.properties")); } catch (IOException e) { logger.error(e.getMessage(), e); } } this.configurator = Configurator.getInstance(configId); hornetQIp = configurator.getString("hornetq.ip"); hornetQPort = configurator.getString("hornetq.port"); embeddedUse = configurator.getBoolean("embedded.hornetq.use", false); connectorMode = JmsConnectorTypes.parse(configurator.getString("hornetq.connector.mode", "netty")); if(logger.isInfoEnabled()) logger.info("HornetQ Connection use the '"+connectorMode+"' mode."); logger.info("HornetQ Provider set. ip : "+hornetQIp+", hornetQPort : "+hornetQPort); } /** * Returns a HornetQConnectionFactory instance. */ protected HornetQConnectionFactory createConnectionFactory(JMSFactoryType factoryType) throws JMSException { HornetQConnectionFactory cf = null; if(!embeddedUse) cf = initConnectionFactory(factoryType, false); else { if(connectorMode.equals(JmsConnectorTypes.CONNECTOR_NETTY)) { cf = initConnectionFactory(factoryType, false); } else if(connectorMode.equals(JmsConnectorTypes.CONNECTOR_VM)) { cf = initConnectionFactory(factoryType, true); } else { // all if(QueueHandlerFactory.getInstance().isMainNodeType()){ cf = initConnectionFactory(factoryType, true); } else { cf = initConnectionFactory(factoryType, false); } } } return cf; } private HornetQConnectionFactory initConnectionFactory(JMSFactoryType factoryType, boolean useVM) throws JMSException { HornetQConnectionFactory cf = null; try { if(useVM) { logger.info("HornetQ use the VM connector."); cf = HornetQJMSClient.createConnectionFactoryWithoutHA( factoryType, new TransportConfiguration(InVMConnectorFactory.class.getName())); initConnectionFactoryProperties(cf); } else { logger.info("HornetQ use the netty connector. ip : "+hornetQIp+", port : "+hornetQPort); Map<String, Object> connectionParams = new HashMap<String, Object>(); connectionParams.put(org.hornetq.core.remoting.impl.netty.TransportConstants.HOST_PROP_NAME, hornetQIp); connectionParams.put(org.hornetq.core.remoting.impl.netty.TransportConstants.PORT_PROP_NAME, hornetQPort); connectionParams.put(org.hornetq.core.remoting.impl.netty.TransportConstants.USE_NIO_PROP_NAME, true); connectionParams.put(org.hornetq.core.remoting.impl.netty.TransportConstants.TCP_SENDBUFFER_SIZE_PROPNAME, "1024288"); //524K connectionParams.put(org.hornetq.core.remoting.impl.netty.TransportConstants.TCP_RECEIVEBUFFER_SIZE_PROPNAME, "1024288"); //524K TransportConfiguration transportConfiguration = new TransportConfiguration(NettyConnectorFactory.class.getName(), connectionParams); cf = HornetQJMSClient.createConnectionFactoryWithoutHA(factoryType, transportConfiguration); initConnectionFactoryProperties(cf); } } catch (Exception e) { logger.error(e.getMessage(), e); throw new JMSException(factoryType.toString()+" ConnectionFactory Lookup Error!!. IP : "+hornetQIp+", PORT : "+hornetQPort); } logger.info(factoryType.toString()+" Type ConnectionFactory created."); return cf; } private void initConnectionFactoryProperties(HornetQConnectionFactory connectionFactory) { // set connection factory properties. connectionFactory.setMinLargeMessageSize(configurator.getInt("min.large.message.size", 10501024)); connectionFactory.setRetryInterval(configurator.getInt("retry.interval", 60000)); connectionFactory.setRetryIntervalMultiplier(Double.valueOf(configurator.getString("retry.interval.multiplier", "1.5"))); connectionFactory.setMaxRetryInterval(configurator.getInt("retry.max.interval", 60000)); connectionFactory.setReconnectAttempts(configurator.getInt("reconnect.attempts", 10)); connectionFactory.setFailoverOnInitialConnection(configurator.getBoolean("failover.initial.connection", true)); connectionFactory.setClientFailureCheckPeriod(configurator.getInt("client.failure.check.period", 5000)); connectionFactory.setConnectionTTL(configurator.getInt("connection.ttl", 600000)); // connectionFactory.setCallTimeout(configurator.getInt("call.timeout", 30000)); // connectionFactory.setCallFailoverTimeout(configurator.getInt("call.failover.timeout", -1)); // connectionFactory.setUseGlobalPools(false); // connectionFactory.setThreadPoolMaxSize(-1); // connectionFactory.setScheduledThreadPoolMaxSize(3); } /** * QUEUE Connection을 생성하여 리턴한다. */ public synchronized Connection createQueueConnection(String queueName, boolean reuse) throws JMSException { return createConnection(JMSFactoryType.QUEUE_CF, queueName, reuse); } /** * TOPIC Connection을 생성하여 리턴한다. */ public synchronized Connection createTopicConnection(String queueName, boolean reuse) throws JMSException { return createConnection(JMSFactoryType.TOPIC_CF, queueName, reuse); } protected Connection createConnection(JMSFactoryType factoryType, String queueName, boolean reuse) throws JMSException { if(factoryType.equals(JMSFactoryType.QUEUE_CF)) { if(this.queueConnectionFactory==null) this.queueConnectionFactory = createConnectionFactory(factoryType); } else { if(this.topicConnectionFactory==null) this.topicConnectionFactory = createConnectionFactory(factoryType); } if(reuse) { try { JmsConnectionPool pool = JmsConnectionFactory.getInstance().getJmsConnectionPool(configId); Connection connection = pool.getConnection(queueName); if(connection==null) { if(factoryType.equals(JMSFactoryType.QUEUE_CF)) { connection = queueConnectionFactory.createQueueConnection(); } else { connection = topicConnectionFactory.createTopicConnection(); } pool.putConnection(queueName, connection); } return connection; } catch (JMSException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { logger.error("Can not get the connection.", e); throw new JMSException("Can not get the connection."); } } // 일반적으로 messageListener를 구현하는 경우 connection을 리턴하면, 별도로 관리하지 않는다. // connection은 listener를 생성한 모듈에서 관리되어야 한다. if(factoryType.equals(JMSFactoryType.QUEUE_CF)) { return queueConnectionFactory.createQueueConnection(); } else { return topicConnectionFactory.createTopicConnection(); } } }
package com.sherry.epaydigital.bussiness.service; import com.sherry.epaydigital.bussiness.domain.QRCodeDomain; import com.sherry.epaydigital.data.model.Customer; import com.sherry.epaydigital.data.model.EpayDigitalMeLink; import com.sherry.epaydigital.data.model.QRCode; import com.sherry.epaydigital.data.repository.CustomerRepository; import com.sherry.epaydigital.data.repository.QRCodeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class QRCodeService { private QRCodeRepository qrCodeRepository; private CustomerRepository customerRepository; @Autowired public QRCodeService(QRCodeRepository qrCodeRepository, CustomerRepository customerRepository) { this.qrCodeRepository = qrCodeRepository; this.customerRepository = customerRepository; } public void addQRCodeToDb(QRCodeDomain qrCodeDomain, Long customerId) { Optional<Customer> customerOptional = customerRepository.findById(customerId); if (customerOptional.isPresent()) { Customer customer = customerOptional.get(); if (customer.getQrCode() == null) { QRCode qrCode = new QRCode(); qrCode.setQrCodeImage(qrCodeDomain.getQrCodeImage()); qrCode.setCustomer(customer); customer.setQrCode(qrCode); qrCodeRepository.save(qrCode); } } } public String getQRImage(long customerId) { Optional<Customer> optionalCustomer = customerRepository.findById(customerId); if (optionalCustomer.isPresent()) { Customer customer = optionalCustomer.get(); long qrCodeId = customer.getQrCode().getId(); Optional<QRCode> optionalQRCode = qrCodeRepository.findById(qrCodeId); if (optionalQRCode.isPresent()) { QRCode qrCode = optionalQRCode.get(); return qrCode.getQrCodeImage(); } } return null; } }
package com.engin.widget; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.graphics.Shader; import android.os.Build; import android.util.AttributeSet; import android.widget.FrameLayout; import android.widget.ImageView; /** * @description: author:zhaoningqiang * @time 16/6/27/下午3:08 */ public class LayerImageView extends FrameLayout { public LayerImageView(Context context) { super(context); init(context); } public LayerImageView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public LayerImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public LayerImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context); } private ImageView underImageView; private ImageView topImageView; private void init(Context context) { setWillNotDraw(false); underImageView = new ImageView(context); FrameLayout.LayoutParams underParamas = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); underImageView.setLayoutParams(underParamas); underImageView.setScaleType(ImageView.ScaleType.FIT_XY); addView(underImageView); topImageView = new ImageView(context); FrameLayout.LayoutParams topParamas = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); topImageView.setLayoutParams(topParamas); topImageView.setScaleType(ImageView.ScaleType.FIT_XY); addView(topImageView); } public void setUpperLayerBitmap(Bitmap bitmap){ topImageView.setImageBitmap(bitmap); } public void setImageBitmap(Bitmap bm) { underImageView.setImageBitmap(bm); } int width = 0; @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); width = w; } public void update(float offset){ if (offset >=0 && offset <=1){ offset = 1.f - offset ; topImageView.setScrollX((int) (width * offset)); invalidate(); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setARGB(255,255,0,255); mPaint.setStyle(Paint.Style.FILL); RectF rectF = new RectF(getPaddingLeft(),getPaddingTop(),getWidth() - getPaddingRight(),getHeight() - getPaddingBottom()); Path mPath = new Path(); mPath.addRect(rectF, Path.Direction.CW); mPath.addArc(rectF,0,360); mPath.setFillType(Path.FillType.EVEN_ODD); canvas.drawPath(mPath,mPaint); } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); } }
/* IdSpace.java Purpose: Description: History: Fri Jul 29 10:41:31 2005, Created by tomyeh Copyright (C) 2005 Potix Corporation. All Rights Reserved. {{IS_RIGHT This program is distributed under LGPL Version 2.1 in the hope that it will be useful, but WITHOUT ANY WARRANTY. }}IS_RIGHT */ package org.zkoss.zk.ui; import java.util.Collection; import org.zkoss.zk.ui.ext.Scope; /** * Implemented by a component ({@link Component}) and a page * ({@link Page}) * to denote that all its descendant and itself forms an independent ID space. * * <p>In an ID space, ID of each component ({@link Component#getId}) must be * unique. * And, you could retrieve any component in the same ID space by calling * {@link #getFellow} upon any component of the same ID space. * * <p>For sake of description, components in the same ID space are called * fellows. * If the component has an ancestor which implements {@link IdSpace}, * we say a component belongs to the ID space owned by the ancestor. * If no such ancestor exists, the component belongs to the ID space * owned by the page. * The ancestor and the page is called the owner * ({@link Component#getSpaceOwner}). * * <p>For sake of description, we also call the ID space as space X, if * the owner is component X (or page X). * If component Y is a child of X and also implements {@link IdSpace} * (aka., another owner), then space X includes component Y, but * EXCLUDES descendants of Y. In other words, Y belongs to space X and space Y. * Thus, to get a child Z in the Y space, you shall X.getFellow('Y').getFellow('Z'). * * <p>Example: Assumes component A is a child of B, B a child of C and * C a child of D. If only C implements {@link IdSpace}, A, B and C are all * belonged to the C space. D doesn't belong any space. * * <p>If both C and D implements {@link IdSpace}, C and D belongs * to the D space while A, B and C belongs to the C space. * * <p>Note: to make a component (deriving from {@link AbstractComponent}) * an ID space owner, all it needs to do is to implement this interface. * * @author tomyeh */ public interface IdSpace extends Scope { /** Returns a component of the specified ID in this ID space. * Components in the same ID space are called fellows. * * <p>Unlike {@link #getFellowIfAny(String)}, it throws {@link ComponentNotFoundException} * if not found. * * @exception ComponentNotFoundException is thrown if * this component doesn't belong to any ID space */ public Component getFellow(String id) throws ComponentNotFoundException; /** Returns a component of the specified ID in this ID space, or null * if not found. * <p>Unlike {@link #getFellow(String)}, it returns null if not found. */ public Component getFellowIfAny(String id); /** Returns all fellows in this ID space. * The returned collection is readonly. * @since 3.0.6 */ public Collection getFellows(); /** Returns whether there is a fellow named with the specified component ID. * @since 3.5.2 */ public boolean hasFellow(String id); /** Returns a component of the specified ID in this ID space. * * <p>Unlike {@link #getFellowIfAny(String, boolean)}, it throws {@link ComponentNotFoundException} * if not found. * * @exception ComponentNotFoundException is thrown if * this component doesn't belong to any ID space * @param recurse whether to look up the parent ID space for the * existence of the fellow * @since 5.0.0 */ public Component getFellow(String id, boolean recurse) throws ComponentNotFoundException; /** Returns a component of the specified ID in this ID space, or null * if not found. * * <p>Unlike {@link #getFellow(String, boolean)}, it returns null * if not found. * * @param recurse whether to look up the parent ID space for the * existence of the fellow * @since 5.0.0 */ public Component getFellowIfAny(String id, boolean recurse); /** Returns whether there is a fellow named with the specified component ID. * * @param recurse whether to look up the parent ID space for the * existence of the fellow * @since 5.0.0 */ public boolean hasFellow(String id, boolean recurse); }
public class TwoColorSquare{ public static void main(String[] args){ StdDraw.setXscale(-5,5); StdDraw.setYscale(-5,5); //Halvfyrkant 1 StdDraw.setPenColor(StdDraw.DARK_GRAY); StdDraw.filledRectangle(-3,0,3,6); //Halvfyrkant 2 StdDraw.setPenColor(StdDraw.LIGHT_GRAY); StdDraw.filledRectangle(3,0,3,6); //Fyrkant 3 StdDraw.setPenColor(StdDraw.GRAY); StdDraw.filledSquare(0,0,3); } }
package awtSample06; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.text.BadLocationException; public class WindowTest extends JFrame /* implements ActionListener */ { JTextField textField; JTextArea textArea; JButton btn1, btn2; public WindowTest() { super("textfield"); JPanel panel = new JPanel(); textArea = new JTextArea(); textArea.setLineWrap(true); JScrollPane scrPane = new JScrollPane(textArea); scrPane.setPreferredSize(new Dimension(400, 300)); panel.add(scrPane); JPanel botpan = new JPanel(); textField = new JTextField(20); btn1 = new JButton("next insert"); btn1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // JOptionPane.showMessageDialog(null, "next insert"); if(!textField.getText().equals("")) { String msg = textField.getText() + "\n"; textArea.append(msg); textField.setText(""); } } }); btn2 = new JButton("prev insert"); btn2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { textArea.insert(textField.getText() + "\n", textArea.getLineStartOffset(0)); } catch (BadLocationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); botpan.add(textField); botpan.add(btn1); botpan.add(btn2); Container contentPane = getContentPane(); contentPane.add(panel, BorderLayout.CENTER); contentPane.add(botpan, BorderLayout.SOUTH); setBounds(0, 0, 640, 480); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } /* @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub } */ }
/* * 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.http.converter.json; import java.net.URI; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.http.HttpStatus; import org.springframework.http.ProblemDetail; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for serializing a {@link org.springframework.http.ProblemDetail} through * the Jackson library. * * @author Rossen Stoyanchev * @since 6.0 */ class ProblemDetailJacksonMixinTests { private final ObjectMapper mapper = new Jackson2ObjectMapperBuilder().build(); @Test void writeStatusAndHeaders() throws Exception { ProblemDetail detail = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Missing header"); testWrite(detail, """ { "type": "about:blank", "title": "Bad Request", "status": 400, "detail": "Missing header" }"""); } @Test void writeCustomProperty() throws Exception { ProblemDetail detail = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Missing header"); detail.setProperty("host", "abc.org"); detail.setProperty("user", null); testWrite(detail, """ { "type": "about:blank", "title": "Bad Request", "status": 400, "detail": "Missing header", "host": "abc.org", "user": null }"""); } @Test void readCustomProperty() throws Exception { ProblemDetail detail = this.mapper.readValue(""" { "type": "about:blank", "title": "Bad Request", "status": 400, "detail": "Missing header", "host": "abc.org", "user": null }""", ProblemDetail.class); assertThat(detail.getType()).isEqualTo(URI.create("about:blank")); assertThat(detail.getTitle()).isEqualTo("Bad Request"); assertThat(detail.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value()); assertThat(detail.getDetail()).isEqualTo("Missing header"); assertThat(detail.getProperties()) .containsEntry("host", "abc.org") .containsEntry("user", null); } @Test void readCustomPropertyFromXml() throws Exception { ObjectMapper xmlMapper = new Jackson2ObjectMapperBuilder().createXmlMapper(true).build(); ProblemDetail detail = xmlMapper.readValue(""" <problem xmlns="urn:ietf:rfc:7807"> <type>about:blank</type> <title>Bad Request</title> <status>400</status> <detail>Missing header</detail> <host>abc.org</host> </problem>""", ProblemDetail.class); assertThat(detail.getType()).isEqualTo(URI.create("about:blank")); assertThat(detail.getTitle()).isEqualTo("Bad Request"); assertThat(detail.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value()); assertThat(detail.getDetail()).isEqualTo("Missing header"); assertThat(detail.getProperties()).containsEntry("host", "abc.org"); } private void testWrite(ProblemDetail problemDetail, String expected) throws Exception { String output = this.mapper.writeValueAsString(problemDetail); JSONAssert.assertEquals(expected, output, false); } }
package com.netcracker.CustomException; public class FailureRequestPayment extends Exception{ }
package com.isg.ifrend.core.model.mli.transaction; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * * Bean class for Transaction * */ public class AuthorizeTransaction implements Serializable { private static final long serialVersionUID = 6838235722553547202L; private String accountNumber; private Date transactionDate; private String billCurrencyCode; private BigDecimal billAmount; private String response; private String authCode; private String origCurrencyCode; private BigDecimal origAmount; private BigDecimal reviseCode; private String merchantName; private String revesalReason; public AuthorizeTransaction(){ } public AuthorizeTransaction(String accountNumber, Date transactionDate, String billCurrencyCode, BigDecimal billAmount, String response, String authCode, String origCurrencyCode, BigDecimal origAmount, BigDecimal reviseCode, String merchantName, String revesalReason) { this.accountNumber = accountNumber; this.transactionDate = transactionDate; this.billCurrencyCode = billCurrencyCode; this.billAmount = billAmount; this.response = response; this.authCode = authCode; this.origCurrencyCode = origCurrencyCode; this.origAmount = origAmount; this.reviseCode = reviseCode; this.merchantName = merchantName; this.revesalReason = revesalReason; } /** getter and setter **/ public Date getTransactionDate() { return transactionDate; } public String getAccountNumber() { return accountNumber; } public void setAccountNumber(String accountNumber) { this.accountNumber = accountNumber; } public void setTransactionDate(Date transactionDate) { this.transactionDate = transactionDate; } public String getBillCurrencyCode() { return billCurrencyCode; } public void setBillCurrencyCode(String billCurrencyCode) { this.billCurrencyCode = billCurrencyCode; } public BigDecimal getBillAmount() { return billAmount; } public void setBillAmount(BigDecimal billAmount) { this.billAmount = billAmount; } public String getResponse() { return response; } public void setResponse(String response) { this.response = response; } public String getAuthCode() { return authCode; } public void setAuthCode(String authCode) { this.authCode = authCode; } public String getOrigCurrencyCode() { return origCurrencyCode; } public void setOrigCurrencyCode(String origCurrencyCode) { this.origCurrencyCode = origCurrencyCode; } public BigDecimal getOrigAmount() { return origAmount; } public void setOrigAmount(BigDecimal origAmount) { this.origAmount = origAmount; } public BigDecimal getReviseCode() { return reviseCode; } public void setReviseCode(BigDecimal reviseCode) { this.reviseCode = reviseCode; } public String getMerchantName() { return merchantName; } public void setMerchantName(String merchantName) { this.merchantName = merchantName; } public String getRevesalReason() { return revesalReason; } public void setRevesalReason(String revesalReason) { this.revesalReason = revesalReason; } }
// https://www.youtube.com/watch?v=4ykBXGbonlA class Solution { public List<List<String>> partition(String s) { List<List<String>> decompositions = new ArrayList(); decomposeString(0, s, new ArrayList<>(), decompositions); return decompositions; } private void decomposeString(int workingIndex, String s, List<String> partialDecomposition, List<List<String>> decompositions) { if (workingIndex == s.length()) { decompositions.add(new ArrayList<>(partialDecomposition)); return; } for (int i = workingIndex; i < s.length(); i++) { if (isPalindrome(workingIndex, i, s)) { String palindromicSnippet = s.substring(workingIndex, i + 1); partialDecomposition.add(palindromicSnippet); decomposeString(i + 1, s, partialDecomposition, decompositions); partialDecomposition.remove(partialDecomposition.size() - 1); } } } public boolean isPalindrome(int left, int right, String s) { while (left < right) { if (s.charAt(left) != s.charAt(right)) return false; left++; right--; } return true; } }
import java.util.Scanner; public class Cliente implements GestionBiblio{ private String nombre; private String dni; Cliente(){ } Cliente (String nombre, String dni){ this.nombre = nombre; this.dni = dni; } //NOMBRE// public void setNombre(String nombre) { this.nombre = nombre; } public String getNombre() { return nombre; } //DNI// public void setDni(String dni) { this.dni = dni; } public String getDni() { return dni; } //Utilizamos el método de la interfaz @Override public void ejectuarAccion() { Cliente cliente = new Cliente(); Scanner sc = new Scanner(System.in); System.out.println("Dime tu nombre: "); String nombre = sc.nextLine(); System.out.println("Dime tu dni: "); String dni = sc.nextLine(); System.out.println("Nuevo Cliente: \n" + "Nombre: " + nombre + ", DNI: " + dni); } }
package rso.dfs.dummy.server; import org.apache.thrift.server.TServer; import org.apache.thrift.server.TServer.Args; import org.apache.thrift.server.TSimpleServer; import org.apache.thrift.transport.TServerSocket; import org.apache.thrift.transport.TServerTransport; import rso.dfs.dummy.generated.StorageService; /** * @author Adam Papros <adam.papros@gmail.com> * TODO:DELETE THIS SHIT * @deprecated * */ @Deprecated public class StorageServer { static StorageHandler handler; static StorageService.Processor procesor; static final int portNumber = 9091; public static void main(String[] args) { try { handler = new StorageHandler(); procesor = new StorageService.Processor(handler); Runnable simple = new Runnable() { @Override public void run() { simple(procesor); } }; new Thread(simple).start(); } catch (Exception e) { e.printStackTrace(); } } public static void simple(StorageService.Processor processor) { try { TServerTransport serverTransport = new TServerSocket(portNumber); TServer server = new TSimpleServer(new Args(serverTransport).processor(processor)); System.out.println("Starting storage server..."); server.serve(); } catch (Exception e) { e.printStackTrace(); } } }
package com.developworks.jvmcode; /** * <p>Title: areturn</p> * <p>Description: 从方法中返回一个引用类型数据</p> * <p>Author: ouyp </p> * <p>Date: 2018-05-19 15:38</p> */ public class areturn { public Object areturn(Object o) { return o; } } /** * public java.lang.Object areturn(java.lang.Object); * Code: * 0: aload_1 * 1: areturn */
package com.atguigu.callable; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; public class NumThread{ public static void main(String[] args) { ThreadNew threadNew = new ThreadNew(); FutureTask futureTask = new FutureTask(threadNew); new Thread(futureTask).start(); try{ Object sum = futureTask.get(); System.out.println("总和为:"+sum); }catch (Exception e){ e.printStackTrace(); } } } class ThreadNew implements Callable { @Override public Object call() throws Exception { int sum=0; for (int i = 1; i <= 100; i++) { if(i%2==0){ System.out.println(i); sum+=i; } } return sum; } }
import org.junit.Test; import static org.junit.Assert.*; class CustomerTest { @Test void testStatement() { Customer customer1 = new Customer("Maria"); assertEquals( "Rental Record for Maria\n" + "Amount owed is 0.0\n" + "You earned 0 frequent renter points", customer1.statement() ); Movie movie1 = new Movie( "Os Sonhadores", Movie.REGULAR ); Movie movie2 = new Movie( "Pierrot Le Fou", Movie.NEW_RELEASE ); customer1.addRental(new Rental(movie1, 12)); assertEquals( "Rental Record for Maria\n" + "\tOs Sonhadores\t17.0\n" + "Amount owed is 17.0\n" + "You earned 1 frequent renter points", customer1.statement() ); customer1.addRental(new Rental(movie2, 10)); assertEquals( "Rental Record for Maria\n" + "\tOs Sonhadores\t17.0\n" + "\tPierrot Le Fou\t30.0\n" + "Amount owed is 47.0\n" + "You earned 3 frequent renter points", customer1.statement() ); } }
package ticTacToe; public enum Mark { X("X"), O("O"), EMPTY("_"); public String value; Mark(String value) { this.value = value; } @Override public String toString() { return value; } }
package modelo; public class tableDetalle_ventasDTO { private long codigo_detalle_venta; private int cantidad_producto; private long codigo_producto; private long codigo_venta; private double valor_total; private double valor_venta; private double valoriva; public tableDetalle_ventasDTO(long codigo_detalle_venta, int cantidad_producto, long codigo_producto, long codigo_venta, double valor_total, double valor_venta, double valoriva) { super(); this.codigo_detalle_venta = codigo_detalle_venta; this.cantidad_producto = cantidad_producto; this.codigo_producto = codigo_producto; this.codigo_venta = codigo_venta; this.valor_total = valor_total; this.valor_venta = valor_venta; this.valoriva = valoriva; } public long getCodigo_detalle_venta() { return codigo_detalle_venta; } public void setCodigo_detalle_venta(long codigo_detalle_venta) { this.codigo_detalle_venta = codigo_detalle_venta; } public int getCantidad_producto() { return cantidad_producto; } public void setCantidad_producto(int cantidad_producto) { this.cantidad_producto = cantidad_producto; } public long getCodigo_producto() { return codigo_producto; } public void setCodigo_producto(long codigo_producto) { this.codigo_producto = codigo_producto; } public long getCodigo_venta() { return codigo_venta; } public void setCodigo_venta(long codigo_venta) { this.codigo_venta = codigo_venta; } public double getValor_total() { return valor_total; } public void setValor_total(double valor_total) { this.valor_total = valor_total; } public double getValor_venta() { return valor_venta; } public void setValor_venta(double valor_venta) { this.valor_venta = valor_venta; } public double getValoriva() { return valoriva; } public void setValoriva(double valoriva) { this.valoriva = valoriva; } }
package com.guoguo.mocktest.account; public class Account { private String accountId; private long balance; public Account (String accountId, long initialBalance){ this.accountId=accountId; this.balance=initialBalance; } public void debit(long amount){ this.balance-=amount; } public void credit(long amount){ this.balance+=amount; } public long getBalance() { return balance; } public void setBalance(long balance) { this.balance = balance; } public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } }
package com.xinhua.api.domain.xinXXGBean; import com.apsaras.aps.increment.domain.AbstractIncResponse; import java.io.Serializable; /** * Created by lirs_wb on 2015/8/28. * 信息修改 响应 */ public class XinXXGResponse extends AbstractIncResponse implements Serializable { /** * 保险公司交易日期 */ private String transExeDate; /** *保险公司交易时间 */ private String transExeTime; /** *交易流水号 */ private String transRefGUID; /** *处理标志 */ private String transType; /** *返回码 */ private String resultCode; /** *返回信息 */ private String resultInfo; /** *保单号码 */ private String polNumber; /** *批文内容 */ private String attachmentData; /** *批改生效日期 */ private String formInstanceStatusDate; /** *单证名称 */ private String formName; /** *单证号码 */ private String documentControlNumber; /** * 用于无法处理的字段 */ private String no; public String getNo() { return no; } public void setNo(String no) { this.no = no; } public String getTransExeDate() { return transExeDate; } public void setTransExeDate(String transExeDate) { this.transExeDate = transExeDate; } public String getTransExeTime() { return transExeTime; } public void setTransExeTime(String transExeTime) { this.transExeTime = transExeTime; } public String getTransRefGUID() { return transRefGUID; } public void setTransRefGUID(String transRefGUID) { this.transRefGUID = transRefGUID; } public String getTransType() { return transType; } public void setTransType(String transType) { this.transType = transType; } public String getResultCode() { return resultCode; } public void setResultCode(String resultCode) { this.resultCode = resultCode; } public String getResultInfo() { return resultInfo; } public void setResultInfo(String resultInfo) { this.resultInfo = resultInfo; } public String getPolNumber() { return polNumber; } public void setPolNumber(String polNumber) { this.polNumber = polNumber; } public String getAttachmentData() { return attachmentData; } public void setAttachmentData(String attachmentData) { this.attachmentData = attachmentData; } public String getFormInstanceStatusDate() { return formInstanceStatusDate; } public void setFormInstanceStatusDate(String formInstanceStatusDate) { this.formInstanceStatusDate = formInstanceStatusDate; } public String getFormName() { return formName; } public void setFormName(String formName) { this.formName = formName; } public String getDocumentControlNumber() { return documentControlNumber; } public void setDocumentControlNumber(String documentControlNumber) { this.documentControlNumber = documentControlNumber; } @Override public String toString() { return "XinXXGResponse{" + "transExeDate='" + transExeDate + '\'' + ", transExeTime='" + transExeTime + '\'' + ", transRefGUID='" + transRefGUID + '\'' + ", transType='" + transType + '\'' + ", resultCode='" + resultCode + '\'' + ", resultInfo='" + resultInfo + '\'' + ", polNumber='" + polNumber + '\'' + ", attachmentData='" + attachmentData + '\'' + ", formInstanceStatusDate='" + formInstanceStatusDate + '\'' + ", formName='" + formName + '\'' + ", documentControlNumber='" + documentControlNumber + '\'' + ", no='" + no + '\'' + '}'; } }
package com.swapping.springcloud.ms.core.utils; import org.apache.commons.codec.digest.DigestUtils; import java.util.UUID; /** * swapping项目下所有的工具方法 * @author SXD * @date 2018.10.26 */ public class SwappingUtils { public static final String MD5_KEY = "Angel_SXD"; /** * 公共获取UUID方法 * 获取长度为32位的UUID * @return */ public static String uid(){ return UUID.randomUUID().toString().replaceAll("-", ""); } /** * MD5加密方法 * * @param original 原始文 * @return 加密文 */ public static String MD5(String original){ return DigestUtils.md5Hex(original+MD5_KEY); } /** * MD5验证方法 * @param original 原始文 * @param md5 待验证加密文 * @return 验证通过true、失败false */ public static boolean MD5_verify(String original,String md5){ String encryption = DigestUtils.md5Hex(original+MD5_KEY); return encryption.equals(md5) ? true : false; } }
package array; /** * Created by gouthamvidyapradhan on 12/12/2017. * Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to * compute the researcher's h-index. According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each." For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, his h-index is 3. Note: If there are several possible values for h, the maximum one is taken as the h-index. Solution O(n) Replace all the citations which are greater than n with n, the result will not change with this operation. Maintain a count array with count of each citations. Sum up all the counts from n -> 0 and store this in a array S. Value in array index Si is number of papers having citations at least i. The first value at index i, from right to left in array S which has i <= Si is the answer. */ public class HIndex { public static void main(String[] args) throws Exception{ int[] A = {3, 0, 6, 1, 5}; System.out.println(new HIndex().hIndex(A)); } public int hIndex(int[] citations) { int n = citations.length; int[] count = new int[n + 1]; int[] S = new int[n + 1]; for(int i = 0; i < citations.length; i ++){ if(citations[i] > n){ citations[i] = n; } } for (int citation : citations) { count[citation]++; } S[n] = count[n]; for(int i = n - 1; i >= 0; i --){ S[i] = count[i] + S[i + 1]; } for(int i = n; i >= 0; i--){ if(i <= S[i]){ return i; } } return 0; } }
package com.metoo.module.app.chatting.view.action; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.nutz.json.Json; import org.nutz.json.JsonFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.metoo.core.domain.virtual.SysMap; import com.metoo.core.mv.JModelAndView; import com.metoo.core.query.support.IPageList; import com.metoo.core.tools.CommUtil; import com.metoo.foundation.domain.Goods; import com.metoo.foundation.domain.GoodsClass; import com.metoo.foundation.domain.Store; import com.metoo.foundation.domain.User; import com.metoo.foundation.service.IAccessoryService; import com.metoo.foundation.service.IArticleService; import com.metoo.foundation.service.IGoodsClassService; import com.metoo.foundation.service.IGoodsService; import com.metoo.foundation.service.IOrderFormService; import com.metoo.foundation.service.IReturnGoodsLogService; import com.metoo.foundation.service.IStoreService; import com.metoo.foundation.service.ISysConfigService; import com.metoo.foundation.service.IUserConfigService; import com.metoo.foundation.service.IUserService; import com.metoo.manage.admin.tools.OrderFormTools; import com.metoo.module.app.buyer.domain.Result; import com.metoo.module.app.view.web.tool.AppGoodsViewTools; import com.metoo.module.chatting.domain.Chatting; import com.metoo.module.chatting.domain.ChattingConfig; import com.metoo.module.chatting.domain.ChattingLog; import com.metoo.module.chatting.domain.query.ChattingLogQueryObject; import com.metoo.module.chatting.service.IChattingConfigService; import com.metoo.module.chatting.service.IChattingLogService; import com.metoo.module.chatting.service.IChattingService; import com.metoo.view.web.tools.ActivityViewTools; import com.metoo.view.web.tools.GoodsViewTools; /** * * <p> * ·Title: ChattingViewAction.java * </p> * * <p> * ·Description: 系统聊天工具,作为单独聊天系统,可以集成其他系统,用户使用聊天系统超过session时长自动关闭会话窗口 * </p> * * <p> * ·Copyright: Copyright (c) 2019 * </p> * * <p> * ·Company: 湖南觅通 * </p> * * @author * * @date 2019年7月25日 * * @version */ @Controller public class AppUserChattingViewAction { @Autowired private ISysConfigService configService; @Autowired private IUserConfigService userConfigService; @Autowired private IUserService userService; @Autowired private IGoodsService goodsService; @Autowired private IGoodsClassService goodsclassService; @Autowired private GoodsViewTools goodsViewTools; @Autowired private IStoreService storeService; @Autowired private IOrderFormService ofService; @Autowired private IChattingService chattingService; @Autowired private IChattingLogService chattinglogService; @Autowired private IChattingConfigService chattingconfigService; @Autowired private IAccessoryService accessoryService; @Autowired private IReturnGoodsLogService returngoodslogService; @Autowired private OrderFormTools orderformTools; @Autowired private IArticleService articleService; @Autowired private ActivityViewTools activityViewTools; @Autowired private AppGoodsViewTools metooGoodsViewTools; @RequestMapping("/user_chatting.json") public void user_chatting(HttpServletRequest request, HttpServletResponse response, String gid, String type, String store_id, String currentPage, String token) { Result result = null; Map chatting_map = new HashMap(); ModelAndView mv = new JModelAndView("chatting/user_chatting.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 1, request, response); if(token.equals("")){ result = new Result(-100,"token Invalidation"); }else{ Map params = new HashMap(); params.put("app_login_token", token); List<User> users = this.userService.query("select obj from User obj where obj.app_login_token=:app_login_token order by obj.addTime desc", params, -1, -1); if(users.isEmpty()){ result = new Result(-100,"token Invalidation"); }else{ User user = users.get(0); List<Chatting> chattings = null; Chatting chatting = new Chatting(); ChattingConfig config = new ChattingConfig(); if (!users.isEmpty()) { HttpSession session = request.getSession(false); session.setAttribute("chatting_session", "chatting_session"); //[接受商品id查询商品信息 否则该位置显示推荐商品信息] if (gid != null && !gid.equals("")) { Goods goods = this.goodsService.getObjById(CommUtil .null2Long(gid)); if (goods.getGoods_type() == 1) {// 和商家客服对话 Map map = new HashMap(); // 生成聊天组件配置信息 map.put("store_id", goods.getGoods_store().getId()); List<ChattingConfig> config_list = this.chattingconfigService .query("select obj from ChattingConfig obj where obj.store_id=:store_id ", map, 0, 1); if (config_list.size() == 0) { config.setAddTime(new Date()); config.setConfig_type(0); config.setStore_id(goods.getGoods_store().getId()); config.setKf_name(goods.getGoods_store() .getStore_name() + "在线客服"); this.chattingconfigService.save(config); } else { config = config_list.get(0); } map.clear(); map.put("uid", user.getId()); map.put("store_id", goods.getGoods_store().getId()); chattings = this.chattingService .query("select obj from Chatting obj where obj.user_id=:uid and obj.config.store_id=:store_id order by addTime asc", map, 0, 1); if (chattings.size() == 0) { chatting.setAddTime(new Date()); chatting.setUser_id(user.getId()); chatting.setConfig(config); chatting.setUser_name(user.getUserName()); chatting.setGoods_id(CommUtil.null2Long(gid)); this.chattingService.save(chatting); } else { chatting = chattings.get(0); chatting.setGoods_id(CommUtil.null2Long(gid)); this.chattingService.update(chatting); } mv.addObject("store", goods.getGoods_store()); this.generic_evaluate(goods.getGoods_store(), mv);// 店铺信用信息 } else {// 和平台客服对话 Map map = new HashMap(); // 生成聊天组件配置信息 map.put("config_type", 1);// 平台 List<ChattingConfig> config_list = this.chattingconfigService .query("select obj from ChattingConfig obj where obj.config_type=:config_type ", map, 0, 1); if (config_list.size() == 0) { config.setAddTime(new Date()); config.setConfig_type(1);// 平台聊天 config.setKf_name("平台在线客服"); this.chattingconfigService.save(config); } else { config = config_list.get(0); } map.clear(); map.put("uid", user.getId()); map.put("config_type", 1); chattings = this.chattingService .query("select obj from Chatting obj where obj.user_id=:uid and obj.config.config_type=:config_type order by addTime asc", map, 0, 1); if (chattings.size() == 0) { chatting.setAddTime(new Date()); chatting.setUser_id(user.getId()); chatting.setConfig(config); chatting.setUser_name(user.getUserName()); chatting.setGoods_id(CommUtil.null2Long(gid)); this.chattingService.save(chatting); } else { chatting = chattings.get(0); chatting.setGoods_id(CommUtil.null2Long(gid)); this.chattingService.update(chatting); } } } else {// 当不传入商品id时,聊天窗口不显示商品信息,显示推荐商品 Map map = new HashMap(); if (type.equals("store")) {// 没有传入商品id时和商家客服对话 Store store = this.storeService.getObjById(CommUtil .null2Long(store_id)); if (store != null) { map.clear(); map.put("store_id", store.getId()); map.put("goods_status", 0); List<Goods> recommends = this.goodsService .query("select obj from Goods obj where obj.goods_status=:goods_status and obj.goods_store.id=:store_id order by goods_salenum desc", map, 0, 5); mv.addObject("recommends", recommends); // 生成聊天组件配置信息 map.clear(); map.put("store_id", store.getId()); List<ChattingConfig> config_list = this.chattingconfigService .query("select obj from ChattingConfig obj where obj.store_id=:store_id ", map, 0, 1); if (config_list.size() == 0) { config.setAddTime(new Date()); config.setConfig_type(0); //[类型 0商家] config.setStore_id(store.getId());//[店铺id] config.setKf_name(store.getStore_name() + "在线客服");//[客服自定义名称] this.chattingconfigService.save(config); } else { config = config_list.get(0); } map.clear(); map.put("uid", user.getId()); map.put("store_id", store.getId()); chattings = this.chattingService .query("select obj from Chatting obj where obj.user_id=:uid and obj.config.store_id=:store_id order by addTime asc", map, 0, 1); if (chattings.size() == 0) { chatting.setAddTime(new Date()); chatting.setUser_id(user.getId()); chatting.setConfig(config); chatting.setUser_name(user.getUserName()); this.chattingService.save(chatting); } else { chatting = chattings.get(0); } mv.addObject("store", store); this.generic_evaluate(store, mv);// 店铺信用信息 } else { result = new Result(1,"请求参数错误"); } } else {// 没有传入商品id时和平台客服对话 map.clear(); map.put("goods_type", 0); map.put("goods_status", 0); List<Goods> recommends = this.goodsService .query("select obj from Goods obj where obj.goods_status=:goods_status and obj.goods_type=:goods_type order by goods_salenum desc", map, 0, 5); mv.addObject("recommends", recommends); // 生成聊天组件配置信息 map.clear(); map.put("config_type", 1);// 平台 List<ChattingConfig> config_list = this.chattingconfigService .query("select obj from ChattingConfig obj where obj.config_type=:config_type ", map, 0, 1); if (config_list.size() == 0) { config.setAddTime(new Date()); config.setConfig_type(1);// 平台聊天 config.setKf_name("平台在线客服"); this.chattingconfigService.save(config); } else { config = config_list.get(0); } map.clear(); map.put("uid", user.getId()); map.put("config_type", 1); chattings = this.chattingService .query("select obj from Chatting obj where obj.user_id=:uid and obj.config.config_type=:config_type order by addTime asc", map, 0, 1); if (chattings.size() == 0) { chatting.setAddTime(new Date()); chatting.setUser_id(user.getId()); chatting.setConfig(config); chatting.setUser_name(user.getUserName()); this.chattingService.save(chatting); } else { chatting = chattings.get(0); } //读取聊天记录 List<ChattingLog> chattingLogs = new ArrayList<ChattingLog>(); ChattingLogQueryObject qo = new ChattingLogQueryObject(currentPage, mv, "addTime", "desc"); qo.addQuery("obj.user_id", new SysMap("user_id", user.getId()), "="); qo.addQueryOR("obj.chatting.id", new SysMap("chatting_id", chatting.getId()), "="); //qo.addQuery("obj.user_read", new SysMap("user_read", 1), "="); //qo.addQuery("obj.plat_read", new SysMap("plat_read", 1), "="); qo.setPageSize(20); IPageList pList = chattinglogService.list(qo); chattingLogs = pList.getResult(); List<Map<String,Object>> list = new ArrayList<Map<String,Object>>(); for(ChattingLog log : chattingLogs){ Map<String,Object> logmap = new HashMap<String,Object>(); logmap.put("user_read", log.getUser_read()); logmap.put("user_id", log.getUser_id()); logmap.put("addTime", log.getAddTime()); logmap.put("store_read", log.getStore_read()); logmap.put("plat_read", log.getPlat_read()); logmap.put("id", log.getId()); logmap.put("content", log.getContent()); list.add(logmap); } Collections.reverse(list); chatting_map.put("chattingLogJson", list); } } // 我的订单 params.clear(); /*params.put("user_id", SecurityUserHolder.getCurrentUser().getId() .toString()); List<OrderForm> orders = this.ofService .query("select obj from OrderForm obj where obj.user_id=:user_id order by addTime desc", params, 0, 1);*/ /*params.clear(); params.put("user_id", SecurityUserHolder.getCurrentUser().getId() .toString()); List<OrderForm> all_orders = this.ofService .query("select obj.id from OrderForm obj where obj.user_id=:user_id order by addTime desc", params, -1, -1);*/ // 我的退货 /*params.clear(); params.put("user_id", SecurityUserHolder.getCurrentUser().getId()); List<ReturnGoodsLog> returnlogs = this.returngoodslogService .query("select obj from ReturnGoodsLog obj where obj.user_id=:user_id order by addTime desc", params, 0, 1);*/ /*params.clear(); params.put("user_id", SecurityUserHolder.getCurrentUser().getId()); List<ReturnGoodsLog> all_returnlogs = this.returngoodslogService .query("select obj.id from ReturnGoodsLog obj where obj.user_id=:user_id order by addTime desc", params, -1, -1);*/ // 文章 /*params.clear(); params.put("class_mark", "chatting_article"); params.put("display", true); List<Article> article = this.articleService .query("select obj from Article obj where obj.articleClass.parent.mark=:class_mark and obj.display=:display order by obj.addTime desc", params, 0, 10);*/ //mv.addObject("chatting", chatting); chatting_map.put("chatting_user_id", user.getId()); chatting_map.put("store_id", store_id == null ? "" : store_id); chatting_map.put("chatting_userName", user.getUserName()); chatting_map.put("chatting_id", chatting.getId()); chatting_map.put("chatting_font", chatting.getFont()); chatting_map.put("chatting_font_size", chatting.getFont_size()); chatting_map.put("chatting_font_colour", chatting.getFont_colour()); chatting_map.put("chatting_config_name", chatting.getConfig().getKf_name()); if(!chatting_map.isEmpty()){ result = new Result(0,"success",chatting_map); }else{ result = new Result(1,"error"); } //mv.addObject("user", user); //mv.addObject("article", article); //mv.addObject("returnlogs", returnlogs); //mv.addObject("all_returnlogs", all_returnlogs.size()); //mv.addObject("orders", orders); //mv.addObject("all_orders", all_orders.size()); //mv.addObject("orderformTools", orderformTools); } else { result = new Result(2,"长时间没有操作,窗口已关闭"); } } } try { response.getWriter().print(Json.toJson(result, JsonFormat.compact())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @RequestMapping("/user_chatting_save.json") public void user_chatting_save(HttpServletRequest request, HttpServletResponse response, String text, String chatting_id, String font, String font_size, String font_colour, String token) { Result result = null; Map user_chatting_map = new HashMap(); ModelAndView mv = new JModelAndView("chatting/user_chatting_log.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 1, request, response); if(token.equals("")){ result = new Result(-100,"token Invalidation"); }else{ Map params = new HashMap(); params.put("app_login_token", token); List<User> users = this.userService.query("select obj from User obj where obj.app_login_token=:app_login_token order by obj.addTime desc", params, -1, -1); if(users.isEmpty()){ result = new Result(-100,"token Invalidation"); }else{ boolean ret = true; User user = users.get(0); Chatting chatt = this.chattingService.getObjById(CommUtil .null2Long(chatting_id)); if (chatt == null) { ret = false; } if (users.isEmpty()) { ret = false; } if (ret) { chatt.setChatting_display(0);// 显示 this.chattingService.update(chatt); ChattingLog log = new ChattingLog(); log.setAddTime(new Date()); log.setContent(text); log.setFont(font); log.setFont_size(font_size); log.setFont_colour(font_colour); log.setChatting(chatt); log.setUser_id(user.getId()); log.setUser_read(1);// 自己发布的消息设置为自己已读 this.chattinglogService.save(log); // 保存用户聊天组件字体信息 if (!font.equals(chatt.getFont()) && !font.equals("")) { chatt.setFont(font); } if (!font_size.equals(chatt.getFont_size()) && !font_size.equals("")) { chatt.setFont_size(font_size); } if (!font_colour.equals(chatt.getFont_colour()) && !font_colour.equals("")) { chatt.setFont_colour(font_colour); } this.chattingService.update(chatt); List<ChattingLog> cls = new ArrayList<ChattingLog>(); cls.add(log); // 客服自动回复 if (chatt.getConfig().getQuick_reply_open() == 1) { ChattingLog log2 = new ChattingLog(); log2.setAddTime(new Date()); log2.setChatting(chatt); log2.setContent(chatt.getConfig().getQuick_reply_content() + "[自动回复]"); log2.setFont(chatt.getConfig().getFont()); log2.setFont_size(chatt.getConfig().getFont_size()); log2.setFont_colour(chatt.getConfig().getFont_colour()); log2.setStore_id(chatt.getConfig().getStore_id());// 当与平台对话时,该值为null this.chattinglogService.save(log2); } List<Map> cl_list = new ArrayList<Map>(); for(ChattingLog obj : cls){ if(obj.getUser_id() != null && !obj.getUser_id().equals("")){ Map cl_map = new HashMap(); cl_map.put("user_name", obj.getChatting().getUser_name()); User usr = this.userService.getObjById(CommUtil.null2Long(obj.getUser_id())); if(usr.getSex() == 0){ cl_map.put("profile_photo", this.configService.getSysConfig().getImageWebServer()+"/"+"resources"+"/"+"style"+"/"+"common"+"/"+"images"+"/"+"member0.png"); } if(usr.getSex() == 1){ cl_map.put("profile_photo", this.configService.getSysConfig().getImageWebServer()+"/"+"resources"+"/"+"style"+"/"+"common"+"/"+"images"+"/"+"member1.png"); } if(usr.getSex() == -1){ cl_map.put("profile_photo", this.configService.getSysConfig().getImageWebServer()+"/"+"resources"+"/"+"style"+"/"+"common"+"/"+"images"+"/"+"member.png"); } cl_map.put("chatting_time", CommUtil.formatLongDate(obj.getAddTime())); cl_map.put("chatting_font_colour", obj.getFont_colour()); cl_map.put("chatting_font", obj.getFont()); cl_map.put("chatting_font_size", obj.getFont_size()); cl_map.put("chatting_content", obj.getContent()); cl_map.put("kf_name", obj.getChatting().getConfig().getKf_name()); cl_list.add(cl_map); } } user_chatting_map.put("cl_list", cl_list); //mv.addObject("chatting", chatt); // 重新设置sessin HttpSession session = request.getSession(false); session.removeAttribute("chatting_session"); session.setAttribute("chatting_session", "chatting_session"); String chatting_session = CommUtil.null2String(session .getAttribute("chatting_session")); if (session != null && !session.equals("")) { user_chatting_map.put("chatting_session", chatting_session); //mv.addObject("chatting_session", chatting_session); } result = new Result(0,"chatting_success",user_chatting_map); } else { result = new Result(1,"chatting_error",true); } } } try { response.getWriter().print(Json.toJson(result, JsonFormat.compact())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 用户端定时刷新请求, type;// 对话类型,0为用户和商家对话,1为用户和平台对话 user_read:用户没有读过的信息 * * @param request * @return */ @RequestMapping("/user_chatting_refresh.json") public void user_chatting_refresh(HttpServletRequest request, HttpServletResponse response, String chatting_id, String token) { Map refresh_map = new HashMap(); Result result = null; ModelAndView mv = new JModelAndView("chatting/user_chatting_log.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 1, request, response); if(token.equals("")){ result = new Result(-100,"token Invalidation"); }else{ Map params = new HashMap(); params.put("app_login_token", token); List<User> users = this.userService.query("select obj from User obj where obj.app_login_token=:app_login_token order by obj.addTime desc", params, -1, -1); if(users.isEmpty()){ result = new Result(-100,"token Invalidation"); }else{ Chatting chatting = this.chattingService.getObjById(CommUtil .null2Long(chatting_id)); if (!users.isEmpty() && chatting != null) { params.clear(); params.put("chatting_id", CommUtil.null2Long(chatting_id)); params.put("user_read", 0);// user_read:用户没有读过的信息 List<ChattingLog> logs = this.chattinglogService .query("select obj from ChattingLog obj where obj.chatting.id=:chatting_id and obj.user_read=:user_read order by addTime asc", params, -1, -1); for (ChattingLog log : logs) { log.setUser_read(1);// 标记为用户已读 this.chattinglogService.update(log); } HttpSession session = request.getSession(false); String chatting_session = CommUtil.null2String(session .getAttribute("chatting_session")); if (session != null && !session.equals("")) { refresh_map.put("chatting_session", chatting_session); } List<Map> cl_list = new ArrayList<Map>(); for(ChattingLog obj : logs){ if(obj.getUser_id() != null && !obj.getUser_id().equals("")){ Map cl_map = new HashMap(); cl_map.put("user_name", obj.getChatting().getUser_name()); cl_map.put("addTime", CommUtil.formatLongDate(obj.getAddTime())); cl_map.put("content", obj.getContent()); User usr = this.userService.getObjById(CommUtil.null2Long(obj.getUser_id())); if(usr.getSex() == 0){ cl_map.put("profile_photo", this.configService.getSysConfig().getImageWebServer()+"/"+"resources"+"/"+"style"+"/"+"common"+"/"+"images"+"/"+"member0.png"); } if(usr.getSex() == 1){ cl_map.put("profile_photo", this.configService.getSysConfig().getImageWebServer()+"/"+"resources"+"/"+"style"+"/"+"common"+"/"+"images"+"/"+"member1.png"); } if(usr.getSex() == -1){ cl_map.put("profile_photo", this.configService.getSysConfig().getImageWebServer()+"/"+"resources"+"/"+"style"+"/"+"common"+"/"+"images"+"/"+"member.png"); } cl_map.put("kf_name", obj.getChatting().getConfig().getKf_name()); cl_list.add(cl_map); }else{ Map cl_map = new HashMap(); cl_map.put("profile_photo", this.configService.getSysConfig().getImageWebServer()+"/"+"resources"+"/"+"style"+"/"+"common"+"/"+"images"+"/"+"loader.png"); cl_map.put("kf_name", obj.getChatting().getConfig().getKf_name()); cl_map.put("chatting_time", CommUtil.formatLongDate(obj.getAddTime())); cl_map.put("chatting_font_colour", obj.getFont_colour()); cl_map.put("chatting_font", obj.getFont()); cl_map.put("chatting_font_size", obj.getFont_size()); cl_map.put("content", obj.getContent()); cl_list.add(cl_map); } } refresh_map.put("cl_list", cl_list); } if(refresh_map.isEmpty()){ result = new Result(1,"暂时还没有聊天记录"); }else{ result = new Result(0,"success",refresh_map); } } } try { response.getWriter().print(Json.toJson(result, JsonFormat.compact())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 加载店铺评分信息 * * @param store * @param mv */ private void generic_evaluate(Store store, ModelAndView mv) { double description_result = 0; double service_result = 0; double ship_result = 0; GoodsClass gc = this.goodsclassService .getObjById(store.getGc_main_id()); if (store != null && gc != null && store.getPoint() != null) { float description_evaluate = CommUtil.null2Float(gc .getDescription_evaluate()); float service_evaluate = CommUtil.null2Float(gc .getService_evaluate()); float ship_evaluate = CommUtil.null2Float(gc.getShip_evaluate()); float store_description_evaluate = CommUtil.null2Float(store .getPoint().getDescription_evaluate()); float store_service_evaluate = CommUtil.null2Float(store.getPoint() .getService_evaluate()); float store_ship_evaluate = CommUtil.null2Float(store.getPoint() .getShip_evaluate()); // 计算和同行比较结果 description_result = CommUtil.div(store_description_evaluate - description_evaluate, description_evaluate); service_result = CommUtil.div(store_service_evaluate - service_evaluate, service_evaluate); ship_result = CommUtil.div(store_ship_evaluate - ship_evaluate, ship_evaluate); } if (description_result > 0) { mv.addObject("description_css", "red"); mv.addObject("description_css1", "bg_red"); mv.addObject("description_type", "高于"); mv.addObject( "description_result", CommUtil.null2String(CommUtil.mul(description_result, 100) > 100 ? 100 : CommUtil.mul(description_result, 100)) + "%"); } if (description_result == 0) { mv.addObject("description_css", "orange"); mv.addObject("description_css1", "bg_orange"); mv.addObject("description_type", "持平"); mv.addObject("description_result", "-----"); } if (description_result < 0) { mv.addObject("description_css", "green"); mv.addObject("description_css1", "bg_green"); mv.addObject("description_type", "低于"); mv.addObject( "description_result", CommUtil.null2String(CommUtil.mul(-description_result, 100)) + "%"); } if (service_result > 0) { mv.addObject("service_css", "red"); mv.addObject("service_css1", "bg_red"); mv.addObject("service_type", "高于"); mv.addObject("service_result", CommUtil.null2String(CommUtil.mul(service_result, 100)) + "%"); } if (service_result == 0) { mv.addObject("service_css", "orange"); mv.addObject("service_css1", "bg_orange"); mv.addObject("service_type", "持平"); mv.addObject("service_result", "-----"); } if (service_result < 0) { mv.addObject("service_css", "green"); mv.addObject("service_css1", "bg_green"); mv.addObject("service_type", "低于"); mv.addObject("service_result", CommUtil.null2String(CommUtil.mul(-service_result, 100)) + "%"); } if (ship_result > 0) { mv.addObject("ship_css", "red"); mv.addObject("ship_css1", "bg_red"); mv.addObject("ship_type", "高于"); mv.addObject("ship_result", CommUtil.null2String(CommUtil.mul(ship_result, 100)) + "%"); } if (ship_result == 0) { mv.addObject("ship_css", "orange"); mv.addObject("ship_css1", "bg_orange"); mv.addObject("ship_type", "持平"); mv.addObject("ship_result", "-----"); } if (ship_result < 0) { mv.addObject("ship_css", "green"); mv.addObject("ship_css1", "bg_green"); mv.addObject("ship_type", "低于"); mv.addObject("ship_result", CommUtil.null2String(CommUtil.mul(-ship_result, 100)) + "%"); } } @RequestMapping("/user_chattinglog.json") public void chattingLog(HttpServletRequest request, HttpServletResponse response, String chatting_id, String store_id, String token, String currentPage){ Result result = null; ModelAndView mv = new JModelAndView("", configService.getSysConfig(), this.userConfigService.getUserConfig(), 1, request, response); if(token != null && !token.equals("")){ Map params = new HashMap(); params.put("app_login_token", token); List<User> users = this.userService.query("select obj from User obj where obj.app_login_token=:app_login_token order by obj.addTime desc", params, -1, -1); if(users.isEmpty()){ result = new Result(-100,"token Invalidation"); }else{ int code = -1; User user = users.get(0); List<ChattingLog> chattingLogs = new ArrayList<ChattingLog>(); ChattingLogQueryObject qo = new ChattingLogQueryObject(currentPage, mv, "addTime", "desc"); qo.addQuery("obj.user_id", new SysMap("user_id", user.getId()), "="); qo.addQueryOR("obj.chatting.id", new SysMap("chatting_id", CommUtil.null2Long(chatting_id)), "="); if(store_id != null && !store_id.equals("")){ //qo.addQuery("obj.user_read", new SysMap("user_read", 1), "="); //qo.addQuery("obj.store_read", new SysMap("store_read", 1), "="); qo.setPageSize(20); qo.setCurrentPage(CommUtil.null2Int(currentPage) + 1); IPageList pList = chattinglogService.list(qo); int page = pList.getPages(); chattingLogs = pList.getResult(); if(page <= 1){ code = 1; } }else{ //qo.addQuery("obj.user_read", new SysMap("user_read", 1), "="); //qo.addQuery("obj.plat_read", new SysMap("plat_read", 1), "="); qo.setPageSize(20); int pages = CommUtil.null2Int(currentPage) + 1; qo.setCurrentPage(pages); IPageList pList = chattinglogService.list(qo); chattingLogs = pList.getResult(); int page = pList.getPages(); /*if(page <= 1){ code = 1; }*/ } /*if(code == 1){ result = new Result(-1, "No history chat"); }else{*/ List<Map> list = new ArrayList<Map>(); for(ChattingLog log : chattingLogs){ Map logmap = new HashMap(); logmap.put("user_read", log.getUser_read()); logmap.put("user_id", log.getUser_id()); logmap.put("addTime", log.getAddTime()); logmap.put("store_read", log.getStore_read()); logmap.put("plat_read", log.getPlat_read()); logmap.put("id", log.getId()); logmap.put("content", log.getContent()); list.add(logmap); //} //JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(chattingLogs)); } Collections.reverse(list); result = new Result(0, list); } }else{ result = new Result(-100, "token为空"); } response.setContentType("text/plain"); response.setHeader("Cache-Control", "no-cache"); response.setCharacterEncoding("UTF-8"); PrintWriter writer; try { writer = response.getWriter(); writer.print(Json.toJson(result, JsonFormat.compact())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.gsccs.sme.shiro.client; import org.apache.shiro.authc.UsernamePasswordToken; /** * 类功能说明 TODO:自定义Token * * @author x.d zhang * @version V2.0 */ public class UserPwdSiteToken extends UsernamePasswordToken { private static final long serialVersionUID = -3217596468830869181L; private String captcha; private Long site; public Long getSite() { return site; } public void setSite(Long site) { this.site = site; } public String getCaptcha() { return captcha; } public void setCaptcha(String captcha) { this.captcha = captcha; } public UserPwdSiteToken(String username, String password, boolean rememberMe, String host, String captcha) { super(username, password, rememberMe, host); this.captcha = captcha; } public UserPwdSiteToken() { super(); } }
import java.awt.EventQueue; import java.sql.*; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JComboBox; import com.jgoodies.forms.layout.FormLayout; import com.jgoodies.forms.layout.ColumnSpec; import com.jgoodies.forms.layout.RowSpec; import com.jgoodies.forms.factories.FormFactory; import javax.swing.JButton; import javax.swing.JLabel; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class AddSoap { private JFrame frame; /** * Launch the application. */ public static void runAddSoap(final long phno, final String cartName) { EventQueue.invokeLater(new Runnable() { public void run() { try { AddSoap window = new AddSoap(phno, cartName); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. * @throws SQLException */ public AddSoap(long phno, String cartName) { initialize(phno, cartName); } /** * Initialize the contents of the frame. * @throws SQLException */ private int getInt(String s) { if(s == "1") return 1; else if(s == "2") return 2; return 1; } private String getString(int i) { switch(i) { case 1 : return("1"); case 2 : return("2"); case 3 : return("3"); case 4 : return("4"); case 5 : return("5"); case 6 : return("6"); case 7 : return("7"); case 8 : return("8"); case 9 : return("9"); case 10 : return("10"); case 101: return("101"); case 102: return("102"); case 103: return("103"); case 104: return("104"); case 106: return("106"); case 108: return("108"); case 109: return("109"); } return("1"); } private void initialize(final long phno, final String cartName) { frame = new JFrame(); frame.setBounds(100, 100, 677, 343); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Connection con; String[] values = new String[4]; try { con = DriverManager.getConnection("jdbc:mysql://localhost/Supermarket", "root", "mysql_divya"); Statement st; st = con.createStatement(); ResultSet rs = st.executeQuery("select name,brand from items where type='Soap'"); int i=0; while(rs.next()) values[i++]=rs.getString(2)+" - " +rs.getString(1); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } final JComboBox Products = new JComboBox(values); Products.setBounds(73, 83, 268, 34); frame.getContentPane().add(Products); Products.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { int c; float f; final Statement st; final Connection con; con = DriverManager.getConnection("jdbc:mysql://localhost/Supermarket", "root", "mysql_divya"); st = con.createStatement(); String shampoo = (String) Products.getItemAt(Products.getSelectedIndex()); final String arr[] = shampoo.split(" - "); final ResultSet rs = st.executeQuery("select qty,code,price from items where type='Soap' and brand = \"" +arr[0]+"\" and name=\""+arr[1]+"\"; "); int i=0; while(rs.next()) { i = rs.getInt(1); c = rs.getInt(2); f = rs.getFloat(3); } final String[] qty = new String[i]; while(i>0) { qty[i-1]= Integer.toString(i); i--; } final JComboBox Quantity = new JComboBox(qty); Quantity.setBounds(359, 83, 69, 34); frame.getContentPane().add(Quantity); JButton btnBuy = new JButton("Buy!"); btnBuy.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { final Connection con; con = DriverManager.getConnection("jdbc:mysql://localhost/Supermarket", "root", "mysql_divya"); Statement st; int code=0; float price=0; st = con.createStatement(); ResultSet rs = st.executeQuery("select code, price from items where type='Soap' and brand = \""+arr[0]+"\" and name = \""+arr[1]+"\";"); while(rs.next()) { code = rs.getInt(1); price = rs.getFloat(2); } System.out.println("COde is : "+ code); int q=0; String Q = (String) Quantity.getItemAt(Quantity.getSelectedIndex()); System.out.println(Q); q = Integer.parseInt(Q); System.out.println("Quantity is "+ q); //if exists, add qty ResultSet r = st.executeQuery("select code from cart where code = " + code + " and cartname = \'" + cartName + "\';"); int flag = 0; while(r.next()) { flag = 1; st.executeUpdate("update cart set qty = "+ getString(q) +" where code = " + code + " and cartname = \'" + cartName + " \';"); frame.setVisible(false); break; } if(flag == 0) { st.executeUpdate("insert into cart values (\'" + cartName+ "\',"+phno+","+ code +","+getString(q)+","+price+");"); frame.setVisible(false); } } catch (SQLException e1) { e1.printStackTrace(); } } }); btnBuy.setBounds(462, 88, 117, 25); frame.getContentPane().add(btnBuy); } catch (SQLException e1) { e1.printStackTrace(); } } }); JLabel lblQty = new JLabel("Qty"); lblQty.setBounds(369, 46, 37, 25); frame.getContentPane().add(lblQty); JLabel lblProduct = new JLabel("Product"); lblProduct.setBounds(162, 46, 69, 25); frame.getContentPane().add(lblProduct); } }
package com.spring.testable.mock.pojo.dto; import lombok.Data; /** * @author caijie */ @Data public class UserDto { private String account; }
package baguchan.earthmobsmod.tag; import baguchan.earthmobsmod.handler.EarthFluids; import baguchan.earthmobsmod.handler.EarthTags; import net.minecraft.data.DataGenerator; import net.minecraft.data.FluidTagsProvider; public class EarthFluidTagsProvider extends FluidTagsProvider { public EarthFluidTagsProvider(DataGenerator generator) { super(generator); } @Override public void registerTags() { this.getBuilder(EarthTags.Fluids.MUD_WATER).add(EarthFluids.MUD_WATER, EarthFluids.MUD_WATER_FLOW); } @Override public String getName() { return "Earth Fluid Tags"; } }
package pl.szymonleyk.jpa; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; public class AddressRepository implements Repository<Address> { public void insert(Address address) { EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("db-unit"); EntityManager em = emf.createEntityManager(); EntityTransaction et = em.getTransaction(); try { et.begin(); // otwieram em.persist(address); // utrwalam obiekt w bazie et.commit(); // zapis } catch (Exception e) { et.rollback(); } } public void delete(Address v) { } public Address select(int id) { EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("db-unit"); EntityManager em = emf.createEntityManager(); return em.find(Address.class, id); } }
/** * */ package eierlegendeWollmilchSau; /** * @author Otto Werse * */ public enum EigeneEnum { EINS_ZUSTAND(0), ZWEI_ZUSTAND(1); int nummer; private EigeneEnum(int i) { this.nummer = i; } @Override public String toString() { String s = ""; switch (this.nummer) { case 1: s = "Zustand 1"; break; case 2: s = "Zustand 2"; break; default: break; } return s; } }
package Controller; import java.util.List; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import Entity.GioHang; import Entity.TaiKhoan; import Services.DanhMucSer; import Services.QSportSer; import Services.SanPhamSer; import Services.TaiKhoanSer; @Controller @RequestMapping("/User") public class TaiKhoanComtroller { @Autowired SanPhamSer sanPhamSer; @Autowired DanhMucSer danhMucSer; @Autowired QSportSer qSportSer; @Autowired TaiKhoanSer taiKhoanSer; @GetMapping public String Default(ModelMap mdMap, HttpSession httpSession) { /* Show ten tai khoan */ if(httpSession.getAttribute("TaiKhoan") != null) { String tenHT =(String) httpSession.getAttribute("TaiKhoan"); int idTK = (Integer) httpSession.getAttribute("idTaiKhoan"); mdMap.addAttribute("user",taiKhoanSer.ShowTaiKhoan(idTK)); mdMap.addAttribute("Quyen", taiKhoanSer.ShowTaiKhoan(idTK).getPhanQuyen().getTenQuyen()); mdMap.addAttribute("tenHT", tenHT); } /* show thong tin QSport*/ mdMap.addAttribute("QSport",qSportSer.showQSport()); /* So luong trong gio hang */ if(httpSession.getAttribute("GioHang") != null) { List<GioHang> lstGioHangs = (List<GioHang>) httpSession.getAttribute("GioHang"); mdMap.addAttribute("soLuongTrongGio", lstGioHangs.size()); mdMap.addAttribute("lstGioHang", lstGioHangs); }else { mdMap.addAttribute("soLuongTrongGio", 0); } return "user"; } @GetMapping("/Update") @ResponseBody String update(HttpSession httpSession, @RequestParam String hoTen, @RequestParam String GioiTinh,@RequestParam String sdt, @RequestParam String diachi, @RequestParam String email, @RequestParam String matkhau){ int idTK = (Integer) httpSession.getAttribute("idTaiKhoan"); TaiKhoan tk = new TaiKhoan(); tk.setHoTen(hoTen); tk.setGioiTinh(GioiTinh); tk.setSdt(sdt); tk.setEmail(email); tk.setDiaChi(diachi); tk.setMatKhau(matkhau); taiKhoanSer.update(tk, idTK); return ""; } @GetMapping("/updateTrangThai") @ResponseBody String updateTrangThai(@RequestParam int idTaiKhoan, @RequestParam String trangthai) { taiKhoanSer.updateTrangThai(idTaiKhoan, trangthai); return ""; } }