text
stringlengths
10
2.72M
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; import static java.lang.Math.min; public class ThirtyOne { public static List<List<String>> partition(List<String> dataStr, Integer nLines) { List<List<String>> returnList = new ArrayList<>(); for(int i = 0; i < dataStr.size(); i += nLines) { returnList.add(dataStr.subList(i, min((i + nLines), dataStr.size()))); } return returnList; } public static List<Map<String, Integer>> splitWords(List<String> dataStr) { List<Map<String, Integer>> result = new ArrayList<>(); class InnerSWC { public List<String> scan(List<String> strData) { List<String> returnList = new ArrayList<>(); for(String strLine : strData) { String[] wordsOfTheLine = strLine.replaceAll("[\\W_]+", " ").toLowerCase().split(" "); returnList.addAll(Arrays.asList(wordsOfTheLine)); } return returnList; } public List<String> removeStopWords(List<String> wordList) { List<String> returnList = new ArrayList<>(); String stopWordsLine = null; String[] stopWordsArray = null; try{ // Takes a list of words and returns a copy with all stop words removed BufferedReader stopWordsReader = new BufferedReader(new FileReader("../stop_words.txt")); stopWordsLine = stopWordsReader.readLine(); stopWordsReader.close(); } catch (IOException e) { e.printStackTrace(); } if(stopWordsLine != null && !stopWordsLine.trim().equals("")) { stopWordsArray = stopWordsLine.split(","); } List<String> stopWordList = new ArrayList<>(Arrays.asList(stopWordsArray)); for(String word : wordList) { if(!word.trim().equals("") && word.length() >= 2 && !stopWordList.contains(word)) { returnList.add(word); } } return returnList; } } InnerSWC iswc = new InnerSWC(); List<String> words = iswc.removeStopWords(iswc.scan(dataStr)); for(String w : words) { Map<String, Integer> swlTMap = new HashMap<>(); swlTMap.put(w, 1); result.add(swlTMap); } return result; } public static Map<String, List<Map<String, Integer>>> regroup(List<List<Map<String, Integer>>> pairsList) { Map<String, List<Map<String, Integer>>> mapping = new HashMap<>(); for(List<Map<String, Integer>> tList : pairsList) { for(Map<String, Integer> pairs : tList) { //System.out.println("yes"); for(Map.Entry p : pairs.entrySet()) { if(mapping.containsKey(p.getKey())) { List<Map<String, Integer>> pList = new ArrayList<>(); pList = mapping.get(p.getKey()); Map<String, Integer> tempMap = new HashMap<>(); tempMap.put((String)p.getKey(), (Integer)p.getValue()); pList.add(tempMap); mapping.put((String)p.getKey(), pList); } else { List<Map<String, Integer>> pList = new ArrayList<>(); Map<String, Integer> tempMap = new HashMap<>(); tempMap.put((String)p.getKey(), (Integer)p.getValue()); pList.add(tempMap); mapping.put((String)p.getKey(), pList); } } } } return mapping; } public static Map<String, Integer> countWords(Map.Entry<String, List<Map<String, Integer>>> mapping) { Map<String, Integer> result = new HashMap<>(); List<Integer> valueList = new ArrayList<>(); for(Map<String, Integer> test : mapping.getValue()) { for(Map.Entry s : test.entrySet()) { valueList.add((Integer)s.getValue()); } } Integer sum = valueList.stream().reduce(0, (element1, element2) -> element1 + element2); result.put(mapping.getKey(), sum); return result; } public static List<String> readFile(String pathToFile) { List<String> lineList = new ArrayList<>(); try { BufferedReader articleReader = null; articleReader = new BufferedReader(new FileReader(pathToFile)); String strLine = null; strLine = articleReader.readLine(); while(strLine != null) { if(!strLine.trim().equals("")) { //String[] wordsOfTheLine = strLine.replaceAll("[\\W_]+", " ").toLowerCase().split(" "); //lineList.addAll(Arrays.asList(wordsOfTheLine)); lineList.add(strLine); } strLine = articleReader.readLine(); } articleReader.close(); } catch (IOException e) { e.printStackTrace(); } return lineList; } public static List<Map.Entry<String, Integer>> sort(List<Map<String, Integer>> wordFreqsList) { Map<String, Integer> wordFreqs = new HashMap<>(); for(Map<String, Integer> m : wordFreqsList) { for(Map.Entry e : m.entrySet()) { wordFreqs.put((String)e.getKey(), (Integer)e.getValue()); } } //List<Map.Entry<String, Integer>> result = new ArrayList<>(); List<Map.Entry<String, Integer>> sortedMapList = new ArrayList<>(wordFreqs.entrySet()); Collections.sort(sortedMapList, (o1, o2) -> o2.getValue() - o1.getValue()); return sortedMapList; } public static void main(String args[]) { List<List<Map<String, Integer>>> splits = partition(readFile(args[0]), 200).stream().map((strList) -> splitWords(strList)).collect(Collectors.toList()); Map<String, List<Map<String, Integer>>> splitsPerWord = regroup(splits); List<Map<String, Integer>> wordFreqs = splitsPerWord.entrySet().stream().map((argsC) -> countWords(argsC)).collect(Collectors.toList()); List<Map.Entry<String, Integer>> wordFreqsSorted = sort(wordFreqs); for(Map.Entry<String, Integer> entry : wordFreqsSorted.subList(0, 25)) { System.out.println(entry.getKey() + " - " + entry.getValue()); } } }
package classes; public class Bmw extends Cars{ private int roadservicemonths; public Bmw(String size, String name, int wheels, int doors, int gears, boolean manual, int currentgear, int roadservicemonths) { super(size, name, wheels, doors, gears, manual, currentgear); this.roadservicemonths = roadservicemonths; } public int getRoadservicemonths() { return roadservicemonths; } public void setRoadservicemonths(int roadservicemonths) { this.roadservicemonths = roadservicemonths; } public void speedup(int rate){ // //int newvel=getCurrentvel()+rate; // if(newvel==0){ // // } // else if(newvel>0 && newvel <=10){ // changegear(1); // } // else if(newvel>10 && newvel <=20){ // changegear(2); // } // else if(newvel>20 && newvel <=30){ // changegear(3); // } // else{ // changegear(4); // } } }
package sr.hakrinbank.intranet.api.model; import org.hibernate.envers.Audited; import javax.persistence.*; import java.util.Date; /** * Created by clint on 6/22/17. */ @Entity @Audited public class Gallery { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Temporal(TemporalType.TIMESTAMP) private Date date; private String name; private String url; @Lob private byte[] thumbnail; private String thumbnailName; @Column(nullable = false, columnDefinition = "TINYINT", length = 1) private boolean deleted; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public byte[] getThumbnail() { return thumbnail; } public void setThumbnail(byte[] thumbnail) { this.thumbnail = thumbnail; } public boolean isDeleted() { return deleted; } public void setDeleted(boolean deleted) { this.deleted = deleted; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getThumbnailName() { return thumbnailName; } public void setThumbnailName(String thumbnailName) { this.thumbnailName = thumbnailName; } }
package guillaumeagis.perk4you.api; import android.app.Activity; /** * * You need to implement this class and call your api from here */ public final class OnlineManager implements IAPIManager { @Override public void loadData(final Activity activity) { // TODO : CALL your API } }
package com.layduo.framework.manager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.layduo.framework.shiro.web.session.SpringSessionValidationScheduler; import javax.annotation.PreDestroy; /** * 确保应用退出时能关闭后台线程 * * @author layduo */ @Component public class ShutdownManager { private static final Logger logger = LoggerFactory.getLogger("sys-user"); /** * @Autowired(required = false)表示忽略当前要注入的bean,如果有直接注入,没有跳过,不会报错。 * 默认@Autowired(required = true)表示注入的bean必须存在,不存在会报错 */ @Autowired(required = false) private SpringSessionValidationScheduler springSessionValidationScheduler; /** * 从Java EE 5规范开始,Servlet中增加了两个影响Servlet生命周期的注解(Annotion); * @PostConstruct和 @PreDestroy。这两个注解被用来修饰一个非静态的void()方法 * @PostConstruct和 @PreDestroy 方法 实现bean初始化前和销毁之前进行的操作 * 被@PostConstruct修饰的方法会在服务器加载Servle的时候运行,并且只会被服务器执行一次、不得有任何参数、不得抛出已检查异常。 * PostConstruct在构造函数之后执行,init()方法之前执行,主要是加载一些缓存数据。PreDestroy()方法在destroy()方法执行执行之后执行 * 被注解的Servlet生命周期如下: * 服务器加载servlet -> servlet构造函数 -> PostConstruct -> init -> servlet -> destory -> PreDestroy ->服务器卸载servlet完毕 */ @PreDestroy public void destroy() { shutdownSpringSessionValidationScheduler(); shutdownAsyncManager(); } /** * 停止Seesion会话检查 */ private void shutdownSpringSessionValidationScheduler() { if (springSessionValidationScheduler != null && springSessionValidationScheduler.isEnabled()) { try { logger.info("====关闭会话验证任务===="); springSessionValidationScheduler.disableSessionValidation(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } /** * 停止异步执行任务 */ private void shutdownAsyncManager() { try { logger.info("====关闭后台任务任务线程池===="); AsyncManager.me().shutdown(); } catch (Exception e) { logger.error(e.getMessage(), e); } } }
package com.example.trialattemptone; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import com.example.trialattemptone.Creators.AssessmentType; import com.example.trialattemptone.database.DataSource; public class AddTypeScreen extends AppCompatActivity { public DataSource mDataSource; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_type_screen); mDataSource = new DataSource(this); mDataSource.open(); } public void cancelTypeButtonPressed(View view) { this.finish(); } public void saveTypeButtonPressed(View view) { EditText typeTitleText; typeTitleText = findViewById(R.id.typeTitleET); String typeTitleString = typeTitleText.getText().toString(); AssessmentType assessmentType = new AssessmentType(typeTitleString); mDataSource.addAssessmentType(assessmentType); this.finish(); } }
package com.alibaba.druid.bvt.sql.mysql.createTable; import com.alibaba.druid.sql.MysqlTest; import com.alibaba.druid.sql.ast.SQLStatement; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlCreateTableStatement; import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; import java.util.List; public class MySqlCreateTableTest105 extends MysqlTest { public void test_0() throws Exception { String sql = "CREATE DIMENSION TABLE tpch_junlan.nation (\n" + " n_nationkey int NOT NULL COMMENT '',\n" + " n_name varchar NOT NULL COMMENT '',\n" + " n_regionkey int NOT NULL COMMENT '',\n" + " n_comment varchar COMMENT '',\n" + " PRIMARY KEY (N_NATIONKEY)\n" + ")\n" + "OPTIONS (UPDATETYPE='realtime')\n" + "COMMENT ''"; MySqlStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); MySqlCreateTableStatement stmt = (MySqlCreateTableStatement) statementList.get(0); assertEquals(1, statementList.size()); assertEquals(5, stmt.getTableElementList().size()); assertEquals("CREATE DIMENSION TABLE tpch_junlan.nation (\n" + "\tn_nationkey int NOT NULL COMMENT '',\n" + "\tn_name varchar NOT NULL COMMENT '',\n" + "\tn_regionkey int NOT NULL COMMENT '',\n" + "\tn_comment varchar COMMENT '',\n" + "\tPRIMARY KEY (N_NATIONKEY)\n" + ")\n" + "OPTIONS (UPDATETYPE = 'realtime') COMMENT ''", stmt.toString()); } }
package lka.wine.dao; import java.math.BigDecimal; public class WineSummary extends Wine { private String pricePer; private BigDecimal minPrice; private BigDecimal avgPrice; private BigDecimal maxPrice; private int qty; private int qtyOnHand; private int minRating; private BigDecimal avgRating; private int maxRating; public String getPricePer() { return pricePer; } public void setPricePer(String pricePer) { this.pricePer = pricePer; } public BigDecimal getMinPrice() { return minPrice; } public void setMinPrice(BigDecimal minPrice) { this.minPrice = minPrice; } public BigDecimal getAvgPrice() { return avgPrice; } public void setAvgPrice(BigDecimal avgPrice) { this.avgPrice = avgPrice; } public BigDecimal getMaxPrice() { return maxPrice; } public void setMaxPrice(BigDecimal maxPrice) { this.maxPrice = maxPrice; } public int getQty() { return qty; } public void setQty(int qty) { this.qty = qty; } public int getQtyOnHand() { return qtyOnHand; } public void setQtyOnHand(int qtyOnHand) { this.qtyOnHand = qtyOnHand; } public int getMinRating() { return minRating; } public void setMinRating(int minRating) { this.minRating = minRating; } public BigDecimal getAvgRating() { return avgRating; } public void setAvgRating(BigDecimal avgRating) { this.avgRating = avgRating; } public int getMaxRating() { return maxRating; } public void setMaxRating(int maxRating) { this.maxRating = maxRating; } }
/* * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.jet.contrib.mqtt; import com.hazelcast.jet.JetException; import com.hazelcast.jet.Job; import com.hazelcast.jet.SimpleTestInClusterSupport; import com.hazelcast.jet.contrib.mqtt.impl.ConcurrentMemoryPersistence; import com.hazelcast.jet.pipeline.Pipeline; import com.hazelcast.jet.pipeline.Sink; import com.hazelcast.jet.pipeline.test.TestSources; import com.hazelcast.jet.retry.RetryStrategies; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.MqttSecurityException; import org.junit.After; import org.junit.BeforeClass; import org.junit.Test; import org.testcontainers.containers.Network; import org.testcontainers.containers.ToxiproxyContainer; import org.testcontainers.containers.ToxiproxyContainer.ContainerProxy; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import static com.hazelcast.internal.util.UuidUtil.newUnsecureUuidString; import static com.hazelcast.jet.contrib.mqtt.SecuredMosquittoContainer.PASSWORD; import static com.hazelcast.jet.contrib.mqtt.SecuredMosquittoContainer.USERNAME; import static java.util.stream.Collectors.toList; import static java.util.stream.IntStream.range; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertTrue; public class MqttSinkTest extends SimpleTestInClusterSupport { private static final int ITEM_COUNT = 1000; private MosquittoContainer mosquitto; private MqttClient client; private Job job; @BeforeClass public static void beforeClass() { initialize(2, null); } @After public void teardown() throws MqttException { if (job != null) { job.cancel(); } if (client != null) { try { client.disconnect(); } catch (MqttException exception) { logger.warning("Exception when disconnecting", exception); } client.close(); } if (mosquitto != null) { mosquitto.stop(); } } @Test public void test_retryStrategy() throws MqttException { try ( Network network = Network.newNetwork(); ToxiproxyContainer toxiproxy = initToxiproxy(network); ) { mosquitto = new MosquittoContainer().withNetwork(network); mosquitto.start(); ContainerProxy proxy = toxiproxy.getProxy(mosquitto, MosquittoContainer.PORT); String broker = MosquittoContainer.connectionString(proxy); ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>(); client = mqttClient(broker); client.subscribe("retry", 2, (topic, message) -> map.put(payload(message), topic)); Pipeline p = Pipeline.create(); Sink<Integer> sink = MqttSinks.builder() .broker(broker) .topic("retry") .connectOptionsFn(() -> { MqttConnectOptions options = new MqttConnectOptions(); options.setAutomaticReconnect(true); options.setCleanSession(false); return options; }) .retryStrategy(RetryStrategies.indefinitely(1000)) .messageFn(MqttSinkTest::message) .build(); p.readFrom(TestSources.items(range(0, ITEM_COUNT).boxed().collect(toList()))) .rebalance() .writeTo(sink); job = instance().getJet().newJob(p); assertTrueEventually(() -> assertTrue(map.size() > ITEM_COUNT / 2)); proxy.setConnectionCut(true); sleepSeconds(1); proxy.setConnectionCut(false); assertTrueEventually(() -> assertTrue(client.isConnected())); client.subscribe("retry", 2, (topic, message) -> map.put(payload(message), topic)); assertEqualsEventually(map::size, ITEM_COUNT); } } @Test public void test() throws MqttException { mosquitto = new MosquittoContainer(); mosquitto.start(); testInternal(new MqttConnectOptions(), MqttSinks.builder(), (counter, job) -> { job.join(); assertEqualsEventually(ITEM_COUNT, counter); }); } @Test public void testSecured() throws MqttException { mosquitto = new SecuredMosquittoContainer(); mosquitto.start(); testInternal(optionsWithAuth(), MqttSinks.<Integer>builder().auth(USERNAME, PASSWORD.toCharArray()), (counter, job) -> { job.join(); assertEqualsEventually(ITEM_COUNT, counter); }); } @Test public void testAccessWithoutPassword() throws MqttException { mosquitto = new SecuredMosquittoContainer(); mosquitto.start(); testInternal(optionsWithAuth(), MqttSinks.builder(), (ignored, job) -> assertThatThrownBy(job::join) .hasCauseInstanceOf(JetException.class) .hasRootCauseInstanceOf(MqttSecurityException.class) .hasMessageContaining("Not authorized to connect")); } @Test public void testWrongPassword() throws MqttException { mosquitto = new SecuredMosquittoContainer(); mosquitto.start(); testInternal(optionsWithAuth(), MqttSinks.<Integer>builder().auth(USERNAME, "wrongPassword" .toCharArray()), (ignored, job) -> assertThatThrownBy(job::join) .hasCauseInstanceOf(JetException.class) .hasRootCauseInstanceOf(MqttSecurityException.class) .hasMessageContaining("Not authorized to connect")); } private void testInternal( MqttConnectOptions options, MqttSinkBuilder<Integer> builder, BiConsumer<AtomicInteger, Job> assertFn ) throws MqttException { String broker = mosquitto.connectionString(); client = new MqttClient(broker, newUnsecureUuidString(), new ConcurrentMemoryPersistence()); client.connect(options); AtomicInteger counter = new AtomicInteger(); client.subscribe("topic", 0, (topic, message) -> counter.incrementAndGet()); Pipeline p = Pipeline.create(); Sink<Integer> sink = builder .broker(broker) .topic("topic") .messageFn(MqttSinkTest::message) .build(); p.readFrom(TestSources.items(range(0, ITEM_COUNT).boxed().collect(toList()))) .rebalance() .writeTo(sink); Job job = instance().getJet().newJob(p); assertFn.accept(counter, job); } private static MqttClient mqttClient(String broker) throws MqttException { MqttClient client = new MqttClient(broker, newUnsecureUuidString(), new ConcurrentMemoryPersistence()); MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setAutomaticReconnect(true); connectOptions.setCleanSession(false); client.connect(connectOptions); return client; } private static MqttConnectOptions optionsWithAuth() { MqttConnectOptions options = new MqttConnectOptions(); options.setUserName(USERNAME); options.setPassword(PASSWORD.toCharArray()); return options; } private static byte[] intToByteArray(int value) { return new byte[]{ (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value}; } private static int byteArrayToInt(byte[] data) { int val = 0; for (int i = 0; i < 4; i++) { val = val << 8; val = val | (data[i] & 0xFF); } return val; } private static MqttMessage message(int value) { MqttMessage message = new MqttMessage(intToByteArray(value)); message.setQos(2); return message; } private static int payload(MqttMessage message) { return byteArrayToInt(message.getPayload()); } private static ToxiproxyContainer initToxiproxy(Network network) { ToxiproxyContainer toxiproxy = new ToxiproxyContainer().withNetwork(network); toxiproxy.start(); return toxiproxy; } }
package com.java.practice.array; /** * Given an array of non-negative integers nums, you are initially positioned at the first index of the array. * <p> * Each element in the array represents your maximum jump length at that position. * <p> * Your goal is to reach the last index in the minimum number of jumps. * <p> * You can assume that you can always reach the last index. * <p> * <p> * <p> * Example 1: * <p> * Input: nums = [2,3,1,1,4] * Output: 2 * Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. */ public class Ladder { public static void main(String[] args) { //int[] A = {2, 3, 1, 1, 4}; //int[] A = {2, 0, 0, 1, 4}; int[] A = {1, 4, 3, 7, 1, 2, 6, 7, 6, 10}; int noOfJump = jump(A); System.out.println((noOfJump > 0 ? noOfJump : "Not Possible")); } public static int jump(int[] A) { if (A.length <= 1) { return 0; } int ladder = A[0]; // consider largest ladder int stair = A[0]; // consider largest ladder stairs int jump = 1; // consider initial 1 jump required for (int level = 1; level < A.length; level++) { // condition-1: if all level consumed if (level == A.length - 1) { return jump; } // condition-2 : if found largest ladder on level, then keep it for future if (ladder < level + A[level]) { ladder = level + A[level]; } // exhaust the stair by each level stair--; // condition-3 : if all stair are exhausted then assign remaining stair from // ladder if (stair == 0) { jump++; stair = ladder - level; // condition-4 : special case if ladder stair are also exhausted before reaching // to the end if (stair == 0) { return 0; } } } return jump; } public static int jump1(int[] A) { if (A.length <= 1) { return 0; } int ladder = A[0]; int jump = 0; for (int i = 1; i < A.length; i++) { if (i == A.length - 1) { return jump; } if (ladder < i + A[i]) { ladder = i + A[i]; } } return jump; } }
package ua.siemens.dbtool.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import ua.siemens.dbtool.service.ImageService; import javax.servlet.ServletException; import java.io.IOException; import java.net.MalformedURLException; /** * The class is responsible of processing image related requests * * @author Perevoznyk Pavlo * created on 17 may 2017 * @version 1.0 */ @RestController @RequestMapping("api/images") public class ImageController { private static final Logger LOG = LoggerFactory.getLogger(ImageController.class); private ImageService imageService; @Autowired public ImageController(ImageService imageService) { this.imageService = imageService; } @RequestMapping(value = "getImage/{imageId}", method = RequestMethod.GET) public ResponseEntity<Resource> getImage(@PathVariable(name = "imageId") long imageId) { LOG.debug(">> getImage(), imageId={}", imageId); Resource image = null; try { image = imageService.findById(imageId); } catch (MalformedURLException e) { e.printStackTrace(); return new ResponseEntity<>(HttpStatus.NOT_FOUND); } LOG.debug("<< getImage()"); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.IMAGE_JPEG); return new ResponseEntity<>(image, headers, HttpStatus.OK); } @RequestMapping(value = "/uploadUserImage", method = RequestMethod.POST) public String uploadUserImage(@RequestParam("file") MultipartFile file) throws ServletException, IOException { // User user = userService.getAuthenticatedUser(); // if (!file.getContentType().equals("image/jpg") && !file.getContentType().equals("image/jpeg") && !file.getContentType().equals("image/gif") && !file.getContentType().equals("image/png")) { // throw new IllegalStateException("The file you selected is of incorrect type. An image should be .jpg, .gif or .png"); // } // if (file.getSize() > 1024 * 100) { // throw new IllegalStateException("The file you selected is too big. A file must be less than 100 kB."); // } // long imageId = user.getImageId(); // if (imageId != Constants.DEFAULT_IMAGE_ID) { // Image image = imageService.findById(imageId); // image.setData(file.getBytes()); // imageService.update(image); // } else { // Image newImage = new Image(); // newImage.setData(file.getBytes()); // newImage = imageService.save(newImage); // System.out.println(newImage.getId()); // user.setImageId(newImage.getId()); // userService.update(user); // } return "redirect:/users/myPage"; } }
package com.example.administrator.cookman.utils; import android.app.Activity; import android.content.Context; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; /** * Created by PeOS on 2016/8/8 0008. */ public class KeyboardUtil { public static void showKeyboard(Activity activity, boolean isShow){ if(isShow){ activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); } else{ activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); } } public static void showKeyboard(Activity activity, View view, boolean isShow){ if(isShow) ((InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInputFromInputMethod(view.getWindowToken(), 0); else ((InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(view.getWindowToken(),0); } }
package com.cipher.c0753362_mad3125_midterm.activities; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import com.cipher.c0753362_mad3125_midterm.R; public class WebLinksActivity extends AppCompatActivity { WebView webView; String link; Toolbar toolbar; private static final String TAG = "WebLinksActivity"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_weblinks); toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setTitle("Links"); if (getIntent().getExtras()!=null){ link = getIntent().getStringExtra("links"); } webView = findViewById(R.id.webView); webView.getSettings().setLoadsImagesAutomatically(true); webView.getSettings().setJavaScriptEnabled(true); webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); webView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { Log.e(TAG, "onPageFinished: " ); } }); webView.loadUrl(link); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) // Press Back Icon { finish(); } return super.onOptionsItemSelected(item); } }
package week1; //- The user enters a number and the program needs to check whether entered number is Magic one. // Magic number: A number is said to be a Magic number if the sum of its digits are calculated till // a single digit is obtained by recursively adding the sum of its digits. If the single digit comes to be 1 then the number is a magic number. import java.util.Scanner; public class HomeWork4 { public static void main(String args[]) { Scanner input=new Scanner(System.in); System.out.println("Enter the number to be checked: "); String n=input.next(); int sum = 0; while(n.length()>1) { sum = 0; for (int i = 0; i < n.length(); i++) { String c = String.valueOf(n.charAt(i)); sum = sum + Integer.valueOf(c); } n = String.valueOf(sum); } if(Integer.valueOf(n)==1) { System.out.println("Is a Magic Number."); } else { System.out.println("Is not a Magic Number."); } } }
/* * 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 phatnh.customer; import java.io.Serializable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.naming.NamingException; import phatnh.utils.DatabaseUtils; /** * * @author nguyenhongphat0 */ public class CustomerDAO implements Serializable { public String checkLogin(String username, String password) throws NamingException, SQLException { Connection con = null; PreparedStatement pre = null; ResultSet res = null; try { con = DatabaseUtils.getConnection(); String sql = "SELECT * FROM customer WHERE custID = ? AND password = ?"; pre = con.prepareStatement(sql); pre.setString(1, username); pre.setString(2, password); res = pre.executeQuery(); if (res.next()) { return res.getString("custID"); } } finally { if (res != null) { res.close(); } if (pre != null) { pre.close(); } if (con != null) { con.close(); } } return null; } public CustomerDTO getCustomer(String custID) throws NamingException, SQLException { Connection con = null; PreparedStatement pre = null; ResultSet res = null; try { con = DatabaseUtils.getConnection(); String sql = "SELECT * FROM customer WHERE custID = ?"; pre = con.prepareStatement(sql); pre.setString(1, custID); res = pre.executeQuery(); if (res.next()) { CustomerDTO dto = new CustomerDTO(); dto.setCustID(res.getString(1)); dto.setPassword(res.getString(2)); dto.setCustName(res.getString(3)); dto.setLastName(res.getString(4)); dto.setMiddleName(res.getString(5)); dto.setAddress(res.getString(6)); dto.setPhone(res.getString(7)); dto.setCustLevel(res.getInt(8)); return dto; } } finally { if (res != null) { res.close(); } if (pre != null) { pre.close(); } if (con != null) { con.close(); } } return null; } public boolean createCustomer(CustomerDTO dto) throws NamingException, SQLException { Connection con = null; PreparedStatement pre = null; try { con = DatabaseUtils.getConnection(); String sql = "INSERT INTO customer VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; pre = con.prepareStatement(sql); pre.setString(1, dto.getCustID()); pre.setString(2, dto.getPassword()); pre.setString(3, dto.getCustName()); pre.setString(4, dto.getLastName()); pre.setString(5, dto.getMiddleName()); pre.setString(6, dto.getAddress()); pre.setString(7, dto.getPhone()); pre.setInt(8, dto.getCustLevel()); int res = pre.executeUpdate(); return res > 0; } finally { if (pre != null) { pre.close(); } if (con != null) { con.close(); } } } }
package com.containers.model; import lombok.Data; import lombok.EqualsAndHashCode; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; import java.util.Collections; import java.util.HashSet; import java.util.Set; import static javax.persistence.CascadeType.ALL; import static javax.persistence.FetchType.LAZY; @Entity @Data @EqualsAndHashCode(exclude = {"reports"}) public class Container { @Id private String containerIdNumber; private String containerType; private String containerShipOwner; @OneToMany(targetEntity = Report.class, fetch = LAZY, cascade = ALL) private Set<Report> reports = new HashSet<>(); public void addReport(Report report) { if (report == null) { reports = Collections.emptySet(); } else { reports.add(report); } } }
package mergeSort; public class Basic { private int arr[]; private int out[]; int n=0; void printArry() { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+","); //+", a b " + arr[i] System.out.println(""); } void input(int a[]) { arr=a; out=new int[arr.length]; } void sort(int arr[]) { int aux[]=new int[arr.length]; sort(arr, aux, arr.length-1, 0); } void sort(int arr[],int aux[] ,int high ,int low) { if(high<low||high==0) return; int mid =0; mid=(high+low)/2+low; if(high<=mid||high==low) return; sort( arr, aux , mid , low); sort( arr, aux, high , mid+1); merge( arr, aux , high , low,mid); } void merge(int arr[],int aux[] ,int high ,int low,int mid) { int i=0,j=0; for(int arrtemp=0;arrtemp<arr.length;arrtemp++) aux[arrtemp]=arr[arrtemp]; j=mid+1; i=low; for(int k=low;k<=high;k++) { { if(i>mid) arr[k]=aux[j++]; else if(j>high) arr[k]=aux[i++]; else if(aux[i]>aux[j]){ arr[k]=aux[j++]; } else { arr[k]=aux[i++]; } } //System.out.println(arr[i]+" "+arr[j]); } //printArry(); } }
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.test.util; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.hamcrest.core.Is.is; /** * Unit tests for {@link JsonPathExpectationsHelper}. * * @author Rossen Stoyanchev * @author Sam Brannen * @since 3.2 */ class JsonPathExpectationsHelperTests { private static final String CONTENT = """ { 'str': 'foo', 'num': 5, 'bool': true, 'arr': [42], 'colorMap': {'red': 'rojo'}, 'whitespace': ' ', 'emptyString': '', 'emptyArray': [], 'emptyMap': {} }"""; private static final String SIMPSONS = """ { 'familyMembers': [ {'name': 'Homer' }, {'name': 'Marge' }, {'name': 'Bart' }, {'name': 'Lisa' }, {'name': 'Maggie'} ] }"""; @Test void exists() throws Exception { new JsonPathExpectationsHelper("$.str").exists(CONTENT); } @Test void existsForAnEmptyArray() throws Exception { new JsonPathExpectationsHelper("$.emptyArray").exists(CONTENT); } @Test void existsForAnEmptyMap() throws Exception { new JsonPathExpectationsHelper("$.emptyMap").exists(CONTENT); } @Test void existsForIndefinitePathWithResults() throws Exception { new JsonPathExpectationsHelper("$.familyMembers[?(@.name == 'Bart')]").exists(SIMPSONS); } @Test void existsForIndefinitePathWithEmptyResults() throws Exception { String expression = "$.familyMembers[?(@.name == 'Dilbert')]"; assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> new JsonPathExpectationsHelper(expression).exists(SIMPSONS)) .withMessageContaining("No value at JSON path \"" + expression + "\""); } @Test void doesNotExist() throws Exception { new JsonPathExpectationsHelper("$.bogus").doesNotExist(CONTENT); } @Test void doesNotExistForAnEmptyArray() throws Exception { String expression = "$.emptyArray"; assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> new JsonPathExpectationsHelper(expression).doesNotExist(CONTENT)) .withMessageContaining("Expected no value at JSON path \"" + expression + "\" but found: []"); } @Test void doesNotExistForAnEmptyMap() throws Exception { String expression = "$.emptyMap"; assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> new JsonPathExpectationsHelper(expression).doesNotExist(CONTENT)) .withMessageContaining("Expected no value at JSON path \"" + expression + "\" but found: {}"); } @Test void doesNotExistForIndefinitePathWithResults() throws Exception { String expression = "$.familyMembers[?(@.name == 'Bart')]"; assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> new JsonPathExpectationsHelper(expression).doesNotExist(SIMPSONS)) .withMessageContaining("Expected no value at JSON path \"" + expression + "\" but found: [{\"name\":\"Bart\"}]"); } @Test void doesNotExistForIndefinitePathWithEmptyResults() throws Exception { new JsonPathExpectationsHelper("$.familyMembers[?(@.name == 'Dilbert')]").doesNotExist(SIMPSONS); } @Test void assertValueIsEmptyForAnEmptyString() throws Exception { new JsonPathExpectationsHelper("$.emptyString").assertValueIsEmpty(CONTENT); } @Test void assertValueIsEmptyForAnEmptyArray() throws Exception { new JsonPathExpectationsHelper("$.emptyArray").assertValueIsEmpty(CONTENT); } @Test void assertValueIsEmptyForAnEmptyMap() throws Exception { new JsonPathExpectationsHelper("$.emptyMap").assertValueIsEmpty(CONTENT); } @Test void assertValueIsEmptyForIndefinitePathWithEmptyResults() throws Exception { new JsonPathExpectationsHelper("$.familyMembers[?(@.name == 'Dilbert')]").assertValueIsEmpty(SIMPSONS); } @Test void assertValueIsEmptyForIndefinitePathWithResults() throws Exception { String expression = "$.familyMembers[?(@.name == 'Bart')]"; assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> new JsonPathExpectationsHelper(expression).assertValueIsEmpty(SIMPSONS)) .withMessageContaining("Expected an empty value at JSON path \"" + expression + "\" but found: [{\"name\":\"Bart\"}]"); } @Test void assertValueIsEmptyForWhitespace() throws Exception { String expression = "$.whitespace"; assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> new JsonPathExpectationsHelper(expression).assertValueIsEmpty(CONTENT)) .withMessageContaining("Expected an empty value at JSON path \"" + expression + "\" but found: ' '"); } @Test void assertValueIsNotEmptyForString() throws Exception { new JsonPathExpectationsHelper("$.str").assertValueIsNotEmpty(CONTENT); } @Test void assertValueIsNotEmptyForNumber() throws Exception { new JsonPathExpectationsHelper("$.num").assertValueIsNotEmpty(CONTENT); } @Test void assertValueIsNotEmptyForBoolean() throws Exception { new JsonPathExpectationsHelper("$.bool").assertValueIsNotEmpty(CONTENT); } @Test void assertValueIsNotEmptyForArray() throws Exception { new JsonPathExpectationsHelper("$.arr").assertValueIsNotEmpty(CONTENT); } @Test void assertValueIsNotEmptyForMap() throws Exception { new JsonPathExpectationsHelper("$.colorMap").assertValueIsNotEmpty(CONTENT); } @Test void assertValueIsNotEmptyForIndefinitePathWithResults() throws Exception { new JsonPathExpectationsHelper("$.familyMembers[?(@.name == 'Bart')]").assertValueIsNotEmpty(SIMPSONS); } @Test void assertValueIsNotEmptyForIndefinitePathWithEmptyResults() throws Exception { String expression = "$.familyMembers[?(@.name == 'Dilbert')]"; assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> new JsonPathExpectationsHelper(expression).assertValueIsNotEmpty(SIMPSONS)) .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: []"); } @Test void assertValueIsNotEmptyForAnEmptyString() throws Exception { String expression = "$.emptyString"; assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> new JsonPathExpectationsHelper(expression).assertValueIsNotEmpty(CONTENT)) .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: ''"); } @Test void assertValueIsNotEmptyForAnEmptyArray() throws Exception { String expression = "$.emptyArray"; assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> new JsonPathExpectationsHelper(expression).assertValueIsNotEmpty(CONTENT)) .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: []"); } @Test void assertValueIsNotEmptyForAnEmptyMap() throws Exception { String expression = "$.emptyMap"; assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> new JsonPathExpectationsHelper(expression).assertValueIsNotEmpty(CONTENT)) .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: {}"); } @Test void hasJsonPath() { new JsonPathExpectationsHelper("$.abc").hasJsonPath("{\"abc\": \"123\"}"); } @Test void hasJsonPathWithNull() { new JsonPathExpectationsHelper("$.abc").hasJsonPath("{\"abc\": null}"); } @Test void hasJsonPathForIndefinitePathWithResults() { new JsonPathExpectationsHelper("$.familyMembers[?(@.name == 'Bart')]").hasJsonPath(SIMPSONS); } @Test void hasJsonPathForIndefinitePathWithEmptyResults() { String expression = "$.familyMembers[?(@.name == 'Dilbert')]"; assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> new JsonPathExpectationsHelper(expression).hasJsonPath(SIMPSONS)) .withMessageContaining("No values for JSON path \"" + expression + "\""); } @Test // SPR-16339 void doesNotHaveJsonPath() { new JsonPathExpectationsHelper("$.abc").doesNotHaveJsonPath("{}"); } @Test // SPR-16339 void doesNotHaveJsonPathWithNull() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> new JsonPathExpectationsHelper("$.abc").doesNotHaveJsonPath("{\"abc\": null}")); } @Test void doesNotHaveJsonPathForIndefinitePathWithEmptyResults() { new JsonPathExpectationsHelper("$.familyMembers[?(@.name == 'Dilbert')]").doesNotHaveJsonPath(SIMPSONS); } @Test void doesNotHaveEmptyPathForIndefinitePathWithResults() { String expression = "$.familyMembers[?(@.name == 'Bart')]"; assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> new JsonPathExpectationsHelper(expression).doesNotHaveJsonPath(SIMPSONS)) .withMessageContaining("Expected no values at JSON path \"" + expression + "\" " + "but found: [{\"name\":\"Bart\"}]"); } @Test void assertValue() throws Exception { new JsonPathExpectationsHelper("$.num").assertValue(CONTENT, 5); } @Test // SPR-14498 void assertValueWithNumberConversion() throws Exception { new JsonPathExpectationsHelper("$.num").assertValue(CONTENT, 5.0); } @Test // SPR-14498 void assertValueWithNumberConversionAndMatcher() throws Exception { new JsonPathExpectationsHelper("$.num").assertValue(CONTENT, is(5.0), Double.class); } @Test void assertValueIsString() throws Exception { new JsonPathExpectationsHelper("$.str").assertValueIsString(CONTENT); } @Test void assertValueIsStringForAnEmptyString() throws Exception { new JsonPathExpectationsHelper("$.emptyString").assertValueIsString(CONTENT); } @Test void assertValueIsStringForNonString() throws Exception { String expression = "$.bool"; assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> new JsonPathExpectationsHelper(expression).assertValueIsString(CONTENT)) .withMessageContaining("Expected a string at JSON path \"" + expression + "\" but found: true"); } @Test void assertValueIsNumber() throws Exception { new JsonPathExpectationsHelper("$.num").assertValueIsNumber(CONTENT); } @Test void assertValueIsNumberForNonNumber() throws Exception { String expression = "$.bool"; assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> new JsonPathExpectationsHelper(expression).assertValueIsNumber(CONTENT)) .withMessageContaining("Expected a number at JSON path \"" + expression + "\" but found: true"); } @Test void assertValueIsBoolean() throws Exception { new JsonPathExpectationsHelper("$.bool").assertValueIsBoolean(CONTENT); } @Test void assertValueIsBooleanForNonBoolean() throws Exception { String expression = "$.num"; assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> new JsonPathExpectationsHelper(expression).assertValueIsBoolean(CONTENT)) .withMessageContaining("Expected a boolean at JSON path \"" + expression + "\" but found: 5"); } @Test void assertValueIsArray() throws Exception { new JsonPathExpectationsHelper("$.arr").assertValueIsArray(CONTENT); } @Test void assertValueIsArrayForAnEmptyArray() throws Exception { new JsonPathExpectationsHelper("$.emptyArray").assertValueIsArray(CONTENT); } @Test void assertValueIsArrayForNonArray() throws Exception { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> new JsonPathExpectationsHelper(expression).assertValueIsArray(CONTENT)) .withMessageContaining("Expected an array at JSON path \"" + expression + "\" but found: 'foo'"); } @Test void assertValueIsMap() throws Exception { new JsonPathExpectationsHelper("$.colorMap").assertValueIsMap(CONTENT); } @Test void assertValueIsMapForAnEmptyMap() throws Exception { new JsonPathExpectationsHelper("$.emptyMap").assertValueIsMap(CONTENT); } @Test void assertValueIsMapForNonMap() throws Exception { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> new JsonPathExpectationsHelper(expression).assertValueIsMap(CONTENT)) .withMessageContaining("Expected a map at JSON path \"" + expression + "\" but found: 'foo'"); } }
package com.financecrudbackend.services.impl; import com.financecrudbackend.util.NotFoundException; import com.financecrudbackend.models.FiscalPosition; import com.financecrudbackend.repositories.FiscalPositionRepository; import com.financecrudbackend.services.FiscalPositionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; @Service public class FiscalPositionServiceImpl implements FiscalPositionService { private final FiscalPositionRepository fiscalPositionRepository; @Autowired public FiscalPositionServiceImpl(FiscalPositionRepository fiscalPositionRepository) { this.fiscalPositionRepository = fiscalPositionRepository; } @Override public Page<FiscalPosition> getAll(Pageable pageable) { return fiscalPositionRepository.findAll(pageable); } @Override public FiscalPosition getById(Long id) { return fiscalPositionRepository.findById(id) .orElseThrow(() -> new NotFoundException("FiscalPosition", "id", id)); } @Override public FiscalPosition save(FiscalPosition fiscalPosition) { return fiscalPositionRepository.save(fiscalPosition); } @Override public FiscalPosition update(Long id, FiscalPosition fiscalPosition) { FiscalPosition founded = fiscalPositionRepository.findById(id) .orElseThrow(() -> new NotFoundException("FiscalPosition", "id", id)); founded.setYearOfBalance(fiscalPosition.getYearOfBalance()); founded.setState(fiscalPosition.getState()); founded.setCategory(fiscalPosition.getCategory()); founded.setItem(fiscalPosition.getItem()); founded.setAmount(fiscalPosition.getAmount()); founded.setPercentOfGdp(fiscalPosition.getPercentOfGdp()); return fiscalPositionRepository.save(founded); } @Override public void delete(Long id) { FiscalPosition founded = fiscalPositionRepository.findById(id) .orElseThrow(() -> new NotFoundException("FiscalPosition", "id", id)); fiscalPositionRepository.delete(founded); } }
package org.bca.training.spring.core.beans.data; //@Component public class Human implements Model { String firstName; String lastName; Integer age; public void parse(String[] values) { if (values[0].equalsIgnoreCase("Human")) { lastName = values[1]; firstName = values[2]; age = Integer.parseInt(values[3]); } else { throw new RuntimeException(); } } public void display() { System.out.println(String.format("Human: %s %s %d", firstName, lastName, age)); } }
package Pack01; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class Test { public static void main(String[] args) { BeanFactory context=new XmlBeanFactory(new ClassPathResource("Beans.xml")); Employee employee1=(Employee)context.getBean("employee"); System.out.println(employee1.getName()); } }
import java.math.*; import java.util.*; public class Main { public static void main(String[] args){ Scanner cin=new Scanner(System.in); int T=cin.nextInt(); for(int cas=1;cas<=T;cas++){ BigInteger a,b; a=cin.nextBigInteger(); b=cin.nextBigInteger(); BigInteger c=a.add(b); System.out.println("Case "+cas+":"); System.out.println(a+" + "+b+" = "+c); if(cas!=T) System.out.println(""); } } }
package com.kNoAPP.SB.mapdata; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.boss.BarColor; import org.bukkit.boss.BarStyle; import org.bukkit.boss.BossBar; import org.bukkit.entity.Player; public class GamePlayer { public static List<GamePlayer> players = new ArrayList<GamePlayer>(); private GameTeam team; private UUID uuid; private BossBar bb; private PlayerState playerState; private GameMap voted; public enum PlayerState { ALIVE, DEAD, OFFLINE; } public GamePlayer(UUID uuid) { this.uuid = uuid; this.bb = Bukkit.createBossBar("null", BarColor.WHITE, BarStyle.SOLID); if(isValid()) bb.addPlayer(getPlayer()); bb.setVisible(false); } public UUID getUniqueID() { return uuid; } public Player getPlayer() { return Bukkit.getPlayer(uuid); } public boolean isValid() { Player p = getPlayer(); if(p == null) return false; return p.isOnline(); } public void setTeam(GameTeam team){ this.team = team; } public GameTeam getTeam(){ return team; } public BossBar getBar() { return bb; } public GameMap getVotedMap() { return voted; } public void setVotedMap(GameMap voted) { this.voted = voted; } public void join() { players.remove(this); players.add(this); } public void quit() { playerState = PlayerState.OFFLINE; } public PlayerState getPlayerState(){ return playerState; } public void setPlayerState(PlayerState ps){ playerState = ps; } public static GamePlayer getGamePlayer(Player p) { for(GamePlayer gp : players) if(gp.getUniqueID().equals(p.getUniqueId())) return gp; return null; } }
package com.gaoshin.fbobuilder.client.editor; public class GroupEditor extends ContainerEditor { }
package de.varylab.discreteconformal.heds; import de.jreality.math.Pn; import de.varylab.discreteconformal.functional.node.ConformalEdge; public class CoEdge extends ConformalEdge<CoVertex, CoEdge, CoFace> { public CustomEdgeInfo info = null; public double getLength() { double[] s = getStartVertex().P; double[] t = getTargetVertex().P; return Pn.distanceBetween(s, t, Pn.EUCLIDEAN); } public double getTexLength() { double[] s = getStartVertex().T; double[] t = getTargetVertex().T; return Pn.distanceBetween(s, t, Pn.EUCLIDEAN); } @Override public void copyData(CoEdge e) { super.copyData(e); if (e.info != null) { info = new CustomEdgeInfo(e.info); } } }
package json; public final class Version extends Object { public final static String Name = "@VersionName@"; public final static int Major = @VersionMajor@; public final static int Minor = @VersionMinor@; public final static int Build = @VersionBuild@; public final static String Number = String.valueOf(Major)+'.'+String.valueOf(Minor); public final static String Full = Name+'/'+Number; private Version(){ super(); } }
package com.example.gaga.test; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.robotium.solo.Solo; import android.test.ActivityInstrumentationTestCase2; import android.util.Log; @SuppressWarnings("rawtypes") public class linkustest extends ActivityInstrumentationTestCase2{ private Solo solo; LinkusforAndroid linkus = new LinkusforAndroid(); private static final String LAUNCHER_ACTIVITY_FULL_CLASSNAME ="com.linkus.activity.WelcomeActivity" ; private static Class launcherActivityClass; static{ try{ launcherActivityClass = Class.forName(LAUNCHER_ACTIVITY_FULL_CLASSNAME); }catch(ClassNotFoundException e){ Log.i("gaga",e.toString()); throw new RuntimeException(e); } } @SuppressWarnings("unchecked") public linkustest() { super(launcherActivityClass); } @Before public void setUp() throws Exception { solo = new Solo(getInstrumentation(),getActivity()); linkus.Init(solo); } @After public void tearDown() throws Exception { solo.finishOpenedActivities(); } @Test public void test() { solo.waitForActivity("WelcomeActivity", 30000); linkus.clickSetServer(); linkus.inputLocalIp("192.168.3.223"); linkus.clickOK(); linkus.inputLoginUser("5005"); linkus.inputLoginPass("123456"); linkus.clickLogin(); solo.sleep(10000); } }
package com.codekarma.domain; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import org.hibernate.engine.internal.Cascade; import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.NotBlank; @Entity public class Building { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; @Column @NotEmpty(message="building name cannot be empty") private String name; @Column @NotEmpty(message="building desc cannot be empty") private String description; @OneToMany(fetch=FetchType.LAZY, mappedBy="building",cascade=CascadeType.ALL) List<Room>lstRoomInBuilding; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<Room> getLstRoomInBuilding() { return lstRoomInBuilding; } public void setLstRoomInBuilding(List<Room> lstRoomInBuilding) { this.lstRoomInBuilding = lstRoomInBuilding; } }
package com.hzw.supertextview; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.StateListDrawable; import android.text.TextUtils; import android.util.AttributeSet; import android.view.Gravity; import android.widget.TextView; import androidx.annotation.ColorRes; import androidx.annotation.Px; import static android.graphics.drawable.GradientDrawable.LINEAR_GRADIENT; /** * author:HZWei * date: 2020/9/7 * desc: */ public class SuperTextViewHelper { private Context mContext; private int mCanvasTranslationX; private int mDrawablePadding; private Drawable mIconLeft; private Drawable mIconRight; private Drawable mIconTop; private Drawable mIconBottom; private int mTextWidth; private int mTextViewWidth; private int mPaddingStart; private int mPaddingEnd; private boolean mIsOpenResetSwitch; private GradientDrawable mNormalBGDrawable; private GradientDrawable mDisableDrawable; private GradientDrawable mPressedDrawable; private int mStrokeColor; private int mStrokeWidth; public enum GradientOrientation { LEFT_RIGHT(0), RIGHT_LEFT(1), TOP_BOTTOM(2), BOTTOM_TOP(3); int value; GradientOrientation(int value) { this.value = value; } public static GradientOrientation getOrientation(int val) { for (GradientOrientation orientation : values()) { if (orientation.value == val) return orientation; } return GradientOrientation.LEFT_RIGHT; } } public SuperTextViewHelper(TextView view, AttributeSet attrs) { mContext = view.getContext(); TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.SuperTextView); mIsOpenResetSwitch = typedArray.getBoolean(R.styleable.SuperTextView_open_reset_switch, true); int gradientOrientation = typedArray.getInt(R.styleable.SuperTextView_hzw_bg_gradient_orientation, 0); int startColor = typedArray.getColor(R.styleable.SuperTextView_hzw_bg_gradient_start_color, 0); int centerColor = typedArray.getColor(R.styleable.SuperTextView_hzw_bg_gradient_center_color, 0); int endColor = typedArray.getColor(R.styleable.SuperTextView_hzw_bg_gradient_end_color, 0); int normalColor = typedArray.getColor(R.styleable.SuperTextView_hzw_normal_fill_color, 0); int disableColor = typedArray.getColor(R.styleable.SuperTextView_hzw_disable_color, 0); int pressedColor = typedArray.getColor(R.styleable.SuperTextView_hzw_pressed_color, 0); mStrokeColor = typedArray.getColor(R.styleable.SuperTextView_hzw_stroke_color, 0); mStrokeWidth = typedArray.getDimensionPixelSize(R.styleable.SuperTextView_hzw_stroke_width, 0); int radius = typedArray.getDimensionPixelSize(R.styleable.SuperTextView_hzw_radius, 0); int radiusLT = typedArray.getDimensionPixelSize(R.styleable.SuperTextView_hzw_radius_left_top, 0); int radiusRT = typedArray.getDimensionPixelSize(R.styleable.SuperTextView_hzw_radius_right_top, 0); int radiusRB = typedArray.getDimensionPixelSize(R.styleable.SuperTextView_hzw_radius_right_bottom, 0); int radiusLB = typedArray.getDimensionPixelSize(R.styleable.SuperTextView_hzw_radius_left_bottom, 0); typedArray.recycle(); int[] fillColors = centerColor != 0 ? new int[]{startColor, centerColor, endColor} : new int[]{startColor, endColor}; float[] cornerRadius = {radiusLT, radiusLT, radiusRT, radiusRT, radiusRB, radiusRB, radiusLB, radiusLB}; mNormalBGDrawable = new GradientDrawable(); mNormalBGDrawable.setGradientType(LINEAR_GRADIENT); mNormalBGDrawable.setStroke(mStrokeWidth, mStrokeColor); setCornerRadius(mNormalBGDrawable, radius, cornerRadius); setFillColor(mNormalBGDrawable, normalColor, fillColors); switch (GradientOrientation.getOrientation(gradientOrientation)) { case LEFT_RIGHT: mNormalBGDrawable.setOrientation(GradientDrawable.Orientation.LEFT_RIGHT); break; case RIGHT_LEFT: mNormalBGDrawable.setOrientation(GradientDrawable.Orientation.RIGHT_LEFT); break; case TOP_BOTTOM: mNormalBGDrawable.setOrientation(GradientDrawable.Orientation.TOP_BOTTOM); break; case BOTTOM_TOP: mNormalBGDrawable.setOrientation(GradientDrawable.Orientation.BOTTOM_TOP); break; } initDisableDrawable(disableColor, radius, cornerRadius); initPressedDrawable(pressedColor,radius, cornerRadius); int pressed = android.R.attr.state_pressed; int enabled = android.R.attr.state_enabled; int focused = android.R.attr.state_focused; StateListDrawable stateListDrawable = new StateListDrawable(); stateListDrawable.addState(new int[]{pressed}, mPressedDrawable); //按下状态 stateListDrawable.addState(new int[]{enabled}, mNormalBGDrawable);//恢复正常状态 stateListDrawable.addState(new int[]{-enabled}, mDisableDrawable);//禁止状态 stateListDrawable.addState(new int[]{}, mNormalBGDrawable); //正常状态 view.setBackground(stateListDrawable); } private void initDisableDrawable(int disableColor, int radius, float[] cornerRadius) { //禁止状态 if (mDisableDrawable == null) { mDisableDrawable = new GradientDrawable(); } setCornerRadius(mDisableDrawable, radius, cornerRadius); setFillColor(mDisableDrawable, disableColor, null); } private void initPressedDrawable(int pressedColor, int radius, float[] cornerRadius) { //手指按下的状态 if (pressedColor!=0){ if (mPressedDrawable == null) { mPressedDrawable = new GradientDrawable(); } }else { mPressedDrawable=mNormalBGDrawable; } mPressedDrawable.setStroke(mStrokeWidth, mStrokeColor); setCornerRadius(mPressedDrawable, radius, cornerRadius); setFillColor(mPressedDrawable, pressedColor, null); } private void setFillColor(GradientDrawable drawable, int solidColor, int[] fillColors) { if (fillColors != null) drawable.setColors(fillColors); if (solidColor != 0) drawable.setColor(solidColor); } private void setCornerRadius(GradientDrawable drawable, int radius, float[] cornerRadius) { if (cornerRadius != null) drawable.setCornerRadii(cornerRadius); if (radius != 0) drawable.setCornerRadius(radius); } public void setCornerRadius(@Px int radius){ if (mNormalBGDrawable!=null){ mNormalBGDrawable.setCornerRadius(radius); } if (mPressedDrawable!=null){ mPressedDrawable.setCornerRadius(radius); } if (mDisableDrawable!=null){ mDisableDrawable.setCornerRadius(radius); } } /** * * @param ltRadius 左上圆角 * @param rtRadius 右上圆角 * @param rbRadius 右下圆角 * @param lbRadius 左下圆角 */ public void setCornerRadius(int ltRadius,int rtRadius,int rbRadius,int lbRadius){ float[] radius={ltRadius,ltRadius,rtRadius,rtRadius,rbRadius,rbRadius,lbRadius,lbRadius}; if (mNormalBGDrawable!=null){ mNormalBGDrawable.setCornerRadii(radius); } if (mPressedDrawable!=null){ mPressedDrawable.setCornerRadii(radius); } if (mDisableDrawable!=null){ mDisableDrawable.setCornerRadii(radius); } } public void setFillColor(@ColorRes int color){ mNormalBGDrawable.setColor(mContext.getResources().getColor(color)); } public void setFillColor(int... colors){ if (colors.length==1){ mNormalBGDrawable.setColor(mContext.getResources().getColor(colors[0])); } if (colors.length==2 || colors.length==3 ){ mNormalBGDrawable.setColors(colors); } } public void setStrokeWidth(int width){ mStrokeWidth=dp2px(width); mNormalBGDrawable.setStroke(mStrokeWidth,mStrokeColor); } public void setStrokeColor(@ColorRes int color){ mStrokeColor=mContext.getResources().getColor(color); mNormalBGDrawable.setStroke(mStrokeWidth,mStrokeColor); } protected void updateIcon(TextView view) { if (!mIsOpenResetSwitch) return; String text = view.getText().toString(); if (TextUtils.isEmpty(text)) return; mCanvasTranslationX = 0; mDrawablePadding = view.getCompoundDrawablePadding(); Drawable[] drawables = view.getCompoundDrawablesRelative(); mIconLeft = drawables[0]; mIconRight = drawables[2]; mIconTop = drawables[1]; mIconBottom = drawables[3]; mTextWidth = (int) view.getPaint().measureText(text); mTextViewWidth = view.getMeasuredWidth(); mPaddingStart = view.getPaddingStart(); mPaddingEnd = view.getPaddingEnd(); int gravity = view.getGravity(); switch (gravity) { case Gravity.CENTER: case Gravity.CENTER_HORIZONTAL: //文本在中间 setLeftAndRightIconRectBoundsForMiddle(); break; case (Gravity.START | Gravity.CENTER_VERTICAL): case (Gravity.START | Gravity.TOP): //文本在左边 setLeftAndRightIconRectBoundsForSides(true); setTopAndBottomIconRectBounds(true); break; case (Gravity.END | Gravity.CENTER_VERTICAL): case (Gravity.END | Gravity.TOP): //文本在右边 setLeftAndRightIconRectBoundsForSides(false); setTopAndBottomIconRectBounds(false); break; } } private void setLeftAndRightIconRectBoundsForMiddle() { if (mIconLeft != null) { Rect bounds = mIconLeft.getBounds(); int iconWidth = mIconLeft.getIntrinsicWidth(); int distance = (mTextViewWidth - mTextWidth - iconWidth - mPaddingStart - mPaddingEnd) / 2 - mDrawablePadding; if (mIconRight != null) { distance -= iconWidth / 2; mCanvasTranslationX = 0; } else { mCanvasTranslationX = iconWidth; } bounds.set(bounds.left + distance, bounds.top, bounds.right + distance, bounds.bottom); } if (mIconRight != null) { Rect bounds = mIconRight.getBounds(); int iconWidth = mIconRight.getIntrinsicWidth(); int distance = (mTextViewWidth - mTextWidth - iconWidth - mPaddingStart - mPaddingEnd) / 2 - mDrawablePadding; if (mIconLeft != null) { distance -= iconWidth / 2; mCanvasTranslationX = 0; } else { mCanvasTranslationX = -iconWidth; } bounds.set(bounds.left - distance, bounds.top, bounds.right - distance, bounds.bottom); } } private void setLeftAndRightIconRectBoundsForSides(boolean isLeftPosition) { if (isLeftPosition) { if (mIconRight != null) { Rect bounds = mIconRight.getBounds(); int iconWidth = mIconRight.getIntrinsicWidth(); int iconLeftWidth = mIconLeft != null ? mIconLeft.getIntrinsicWidth() : 0; int distance = mTextViewWidth - iconLeftWidth - mTextWidth - iconWidth - mPaddingStart - mPaddingEnd - (mIconLeft != null ? mDrawablePadding * 2 : mDrawablePadding); bounds.set(bounds.left - distance, bounds.top, bounds.right - distance, bounds.bottom); } } else { if (mIconLeft != null) { Rect bounds = mIconLeft.getBounds(); int iconWidth = mIconLeft.getIntrinsicWidth(); int iconRightWidth = mIconRight != null ? mIconRight.getIntrinsicWidth() : 0; int distance = mTextViewWidth - iconRightWidth - mTextWidth - iconWidth - mPaddingStart - mPaddingEnd - (mIconRight != null ? mDrawablePadding * 2 : mDrawablePadding); bounds.set(bounds.left + distance, bounds.top, bounds.right + distance, bounds.bottom); } } } private void setTopAndBottomIconRectBounds(boolean isLeftPosition) { if (mIconTop != null || mIconBottom != null) { int iconLeftWidth = mIconLeft != null ? mIconLeft.getIntrinsicWidth() : 0; int iconRightWidth = mIconRight != null ? mIconRight.getIntrinsicHeight() : 0; int totalContentWidth = mPaddingStart + iconLeftWidth + mDrawablePadding + mTextWidth + mDrawablePadding + iconRightWidth + mPaddingEnd; int distance = (mTextViewWidth - totalContentWidth) / 2; if (isLeftPosition) distance = -distance; if (mIconTop != null) { Rect bounds = mIconTop.getBounds(); bounds.set(bounds.left + distance, bounds.top, bounds.right + distance, bounds.bottom); } if (mIconBottom != null) { Rect bounds = mIconBottom.getBounds(); bounds.set(bounds.left + distance, bounds.top, bounds.right + distance, bounds.bottom); } } } protected void draw(Canvas canvas) { if (mCanvasTranslationX != 0) { canvas.save(); canvas.translate(mCanvasTranslationX, 0); canvas.restore(); } } public GradientDrawable getBackgroundDrawable() { return mNormalBGDrawable; } public void setBackgroundDrawable(GradientDrawable drawable) { this.mNormalBGDrawable = drawable; } private int dp2px(int dp) { float density = mContext.getResources().getDisplayMetrics().density; return (int) (density * dp + 0.5f); } }
import java.util.Arrays; /** * Created by memoria on 7/07/16. */ public class Control { private static Integer productTypeAmount = 10; private static String[] productName = new String[productTypeAmount]; private static Integer[] productAmount = new Integer[productTypeAmount]; private static Integer[] productValue = new Integer[productTypeAmount]; private static Integer[] productImage = new Integer[productTypeAmount]; private static Integer[] coin = new Integer[6]; private static Integer[] coinSize = new Integer[6]; private Integer buyProductID = -1; //---------------------------------------------------------------- Control(){ //Setting coinSize[0] = 10; coinSize[1] = 50; coinSize[2] = 100; coinSize[3] = 500; coinSize[4] = 1000; coinSize[5] = 5000; clearMoney(); setName(0, "緑茶"); setName(1, "緑茶"); setName(2, "紅茶"); setName(3, "コーヒー無糖"); setName(4, "コーヒー微糖"); setName(5, "コーラ"); setName(6, "コーラ"); setName(7, "りんごジュース"); setName(8, "オレンジ"); setName(9, "水"); setAmount(0, 10); setAmount(1, 1); setAmount(2, 20); setAmount(3, 0); setAmount(4, 5); setAmount(5, 5); setAmount(6, 15); setAmount(7, 5); setAmount(8, 5); setAmount(9, 5); setValue(0, 140); setValue(1, 140); setValue(2, 130); setValue(3, 130); setValue(4, 130); setValue(5, 110); setValue(6, 110); setValue(7, 160); setValue(8, 160); setValue(9, 110); setImage(0, 6); setImage(1, 6); setImage(2, 7); setImage(3, 4); setImage(4, 5); setImage(5, 0); setImage(6, 0); setImage(7, 2); setImage(8, 3); setImage(9, 1); // //-------------------------------- // // // Debug // // //商品情報 // showProduct(); // // //~~~~買い方~~~~ // // //買い物の準備 // Integer[] tempCoin = new Integer[6]; // Boolean lotResult = false; // // //これで配列の全要素に一括で入れられるらしい、べんり // Arrays.fill(tempCoin, 0); // // //コイン入れる // tempCoin = inputCoin(0); // tempCoin = inputCoin(1); // tempCoin = inputCoin(2); // tempCoin = inputCoin(5); // tempCoin = inputCoin(4); // tempCoin = inputCoin(3); // // //買う // tempCoin = buyProduct(2); // lotResult = lot(); // tempCoin = buyProduct(2); // lotResult = lot(); // tempCoin = buyProduct(3); // lotResult = lot(); // tempCoin = buyProduct(0); // lotResult = lot(); // tempCoin = buyProduct(2); // lotResult = lot(); // tempCoin = buyProduct(3); // lotResult = lot(); // tempCoin = buyProduct(1); // lotResult = lot(); // tempCoin = buyProduct(4); // lotResult = lot(); // tempCoin = buyProduct(2); // lotResult = lot(); // tempCoin = buyProduct(0); // lotResult = lot(); // tempCoin = buyProduct(3); // lotResult = lot(); // tempCoin = buyProduct(2); // lotResult = lot(); // tempCoin = buyProduct(3); // lotResult = lot(); // // //終わり // tempCoin = tradeClose(); } //---------------------------------------------------------------- //メソッド //-------------------------------- //コインを入れるたびに呼ぶ //inputCoinを2つ用意したのでどっちでも //1枚ずつ入れる //引数: 入れたコインの添字 //戻り値: 今までに入れた全てのコイン public Integer[] inputCoin(Integer inputCoinID){ coin[inputCoinID]++; //Debug System.out.println( String.format("%4d円 を 1枚投入", coinSize[inputCoinID]) ); System.out.println(""); showCoin(); return coin; } //一気に何枚も入れられるけど処理的にこっちは使わないと思う //引数: 入れたコイン、1枚ずつ //戻り値: 今までに入れた全てのコイン public Integer[] inputCoin(Integer[] tempCoin){ for(int i = 0; i < 6; i++){ coin[i] += tempCoin[i]; //Debug if(tempCoin[i] > 0){ System.out.println( String.format("%4d円 を %d枚投入", coinSize[i], tempCoin[i]) ); System.out.println(""); showCoin(); } } return coin; } //-------------------------------- //買うときに呼ぶ //引数: 商品の添字 //戻り値: 残金 public Integer[] buyProduct(int productID){ if(availability(productID)){ if(getAmount(productID) > 0){ setAmount(productID, getAmount(productID) - 1); buyProductID = productID; Integer money = 0; //購入後の残額を計算 money = getMoney(coin) - getValue(productID); //残額に合わせてコインをセット coin = setMoney(money); //Debug System.out.println( String.format("%-20s(%3d円)を購入", getName(productID), getValue(productID)) ); System.out.println(""); showCoin(); }else{ //Debug System.out.println( String.format("エラー: %-20s 在庫なし", getName(productID)) ); System.out.println(""); } }else{ //Debug System.out.println( String.format("エラー: %-20s(%d円) 残高不足 残高 %d円", getName(productID), getValue(productID), getMoney()) ); System.out.println(""); } return coin; } //-------------------------------- //買えるか判定 //戻り値: 買える場合true public Boolean availability(int productID){ if(getMoney() >= getValue(productID)){ return true; }else{ return false; } } //-------------------------------- //お釣りボタン押したときに呼ぶ //戻り値: 残金、おつり public Integer[] tradeClose(){ Integer[] returnCoin = coin; //コイン初期化 clearMoney(); //Debug System.out.println("取引終了"); System.out.println(""); return returnCoin; } //-------------------------------- //くじ関数 //ものを買ったとき(buyProductのあと)に毎回呼ぶ //当たりなら勝手に個数とか減らしちゃうから、 //戻り値: trueなら当たり public Boolean lot(){ Boolean lotResult = false; if(getAmount(buyProductID) > 0){ if((int)(Math.random() * 5) == 0){ lotResult = true; } } //Debug if(lotResult){ System.out.println("くじ当たり"); }else{ System.out.println("くじはずれ"); } System.out.println(""); return lotResult; } //---------------------------------------------------------------- // //-------------------------------- //コインを取得 private Integer[] getCoin(){ return coin; } //-------------------------------- //コインサイズを取得 private Integer[] getCoinSize(){ return coinSize; } //-------------------------------- //お金を取得 public Integer getMoney(){ Integer tempMoney = 0; for(int i = 0; i < 6; i++){ tempMoney += coin[i] * coinSize[i]; } return tempMoney; } //-------------------------------- //お金を取得 public Integer getMoney(Integer[] tempCoin){ Integer tempMoney = 0; for(int i = 0; i < 6; i++){ tempMoney += tempCoin[i] * coinSize[i]; } return tempMoney; } //-------------------------------- //お金をセット public Integer[] setMoney(int tempMoney){ //コイン初期化 clearMoney(); for(int i = 5; i >= 0; i--){ while(true){ if(tempMoney >= coinSize[i]){ tempMoney -= coinSize[i]; coin[i]++; }else{ break; } } } return coin; } //-------------------------------- //お金を初期化 private void clearMoney(){ for(int i = 0; i < 6; i++){ coin[i] = 0; } } //---------------------------------------------------------------- //Get public String[] getNameArray(){ return productName; } public Integer[] getAmountArray(){ return productAmount; } public Integer[] getValueArray(){ return productValue; } public Integer[] getImageArray(){ return productImage; } public String getName(int arg){ if(arg >= 0 && arg <= 9){ return productName[arg]; } return null; } public Integer getAmount(int arg){ if(arg >= 0 && arg <= 9){ return productAmount[arg]; } return null; } public Integer getValue(int arg){ if(arg >= 0 && arg <= 9){ return productValue[arg]; } return null; } public Integer getImage(int arg){ if(arg >= 0 && arg <= 9){ return productImage[arg]; } return null; } //---------------------------------------------------------------- //Set public void setNameArray(String[] args){ productName = args; } public void setAmountArray(Integer[] args){ productAmount = args; } public void setValueArray(Integer[] args){ productValue = args; } public void setImageArray(Integer[] args){ productImage = args; } public void setName(int arg, String argSet){ if(arg >= 0 && arg <= 9){ productName[arg] = argSet; } } public void setAmount(int arg, Integer argSet){ if(arg >= 0 && arg <= 9){ productAmount[arg] = argSet; } } public void setValue(int arg, Integer argSet){ if(arg >= 0 && arg <= 9){ productValue[arg] = argSet; } } public void setImage(int arg, Integer argSet){ if(arg >= 0 && arg <= 9){ productImage[arg] = argSet; } } //---------------------------------------------------------------- //Debug //商品情報 private void showProduct(){ for(int i = 0; i < productTypeAmount; i++){ System.out.println( String.format("%-20s %4d個 %4d円 画像: %2d", getName(i), getAmount(i), getValue(i), getImage(i)) ); } System.out.println(""); } //-------------------------------- //コインを表示 private void showCoin(){ System.out.println( String.format("%4d円 %4d円 %4d円 %4d円 %4d円 %4d円", coinSize[0], coinSize[1], coinSize[2], coinSize[3], coinSize[4], coinSize[5] ) ); System.out.println( String.format("%4d枚 %4d枚 %4d枚 %4d枚 %4d枚 %4d枚", coin[0], coin[1], coin[2], coin[3], coin[4], coin[5] ) ); System.out.println( String.format(" 合計 %5d円", getMoney(coin)) ); System.out.println(""); } }
package com.galid.commerce.domains.order.service; import com.galid.commerce.domains.cart.service.CartService; import com.galid.commerce.domains.delivery.domain.DeliveryEntity; import com.galid.commerce.domains.catalog.domain.item.ItemEntity; import com.galid.commerce.domains.catalog.domain.item.ItemRepository; import com.galid.commerce.domains.member.domain.MemberEntity; import com.galid.commerce.domains.member.service.MemberService; import com.galid.commerce.domains.order.domain.OrderEntity; import com.galid.commerce.domains.order.domain.OrderItemEntity; import com.galid.commerce.domains.order.domain.OrderRepository; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.stream.Collectors; @Service @Transactional @RequiredArgsConstructor public class OrderService { private final OrderRepository orderRepository; private final MemberService memberService; private final CartService cartService; private final ItemRepository itemRepository; public Long order(Long ordererId, OrderRequest orderRequest) { // 엔티티 조회 MemberEntity orderer = memberService.findMember(ordererId); // 배송지 생성 DeliveryEntity deliveryEntity = DeliveryEntity.builder() .address(orderer.getAddress()) .build(); // 주문상품 생성 List<OrderItemEntity> orderItemEntityList = orderRequest.getOrderLineList() .stream() .map(ol -> { ItemEntity itemEntity = itemRepository.findById(ol.getItemId()) .get(); return new OrderItemEntity(itemEntity, ol.getOrderCount()); }) .collect(Collectors.toList()); // 주문 상품 재고 줄이기 orderItemEntityList.stream() .forEach(oi -> oi.removeStockQuantity()); // 주문 생성 OrderEntity orderEntity = OrderEntity.builder() .orderer(orderer) .deliveryInformation(deliveryEntity) .orderItemEntityList(orderItemEntityList) .build(); // 장바구니 비우기 (특정 상품들만 주문하는 경우가 존재하므로, 장바구니를 그냥 비우는게 아닌, id를 기준으로 비워야함) List<Long> itemIdList = orderRequest.getOrderLineList().stream() .map(ol -> ol.getItemId()) .collect(Collectors.toList()); cartService.removeCartLines(orderer.getMemberId(), itemIdList); // 주문 저장 return orderRepository.save(orderEntity).getOrderId(); } public void cancel(Long orderId) { OrderEntity order = orderRepository.findById(orderId).get(); order.cancel(); } }
package com.ihome.android.ihome; import android.content.SharedPreferences; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import org.w3c.dom.Text; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class Motion_Detector extends AppCompatActivity { private Button button; private TextView textView; private StringBuilder response = new StringBuilder(); private String username; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_motion__detector); button = (Button) findViewById(R.id.btnActivate); button.setVisibility(View.GONE); textView = (TextView) findViewById(R.id.MotionDetectorStatus); SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); username = pref.getString("Username", "Error"); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (response.toString().equals("1090")) { task2 m = new task2(); m.execute("110@@" + username, getString(R.string.SERVER_IP)); } if (response.toString().equals("1091")) { task2 m = new task2(); m.execute("111@@" + username, getString(R.string.SERVER_IP)); } } }); task1 m = new task1(); m.execute("109", getString(R.string.SERVER_IP)); } private class task1 extends AsyncTask<String,String,String> { @Override protected String doInBackground(String... params) { //params[0] - message, params[1] - server IP try { Socket soc; PrintWriter writer; BufferedReader reader; // open socket and send message soc = new Socket(params[1], 1618); //send message to server writer = new PrintWriter(soc.getOutputStream()); writer.write(params[0]); writer.flush(); reader = new BufferedReader(new InputStreamReader(soc.getInputStream())); String line; //read from socket line = reader.readLine(); response.append(line); writer.close(); soc.close(); return response.toString(); } catch (IOException e) { e.printStackTrace(); return null; } } @Override protected void onPostExecute(String result) { if (result != null) { if (result.equals("1090")) { textView.setText("Status: Not-Active"); button.setVisibility(View.VISIBLE); button.setText("Activate"); } else if (result.equals("1091")) { textView.setText("Status: Active"); button.setVisibility(View.VISIBLE); button.setText("Deactivate"); } else { Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show(); } } } private class task2 extends AsyncTask<String,String,String> { @Override protected String doInBackground(String... params) { //params[0] - message, params[1] - server IP try { Socket soc; PrintWriter writer; BufferedReader reader; // open socket and send message soc = new Socket(params[1], 1618); //send message to server writer = new PrintWriter(soc.getOutputStream()); writer.write(params[0]); writer.flush(); reader = new BufferedReader(new InputStreamReader(soc.getInputStream())); StringBuilder res = new StringBuilder(); String line; //read from socket Log.d("qwertyuiop", "receiving"); while ((line = reader.readLine()) != null) res.append(line); Log.d("qwertyuiop", res.toString()); writer.close(); soc.close(); return res.toString(); } catch (IOException e) { e.printStackTrace(); return null; } } @Override protected void onPostExecute(String result) { if (result != null) { if (result.equals("200") && response.toString().equals("1090")) { textView.setText("Status: Active"); button.setVisibility(View.VISIBLE); button.setText("Deactivate"); response = new StringBuilder("1091"); } else if (result.equals("200") && response.toString().equals("1091")) { textView.setText("Status: Not-Active"); button.setVisibility(View.VISIBLE); button.setText("Activate"); response = new StringBuilder("1090"); } else if (result.equals("1100")) { Toast.makeText(getApplicationContext(), "You cannot activate motion detection when live streaming is on", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show(); } } } /*private class end extends AsyncTask<String,String,String> { @Override protected String doInBackground(String... params) { //params[0] - message, params[1] - server IP try{ // open socket and send message writer.write(params[0]); writer.flush(); writer.close(); soc.close(); return null; }catch(IOException e){ e.printStackTrace(); return null; } } @Override protected void onPostExecute(String result) { } }*/ }
package ua.game.pro.validator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import ua.game.pro.dao.UserDao; import ua.game.pro.entity.User; @Component("userValidator") public class UserValidator implements Validator { @Autowired private UserDao userDao; public void validate(Object object) throws Exception { User user = (User) object; if (user.getName().isEmpty()) { throw new UserValidationException(UserValidationMessages.EMPTY_USERNAME_FIELD); } if (userDao.findByName(user.getName()) != null) { throw new UserValidationException(UserValidationMessages.NAME_ALREADY_EXIST); } if (userDao.userExistsByEmail(user.getEmail())) { throw new UserValidationException(UserValidationMessages.EMAIL_ALREADY_EXIST); } if (user.getEmail().isEmpty()) { throw new UserValidationException(UserValidationMessages.EMPTY_EMAIl_FIELD); } if (user.getPassword().isEmpty()) { throw new UserValidationException(UserValidationMessages.EMPTY_PASSWORD_FIELD); } } }
package pkgb; public class BFromClasspath { public String doIt() { return "from pkgb.BFromClasspath (in cpb)"; } }
/** * Theme support classes for Spring's web MVC framework. * Provides standard ThemeResolver implementations, * and a HandlerInterceptor for theme changes. * * <p> * <ul> * <li>If you don't provide a bean of one of these classes as {@code themeResolver}, * a {@code FixedThemeResolver} will be provided with the default theme name 'theme'.</li> * <li>If you use a defined {@code FixedThemeResolver}, you will able to use another theme * name for default, but the users will stick on this theme.</li> * <li>With a {@code CookieThemeResolver} or {@code SessionThemeResolver}, you can allow * the user to change his current theme.</li> * <li>Generally, you will put in the themes resource bundles the paths of CSS files, images and HTML constructs.</li> * <li>For retrieving themes data, you can either use the spring:theme tag in JSP or access via the * {@code RequestContext} for other view technologies.</li> * <li>The {@code pagedlist} demo application uses themes</li> * </ul> */ @NonNullApi @NonNullFields package org.springframework.web.servlet.theme; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
package classes; import interfaces.DrawAPI; /** * @author dylan * */ public abstract class Shape { protected DrawAPI drawAPI; /** * @param drawAPI */ protected Shape(DrawAPI drawAPI) { this.drawAPI = drawAPI; } /** * */ public abstract void draw(); }
package authoring; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.TargetDataLine; import javax.swing.JFileChooser; import javax.swing.filechooser.FileNameExtensionFilter; import org.apache.commons.io.FilenameUtils; /** * Utility class which records from a given source to an output file. Used by * (and created by) the authoring UI to record from a microphone to a WAV file. * Works in a separate thread so that it does not lock up the UI. * * @author Dilshad Khatri, Alvis Koshy, Drew Noel, Jonathan Tung * @version 1.0 * @since 2017-03-15 */ public class ThreadRunnable extends Thread { private AudioRecorder recorder; private TargetDataLine line; private File temporaryRecordingFile; /** * Create a new thread for recording, will save in a temporary location * until completed. */ public ThreadRunnable() { // Define the audio format to be WAVE audio, Microsoft PCM, 16 bit, // stereo 44100 Hz AudioFormat audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100.0F, 16, 2, 4, 44100.0F, false); DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat); try { line = (TargetDataLine) AudioSystem.getLine(info); line.open(audioFormat); } catch (LineUnavailableException ex) { // No audio device? That's outside our control, bail. System.err.println("There was no audio device available"); ex.printStackTrace(); return; } // Inform the recorder of the line and filename try { temporaryRecordingFile = File.createTempFile("recording", ".wav"); } catch (IOException e) { // If we couldn't create a temporary file, a filesystem error // occured. Bail. e.printStackTrace(); return; } recorder = new AudioRecorder(line); recorder.setFileName(temporaryRecordingFile.getAbsolutePath()); } @Override public void start() { // Begin listening on the recording line line.start(); // Now call Thread's start (which triggers ThreadRunnable's run() for // us) super.start(); } @Override public void run() { // Start recording recorder.recordAudio(); } /** * Close the line, which will terminate the recorder and request the user to * save the generated file someplace. Afterward, the thread will be stopped * automatically. */ public File stopRecording() { // Stop the line and then close it. The recorder will drain the line // itself. line.stop(); line.close(); // Create a file chooser JFileChooser saveFile = new JFileChooser(); // Create a new file filter to only allow WAV files FileNameExtensionFilter wavFileFilter = new FileNameExtensionFilter("wav files (*.wav)", "wav"); saveFile.addChoosableFileFilter(wavFileFilter); saveFile.setFileFilter(wavFileFilter); // Show the save dialog and wait for the user to save the file saveFile.showSaveDialog(null); // Get the file and fix the extension if it's wrong File file = saveFile.getSelectedFile(); if (file == null) { return null; } if (!FilenameUtils.getExtension(file.getName()).equalsIgnoreCase("wav")) { file = new File(file.toString() + ".wav"); } // Move the file try { Files.move(this.temporaryRecordingFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { // If the move failed, a filesystem error occured. Could be a // permissions error. e.printStackTrace(); return null; } return file; } public void cancel() { line.stop(); line.close(); temporaryRecordingFile.delete(); } }
/* Copyright 2017 Stratumn SAS. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.stratumn.sdk.model.trace; public class PaginationResults { private int totalCount; private Info info; public PaginationResults() { } public PaginationResults(int totalCount, Info info) throws IllegalArgumentException { if (info == null) { throw new IllegalArgumentException("info cannot be null in PaginationResults"); } this.totalCount = totalCount; } public int getTotalCount() { return this.totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public Info getInfo() { return this.info; } public void setInfo(Info info) { this.info = info; } }
/** * @Author: Mahmoud Abdelrahman * Appointment Request Data Transfer Object is where the specifications required for requests declared. */ package com.easylearn.easylearn.model; import java.time.LocalDateTime; import java.util.Date; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.Setter; @Getter @Builder // It does not work unless, there is a @AllArgsConstructor. @AllArgsConstructor public class AppointmentReqDTO { private LocalDateTime startDate; private LocalDateTime endDate; private int roomNumber; }
package web.todo.list.dao; import org.springframework.stereotype.Repository; import web.todo.list.model.Item; @Repository public class ItemDao extends CommonDao { public ItemDao() { super(Item.class); } }
package com.ecommerceserver.payload.request; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class SignupRequest { @NotBlank(message = "Vui lòng nhập họ và tên") @Size(min = 5, max = 50, message = "Họ tên phải dài từ 5 đên 50 ký tự") private String fullname; @NotBlank(message = "Vui lòng nhập email") @Size(max = 50, message = "Email dài tối đa là 50 ký tự") @Email(message = "Email không hợp lệ") private String email; private String username; private String phoneNumber; String role; @NotBlank @Size(min = 6, message = "Mật khẩu phải lớn hơn 6 ký tự") private String password; }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.innovaciones.reporte.service; import com.innovaciones.reporte.model.ProductoClienteReporte; import java.util.List; /** * * @author pisama */ public interface ProductoClienteReporteService { public ProductoClienteReporte saveOrUpdateProductoClienteReporte(ProductoClienteReporte productoClienteReporte); public ProductoClienteReporte save(ProductoClienteReporte productoClienteReporte); public ProductoClienteReporte update(ProductoClienteReporte productoClienteReporte); public ProductoClienteReporte getByReportId(Integer ids); public ProductoClienteReporte getByUsuarioRuc(String ruc); public List<ProductoClienteReporte> getBySerial(String serial); public ProductoClienteReporte getByIdProductoCliente(Integer idProductoCliente); public List<ProductoClienteReporte> getByTipoReporte(String tipo); }
package com.mygdx.game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.mygdx.assets.AssetHandler; import com.mygdx.renderable.Node; import com.mygdx.renderable.Player; /** * Used as a CheckPoint, so it is able to reset to the point to where * you entered into the house. Ensuring that the villagers have been properly * reset. * @author Inder Panesar * @version 1.0 */ public class CheckPoint implements Screen { /** Amount of time within this Screen */ float stateTime = 0f; /** The main class */ Main main; /** initial node, is the node which the player is already in */ Node initialNode; /** The map screen instance of the game */ MapScreen mapScreen; /** Label to show someone is dead*/ Label dead; /** Set the mask durability of the current mask */ private float maskDurablity; /** Create an instance of the checkpoint * * @param main The main class * @param initialNode The initial node * @param mapScreen The current map screen * @param maskDurabilty The initial mask durabilty of the player on the last checkpoint. */ public CheckPoint(Main main, Node initialNode, MapScreen mapScreen, float maskDurabilty) { this.main = main; this.initialNode = initialNode; this.mapScreen = mapScreen; this.maskDurablity = maskDurabilty; dead = new Label("YOU'RE DEAD...", AssetHandler.FONT_SIZE_128_WHITE); dead.setPosition(main.ui.getWidth()/2-dead.getWidth()/2, main.ui.getHeight()/2-dead.getHeight()/2); main.ui.addActor(dead); } @Override public void show() { // TODO Auto-generated method stub } @Override public void render(float delta) { Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); stateTime = stateTime + delta; main.ui.draw(); if(stateTime > 3 && dead.isVisible()) { stateTime = 0; dead.setVisible(false); changeScreen(); } } /** * Change the screen the current player is on. */ public void changeScreen() { main.ui.clear(); System.out.println("MASK DURABILITY: " + maskDurablity); Player.getInstance().setCurrentMaskDuration(maskDurablity); main.setScreen(new HouseScreen(main, initialNode, mapScreen)); } @Override public void resize(int width, int height) { // TODO Auto-generated method stub } @Override public void pause() { // TODO Auto-generated method stub } @Override public void resume() { // TODO Auto-generated method stub } @Override public void hide() { // TODO Auto-generated method stub } @Override public void dispose() { // TODO Auto-generated method stub } }
package com.example.pettrackerapp; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.fragment.app.FragmentManager; import android.Manifest; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbManager; import android.location.Location; import android.os.Bundle; import android.text.Html; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.ftdi.j2xx.D2xxManager; import com.ftdi.j2xx.FT_Device; import com.google.android.gms.location.LocationServices; import com.google.android.gms.tasks.OnSuccessListener; import java.util.HashMap; import java.util.Iterator; public class DetailViewActivity extends AppCompatActivity { String name; String type; int id, position; ImageView imageView; TextView petNameTextView; TextView petTypeTextView; Button deleteButton; public com.google.android.gms.location.FusedLocationProviderClient fusedLocationClient; private PetDatabaseHelper petDatabaseHelper; SQLiteDatabase sqLiteDatabase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().setTitle(Html.fromHtml("<font color=\"black\">" + getString(R.string.app_name) + "</font>")); fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); setContentView(R.layout.activity_detail_view); Intent intent = getIntent(); petNameTextView = findViewById(R.id.DetailPetNameTextView); petTypeTextView = findViewById(R.id.DetailPetTypeTextView); deleteButton = findViewById(R.id.deleteButton); imageView = findViewById(R.id.imageView); PetDatabaseHelper petDatabaseHelper = new PetDatabaseHelper(getApplicationContext()); SQLiteDatabase sqLiteDatabase = petDatabaseHelper.getReadableDatabase(); Cursor cursor = sqLiteDatabase.query("pets", new String[]{"_id", "name", "type", "drawable", "homeLat", "homeLong", "petLat", "petLong"}, null, null, null, null, null); position = intent.getIntExtra("pos", 0); cursor.moveToPosition(position); int column = cursor.getColumnIndex("_id"); id = Integer.parseInt(cursor.getString(column)); column = cursor.getColumnIndex("name"); name = cursor.getString(column); column = cursor.getColumnIndex("type"); type = cursor.getString(column); petNameTextView.setText(name); petTypeTextView.setText(type); if(type.equals("cat") || type.equals("CAT") || type.equals("Cat")){ imageView.setImageResource(R.drawable.cat); } else if(type.equals("dog") || type.equals("DOG") || type.equals("Dog")){ imageView.setImageResource(R.drawable.dog); } else{ imageView.setImageResource(R.drawable.pet); } } public void onLaunchLocation(View view){ Intent intent = new Intent(getApplicationContext(), LocationStringActivity.class); intent.putExtra("_id", id); intent.putExtra("name", name); intent.putExtra("type", type); intent.putExtra("pos", position); startActivity(intent); } @Override public void onBackPressed() { super.onBackPressed(); Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.menu_layout, menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch(item.getItemId()){ case R.id.menuAddPet: showAddDialog(); return true; case R.id.menuHome: Intent intent = new Intent(this, MainActivity.class); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } private void showAddDialog(){ FragmentManager fm = getSupportFragmentManager(); AddPetDialogFragment addPetDialogFragment = AddPetDialogFragment.newInstance("Add New Pet"); addPetDialogFragment.show(fm, "fragment_add_pet"); } public void onClickDelete(View view){ final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Delete Pet?"); builder.setMessage("Are you sure you want to delete this pet?"); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(DetailViewActivity.this, "pet deleted", Toast.LENGTH_LONG).show(); Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); petDatabaseHelper = new PetDatabaseHelper(getApplicationContext()); sqLiteDatabase = petDatabaseHelper.getReadableDatabase(); sqLiteDatabase.delete("pets", "name = ?", new String[]{name}); } }); builder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { AlertDialog alertDialog = builder.create(); alertDialog.dismiss(); } }); builder.show(); } public void onClickSetCurrentLocation(View view){ if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}; ActivityCompat.requestPermissions(this, permissions, 1); } else { fusedLocationClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { if(location != null){ Toast.makeText(DetailViewActivity.this, "Current location set as home location", Toast.LENGTH_SHORT).show(); ContentValues updatedPetValues = new ContentValues(); updatedPetValues.put("homeLat", location.getLatitude()); updatedPetValues.put("homeLong", location.getLongitude()); petDatabaseHelper = new PetDatabaseHelper(getApplicationContext()); sqLiteDatabase = petDatabaseHelper.getWritableDatabase(); sqLiteDatabase.update("pets", updatedPetValues, "_id = ?", new String[] {String.valueOf(id)}); } else{ Toast.makeText(DetailViewActivity.this, "Location not received", Toast.LENGTH_SHORT).show(); } } }); } } }
package org.yoqu.fish.common.codec.compress; /** * @author yoqu * @date 2018/2/5 - 下午2:57 */ public class SnappyCompress implements Compress { @Override public byte[] compress(byte[] bytes) { return new byte[0]; } @Override public byte[] unCompress(byte[] bytes) { return new byte[0]; } }
package com.marcodinacci.demos.alv; /** * This file is part of AdvancedListViewDemo. * You should have downloaded this file from www.intransitione.com, if not, * please inform me by writing an e-mail at the address below: * * Copyright [2011] [Marco Dinacci <marco.dinacci@gmail.com>] * * 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. * The license text is available online and in the LICENSE file accompanying the distribution * of this program. */ import android.content.Context; import android.content.res.TypedArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; public class ImageAndTextAdapter extends ArrayAdapter<String> { private LayoutInflater mInflater; private String[] mStrings; private TypedArray mIcons; private int mViewResourceId; public ImageAndTextAdapter(Context ctx, int viewResourceId, String[] strings, TypedArray icons) { super(ctx, viewResourceId, strings); mInflater = (LayoutInflater)ctx.getSystemService( Context.LAYOUT_INFLATER_SERVICE); mStrings = strings; mIcons = icons; mViewResourceId = viewResourceId; } @Override public int getCount() { return mStrings.length; } @Override public String getItem(int position) { return mStrings[position]; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = mInflater.inflate(mViewResourceId, null); ImageView iv = (ImageView)convertView.findViewById(R.id.option_icon); iv.setImageDrawable(mIcons.getDrawable(position)); TextView tv = (TextView)convertView.findViewById(R.id.option_text); tv.setText(mStrings[position]); return convertView; } }
package com.marks.asuper.doubanmovie; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import com.marks.asuper.doubanmovie.adapters.DoubanAdapter; import com.marks.asuper.doubanmovie.model.DoubanBean; import com.marks.asuper.doubanmovie.services.DoubanService; import java.util.ArrayList; import java.util.List; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class GeneralActivity extends AppCompatActivity implements AdapterView.OnItemClickListener { private static final String TAG = "GeneralActivity"; private ListView mListView; private List<DoubanBean.Subjects> mList; private DoubanAdapter mAdapter; private DoubanService mService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_general); initView(); } public void initView() { mListView = (ListView) findViewById(R.id.General_listView); mList = new ArrayList<>(); mAdapter = new DoubanAdapter(this,mList); if (mService == null) { Retrofit.Builder builder = new Retrofit.Builder(); builder.baseUrl("https://api.douban.com/"); builder.addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io())); builder.addConverterFactory(GsonConverterFactory.create()); Retrofit retrofit = builder.build(); mService = retrofit.create(DoubanService.class); } mListView.setAdapter(mAdapter); Observable<DoubanBean> observable = mService.getDoubanBean(0, 20); observable .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<DoubanBean>() { @Override public void onCompleted() { mAdapter.notifyDataSetChanged(); } @Override public void onError(Throwable e) { mList.clear(); e.printStackTrace(); mAdapter.notifyDataSetChanged(); } @Override public void onNext(DoubanBean bean) { List<DoubanBean.Subjects> subjectses = bean.getSubjectses(); mList.addAll(subjectses); mAdapter.notifyDataSetChanged(); } }); mListView.setOnItemClickListener(this); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { DoubanBean.Subjects subjects = mList.get(position); String url = subjects.getContextUrl(); Intent intent = new Intent(this , WebViewActivity.class); intent.putExtra("url",url); startActivity(intent); } }
package exercicio03; public class teste { public static void main (String[] args) { Restaurante BoxMineiro = new Restaurante("BoxMineiro","Joćo Monlevade","35930-001","(31)3851-7577","TROPEIRO", 30); System.out.println(BoxMineiro.toString()); } }
/* * Copyright 2002-2020 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.aop.interceptor; import java.io.Serializable; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.Advisor; import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.core.NamedThreadLocal; import org.springframework.core.PriorityOrdered; import org.springframework.lang.Nullable; /** * Interceptor that exposes the current {@link org.aopalliance.intercept.MethodInvocation} * as a thread-local object. We occasionally need to do this; for example, when a pointcut * (e.g. an AspectJ expression pointcut) needs to know the full invocation context. * * <p>Don't use this interceptor unless this is really necessary. Target objects should * not normally know about Spring AOP, as this creates a dependency on Spring API. * Target objects should be plain POJOs as far as possible. * * <p>If used, this interceptor will normally be the first in the interceptor chain. * * @author Rod Johnson * @author Juergen Hoeller */ @SuppressWarnings("serial") public final class ExposeInvocationInterceptor implements MethodInterceptor, PriorityOrdered, Serializable { /** Singleton instance of this class. */ public static final ExposeInvocationInterceptor INSTANCE = new ExposeInvocationInterceptor(); /** * Singleton advisor for this class. Use in preference to INSTANCE when using * Spring AOP, as it prevents the need to create a new Advisor to wrap the instance. */ public static final Advisor ADVISOR = new DefaultPointcutAdvisor(INSTANCE) { @Override public String toString() { return ExposeInvocationInterceptor.class.getName() +".ADVISOR"; } }; private static final ThreadLocal<MethodInvocation> invocation = new NamedThreadLocal<>("Current AOP method invocation"); /** * Return the AOP Alliance MethodInvocation object associated with the current invocation. * @return the invocation object associated with the current invocation * @throws IllegalStateException if there is no AOP invocation in progress, * or if the ExposeInvocationInterceptor was not added to this interceptor chain */ public static MethodInvocation currentInvocation() throws IllegalStateException { MethodInvocation mi = invocation.get(); if (mi == null) { throw new IllegalStateException( "No MethodInvocation found: Check that an AOP invocation is in progress and that the " + "ExposeInvocationInterceptor is upfront in the interceptor chain. Specifically, note that " + "advices with order HIGHEST_PRECEDENCE will execute before ExposeInvocationInterceptor! " + "In addition, ExposeInvocationInterceptor and ExposeInvocationInterceptor.currentInvocation() " + "must be invoked from the same thread."); } return mi; } /** * Ensures that only the canonical instance can be created. */ private ExposeInvocationInterceptor() { } @Override @Nullable public Object invoke(MethodInvocation mi) throws Throwable { MethodInvocation oldInvocation = invocation.get(); invocation.set(mi); try { return mi.proceed(); } finally { invocation.set(oldInvocation); } } @Override public int getOrder() { return PriorityOrdered.HIGHEST_PRECEDENCE + 1; } /** * Required to support serialization. Replaces with canonical instance * on deserialization, protecting Singleton pattern. * <p>Alternative to overriding the {@code equals} method. */ private Object readResolve() { return INSTANCE; } }
package kr.or.ddit.basic; /* * 멀티 쓰레드 프로그램 */ public class T02_ThreadTest { public static void main(String[] args) { // 방법1 : Thread 클래스를 상속한 class의 인스턴스 생성 후 이 인스턴스의 start() 메소드 호출 MyThread1 th1 = new MyThread1(); //방법2 : Runnable 인터페이스를 구현한 class의 인스턴스 생성 후 이 인스턴스를 // Thread 객체의 인스턴스를 생성할 때 생성자의 매개변수로 넘겨주는 방법 // 이 때 생성된 Thread객체의 인스턴스의 start()메소드 호출 MyThread2 r1 = new MyThread2(); // Runnable 객체만 가져옴 - run()을 가져옴 Thread th2 = new Thread(r1); // thread객체를 가져와야함 -> 여기에 run을 실행하겠다고 말하는 것 - run()을 실행 //방법3 : 익명 클래스를 이용하는 방법 // Runnable 인터페이스를 구현한 익명크래스를 //Thread 인스턴스를 생성할 때 매개변수로 넘겨주기 Thread th3 = new Thread(new Runnable() { @Override public void run() { for(int i=1;i<=10;i++) { System.out.print("@"); } try { Thread.sleep(1000); }catch(InterruptedException e) { e.printStackTrace(); } } }); th1.start(); //start를 이용해 동작하도록 함 // 메인 thread가 thread1,2,3을 동작 시킴 -> 총 4개의 쓰레드가 동작 th2.start(); // 콜스택 하나 늘려주는 메소드 // 메인 말고 다른 쓰레드 하나가 실행하는 것 th3.start(); th1.run(); // 메인 스레드가 실행 System.out.println("메인 메소드 끗"); } } class MyThread1 extends Thread{ // 이 자체가 Thread @Override public void run() { //run이 실행하는 부분 for(int i=1;i<=10;i++) { System.out.print("*"); try { //Thread.sleep(시간) => 주어진 시간동안 작업을 잠시 멈춤 //시간은 밀리세컨드 단위 => 1000 은 1초 Thread.sleep(1000); }catch(InterruptedException e) { e.printStackTrace(); } } } } class MyThread2 implements Runnable{ // thread method run() - @Override public void run() { for(int i=1;i<=10;i++) { System.out.print("$"); try { //Thread.sleep(시간) => 주어진 시간동안 작업을 잠시 멈춤 //시간은 밀리세컨드 단위 => 1000 은 1초 Thread.sleep(1000); }catch(InterruptedException e) { e.printStackTrace(); } } } }
package com.FileHandling; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; class A { public void operation() throws IOException { File file = new File("C:\\Users\\nayak\\workspace\\IBM\\abc.txt"); FileInputStream fis = new FileInputStream(file); StringBuilder sb = new StringBuilder(""); int i = 0; do { i = fis.read(); if(i != -1) sb.append((char)i); } while(i != -1); // -1 represents end of file (EOF) System.out.println("File contents: "+ sb); fis.close(); file = new File("C:\\Users\\nayak\\workspace\\IBM\\def.txt"); FileOutputStream Fos = new FileOutputStream(file); Fos.write(sb.toString().getBytes()); Fos.flush(); Fos.close(); } } public class oneToOther { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub A obj=new A(); obj.operation(); } }
package com.maltem.dao; import java.util.List; import com.maltem.exception.ApplicationException; import com.maltem.model.Message; public interface TaskDao { Boolean updateMessage(Message message)throws ApplicationException; List<Message> getMessageList(Long stTime, Long endTime)throws ApplicationException; }
/** * */ package com.chamki.log.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author chamki * @version 1.0 * @createtime 2017-12-12 22:58:39 */ public class Client { private static final Logger logger = LoggerFactory.getLogger(Client.class); public static void main(String[] args) { logger.trace("trace level--信息"); logger.debug("debug level--信息"); logger.info("info level--信息"); logger.warn("warn level--信息"); logger.error("error level--信息"); //logger.fatal("fatal level--信息"); } }
package PrimerServlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author jesus */ @WebServlet(urlPatterns = {"/PrimerServlet/PrimerServlet"}) public class PrimerServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = new PrintWriter(res.getOutputStream()); out.println("<html>"); out.println("<head><title>HolaMundoServlet</title></head>"); out.println("<body>"); out.println("<h1><center>Hola Mundo desde el servidor WEB</center > </h1>"); out.println("</body></html>"); out.close(); } @Override public String getServletInfo() { return "Crea una página HTML que dice HolaMundo"; } }
package com.smartlead.api.user; import com.smartlead.api.user.repository.OrganizationRepository; import com.smartlead.api.user.repository.RoleRepository; import com.smartlead.api.user.repository.UserRepository; import com.smartlead.common.entity.Organization; import com.smartlead.common.entity.Role; import com.smartlead.common.entity.User; import org.dozer.DozerBeanMapper; import org.dozer.Mapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import java.util.HashSet; import java.util.List; import java.util.Set; @EnableEurekaServer @EnableZuulProxy @SpringBootApplication @EntityScan("com.smartlead.*") @EnableJpaRepositories("com.smartlead.*") @ComponentScan(basePackages = {"com.smartlead.*"}) public class UserMicroserviceApplication { private static final Logger log = LoggerFactory.getLogger(UserMicroserviceApplication.class); public static void main(String[] args) { SpringApplication.run(UserMicroserviceApplication.class, args); } @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } @Bean public Mapper mapper() { return new DozerBeanMapper(); } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("OPTIONS"); config.addAllowedMethod("GET"); config.addAllowedMethod("POST"); config.addAllowedMethod("PUT"); config.addAllowedMethod("DELETE"); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } @Bean public CommandLineRunner createTestUsers(UserRepository userRepository, OrganizationRepository organizationRepository, RoleRepository roleRepository) { return args -> { if (userRepository.count() == 0) { List<Organization> organizations = organizationRepository.findAll(); Role role = roleRepository.findByRoleName("Employee"); Set<Role> roles = new HashSet(); roles.add(role); for (int i = 1; i <= 3; i++) { User user = new User(); user.setFirstName("Test"); user.setLastName("User"); user.setUsername("user" + i); user.setMobile("+919898989898"); user.setEmail(user.getUsername() + "@user.com"); user.setOrganization(organizations.get(0)); user.setRoles(roles); user.setPassword(new BCryptPasswordEncoder().encode("changeme")); userRepository.save(user); } } }; } }
package configuracionesDeVistaCampoJugadores; import vista.Grilla; public class ConfiguracionIncialDeCampoDeJugadorB implements ConfiguracionDeLaVistaCampoJugadores{ @Override public void configurar(Grilla grilla) { //no hace nada con los botones, los deja en el estado en el que estaban } @Override public ConfiguracionDeLaVistaCampoJugadores obtenerSiguiente() { return new ConfigurarBotonesFaseInicialTurnoJugadorA(); } }
package com.hfjy.framework.common.entity; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class Folder implements Cloneable, Serializable { private static final long serialVersionUID = 1L; private String path; private String name; private List<Folder> folders = new ArrayList<>(); private List<FileInfo> fileInfos = new ArrayList<>(); public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public List<Folder> getFolders() { return folders; } public void setFolders(List<Folder> folders) { this.folders = folders; } public List<FileInfo> getFileInfos() { return fileInfos; } public void setFileInfos(List<FileInfo> fileInfos) { this.fileInfos = fileInfos; } public void addFile(FileInfo fileInfo) { fileInfos.add(fileInfo); } public void addFolder(Folder folder) { folders.add(folder); } @Override public Folder clone() throws CloneNotSupportedException { Folder folder = (Folder) super.clone(); folder.fileInfos = new ArrayList<FileInfo>(fileInfos); folder.folders = new ArrayList<Folder>(folders); return folder; } }
package nichol.springframework.springpetclinic.services; import nichol.springframework.springpetclinic.model.Vet; public interface VetService extends CrudService<Vet, Long> { }
package net.rafaeltoledo.vidabeta; import java.io.InputStream; import java.net.URL; import android.app.Activity; import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Message; import android.os.Messenger; import android.util.DisplayMetrics; import android.util.Log; import android.view.WindowManager; public class DownloadImageService extends IntentService { public static final String MESSENGER_EXTRA = "net.rafaeltoledo.MESSENGER_EXTRA"; public static final String IMAGE_LOCATION = "net.rafaeltoledo.IMAGE_LOCATION"; public DownloadImageService() { super("DownloadImageService"); } @Override protected void onHandleIntent(Intent intent) { Messenger messenger = (Messenger) intent.getExtras().get( MESSENGER_EXTRA); Message msg = Message.obtain(); try { Drawable imagem = getDrawable(intent.getStringExtra(IMAGE_LOCATION)); msg.arg1 = Activity.RESULT_OK; msg.obj = imagem; } catch (Exception ex) { Log.e(getString(R.string.app_name), "Falha no download!", ex); msg.arg1 = Activity.RESULT_CANCELED; msg.obj = ex; } try { messenger.send(msg); } catch (Exception ex) { Log.w(getString(R.string.app_name), "Falha ao enviar mensagem (download)", ex); } } private Drawable getDrawable(String url) throws Exception { URL u = new URL(url); InputStream is = (InputStream) u.getContent(); Drawable d = Drawable.createFromStream(is, "src"); DisplayMetrics metrics = new DisplayMetrics(); WindowManager wm = (WindowManager) getApplicationContext() .getSystemService(Context.WINDOW_SERVICE); wm.getDefaultDisplay().getMetrics(metrics); Log.i("ScreenInfo", String.valueOf(metrics.densityDpi)); if (metrics.densityDpi == DisplayMetrics.DENSITY_HIGH) { Bitmap bitmap = ((BitmapDrawable) d).getBitmap(); Bitmap tmp = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth() * 3, bitmap.getHeight() * 3, false); d = new BitmapDrawable(tmp); } return d; } }
/* * This Java source file was generated by the Gradle 'init' task. */ package Code.app; import kaptainwutax.biomeutils.source.OverworldBiomeSource; import kaptainwutax.featureutils.structure.Stronghold; import kaptainwutax.featureutils.structure.Village; import kaptainwutax.seedutils.mc.ChunkRand; import kaptainwutax.seedutils.mc.MCVersion; import kaptainwutax.featureutils.structure.SwampHut; import kaptainwutax.seedutils.mc.pos.CPos; import java.util.ArrayList; public class Main { public static void main(String[] args) { SwampHut SwampHut = new SwampHut(MCVersion.v1_16_2); Village Village = new Village(MCVersion.v1_16_2); Stronghold Stronghold = new Stronghold(MCVersion.v1_16_2); ChunkRand myChunkRand = new ChunkRand(); System.out.println("test"); int regionX; int regionY; for (long structureSeed = 0; structureSeed < 1L << 48; structureSeed++) { CPos vil1 = Village.getInRegion(structureSeed, regionX = 0, regionY = 0, myChunkRand); CPos hut2 = SwampHut.getInRegion(structureSeed, regionX = 0, regionY = 1, myChunkRand); CPos hut3 = SwampHut.getInRegion(structureSeed, regionX = 1, regionY = 0, myChunkRand); CPos hut4 = SwampHut.getInRegion(structureSeed, regionX = 0, regionY = 1, myChunkRand); if (Math.abs(vil1.getX() - hut2.getX()) < 8) { System.out.println(vil1.toString()); System.out.println(hut2.toString()); } } ArrayList<Long> structureSeed = new ArrayList<>(); OverworldBiomeSource OverworldBiomeSource=new OverworldBiomeSource(MCVersion.v1_16_2); for (Long structure : structureSeed) { CPos hut1 = SwampHut.getInRegion(structure, regionX = 0, regionY = 0, myChunkRand); for (int biomes = 0; biomes < 1 << 16; biomes++) { if (!SwampHut.canSpawn(hut1.getX().hut1.getY())); } } } }
package org.usfirst.frc.team178.robot.commands; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc.team178.robot.*; import org.usfirst.frc.team178.robot.subsystems.*; import edu.wpi.first.wpilibj.DriverStation; public class JoystickDrive extends Command { Encoders encoders; OI oi; DriveTrain drivetrain; double yVal,twistVal; public JoystickDrive() { requires(Robot.drivetrain); requires(Robot.encoders); } protected void initialize() { oi = Robot.oi; encoders = Robot.encoders; drivetrain = Robot.drivetrain; } protected void execute() { //Joystick returns from -1 to 1, motor takes values from -1 to 1. //Motors are attached backwards, hence the negatives yVal = -1*oi.getY(); twistVal = -1*oi.getTwist(); //System.out.println("Y Val: " + yVal); //System.out.println("Twist Val: " + twistVal); //System.out.println("X Val: " + oi.getX()); // 6wl tank drive has two motors on one gearbox that drive in the same direction. //The if condition implements what's called a dead zone. The controllers have some variances to them, //and this makes sure that the robot doesn't do anything we don't want it to. //Without this, the motor speed is never upset. //The robot would continue moving at its last speed. This makes it stop. if(Math.abs(yVal)>0.05 || Math.abs(twistVal)>0.05){ drivetrain.drive(-twistVal+yVal, -twistVal-yVal); } else { drivetrain.drive(0,0); } //System.out.println("rick"); } protected boolean isFinished() { return false; } protected void end() { // drivetrain.drive(0,0); } protected void interrupted() { } }
/** * Created with IntelliJ IDEA. * User: dexctor * Date: 13-1-2 * Time: 下午8:34 * To change this template use File | Settings | File Templates. */ public class TestLineGraph { public static void main(String[] args) { LineGraph G = new LineGraph(new In("lineG.txt")); StdOut.println(G.weight(0, G.V() - 1)); } }
package com.ecjtu.hotel.pojo; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; public class Guest { private Long id; private String name; private String idnum; private Integer roomnum; private String phone; private Date arraytime; private Date leavetime; private Integer receivable; private Integer deposit; private Integer status; public Guest(Long id, String name, String idnum, Integer roomnum, String phone, Date arraytime, Date leavetime, Integer receivable, Integer deposit, Integer status, String remark) { super(); this.id = id; this.name = name; this.idnum = idnum; this.roomnum = roomnum; this.phone = phone; this.arraytime = arraytime; this.leavetime = leavetime; this.receivable = receivable; this.deposit = deposit; this.status = status; this.remark = remark; } @Override public String toString() { return "Guest [id=" + id + ", name=" + name + ", idnum=" + idnum + ", roomnum=" + roomnum + ", phone=" + phone + ", arraytime=" + arraytime + ", leavetime=" + leavetime + ", receivable=" + receivable + ", deposit=" + deposit + ", status=" + status + ", remark=" + remark + "]"; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIdnum() { return idnum; } public void setIdnum(String idnum) { this.idnum = idnum; } public Integer getRoomnum() { return roomnum; } public void setRoomnum(Integer roomnum) { this.roomnum = roomnum; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Date getArraytime() { return arraytime; } public void setArraytime(Date arraytime) { this.arraytime = arraytime; } public Date getLeavetime() { return leavetime; } public void setLeavetime(Date leavetime) { this.leavetime = leavetime; } public Integer getReceivable() { return receivable; } public void setReceivable(Integer receivable) { this.receivable = receivable; } public Integer getDeposit() { return deposit; } public void setDeposit(Integer deposit) { this.deposit = deposit; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } private String remark; public Guest() { // TODO Auto-generated constructor stub } }
/* * Copyright (c) 2008-2019 Haulmont. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.haulmont.reports.app; import com.haulmont.cuba.security.entity.Group; import com.haulmont.cuba.security.entity.User; import com.haulmont.reports.testsupport.ReportsTestContainer; import org.junit.Assert; import org.junit.ClassRule; import org.junit.Test; public class EntityMapTest { @ClassRule public static ReportsTestContainer cont = ReportsTestContainer.Common.INSTANCE; @Test public void testGetValue() throws Exception { User user = new User(); user.setName("The User"); user.setLogin("admin"); Group group = new Group(); group.setName("The Group"); user.setGroup(group); EntityMap entityMap = new EntityMap(user); Assert.assertEquals("admin", entityMap.get("login")); Assert.assertEquals("The User", entityMap.get("name")); Assert.assertEquals("The User [admin]", entityMap.get(EntityMap.INSTANCE_NAME_KEY)); Assert.assertEquals("The Group", entityMap.get("group." + EntityMap.INSTANCE_NAME_KEY)); Assert.assertNull(entityMap.get("group...." + EntityMap.INSTANCE_NAME_KEY)); } }
package com.sirma.itt.javacourse.desing_patterns.task4.object_pool.test; import static org.junit.Assert.assertTrue; import org.apache.log4j.Logger; import org.junit.Before; import org.junit.Test; import com.sirma.itt.javacourse.desingpatterns.task4.objectpool.NoMoreResourcesException; import com.sirma.itt.javacourse.desingpatterns.task4.objectpool.User; import com.sirma.itt.javacourse.desingpatterns.task4.objectpool.UserPool; /** * Test class for {@link UserPool} * * @author Simeon Iliev */ public class TestUserPool { private static Logger log = Logger.getLogger(TestUserPool.class.getName()); private UserPool<User> pool; /** * Set up method. * * @throws Exception * something went wrong. */ @Before public void setUp() throws Exception { pool = new UserPool<User>(new User()); } /** * Test method for * {@link com.sirma.itt.javacourse.desingpatterns.task4.objectpool.UserPool#acquire()}. * * @throws NoMoreResourcesException */ @Test public void testAquareUser() throws NoMoreResourcesException { User user = pool.acquire(); assertTrue(user instanceof User); } /** * Test method for * {@link com.sirma.itt.javacourse.desingpatterns.task4.objectpool.UserPool#acquire()}. * * @throws NoMoreResourcesException */ @Test public void testAquareUserException() { User userOne = null, userTwo = null, userThree = null, userFour = null, userFive = null; try { userOne = pool.acquire(); userTwo = pool.acquire(); userThree = pool.acquire(); userFour = pool.acquire(); userFive = pool.acquire(); pool.acquire(); } catch (NoMoreResourcesException e) { assertTrue(e instanceof NoMoreResourcesException); } finally { try { pool.release(userOne); pool.release(userTwo); pool.release(userThree); pool.release(userFour); pool.release(userFive); } catch (NoMoreResourcesException e) { log.error(e.getMessage(), e); } } } /** * Test method for * {@link com.sirma.itt.javacourse.desingpatterns.task4.objectpool.UserPool#releseUser(com.sirma.itt.javacourse.desingpatterns.task4.objectpool.User)} * . */ @Test public void testReleseUser() { try { User user = pool.acquire(); pool.release(user); } catch (NoMoreResourcesException e) { log.error(e.getMessage(), e); } } }
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.io.InputStream; import java.io.PrintStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; import java.io.StringReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class Client { private String host; private int port; public Connection conn; public static void main(String[] args) throws UnknownHostException, IOException, SQLException { new Client("127.0.0.1", 12345); } public Client(String host, int port) throws IOException, UnknownHostException, SQLException { this.host = host; this.port = port; try { //Establish a driver Class.forName("com.mysql.jdbc.Driver").newInstance(); //Connect to the database conn = DriverManager.getConnection("jdbc:mysql://seitux2.adfa.unsw.edu.au/z5157409", "z5157409", "mysqlpass"); } catch (Exception ex) { System.err.println("Unable to load MySQL driver."); ex.printStackTrace(); } run(); } public void run() throws UnknownHostException, IOException, SQLException { // connect client to server Socket client = new Socket(host, port); System.out.println("Client successfully connected to server!"); // Get Socket output stream (where the client send her mesg) PrintStream output = new PrintStream(client.getOutputStream()); // ask for a nickname Scanner sc = new Scanner(System.in); System.out.print("Enter a nickname: "); String nickname = sc.nextLine(); System.out.print("Enter a password: "); String password = sc.nextLine(); // PreparedStatement ps = conn.prepareStatement("INSERT INTO ACCOUNT(username, password, created_at) VALUES(?,SHA2(CONCAT(CURRENT_TIMESTAMP,?),512),CURRENT_TIMESTAMP);"); // ps.setString(1, nickname); // ps.setString(2, password); // ps.executeUpdate(); boolean exists = false; PreparedStatement ps = conn.prepareStatement("SELECT * FROM ACCOUNT WHERE username = ? AND password = SHA2(CONCAT(created_at,?),512);"); ps.setString(1, nickname); ps.setString(2, password); ResultSet rs = ps.executeQuery(); if (rs.first()) { exists = true; } //Close the connection rs.close(); ps.close(); if (exists) { System.out.println("login successful"); } // send nickname to server output.println(nickname); // create a new thread for server messages handling new Thread(new ReceivedMessagesHandler(client.getInputStream())).start(); // read messages from keyboard and send to server System.out.println("Messages: \n"); // while new messages while (sc.hasNextLine()) { output.println(sc.nextLine()); } // end ctrl D output.close(); sc.close(); client.close(); } } class ReceivedMessagesHandler implements Runnable { private InputStream server; public ReceivedMessagesHandler(InputStream server) { this.server = server; } public void run() { // receive server messages and print out to screen Scanner s = new Scanner(server); String tmp = ""; while (s.hasNextLine()) { tmp = s.nextLine(); if (tmp.charAt(0) == '[') { tmp = tmp.substring(1, tmp.length() - 1); System.out.println( "\nUSERS LIST: " + new ArrayList<String>(Arrays.asList(tmp.split(","))) + "\n" ); } else { try { System.out.println("\n" + getTagValue(tmp)); // System.out.println(tmp); } catch (Exception ignore) { } } } s.close(); } // I could use a javax.xml.parsers but the goal of Client.java is to keep everything tight and simple public static String getTagValue(String xml) { return xml.split(">")[2].split("<")[0] + xml.split("<span>")[1].split("</span>")[0]; } }
package com.sinodynamic.hkgta.entity.pos; import javax.persistence.*; import java.io.Serializable; import java.util.Date; @Entity @Table(name = "restaurant_booking_quota") public class RestaurantBookingQuota implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name = "quota_id") private Long quotaId; @ManyToOne @JoinColumn(name = "restaurant_id") private RestaurantMaster restaurantMaster; @Column(name = "period_code") private String periodCode; @Column(name = "start_time") private Integer startTime; @Column(name = "end_time") private Integer endTime; @Column(name = "quota") private Integer quota; @Column(name = "create_by", length = 50) private String createBy; @Temporal(TemporalType.TIMESTAMP) @Column(name = "create_date") private Date createDate; @Column(name = "update_by", length = 50) private String updateBy; @Temporal(TemporalType.TIMESTAMP) @Column(name = "update_date") private Date updateDate; @Version @Column(name = "ver_no") private Long verNo; public Long getQuotaId() { return quotaId; } public void setQuotaId(Long quotaId) { this.quotaId = quotaId; } public RestaurantMaster getRestaurantMaster() { return restaurantMaster; } public void setRestaurantMaster(RestaurantMaster restaurantMaster) { this.restaurantMaster = restaurantMaster; } public String getPeriodCode() { return periodCode; } public void setPeriodCode(String periodCode) { this.periodCode = periodCode; } public Integer getStartTime() { return startTime; } public void setStartTime(Integer startTime) { this.startTime = startTime; } public Integer getEndTime() { return endTime; } public void setEndTime(Integer endTime) { this.endTime = endTime; } public Integer getQuota() { return quota; } public void setQuota(Integer quota) { this.quota = quota; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public String getUpdateBy() { return updateBy; } public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } public Long getVerNo() { return verNo; } public void setVerNo(Long verNo) { this.verNo = verNo; } }
package com.cb.cbfunny.tv.adapter; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.cb.cbfunny.Constans; import com.cb.cbfunny.R; import com.cb.cbfunny.tv.fragment.TVOnlineTypeFragment; public class IndicatorFragmentAdapter extends FragmentPagerAdapter{ protected static final Integer[] CONTENT = new Integer[] { R.string.content_type_central, R.string.content_type_internal, R.string.content_type_hk, R.string.content_type_japan, R.string.content_type_europe}; protected static final Integer[] TYPES = new Integer[]{ Constans.TV_TYPE_CENTRAL, Constans.TV_TYPE_INTERNAL, Constans.TV_TYPE_HK, Constans.TV_TYPE_JAPAN, Constans.TV_TYPE_EUROPE }; // protected static final int[] ICONS = new int[] { // R.drawable.perm_group_calendar, // R.drawable.perm_group_camera, // R.drawable.perm_group_device_alarms, // R.drawable.perm_group_location // }; private Context mContext; private int mCount = CONTENT.length; public IndicatorFragmentAdapter(FragmentManager fm,Context ctx) { super(fm); mContext = ctx; } @Override public Fragment getItem(int position) { return TVOnlineTypeFragment.getInstance(TYPES[position % TYPES.length]); } @Override public int getCount() { return mCount; } @Override public CharSequence getPageTitle(int position) { return mContext.getString(IndicatorFragmentAdapter.CONTENT[position % CONTENT.length]); } public void setCount(int count) { if (count > 0 && count <= 10) { mCount = count; notifyDataSetChanged(); } } }
package com.bslp_lab1.changeorg.validation; import com.bslp_lab1.changeorg.DTO.PetitionDTO; import com.bslp_lab1.changeorg.exceptions.PetitionValidationException; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; @Service public class PetitionValidationService { public void validatePetitionDTO(PetitionDTO petitionDTO) throws PetitionValidationException { if(!validateTopicPetitionDTO(petitionDTO.getTopic())){ throw new PetitionValidationException("Invalid topic", HttpStatus.BAD_REQUEST); }else if(!validateSignGoalPetitionDTO(petitionDTO.getSignGoal())){ throw new PetitionValidationException("Sign goal must be a positive int", HttpStatus.BAD_REQUEST); } } public boolean validateTopicPetitionDTO(String topic){ int length = topic.length(); if(length < 5){ return false; }else if(length > 40){ return false; } return true; } public boolean validateSignGoalPetitionDTO(int signGoal){ if(signGoal<0){ return false; } return true; } }
package com.logzc.webzic.collection; /** * Created by lishuang on 2016/7/29. */ public class MapBean0 { public String name; }
package com.example.jwtdemo2.services; import com.example.jwtdemo2.models.User; import com.example.jwtdemo2.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class UserService { @Autowired UserRepository userRepository; public int updateUserById(Long id, User user,int email){ if(email==1) { userRepository.updateUserEmail(id, user.getEmail()); } userRepository.updateUserFirst(id,user.getFirstName()); userRepository.updateUserLast(id,user.getLastName()); return 1; } public Optional<User> findUserById(Long id) { return userRepository.findById(id); } public boolean existsEmail(String email){ return userRepository.existsByEmail(email); } public List<User> findAllUser(){ List<User> s=new ArrayList<>(); userRepository.findAll().forEach(s::add); return s; } }
package dwz.web; import javax.servlet.http.HttpServletRequest; 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 dwz.framework.config.Constants; import dwz.framework.user.User; import dwz.framework.user.UserServiceMgr; /** * @Author: LCF * @Date: 2020/1/8 17:41 * @Package: dwz.web */ @Controller @RequestMapping(value = "/passport") public class PassportController extends BaseController { @Autowired private UserServiceMgr userMgr; // @RequestMapping("/register") // public ModelAndView register(User user){ // try { // userMgr.register(user); // } catch (ServiceException e) { // return ajaxDoneError(e.getMessage()); // } // // return ajaxDoneSuccess(getMessage("msg.operation.success")); // } // @RequestMapping("/verify/{verifyCode}") // public String verify(@PathVariable("verifyCode") String verifyCode, Model model) { // try { // userMgr.verify(verifyCode); // } catch (ServiceException e) { // model.addAttribute("statusCode", 300); // model.addAttribute("message", e.getMessage()); // } // return "/alert"; // } // @RequestMapping("/sendVerifyEmail/{username}") // public ModelAndView sendVerifyEmail(@PathVariable("username") String username, Model model) { // try { // User user = userMgr.getUserByUsername(username); // userMgr.sendVerifyEmail(user); // } catch (ServiceException e) { // ajaxDoneError(e.getMessage()); // } // return ajaxDoneSuccess(getMessage("msg.operation.success")); // } @RequestMapping("/login") public ModelAndView login(HttpServletRequest request) { ModelAndView mv = new ModelAndView("login"); mv.addObject("coCodes", this.userMgr.getCoCodes()); String coCode = request.getParameter("coCode"); String username = request.getParameter("username"); String password = request.getParameter("password"); // try { // if (isSkipVC() || this.verifyValidationCode(getValidationCode())) { // loginOk = userMgr.hasMatchUser(username, password); // } else { // setStatusCode(300); // setMessage(this.getText("msg.validation.code.match")); // } // // } catch (AuthenticationException e) { // setStatusCode(300); // setMessage(e.getLocalizedMessage()); // } if ((username == null || username.trim().equals("")) && (password == null || password.trim().equals(""))) { mv.addObject("error", getMessage("ivf.login.inputusernamepassword")); return mv; } else if ((username == null || username.trim().equals("")) && (password != null && !password.trim().equals(""))) { mv.addObject("error", getMessage("ivf.login.inputusername")); return mv; } else if ((username != null && !username.trim().equals("")) && (password == null || password.trim().equals(""))) { mv.addObject("username", username); mv.addObject("error", getMessage("ivf.login.inputpassword")); return mv; } else { // 帐号和密码都有 User user = userMgr.getUserByUsernameAndCocode(username, coCode); if (user != null && password != null && password.equals(user.getUsrPass())) { //登录成功 request.getSession().setAttribute(Constants.AUTHENTICATION_KEY, user); //request.getSession().setAttribute("user", user); ModelAndView indexMv = new ModelAndView("forward:/management/index"); //set session scope "hospital name" for print page // indexMv.addObject("authorizationVo", authorizationVo); return indexMv; // return new ModelAndView("forward:/management/index", "", ""); } else { //用户名或者是密码错误 mv.addObject("username", username); mv.addObject("error", getMessage("ivf.login.wrongusernameorpassword")); return mv; } } } @RequestMapping("/logout") public String logout(HttpServletRequest request) { // ModelAndView logoutMv = new ModelAndView("logout"); ModelAndView logoutMv = new ModelAndView("login"); request.getSession().removeAttribute(Constants.AUTHENTICATION_KEY); request.getSession().removeAttribute("user"); request.getSession().removeAttribute("hospitalName"); request.getSession().invalidate();//注销 String locale = (String) request.getParameter("locale"); // logoutMv.addObject("locale", locale); return "redirect:/login" + "?locale=" + locale; } }
package com.atlassian.theplugin.idea.action.bamboo; import com.atlassian.theplugin.idea.IdeaHelper; import com.atlassian.theplugin.idea.bamboo.BuildToolWindow; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; /** * User: jgorycki * Date: Jan 22, 2009 * Time: 12:03:00 PM */ public class JumpToSourceAction extends AnAction { public void actionPerformed(AnActionEvent e) { BuildToolWindow window = IdeaHelper.getBuildToolWindow(e); window.jumpToSource(e.getPlace()); } public void update(AnActionEvent e) { BuildToolWindow window = IdeaHelper.getBuildToolWindow(e); if (window != null) { e.getPresentation().setEnabled(window.canJumpToSource(e.getPlace())); } super.update(e); } }
package com.ipiecoles.java.java210; public class Main { public static void main(String[] args) throws Exception { Sudoku monSudoku = new Sudoku(); monSudoku.remplitSudokuATrous(monSudoku.demandeCoordonneesSudoku()); monSudoku.ecrireSudoku(monSudoku.getSudokuAResoudre()); if(monSudoku.resoudre(0, 0, monSudoku.getSudokuAResoudre())){ monSudoku.ecrireSudoku(monSudoku.getSudokuAResoudre()); } else { System.out.println("Pas de solution..."); } } } /*018 034 052 076 * 113 124 169 171 * 209 216 278 284 * 332 341 356 * 533 545 557 * 608 614 677 685 * 712 726 761 773 * 819 837 851 874 */
package math.doubleV; import asj.LoadManager; import asj.data.JSONObject; public class CartesianAxes extends AbstractAxes { public CartesianAxes(AbstractBasis globalBasis, AbstractAxes parent) { super(globalBasis, parent); } public CartesianAxes(Vec3d<?> origin, Vec3d<?> inX, Vec3d<?> inY, Vec3d<?> inZ, AbstractAxes parent) { super(origin, inX, inY, inZ, parent, true); createTempVars(origin); areGlobal = true; localMBasis = new CartesianBasis(origin, inX, inY, inZ); globalMBasis = new CartesianBasis(origin, inX, inY, inZ); Vec3d<?> o = origin.copy(); o.set(0,0,0); Vec3d<?> i = o.copy(); i.set(1,1,1); if(parent != null) { this.setParent(parent); } else { this.areGlobal = true; } this.markDirty(); this.updateGlobal(); } public sgRayd x_() { this.updateGlobal(); return this.getGlobalMBasis().getXRay(); } public sgRayd y_() { this.updateGlobal(); return this.getGlobalMBasis().getYRay(); } public sgRayd z_() { this.updateGlobal(); return this.getGlobalMBasis().getZRay(); } @Override public <A extends AbstractAxes> boolean equals(A ax) { this.updateGlobal(); ax.updateGlobal(); boolean composedRotationsAreEquivalent = getGlobalMBasis().rotation.equals(ax.globalMBasis.rotation); boolean originsAreEquivalent = getGlobalMBasis().getOrigin().equals(ax.origin_()); return composedRotationsAreEquivalent && originsAreEquivalent; } @Override public CartesianAxes getGlobalCopy() { return new CartesianAxes(getGlobalMBasis(), this.getParentAxes()); } @Override public AbstractAxes relativeTo(AbstractAxes in) { // TODO Auto-generated method stub return null; } @Override public AbstractAxes getLocalOf(AbstractAxes input) { // TODO Auto-generated method stub return null; } @Override public AbstractAxes freeCopy() { AbstractAxes freeCopy = new CartesianAxes(this.getLocalMBasis(), null); freeCopy.getLocalMBasis().adoptValues(this.localMBasis); freeCopy.markDirty(); freeCopy.updateGlobal(); return freeCopy; } @Override public void loadFromJSONObject(JSONObject j, LoadManager l) { super.loadFromJSONObject(j, l); } /** * Creates an exact copy of this Axes object. Attached to the same parent as this Axes object * @param slipAware * @return */ @Override public CartesianAxes attachedCopy(boolean slipAware) { this.updateGlobal(); CartesianAxes copy = new CartesianAxes(getGlobalMBasis(), this.getParentAxes()); if(!slipAware) copy.setSlipType(IGNORE); copy.getLocalMBasis().adoptValues(this.localMBasis); copy.markDirty(); return copy; } @Override public <B extends AbstractBasis> B getLocalOf(B input) { CartesianBasis newBasis = new CartesianBasis((CartesianBasis)input); getGlobalMBasis().setToLocalOf(input, newBasis); return (B)newBasis; } }
package com.esum.wp.ims.notifymoduleinfo.dao; import java.util.Map; import com.esum.appframework.dao.IBaseDAO; import com.esum.wp.ims.notifymoduleinfo.NotifyModuleInfo; public interface INotifyModuleInfoDAO extends IBaseDAO{ public Map saveNotifyModuleInfoExcel(NotifyModuleInfo info); }
package com.share.dao; import com.share.template.HibernateTemplate; public class PlatformDao extends HibernateTemplate { }
package com.example.myapplication; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.location.Geocoder; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.CardView; import android.telecom.Call; import android.text.style.CharacterStyle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.places.AutocompletePrediction; import com.google.android.gms.location.places.AutocompletePredictionBuffer; import com.google.android.gms.location.places.AutocompletePredictionBufferResponse; import com.google.android.gms.location.places.GeoDataClient; import com.google.android.gms.location.places.Place; import com.google.android.gms.location.places.PlaceDetectionClient; import com.google.android.gms.location.places.PlaceLikelihood; import com.google.android.gms.location.places.PlaceLikelihoodBufferResponse; import com.google.android.gms.location.places.Places; import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment; import com.google.android.gms.location.places.ui.PlacePicker; import com.google.android.gms.location.places.ui.PlaceSelectionListener; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.MapsInitializer; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectStreamException; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class Mappa extends AppCompatActivity implements OnMapReadyCallback { private String TAG = "MAP_LIFE"; private MapView vMappa; private GoogleMap mGoogleMap; private CardView vCard; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Locale locale = new Locale("it"); Configuration configs = getBaseContext().getResources().getConfiguration(); configs.locale = locale; getBaseContext().getResources().updateConfiguration(configs, getBaseContext().getResources().getDisplayMetrics()); getApplicationContext().getResources().updateConfiguration(configs, getBaseContext().getResources().getDisplayMetrics()); setContentView(R.layout.layout_mappa); vCard = findViewById(R.id.Card); vMappa = findViewById(R.id.vMappa); vMappa.onCreate(savedInstanceState); vMappa.getMapAsync(this); final PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment); autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() { @Override public void onPlaceSelected(Place place) { // TODO: Get info about the selected place. mGoogleMap.clear(); mGoogleMap.addMarker(new MarkerOptions().position(place.getLatLng())); mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(place.getLatLng(), 10)); Log.i(TAG, "Place: " + place.getName()); LatLngBounds latLngBounds = new LatLngBounds(place.getLatLng(), place.getLatLng()); PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder(); builder.setLatLngBounds(latLngBounds); try { startActivityForResult(builder.build(Mappa.this), 3); } catch (Exception e) { Log.e(TAG, e.getStackTrace().toString()); } } @Override public void onError(Status status) { // TODO: Handle the error. Log.i(TAG, "An error occurred: " + status); } }); } protected void onResume() { vMappa.onResume(); super.onResume(); } @SuppressLint("MissingPermission") @Override public void onMapReady(GoogleMap googleMap) { mGoogleMap = googleMap; mGoogleMap.getUiSettings().setZoomControlsEnabled(true); try { MapsInitializer.initialize(this); } catch (Exception e) { e.printStackTrace(); } LatLng llAversa = new LatLng(40.9675999, 14.1996051); mGoogleMap.addMarker(new MarkerOptions().position(llAversa).title("Locazione abitazione").title("La mia posizione")); mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(llAversa, 15)); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 3) { if (resultCode == RESULT_OK) { Place place = PlacePicker.getPlace(getApplicationContext(), data); mGoogleMap.addMarker(new MarkerOptions().position(place.getLatLng()).title(place.getName().toString()) .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))); mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(place.getLatLng(), 15)); //String toastMsg = String.format("Place: %s", place.getName()); //Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show(); } } } }
package com.example.shivam.myapplication; import android.app.ProgressDialog; import android.content.Context; import android.graphics.Color; import android.os.AsyncTask; import android.view.View; import android.widget.TextView; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * Created by shivam on 30-05-2017. */ public class LoadData extends AsyncTask<String,Void,Void>{ Context context; View view; TextView tv1,tv2,tv3,tv4; String s[]; ProgressDialog progressDialog; public LoadData(Context context,TextView tv1,TextView tv2,TextView tv3,TextView tv4) { this.context=context; this.tv1=tv1; this.tv2=tv2; this.tv3=tv3; this.tv4=tv4; } @Override protected void onPreExecute() { super.onPreExecute(); progressDialog= new ProgressDialog(context); progressDialog.setTitle("Fetching Load Data..."); progressDialog.setMessage("Please wait..."); progressDialog.setCancelable(true); progressDialog.show(); } @Override protected Void doInBackground(String... params) { URL url= null; String Data; try { url = new URL(params[0]); HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection(); urlConnection.connect(); InputStream in=new BufferedInputStream(urlConnection.getInputStream()); BufferedReader br=new BufferedReader(new InputStreamReader(in)); Data=br.readLine(); s=Data.split(":"); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); if(progressDialog.isShowing())progressDialog.dismiss(); float per=Float.parseFloat(s[0]); float tot=Float.parseFloat(s[1]); float free=Float.parseFloat(s[2]); float perFree=(free/tot)*100; tv1.setText(s[0]+"%"); tv2.setText(Converter.convert(s[1])); tv3.setText(Converter.convert(s[2])); if((per>=90) && (per<=100)) tv1.setTextColor(Color.parseColor("#aa0505")); else if((per>=70) && (per<90)) tv1.setTextColor(Color.parseColor("#e56232")); else if((per>=0) && (per<70)) tv1.setTextColor(Color.parseColor("#2176dd")); if((perFree>=90) && (perFree<=100)) tv3.setTextColor(Color.parseColor("#2176dd")); else if((perFree>=70) && (perFree<90)) tv3.setTextColor(Color.parseColor("#e56232")); else if((per>=0) && (per<50)) tv3.setTextColor(Color.parseColor("#aa0505")); String f=""; int x=0; for(int i=0;i<s.length;i++) { if(s[i].matches("[A-Za-z]")&&s[i+1].matches("[0-9]+")&&s[i+2].matches("[0-9]+")) { f=f+(s[i]); f=f+"\t\t\t"+Converter.convert(s[i+1]); f=f+"\t\t\t"+Converter.convert(s[i+2]); f=f+"\n"; x++; } } if(x>0) { tv4.setText("Drive \t\t\t Total Free \t\t\t Total Capacity"+"\n"+f); } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pmm.sdgc.dao; import com.pmm.sdgc.model.Lotacao; import com.pmm.sdgc.model.Solicitacao; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; /** * * @author ajuliano */ @Stateless public class LotacaoDao { @PersistenceContext EntityManager em; public List<Lotacao> getLotacao(){ Query q=em.createQuery("select lo from Lotacao lo where lo.ativo = true order by trim(lo.nome)"); //return q.setMaxResults(10).getResultList(); return q.getResultList(); } public List<Lotacao> getLotacaoAtivo(String idFunc){ Query q=em.createQuery("select lo from Lotacao lo where lo.ativo = 1 order by trim(lo.nome)"); return q.getResultList(); } public Lotacao getLotacaoPorId(String id) throws Exception { Query q = em.createQuery("select l from Lotacao l where l.id = :id"); q.setParameter("id", id); List<Lotacao> lotacoes = q.getResultList(); if (lotacoes.isEmpty()) { throw new Exception("Lotacao com o id " + id + " nao encontrado"); } return lotacoes.get(0); } public void incluir(Lotacao lo) throws Exception { em.persist(lo); } public void alterar(Lotacao lo) throws Exception { em.merge(lo); } public void remover(Lotacao lo) throws Exception { Query q = em.createQuery("select lo from Lotacao lo where lo = :ca"); q.setParameter("ca", lo); List<Lotacao> l = q.getResultList(); if (l.isEmpty()) throw new Exception("Lotação não encontrada!"); Lotacao car = l.get(0); em.remove(car); } }
package com.example.fileshare.model; public enum Category { MEN, WOMEN, ACCESSORIES }
/** * Nutzer Repository */ package de.verteilteanzeigetafel.repo; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.data.repository.CrudRepository; import de.verteilteanzeigetafel.entities.Nutzer; import java.util.ArrayList; import java.util.List; import java.util.Optional; // Schnittstelle zur Datenbank, CRUD= Create, Read, Update, Delete [Rest funktionalitaeten]. public interface NutzerRepository extends CrudRepository <Nutzer, Long> { Optional<Nutzer> findByName(String name); }
package com.appirio.service.member.api; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.Setter; /** * Represents External accounts bit bucket * * Created by rakeshrecharla on 9/11/15. */ @DynamoDBTable(tableName="Externals.BitBucket") public class ExternalAccountsBitBucket { /** * Id of the user */ @DynamoDBHashKey @Getter @Setter @JsonIgnore private Integer userId; /** * Handle of the user */ @Getter @Setter private String handle; /** * Followers */ @Getter @Setter private Long followers; /** * Languages */ @Getter @Setter private String languages; /** * Profile URL */ @JsonProperty("profileURL") @Getter @Setter private String profileUrl; /** * Repos */ @Getter @Setter private Long repos; }
package com.arthur.leetcode; /** * @title: No34 * @Author ArthurJi * @Date: 2021/3/9 11:15 * @Version 1.0 */ public class No34 { public int[] searchRange(int[] nums, int target) { int len = nums.length; if (len == 0) { return new int[]{-1, -1}; } int left = findFirstPosition(nums, target); if (left == -1) { return new int[]{-1, -1}; } int right = findLastPosition(nums, target); return new int[]{left, right}; } private int findFirstPosition(int[] nums, int target) { int left = 0; int right = nums.length - 1; while (left < right) { int mid = left + (right - left) / 2; //注意俩个函数这里是不一样的,当left和right靠近时,决定mid是left还是rigth,这里是right,因为要找第一个 if (nums[mid] > target) { right = mid - 1; } else if (nums[mid] < target) { left = mid + 1; } else { right = mid;//注意这里也是不一样的 } } if(nums[left] == target) { //这里只能是left,因为right会变成mid-1, 可能会翻车,此时right==left - 1 right和mid是一样的 return left; } return -1; } private int findLastPosition(int[] nums, int target) { int left = 0; int right = nums.length - 1; while (left < right) { int mid = left + (right - left + 1) / 2; if (nums[mid] > target) { right = mid - 1; } else if (nums[mid] < target) { left = mid + 1; } else { left = mid; } } return right; //这里返回right和left都行,因为有前一个函数保驾护航,肯定会有target出现。但是最好写成right, // 同理,当一般情况下不存在target时,left会越过right,那时候就翻车了 } } /* 34. 在排序数组中查找元素的第一个和最后一个位置 给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。 如果数组中不存在目标值 target,返回 [-1, -1]。 进阶: 你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗? 示例 1: 输入:nums = [5,7,7,8,8,10], target = 8 输出:[3,4] 示例 2: 输入:nums = [5,7,7,8,8,10], target = 6 输出:[-1,-1] 示例 3: 输入:nums = [], target = 0 输出:[-1,-1]*/ /* public class Solution { public int[] searchRange(int[] nums, int target) { int len = nums.length; if (len == 0) { return new int[]{-1, -1}; } int firstPosition = findFirstPosition(nums, target); if (firstPosition == -1) { return new int[]{-1, -1}; } int lastPosition = findLastPosition(nums, target); return new int[]{firstPosition, lastPosition}; } private int findFirstPosition(int[] nums, int target) { int left = 0; int right = nums.length - 1; while (left < right) { int mid = left + (right - left) / 2; // 小于一定不是解 if (nums[mid] < target) { // 下一轮搜索区间是 [mid + 1, right] left = mid + 1; } else if (nums[mid] == target) { // 下一轮搜索区间是 [left, mid] right = mid; } else { // nums[mid] > target,下一轮搜索区间是 [left, mid - 1] right = mid - 1; } } if (nums[left] == target) { return left; } return -1; } private int findLastPosition(int[] nums, int target) { int left = 0; int right = nums.length - 1; while (left < right) { int mid = left + (right - left + 1) / 2; if (nums[mid] > target) { // 下一轮搜索区间是 [left, mid - 1] right = mid - 1; } else if (nums[mid] == target){ // 下一轮搜索区间是 [mid, right] left = mid; } else { // nums[mid] < target,下一轮搜索区间是 [mid + 1, right] left = mid + 1; } } return left; } } 作者:liweiwei1419 链接:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/solution/si-lu-hen-jian-dan-xi-jie-fei-mo-gui-de-er-fen-cha/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/
package com.lsjr.zizisteward; import android.app.Application; import android.content.res.Configuration; import android.graphics.Point; import android.view.WindowManager; import com.facebook.drawee.backends.pipeline.Fresco; import com.lsjr.net.BaseUrl; import com.lsjr.net.DcodeService; import com.lsjr.zizisteward.activity.contentprovider.Global; import com.lsjr.zizisteward.http.AppUrl; import com.taobao.sophix.PatchStatus; import com.taobao.sophix.SophixManager; import com.taobao.sophix.listener.PatchLoadStatusListener; import com.tencent.mm.opensdk.openapi.IWXAPI; import com.tencent.mm.opensdk.openapi.WXAPIFactory; import com.ymz.baselibrary.BaseApplication; import com.ymz.baselibrary.utils.L_; import cn.sharesdk.framework.ShareSDK; /** * 创建人:gyymz1993 * 创建时间:2017/4/14/12:13 **/ public class MyApplication extends Application { // 自己微信应用的 appId public static String WX_APP_ID = "wx388b90f68846eb73"; // 自己微信应用的 appSecret public static String WX_SECRET = "ab78f012fd5b2ce002cd1b3fe209265b"; public static String WX_CODE = ""; //商户号 public static final String WX_MCH_ID = "1317019401"; // API密钥,在商户平台设置 public static final String API_KEY = "34e5ae602475c96bf826cf425b9b77c5"; // 自己qq应用的 appId public static String QQ_APP_ID = "1105677331"; public static String QQ_APP_KEY = "v4RibiP3xgbECbX7"; public static IWXAPI wxApi; //public static Tencent mTencent; @Override public void onCreate() { super.onCreate(); resetDensity(); Global.init(this); BaseApplication.instance().initialize(this); BaseUrl.setBastUrl(AppUrl.HOST); DcodeService.initialize(this); //UploadService.initialize(this); //LoaderFactory.initLoaderFactory(this); Fresco.initialize(this); LoadingLayoutInit(); wxApi = WXAPIFactory.createWXAPI(this, WX_APP_ID, true); wxApi.registerApp(WX_APP_ID); // mTencent = Tencent.createInstance(QQ_APP_ID, this.getApplicationContext()); /*微博*/ ShareSDK.initSDK(this); //aliSophixManager(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); resetDensity(); } public final static float DESIGN_WIDTH = 750; //绘制页面时参照的设计图宽度 public void resetDensity(){ Point size = new Point(); ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay().getSize(size); getResources().getDisplayMetrics().xdpi = size.x/DESIGN_WIDTH*72f; } String appVersion = "1.1.0"; public void aliSophixManager() { // initialize最好放在attachBaseContext最前面 SophixManager.getInstance().setContext(this) .setAppVersion(appVersion) .setAesKey(null) .setEnableDebug(true) .setPatchLoadStatusStub(new PatchLoadStatusListener() { @Override public void onLoad(final int mode, final int code, final String info, final int handlePatchVersion) { // 补丁加载回调通知 L_.e("补丁加载回调通知:" + handlePatchVersion); if (code == PatchStatus.CODE_LOAD_SUCCESS) { // 表明补丁加载成功 L_.e("补丁加载成功:" + handlePatchVersion); } else if (code == PatchStatus.CODE_LOAD_RELAUNCH) { // 表明新补丁生效需要重启. 开发者可提示用户或者强制重启; // 建议: 用户可以监听进入后台事件, 然后应用自杀 L_.e("补丁生效需要重启. 开发者可提示用户或者强制重启:" + handlePatchVersion); } else if (code == PatchStatus.CODE_LOAD_FAIL) { // 内部引擎异常, 推荐此时清空本地补丁, 防止失败补丁重复加载 // SophixManager.getInstance().cleanPatches(); } else { // 其它错误信息, 查看PatchStatus类说明 } } }).initialize(); // queryAndLoadNewPatch不可放在attachBaseContext 中,否则无网络权限,建议放在后面任意时刻,如onCreate中 } private void LoadingLayoutInit() { } }
package com.crypto.document; import java.util.Map; import com.fasterxml.jackson.annotation.JsonProperty; public class RealTimeCryptData { @JsonProperty("Time Series (Digital Currency Intraday)") public Map<String, Object> payload; public Map<String, Object> getPayload() { return payload; } public void setPayload(Map<String, Object> payload) { this.payload = payload; } }
package deckofcardsapi; import io.restassured.RestAssured; import io.restassured.http.Method; import io.restassured.path.json.JsonPath; import io.restassured.response.Response; import org.testng.Assert; import org.testng.annotations.Test; import org.testng.annotations.BeforeClass; public class NewDeckofCardsTest { private static final String BASE_URL="https://deckofcardsapi.com"; private static final String JOCKERS_ENABLED="jokers_enabled"; private static final String NEW_DECK="/api/deck/new"; private static final String DECK_ID= "deck_id"; private static final String SUCCESS="success"; private static final String SHUFFLED="shuffled"; private static final String REMAINING="remaining"; private static final int SUCCESS_STATUS_CODE=200; @BeforeClass public static void setUp(){ RestAssured.baseURI=BASE_URL; } @Test public void createNewDeck(){ Response response=RestAssured.given().log().all().queryParam(JOCKERS_ENABLED,"false").request(Method.GET,NEW_DECK); checkNewDeck(response,52); Response response2=RestAssured.given().log().all().request(Method.GET,NEW_DECK); checkNewDeck(response2,52); } @Test public void addNewDeckJokers(){ Response response=RestAssured.given().log().all().queryParam(JOCKERS_ENABLED,"true").request(Method.GET,NEW_DECK); checkNewDeck(response,54); } private static void checkNewDeck(Response response,int numberOfCards){ Assert.assertEquals(SUCCESS_STATUS_CODE,response.getStatusCode()); JsonPath jsonPathEV=response.jsonPath(); Assert.assertEquals(true,jsonPathEV.get(SUCCESS)); Assert.assertEquals(numberOfCards,jsonPathEV.get(REMAINING)); Assert.assertEquals(false,jsonPathEV.get(SHUFFLED)); Assert.assertNotNull(jsonPathEV.get(DECK_ID)); } }
/* * (C) Copyright 2018 Fresher Academy. All Rights Reserved. * * @author viettn.admin * @date Apr 20, 2018 * @version 1.0 */ package edu.fa.service; public class EmployeeService { public int authenticate(String username, String password) { if(username.equals("David") && password.equals("Beckham")) { return 1; } return 0; } }
/* * 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 negocio; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author ian */ public class GerenciadoraContasTest { private GerenciadoraContas gerenciadoraContas; public GerenciadoraContasTest() { } @Before public void setUp() { List<ContaCorrente> contasDoBanco = new ArrayList<>(); contasDoBanco.add(new ContaCorrente(1, 100, true)); contasDoBanco.add(new ContaCorrente(2, 0, true)); contasDoBanco.add(new ContaCorrente(3, 1000, true)); this.gerenciadoraContas = new GerenciadoraContas(contasDoBanco); } @Test public void testTransfereValor_SaldoPositivo() { int contaOrigem = 1; int contaDestino = 2; boolean success = this.gerenciadoraContas.transfereValor(contaOrigem, 50, contaDestino); assertTrue(success); } @Test public void testTransfereValor_SaldoNegativo() { int contaOrigem = 2; int contaDestino = 1; boolean success = this.gerenciadoraContas.transfereValor(contaOrigem, 100, contaDestino); assertFalse(success); } @Test public void testTransfereValorValorMaiorQueOSaldo() { int contaOrigem = 1; int contaDestino = 2; boolean success = this.gerenciadoraContas.transfereValor(contaOrigem, 1000, contaDestino); assertFalse(success); } @Test public void testTransfereValorContaOrigemInexistente() { int contaOrigem = 4; int contaDestino = 1; boolean success = this.gerenciadoraContas.transfereValor(contaOrigem, 100, contaDestino); assertFalse(success); } @Test public void testTransfereValorContaDestinoInexistente() { int contaOrigem = 1; int contaDestino = 4; boolean success = this.gerenciadoraContas.transfereValor(contaOrigem, 100, contaDestino); assertFalse(success); } }
package net.lantrack.framework.sysbase.service.imp; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import net.lantrack.framework.core.lcexception.ServiceException; import net.lantrack.framework.core.service.BaseDao; import net.lantrack.framework.core.service.BaseService; import net.lantrack.framework.sysbase.dao.SysDataruleMapper; import net.lantrack.framework.sysbase.entity.SysDatarule; import net.lantrack.framework.sysbase.entity.SysDataruleExample; import net.lantrack.framework.sysbase.entity.SysDataruleExample.Criteria; import net.lantrack.framework.sysbase.model.menu.DataRuleTree; import net.lantrack.framework.sysbase.service.AuthorizingService; import net.lantrack.framework.sysbase.service.SysDataruleService; import net.lantrack.framework.sysbase.util.UserUtil; @Service public class SysDataruleServiceImpl extends BaseService implements SysDataruleService { @Autowired protected SysDataruleMapper sysDataruleMapper; @Autowired protected AuthorizingService authorizingService; @Autowired protected BaseDao baseDao; @Override public List<SysDatarule> list(Integer menuId) { try { SysDataruleExample example = new SysDataruleExample(); Criteria cr = example.createCriteria(); cr.andMenuIdEqualTo(menuId); return sysDataruleMapper.selectByExample(example); } catch (Exception e) { printException(e); } return null; } @Override public SysDatarule detial(Integer id) { try { SysDatarule datarule = sysDataruleMapper.selectByPrimaryKey(id); return datarule; } catch (Exception e) { printException(e); } return null; } @Override public void delete(String ids) { if(StringUtils.isBlank(ids)) { throw new ServiceException("id不能为空"); } String[] split = ids.split(","); try { SysDataruleExample example = new SysDataruleExample(); Criteria cr = example.createCriteria(); cr.andIdIn(Arrays.asList(split)); sysDataruleMapper.deleteByExample(example); } catch (Exception e) { throw printException(e); } } boolean validateRepeat(SysDatarule rule) { boolean repeat = false; SysDataruleExample example = new SysDataruleExample(); Criteria cr = example.createCriteria(); cr.andMenuIdEqualTo(rule.getMenuId()); cr.andRuleNameEqualTo(rule.getRuleName()); List<SysDatarule> list = sysDataruleMapper.selectByExample(example); if(list!=null&&list.size()>0) { for(SysDatarule bean:list) { if(!bean.getId().equals(rule.getId())) { repeat = true; } } } return repeat; } @Override public void update(SysDatarule rule) { if(validateRepeat(rule)) { throw new ServiceException("当前规则名称已存在"); } try { sysDataruleMapper.updateByPrimaryKeySelective(rule); } catch (Exception e) { throw printException(e); } } @Override public Integer save(SysDatarule rule) { if(validateRepeat(rule)) { throw new ServiceException("当前规则名称已存在"); } try { sysDataruleMapper.insertSelective(rule); return rule.getId(); } catch (Exception e) { throw printException(e); } } @Override public List<DataRuleTree> dataruleTree() { List<DataRuleTree> list = new ArrayList<>(); try { StringBuffer sqlbuf = new StringBuffer(); sqlbuf.append("select id,parent_id as pid,menu_name as name,sort "); //管理员查看所有 if(UserUtil.ifAdmin()) { sqlbuf.append(" from sys_menu where target = '0'"); }else { //查询当前用户能查看的菜单id Set<Integer> menuId = this.authorizingService.getMenuIdsByUserId(UserUtil.getCurrentUserId()); if(menuId==null || menuId.size()==0) { return list; } StringBuffer idsBuf = new StringBuffer(); for(Integer mid:menuId) { idsBuf.append("'").append(mid).append("',"); } String ids = ""; if(idsBuf.length()>0) { ids = idsBuf.substring(0, idsBuf.length()-1); } sqlbuf.append(" from sys_menu where id in (").append(ids).append(") and target = '0'"); } //只查询菜单权限 List<DataRuleTree> menuList = this.baseDao.queryList(sqlbuf.toString(), DataRuleTree.class); if(menuList==null || menuList.size()==0) { return list; } list.addAll(menuList); //查询当前菜单下的数据规则 StringBuffer idsBuf = new StringBuffer(); for(DataRuleTree menu:menuList) { idsBuf.append("'").append(menu.getId()).append("',"); } if(idsBuf.length()>0) { String ids = idsBuf.substring(0, idsBuf.length()-1); //查询数据规则 sqlbuf = new StringBuffer("select id,menu_id as pid,rule_name as name,'10000' as sort,'2' as type "); sqlbuf.append(" from sys_datarule where menu_id in (").append(ids).append(")"); List<DataRuleTree> datarule = this.baseDao.queryList(sqlbuf.toString(), DataRuleTree.class); list.addAll(datarule); } } catch (Exception e) { throw printException(e); } return list; } }
package com.shane.demo.activities.videos; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.shane.demo.R; import com.shane.demo.adapters.ViewPagerAdapter; import com.shane.demo.fragments.CommentFragment; import com.shane.demo.fragments.InfoFragment; import com.shane.demo.fragments.ListVideoFragment; import butterknife.Bind; import butterknife.ButterKnife; public class ShowVideoActivity extends AppCompatActivity { @Bind(R.id.toolbar) Toolbar toolbar; @Bind(R.id.tabs) TabLayout tabs; @Bind(R.id.pager) ViewPager pager; ViewPagerAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_video); ButterKnife.bind(this); setSupportActionBar(toolbar); adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(CommentFragment.newInstance(), "Comments"); adapter.addFragment(InfoFragment.newInstance(), "Info"); adapter.addFragment(ListVideoFragment.newInstance(), "Related"); pager.setAdapter(adapter); tabs.setupWithViewPager(pager); } }
package bean; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; /** * 基于注解的AOP日志示例 * @author ZYWANG 2011-3-24 */ @Component @Aspect public class AopLog { @Pointcut("execution (* bean.*.*(..))") public void point1(){} //方法执行前调用 @Before("execution (* bean.Hello.*(..))") public void before() { System.out.println("before"); } /*//方法执行后调用 @After("point1()") public void after() { System.out.println("after"); } //方法执行的前后调用 @Around("point1()") public Object around(ProceedingJoinPoint point) throws Throwable{ System.out.println("begin around"); Object object = point.proceed(); System.out.println("end around"); return object; } //方法运行出现异常时调用 @AfterThrowing(pointcut = "execution (* bean.*.*(..))",throwing = "ex") public void afterThrowing(Exception ex){ System.out.println("afterThrowing"); ex.printStackTrace(); }*/ }
package io.chark.food.domain.restaurant; import io.chark.food.domain.BaseRepository; import org.springframework.stereotype.Repository; @Repository public interface BankRepository extends BaseRepository<Bank> { }
package com.epam.training.sportsbetting.domain; public enum BetType { WINNER, GOALS, PLAYER_SCORE, NUMBER_OF_SETS; BetType() { // TODO Auto-generated constructor stub } }
package org.hpin.webservice.service; /** * 弘康业务接口 * Created by Damian on 16-12-28. */ public interface GeneServiceHK { /** * 客户身份验证 * @param xml * @return String * @auther Damian * @since 2016-12-28 */ String getCustomerAuth(String xml); /** * 保存客户信息 * @param xml * @return String * @auther Damian * @since 2016-12-28 */ String pushCustomerInfoHK(String xml); /** * 客户状态推送 * @param xml * @return String * @auther Damian * @since 2016-12-28 */ String pushCustomerStatus(String xml); /** * 华夏,易安,北京邮政项目:查询预导入表进行客户信息验证 * @param xml XML格式的字符串 * @return String * @auther Damian * @since 2017-01-17 */ String getCustAuth(String xml); }
/** * */ package com.ucas.algorithms.math; /** * @author wjg * */ public class Arithmetic { /** * 整数乘方运算,只允许正数次方 * @param a 底数 * @param b 指数 * @return 幂 */ public static int pow(int a, int b) { if (b < 0) { throw new IllegalArgumentException("The second argument of method pow must be positive."); } int result = 1; for (int i=0; i<b; i++) { result *= a; } return result; } }
package br.com.wda.OpenBeerProject.Entity; /** * * @author Darlan Silva */ public class Funcionario { }
package com.larryhsiao.nyx.core.tags; import com.silverhetch.clotho.Source; import java.sql.Connection; /** * Source to build a conneciton for tag database. */ public class TagDb implements Source<Connection> { private final Source<Connection> connSource; public TagDb(Source<Connection> connSource) { this.connSource = connSource; } @Override public Connection value() { try { Connection conn = connSource.value(); conn.createStatement().executeUpdate( // language=H2 "CREATE TABLE IF NOT EXISTS tags(" + "id integer not null auto_increment, " + "title text not null, " + "version integer not null default 1, " + "delete integer not null default 0" + ");" ); conn.createStatement().executeUpdate( // language=H2 "CREATE TABLE IF NOT EXISTS tag_jot(" + "jot_id integer not null, " + "tag_id integer not null, " + "version integer not null default 1, " + "delete integer not null default 0, " + "unique (jot_id, tag_id)" + ");" ); return conn; } catch (Exception e) { throw new IllegalArgumentException(e); } } }
package com.example.qiyue.mvp_dragger.core.http; import dagger.Component; /** * Created by Administrator on 2016/11/16 0016. */ public class HttpComponent { }
package cn.v5cn.v5cms.controller; import cn.v5cn.v5cms.service.AdvService; import cn.v5cn.v5cms.service.AdvPosService; import cn.v5cn.v5cms.entity.Adv; import cn.v5cn.v5cms.entity.AdvPos; import cn.v5cn.v5cms.entity.Site; import cn.v5cn.v5cms.entity.wrapper.AdvWrapper; import cn.v5cn.v5cms.exception.V5CMSNullValueException; import cn.v5cn.v5cms.util.HttpUtils; import cn.v5cn.v5cms.util.SystemConstant; import cn.v5cn.v5cms.util.SystemUtils; import com.baidu.ueditor.PathFormat; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.File; import java.io.IOException; import java.util.Map; import static cn.v5cn.v5cms.util.MessageSourceHelper.getMessage; /** * Created by ZYW on 2014/7/24. */ @Controller @RequestMapping("/manager/adv") public class AdvController { private final static Logger LOGGER = LoggerFactory.getLogger(AdvController.class); @Autowired private AdvPosService advPosService; @Autowired private AdvService advService; @RequestMapping(value = "/list/{p}",method = {RequestMethod.GET,RequestMethod.POST}) public String advList(Adv adv,@PathVariable Integer p,HttpSession session,HttpServletRequest request,ModelMap modelMap){ if(StringUtils.isNotBlank(adv.getAdvName()) || (adv.getAdvPos() != null && adv.getAdvPos().getAdvPosId() != null)){ session.setAttribute("advSearch",adv); modelMap.addAttribute("searchAdv",adv); }else{ session.setAttribute("advSearch",null); } Object searchObj = session.getAttribute("advSearch"); Page<Adv> result = advService.findAdvByAdvNamePageable((searchObj == null ? (new Adv()):((Adv)searchObj)),p); modelMap.addAttribute("advs",result); modelMap.addAttribute("pagination",SystemUtils.pagination(result,HttpUtils.getContextPath(request)+"/manager/adv/list")); ImmutableList<AdvPos> advposes = advPosService.finadAll(); modelMap.addAttribute("aps",advposes); return "setting/adv_list"; } @RequestMapping(value = "/edit",method = RequestMethod.GET) public String advPosaup(ModelMap model){ ImmutableList<AdvPos> advposes = advPosService.finadAll(); model.addAttribute("aps",advposes); model.addAttribute(new Adv()); model.addAttribute("advTypes", Maps.newHashMap()); return "setting/adv_edit"; } @RequestMapping(value = "/edit/{advId}",method = RequestMethod.GET) public String advEdit(@PathVariable Long advId,ModelMap model){ ImmutableList<AdvPos> advposes = advPosService.finadAll(); model.addAttribute("aps",advposes); Adv adv = advService.findOne(advId); if(adv == null){ LOGGER.error("通过ID为{}没有查到广告信息。",advId); throw new V5CMSNullValueException("通过ID为"+advId+"没有查到广告信息。"); } ObjectMapper jsonObj = new ObjectMapper(); Map<String,String> advTypeMap = null; try { advTypeMap = jsonObj.readValue(adv.getAdvTypeInfo(),Map.class); } catch (IOException e) { e.printStackTrace(); LOGGER.error("JSON转换Map对象异常,异常消息{}",e.getMessage()); } model.addAttribute(adv); model.addAttribute("advTypes",advTypeMap); model.addAttribute("page_title",getMessage("adv.updatepage.title")); return "setting/adv_edit"; } @ResponseBody @RequestMapping(value = "/edit",method = RequestMethod.POST) public ImmutableMap<String,Object> advEdit(@ModelAttribute("adv") AdvWrapper advWrapper,HttpServletRequest request){ // List<String> deleteFilePaths = (List<String>)request.getSession().getAttribute("adv_delete_file_real_path"); // if(deleteFilePaths != null && deleteFilePaths.size() > 0){ // for(String deleteFilePath : deleteFilePaths){ // String fileExt = FilenameUtils.getExtension(deleteFilePath); // boolean result = FileUtils.deleteQuietly(new File(deleteFilePath)); // if(!result){ // //String failedMessage = "swf".equalsIgnoreCase(fileExt)?getMessage("adv.flashdeletefailed.message"):getMessage("adv.imagedeletefailed.message"); // LOGGER.warn("广告图片或者Flash删除失败,名称{}",deleteFilePath); // //return ImmutableMap.<String,Object>of("status","0","message",failedMessage); // } // } // request.getSession().setAttribute("adv_delete_file_real_path",null); // } if(advWrapper.getAdv().getAdvId() != null){ try { advService.update(advWrapper); return ImmutableMap.<String,Object>of("status","1","message",getMessage("adv.updatesuccess.message")); } catch (JsonProcessingException e) { e.printStackTrace(); LOGGER.error("修改广告失败,{}",e.getMessage()); } catch (IllegalAccessException e) { e.printStackTrace(); LOGGER.error("修改广告失败,{}",e.getMessage()); } catch (Exception e) { e.printStackTrace(); LOGGER.error("修改广告失败,{}",e.getMessage()); } return ImmutableMap.<String,Object>of("status","0","message",getMessage("adv.updatefailed.message")); } LOGGER.info("添加广告信息,{}",advWrapper); try { Adv adv= advService.save(advWrapper); } catch (JsonProcessingException e) { e.printStackTrace(); LOGGER.error("添加广告时转换JSON出错!{}",e.getMessage()); ImmutableMap.<String,Object>of("status","0","message",getMessage("adv.addfailed.message")); } return ImmutableMap.<String,Object>of("status","1","message",getMessage("adv.addsuccess.message")); } @ResponseBody @RequestMapping(value = "/upload",method = RequestMethod.POST) public ImmutableMap<String,Object> advUploader(MultipartFile file,HttpServletRequest request){ if(file.isEmpty()){ return ImmutableMap.<String,Object>of("status","0","message",getMessage("global.uploadempty.message")); } Site site = (Site)(SystemUtils.getSessionSite()); String advPath = PathFormat.parseSiteId(SystemConstant.ADV_RES_PATH, site.getSiteId() + ""); String realPath = HttpUtils.getRealPath(request, advPath); SystemUtils.isNotExistCreate(realPath); String timeFileName = SystemUtils.timeFileName(file.getOriginalFilename()); try { file.transferTo(new File(realPath+"/"+timeFileName)); } catch (IOException e) { e.printStackTrace(); return ImmutableMap.<String,Object>of("status","0","message",getMessage("adv.uploaderror.message")); } return ImmutableMap.<String,Object>of("status","1","message",getMessage("adv.uploadsuccess.message"), "filePath",advPath+timeFileName,"contentPath", HttpUtils.getBasePath(request)); } @ResponseBody @RequestMapping(value = "/delete/if",method = RequestMethod.POST) public ImmutableMap<String,String> deleteAdvImage(String if_path,HttpServletRequest request){ // Object siteObj = request.getSession().getAttribute(SystemConstant.SITE_SESSION_KEY); // if(siteObj == null){ // LOGGER.error("Session中存储的站点信息为空!"); // throw new V5CMSSessionValueNullException("Session中存储的站点信息为空!"); // } // Site site = (Site)siteObj; String fileExt = FilenameUtils.getExtension(if_path); // String fileName = FilenameUtils.getName(if_path); String realPath = HttpUtils.getRealPath(request, if_path); boolean deleteResult = FileUtils.deleteQuietly(new File(realPath)); // List<String> deletePaths = (List<String>)request.getSession().getAttribute("adv_delete_file_real_path"); // if(deletePaths == null){ // deletePaths = Lists.newArrayList(); // } // deletePaths.add(realPath+"/"+fileName); // // request.getSession().setAttribute("adv_delete_file_real_path",deletePaths); String failedMessage = ""; if(deleteResult){ failedMessage = "swf".equalsIgnoreCase(fileExt)?(getMessage("adv.flashdeletesuccess.message")):(getMessage("adv.imagedeletesuccess.message")); }else{ failedMessage = "swf".equalsIgnoreCase(fileExt)?(getMessage("adv.flashdeletefailed.message")):(getMessage("adv.imagedeletefailed.message")); } return ImmutableMap.of("status","1","message",failedMessage); } @ResponseBody @RequestMapping(value = "/delete",method = RequestMethod.POST) public ImmutableMap<String,Object> deleteAdvs(Long[] advIds,HttpServletRequest request){ LOGGER.info("删除广告信息,ID为{}",advIds); try { advService.deleteAdvs(advIds,request); } catch (Exception e) { e.printStackTrace(); LOGGER.error("删除广告信息失败,ID为{}",advIds); return ImmutableMap.<String,Object>of("status","0","message",getMessage("adv.deletefailed.message")); } return ImmutableMap.<String,Object>of("status","1","message",getMessage("adv.deletesuccess.message")); } }