text
stringlengths
10
2.72M
package view; import java.io.IOException; public class WelcomPage extends AbstractPage{ public void showPage() throws IOException { System.out.println("Enter user name"); while(true){ String str = readerInput(); if(str.length() > 4 && str.length()<20){ return; }else{ System.out.println("incorrect name"); } } } }
package com.eric.test; import com.eric.constrant.AuthorityConstrant; import com.eric.tools.csv.CSVUtils; import org.junit.Test; import java.awt.*; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; /* *@description:普通测试类,不涉及数据库连接,mapper文件 *@author:cuigs *@Email:cuigs@ti-net.com.cn *@Version:1.0 *@Date:2019/4/6 */ public class CommonTest { @Test public void test1() { String s = "D:\\cgs\\File\\data\\goodAPKSDeCompileResult\\com.book.search.goodsearchbook\\smali\\com\\qihoo\\util\\Configuration.smali"; int len = s.length(); String res = s.substring(len - 6, len); System.out.println(res); } /** * 遍历一个文件夹下的所有文件,列出文件名 */ @Test public void test2() { File file = new File("D:\\cgs\\File\\data\\0test0412\\BadApkResult"); String[] list = file.list(); for (String s : list) { System.out.println(s); } } /** * 打开文件夹测试 */ @Test public void testOpenDir() { try { Desktop.getDesktop().open(new File("G:\\7BiShe\\DeCompileResults\\badApksDecompileResult")); } catch (IOException e) { e.printStackTrace(); } } @Test public void testContains() { List<String> list = new ArrayList<String>(); list.add("草莓"); //向列表中添加数据 list.add("香蕉"); //向列表中添加数据 list.add("菠萝"); //向列表中添加数据 for (int i = 0; i < list.size(); i++) { //通过循环输出列表中的内容 System.out.println(i + ":" + list.get(i)); } String o = "香蕉"; System.out.println("list对象中是否包含元素" + o + ":" + list.contains(o)); } /** * 测试项目中的文件路径该怎么填才能正确定位文件 */ @Test public void testFilePath(){ File file = new File("/src/main/java/com/eric/python/ExtractAuthority2Txt.py"); if(file.exists()){ System.out.println("文件存在"); }else{ System.out.println("文件不存在!"); } } /** * 测试查找类路径下的文件 */ @Test public void testFindFile() { String s = CommonTest.class.getResource("/python/ExtractAuthority2Txt.py").toExternalForm(); if(null!=s){ File file = new File(s); // System.out.println(file.getPath()); String[] split = file.getPath().split("\\\\"); for (int i = 1; i < split.length-1; i++) { System.out.print(split[i]+File.separator); } System.out.println(split[split.length-1]); } } @Test public void testGetPath(){ System.out.println(System.getProperty("user.dir")); // System.out.println(Thread.currentThread().getContextClassLoader().getResource("")); } /** * 测试执行项目中的python文件 */ @Test public void testExecPythonInCurrentDir() throws IOException { //基础路径 E:\projects\AndroidDetection String basePath = System.getProperty("user.dir"); //要执行的python文件的名称 String pyName="LogicCallByJava.py"; //最终文件的绝对路径 String finalPyPath=basePath+File.separator+"src"+File.separator+"main"+File.separator+"python"+File.separator+pyName; String csvFilePath="G:\\7BiShe\\dataset\\method1\\androidDetection_part_2500good_2500bad.csv"; String[] logicCallByJavaPyArgs = new String[]{"python ", finalPyPath, csvFilePath}; Process proc = Runtime.getRuntime().exec(logicCallByJavaPyArgs);// 执行py文件 BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(), "GBK")); String temp=""; while ((temp = in.readLine()) != null) { System.out.println(temp); } } @Test public void testGetFileName(){ File dirFile = new File("G:\\7BiShe\\badAPKs\\1801-2100\\1801-2100HasDone"); if(dirFile.isDirectory()){ File[] files = dirFile.listFiles(); for (File file : files) { String fileName = file.getName(); String substring = fileName.substring(0, fileName.length() - 4); System.out.println(substring); } } } /** * 测试批量检测 * */ @Test public void testBatchPredict() throws IOException, InterruptedException { //所有的权限 List<String> allAuthorityList = Arrays.asList(AuthorityConstrant.AUTHORITY_ARRAY); //1.生成表头 //构造符合工具类要求的表头List List<String> head = new ArrayList<>(); System.out.println("开始构造csv表头数据..."); head.add("package_name"); for (String au : allAuthorityList) { head.add(au); } head.add("apk_attribute"); System.out.println("csv表头数据构造完毕..."); //2.生成每一行数据,构造每一行的数据 List<String> dataList = new ArrayList<>(); System.out.println("开始构造每一行数据..."); //添加包名,包名没用,默认unknown dataList.add("unknown"); //当前应用的权限 List<String> currentApkAuthorityList = new ArrayList<>(); String extractAuthority2TxtPyPath ="E:\\projects\\AndroidDetection\\src\\main\\python\\ExtractAuthority2Txt.py"; File dirFile = new File("G:\\7BiShe\\badAPKs\\1801-2100\\1801-2100HasDone"); if(dirFile.isDirectory()){ File[] files = dirFile.listFiles(); System.out.println("开始遍历每一个apk文件..."); for (File file : files) { String detectApkPath = file.getAbsolutePath(); String fileNameWithSuffix = file.getName(); String fileName = fileNameWithSuffix.substring(0, fileNameWithSuffix.length() - 4); String authorityResSavePath ="E:\\BiSheData\\temp\\testPredict\\"+fileName+".txt"; String[] extractAuthority2TxtPyArgs = new String[]{"python ", extractAuthority2TxtPyPath, detectApkPath, authorityResSavePath}; System.out.println("开始调用提取权限的python程序..."); Process proc = Runtime.getRuntime().exec(extractAuthority2TxtPyArgs);// 执行py文件 //执行完毕开始读取提取出的权限TXT File authorityResFile = new File(authorityResSavePath); int wait = proc.waitFor(); if (wait == 0 && authorityResFile.exists()) { System.out.println("提取权限的python程序执行成功!"); FileReader reader = new FileReader(authorityResSavePath); BufferedReader br = new BufferedReader(reader); for (String au : allAuthorityList) { if (currentApkAuthorityList.contains(au)) { dataList.add(1 + ""); } else { dataList.add(0 + ""); } } //最后一个应用属性未知,默认值为2 dataList.add(2 + ""); System.out.println("每一行csv数据构造完毕!"); }else{ System.out.println("调用python程序失败..."); } } CSVUtils.createCSVFile(head, dataList, "E:\\BiSheData\\temp\\testPredict", "srcApkFeature"); String logicPredictModelPklPath ="E:\\projects\\AndroidDetection\\predictModel\\predict_model.pkl"; String logicPredictModelCSVPath ="E:\\BiSheData\\temp\\testPredict\\srcApkFeature.csv"; String logicPredictModelPyPath ="E:\\projects\\AndroidDetection\\src\\main\\python\\LogicPredictModel.py"; //先判断调用python程序必须的两个文件是否存在 File logicPredictModelPyFile = new File(logicPredictModelPyPath); File logicPredictModelCSVFile = new File(logicPredictModelCSVPath); //两个文件都存在 if (logicPredictModelPyFile.exists() && logicPredictModelCSVFile.exists()) { System.out.println("调用预测模型的所需要的两个文件都存在!"); //调用python程序 String[] apkDetectArgs = new String[]{"python ", logicPredictModelPyPath, logicPredictModelCSVPath, logicPredictModelPklPath}; System.out.println("开始调用预测模型..."); Process apkDetectProc = Runtime.getRuntime().exec(apkDetectArgs);// 执行py文件 BufferedReader apkDetectIn = new BufferedReader(new InputStreamReader(apkDetectProc.getInputStream(), "GBK")); String apkDetecTemp = ""; while ((apkDetecTemp = apkDetectIn.readLine()) != null) { System.out.println("预测结果为:"+apkDetecTemp); } } } } /** * 测试直接根据csv文件进行测试 */ @Test public void testSinglePredict() throws IOException { String logicPredictModelPklPath ="E:\\projects\\AndroidDetection\\predictModel\\predict_model.pkl"; String logicPredictModelCSVPath ="E:\\BiSheData\\temp\\androidDetection_part_1good_100bad.csv"; String logicPredictModelPyPath ="E:\\projects\\AndroidDetection\\src\\main\\python\\LogicPredictModel.py"; //先判断调用python程序必须的两个文件是否存在 File logicPredictModelPyFile = new File(logicPredictModelPyPath); File logicPredictModelCSVFile = new File(logicPredictModelCSVPath); //两个文件都存在 if (logicPredictModelPyFile.exists() && logicPredictModelCSVFile.exists()) { System.out.println("调用预测模型的所需要的两个文件都存在!"); //调用python程序 String[] apkDetectArgs = new String[]{"python ", logicPredictModelPyPath, logicPredictModelCSVPath, logicPredictModelPklPath}; System.out.println("开始调用预测模型..."); Process apkDetectProc = Runtime.getRuntime().exec(apkDetectArgs);// 执行py文件 BufferedReader apkDetectIn = new BufferedReader(new InputStreamReader(apkDetectProc.getInputStream(), "GBK")); String apkDetecTemp = ""; while ((apkDetecTemp = apkDetectIn.readLine()) != null) { System.out.println(apkDetecTemp); } } } @Test public void testContain(){ String path="G:\\7BiShe\\badAPKs\\1201-1500\\1201-1500HasDone"; String[] split = path.split("\\\\"); List<String> list = Arrays.asList(split); if(list.contains("badAPKs")){ System.out.println("恶意应用"); }else{ System.out.println("正常应用"); } } @Test public void testReadTxt() throws InterruptedException { List<String> list = Arrays.asList(AuthorityConstrant.INFO); Random random = new Random(); for (String s : list) { System.out.println(s); int time = random.nextInt(5000)+1000; Thread.sleep(time); } } }
package elements; import org.junit.Test; import static org.junit.Assert.assertEquals; public class HtmlSelectTest { @Test public void test_createHtmlSelect() { HtmlElement htmlSelect = HtmlFactory.createSelect(); assertEquals("<select></select>", htmlSelect.print()); } @Test public void test_createHtmlSelectWithName() { HtmlElement htmlSelect = HtmlFactory.createSelect(); htmlSelect.setName("theName"); assertEquals("<select name=\"theName\"></select>", htmlSelect.print()); } @Test public void test_createHtmlSelectWithId() { HtmlElement htmlSelect = HtmlFactory.createSelect(); htmlSelect.setId("theId"); assertEquals("<select id=\"theId\"></select>", htmlSelect.print()); } @Test public void test_createHtmlSelectWithNameNull() { HtmlElement htmlSelect = HtmlFactory.createSelect(); htmlSelect.setName(null); assertEquals("<select></select>", htmlSelect.print()); } @Test public void test_createHtmlSelectWithOption() { HtmlElement htmlSelect = HtmlFactory.createSelect(); HtmlOption option = HtmlFactory.createOption(); htmlSelect.addOption(option); assertEquals("<select><option></option></select>", htmlSelect.print()); } @Test public void test_createHtmlSelectWithOption_Value() { HtmlElement htmlSelect = HtmlFactory.createSelect(); HtmlOption option = HtmlFactory.createOption(); option.setValue("theValue"); htmlSelect.addOption(option); assertEquals("<select><option value=\"theValue\"></option></select>", htmlSelect.print()); } @Test public void test_createHtmlSelectAddOptionThenOptionValue() { HtmlElement htmlSelect = HtmlFactory.createSelect(); HtmlOption option = HtmlFactory.createOption(); htmlSelect.addOption(option); option.setValue("theValue"); assertEquals("<select><option value=\"theValue\"></option></select>", htmlSelect.print()); } @Test public void test_createHtmlSelectAddTwoOptionsWithValue() { HtmlElement htmlSelect = HtmlFactory.createSelect(); HtmlOption option1 = HtmlFactory.createOption(); htmlSelect.addOption(option1); option1.setValue("theValue"); HtmlOption option2 = HtmlFactory.createOption(); htmlSelect.addOption(option2); option2.setValue("theValueOption2"); assertEquals("<select><option value=\"theValue\"></option><option value=\"theValueOption2\"></option></select>", htmlSelect.print()); } @Test public void test_createHtmlSelectAddOptionAndContent() { HtmlElement htmlSelect = HtmlFactory.createSelect(); HtmlOption option = HtmlFactory.createOption(); htmlSelect.addOption(option); option.setValue("theValue"); option.setContent("THE_TEXT"); assertEquals("<select><option value=\"theValue\">THE_TEXT</option></select>", htmlSelect.print()); } @Test public void test_createHtmlSelectAddOptionWithSelectedOption2() { HtmlElement htmlSelect = HtmlFactory.createSelect(); HtmlOption option1 = HtmlFactory.createOption(); htmlSelect.addOption(option1); option1.setValue("theValue"); option1.setContent("OPTION1"); HtmlOption option2 = HtmlFactory.createOption(); htmlSelect.addOption(option2); option2.setContent("OPTION2"); option2.setValue("theValueOption2"); option2.selected(true); assertEquals("<select><option value=\"theValue\">OPTION1</option><option value=\"theValueOption2\" selected>OPTION2</option></select>", htmlSelect.print()); } @Test public void test_createHtmlSelectAddOptionWithSelectedOption1() { HtmlElement htmlSelect = HtmlFactory.createSelect(); HtmlOption option1 = HtmlFactory.createOption(); htmlSelect.addOption(option1); option1.setValue("theValue"); option1.setContent("OPTION1"); option1.selected(true); HtmlOption option2 = HtmlFactory.createOption(); htmlSelect.addOption(option2); option2.setContent("OPTION2"); option2.setValue("theValueOption2"); assertEquals("<select><option value=\"theValue\" selected>OPTION1</option><option value=\"theValueOption2\">OPTION2</option></select>", htmlSelect.print()); } @Test public void test_createHtmlSelectAddOptionWithUnSelectOption2() { HtmlElement htmlSelect = HtmlFactory.createSelect(); HtmlOption option1 = HtmlFactory.createOption(); htmlSelect.addOption(option1); option1.setValue("theValue"); option1.setContent("OPTION1"); HtmlOption option2 = HtmlFactory.createOption(); htmlSelect.addOption(option2); option2.setContent("OPTION2"); option2.setValue("theValueOption2"); option2.selected(true); assertEquals("<select><option value=\"theValue\">OPTION1</option><option value=\"theValueOption2\" selected>OPTION2</option></select>", htmlSelect.print()); option2.selected(false); assertEquals("<select><option value=\"theValue\">OPTION1</option><option value=\"theValueOption2\">OPTION2</option></select>", htmlSelect.print()); } @Test public void test_createHtmlSelectAddTwoOptionsWithValueAndContent() { HtmlElement htmlSelect = HtmlFactory.createSelect(); HtmlOption option1 = HtmlFactory.createOption(); htmlSelect.addOption(option1); option1.setValue("theValue"); option1.setContent("OPTION1"); HtmlOption option2 = HtmlFactory.createOption(); htmlSelect.addOption(option2); option2.setContent("OPTION2"); option2.setValue("theValueOption2"); assertEquals("<select><option value=\"theValue\">OPTION1</option><option value=\"theValueOption2\">OPTION2</option></select>", htmlSelect.print()); } }
package com.suntiago.network.network.download; /** * */ public class Constants { public static final String KEY_DOWNLOAD_ENTRY = "key_download_entry"; public static final String KEY_DOWNLOAD_ACTION = "key_download_action"; public static final int KEY_DOWNLOAD_ACTION_ADD = 0; public static final int KEY_DOWNLOAD_ACTION_PAUSE = 1; public static final int KEY_DOWNLOAD_ACTION_RESUME = 2; public static final int KEY_DOWNLOAD_ACTION_CANCEL = 3; public static final int KEY_DOWNLOAD_ACTION_PAUSE_ALL = 4; public static final int KEY_DOWNLOAD_ACTION_RECOVER_ALL = 5; public static final int CONNECT_TIME = 30 * 1000; public static final int READ_TIME = 30 * 1000; public static final String DEVICE_CONFIGURE = "device_configure"; public static final String IS_PERMISSION_OPEN = "is_permission_open"; public final static int IS_UPDATE_CANCELED = 1; public final static String IS_SERVICE_STARTED = "is_service_started"; }
package com.nikvay.saipooja_patient.apiCallCommen; public class EndApi { public static final String LOGIN = "ws-patientLogin"; public static final String CHANGEPASSWORD = "ws-userChangePasswordPatient"; public static final String PATIENT_REGISTRATION = "ws-patientragistration"; public static final String SERVICE_LIST = "ws-service"; public static final String APPOINTMENT_TIME_SLOT = "ws-appointmentPatient"; public static final String SERVICElIST = "ws-servicepatientlist"; public static final String DOCTORlIST = "ws-listDoctor"; public static final String DOCTORWISESERVICElIST = "ws-doctorwiseService"; public static final String PATIENTWISEAPPOINMENT = "ws-addAppointmentPatient"; public static final String CLASSlIST = "ws-classesListPatient"; public static final String LIST_APPOINTMENT = "ws-listPatientAptDetails"; public static final String LIST_PAYMENT = "ws-listpPaymentHistoryPatient"; public static final String LIST_DATE_PRESCRIPTION = "ws-listPrescriptiondate"; public static final String LIST_PRESCRIPTION = "ws-listPrescriptionPatient"; public static final String LIST_DATE_APPOINMENT = "ws-listPatientAptDate"; public static final String VIDEO_TUTORIALS = "ws-video-list"; public static final String PHOTO_Gallery_LIST = "ws-gallery-list"; public static final String ADD_NEW_ENQUIRY = "ws-add-enquiry"; public static final String ENQUIRY_LIST = "ws-enquiry-list-for-patient"; public static final String DOCUMENT_PHOTO = "ws-list-prescription-document-for-patient"; }
package org.alienideology.jcord.handle.emoji; /** * EmojiCategory - Categories of emojis in the Discord client UI. * * @author AlienIdeology */ public enum EmojiCategory { PEOPLE("people"), NATURE("nature"), FOOD("food"), ACTIVITIES("activity"), TRAVEL("travel"), OBJECTS("objects"), SYMBOLS("symbols"), FLAGS("flags"), UNKNOWN(""); public final String name; EmojiCategory(String name) { this.name = name; } public static EmojiCategory getByName(String name) { for (EmojiCategory category : EmojiCategory.values()) { if (category.name.equals(name)) return category; } return UNKNOWN; } }
package com.tencent.mm.app; import android.content.ComponentName; import android.content.Intent; import com.tencent.mm.g.a.ja; import com.tencent.mm.model.at; import com.tencent.mm.model.au; import com.tencent.mm.sdk.b.b; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.ui.e.i; class WorkerProfile$23 extends c<ja> { final /* synthetic */ WorkerProfile bzO; WorkerProfile$23(WorkerProfile workerProfile) { this.bzO = workerProfile; this.sFo = ja.class.getName().hashCode(); } public final /* synthetic */ boolean a(b bVar) { ja jaVar = (ja) bVar; if (jaVar.bSG.aAk != 2 && jaVar.bSG.status == 0) { Intent intent = new Intent(); intent.setComponent(new ComponentName(i.thA, "com.tencent.mm.booter.MMReceivers$ToolsProcessReceiver")); intent.putExtra("tools_process_action_code_key", "com.tencent.mm.intent.ACTION_TOOLS_REMOVE_COOKIE"); ad.getContext().sendBroadcast(intent); } if (au.HX()) { if (jaVar.bSG.aAk == 3) { at.dBv.T("login_user_name", ""); } else { at atVar = at.dBv; au.HU(); String str = (String) com.tencent.mm.model.c.DT().get(6, null); au.HU(); int intValue = ((Integer) com.tencent.mm.model.c.DT().get(9, null)).intValue(); au.HU(); atVar.c(str, intValue, (String) com.tencent.mm.model.c.DT().get(5, null)); } } return false; } }
package switch2019.project.infrastructure.dataBaseRepositories; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import switch2019.project.domain.domainEntities.person.Address; import switch2019.project.domain.domainEntities.person.Email; import switch2019.project.domain.domainEntities.person.Person; import switch2019.project.domain.domainEntities.shared.DateAndTime; import switch2019.project.domain.domainEntities.shared.PersonID; import switch2019.project.domain.repositories.PersonRepository; import switch2019.project.utils.customExceptions.ArgumentNotFoundException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest @Transactional class PersonDbRepositoryTest { @Autowired private PersonRepository repository; private Person person; private Person person2; private Person personNotPersisted; private Person father; private Person mother; @BeforeEach public void setup() { person = repository.createPerson ("Marta", new DateAndTime(1995, 11, 12), new Address("Porto"), new Address("Miguel Bombarda", "Porto", "4620-223"), new PersonID(new Email("maria@gmail.com")), new PersonID(new Email("roberto@gmail.com")), new Email("marta@gmail.com")); person2 = repository.createPerson ("Ricardo", new DateAndTime(1999, 11, 12), new Address("Porto"), new Address("Miguel Bombarda", "Porto", "4620-223"), new PersonID(new Email("maria@gmail.com")), new PersonID(new Email("roberto@gmail.com")), new Email("ricardo@gmail.com")); repository.addSibling(person, "ricardo@gmail.com"); personNotPersisted = new Person("António", new DateAndTime(1990, 01, 23), new Address("Guimarães"), new Address("Avenida de França", "Porto", "4620-262"), new Email("antonio@gmail.com")); father = new Person("Roberto Azevedo", new DateAndTime(1967, 1, 9), new Address("Lisboa"), new Address("Avenida Antonio Domingues dos Santos", "Senhora da Hora", "4460-237"), new Email("roberto@gmail.com")); mother = new Person("Margarida Azevedo", new DateAndTime(1964, 12, 1), new Address("Guimarães"), new Address("Avenida Antonio Domingues dos Santos", "Senhora da Hora", "4460-237"), new Email("maria@gmail.com")); }; @Test @DisplayName("Test if a person is saved in Jpa Repository") void createPerson() throws Exception { //Arrange Long expectedSize = repository.repositorySize() + 1; //Act repository.createPerson ("João", new DateAndTime(1993, 10, 12), new Address("Porto"), new Address("Avenida Brasil", "Porto", "4620-262"), new Email("joao@gmail.com")); ///Assert Assertions.assertAll( () -> Assert.notNull(repository.findPersonByEmail(new Email("joao@gmail.com")), "Persons saved is found"), () -> assertEquals(expectedSize, repository.repositorySize()) ); } @Test @DisplayName("Test if a person is saved in Jpa Repository - Person Already Exists - size") void createPersonAlreadyExists() throws Exception { //Arrange Long expectedSize = repository.repositorySize(); //Act repository.createPerson ("Marta", new DateAndTime(1995, 11, 12), new Address("Porto"), new Address("Miguel Bombarda", "Porto", "4620-223"), new Email("marta@gmail.com")); ///Assert Assertions.assertAll( () -> assertEquals(expectedSize, repository.repositorySize()) ); } @Test @DisplayName("Test if a person with mother and father is saved in Jpa Repository") void testCreatePerson() throws Exception { //Arrange Long expectedSize = repository.repositorySize() + 1; //Act repository.createPerson ("Manuela", new DateAndTime(2000, 12, 13), new Address("Porto"), new Address("Avenida Brasil", "Porto", "4620-262"), father.getID(), mother.getID(), new Email("manuela@gmail.com")); //Assert Assertions.assertAll( () -> Assert.notNull(repository.findPersonByEmail(new Email("manuela@gmail.com")), "Persons saved is found"), () -> assertEquals(expectedSize, repository.repositorySize()) ); } @Test @DisplayName("Test if a person is returned form JPA - TRUE") void getByID() throws Exception { //Arrange Person expected = person; //Act Person result = repository.getByID(new PersonID( new Email("marta@gmail.com"))); //Assert assertEquals(expected, person); } @Test @DisplayName("Test if a person is returned form JPA - Exception") void getByIDException() throws Exception { //Act Throwable thrown = catchThrowable(() -> { repository.getByID(new PersonID( new Email("exception@gmail.com")));}); //Assert assertThat(thrown) .isExactlyInstanceOf(ArgumentNotFoundException.class) .hasMessage("No person found with that email."); } @Test @DisplayName("Find person by Email - true") void findByEmail() { //Arrange Person expected = person; //Act Person result = repository.findPersonByEmail(new Email("marta@gmail.com")); //Arrange assertEquals(expected, result); } @Test @DisplayName("Find person by Email - Exception") void findByEmailException() { //Act Throwable thrown = catchThrowable(() -> { repository.findPersonByEmail(new Email("exception@gmail.com"));}); //Assert assertThat(thrown) .isExactlyInstanceOf(ArgumentNotFoundException.class) .hasMessage("No person found with that email."); } @Test @DisplayName("Test if PersonEmail is on JPA repository") void isPersonEmailOnRepositoryTrue() throws Exception { assertTrue(repository.isPersonEmailOnRepository(new Email(person.getID().toString()))); } @Test @DisplayName("Test if PersonEmail is not in the JPA repository") void isPersonEmailOnRepositoryFalse() throws Exception { assertFalse(repository.isPersonEmailOnRepository(new Email(personNotPersisted.getID().toString()))); } @Test @DisplayName("Test if ID is on JPA repository") void isIDOnRepositoryTrue() throws Exception { assertTrue(repository.isIDOnRepository(person.getID())); } @Test @DisplayName("Test if ID is on JPA repository") void isIDOnRepositoryFalse() throws Exception { assertFalse(repository.isIDOnRepository(personNotPersisted.getID())); } /** * Test method addSibling */ @Test @DisplayName("Test if a person is added as sibling - siblingID already in list") void addSiblingAlreadyInList() { //Arrange String siblingID = "ricardo@gmail.com"; //Act boolean addedSibling = repository.addSibling(person, siblingID); ///Assert assertFalse(addedSibling); } }
package nl.themelvin.questlib.reward; import org.bukkit.entity.Player; public abstract class Reward { /** * Reward a player (called when quest or objective finished). * @param player The player to reward. */ public abstract void reward(Player player); }
package com.tencent.mm.plugin.wenote.model.a; public final class k extends u { public Boolean qoV = Boolean.valueOf(false); public Boolean qoW = Boolean.valueOf(false); public final int getType() { return 4; } public final String bZh() { return this.qoT; } }
package com.tencent.mm.plugin.wenote.ui.nativenote.b; import android.graphics.Bitmap; import android.graphics.Color; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import com.tencent.mm.R; import com.tencent.mm.plugin.wenote.b.c; import com.tencent.mm.plugin.wenote.model.a.b; import com.tencent.mm.plugin.wenote.model.nativenote.manager.k; import com.tencent.mm.sdk.platformtools.bi; public final class e extends h { private int dwJ = 0; private ImageView qvj; public e(View view, k kVar) { super(view, kVar); this.bOA.setVisibility(0); this.eRj.setVisibility(8); this.qvq.setVisibility(8); this.bOA.setTag(this); this.bOA.setOnClickListener(this.jXR); this.qvj = (ImageView) view.findViewById(R.h.image_mask); this.qvj.setVisibility(8); this.dwJ = k.mScreenWidth - ((int) k.aq(20.0f)); } public final void a(b bVar, int i, int i2) { String str; String str2 = ((com.tencent.mm.plugin.wenote.model.a.e) bVar).bVd; String str3 = ((com.tencent.mm.plugin.wenote.model.a.e) bVar).qpe; if (com.tencent.mm.a.e.cn(str2)) { str = str2; } else if (com.tencent.mm.a.e.cn(str3)) { str = str3; } else { Object str4 = null; } if (this.qtF.qrC != 3) { str3 = str4; } else if (!com.tencent.mm.a.e.cn(str3)) { str3 = str4; } Bitmap Sq = bi.oW(str3) ? null : c.Sq(str3); this.bOA.setImageBitmap(null); LayoutParams layoutParams = this.bOA.getLayoutParams(); layoutParams.width = -1; layoutParams.height = -1; this.bOA.setLayoutParams(layoutParams); if (Sq != null) { this.bOA.setImageBitmap(Sq); } else { this.bOA.setImageBitmap(null); LayoutParams layoutParams2 = this.bOA.getLayoutParams(); layoutParams2.width = this.dwJ; layoutParams2.height = this.dwJ; this.bOA.setLayoutParams(layoutParams2); this.bOA.setBackgroundColor(Color.parseColor("#f6f6f6")); } if (bVar.qoO) { this.qvj.setVisibility(0); } else { this.qvj.setVisibility(8); } super.a(bVar, i, i2); } public final int caZ() { return 2; } }
package kodlamaio.hrms.business.concretes; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import kodlamaio.hrms.business.abstracts.JobTimeService; import kodlamaio.hrms.core.utilities.result.DataResult; import kodlamaio.hrms.core.utilities.result.Result; import kodlamaio.hrms.core.utilities.result.SuccessDataResult; import kodlamaio.hrms.core.utilities.result.SuccessResult; import kodlamaio.hrms.dataAccess.abstacts.JobTimeDao; import kodlamaio.hrms.entities.concretes.JobTime; @Service public class JobTimeManager implements JobTimeService{ private JobTimeDao jobTimeDao; @Autowired public JobTimeManager(JobTimeDao jobTimeDao) { super(); this.jobTimeDao = jobTimeDao; } @Override public Result add(JobTime jobTime) { this.jobTimeDao.save(jobTime); return new SuccessResult(); } @Override public DataResult<List<JobTime>> getAll() { return new SuccessDataResult<List<JobTime>>(this.jobTimeDao.findAll()); } }
package com.lagou; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; public class DubboPureMain { public static void main(String[] args) throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ProviderConfiguration.class); context.start(); System.in.read(); } @Configuration @EnableDubbo(scanBasePackages = "com.lagou.service.impl") @PropertySource("classpath:/dubbo-provider.properties") static class ProviderConfiguration { @Bean public RegistryConfig registryConfig() { RegistryConfig registryConfig = new RegistryConfig(); registryConfig.setAddress("zookeeper://119.45.52.68:2181?timeout=10000"); //registryConfig.setTimeout(10000); return registryConfig; } } }
package de.jilence.mojang_api.api.name; import de.jilence.mojang_api.json.JSONArray; import de.jilence.mojang_api.json.JSONCreator; import de.jilence.mojang_api.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.atomic.AtomicReference; public class NameHistory { private final String uuid; public NameHistory(String uuid) { this.uuid = uuid; } /** * get a list of all names the player had * * @return a list of names */ public ArrayList<String> getNameList() { JSONArray jsonArray = JSONCreator.getJsonArray("https://api.mojang.com/user/profiles/" + uuid + "/names"); if(jsonArray == null) return null; ArrayList<String> nameList = new ArrayList<>(); jsonArray.forEach(o -> { JSONObject jsonObject = new JSONObject(o); nameList.add(jsonObject.getString("name")); }); return nameList; } /** * get the player name and date when the name was changed * * @return a hashmap with player name and date * @see java.text.SimpleDateFormat to format the date */ public HashMap<String, Integer> getList() { JSONArray jsonArray = JSONCreator.getJsonArray("https://api.mojang.com/user/profiles/" + uuid + "/names"); if(jsonArray == null) return null; HashMap<String, Integer> list = new HashMap<>(); jsonArray.forEach(o -> { JSONObject jsonObject = new JSONObject(o); list.put(jsonObject.getString("name"), jsonObject.getInt("changedToAt")); }); return list; } /** * get the list of dates when the name was changed to a specific name * * @param playerName that search when the name was changed * @return a list of dates * @see java.text.SimpleDateFormat to format the date */ public ArrayList<Integer> getChangedAt(String playerName) { JSONArray jsonArray = JSONCreator.getJsonArray("https://api.mojang.com/user/profiles/" + uuid + "/names"); ArrayList<Integer> changedAt = new ArrayList<>(); if(jsonArray == null) return null; jsonArray.forEach(o -> { JSONObject jsonObject = new JSONObject(o); if(jsonObject.getString("name").equalsIgnoreCase(playerName)) { changedAt.add(jsonObject.getInt("changedToAt"));}}); return changedAt; } }
/* * Copyright (C) 2019-2023 Hedera Hashgraph, LLC * * 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.hedera.mirror.common.converter; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.module.SimpleModule; import com.hedera.mirror.common.domain.entity.EntityId; import io.hypersistence.utils.hibernate.type.util.JsonConfiguration; import java.io.IOException; import lombok.AccessLevel; import lombok.NoArgsConstructor; @NoArgsConstructor(access = AccessLevel.PRIVATE) @SuppressWarnings("java:S6548") public class ObjectToStringSerializer extends JsonSerializer<Object> { public static final ObjectToStringSerializer INSTANCE = new ObjectToStringSerializer(); public static final ObjectMapper OBJECT_MAPPER; static { var module = new SimpleModule(); module.addDeserializer(EntityId.class, EntityIdDeserializer.INSTANCE); module.addSerializer(EntityId.class, EntityIdSerializer.INSTANCE); OBJECT_MAPPER = new ObjectMapper() .registerModule(module) .setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE); // Configure hyperpersistence utils so that JsonBinaryType uses the same object mapper JsonConfiguration.INSTANCE.getObjectMapperWrapper().setObjectMapper(OBJECT_MAPPER); } @Override public void serialize(Object o, JsonGenerator gen, SerializerProvider serializers) throws IOException { var json = OBJECT_MAPPER.writeValueAsString(o); gen.writeString(json); } }
package com.muryang.sureforprice.dao; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import com.muryang.sureforprice.vo.BaseUrl; public class BaseURLDAO { private SqlSessionFactory sqlSessionFactory = null; public BaseURLDAO() { sqlSessionFactory = MyBatisConnectionFactory.getSessionFactory(MyBatisConnectionFactory.DEFAULT_CONFIG) ; } public BaseURLDAO(String config) { sqlSessionFactory = MyBatisConnectionFactory.getSessionFactory(config) ; } public List<BaseUrl> selectAll(){ List<BaseUrl> list = null; SqlSession session = sqlSessionFactory.openSession(); try { list = session.selectList("BaseURL.selectAll"); } finally { session.close(); } System.out.println("selectAll() --> " + list); return list; } }
package com.doronin.mvc.controller; import com.doronin.mvc.model.Tweet; import com.doronin.mvc.service.TweetService; import com.doronin.mvc.service.UserService; import com.doronin.mvc.validation.TweetFormValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.RedirectView; import javax.validation.Valid; @Controller public class TweetController { @Autowired TweetFormValidator tweetFormValidator; private TweetService tweetService; @Autowired private UserService userService; @InitBinder protected void initBinder(WebDataBinder binder) { binder.setValidator(tweetFormValidator); } @Autowired public void setTweetService(TweetService tweetService) { this.tweetService = tweetService; } @Autowired public void setUserService(UserService userService) { this.userService = userService; } @RequestMapping(value = "/summary", method = RequestMethod.POST) public ModelAndView shareTweet(@ModelAttribute("tweetForm") @Valid Tweet tweetForm, BindingResult bindingResult) { ModelAndView modView; if (bindingResult.hasErrors()) { modView = new ModelAndView("summary"); modView.addObject("tweets", tweetService.getAllTweetsOrderedByDesc()); } else { org.springframework.security.core.userdetails.User owner = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); tweetForm.setUser(userService.findByLogin(owner.getUsername())); tweetService.saveTweet(tweetForm); modView = new ModelAndView(new RedirectView("/summary")); } return modView; } @RequestMapping(value = "/summary", method = RequestMethod.GET) public ModelAndView summary() { ModelAndView model = new ModelAndView(); model.addObject("tweetForm", new Tweet()); model.addObject("tweets", tweetService.getAllTweetsOrderedByDesc()); model.setViewName("summary"); return model; } }
package cn.aurora.ssh.dao; import java.util.List; import cn.aurora.ssh.domain.LeaveBill; public interface ILeaveBillDao { void saveLeaveBill(LeaveBill leaveBill); List<LeaveBill> findLeaveBillListByEmployee(Long id); LeaveBill findLeaveBillById(Long id); void deleteLeaveBillByEntity(LeaveBill leaveBill); }
package com.jim.multipos.ui.start_configuration.account; import com.jim.multipos.core.BaseView; import com.jim.multipos.data.db.model.Account; import com.jim.multipos.utils.CompletionMode; import java.util.List; public interface AccountView extends BaseView { void setAccounts(List<Account> accountList); void notifyList(); void setMode(CompletionMode mode); void checkCompletion(); }
package com.sietecerouno.atlantetransportador.sections; import android.app.ActionBar; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.QuerySnapshot; import com.sietecerouno.atlantetransportador.R; import com.sietecerouno.atlantetransportador.manager.Manager; import com.sietecerouno.atlantetransportador.utils.CustomObj; import com.sietecerouno.atlantetransportador.utils.NumberTextWatcherForThousand; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Objects; import jp.wasabeef.glide.transformations.CropCircleTransformation; import me.zhanghai.android.materialratingbar.MaterialRatingBar; public class HistoryActivity extends AppCompatActivity { FirebaseFirestore db; String TAG = "GIO"; ListView listview; TextView text_empty; DocumentReference docRefMyCar; DocumentReference docRefMyUser; TextView v_1; TextView v_2; TextView v_3; TextView v_4; ArrayList listCars; ArrayList listIDCars; ArrayList listTypeCars; int iNum; public static List<CustomObj> obj = new ArrayList<CustomObj>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_current_pedidos); //title getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); getSupportActionBar().setCustomView(R.layout.custom_bar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); //bg ImageView bg = (ImageView) findViewById(R.id.bg); Glide.with(bg.getContext()).load(R.drawable.bg_solo).into(bg); text_empty = (TextView) findViewById(R.id.text_empty); TextView title = (TextView) findViewById(R.id.action_bar_title); ImageView btnMenu = (ImageView) findViewById(R.id.btnMenu); btnMenu.setVisibility(View.INVISIBLE); title.setText("HISTORIAL"); v_1 = (TextView) findViewById(R.id.v_1); v_2 = (TextView) findViewById(R.id.v_2); v_3 = (TextView) findViewById(R.id.v_3); v_4 = (TextView) findViewById(R.id.v_4); listCars = new ArrayList(); listCars.add(v_1); listCars.add(v_2); listCars.add(v_3); listCars.add(v_4); db = FirebaseFirestore.getInstance(); text_empty.setText("Actualmente no se cuenta con servicios disponibles"); listview = (ListView) findViewById(R.id.s_listView); FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); docRefMyUser = db.collection("usuarios").document(user.getUid()); if(Manager.getInstance().vehicleSelected != "") docRefMyCar = db.collection("vehiculos").document(Manager.getInstance().vehicleSelected); checkdb(); db.collection("vehiculos") .whereEqualTo("user", docRefMyUser) .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { listIDCars = new ArrayList(); listTypeCars = new ArrayList(); iNum = 0; for (DocumentSnapshot document : task.getResult()) { listIDCars.add(document.getId()); Long myType = (Long) document.getData().get("tipo"); int realType = myType.intValue(); listTypeCars.add(realType); TextView textViewTemp = (TextView) listCars.get(iNum); textViewTemp.setVisibility(View.VISIBLE); textViewTemp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { allCarsGray(); if (view.getId() == R.id.v_1) { v_1.setTextColor(getResources().getColor(R.color.blueApp)); docRefMyCar = db.collection("vehiculos").document(listIDCars.get(0).toString()); } if (view.getId() == R.id.v_2) { v_2.setTextColor(getResources().getColor(R.color.blueApp)); docRefMyCar = db.collection("vehiculos").document(listIDCars.get(1).toString()); } if (view.getId() == R.id.v_3) { v_3.setTextColor(getResources().getColor(R.color.blueApp)); docRefMyCar = db.collection("vehiculos").document(listIDCars.get(2).toString()); } if (view.getId() == R.id.v_4) { v_4.setTextColor(getResources().getColor(R.color.blueApp)); docRefMyCar = db.collection("vehiculos").document(listIDCars.get(3).toString()); } obj.clear(); listview.setAdapter(null); checkdb(); } }); if (Objects.equals(document.getId(), Manager.getInstance().vehicleSelected)) { textViewTemp.setTextColor(getResources().getColor(R.color.blueApp)); } iNum++; } } } }); } void allCarsGray() { v_1.setTextColor(getResources().getColor(R.color.gray)); v_2.setTextColor(getResources().getColor(R.color.gray)); v_3.setTextColor(getResources().getColor(R.color.gray)); v_4.setTextColor(getResources().getColor(R.color.gray)); } void checkdb() { db.collection("pedidos") .whereEqualTo("transportista", docRefMyUser) .whereEqualTo("estado_actual", 3) .whereEqualTo("vehiculo_obj", docRefMyCar) .addSnapshotListener(new EventListener<QuerySnapshot>() { @Override public void onEvent(@Nullable QuerySnapshot documentSnapshots, @Nullable FirebaseFirestoreException e) { if (e != null) { Log.w(TAG, "Listen failed.", e); return; } obj.clear(); for (final DocumentSnapshot document : documentSnapshots.getDocuments()) { Integer type = 0; Integer valor = 0; if(document.getData().get("tipo") != null && document.getData().get("valor") != null) { type = Integer.parseInt(document.getLong("tipo").toString()); try{ valor = Integer.parseInt(document.getData().get("valor").toString()); }catch (Exception e1) { Double strTemp = (Double) document.getData().get("valor"); valor = strTemp.intValue(); } } String quien_entrega = document.getData().get("quien_entrega").toString(); String que_envia = document.getData().get("que_envia").toString(); String origenStr = document.getData().get("origenStr").toString(); String destinoStr = document.getData().get("destinoStr").toString(); String observaciones = ""; String rank = "5"; DocumentReference user = (DocumentReference) document.getData().get("user"); String userId = user.getId().toString(); Date fechaEntrega = (Date) document.getData().get("fecha_entrega"); if(document.getData().get("observaciones")!=null) observaciones = document.getData().get("observaciones").toString(); if(document.getData().get("calificacion_trans") != null) rank = document.getData().get("calificacion_trans").toString(); String info_txt = "FECHA MÁXIMO DE ENTREGA: \n" +Manager.getInstance().dateFormatter.format(fechaEntrega.getTime()) + "\n" +"Quien envía: " + quien_entrega + "\n" +"Envío: " + que_envia + "\n" +"Origen: " + origenStr + "\n" +"Destino: " + destinoStr+ "\n" +"Observaciones: " + observaciones; obj.add(new CustomObj(document.getId(), info_txt, rank, false, userId, type, valor,0)); } if(obj.size() > 0) { ListAdapter_history customAdapter = new ListAdapter_history(HistoryActivity.this, R.layout.choose_service_tab_custom, obj); listview.setAdapter(customAdapter); }else{ text_empty.setText("Actualmente no se cuenta con servicios disponibles"); } } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } } class ListAdapter_history extends ArrayAdapter<CustomObj> { List<CustomObj> objList; CustomObj p; String TAG = "GIO"; public ListAdapter_history(Context context, int textViewResourceId) { super(context, textViewResourceId); } public ListAdapter_history(Context context, int resource, List<CustomObj> items) { super(context, resource, items); objList = items; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ListAdapter_history.ViewHolder holder = null; if (convertView == null) { LayoutInflater vi = LayoutInflater.from(getContext()); vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = vi.inflate(R.layout.history_tab_custom, null); holder = new ListAdapter_history.ViewHolder(); holder.backgroundImage = convertView.findViewById(R.id.selectedBG); holder.myCel = (RelativeLayout) convertView.findViewById(R.id.myCel); holder.nameUser = (TextView) convertView.findViewById(R.id.name); holder.info = (TextView) convertView.findViewById(R.id.info); holder.type = (TextView) convertView.findViewById(R.id.type); holder.status = (EditText) convertView.findViewById(R.id.status); holder.myRate = (MaterialRatingBar) convertView.findViewById(R.id.myRate); holder.icon = (ImageView) convertView.findViewById(R.id.icon); holder.info.setText(objList.get(position).value); holder.rank = (objList.get(position).img); FirebaseFirestore db = FirebaseFirestore.getInstance(); holder.info.setMovementMethod(new ScrollingMovementMethod()); Double aDouble = Double.valueOf(holder.rank); holder.myRate.setRating(aDouble.intValue()); final ListAdapter_history.ViewHolder finalHolder1 = holder; finalHolder1.idClient = objList.get(position).value2.toString(); holder.status.addTextChangedListener(new NumberTextWatcherForThousand(holder.status)); holder.status.setText("$"+objList.get(position).valueInt2); //Long lg = (Long) document.getData().get("calificacion"); //holder.myRate.setRating(lg.intValue()); int colorToSend = 0; if(objList.get(position).valueInt == 1) { holder.type.setText("SERVICIO INMEDIATO"); holder.type.setTextColor(ContextCompat.getColor(getContext(), R.color.blueApp)); colorToSend = R.color.blueApp; } else if(objList.get(position).valueInt == 2) { holder.type.setText("SERVICIO PERSONALIZADO"); holder.type.setTextColor(ContextCompat.getColor(getContext(), R.color.greenApp)); colorToSend = R.color.greenApp; } else if(objList.get(position).valueInt == 3) { holder.type.setText("SERVICIO PROGRAMADO"); holder.type.setTextColor(ContextCompat.getColor(getContext(), R.color.yellowApp)); colorToSend = R.color.yellowApp; } // set USER info from db user DocumentReference docRefUser = db.collection("usuarios").document(objList.get(position).value2); docRefUser.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot document = task.getResult(); if (document != null) { finalHolder1.nameUser.setText(document.getData().get("nombre").toString()); //Long lg = (Long) document.getData().get("calificacion"); //finalHolder1.myRate.setRating(lg.intValue()); CropCircleTransformation cropCircleTransformation = new CropCircleTransformation(); Glide.with(finalHolder1.icon.getContext()) .load(document.getData().get("foto").toString()) .apply(RequestOptions.bitmapTransform(cropCircleTransformation)) .into(finalHolder1.icon); } else { Log.i(TAG, "No such document inside"); } } else { Log.i(TAG, "get failed with inside", task.getException()); } } }); /* final int finalcolorToSend = colorToSend; holder.myCel.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { String idUser = String.valueOf(objList.get(position).value2); Manager.getInstance().actualClientId_finish = idUser; Intent i = new Intent(getContext(), ResumoFinishAllActivity.class); i.putExtra("type", true); i.putExtra("idPersonalizado", objList.get(position).name); i.putExtra("color", finalcolorToSend); getContext().startActivities(new Intent[]{i}); ((Activity)getContext()).finish(); } }); */ convertView.setTag(holder); }else { holder = (ListAdapter_history.ViewHolder) convertView.getTag(); } return convertView; } public static class ViewHolder { public ImageView icon; public TextView nameUser; public TextView info; public TextView type; public EditText status; public MaterialRatingBar myRate; View backgroundImage; public RelativeLayout myCel; public Boolean isNew = true; public String stateActual; public String rank; public String idClient; } public int getPositionById(String _tag) { Integer pos = 0; for (int i = 0; i < ChooseVActivity.obj.size(); i++) { if (Objects.equals(_tag, String.valueOf(ChooseVActivity.obj.get(i).selected))) { pos = i; return pos; } } return pos; } @Override public int getViewTypeCount() { return getCount(); } @Override public int getItemViewType(int position) { return position; } }
package com.tencent.mm.g.a; public final class oe$a { public long bJC; }
package earth.xor; public class EmbeddedMongoProperties { public final static int PORT = 12345; }
package com.tencent.mm.plugin.appbrand.widget.input; import android.graphics.drawable.Drawable; import com.tencent.mm.br.e; import com.tencent.mm.plugin.appbrand.s.b; import com.tencent.mm.plugin.appbrand.widget.input.ag.c; import com.tencent.mm.sdk.platformtools.ad; final class ag$a extends e { private String[] gJz; ag$a() { super(new c(ad.getContext())); this.gJz = null; this.gJz = ad.getContext().getResources().getStringArray(b.merge_smiley_unicode_emoji); } public final int apV() { return 0; } public final int apW() { return this.gJz != null ? this.gJz.length : 0; } public final Drawable mg(int i) { return new ag.b(mh(i), ag.bB(), (byte) 0); } public final String mh(int i) { if (this.gJz == null || i < 0 || i > this.gJz.length - 1) { return ""; } String[] split = this.gJz[i].split(" "); char[] toChars = Character.toChars(Integer.decode(split[0]).intValue()); return toChars + Character.toChars(Integer.decode(split[1]).intValue()); } public final String getText(int i) { return mh(i); } public final String mi(int i) { return mh(i); } }
package com.tuanhk.utils; import android.util.Log; public class AndroidUtils { public static float density = 1; private static final int INT_EMPTY = 0; public static int dp(float value) { try { if (value == 0) return 0; return (int) Math.ceil(density * value); } catch (Exception e) { Log.d( "dp exception [%s]", e.getMessage()); } return INT_EMPTY; } }
package com.guli.edu.service.impl; import com.guli.edu.entity.Comment; import com.guli.edu.mapper.CommentMapper; import com.guli.edu.service.CommentService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 评论 服务实现类 * </p> * * @author testjava * @since 2021-04-03 */ @Service public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService { }
package sysexp; public class Fait { String nom; Object valeur; public Fait(String nom, Object valeur) { this.nom = nom; this.valeur = valeur; } public String lireNom() { return this.nom; } public Object lireValeur() { return this.valeur; } public void ecrireNom(String nom) { this.nom = nom; } public void ecrireValeur(Object valeur) { this.valeur = valeur; } public String toString() { return nom + "->" + valeur; } }
package main; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; import ast.SVMVisitorImpl; import ast.statements.BlockNode; import ast.types.TypeNode; import exceptions.MemoryAccessException; import exceptions.TypeException; import interpreter.ExecuteSVM; import interpreter.lexer.SVMLexer; import interpreter.lexer.SVMParser; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import parser.SimpLanPlusLexer; import parser.SimpLanPlusParser; import parser.VerboseListener; import ast.SimpLanPlusVisitorImpl; import semanticAnalysis.Environment; import semanticAnalysis.SemanticError; import ast.SVMVisitorImpl; public class Main { public static void main(String[] args) throws Exception { File path = new File("./Tests/"); File[] files = path.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { //test all the files in Tests folder System.out.print("PROCESSING " + files[i] + ": \n"); FileInputStream is = new FileInputStream(files[i]); ANTLRInputStream input = new ANTLRInputStream(is); SimpLanPlusLexer lexer = new SimpLanPlusLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); lexer.removeErrorListeners(); lexer.addErrorListener(new VerboseListener()); if (lexer.errorCount() > 0) { System.out.println("Lexical errors in the file. Exiting the compilation process now"); } else { SimpLanPlusParser parser = new SimpLanPlusParser(tokens); parser.removeErrorListeners(); parser.addErrorListener(new VerboseListener()); SimpLanPlusVisitorImpl visitor = new SimpLanPlusVisitorImpl(); BlockNode ast = visitor.visitBlock(parser.block()); //generazione AST ast.setMain(true); //i need this for code generation //SIMPLE CHECK FOR LEXER ERRORS if (parser.getNumberOfSyntaxErrors() > 0) { System.out.println("The program was not in the right format. Exiting the compilation process now"); } else { Environment env = new Environment(); ArrayList<SemanticError> SemanticErr = ast.checkSemantics(env); if (!SemanticErr.isEmpty()) { if (SemanticErr.size() == 1) System.out.println("You had: " + SemanticErr.size() + " error: "); else System.out.println("You had: " + SemanticErr.size() + " errors:"); for (SemanticError e : SemanticErr) System.out.println("\t" + e); } else { //System.out.println("Visualizing AST..."); //System.out.println(ast.toPrint("")); try { TypeNode type = ast.typeCheck(); //type-checking bottom-up System.out.println(type.toPrint("Type checking ok! Type of the program is: ")); } catch (TypeException e) { System.out.println(e.getMessage()); continue; } ArrayList<SemanticError> effectsErr = ast.checkEffects(env); List<String> unique = new ArrayList<>(); if (!effectsErr.isEmpty()) { System.out.println("Effects analysis:"); for (SemanticError e : effectsErr) if (!unique.contains(e.msg)) unique.add(e.msg); for (String s : unique) System.out.println("\t" + s); } else { File dir = new File("Tests/compiledTests/"); if (!dir.exists()) { dir.mkdirs(); } String code = ast.codeGeneration(); String tmp = files[i].getPath().substring(8); BufferedWriter out = new BufferedWriter(new FileWriter("Tests/compiledTests/" + tmp + ".asm")); out.write(code); out.close(); System.out.println("Code generated! Assembling and running generated code."); FileInputStream isASM = new FileInputStream("Tests/compiledTests/" + tmp + ".asm"); ANTLRInputStream inputASM = new ANTLRInputStream(isASM); SVMLexer lexerASM = new SVMLexer(inputASM); CommonTokenStream tokensASM = new CommonTokenStream(lexerASM); SVMParser parserASM = new SVMParser(tokensASM); //parserASM.assembly(); SVMVisitorImpl visitorSVM = new SVMVisitorImpl(); visitorSVM.visit(parserASM.assembly()); System.out.println("You had: " + lexerASM.errorCount() + " lexical errors and " + parserASM.getNumberOfSyntaxErrors() + " syntax errors."); if (lexerASM.errorCount() > 0 || parserASM.getNumberOfSyntaxErrors() > 0) System.exit(1); System.out.println("Starting Virtual Machine..."); ExecuteSVM vm = new ExecuteSVM(100, visitorSVM.getCode()); try { vm.run(); } catch (MemoryAccessException e) { System.out.println(e.getMessage()); } } } } } } } } }
package datechooser.controller; import datechooser.view.GridPane; public abstract interface DateChooseController { public abstract void reBound(); public abstract void setView(GridPane paramGridPane); } /* Location: /home/work/vm/shared-folder/reverse/ketonix/KetonixUSB-20170310.jar!/datechooser/controller/DateChooseController.class * Java compiler version: 5 (49.0) * JD-Core Version: 0.7.1 */
package com.javarush.task.task13.task1326; /* Сортировка четных чисел из файла */ import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; public class Solution { public static void main(String[] args) throws IOException{ // напишите тут ваш код // напишите тут ваш код BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in)); String filename = br1.readLine(); BufferedReader fileReader = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); ArrayList<Integer> list = new ArrayList<>(); try { while (fileReader.ready()) { int i = Integer.parseInt(fileReader.readLine()); if (i % 2 == 0) list.add(i); } } catch (NumberFormatException e) { fileReader.close(); br1.close(); Collections.sort(list); for (int element : list) System.out.println(element); } } } // ArrayList list = new ArrayList(); // String file; // int line = 0; // BufferedReader redfilename = new BufferedReader(new InputStreamReader(System.in)); //file = redfilename.readLine(); // // BufferedReader readfile = new BufferedReader(new InputStreamReader(new FileInputStream(file))); // while (readfile.ready()) { // try { // line = Integer.parseInt(readfile.readLine()); // } catch (NumberFormatException e) { // e.printStackTrace(); // continue; // } // if ((line % 2) == 0) { // list.add(line); // } // } // Collections.sort(list); // for (int i : list) { // System.out.println(i); // } // readfile.close();
package com.tencent.mm.plugin.appbrand.jsapi; import android.content.Intent; import com.tencent.mm.bg.d; import com.tencent.mm.plugin.appbrand.l; import com.tencent.mm.ui.MMActivity; import org.json.JSONObject; public final class ao extends a { public static final int CTRL_INDEX = 62; public static final String NAME = "openAddress"; public final void a(l lVar, JSONObject jSONObject, int i) { Intent intent = new Intent(); intent.putExtra("req_app_id", lVar.mAppId); intent.putExtra("launch_from_appbrand", true); MMActivity c = c(lVar); if (c == null) { lVar.E(i, f("fail", null)); return; } c.geJ = new 1(this, lVar, i); d.a(c, "address", ".ui.WalletSelectAddrUI", intent, hashCode() & 65535, false); } }
package com.phoebus.test.service; import com.phoebus.test.dao.CustomerRepository; import com.phoebus.test.model.Customer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class CustomerServiceImpl implements CustomerService { @Autowired private CustomerRepository customerRepository; @Override public List<Customer> retrieveAllCustomers() { return customerRepository.findAll(); } @Override public Customer retrieveCustomer(Long id) { Optional<Customer> customer = customerRepository.findById(id); if (customer.isPresent()) return customer.get(); else return null; } @Override public void deleteCustomer(Long id) { Optional<Customer> customer = customerRepository.findById(id); if (customer.isPresent()) { customer.get().getAccounts(); } customerRepository.deleteById(id); } @Override public Customer createCustomer(Customer customer) { return customerRepository.save(customer); } }
package chap15.verify.exam08; public class Student { public int studentNum; public String name; public Student(int studentNum, String name) { this.studentNum = studentNum; this.name = name; } @Override public int hashCode() { return studentNum; } @Override public boolean equals(Object obj) { if (obj instanceof Student) { Student student = (Student) obj; if(student.hashCode() == hashCode()) { return true; } } return false; } }
package org.me.gcu.coursework; // // Name William Thomson // Student ID S1426481 // Programme of Study Computing // import android.util.Log; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.util.Arrays; import java.util.LinkedList; public class XMLPullParserHandler { LinkedList<Earthquake> allEarthquakes; private Earthquake earthquake; private String text; public XMLPullParserHandler() { // make all to parsing code // Note this is not the best location allEarthquakes = new LinkedList<>(); // Write list to log for testing // if(allEarthquakes != null){ // Log.e("MyTag", "List not null"); // for (Object o : allEarthquakes){ // Log.e("MyTag", o.toString()); // } // } // else { // Log.e("MyTag", "List null"); // // } } // get all earthquakes public LinkedList<Earthquake> getEarthquakes() { return allEarthquakes; } public LinkedList<Earthquake> parse(String lDataToParse) { //Earthquake widget = null; //LinkedList<Earthquake> allEarthquakes = null; Boolean itemsStart = false; XmlPullParserFactory factory; XmlPullParser xpparser; try { String dataToParse2 = lDataToParse.replaceAll("geo:lat", "lat"); String dataToParse = dataToParse2.replaceAll("geo:long", "long"); factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); xpparser = factory.newPullParser(); xpparser.setInput(new StringReader(dataToParse)); Log.e("Start try - parsing","here"); int eventType = xpparser.getEventType(); //eventType = xpparser.next(); // eventType.next(); Log.i("Tag names are ", "EventType: " + eventType); while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_TAG: // Check which Tag we have if (xpparser.getName().equalsIgnoreCase("rss")) // maybe 'channel' { // allEarthquakes = new LinkedList<>(); Log.e("ItemStart","Start Tag: Rss"); } else if (xpparser.getName().equalsIgnoreCase("channel")) // maybe 'channel' { allEarthquakes = new LinkedList<>(); Log.e("ItemStart","Start Tag: Channel"); } else if (xpparser.getName().equalsIgnoreCase("image")) // maybe 'channel' { Log.e("ItemStart","Start Tag: image"); } else if (xpparser.getName().equalsIgnoreCase("item")) { Log.e("ItemStart","Start Tag: item"); earthquake = new Earthquake(); } break; case XmlPullParser.TEXT: text = xpparser.getText(); Log.e("ItemText","Text Tag: " + xpparser.getText()); break; case XmlPullParser.END_TAG: if (xpparser.getName().equalsIgnoreCase("image")) { // Log.e("ItemText","Text Tag: " + itemsStart); itemsStart = true; } else if (xpparser.getName().equalsIgnoreCase("item")) { //Log.e("MyTag","widget is " + earthquake.toString()); allEarthquakes.add(earthquake); } // else if (xpparser.getName().equalsIgnoreCase("title") && itemsStart == true) { // // Now just get the associated text // // String temp = xpparser.nextText(); // // Do something with text //// Log.e("MyTag","Title is " + temp); // earthquake.setTitle(text); // // // } else if (xpparser.getName().equalsIgnoreCase("description") && itemsStart == true) { //String temp = xpparser.nextText(); parseDescription(text); earthquake.setDescription(text); } // else // if (tagname.equalsIgnoreCase("link")) // { // earthquake.setLink(text); // } else if (xpparser.getName().equalsIgnoreCase("pubDate") && itemsStart == true) { // String temp = xpparser.nextText(); earthquake.setPubDate(text); } else if (xpparser.getName().equalsIgnoreCase("category") && itemsStart == true) { // String temp = xpparser.nextText(); earthquake.setCategory(text); } else if (xpparser.getName().equalsIgnoreCase("lat")) { Log.e("LatText","LatText Tag: " + xpparser.getText()); earthquake.setLat(text); } else if (xpparser.getName().equalsIgnoreCase("long")) { Log.e("LongText","LongText Tag: " + xpparser.getText()); earthquake.setLong(text); } else if (xpparser.getName().equalsIgnoreCase("link") && itemsStart == true) { //Log.e("LongText","LongText Tag: " + xpparser.getText()); earthquake.setLink(text); } break; default: break; } // Get the next event eventType = xpparser.next(); } // End of while //return allEarthquakes; } catch (XmlPullParserException ae1) { Log.e("MyTags", "Parsing error: " + ae1.toString()); } catch (IOException ae1) { Log.e("MyTagsss", "IO error during parsing"); } Log.e("MyTag","End document"); return allEarthquakes; } // parse the description to attain the: // long, lat, location, public void parseDescription(String lDescriptionFromXML){ // further parse title to get longitude // date/time: Sat, 29 Dec 2018 03:39:09 , Location: PHILIPPINES , Lat/long: 5.974,126.828 , Depth: 60 km , Magnitude: 7.0] // 0 1 2 3 4 String magnitude = ""; String[] listOfData = lDescriptionFromXML.split(";"); String[] value; for(int x = 0; x <= 4; x++) { if( x==1 ) { value = listOfData[x].split(":"); // Log.e("MyTag","Description FParsed: \n" + value[1]); String earthquakeDetail = value[1]; earthquake.setLocation(earthquakeDetail); } else if( x==3 ){ value = listOfData[x].split(":"); // Log.e("MyTag","Descrip FParsed: \n" + value[1]); String earthquakeDetail = value[1]; earthquake.setDepth(earthquakeDetail); } else if( x==4 ){ value = listOfData[x].split(":"); // Log.e("MyTag","Descrip FParsed: \n" + value[1]); String earthquakeDetail = value[1]; earthquake.setMagnitude(earthquakeDetail); } } //Log.e("MyTag","Descrpt FParsed: " + Arrays.toString(listOfData)); // return ""; } }
package android.support.v4.b.a; import android.graphics.drawable.Drawable; import java.lang.reflect.Method; final class b { static Method rq; static boolean rr; private static Method rs; private static boolean rt; public static int i(Drawable drawable) { if (!rt) { try { Method declaredMethod = Drawable.class.getDeclaredMethod("getLayoutDirection", new Class[0]); rs = declaredMethod; declaredMethod.setAccessible(true); } catch (NoSuchMethodException e) { } rt = true; } if (rs != null) { try { return ((Integer) rs.invoke(drawable, new Object[0])).intValue(); } catch (Exception e2) { rs = null; } } return -1; } }
/* * Minesweeper Project * by Group3 : Arnaud BABOL, Guillaume SIMMONEAU */ package Controler.Listeners; import Controler.Minesweeper; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; /** * * @author nono */ public class MenuCustomListener implements ActionListener, MouseListener { /** * * @param e */ @Override public void actionPerformed(ActionEvent e) { this.displayOptions(); } @Override public void mouseClicked(MouseEvent e) { this.displayOptions(); } @Override public void mousePressed(MouseEvent e) {} @Override public void mouseReleased(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} private void displayOptions() { Minesweeper.getInstance().jumToOptions(); } }
package org.usfirst.frc.team467.robot; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.ctre.phoenix.motorcontrol.ControlMode; import com.ctre.phoenix.motorcontrol.can.WPI_TalonSRX; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.MotorSafetyHelper; public class Climber { private static final Logger LOGGER = LogManager.getLogger(Climber.class); private static Climber instance; WPI_TalonSRX climbMotorLeader; WPI_TalonSRX climbMotorFollower1; private TalonSpeedControllerGroup climbController; public Climber() { if (!RobotMap.HAS_CLIMBER) { return; } if(RobotMap.HAS_CLIMBER) { climbMotorLeader = new WPI_TalonSRX(RobotMap.CLIMB_MOTOR_CONTROLLER_LEADER); climbMotorFollower1 = new WPI_TalonSRX(RobotMap.CLIMB_MOTOR_CONTROLLER_FOLLOWER1); climbController = new TalonSpeedControllerGroup(ControlMode.PercentOutput, false, climbMotorLeader, climbMotorFollower1); LOGGER.info("Created climber Motors"); } else { LOGGER.info("Not enough climb motors, no climb capabilities"); } } public static Climber getInstance() { if (instance == null) { if (!RobotMap.HAS_CLIMBER) { } else { instance = new Climber(); } } return instance; } public void climbUp() { if (DriverStation.getInstance().getMatchTime() <= 30.0) { climbController.set(ControlMode.PercentOutput, RobotMap.CLIMBER_SPEED); LOGGER.info("Climbing up."); } else { LOGGER.info("Too early to climb up."); } } public void neutral() { climbController.set(ControlMode.PercentOutput, 0); //LOGGER.info("Climber stopped"); } public void setOpenLoopRamp() { climbController.setOpenLoopRamp(RobotMap.CLIMBER_RAMP_TIME); } }
package io.fab.connector.data; import java.io.Serializable; public class SupplierDelivery implements Serializable { private static final long serialVersionUID = 7587063469810680533L; private Integer timeframe; private SupplierPurchase purchase; SupplierDelivery() {} public SupplierDelivery(final Integer timeframe, final SupplierPurchase purchase) { this.timeframe = timeframe; this.purchase = purchase; } public Integer getTimeframe() { return timeframe; } public SupplierPurchase getPurchase() { return purchase; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (purchase == null ? 0 : purchase.hashCode()); result = prime * result + (timeframe == null ? 0 : timeframe.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final SupplierDelivery other = (SupplierDelivery) obj; if (purchase == null) { if (other.purchase != null) { return false; } } else if (!purchase.equals(other.purchase)) { return false; } if (timeframe == null) { if (other.timeframe != null) { return false; } } else if (!timeframe.equals(other.timeframe)) { return false; } return true; } @Override public String toString() { return "SupplierDelivery [timeframe=" + timeframe + ", purchase=" + purchase + "]"; } }
package temptalemethod.design.pattern.example; class SpecializationOne extends Generalization { protected void thirdStep() { System.out.println( "Subclass implementation" ); } protected void secondStep() { System.out.println( "Subclass implementation" ); } }
/*@author Abhishek Sen * isPrime function checks whether n is prime or not returns 1->prime 0->not prime * complexity O(n^0.5) * but n^0.5 is not calculated mathematically to avoid overhead */ import java.io.*; import java.math.BigInteger; class Prime { static BigInteger count; static int isPrime(BigInteger n) { if (n.compareTo(BigInteger.ONE)<=0)return 0; else if (n.equals(BigInteger.TWO) )return 1; BigInteger i=BigInteger.valueOf(2); BigInteger cn=n; for(i=BigInteger.TWO;i.compareTo(cn)<0;i=i.add(BigInteger.ONE )) { count=count.add(BigInteger.ONE); if(n.mod(i).equals(BigInteger.ZERO))return 0; cn=n.divide(i); } return 1; } public static void main(String args[]) throws IOException { // StringBuilder s = new StringBuilder(""); // BufferedReader buf=new BufferedReader(new InputStreamReader(System.in)); // // System.out.print("enter the number: "); // String Line = buf.readLine(); // while(true) // { // s.append(Line); // Line = buf.readLine(); // if(Line.equals("end")) break; // } // System.out.println("here: -"+s.toString().trim()+"-"); // BigInteger n = new BigInteger(s.toString().trim()); BigInteger n = new BigInteger("48112959837082048697 "); count=BigInteger.ZERO; int check=isPrime(n); System.out.println(n + " isPrime> "+(check==1?"true":"false")+" number of modulo checks: "+count); } }
/** * (C) Copyright IBM Corporation 2014. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.wasdev.wlp.ant.install; import junit.framework.TestCase; public class VersionTest extends TestCase { public void testParse() throws Exception { Version v = null; v = Version.parseVersion("10.20.30"); assertEquals(10, v.getMajor()); assertEquals(20, v.getMinor()); assertEquals(30, v.getMicro()); assertEquals(null, v.getQualifier()); v = Version.parseVersion("1.2.3_beta"); assertEquals(1, v.getMajor()); assertEquals(2, v.getMinor()); assertEquals(3, v.getMicro()); assertEquals("beta", v.getQualifier()); } public void testParseWildcard() throws Exception { Version v = null; v = Version.parseVersion("1.+", true); assertEquals(1, v.getMajor()); assertEquals(-1, v.getMinor()); assertEquals(0, v.getMicro()); assertEquals(null, v.getQualifier()); v = Version.parseVersion("1.20.+", true); assertEquals(1, v.getMajor()); assertEquals(20, v.getMinor()); assertEquals(-1, v.getMicro()); assertEquals(null, v.getQualifier()); v = Version.parseVersion("1.20.30_+", true); assertEquals(1, v.getMajor()); assertEquals(20, v.getMinor()); assertEquals(30, v.getMicro()); assertEquals("+", v.getQualifier()); } public void testMatchSimple() throws Exception { Version v1 = Version.parseVersion("10.20.30"); assertTrue(v1.match(v1)); Version v2 = Version.parseVersion("1.2.3_beta"); assertTrue(v2.match(v2)); assertFalse(v1.match(v2)); } public void testMatch() throws Exception { Version v1 = Version.parseVersion("10.20.30"); Version v2 = Version.parseVersion("1.2.3_beta"); Version wild = null; wild = Version.parseVersion("1.+", true); assertFalse(wild.match(v1)); assertTrue(wild.match(v2)); wild = Version.parseVersion("2.+", true); assertFalse(wild.match(v1)); assertFalse(wild.match(v2)); wild = Version.parseVersion("10.+", true); assertTrue(wild.match(v1)); assertFalse(wild.match(v2)); wild = Version.parseVersion("10.20.+", true); assertTrue(wild.match(v1)); assertFalse(wild.match(v2)); wild = Version.parseVersion("10.21.+", true); assertFalse(wild.match(v1)); assertFalse(wild.match(v2)); } }
package com.tyss.cg.methods; public class VaragsInputEx { // variable argument public int add(int... input) { // type ... for varag int sum = 0; for (int i = 0; i < input.length; i++) { sum += input[i]; // sum = sum + input[i]; } return sum; } public static void main(String[] args) { System.out.println("Sum: " + new VaragsInputEx().add(1, 2, 345, 34, 24, 3, 65, 7)); // this is called Vararg or // variable arguments } }
package calculator; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.text.*; import javafx.event.*; import java.math.BigInteger; public class Controller { @FXML private Text result; @FXML private Text last; private BigInteger number = BigInteger.ZERO; private int radix = 10; private String operator = ""; private boolean start = true; private boolean nextNum = false; private boolean error = false; private final Model model = new Model(); @FXML private void getNumpad(ActionEvent e) { if(error) { clearNumbers(); } else if(start) { result.setText(""); last.setText(""); start = false; } else if(nextNum) { result.setText(""); nextNum = false; } String value = ((Button)e.getSource()).getText(); if(result.getText().equals("0")) result.setText(value); else result.setText(result.getText() + value); } @FXML private void negNumber() { if(error || result.getText().equals("")) return; number = new BigInteger(result.getText(), radix); number = number.negate(); result.setText(number.toString(radix)); } @FXML private void undoNumber() { if(error || result.getText().equals("")) return; number = new BigInteger(result.getText(), radix); number = number.divide(new BigInteger(String.valueOf(radix))); result.setText(number.toString(radix)); } @FXML private void clearNumbers() { result.setText(""); last.setText(""); number = BigInteger.ZERO; operator = ""; start = true; nextNum = false; error = false; } @FXML private void getOperator(ActionEvent e) { if(error) return; String value = ((Button)e.getSource()).getText(); if(!"=".equals(value) && !"n!".equals(value)) { if (!operator.isEmpty() || result.getText().equals("")) return; operator = value; number = new BigInteger(result.getText(), radix); start = false; nextNum = true; last.setText(result.getText() + " " + operator); return; } BigInteger num1; BigInteger num2; if("=".equals(value)) { if (operator.isEmpty()) return; num1 = number; num2 = new BigInteger(result.getText(), radix); } else { if (result.getText().equals("")) return; num1 = new BigInteger(result.getText(), radix); num2 = BigInteger.ZERO; operator = value; } try { BigInteger res = model.calc(num1, num2, operator); result.setText(res.toString(radix)); } catch (Exception exception) { result.setText("math error"); error = true; } operator = ""; start = true; nextNum = false; last.setText(result.getText()); } @FXML private void changeRadix(ActionEvent e) { if(error) { clearNumbers(); } String value = ((ToggleButton)e.getSource()).getText(); BigInteger res = BigInteger.ZERO; if(!result.getText().equals("")) res = new BigInteger(result.getText(), radix); switch (value) { case "bin" -> radix = 2; case "dec" -> radix = 10; case "hex" -> radix = 16; } result.setText(res.toString(radix)); } }
package fr.umlv.escape.world; import org.jbox2d.callbacks.ContactListener; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.Body; import org.jbox2d.dynamics.BodyDef; import org.jbox2d.dynamics.FixtureDef; import org.jbox2d.dynamics.World; import fr.umlv.escape.Objects; /** * This class represent the world simulation of the Escape game. It is the link with the Jbox2d lib. * All uses of the jbox2d should be done using this class. This class is thread safe so that many thread can * interact with the world at the same time. */ public class EscapeWorld { private static EscapeWorld TheWorld; // EscapeWorld Singleton private final World world; private final float timeStep; // This defines how much simulation should advance in one second private final int velocityIterations; // This define how accurately velocity will be simulated private final int positionIterations; // This define how accurately position will be simulated /**Constant that represent the scale between the world simulation and the world draw in the screen. */ public final static float SCALE=50; //Categories for collisions public final static int CATEGORY_DECOR=1; public final static int CATEGORY_PLAYER=2; public final static int CATEGORY_ENNEMY=4; public final static int CATEGORY_BONUS=8; public final static int CATEGORY_BULLET_PLAYER=16; public final static int CATEGORY_BULLET_ENNEMY=32; private final Object lock = new Object(); private EscapeWorld(){ Vec2 gravity = new Vec2(0,0f); // No gravity in space this.world = new World(gravity); this.timeStep = 1.0f/60.0f; this.velocityIterations = 6; this.positionIterations = 3; } /** Get the unique instance of {@link EscapeWorld} * @return The unique instance of {@link EscapeWorld} */ public static EscapeWorld getTheWorld(){ if(EscapeWorld.TheWorld==null){ EscapeWorld.TheWorld = new EscapeWorld(); } return EscapeWorld.TheWorld; } /**Process the next step simulation of the world. */ public void step(){ synchronized(lock){ world.step(timeStep, velocityIterations, positionIterations); } } /**Create a body in the world. * @param def The body definition of the body to create. * @return The body created. */ public Body createBody(BodyDef def){ Objects.requireNonNull(def); synchronized(lock){ return this.world.createBody(def); } } /**Set a contact listener which will be notify for some event like collisions. * @param listener The listener to set. */ public void setContactListener(ContactListener listener){ world.setContactListener(listener); } /** * Destroy a body in the world * @param body Body to destroy. */ public void destroyBody(Body body){ Objects.requireNonNull(body); synchronized(lock){ world.destroyBody(body); } } /** * Create a fixture for a given body * @param body Body to which create the fixture. * @param fd fixture definition for the new fixture */ public void createFixture(Body body, FixtureDef fd) { Objects.requireNonNull(body); Objects.requireNonNull(fd); synchronized(lock){ body.createFixture(fd); } } /** * Set a body to active or inactive. An inactive body does not act in the simulation of the world. * @param body to set the state. * @param state The new state of the body. */ public void setActive(Body body, boolean state){ Objects.requireNonNull(body); synchronized(lock){ body.setActive(state); } } }
package server; import common.Card; import java.io.*; import java.net.ServerSocket; import java.net.Socket; /** * This class represents a concrete implementation of a magic server that uses * the TCP transport layer protocol. * * @author Evert Ball * @version 01 November 2019 */ public class TcpMagicServer extends AbstractMagicServer { /** * Creates a new <code>TcpMagicServer</code> that listens for connections * on the default magic TCP port, and uses the default card source. * * @throws FileNotFoundException if the file used to initialize the cards * is not found. */ public TcpMagicServer() throws FileNotFoundException { super(); } // end empty constructor. /** * Creates a new <code>TcpMagicServer</code> that listens for connections * on the specified port, and uses the default card source. * * @param port The port the server will listen at. * * @throws FileNotFoundException if the file used to initialize the cards * is not found. */ public TcpMagicServer(int port) throws FileNotFoundException { super(port); } // end empty constructor. /** * Creates a new <code>TcpMagicServer</code> that listens for connections * on the default port, and uses the specified card source. * * @param source The source used to generate cards. * * @throws FileNotFoundException if the file used to initialize the cards * is not found. */ public TcpMagicServer(CardSource source) throws FileNotFoundException { super(source); } // end empty constructor. /** * Creates a new <code>TcpMagicServer</code> that listens for connections * on the specified port, and uses the specified card source. * * @param port The port the server will listen at. * @param source The source used to generate cards. * * @throws FileNotFoundException if the file used to initialize the cards * is not found. */ public TcpMagicServer(int port, CardSource source) throws FileNotFoundException { super(port, source); } // end empty constructor. /** * Causes the magic server to listen for requests. * * @throws MagicServerException If an error occurs while trying to listen * for connections. */ public void listen() throws MagicServerException { String flags; try{ //Create the welcoming socket ServerSocket serverSock = new ServerSocket(this.getPort()); while(!serverSock.isClosed()) { // Create socket to accept client data Socket sock = serverSock.accept(); System.out.println("Accepted something"); // Create input streams InputStreamReader incomingStringReader = new InputStreamReader(sock.getInputStream()); BufferedReader buffer = new BufferedReader(incomingStringReader); // Get the flags the client sent flags = buffer.readLine(); System.out.println("Got flags."); this.setCardsReturned(flags); // Create output streams OutputStream outStream = sock.getOutputStream(); ObjectOutputStream objOutStream = new ObjectOutputStream(outStream); // Create and send back correct number of cards System.out.println("Started sending cards"); for(int i=0; i < this.getItemsToSend(); i++) { Card card = this.getSource().next(); objOutStream.writeObject(card); } System.out.println("Finished sending"); objOutStream.writeObject(null); buffer.close(); incomingStringReader.close(); objOutStream.close(); outStream.close(); // Close the socket that accepts client data sock.close(); } // end while loop // Close sockets serverSock.close(); } catch(IOException ioe) { throw new MagicServerException("I/O error, something went wrong.", ioe); } // end try-catch } // end listen method } // end TcpMagicServer class
package listaExercicios8; public abstract class Animal { //Atributos: private String nome; private int idade; private String emitirSom; //Construtores: public Animal(String nome, int idade) { super(); this.nome = nome; this.idade = idade; } //Getters and Setters: public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public int getIdade() { return idade; } public void setIdade(int idade) { this.idade = idade; } public String getEmitirSom() { return emitirSom; } public void setEmitirSom(String emitirSom) { this.emitirSom = emitirSom; } //Métodos: public void AnimalFaz() { System.out.println("Não sei que animal sou, logo não sei qual som emitir.\n"); } }
package web.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import web.dao.UserDAO; import web.model.User; import java.util.Optional; import java.util.logging.Logger; @Service public class UserDetailsServiceImpl implements UserDetailsService { private static Logger log = Logger.getLogger(UserDetailsServiceImpl.class.getName()); @Autowired private UserDAO userDao; public UserDetailsServiceImpl(UserDAO userDao) { this.userDao = userDao; } // «Пользователь» – это просто Object. В большинстве случаев он может быть // приведен к классу UserDetails. // Для создания UserDetails используется интерфейс UserDetailsService, с единственным методом: @Override public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException { Optional<User> user = userDao.findByName(name); log.info("Load user by name: " + user.get().getName()); if(user == null){ log.info("User not found!"); throw new UsernameNotFoundException("Username not found"); } return user.get(); } }
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final import java.math.BigDecimal; import java.util.Date; /** * IIoheader generated by hbm2java */ public class IIoheader implements java.io.Serializable { private String invioid; private Long iotype; private Long iostate; private String reasoncode; private String warehouseid; private String warehousemanager; private Date iodate; private String deptid; private String deptemp; private BigDecimal totalamount; private String invoiceid; private String creator; private Date createtime; private String partnerid; private String vouno; private String billchecker; private String notes; private String text1; private String text2; private String text3; private String text4; private String text5; private String text6; private String text7; private String text8; private String text9; private String text10; private String loader; private String relationid; private String lastModificator; private Date lastModifyTime; private String routing; private String partNumber; private BigDecimal producedQuantity; private String batchnum; private String sn; private String turnBoxId; private String currentBoxId; private String dutyemp; private String warning; private String tobinid; private String towarehouse; private String signer; private Date signdate; public IIoheader() { } public IIoheader(String invioid) { this.invioid = invioid; } public IIoheader(String invioid, Long iotype, Long iostate, String reasoncode, String warehouseid, String warehousemanager, Date iodate, String deptid, String deptemp, BigDecimal totalamount, String invoiceid, String creator, Date createtime, String partnerid, String vouno, String billchecker, String notes, String text1, String text2, String text3, String text4, String text5, String text6, String text7, String text8, String text9, String text10, String loader, String relationid, String lastModificator, Date lastModifyTime, String routing, String partNumber, BigDecimal producedQuantity, String batchnum, String sn, String turnBoxId, String currentBoxId, String dutyemp, String warning, String tobinid, String towarehouse, String signer, Date signdate) { this.invioid = invioid; this.iotype = iotype; this.iostate = iostate; this.reasoncode = reasoncode; this.warehouseid = warehouseid; this.warehousemanager = warehousemanager; this.iodate = iodate; this.deptid = deptid; this.deptemp = deptemp; this.totalamount = totalamount; this.invoiceid = invoiceid; this.creator = creator; this.createtime = createtime; this.partnerid = partnerid; this.vouno = vouno; this.billchecker = billchecker; this.notes = notes; this.text1 = text1; this.text2 = text2; this.text3 = text3; this.text4 = text4; this.text5 = text5; this.text6 = text6; this.text7 = text7; this.text8 = text8; this.text9 = text9; this.text10 = text10; this.loader = loader; this.relationid = relationid; this.lastModificator = lastModificator; this.lastModifyTime = lastModifyTime; this.routing = routing; this.partNumber = partNumber; this.producedQuantity = producedQuantity; this.batchnum = batchnum; this.sn = sn; this.turnBoxId = turnBoxId; this.currentBoxId = currentBoxId; this.dutyemp = dutyemp; this.warning = warning; this.tobinid = tobinid; this.towarehouse = towarehouse; this.signer = signer; this.signdate = signdate; } public String getInvioid() { return this.invioid; } public void setInvioid(String invioid) { this.invioid = invioid; } public Long getIotype() { return this.iotype; } public void setIotype(Long iotype) { this.iotype = iotype; } public Long getIostate() { return this.iostate; } public void setIostate(Long iostate) { this.iostate = iostate; } public String getReasoncode() { return this.reasoncode; } public void setReasoncode(String reasoncode) { this.reasoncode = reasoncode; } public String getWarehouseid() { return this.warehouseid; } public void setWarehouseid(String warehouseid) { this.warehouseid = warehouseid; } public String getWarehousemanager() { return this.warehousemanager; } public void setWarehousemanager(String warehousemanager) { this.warehousemanager = warehousemanager; } public Date getIodate() { return this.iodate; } public void setIodate(Date iodate) { this.iodate = iodate; } public String getDeptid() { return this.deptid; } public void setDeptid(String deptid) { this.deptid = deptid; } public String getDeptemp() { return this.deptemp; } public void setDeptemp(String deptemp) { this.deptemp = deptemp; } public BigDecimal getTotalamount() { return this.totalamount; } public void setTotalamount(BigDecimal totalamount) { this.totalamount = totalamount; } public String getInvoiceid() { return this.invoiceid; } public void setInvoiceid(String invoiceid) { this.invoiceid = invoiceid; } public String getCreator() { return this.creator; } public void setCreator(String creator) { this.creator = creator; } public Date getCreatetime() { return this.createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } public String getPartnerid() { return this.partnerid; } public void setPartnerid(String partnerid) { this.partnerid = partnerid; } public String getVouno() { return this.vouno; } public void setVouno(String vouno) { this.vouno = vouno; } public String getBillchecker() { return this.billchecker; } public void setBillchecker(String billchecker) { this.billchecker = billchecker; } public String getNotes() { return this.notes; } public void setNotes(String notes) { this.notes = notes; } public String getText1() { return this.text1; } public void setText1(String text1) { this.text1 = text1; } public String getText2() { return this.text2; } public void setText2(String text2) { this.text2 = text2; } public String getText3() { return this.text3; } public void setText3(String text3) { this.text3 = text3; } public String getText4() { return this.text4; } public void setText4(String text4) { this.text4 = text4; } public String getText5() { return this.text5; } public void setText5(String text5) { this.text5 = text5; } public String getText6() { return this.text6; } public void setText6(String text6) { this.text6 = text6; } public String getText7() { return this.text7; } public void setText7(String text7) { this.text7 = text7; } public String getText8() { return this.text8; } public void setText8(String text8) { this.text8 = text8; } public String getText9() { return this.text9; } public void setText9(String text9) { this.text9 = text9; } public String getText10() { return this.text10; } public void setText10(String text10) { this.text10 = text10; } public String getLoader() { return this.loader; } public void setLoader(String loader) { this.loader = loader; } public String getRelationid() { return this.relationid; } public void setRelationid(String relationid) { this.relationid = relationid; } public String getLastModificator() { return this.lastModificator; } public void setLastModificator(String lastModificator) { this.lastModificator = lastModificator; } public Date getLastModifyTime() { return this.lastModifyTime; } public void setLastModifyTime(Date lastModifyTime) { this.lastModifyTime = lastModifyTime; } public String getRouting() { return this.routing; } public void setRouting(String routing) { this.routing = routing; } public String getPartNumber() { return this.partNumber; } public void setPartNumber(String partNumber) { this.partNumber = partNumber; } public BigDecimal getProducedQuantity() { return this.producedQuantity; } public void setProducedQuantity(BigDecimal producedQuantity) { this.producedQuantity = producedQuantity; } public String getBatchnum() { return this.batchnum; } public void setBatchnum(String batchnum) { this.batchnum = batchnum; } public String getSn() { return this.sn; } public void setSn(String sn) { this.sn = sn; } public String getTurnBoxId() { return this.turnBoxId; } public void setTurnBoxId(String turnBoxId) { this.turnBoxId = turnBoxId; } public String getCurrentBoxId() { return this.currentBoxId; } public void setCurrentBoxId(String currentBoxId) { this.currentBoxId = currentBoxId; } public String getDutyemp() { return this.dutyemp; } public void setDutyemp(String dutyemp) { this.dutyemp = dutyemp; } public String getWarning() { return this.warning; } public void setWarning(String warning) { this.warning = warning; } public String getTobinid() { return this.tobinid; } public void setTobinid(String tobinid) { this.tobinid = tobinid; } public String getTowarehouse() { return this.towarehouse; } public void setTowarehouse(String towarehouse) { this.towarehouse = towarehouse; } public String getSigner() { return this.signer; } public void setSigner(String signer) { this.signer = signer; } public Date getSigndate() { return this.signdate; } public void setSigndate(Date signdate) { this.signdate = signdate; } }
package com.yinghai.a24divine_user.module.divine.selecttime; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import android.widget.RadioButton; import android.widget.TextView; import com.example.fansonlib.utils.ShowToast; import com.example.fansonlib.widget.dialogfragment.base.BaseDialogFragment; import com.example.fansonlib.widget.dialogfragment.base.ViewHolder; import com.yinghai.a24divine_user.R; /** * @author Created by:fanson * Created Time: 2017/11/1 13:30 * Describe:确认预约时间(上/下午) */ public class ConfirmTimeDialog extends BaseDialogFragment { private RadioButton mRbMorning; private RadioButton mRbAfternoon; private TextView mTvMorningTime; // 上午可预约时间 private TextView mTvMorningNum; // 上午可预约人数 private TextView mTvMorningHasNum; // 上午已预约人数 private TextView mTvAfterTime; // 下午可预约时间 private TextView mTvAfterNum; // 下午可预约人数 private TextView mTvAfterHasNum; // 下午已预约人数 private IChooseTimeListener mListener; //后台所需的时间段,上午/下午 private static final String MORMING_TIME = "10:00"; private static final String AFTER_TIME = "14:00"; public void setIChooseTimeListener(IChooseTimeListener listener) { mListener = listener; } @Override public int intLayoutId() { return R.layout.dialog_confirm_time; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setOutCancel(true); this.setMargin(20); } @Override public void onStart() { super.onStart(); } @Override public void convertView(ViewHolder holder, final BaseDialogFragment dialog) { mRbMorning = holder.getView(R.id.rb_morning); mRbAfternoon = holder.getView(R.id.rb_aftermoon); holder.setText(R.id.tv_morning_time, "8:00-14:00"); holder.setText(R.id.tv_aftermoon_time, "15:00-18:00"); holder.setText(R.id.tv_morning_num, String.format(getString(R.string.appointment_num), 10)); holder.setText(R.id.tv_aftermoon_num, String.format(getString(R.string.appointment_num), 10)); // holder.setText(R.id.tv_morning_has_people, String.format(getString(R.string.has_appointment_num),8)); // holder.setText(R.id.tv_aftermoon_has_people, String.format(getString(R.string.has_appointment_num),8)); holder.setOnClickListener(R.id.rl_morning, new View.OnClickListener() { @Override public void onClick(View v) { mRbMorning.setChecked(true); mRbAfternoon.setChecked(false); } }); holder.setOnClickListener(R.id.rl_aftermoon, new View.OnClickListener() { @Override public void onClick(View v) { mRbMorning.setChecked(false); mRbAfternoon.setChecked(true); } }); holder.setOnClickListener(R.id.btn_confirm, new View.OnClickListener() { @Override public void onClick(View view) { if (mListener != null) { if (mRbMorning.isChecked()) { mListener.chooseTime(MORMING_TIME); dialog.dismiss(); } else if (mRbAfternoon.isChecked()) { mListener.chooseTime(AFTER_TIME); dialog.dismiss(); } else { ShowToast.singleShort(getString(R.string.please_choose_time)); } } } }); } public interface IChooseTimeListener { /** * 选择上下午时间段 * * @param time 10:00 or 14:00 */ void chooseTime(String time); } }
package com.example.serviceplease.views.details; import android.content.Intent; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.view.ViewCompat; import com.example.serviceplease.R; import com.example.serviceplease.helpers.Utils; import com.example.serviceplease.model.foodModel.FoodList; import com.google.android.material.appbar.AppBarLayout; import com.google.android.material.appbar.CollapsingToolbarLayout; import com.squareup.picasso.Picasso; import butterknife.BindView; import butterknife.ButterKnife; import static com.example.serviceplease.views.home.HomeActivity.EXTRA_DETAIL; public class DetailsActivity extends AppCompatActivity implements DetailsView { @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.appbar) AppBarLayout appbar; @BindView(R.id.collapse_toolbar) CollapsingToolbarLayout collapse_toolbar; @BindView(R.id.itemThumb) ImageView itemThumb; @BindView(R.id.categoryLoading) TextView categoryLoading; @BindView(R.id.countryLoading) TextView countryLoading; @BindView(R.id.instructions) TextView instructions; @BindView(R.id.ingredient) TextView ingredient; @BindView(R.id.measurements) TextView measurements; @BindView(R.id.progressBar) ProgressBar progressBar; @BindView(R.id.youtube) TextView youtube; @BindView(R.id.source) TextView source; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details); ButterKnife.bind(this); setupActionBar(); Intent intent = getIntent(); String itemName = intent.getStringExtra(EXTRA_DETAIL); DetailsPresenter presenter = new DetailsPresenter(this); presenter.getMealById(itemName); } private void setupActionBar() { setSupportActionBar(toolbar); collapse_toolbar.setContentScrimColor(getResources().getColor(R.color.colorTextPrimary)); collapse_toolbar.setCollapsedTitleTextColor(getResources().getColor(R.color.colorPrimary)); collapse_toolbar.setExpandedTitleColor(getResources().getColor(R.color.colorTextPrimary)); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_detail, menu); MenuItem favouriteItem = menu.findItem(R.id.favourite); Drawable favouriteItemColor = favouriteItem.getIcon(); setupColorActionBarIcon(favouriteItemColor); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } private void setupColorActionBarIcon(Drawable favouriteItemColor) { appbar.addOnOffsetChangedListener((appbar, verticalOffset) -> { if ((collapse_toolbar.getHeight() + verticalOffset) < (2 * ViewCompat .getMinimumHeight(collapse_toolbar))) { if (toolbar.getNavigationIcon() != null) { toolbar.getNavigationIcon().setColorFilter(getResources() .getColor(R.color.colorAccent), PorterDuff.Mode.SRC_ATOP); favouriteItemColor.mutate().setColorFilter(getResources() .getColor(R.color.colorAccent), PorterDuff.Mode.SRC_ATOP); } } else { if (toolbar.getNavigationIcon() != null) { toolbar.getNavigationIcon().setColorFilter(getResources() .getColor(R.color.colorTextPrimary), PorterDuff.Mode.SRC_ATOP); favouriteItemColor.mutate().setColorFilter(getResources() .getColor(R.color.colorTextPrimary), PorterDuff.Mode.SRC_ATOP); } } }); } @Override public void showLoading() { progressBar.setVisibility(View.VISIBLE); } @Override public void hideLoading() { progressBar.setVisibility(View.INVISIBLE); } @Override public void setMeals(FoodList.Meal meals) { // Log.w("TAG", meals.getStrMeal()); Picasso.get().load(meals.getStrMealThumb()).into(itemThumb); collapse_toolbar.setTitle(meals.getStrMeal()); categoryLoading.setText(meals.getStrCategory()); countryLoading.setText(meals.getStrArea()); instructions.setText(meals.getStrInstructions()); setupActionBar(); // TODO: Check for empty fields in API json (YOUTUBE & SRC) youtube.setOnClickListener(view -> { Intent intentYoutube = new Intent(Intent.ACTION_VIEW); intentYoutube.setData(Uri.parse(meals.getStrYoutube())); startActivity(intentYoutube); }); source.setOnClickListener(v -> { Intent intentSource = new Intent(Intent.ACTION_VIEW); intentSource.setData(Uri.parse(meals.getStrSource())); startActivity(intentSource); }); // TODO: Check for empty fields in API json (INGREDIENTS) if (!meals.getStrIngredient1().isEmpty()) { ingredient.append("\n \u2022 " + meals.getStrIngredient1()); } if (!meals.getStrIngredient2().isEmpty()) { ingredient.append("\n \u2022 " + meals.getStrIngredient2()); } if (!meals.getStrIngredient3().isEmpty()) { ingredient.append("\n \u2022 " + meals.getStrIngredient3()); } if (!meals.getStrIngredient4().isEmpty()) { ingredient.append("\n \u2022 " + meals.getStrIngredient4()); } if (!meals.getStrIngredient5().isEmpty()) { ingredient.append("\n \u2022 " + meals.getStrIngredient5()); } if (!meals.getStrIngredient6().isEmpty()) { ingredient.append("\n \u2022 " + meals.getStrIngredient6()); } if (!meals.getStrIngredient7().isEmpty()) { ingredient.append("\n \u2022 " + meals.getStrIngredient7()); } if (!meals.getStrIngredient8().isEmpty()) { ingredient.append("\n \u2022 " + meals.getStrIngredient8()); } if (!meals.getStrIngredient9().isEmpty()) { ingredient.append("\n \u2022 " + meals.getStrIngredient9()); } if (!meals.getStrIngredient10().isEmpty()) { ingredient.append("\n \u2022 " + meals.getStrIngredient10()); } if (!meals.getStrIngredient11().isEmpty()) { ingredient.append("\n \u2022 " + meals.getStrIngredient11()); } if (!meals.getStrIngredient12().isEmpty()) { ingredient.append("\n \u2022 " + meals.getStrIngredient12()); } if (!meals.getStrIngredient13().isEmpty()) { ingredient.append("\n \u2022 " + meals.getStrIngredient13()); } if (!meals.getStrIngredient14().isEmpty()) { ingredient.append("\n \u2022 " + meals.getStrIngredient14()); } if (!meals.getStrIngredient15().isEmpty()) { ingredient.append("\n \u2022 " + meals.getStrIngredient15()); } if (!meals.getStrIngredient16().isEmpty()) { ingredient.append("\n \u2022 " + meals.getStrIngredient16()); } if (!meals.getStrIngredient17().isEmpty()) { ingredient.append("\n \u2022 " + meals.getStrIngredient17()); } if (!meals.getStrIngredient18().isEmpty()) { ingredient.append("\n \u2022 " + meals.getStrIngredient18()); } if (!meals.getStrIngredient19().isEmpty()) { ingredient.append("\n \u2022 " + meals.getStrIngredient19()); } if (!meals.getStrIngredient20().isEmpty()) { ingredient.append("\n \u2022 " + meals.getStrIngredient20()); } // TODO: Check for empty fields in API json (INGREDIENTS) if (!meals.getStrMeasure1().isEmpty() && !Character.isWhitespace(meals.getStrMeasure1().charAt(0))) { measurements.append("\n : " + meals.getStrMeasure1()); } if (!meals.getStrMeasure2().isEmpty() && !Character.isWhitespace(meals.getStrMeasure2().charAt(0))) { measurements.append("\n : " + meals.getStrMeasure2()); } if (!meals.getStrMeasure3().isEmpty() && !Character.isWhitespace(meals.getStrMeasure3().charAt(0))) { measurements.append("\n : " + meals.getStrMeasure3()); } if (!meals.getStrMeasure4().isEmpty() && !Character.isWhitespace(meals.getStrMeasure4().charAt(0))) { measurements.append("\n : " + meals.getStrMeasure4()); } if (!meals.getStrMeasure5().isEmpty() && !Character.isWhitespace(meals.getStrMeasure5().charAt(0))) { measurements.append("\n : " + meals.getStrMeasure5()); } if (!meals.getStrMeasure6().isEmpty() && !Character.isWhitespace(meals.getStrMeasure6().charAt(0))) { measurements.append("\n : " + meals.getStrMeasure6()); } if (!meals.getStrMeasure7().isEmpty() && !Character.isWhitespace(meals.getStrMeasure7().charAt(0))) { measurements.append("\n : " + meals.getStrMeasure7()); } if (!meals.getStrMeasure8().isEmpty() && !Character.isWhitespace(meals.getStrMeasure8().charAt(0))) { measurements.append("\n : " + meals.getStrMeasure8()); } if (!meals.getStrMeasure9().isEmpty() && !Character.isWhitespace(meals.getStrMeasure9().charAt(0))) { measurements.append("\n : " + meals.getStrMeasure9()); } if (!meals.getStrMeasure10().isEmpty() && !Character.isWhitespace(meals.getStrMeasure10().charAt(0))) { measurements.append("\n : " + meals.getStrMeasure10()); } if (!meals.getStrMeasure11().isEmpty() && !Character.isWhitespace(meals.getStrMeasure11().charAt(0))) { measurements.append("\n : " + meals.getStrMeasure11()); } if (!meals.getStrMeasure12().isEmpty() && !Character.isWhitespace(meals.getStrMeasure12().charAt(0))) { measurements.append("\n : " + meals.getStrMeasure12()); } if (!meals.getStrMeasure13().isEmpty() && !Character.isWhitespace(meals.getStrMeasure13().charAt(0))) { measurements.append("\n : " + meals.getStrMeasure13()); } if (!meals.getStrMeasure14().isEmpty() && !Character.isWhitespace(meals.getStrMeasure14().charAt(0))) { measurements.append("\n : " + meals.getStrMeasure14()); } if (!meals.getStrMeasure15().isEmpty() && !Character.isWhitespace(meals.getStrMeasure15().charAt(0))) { measurements.append("\n : " + meals.getStrMeasure15()); } if (!meals.getStrMeasure16().isEmpty() && !Character.isWhitespace(meals.getStrMeasure16().charAt(0))) { measurements.append("\n : " + meals.getStrMeasure16()); } if (!meals.getStrMeasure17().isEmpty() && !Character.isWhitespace(meals.getStrMeasure17().charAt(0))) { measurements.append("\n : " + meals.getStrMeasure17()); } if (!meals.getStrMeasure18().isEmpty() && !Character.isWhitespace(meals.getStrMeasure18().charAt(0))) { measurements.append("\n : " + meals.getStrMeasure18()); } if (!meals.getStrMeasure19().isEmpty() && !Character.isWhitespace(meals.getStrMeasure19().charAt(0))) { measurements.append("\n : " + meals.getStrMeasure19()); } if (!meals.getStrMeasure20().isEmpty() && !Character.isWhitespace(meals.getStrMeasure20().charAt(0))) { measurements.append("\n : " + meals.getStrMeasure20()); } } @Override public void onErrorLoading(String message) { Utils.showDialogMessage(this, "Error", message); } }
package com.jovin.services; import com.jovin.dao.UserDao; import com.jovin.models.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Map; /** * Created by jovin on 14/2/16. */ @Service("userService") @Transactional public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; public UserServiceImpl(){ System.out.println("Reached user service impl"); } public void add(User user) throws Exception { userDao.add(user); } public User getUserByEmail(String email) throws Exception { return userDao.getUserByEmail(email); } public User getUserByName(String name) throws Exception { return userDao.getUserByName(name); } @Override public List<User> managerList() throws Exception { return userDao.managerList(); } @Override public List<User> projectUserDropdownList() throws Exception { return userDao.projectUserDropdownList(); } @Override public User getUserById(Integer userId) throws Exception { return userDao.getUserById(userId); } public void update(User user) throws Exception { userDao.update(user); } public List<User> userList() throws Exception { return userDao.userList(); } }
package LabExercises; public class CastingExercise { public static void main(String[] args) { byte b=10; int i=b; //Automatic type promotion. byte c=i; //Lower datatype cannot be put into higher. byte d=(byte)i; //Type casting enables us to atore compatible types. byte x=10, byte y=20; byte sum=x*y; // Error is thrown because when two bytes are used in an //arithmetic operation, the result will be integer } }
package hu.bme.aut.exhibitionexplorer; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.View; import hu.bme.aut.exhibitionexplorer.data.Artifact; import hu.bme.aut.exhibitionexplorer.fragment.ArtifactDetailFragment; import hu.bme.aut.exhibitionexplorer.interfaces.OnFavoriteListener; public class ArtifactActivity extends AppCompatActivity implements OnFavoriteListener { Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_artifact); Artifact artifact = getIntent().getParcelableExtra(Artifact.KEY_ARTIFACT_PARCELABLE); Bundle bundleArtifact = new Bundle(); bundleArtifact.putParcelable(Artifact.KEY_ARTIFACT_PARCELABLE, artifact); Fragment artifactDetailFragment = new ArtifactDetailFragment(); artifactDetailFragment.setArguments(bundleArtifact); showFragmentWithNoBackStack(artifactDetailFragment, ArtifactDetailFragment.TAG); toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); } private void showFragmentWithNoBackStack(Fragment fragment, String tag) { FragmentTransaction localFragmentTransaction = getSupportFragmentManager().beginTransaction(); localFragmentTransaction.replace(R.id.fragment_container, fragment, tag) .commit(); } @Override public void ArtifactToFavorite(Artifact artifact) { artifact.save(); } @Override public void ArtifactRemovedFromFavorite(Artifact artifact) { artifact.delete(); } }
/* 1: */ package org.linphone.core.tutorials; /* 2: */ /* 3: */ /* 4: */ /* 5: */ public class TutorialNotifier /* 6: */ { /* 7: */ public void notify(String s) /* 8: */ { /* 9:31 */ System.out.println(s); /* 10: */ } /* 11: */ } /* Location: E:\DO-AN\Libraries\linphone-android-sdk-2.4.0\libs\LinLinphone\linphone.jar * Qualified Name: org.linphone.core.tutorials.TutorialNotifier * JD-Core Version: 0.7.0.1 */
package ch.examples.service; import org.springframework.stereotype.Service; import ch.springcloud.lite.core.anno.Remote; import ch.springcloud.lite.core.anno.Stub; @Service @Stub public class StubService implements NewService { @Remote NewService newService2; @Override public Result call(int i) { System.out.println("STUB !"); return newService2.call(2); } }
package com.udacity.popularmovies.shared; import android.content.Context; import android.view.animation.AnimationUtils; import android.view.animation.LayoutAnimationController; import java.util.Objects; import androidx.recyclerview.widget.RecyclerView; /** * Created by JesseFariasdeLima on 4/10/2019. * This is a part of the project adnd-popular-movies. */ public final class RecyclerViewAnimator { public static void runLayoutAnimation(final RecyclerView recyclerView, int animationResourceId ) { final Context context = recyclerView.getContext(); final LayoutAnimationController controller = AnimationUtils.loadLayoutAnimation(context, animationResourceId); recyclerView.setLayoutAnimation(controller); Objects.requireNonNull(recyclerView.getAdapter()).notifyDataSetChanged(); recyclerView.scheduleLayoutAnimation(); } }
package com.goldgov.dygl.module.partymemberrated.evaluation.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.goldgov.dygl.module.partymemberrated.evaluation.domain.EvaluationClassification; import com.goldgov.dygl.module.partymemberrated.evaluation.service.EvaluationIndexQuery; import com.goldgov.gtiles.core.dao.mybatis.annotation.MybatisRepository; @MybatisRepository("evaluationClassificationDao") public interface IEvaluationClassificationDao { public void addInfo(EvaluationClassification classification); public void updateInfo(EvaluationClassification classification); public void deleteInfo(@Param("ids") String[] entityIDs); public EvaluationClassification findInfoById(@Param("id") String entityID); public List<EvaluationClassification> findInfoListByPage(@Param("query") EvaluationIndexQuery query); }
package ru.molkov.dao; import java.util.List; import ru.molkov.core.GenericDao; import ru.molkov.model.Disc; public interface DiscDao extends GenericDao<Disc> { List<Disc> getDiscsByUser(Integer userId); }
package edu.authentcate.api.security; import lombok.extern.slf4j.Slf4j; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; @Slf4j public class AppAuthenticationProvider implements AuthenticationProvider { private AppAuthenticationService authenticationService; public AppAuthenticationProvider(AppAuthenticationService authenticationService) { this.authenticationService = authenticationService; } @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!this.supports(authentication.getClass())) { log.error("Not Supported for : {}", authentication.getClass()); return null; } log.info("Hello AuthenticationProvider ... "); return this.authenticationService.authenticate(authentication); } @Override public boolean supports(Class<?> authentication) { return authentication.equals(AppAuthenticationToken.class); } }
package api.longpoll.bots.model.response; import api.longpoll.bots.model.objects.additional.VkList; import api.longpoll.bots.model.objects.basic.Community; import api.longpoll.bots.model.objects.basic.User; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Describes Vk list with "profiles" and "groups" additional fields. * * @param <T> type of items. */ public class ExtendedVkList<T> extends VkList<T> { /** * List of users. */ @SerializedName("profiles") private List<User> profiles; /** * List of communities. */ @SerializedName("groups") private List<Community> groups; public List<User> getProfiles() { return profiles; } public void setProfiles(List<User> profiles) { this.profiles = profiles; } public List<Community> getGroups() { return groups; } public void setGroups(List<Community> groups) { this.groups = groups; } @Override public String toString() { return "ExtendedVkList{" + "profiles=" + profiles + ", groups=" + groups + "} " + super.toString(); } }
package com.commercetools.pspadapter.payone.notification; import com.commercetools.pspadapter.payone.domain.payone.model.common.Notification; import com.commercetools.pspadapter.payone.domain.payone.model.common.NotificationAction; import io.sphere.sdk.client.ConcurrentModificationException; import io.sphere.sdk.commands.UpdateAction; import io.sphere.sdk.payments.Payment; import io.sphere.sdk.payments.Transaction; import io.sphere.sdk.payments.commands.updateactions.SetCustomer; import org.assertj.core.api.JUnitSoftAssertions; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; /** * @author Jan Wolter */ @RunWith(MockitoJUnitRunner.class) public class NotificationProcessorBaseTest extends BaseNotificationProcessorTest { @Rule public JUnitSoftAssertions softly = new JUnitSoftAssertions(); @Mock private Payment payment; @Override @Before public void setUp() throws Exception { super.setUp(); } @Test public void rethrowsSphereSdkConcurrentModificationExceptionWrappedInJavaUtilConcurrentModificationException() { // arrange final NotificationAction txAction = randomTxAction(); final Notification notification = new Notification(); notification.setTxaction(txAction); final List<UpdateAction<Payment>> updateActions = Arrays.asList(SetCustomer.of(null)); final NotificationProcessorBase testee = new NotificationProcessorBase(tenantFactory, tenantConfig, transactionStateResolver) { @Override protected boolean canProcess(final Notification notification) { return true; } @Override protected List<UpdateAction<Payment>> createPaymentUpdates(final Payment aPayment, final Notification aNotification) { return (payment == aPayment) && (notification == aNotification) ? updateActions : Collections.emptyList(); } }; final ConcurrentModificationException sdkException = new ConcurrentModificationException(); when(paymentService.updatePayment(any(), any())).thenThrow(sdkException); // act final Throwable throwable = catchThrowable(() -> testee.processTransactionStatusNotification(notification, payment)); // assert verify(paymentService).updatePayment(paymentRequestPayment.capture(), paymentRequestUpdatesCaptor.capture()); // order service methods should not be called // because tenantConfig.isUpdateOrderPaymentState() expected to be "false" by default verifyUpdateOrderActionsNotCalled(); softly.assertThat(paymentRequestPayment.getValue()).isEqualTo(payment); softly.assertThat(paymentRequestUpdatesCaptor.getValue()).as("update action instance") .isSameAs(updateActions); softly.assertThat(throwable).as("exception") .isInstanceOf(java.util.ConcurrentModificationException.class) .hasCause(sdkException); } @Test public void isNotCompletedTransaction_callsInjectedStateResolver() throws Exception { final NotificationProcessorBase testee = new NotificationProcessorBase(tenantFactory, tenantConfig, transactionStateResolver){ @Override protected boolean canProcess(Notification notification) { return true; } }; doReturn(true).when(transactionStateResolver).isNotCompletedTransaction(any()); assertThat(testee.isNotCompletedTransaction(mock(Transaction.class))).isTrue(); doReturn(false).when(transactionStateResolver).isNotCompletedTransaction(any()); assertThat(testee.isNotCompletedTransaction(mock(Transaction.class))).isFalse(); } private static NotificationAction randomTxAction() { final List<NotificationAction> txActions = Arrays.asList(NotificationAction.values()); Collections.shuffle(txActions); return txActions.get(0); } }
import java.io.*; public class Reader implements Runnable { RWMonitor rwMonitor; int readIntervalInSecs; public Reader(RWMonitor rwMonitor, int readIntervalInSecs) { this.rwMonitor = rwMonitor; this.readIntervalInSecs = readIntervalInSecs; } @Override public void run() { while (true) { try { /*ENTRY*/ rwMonitor.readTry.acquire(); rwMonitor.readMutex.acquire(); rwMonitor.readCount++; if (rwMonitor.readCount == 1) { rwMonitor.resourceMutex.acquire(); } rwMonitor.readMutex.release(); rwMonitor.readTry.release(); /*CS*/ read(); /*EXIT*/ rwMonitor.readMutex.acquire(); rwMonitor.readCount--; if (rwMonitor.readCount == 0) { rwMonitor.resourceMutex.release(); } rwMonitor.readMutex.release(); Thread.sleep(readIntervalInSecs * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } } public void read() { System.out.println("Reading from reader on Thread ID: " + Thread.currentThread().getId()); try { BufferedReader bufferedReader = new BufferedReader( new FileReader(rwMonitor.sharedFile) ); StringBuilder out = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { out.append(line); } System.out.printf("\nRead output: %s\n%n", out.toString()); bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } }
package com.tencent.mm.plugin.emoji.ui; import com.tencent.mm.sdk.e.j.a; import com.tencent.mm.sdk.e.l; import com.tencent.mm.sdk.platformtools.bi; class EmojiCustomUI$13 implements a { final /* synthetic */ EmojiCustomUI ilG; EmojiCustomUI$13(EmojiCustomUI emojiCustomUI) { this.ilG = emojiCustomUI; } public final void a(String str, l lVar) { if (!bi.oW(str)) { if ((str.length() == 32 || str.equals("event_update_emoji")) && EmojiCustomUI.e(this.ilG) != null) { EmojiCustomUI.e(this.ilG).aFM(); EmojiCustomUI.e(this.ilG).notifyDataSetChanged(); } } } }
package com.konka.downloadcenter.manager; import com.konka.downloadcenter.database.TasksManagerDBController; import com.konka.downloadcenter.domain.TaskManagerModel; import com.liulishuo.filedownloader.FileDownloadConnectListener; import com.liulishuo.filedownloader.FileDownloader; import java.lang.ref.WeakReference; import java.util.List; /** * Created by xiaowu on 2016-5-20. */ public class TaskManager { private final static class HolderClass { private final static TaskManager INSTANCE = new TaskManager(); } public static TaskManager getImpl() { return HolderClass.INSTANCE; } private List<TaskManagerModel> mTaskList; private TasksManagerDBController mController; private FileDownloadConnectListener listener; public TaskManager() { mController=new TasksManagerDBController(); initData(); mTaskList=mController.getAllTasks(); } public int getTaskCount() { return mTaskList.size(); } public TaskManagerModel get(int position) { return mTaskList.get(position); } public boolean isReady() { return FileDownloader.getImpl().isServiceConnected(); } public int getStatus(final int id) { return FileDownloader.getImpl().getStatus(id); } public int getSoFar(final int id) { return (int) FileDownloader.getImpl().getSoFar(id); } public int getTotal(final int id) { return (int) FileDownloader.getImpl().getTotal(id); } public boolean deleteTask(final int id,final int position) { boolean success=mController.deleteTask(id); if (success) { mTaskList.remove(position); } return success; } public void onCreate(final WeakReference<MainActivity> activityWeakReference) { FileDownloader.getImpl().bindService(); if (listener != null) { FileDownloader.getImpl().removeServiceConnectListener(listener); } listener = new FileDownloadConnectListener() { @Override public void connected() { if (activityWeakReference == null || activityWeakReference.get() == null) { return; } activityWeakReference.get().postNotifyDataChanged(); } @Override public void disconnected() { if (activityWeakReference == null || activityWeakReference.get() == null) { return; } activityWeakReference.get().postNotifyDataChanged(); } }; FileDownloader.getImpl().addServiceConnectListener(listener); } public void initData() { mController.addTask("http://download.chinaunix.net/down.php?id=10608&ResourceID=5267&site=1","data/data/filedownfiles/test1","test1"); mController.addTask("http://180.153.105.144/dd.myapp.com/16891/E2F3DEBB12A049ED921C6257C5E9FB11.apk","data/data/filedownfiles/test2","test1"); mController.addTask("http://7xjww9.com1.z0.glb.clouddn.com/Hopetoun_falls.jpg","data/data/filedownfiles/test3","test1"); } }
package com.example.bottomnavi; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.charts.Chart; import com.github.mikephil.charting.components.Description; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.PieData; import com.github.mikephil.charting.data.PieEntry; import java.util.ArrayList; public class showBarChartActivity extends AppCompatActivity { BarChart barChart; int[] colorArray = new int[]{Color.LTGRAY,Color.BLUE,Color.RED,Color.CYAN,Color.YELLOW}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_bar_chart); barChart = findViewById(R.id.barchart); BarDataSet barDataSet = new BarDataSet(data1(),"중식"); BarDataSet barDataSet1 = new BarDataSet(data2(),"fast"); BarDataSet barDataSet2 = new BarDataSet(data3(),"일식"); BarDataSet barDataSet3 = new BarDataSet(data4(),"한식"); BarDataSet barDataSet4 = new BarDataSet(data5(),"양식"); barDataSet.setColors(Color.LTGRAY); barDataSet1.setColors(Color.BLUE); barDataSet2.setColors(Color.RED); barDataSet3.setColors(Color.CYAN); barDataSet4.setColors(Color.YELLOW); BarData barData = new BarData(); barData.addDataSet(barDataSet); barData.addDataSet(barDataSet1); barData.addDataSet(barDataSet2); barData.addDataSet(barDataSet3); barData.addDataSet(barDataSet4); //barChart description setting Description description = new Description(); description.setText("먹은 비율"); description.setTextSize(15); barChart.setDescription(description); barChart.setData(barData); barChart.invalidate(); } //차트에 넣을 데이터 private ArrayList<BarEntry>data1(){ ArrayList<BarEntry>datavalue = new ArrayList<>(); Intent intent = getIntent(); int china = Integer.valueOf(getIntent().getStringExtra("china")); datavalue.add(new BarEntry(0,china)); return datavalue; } private ArrayList<BarEntry>data2(){ ArrayList<BarEntry>datavalue = new ArrayList<>(); Intent intent = getIntent(); int fast = Integer.valueOf(getIntent().getStringExtra("fast")); datavalue.add(new BarEntry(1,fast)); return datavalue; } private ArrayList<BarEntry>data3(){ ArrayList<BarEntry>datavalue = new ArrayList<>(); Intent intent = getIntent(); int japan = Integer.valueOf(getIntent().getStringExtra("japan")); datavalue.add(new BarEntry(2,japan)); return datavalue; } private ArrayList<BarEntry>data4(){ ArrayList<BarEntry>datavalue = new ArrayList<>(); Intent intent = getIntent(); int korea = Integer.valueOf(getIntent().getStringExtra("korea")); datavalue.add(new BarEntry(3,korea)); return datavalue; } private ArrayList<BarEntry>data5(){ ArrayList<BarEntry>datavalue = new ArrayList<>(); Intent intent = getIntent(); int usa = Integer.valueOf(getIntent().getStringExtra("usa")); datavalue.add(new BarEntry(4,usa)); return datavalue; } }
package cn.canlnac.onlinecourse.presentation.presenter; import android.support.annotation.NonNull; import javax.inject.Inject; import cn.canlnac.onlinecourse.data.exception.ResponseStatusException; import cn.canlnac.onlinecourse.domain.interactor.DefaultSubscriber; import cn.canlnac.onlinecourse.domain.interactor.UseCase; import cn.canlnac.onlinecourse.presentation.internal.di.PerActivity; import cn.canlnac.onlinecourse.presentation.model.DocumentModel; import cn.canlnac.onlinecourse.presentation.ui.activity.RegisterActivity; @PerActivity public class GetDocumentPresenter implements Presenter { RegisterActivity getDocumentActivity; private final UseCase getDocumentUseCase; @Inject public GetDocumentPresenter(UseCase getDocumentUseCase) { this.getDocumentUseCase = getDocumentUseCase; } public void setView(@NonNull RegisterActivity getDocumentActivity) { this.getDocumentActivity = getDocumentActivity; } public void initialize() { this.getDocumentUseCase.execute(new GetDocumentPresenter.GetDocumentSubscriber()); } @Override public void resume() { } @Override public void pause() { } @Override public void destroy() { this.getDocumentUseCase.unsubscribe(); } private final class GetDocumentSubscriber extends DefaultSubscriber<DocumentModel> { @Override public void onCompleted() { } @Override public void onError(Throwable e) { if (e instanceof ResponseStatusException) { switch (((ResponseStatusException)e).code) { case 400: GetDocumentPresenter.this.getDocumentActivity.showToastMessage("参数错误!"); break; case 404: GetDocumentPresenter.this.getDocumentActivity.showToastMessage("资源不存在!"); break; case 409: GetDocumentPresenter.this.getDocumentActivity.showToastMessage("用户名已被注册!"); break; default: GetDocumentPresenter.this.getDocumentActivity.showToastMessage("服务器错误:"+((ResponseStatusException)e).code); } } else { GetDocumentPresenter.this.getDocumentActivity.showToastMessage("网络连接错误!"); } } @Override public void onNext(DocumentModel documentModel) { GetDocumentPresenter.this.getDocumentActivity.showToastMessage("创建成功"); } } }
package Classes; import java.util.Comparator; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; public class Cinema implements Comparator<Days>{ private TreeMap<Days, Schedule> map; private Time open; private Time close; public Cinema(Time open, Time close) { // treemap will sort elements by days this.map =new TreeMap<Days,Schedule>(/*new ComparatorDescend()*/); try{ //check if open&close time is correct if (open.correctTime()&&close.correctTime()){ this.open=open; this.close=close; } else { throw new InvalidFormatTime(); } } catch(InvalidFormatTime e){ e.getMessage(); System.exit(0); } } // this function delete all movies from all seances public void removeMovie(){ System.out.println("Input name of the movie which you want to remove"); Scanner sc = new Scanner (System.in); String s = sc.nextLine(); // get access to values of map by keys for (final Map.Entry<Days, Schedule> entry : map.entrySet()) { //get access to set of Seances for (Seance seance : entry.getValue().getSet()) { // check if name of movie is equal to our inputed value if (seance.getMovie().getTitle().equalsIgnoreCase(s)){ // if true delete such movie entry.getValue().removeSeance(seance); } } } } // this function add only 1 seance to the exact schedule public void addSeance(Seance s, String day){ if (map.isEmpty()){ Schedule sch = new Schedule(); sch.addSeance(s); map.put(Days.valueOf(day),sch); } for (final Map.Entry<Days, Schedule> entry : map.entrySet()) { if (entry.getKey().name().equalsIgnoreCase(day)){ entry.getValue().getSet().add(s); } } } //this function input as many seances as you want public Schedule inputSeances(Time open,Time close ) throws InvalidFormatTime{ Time t = new Time(); Scanner sc= new Scanner(System.in); boolean b = true; String mov=""; while(b==true){ System.out.print("Input name of movie : "); mov = sc.nextLine(); if (!mov.isEmpty()) { b=false; } else System.out.println("You entered incorrect name of movie, plz try again"); } System.out.println("Input duration of movie"); t.inputTime(); Movie m = new Movie(mov,t); // output created movie System.out.println(m); Schedule s = new Schedule(); int g=1; while( g==1) { // input start of the seance System.out.println("Input time of the beginning of the film"); Time t1 = new Time(); t1.inputTime(); Seance sea = new Seance(m,t1); System.out.println(sea); // check if the beginning\ending of the seance isn't earlier than opening\closing of the cinema if ((sea.getStartTime().compareTo(open)>=0)&&(sea.getEndTime().compareTo(close)<=0)) { s.getSet().add(sea); } else { System.out.println("You have input wrong time of the seance"); } System.out.println("If you want to add one more seance input 1, otherwise input 0"); g=sc.nextInt(); } return s; } // output all schedules public void output(){ for (final Map.Entry<Days, Schedule> entry : map.entrySet()) { System.out.println("\n"+entry.getKey() +"'s schedule"); entry.getValue().Output_seance(); } } public void menu(Time t,Time t1) throws InvalidFormatTime{ Scanner sc = new Scanner (System.in); Set<Seance> set = new TreeSet<>(); Schedule s = new Schedule(); //variable which will start our cycle String choice="YES"; while(choice.equalsIgnoreCase("YES")) { System.out.println("Input what day of schedule do you want to edit"+"\nIf you want to output all schedules input \"output\""); choice=sc.nextLine(); choice=choice.toUpperCase(); //System.out.println(choice); boolean b = false; //check if entered day belong to days for (Days d : Days.values()) { if (d.name().equals(choice)){ b=true; } } if (b==true){ s=inputSeances(t, t1); // if map doesn't contain entered day , create key-value if (!map.containsKey(Days.valueOf(choice))){ map.put(Days.valueOf(choice),s); output(); } else{ // if map contain , complete set of seances map.get(Days.valueOf(choice)).getSet().addAll(s.getSet()); output(); } } else { System.out.println("You have entered incorrect day"); } if (choice=="OUTPUT") { output(); } System.out.println("Do you want to continue? Yes / No"); choice=sc.nextLine(); } System.out.println("Bye-bye"); } @Override public int compare(Days d1, Days d2) { int res= d1.ordinal()-d2.ordinal(); return res; } }
package com.lec.condition; import java.util.Scanner; public class Q1_if { public static void main(String[] args) { Scanner i = new Scanner(System.in); System.out.println("입력하실 수는? "+i); int num = i.nextInt(); if(num>=0) { System.out.println("절대값은 "+num); }else { System.out.println("절대값은 "+(-num)); System.out.println("절대값은 "+(-num)); } } }
package com.todo.controller; import com.todo.service.TodoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; @Controller public class TodoController { @Autowired private TodoService todoService; @RequestMapping("/todo/update") public String update(final @RequestParam(value = "id") String id, final @RequestParam(value = "todo") String todo, Model model, HttpServletRequest request) { return todoService.update(request, id, todo, model); } @RequestMapping("/todo/cancel") public String remove(final @RequestParam(value = "id") String id, Model model, HttpServletRequest request) { return todoService.cancel(request, id, model); } @RequestMapping("/todo/add") public String add(final @RequestParam(value = "todo") String todo, Model model, HttpServletRequest request) { return todoService.add(request, todo, model); } @RequestMapping("/todo/complete") public String complete(final @RequestParam(value = "id") String id, Model model, HttpServletRequest request) { return todoService.complete(request, id, model); } }
package com.itheima.core.controller; import com.alibaba.dubbo.config.annotation.Reference; import com.itheima.core.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("login") public class LoginController { @Reference private UserService userService; @RequestMapping("name") public Map<String,String> showName(){ String name= SecurityContextHolder.getContext().getAuthentication().getName(); Map<String,String> map = new HashMap(); map.put("loginName",name); userService.addUserCount(name); return map; } }
package com.ttcscn.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.ttcscn.dto.OrderDto; import com.ttcscn.entity.Message; import com.ttcscn.entity.Order; import com.ttcscn.service.OrderService; @RestController public class OrderController { @Autowired private OrderService orderService; @RequestMapping(value = "/order/get", method = RequestMethod.GET) @ResponseBody public List<Order> getAllListMenu() { List<Order> arrOrder = orderService.getAllList(); return arrOrder; } @RequestMapping(value = "/order/add", method = RequestMethod.POST) @ResponseBody public OrderDto saveMenu(@RequestBody Order order) { OrderDto orderDto = new OrderDto(); Order orderfromData = orderService.findOrder(order.getMaOrder()); if(orderfromData!=null) { orderDto.setStatus("Failse"); orderDto.setMessage("Order thất bại!"); } else { String mess = orderService.saveOrder(order); orderDto.setStatus("Success"); orderDto.setMessage(mess); } return orderDto; } /* @RequestMapping(value = "/order/update", method = RequestMethod.POST) @ResponseBody public OrderDto updateMenu(@RequestBody Order order) { OrderDto orderDto = new OrderDto(); Order orderfromData = orderService.findOrder(order.getMaOrder()); if(orderfromData==null) { orderDto.setStatus("Failse"); orderDto.setMessage("Khong tim thay đơn nay"); } else { String mess = orderService.updateOrder(order); orderDto.setStatus("Success"); orderDto.setMessage(mess); } return orderDto; }*/ @RequestMapping(value = "/order/delete", method = RequestMethod.POST) @ResponseBody public OrderDto deleteMenu(@RequestBody Order order) { OrderDto orderDto = new OrderDto(); Order orderfromData = orderService.findOrder(order.getMaOrder()); if(orderfromData==null) { orderDto.setStatus("Failse"); orderDto.setMessage("Khong tim thay thuc uong nay"); } else { String mess = orderService.deleteOrder(order.getMaOrder(), order.getMaBan()); orderDto.setStatus("Success"); orderDto.setMessage(mess); } return orderDto; } @RequestMapping(value = "/order/find", method = RequestMethod.GET) @ResponseBody public Order findById(@RequestParam("orderService") String maOrder) { Order order = orderService.findOrder(maOrder); return order; } //Thêm @RequestMapping(value = "/order/addlist", method = RequestMethod.POST) @ResponseBody public Message addListOrder(@RequestBody List<Order> arrOrder) { OrderDto orderDto = new OrderDto(); for(Order order : arrOrder) { orderService.saveOrder(order); } Message message = new Message(); message.setMessage("Đã order thành công! Vui lòng đợi!"); return message; } }
package com.example.android.giphyapiretrofit; import com.google.gson.annotations.SerializedName; import java.util.List; public class TopObject { @SerializedName("data") List<Datum> data; public List<Datum> getData() { return data; } public TopObject setData(List<Datum> data) { this.data = data; return this; } }
package asu.shell.sh.commands; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.lang.StringUtils; import me.asu.util.Strings; @Cmd(value = "native2ascii") public class Native2ascii extends Command { Options opt = new Options(); public Native2ascii() { // ative2ascii -encoding UTF-8 utf8.properties nonUtf8.properties opt.addOption("h", "help", false, "显示帮助信息。"); opt.addOption("u", "usage", false, "显示帮助信息。"); opt.addOption("s", true, "来源。"); opt.addOption("r", false, "反转。"); } @Override public void execute(String... paramArrayOfString) { BasicParser parser = new BasicParser(); CommandLine cl; try { if (paramArrayOfString == null || paramArrayOfString.length == 0) { usage(); return; } cl = parser.parse(opt, paramArrayOfString); if (cl.hasOption('h') || cl.hasOption('u')) { usage(); } else if (cl.hasOption('r') && cl.hasOption('s')) { // System.err.println("未实现!!"); String s = cl.getOptionValue('s'); int len = s.length(); int start = 0; StringBuilder builder = new StringBuilder(); while (start < len) { int i = s.indexOf("\\u", start); if (i != -1 && i != start) { String x = s.substring(start, i); builder.append(x); String h = s.substring(i + 2, i + 6); int ch = Integer.parseInt(h, 16); builder.append((char) ch); start = i + 6; } else if (i != -1 && i == start) { String h = s.substring(i + 2, i + 6); int ch = Integer.parseInt(h, 16); builder.append((char) ch); start = i + 6; } else { String x = s.substring(start); builder.append(x); start = len; } } out().println(builder.toString()); } else if (cl.hasOption('s')) { String s = cl.getOptionValue('s'); if (StringUtils.isEmpty(s)) { out().println(""); } StringBuilder builder = new StringBuilder(); for (int i = 0, j = s.length(); i < j; i++) { int ch = s.charAt(i); if (ch < 127) { builder.append((char) ch); } else { String x = Strings.fillHex(ch, 4); builder.append("\\u").append(x); } } out().println(builder.toString()); } else { usage(); } } catch (Exception e) { e.printStackTrace(); } } @Override public void usage() { HelpFormatter help = new HelpFormatter(); help.setSyntaxPrefix("使用方法:"); help.printHelp(" native2ascii [options] ", Strings.dup('=', 60), opt, Strings.dup('-', 60)); } }
package com.dishcuss.foodie.hub.Models; import android.os.Parcel; import android.os.Parcelable; import io.realm.RealmList; import io.realm.RealmObject; /** * Created by Naeem Ibrahim on 8/8/2016. */ public class LocalFeedReview extends RealmObject implements Parcelable { int reviewID; String updated_at; String title; String summary; int rating; int reviewable_id; String reviewable_type; Boolean isBookmarked; Boolean isLiked; int reviewOnID; String reviewOnName; String reviewOnLocation; String reviewImage; int reviewerID; String reviewerName; String reviewerLocation; String reviewerAvatar; int reviewLikesCount; int reviewCommentCount; int reviewSharesCount; RealmList<Comment> commentRealmList; public LocalFeedReview(){ } public RealmList<Comment> getCommentRealmList() { return commentRealmList; } public void setCommentRealmList(RealmList<Comment> commentRealmList) { this.commentRealmList = commentRealmList; } public Boolean getLiked() { return isLiked; } public void setLiked(Boolean liked) { isLiked = liked; } public Boolean getBookmarked() { return isBookmarked; } public void setBookmarked(Boolean bookmarked) { isBookmarked = bookmarked; } public int getReviewID() { return reviewID; } public void setReviewID(int reviewID) { this.reviewID = reviewID; } public String getUpdated_at() { return updated_at; } public void setUpdated_at(String updated_at) { this.updated_at = updated_at; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public int getRating() { return rating; } public void setRating(int rating) { this.rating = rating; } public int getReviewable_id() { return reviewable_id; } public void setReviewable_id(int reviewable_id) { this.reviewable_id = reviewable_id; } public String getReviewable_type() { return reviewable_type; } public void setReviewable_type(String reviewable_type) { this.reviewable_type = reviewable_type; } public int getReviewOnID() { return reviewOnID; } public void setReviewOnID(int reviewOnID) { this.reviewOnID = reviewOnID; } public String getReviewOnName() { return reviewOnName; } public void setReviewOnName(String reviewOnName) { this.reviewOnName = reviewOnName; } public String getReviewOnLocation() { return reviewOnLocation; } public void setReviewOnLocation(String reviewOnLocation) { this.reviewOnLocation = reviewOnLocation; } public String getReviewImage() { return reviewImage; } public void setReviewImage(String reviewImage) { this.reviewImage = reviewImage; } public int getReviewerID() { return reviewerID; } public void setReviewerID(int reviewerID) { this.reviewerID = reviewerID; } public String getReviewerName() { return reviewerName; } public void setReviewerName(String reviewerName) { this.reviewerName = reviewerName; } public String getReviewerLocation() { return reviewerLocation; } public void setReviewerLocation(String reviewerLocation) { this.reviewerLocation = reviewerLocation; } public int getReviewLikesCount() { return reviewLikesCount; } public void setReviewLikesCount(int reviewLikesCount) { this.reviewLikesCount = reviewLikesCount; } public int getReviewCommentCount() { return reviewCommentCount; } public void setReviewCommentCount(int reviewCommentCount) { this.reviewCommentCount = reviewCommentCount; } public int getReviewSharesCount() { return reviewSharesCount; } public void setReviewSharesCount(int reviewSharesCount) { this.reviewSharesCount = reviewSharesCount; } public String getReviewerAvatar() { return reviewerAvatar; } public void setReviewerAvatar(String reviewerAvatar) { this.reviewerAvatar = reviewerAvatar; } public LocalFeedReview(Parcel in){ this.reviewID = in.readInt(); this.reviewerName = in.readString(); this.reviewerAvatar = in.readString(); this.updated_at = in.readString(); this.summary = in.readString(); this.reviewImage = in.readString(); this.reviewLikesCount = in.readInt(); this.reviewCommentCount = in.readInt(); this.reviewSharesCount = in.readInt(); this.commentRealmList=new RealmList<Comment>(); in.readTypedList(this.commentRealmList,Comment.CREATOR); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(reviewID); dest.writeString(reviewerName); dest.writeString(reviewerAvatar); dest.writeString(updated_at); dest.writeString(summary); dest.writeString(reviewImage); dest.writeInt(reviewLikesCount); dest.writeInt(reviewCommentCount); dest.writeInt(reviewSharesCount); dest.writeTypedList(commentRealmList); } public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public LocalFeedReview createFromParcel(Parcel in) { return new LocalFeedReview(in); } public LocalFeedReview[] newArray(int size) { return new LocalFeedReview[size]; } }; }
// assignment 6 // pair p134 // Singh, Bhavneet // singhb // Wang, Shiyu // shiyu /* * * * ------------------------------- * | ISelectImageFile | * ------------------------------- * / \ * --- * | * |----------------------- * | * ------------------------- | * | SmallImageFile |---------------| * ------------------------- | * | * --------------------------- | * | NameShorterThan4 |-------------| * --------------------------- | * | * -------------------- | * | GivenKind |--------------------- * -------------------- * */ // to represent a predicate for ImageFile-s public interface ISelectImageFile { // Return true if the given ImageFile // should be selected public boolean select(ImageFile f); } // Select image files smaller than 40000 class SmallImageFile implements ISelectImageFile { /*TEMPLATE * * FIELDS: * NONE * *METHODS: * ...select(ImageFile)... --boolean * *METHODS FOR FIELDS: * Built-in */ // Return true if the given ImageFile is smaller than 40000 public boolean select(ImageFile f) { return f.size() < 40000; } } // Select image files whose names are shorter than 4 class NameShorterThan4 implements ISelectImageFile { /*TEMPLATE * * FIELDS: * NONE * *METHODS: * ...select(ImageFile)... --boolean * *METHODS FOR FIELDS: * Built-in */ // Return true if the given ImageFile has a name shorter than 4 public boolean select(ImageFile f) { return f.name.length() < 4; } } // Select image files whose names are shorter than 4 class GivenKind implements ISelectImageFile { String kind; GivenKind(String kind) { this.kind = kind; } /*TEMPLATE * * FIELDS: * this.kind... --String * *METHODS: * ...select(ImageFile)... --boolean * *METHODS FOR FIELDS: * Built-in */ // Return true if the given ImageFile has the same kind as this // GivenKind's kind public boolean select(ImageFile f) { return f.kind.equals(this.kind); } }
package br.com.treinarminas.academicos.operadores; public class Relational { public static void main(String[] args) { int a = 10; int b = 10; System.out.println(a == b); boolean valoresIguais = a == b; System.out.println(valoresIguais); System.out.println(a != b); boolean verdade = true; System.out.println(!verdade); } }
package test; import java.util.Arrays; import java.util.List; import java.util.concurrent.locks.Lock; public class CollectionTest { public static void main(String[] args) throws InterruptedException { final Table ta = new Table(); final Table2 ta2 = new Table2(); new Thread( new Runnable() { @Override public void run() { for (int i = 0; i < 50; i++) { try { ta.sleepMain(); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { try { ta2.sleepSub(); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } } class Table { // boolean flag = false; public synchronized void sleepMain() throws InterruptedException { // this.notify(); // if(flag) { // // 互斥 // this.wait(); // } for (int i = 1; i <= 11; i++) { System.out.println(Thread.currentThread().getName() + ":" + i); if(i == 11) { // flag = true; this.notify(); this.wait(); } } } public synchronized void sleepSub() throws InterruptedException { // 在main 走完往前进入循环输出前都是 沉睡状态 // if(!flag) { // this.wait(); // this.notify(); // } for (int i = 1; i <= 10; i++) { System.err.println(Thread.currentThread().getName() + ":" + i); // if(i == 10) { // flag = false; this.notify(); this.wait(); } } } } class Table2 { public synchronized void sleepSub() throws InterruptedException { // 在main 走完往前进入循环输出前都是 沉睡状态 // if(!flag) { // this.wait(); // this.notify(); // } for (int i = 1; i <= 10; i++) { System.err.println(Thread.currentThread().getName() + ":" + i); // if(i == 10) { // flag = false; this.notify(); this.wait(); } } } }
import java.math.BigInteger; import java.net.InetSocketAddress; public class PredFoundThread implements Runnable { Message message; public PredFoundThread(Message message) { this.message = message; } @Override public void run() { //System.out.println("INSIDE PredFoundThread"); // Version PREDFOUND + nodeId + address + port String[] header = this.message.getHeader(); System.out.println("RECEIVED: " + header[0] + " " + header[1] + " " + header[2] + " " + header[3] + " " + header[4]); BigInteger nodeId = new BigInteger(header[2]); String address = header[3]; int port = Integer.parseInt(header[4]); NodeInfo node = new NodeInfo(nodeId, new InetSocketAddress(address, port)); Peer.getChordNode().setSuccPred(node); Peer.getChordNode().decrementStabilizeCountDownLatch(); } }
package org.slevin.dao; import org.slevin.common.Mahalle; public interface MahalleDao extends EntityDao<Mahalle> { }
/* * 2012-3 Red Hat Inc. and/or its affiliates and other contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.overlord.rtgov.tests.epn; import org.overlord.rtgov.epn.Network; import org.overlord.rtgov.epn.Node; import org.overlord.rtgov.epn.Subscription; import org.overlord.rtgov.epn.util.NetworkUtil; /** * This class is responsible for loading the test network and registering it with the * Event Processor Network Manager. * */ public class NetworkLoader { /** The root. **/ public static final String ROOT = "Root"; /** The child A. **/ public static final String CHILD_A = "ChildA"; /** The child B. **/ public static final String CHILD_B = "ChildB"; /** The subject. **/ public static final String TEST_SUBJECT = "TestSubject"; /** The network. **/ public static final String TEST_NETWORK = "TestNetwork"; /** The file. **/ public static final String NETWORK_FILE="/networks/TestNetwork.json"; /** * The main method. * * @param args The list of args */ public static void main(String[] args) { NetworkLoader loader=new NetworkLoader(); Network net=loader.createNetwork(); try { byte[] b=NetworkUtil.serialize(net); java.net.URL url=NetworkLoader.class.getResource(NETWORK_FILE); java.io.FileOutputStream fos=new java.io.FileOutputStream(url.getFile()); fos.write(b); fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); } } /** * This method loads the network. * * @return The network */ public Network loadNetwork() { Network ret=null; try { java.io.InputStream is=NetworkLoader.class.getResourceAsStream(NETWORK_FILE); byte[] b=new byte[is.available()]; is.read(b); is.close(); ret = NetworkUtil.deserialize(b); } catch (Exception e) { e.printStackTrace(); } return (ret); } /** * This method creates the network. * * @return The new network */ public Network createNetwork() { Network ret=new Network(); ret.setName(TEST_NETWORK); ret.setVersion(""+System.currentTimeMillis()); ret.subjects().add(TEST_SUBJECT); Root rootep=new Root(); Child childAep=new Child(); Child childBep=new Child(); ChildPredicate childApred=new ChildPredicate(); childApred.setMin(0); childApred.setMax(9); ChildPredicate childBpred=new ChildPredicate(); childBpred.setMin(10); childBpred.setMax(19); Node root=new Node(); root.setName(ROOT); root.setEventProcessor(rootep); ret.getNodes().add(root); Node childA=new Node(); childA.setName(CHILD_A); childA.setPredicate(childApred); childA.setEventProcessor(childAep); childA.getSourceNodes().add(ROOT); ret.getNodes().add(childA); Node childB=new Node(); childB.setName(CHILD_B); childB.setPredicate(childBpred); childB.setEventProcessor(childBep); childB.getSourceNodes().add(ROOT); ret.getNodes().add(childB); Subscription sub=new Subscription(); sub.setNodeName(ROOT); sub.setSubject(TEST_SUBJECT); ret.getSubscriptions().add(sub); return (ret); } }
/* * Copyright 2015 Michal Harish, michal.harish@gmail.com * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 io.amient.kafka.metrics; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import joptsimple.internal.Strings; import java.io.FileOutputStream; import java.io.IOException; public class Dashboard { private final ObjectMapper mapper = new ObjectMapper(); private final ObjectNode root; private final ArrayNode rows; private final String filename; private final String dataSource; private final ArrayNode templating; private int numPanels = 0; public Dashboard(String title, String dataSource, String filename) { this.dataSource = dataSource; this.filename = filename; root = mapper.createObjectNode(); root.put("schemaVersion", 7); root.put("id", (String) null); root.put("version", 0); root.put("title", title); root.put("originalTitle", title); root.put("style", "dark"); root.put("timezone", "browser"); root.put("refresh", "10s"); root.set("time", mapper.createObjectNode().put("from", "now-30m").put("to", "now")); root.put("editable", true); root.put("hideControls", false); root.put("sharedCrosshair", false); root.set("links", mapper.createArrayNode()); root.set("tags", mapper.createArrayNode()); templating = mapper.createArrayNode(); root.set("templating", mapper.createObjectNode().set("list", templating)); root.set("annotations", mapper.createObjectNode().set("list", mapper.createArrayNode())); rows = mapper.createArrayNode(); root.set("rows", rows); } public void save() { mapper.enable(SerializationFeature.INDENT_OUTPUT); try { FileOutputStream out = new FileOutputStream(filename); try { mapper.writeValue(out, root); } finally { out.close(); } } catch (IOException e) { e.printStackTrace(); } } public ArrayNode newRow(String rowTitle, int heightPx, boolean expand) { ObjectNode row = rows.addObject(); row.put("title", rowTitle); row.put("showTitle", rowTitle != null); row.put("height", heightPx + "px"); row.put("editable", true); row.put("collapse", !expand); ArrayNode panels = mapper.createArrayNode(); row.set("panels", panels); return panels; } public ObjectNode newGraph(ArrayNode rowPanels, String title, int span, boolean showLegend) { ObjectNode graph = newPanel(rowPanels, title, span, "graph"); // graph.put("nullPointMode", "connected"); graph.put("x-axis", true); graph.put("y-axis", true); graph.set("y_formats", mapper.createArrayNode().add("short").add("short")); graph.put("lines", true); graph.put("linewidth", 2); graph.put("steppedLine", false); graph.put("fill", 1); graph.put("points", false); graph.put("pointradius", 2); graph.put("bars", false); graph.put("percentage", false); graph.put("stack", false); // graph.set("tooltip", mapper.createObjectNode() .put("value_type", "cumulative") .put("shared", true)); // graph.set("seriesOverrides", mapper.createArrayNode()); graph.set("aliasColors", mapper.createObjectNode()); graph.set("legend", mapper.createObjectNode() .put("show", showLegend) .put("values", false) .put("min", false) .put("max", false) .put("current", false) .put("total", false) .put("avg", false)); // graph.set("grid", mapper.createObjectNode() .put("leftLogBase", 1) .put("leftMax", (Integer) null) .put("rightMax", (Integer) null) .put("leftMin", (Integer) null) .put("rightMin", (Integer) null) .put("rightLogBase", (Integer) 1) .put("threshold1", (Integer) null) .put("threshold1Color", "rgba(216, 200, 27, 0.27)") .put("threshold2", (Integer) null) .put("threshold2Color", "rgba(234, 112, 112, 0.22)")); return graph; } public ObjectNode newTable(ArrayNode rowPanels, String title, int span, String valueName, String alias, String query) { ObjectNode table = newPanel(rowPanels, title, span, "table"); table.put("transform", "timeseries_aggregations"); newTarget(table, alias, query); // ArrayNode columns = mapper.createArrayNode(); columns.addObject().put("value", valueName).put("text", valueName); table.set("columns", columns); ArrayNode styles = mapper.createArrayNode(); styles.addObject() .put("value", valueName) .put("type", "number") .put("pattern", "/.*/") .put("decimals", 0) //.put("colorMode", null)// .put("unit", "short"); table.set("styles", styles); // table.put("showHeader", true); table.put("scroll", true); table.put("fontSize", "100%"); table.put("pageSize", (Integer) null); table.set("sort", mapper.createObjectNode().put("col", (String) null).put("desc", false)); return table; } public ObjectNode newStat(ArrayNode rowPanels, String title, int span, String query) { ObjectNode stat = newPanel(rowPanels, title, span, "singlestat"); stat.put("valueName", "current"); stat.put("decimals", 0); stat.put("maxDataPoints", 100); stat.put("prefix", ""); stat.put("postfix", ""); stat.put("nullText", (String) null); stat.put("prefixFontSize", "50%"); stat.put("valueFontSize", "80%"); stat.put("postfixFontSize", "50%"); stat.put("format", "none"); stat.put("nullPointMode", "connected"); stat.set("sparkline", mapper.createObjectNode() .put("show", false) .put("full", false) ); // "thresholds": "", // "colorBackground": false, // "colorValue": false, newTarget(stat, "", query); return stat; } public ObjectNode newVariable(String name, boolean includeAll, String... options) { ObjectNode variable = templating.addObject() .put("type", "custom") .put("name", name) .put("label", name) .put("includeAll", includeAll) .put("multi", false) .put("query", Strings.join(options, ",")) .put("datasource", (String) null) .put("refresh", 0) .put("hide", 0); variable.set("current", mapper.createObjectNode() .put("text", "All") .put("value", "$__all") .set("tags", mapper.createArrayNode())); ArrayNode optionsArray = mapper.createArrayNode(); variable.set("options", optionsArray); if (includeAll) { variable.put("allValue", ".+"); optionsArray.addObject().put("text", "All").put("value", "$__all").put("selected", true); } for(String option: options) { optionsArray.addObject().put("text", option).put("value", option).put("selected", false); } return variable; } public ObjectNode newTarget(ObjectNode panel, String aliasPattern, String rawQuery) { ArrayNode targets = ((ArrayNode) panel.get("targets")); ObjectNode target = targets.addObject(); target.put("refId", Character.toString((char) (64 + targets.size()))); target.put("query", rawQuery); target.put("alias", aliasPattern); target.put("rawQuery", true); return target; } // public ObjectNode newTarget(ObjectNode panel) { // ObjectNode target = ((ArrayNode) panel.get("targets")).addObject(); // target.put("rawQuery", false); // // target.put("measurement", "UnderReplicatedPartitions"); // // ArrayNode fields = mapper.createArrayNode(); // fields.addObject().put("name", "Value").put("func", "mean"); // target.set("fields", fields); // // ArrayNode groupBy = mapper.createArrayNode(); // groupBy.addObject().put("type", "time").put("interval", "auto"); // target.set("groupBy", groupBy); // // ArrayNode tags = mapper.createArrayNode(); // tags.addObject().put(...).put(...).put(...); // target.set("tags", tags); // // return target; // } private ObjectNode newPanel(ArrayNode rowPanels, String title, int span, String type) { ObjectNode panel = rowPanels.addObject(); panel.put("title", title); panel.put("span", span); panel.put("id", ++numPanels); panel.put("datasource", dataSource); panel.put("type", type); panel.put("renderer", "flot"); // panel.put("timeFrom", (String) null); panel.put("timeShift", (String) null); // panel.put("editable", true); panel.put("error", false); panel.put("isNew", true); // panel.set("targets", mapper.createArrayNode()); return panel; } public ObjectNode newObject() { return mapper.createObjectNode(); } public ArrayNode newArray(String... values) { ArrayNode node = mapper.createArrayNode(); for (String v : values) node.add(v); return node; } public ObjectNode get(ObjectNode node, String fieldName) { return (ObjectNode) node.get(fieldName); } }
package com.tencent.mm.plugin.appbrand.game; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLDisplay; abstract class GameGLSurfaceView$a implements GameGLSurfaceView$e { protected int[] fzg; final /* synthetic */ GameGLSurfaceView fzh; abstract EGLConfig b(EGL10 egl10, EGLDisplay eGLDisplay, EGLConfig[] eGLConfigArr); public GameGLSurfaceView$a(GameGLSurfaceView gameGLSurfaceView, int[] iArr) { this.fzh = gameGLSurfaceView; if (GameGLSurfaceView.a(this.fzh) == 2 || GameGLSurfaceView.a(this.fzh) == 3) { Object obj = new int[15]; System.arraycopy(iArr, 0, obj, 0, 12); obj[12] = 12352; if (GameGLSurfaceView.a(this.fzh) == 2) { obj[13] = 4; } else { obj[13] = 64; } obj[14] = 12344; Object iArr2 = obj; } this.fzg = iArr2; } public final EGLConfig chooseConfig(EGL10 egl10, EGLDisplay eGLDisplay) { int[] iArr = new int[1]; if (egl10.eglChooseConfig(eGLDisplay, this.fzg, null, 0, iArr)) { int i = iArr[0]; if (i <= 0) { throw new IllegalArgumentException("No configs match configSpec"); } EGLConfig[] eGLConfigArr = new EGLConfig[i]; if (egl10.eglChooseConfig(eGLDisplay, this.fzg, eGLConfigArr, i, iArr)) { EGLConfig b = b(egl10, eGLDisplay, eGLConfigArr); if (b != null) { return b; } throw new IllegalArgumentException("No config chosen"); } throw new IllegalArgumentException("eglChooseConfig#2 failed"); } throw new IllegalArgumentException("eglChooseConfig failed"); } }
import java.util.Scanner; class array_max { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter the size of Array: "); int N=scan.nextInt(); int array[]= new int[N]; for (int i=0;i<array.length;i++) array[i]=scan.nextInt(); maxvalue(array); } public static void maxvalue(int array[]) { int temp; for (int i=0;i<array.length;i++) { for (int j=i+1;j<array.length;j++) { if (array[i]>array[j]) { temp=array[i]; array[i]=array[j]; array[j]=temp; } } } System.out.println("Max Value: "+array[array.length-1]); } }
package it.unirc.pwm.eureca.tessera.dao; public class TesseraDAOFactory { private static TesseraDAOInterface dao = null; private TesseraDAOFactory(){ } public static TesseraDAOInterface getDAO() { if ( dao == null ) { dao = new TesseraDAOImplement(); } return dao; } }
package sample; import javafx.scene.input.MouseEvent; import javax.xml.crypto.Data; import java.io.*; import java.util.ArrayList; public class SaveAndLoad extends Thread { private File saveFile; private IdFile ID = new IdFile(); private int saveNumber = ID.getI(); private DataInfo _dataInfo; public DataInfo get_dataInfo() { return _dataInfo; } public void set_dataInfo(DataInfo _dataInfo) { this._dataInfo = _dataInfo; } public int getSaveNumber() { return saveNumber; } public void setSaveNumber(int saveNumber) { this.saveNumber = saveNumber; } public void setSaveFile(String saveFile) { this.saveFile = new File(saveFile); } public void SaveAndLoad(){ saveFile = new File("./src/data/SavedGames/SavedData" + (saveNumber) + ".ran"); } @Override public void run(){ if(_dataInfo.getChoice() == Choice.SAVE) saveGameStateBinary(); else loadGameStateBinary(); } public void saveGameStateBinary() { try { saveFile = new File("./src/data/SavedGames/SavedData" + (saveNumber) + ".ran"); ObjectOutputStream objOutStream = new ObjectOutputStream( new FileOutputStream(saveFile) ); objOutStream.writeObject(_dataInfo); objOutStream.close(); } catch (IOException e) { e.printStackTrace(); } ID.setI(saveNumber); } public void loadGameStateBinary() { try { ObjectInputStream objInputStream = new ObjectInputStream(new FileInputStream(saveFile)); _dataInfo = (DataInfo) objInputStream.readObject(); objInputStream.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } public void getPLayersName(File file) { try { FileInputStream fIn = new FileInputStream(file); ObjectInputStream objInputStream = new ObjectInputStream(fIn); _dataInfo = (DataInfo)objInputStream.readObject(); objInputStream.close(); fIn.close(); } catch (IOException | ClassNotFoundException e) { System.out.println("File has been read successfully"); } } }
public class Roles { // arguments are passed using the text field below this editor public static void main(String[] args) { String [] roles= { "Городничий","Аммос Федорович", "Артемий Филиппович", "Лука Лукич"}; String [] textLines={ "Городничий: Я пригласил вас, господа, с тем, чтобы сообщить вам пренеприятное известие: к нам едет ревизор.", "Аммос Федорович: Как ревизор?", "Артемий Филиппович: Как ревизор?", "Городничий: Ревизор из Петербурга, инкогнито. И еще с секретным предписаньем.", "Аммос Федорович: Вот те на!", "Артемий Филиппович: Вот не было заботы, так подай!", "Лука Лукич: Господи боже! еще и с секретным предписаньем!"}; StringBuilder res = new StringBuilder(""); for (String role : roles) { res.append(role + ":\n"); for (int i = 0; i < textLines.length; i++) { if ( textLines[i].matches("^"+role+":.*") ){ res.append(String.valueOf(i+1) + ")" + textLines[i].substring(role.length()+1)); } } res.append("\n"); } System.out.println( res.toString()); } }
package edu.iit.cs445.StateParking.REST; import java.util.ArrayList; import edu.iit.cs445.StateParking.Objects.*; public class VisitorWithDetailsPresenter { public String vid; public visitor visitor; public ArrayList<NoteForVisitorPresenter> note; public ArrayList<OrderForVisitorPresenter> order; public void addNote(NoteForVisitorPresenter N ) { this.note.add(N); } public void addOrder(OrderForVisitorPresenter O) { this.order.add(O); } public VisitorWithDetailsPresenter(Visitor a) { this.vid = Integer.toString(a.getVid()); this.visitor = new visitor(a); this.note = new ArrayList<NoteForVisitorPresenter>(); this.order = new ArrayList<OrderForVisitorPresenter>(); } public class visitor { public String name; public String email; public visitor (Visitor a) { this.name = a.getName(); this.email = a.getEmail(); } } }
package com.nikogalla.tripbook.data; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.nikogalla.tripbook.data.LocationContract.LocationEntry; import com.nikogalla.tripbook.data.LocationContract.UserEntry; import com.nikogalla.tripbook.models.Location; import com.nikogalla.tripbook.models.User; import java.util.ArrayList; /** * Created by Nicola on 2017-02-03. */ public class LocationDbHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 13; static final String DATABASE_NAME = "location.db"; public LocationDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { // Create a table to hold locations. final String SQL_CREATE_LOCATION_TABLE = "CREATE TABLE " + LocationEntry.TABLE_NAME + " (" + LocationEntry._ID + " INTEGER PRIMARY KEY," + LocationEntry.COLUMN_KEY + " TEXT UNIQUE ON CONFLICT REPLACE," + LocationEntry.COLUMN_ADDRESS + " TEXT NOT NULL, " + LocationEntry.COLUMN_LATITUDE + " REAL NOT NULL, " + LocationEntry.COLUMN_LONGITUDE + " REAL NOT NULL, " + LocationEntry.COLUMN_NAME + " TEXT NOT NULL, " + LocationEntry.COLUMN_PICTURE_URL + " TEXT NOT NULL, " + LocationEntry.COLUMN_DESCRIPTION + " TEXT NOT NULL, " + LocationEntry.COLUMN_DISTANCE + " REAL, " + LocationEntry.COLUMN_COMMENT_COUNT + " INTEGER, " + LocationEntry.COLUMN_RATE + " REAL, " + LocationEntry.COLUMN_RATE_COUNT + " INTEGER, " + LocationEntry.COLUMN_USER_ID + " TEXT NOT NULL " + " );"; sqLiteDatabase.execSQL(SQL_CREATE_LOCATION_TABLE); final String SQL_CREATE_USER_TABLE = "CREATE TABLE " + UserEntry.TABLE_NAME + " (" + UserEntry._ID + " INTEGER PRIMARY KEY, " + UserEntry.COLUMN_UID + " TEXT UNIQUE ON CONFLICT REPLACE, " + UserEntry.COLUMN_NAME + " TEXT NOT NULL, " + UserEntry.COLUMN_EMAIL + " TEXT NOT NULL, " + UserEntry.COLUMN_PROVIDER + " REAL NOT NULL, " + UserEntry.COLUMN_PICTURE_URL + " TEXT " + " );"; sqLiteDatabase.execSQL(SQL_CREATE_USER_TABLE); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { // This database is only a cache for online data, so its upgrade policy is // to simply to discard the data and start over // Note that this only fires if you change the version number for your database. // It does NOT depend on the version number for your application. // If you want to update the schema without wiping data, commenting out the next 2 lines // should be your top priority before modifying this method. sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + LocationEntry.TABLE_NAME); sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + UserEntry.TABLE_NAME); onCreate(sqLiteDatabase); } public static void saveUserLocally(User user, Context context){ // Table location ContentValues contentValues = new ContentValues(); contentValues.put(UserEntry.COLUMN_UID, user.UID); contentValues.put(UserEntry.COLUMN_NAME, user.name); contentValues.put(UserEntry.COLUMN_EMAIL, user.email); contentValues.put(UserEntry.COLUMN_PROVIDER, user.provider); contentValues.put(UserEntry.COLUMN_PICTURE_URL, user.pictureUrl); context.getContentResolver().insert(LocationContract.UserEntry.CONTENT_URI, contentValues); } public static void saveLocationLocally(Location location, Context context){ // Table location ContentValues contentValues = new ContentValues(); contentValues.put(LocationEntry.COLUMN_KEY, location.getKey()); contentValues.put(LocationEntry.COLUMN_ADDRESS, location.address); contentValues.put(LocationEntry.COLUMN_LATITUDE, location.latitude); contentValues.put(LocationEntry.COLUMN_LONGITUDE, location.longitude); contentValues.put(LocationEntry.COLUMN_NAME, location.name); contentValues.put(LocationEntry.COLUMN_PICTURE_URL, location.getMainPhotoUrl()); contentValues.put(LocationEntry.COLUMN_DESCRIPTION, location.description); contentValues.put(LocationEntry.COLUMN_DISTANCE, location.distance); contentValues.put(LocationEntry.COLUMN_USER_ID, location.userId); contentValues.put(LocationEntry.COLUMN_COMMENT_COUNT, location.comments.size()); contentValues.put(LocationEntry.COLUMN_RATE, location.getRate()); contentValues.put(LocationEntry.COLUMN_RATE_COUNT, location.rates.size()); context.getContentResolver().insert(LocationContract.LocationEntry.CONTENT_URI, contentValues); } public static int saveLocationsLocally(ArrayList<Location> locations, Context context){ ArrayList<ContentValues> locationsToInsert = new ArrayList<>(); int insertedRowsCount = -1; for (Location location : locations){ ContentValues contentValues = new ContentValues(); contentValues.put(LocationEntry.COLUMN_KEY, location.getKey()); contentValues.put(LocationEntry.COLUMN_ADDRESS, location.address); contentValues.put(LocationEntry.COLUMN_LATITUDE, location.latitude); contentValues.put(LocationEntry.COLUMN_LONGITUDE, location.longitude); contentValues.put(LocationEntry.COLUMN_NAME, location.name); contentValues.put(LocationEntry.COLUMN_PICTURE_URL, location.getMainPhotoUrl()); contentValues.put(LocationEntry.COLUMN_DESCRIPTION, location.description); contentValues.put(LocationEntry.COLUMN_DISTANCE, location.distance); contentValues.put(LocationEntry.COLUMN_USER_ID, location.userId); contentValues.put(LocationEntry.COLUMN_COMMENT_COUNT, location.comments.size()); contentValues.put(LocationEntry.COLUMN_RATE, location.getRate()); contentValues.put(LocationEntry.COLUMN_RATE_COUNT, location.rates.size()); locationsToInsert.add(contentValues); } // Add products to the database ContentValues[] cvArray = new ContentValues[locationsToInsert.size()]; locationsToInsert.toArray(cvArray); // Flushing local locations, distance informations have to be updated context.getContentResolver().delete(LocationContract.LocationEntry.CONTENT_URI,null,null); // Insert updated data insertedRowsCount = context.getContentResolver().bulkInsert(LocationContract.LocationEntry.CONTENT_URI, cvArray); return insertedRowsCount; } }
package july; public class ExampleIfEqualString { public static void main(String[] args) { String word1 = "java"; String word2 = "java"; String word = "Java"; String word3 = new String("Java"); String word4 = new String("Java"); String word5 = new String("java"); // System.out.println(word1==word2);//true // System.out.println(word1.equals(word2)); //true // // System.out.println(word==word1);//false // // System.out.println(word4==word3);//false // System.out.println(word4.equals(word3));//true // // System.out.println(word1==word3); // System.out.println(word.equals(word3)) ;//true //0 System.out.println(word==word3) ;//false // ; // System.out.println(word2==word4); // System.out.println(word2.equals(word4)); System.out.println(word1.equals(word5));//true System.out.println(word1==word5);//false } }
package com.rensimyl.www.mathics; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class Matmatriks4 extends AppCompatActivity { Button backmatriks4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_matmatriks4); backmatriks4 = findViewById(R.id.matriks4_back); backmatriks4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } }
package com.sysh.web.controller; import com.sysh.dto.AB10_AB01Dto; import com.sysh.entity.AC01Part; import com.sysh.service.PovertyDetailsService; import com.sysh.util.ResultData; import com.sysh.util.ToJson; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; /** * ClassName: <br/> * Function:贫困户详细信息<br/> * date: 2018年06月05日 <br/> * * @author 苏积钰 * @since JDK 1.8 */ @RestController @RequestMapping("/poverty") public class PovertyDetailsController { @Autowired private PovertyDetailsService povertyDetailsService; /** * 点击眼睛详情看页面 * @param povertyNumber * @param callback * @return */ @RequestMapping(value = "/detail") public ResultData povertyDetail(String povertyNumber,String callback) { // 致贫原因 // 户编号,户住证件号,家庭地址,联系方式 AC01Part ac01=povertyDetailsService.selectAll(Long.parseLong(povertyNumber)); Map<String,Object> map=new HashMap<>(); map.put("POVERTYDETAIL",ac01); //return ToJson.toJson(map,callback); return ResultData.returnResultData(ResultData.RESULT_SUCCESS,"ok",map); } /** * 基本信息查询 * @param povertyNumber * @param callback * @return */ @RequestMapping(value = "/basic") public ResultData povertyBasicDetail(String povertyNumber,String callback) { Long num=Long.parseLong(povertyNumber); Map<String,Object> map=new HashMap<>(); map.put("Ac01Basic",povertyDetailsService.selectAC01Basic(num)); return ResultData.returnResultData(ResultData.RESULT_SUCCESS,"ok",map); //return ToJson.toJson(map,callback); } /** * 收入查询,患病查询 * @param povertyNumber * @param callback * @return */ @RequestMapping(value = "/income") public ResultData povertyIncome(String povertyNumber,String callback) { Long num=Long.parseLong(povertyNumber); Map<String,Object> map=new HashMap<>(); map.put("Ac07Income",povertyDetailsService.selectPovertyIncome(num)); map.put("Health",povertyDetailsService.findHealth(povertyNumber)); return ResultData.returnResultData(ResultData.RESULT_SUCCESS,"ok",map); // return ToJson.toJson(map,callback); } /** * 五项指标 * @param povertyNumber * @param callback * @return */ @RequestMapping(value = "/Alleviation") public ResultData povertyAlleviation(String povertyNumber,String callback) { Long num=Long.parseLong(povertyNumber); Map<String,Object> map=new HashMap<>(); map.put("FiveExit",povertyDetailsService.selectFivePoverty(num)); return ResultData.returnResultData(ResultData.RESULT_SUCCESS,"ok",map); } /** * 家庭成员信息概要 * @param povertyNumber * @param callback * @return */ @RequestMapping(value = "/familyInfo") public ResultData FamilyInfo(String povertyNumber,String callback) { Long num=Long.parseLong(povertyNumber); Map<String,Object> map=new HashMap<>(); map.put("FamilyInfo",povertyDetailsService.selectFamily(num)); return ResultData.returnResultData(ResultData.RESULT_SUCCESS,"ok",map); } /** * 家庭成员详情 * @param povertyNumber * @param callback * @return */ @RequestMapping(value="/fInfo") public ResultData FamilyDetailInfo(String povertyNumber,String callback) { Long num=Long.parseLong(povertyNumber); Map<String,Object> map=new HashMap<>(); AB10_AB01Dto ab10_ab01Dto=povertyDetailsService.selectFamilyIfo(num); map.put("FamilyDetailInfo",ab10_ab01Dto); return ResultData.returnResultData(ResultData.RESULT_SUCCESS,"ok",map); } /** * 生产生活 * @param povertyNumber * @param callback * @return */ @RequestMapping(value="/Produce") public ResultData PovertyProduce(String povertyNumber,String callback) { Long num=Long.parseLong(povertyNumber); Map<String,Object> map=new HashMap<>(); map.put("PovertyProduce",povertyDetailsService.selectPovertyProduce(num)); return ResultData.returnResultData(ResultData.RESULT_SUCCESS,"ok",map); } /** * 帮扶干部结对信息 * @param povertyNumber * @param callback * @return */ @RequestMapping(value="/HelpUser") public ResultData PovertyHelpUser(String helpNumber,String callback) { Long num=Long.parseLong(helpNumber); Map<String,Object> map=new HashMap<>(); map.put("PovertyHelp",povertyDetailsService.selectAC01AK11(num)); return ResultData.returnResultData(ResultData.RESULT_SUCCESS,"ok",map); } }
package Sudoku_Logica; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Random; public class Sudoku { //Atributos private Celda[][] tablero; private int cantFilas; private int cantFilasSubcuadrante; private long Hora; private boolean estadoinicialcorrecto; //Constructor public Sudoku() { Hora=System.currentTimeMillis() ; cantFilas=9; cantFilasSubcuadrante=3; tablero=new Celda[cantFilas][cantFilas]; for (int i=0;i<cantFilas;i++) { for (int j=0;j<cantFilas;j++) { tablero[i][j]=new Celda(i,j); } } estadoinicialcorrecto=this.ingresarestadoinicial("archivodetexto/EstadoInicial.txt") && estadoinicialcorrecto; } //Metodos public void accionar(Celda c, int num) { accionar2(c,num); this.actualizar(); } public void actualizar() { //Para cada celda del tablero, inserta el mismo valor que tenia antes, para ver si un nuevo valor ingresado al tablero creo un conflicto for (int i=0;i<cantFilas;i++) { for (int j=0;j<cantFilas;j++) { Celda c=tablero[i][j]; if (c!=null && c.getValor()!=0) { this.accionar2(c,c.getValor()); } } } } private void accionar2(Celda c, int num) { int i=c.getfila(); int j=c.getcolumna(); c.setValor(num); boolean cumple=noesta(i,j,num); c.setcorrecto(cumple); } public boolean gano() { boolean estado=true; for (int i=0;i<cantFilas && estado;i++) { for(int j=0;j<cantFilas && estado;j++) { if (!tablero[i][j].getcorrecto()) { estado=false; } } } return estado; } private boolean noesta(int i, int j, int num) { return (this.noestaenfila(i, j, num) && this.noestaencolumna(i, j, num) && this.noestaencuadrante(i, j, num)); } public boolean getestadoinicialcorrecto() { return estadoinicialcorrecto; } public int getcantFilas() { return cantFilas; } public Celda getCelda(int i, int j) { return tablero[i][j]; } private boolean noestaenfila(int i, int j, int num) { boolean cumple=true; for (int col=0;col<cantFilas && cumple;col++) { if (col!=j && tablero[i][col]!=null && tablero[i][col].getValor()!=0) { cumple=(tablero[i][col].getValor()!=num); } } return cumple; } private boolean noestaencolumna(int i, int j, int num) { boolean cumple=true; for (int fila=0;fila<cantFilas && cumple;fila++) { if (fila!=i && tablero[fila][j]!=null && tablero[fila][j].getValor()!=0) { cumple=(tablero[fila][j].getValor()!=num); } } return cumple; } private boolean noestaencuadrante(int fila, int columna, int num) { boolean cumple=true; int a=0, b=0; //Dado el numero de fila y columna de la celda, recorrera el cuadrante sabiendo su posicion superior izquierda, con "a" su n° de fila y "b" su n° de columna a=((int) (fila/cantFilasSubcuadrante)) *cantFilasSubcuadrante; b=((int) (columna/cantFilasSubcuadrante)) *cantFilasSubcuadrante; for (int i=0;i<cantFilasSubcuadrante && cumple;i++) { for (int j=0;j<cantFilasSubcuadrante && cumple;j++) { if (((a+i)!=fila && (b+j)!=columna) && tablero[a+i][b+j]!=null && tablero[a+i][b+j].getValor()!=0) { cumple=(tablero[a+i][b+j].getValor()!=num); } } } return cumple; } public long getHora() { return Hora; } public void reiniciarHora() { Hora=System.currentTimeMillis(); } public String getTiempo() { long TiempoPaso = System.currentTimeMillis() - Hora; long SegundosPaso = TiempoPaso / 1000; long SegundosMostrar = SegundosPaso % 60; long MinutosPaso= SegundosPaso / 60; long MinutosMostrar = MinutosPaso % 60; long HorasMostrar= MinutosPaso / 60; String hms=String.format("%02d:%02d:%02d",HorasMostrar,MinutosMostrar,SegundosMostrar); return (hms); } public boolean ingresarestadoinicial(String nombrearchivo) { //Inicializa el tablero con un estado incial, devuelve un mensaje si ocurrio algun error, sino returna null; InputStream in = Sudoku.class.getClassLoader().getResourceAsStream(nombrearchivo); if (in!=null) { InputStreamReader inr= new InputStreamReader(in); int punteroJ, punteroI=0; try { BufferedReader Buffer= new BufferedReader(inr); while (punteroI<this.getcantFilas() && Buffer.ready()) { punteroJ=0; String linea=Buffer.readLine(); linea=linea.replace(" ",""); //Borro los espacios en blanco char[] arreglo=linea.toCharArray(); if (arreglo.length!=cantFilas) { return false; } while (punteroJ<arreglo.length && punteroJ<this.getcantFilas()) { try { int num=Integer.parseInt(Character.toString(arreglo[punteroJ])); if (num<10 && num>0) { this.accionar(tablero[punteroI][punteroJ], num); } } catch (NumberFormatException exception) { //ERROR NumberFormatException, el valor se reemplazo por un cero(es decir no hace nada porque la celda tiene incializada el valor 0) } punteroJ++; } punteroI++; } if ((punteroI!=this.getcantFilas()) || Buffer.ready()) { return false; } Buffer.close(); } catch (IOException e) { estadoinicialcorrecto=false; } this.estadoinicialcorrecto=this.gano(); this.editarestadoinicial(); return true; } else { return false; } } private void editarestadoinicial() { //Elimina aleatoriamente elementos del Tablero Random rand= new Random(); int cantelemsborrar,puntero,cont; for (int i=0;i<cantFilas;i++) { cont=0; cantelemsborrar=rand.nextInt(cantFilas); while (cont<cantelemsborrar) { puntero=rand.nextInt(cantFilas); tablero[i][puntero]= new Celda(i,puntero); cont++; } } } }
package fr.doranco.ecommerce.vue; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.SessionScoped; @ManagedBean(name = "articleBean") @SessionScoped public class ArticleBean implements Serializable { private static final long serialVersionUID = 1L; private String articleId; @ManagedProperty(name = "nom", value = "") private String nom; @ManagedProperty(name = "description", value = "") private String description; @ManagedProperty(name = "prix", value = "") private String prix; @ManagedProperty(name = "remise", value = "") private String remise; @ManagedProperty(name = "stock", value = "") private String stock; @ManagedProperty(name = "isVendable", value = "") private String isVendable; }
package com.nks.whatsapp.event; import com.nks.whatsapp.Message; public interface ChatListener extends Listener{ public void messageAdded(Message message); }
package com.jiuzhe.app.hotel.service; import java.util.Map; /** * @Description:统计功能 */ public interface CountService { Map<String, String> getIndexCount(String merchantId, String storeId); Map getManageCountInfo(String storeId); }
package com.design.pattern; public class Client { public static void main(String arg[]) throws Exception { ConcretePrototype obj1 = new ConcretePrototype(); ConcretePrototype obj2 = (ConcretePrototype) obj1.clone(); System.out.println("Clone "+ obj1.hashCode()); System.out.println("Clone "+ obj2.hashCode()); } }
package com.xuecheng.order.mq; import com.xuecheng.framework.domain.task.XcTask; import com.xuecheng.order.config.RabbitMQConfig; import com.xuecheng.service.TaskService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; @Component @Slf4j public class ChooseCourseTask { @Autowired private TaskService taskService; //每隔1分钟扫描消息表,向mq发送消息 @Scheduled(cron = "0/3 * * * * *")//测试用3秒,实际用一分钟 //@Scheduled(cron = "* 0/1 * * * *")//测试用3秒,实际用一分钟 public void sendChoosecourseTask() { Calendar calendar = new GregorianCalendar(); calendar.setTime(new Date()); calendar.add(GregorianCalendar.MINUTE,-1); Date updateTime = calendar.getTime(); List<XcTask> taskList = taskService.findTaskList(updateTime, 100); for (XcTask xcTask : taskList) { //使用乐观锁解决集群部署时消息的重复发送 if (taskService.getTask(xcTask.getId(), xcTask.getVersion()) > 0) { //发送选课消息 taskService.publish(xcTask, xcTask.getMqExchange(), xcTask.getMqRoutingkey()); log.info("send choose course task id:{}",xcTask.getId()); } } } @RabbitListener(queues = RabbitMQConfig.XC_LEARNING_FINISHADDCHOOSECOURSE) public void receiveFinishChoosecourseTask(XcTask xcTask) { log.info("receiveChoosecourseTask...{}",xcTask.getId()); if (xcTask != null && StringUtils.isNotBlank(xcTask.getId())) { //添加历史任务 //删除任务 taskService.finishTask(xcTask.getId()); } } }
package com.canby.iterator.model; /** * Created by acanby on 8/10/2014. */ public abstract class AbstractEmployee { String employeeCode; String name; Address address; protected AbstractEmployee(String employeeCode, String name, Address address) { this.employeeCode = employeeCode; this.name = name; this.address = address; } public String getEmployeeCode() { return employeeCode; } public void setEmployeeCode(String employeeCode) { this.employeeCode = employeeCode; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } @Override public String toString() { return "AbstractEmployee{" + "employeeCode='" + employeeCode + '\'' + ", name='" + name + '\'' + ", address=" + address + '}'; } }
/* * 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.prakash.librarymanagement; import com.connection.ConnectionProvider; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.swing.JOptionPane; public class IssueBook extends javax.swing.JFrame { /** * Creates new form IssueBook */ public IssueBook() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); bookCallNoTxt = new javax.swing.JTextField(); studentIdTxt = new javax.swing.JTextField(); studentNameTxt = new javax.swing.JTextField(); studentContactTxt = new javax.swing.JTextField(); issueBookBtn = new javax.swing.JButton(); backBtn = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("ISSUE BOOK"); jLabel1.setFont(new java.awt.Font("Monospaced", 1, 24)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 51, 0)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("ISSUE BOOK"); jLabel1.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(0, 255, 255))); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 0, 51)); jLabel2.setText("Book Call No.:"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 0, 51)); jLabel3.setText("Student Id:"); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 0, 51)); jLabel4.setText("Student Name:"); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel5.setForeground(new java.awt.Color(255, 0, 51)); jLabel5.setText("Student Contact:"); issueBookBtn.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N issueBookBtn.setForeground(new java.awt.Color(255, 0, 51)); issueBookBtn.setText("Issue Book"); issueBookBtn.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); issueBookBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { issueBookBtnActionPerformed(evt); } }); backBtn.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N backBtn.setText("Back"); backBtn.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); backBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { backBtnActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGap(80, 80, 80) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(35, 35, 35) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(bookCallNoTxt) .addComponent(studentIdTxt) .addComponent(studentNameTxt) .addComponent(studentContactTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)) .addComponent(issueBookBtn)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 72, Short.MAX_VALUE) .addComponent(backBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(19, 19, 19) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(bookCallNoTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(studentIdTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(studentNameTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(studentContactTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(issueBookBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(backBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(63, Short.MAX_VALUE)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void backBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backBtnActionPerformed LibrarianSection librarianSection = new LibrarianSection(); this.hide(); librarianSection.show(); }//GEN-LAST:event_backBtnActionPerformed private void issueBookBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_issueBookBtnActionPerformed String bookCallNo = bookCallNoTxt.getText(); String studentId = studentIdTxt.getText(); String studentName = studentNameTxt.getText(); String studentContact = studentContactTxt.getText(); try { Connection con = ConnectionProvider.getConnection(); if (bookCallNo.isBlank() || studentId.isBlank() || studentName.isBlank() || studentContact.isBlank()) { JOptionPane.showMessageDialog(this, "One or more fields are empty."); } else { String query = "select callno from books"; PreparedStatement pstmt = con.prepareStatement(query); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { String callNo = rs.getString("callno"); if (!(bookCallNo.equals(callNo))) { JOptionPane.showMessageDialog(this, "Book Call no not found.Please try again..."); bookCallNoTxt.setText(""); studentIdTxt.setText(""); studentNameTxt.setText(""); studentContactTxt.setText(""); } else { String q2 = "insert into issuedbooks (bookcallno, studentid, studentname, studentcontact) values (?, ?, ?, ?)"; PreparedStatement ps = con.prepareStatement(q2); ps.setString(1, bookCallNo); ps.setString(2, studentId); ps.setString(3, studentName); ps.setString(4, studentContact); ps.execute(); String q3 = "update books set issued = issued+1 where callno = ?"; PreparedStatement ps2 = con.prepareStatement(q3); ps2.setString(1, bookCallNo); ps2.execute(); JOptionPane.showMessageDialog(this, "Book Issued successfully..."); LibrarianSection librarianSection = new LibrarianSection(); this.hide(); librarianSection.show(); } } } } catch (Exception e) { e.printStackTrace(); } }//GEN-LAST:event_issueBookBtnActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(IssueBook.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(IssueBook.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(IssueBook.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(IssueBook.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new IssueBook().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton backBtn; private javax.swing.JTextField bookCallNoTxt; private javax.swing.JButton issueBookBtn; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JTextField studentContactTxt; private javax.swing.JTextField studentIdTxt; private javax.swing.JTextField studentNameTxt; // End of variables declaration//GEN-END:variables }
package org.campus02.event; public class Demo_Event { public static void main(String[] args) { // TODO Auto-generated method stub Event event1 = new Event("Essen","Graz",15.0); Event event2 = new Event("Meeting","Wien",10.0); Event event3 = new Event("Meeting","Graz",10.0); Event event4 = new Event("Essen","Wien",20.0); Event event5 = new Event("Konzert","Linz",35.0); EventKalender test = new EventKalender(); test.add(event1); test.add(event2); test.add(event3); test.add(event4); test.add(event5); System.out.println(test.getByEintrittsPreis(10, 15)); System.out.println(test.getByOrt("Wien")); System.out.println(test.getByTitle("Meeting")); System.out.println(test.getMostExpensiveByOrt("Wien")); System.out.println(test.getAvgPreisByOrt("Wien")); System.out.println(test.getCountByOrt()); } }
package com.tencent.mm.plugin.cdndownloader.c; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.os.RemoteException; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.cdndownloader.a.b; import com.tencent.mm.plugin.cdndownloader.ipc.CDNTaskInfo; import com.tencent.mm.plugin.cdndownloader.ipc.CDNTaskState; import com.tencent.mm.plugin.cdndownloader.service.CDNDownloadService; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.al; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import java.util.Set; public final class a implements com.tencent.mm.ipcinvoker.wx_extension.b.a { private static a hJY; private long hJZ = 0; long hKa = 0; com.tencent.mm.plugin.cdndownloader.a.a hKb; Set<CDNTaskInfo> hKc = new com.tencent.mm.plugin.cdndownloader.d.a(new 1(this)); public b hKd; private ServiceConnection hKe = new ServiceConnection() { public final void onServiceConnected(ComponentName componentName, IBinder iBinder) { x.i("MicroMsg.CDNDownloadClient", "onServiceConnected"); a.this.hKb = com.tencent.mm.plugin.cdndownloader.a.a.a.H(iBinder); a aVar = a.this; try { x.i("MicroMsg.CDNDownloadClient", "registerCallback"); aVar.hKb.a(aVar.hKg); } catch (RemoteException e) { x.e("MicroMsg.CDNDownloadClient", "registerCallback: " + e.getMessage()); } a.c(a.this); } public final void onServiceDisconnected(ComponentName componentName) { x.i("MicroMsg.CDNDownloadClient", "onServiceDisconnected"); if (a.this.hKc.size() != 0) { for (CDNTaskInfo cDNTaskInfo : a.this.hKc) { cDNTaskInfo.hKp = true; } } } }; al hKf = new al(com.tencent.mm.bu.a.coq().getLooper(), new 3(this), true); b hKg = new 4(this); private com.tencent.mm.network.n.a hKh = new com.tencent.mm.network.n.a() { public final void ev(int i) { a aVar = a.this; x.i("MicroMsg.CDNDownloadClient", "notifyNetworkChange: " + i); if (aVar.hKb != null) { try { aVar.hKb.od(i); } catch (RemoteException e) { } } } }; private Context mContext = ad.getContext(); static /* synthetic */ void c(a aVar) { x.i("MicroMsg.CDNDownloadClient", "resumeTaskWhenSvrConnected"); if (aVar.hKc.size() > 0) { aVar.aAg(); } for (CDNTaskInfo cDNTaskInfo : aVar.hKc) { x.i("MicroMsg.CDNDownloadClient", "resumeTaskWhenSvrConnected, url: %s, resume: %b", new Object[]{cDNTaskInfo.downloadUrl, Boolean.valueOf(cDNTaskInfo.hKp)}); try { if (cDNTaskInfo.hKp) { aVar.hKb.b(cDNTaskInfo); } else { aVar.hKb.a(cDNTaskInfo); } } catch (RemoteException e) { x.e("MicroMsg.CDNDownloadClient", "resumeTaskWhenSvrConnected: " + e); h.mEJ.a(710, 0, 1, false); } } } public static synchronized a aAk() { a aVar; synchronized (a.class) { if (hJY == null) { hJY = new a(); } aVar = hJY; } return aVar; } public a() { g.Ek(); g.Eh().a(this.hKh); aAl(); } final synchronized void aAl() { try { x.i("MicroMsg.CDNDownloadClient", "bindService: " + this.mContext.bindService(new Intent(this.mContext, CDNDownloadService.class), this.hKe, 1)); } catch (Exception e) { x.e("MicroMsg.CDNDownloadClient", "bindService: " + e.getMessage()); } return; } public final int a(CDNTaskInfo cDNTaskInfo) { if (cDNTaskInfo == null || bi.oW(cDNTaskInfo.downloadUrl)) { x.w("MicroMsg.CDNDownloadClient", "addDownloadTask, info invalid"); return -1; } x.i("MicroMsg.CDNDownloadClient", "addDownloadTask filePath:%s, url:%s", new Object[]{cDNTaskInfo.filePath, cDNTaskInfo.downloadUrl}); if (this.hKc.contains(cDNTaskInfo)) { x.i("MicroMsg.CDNDownloadClient", "addDownloadTask, already in running"); return -2; } if (this.hKb != null) { try { int a = this.hKb.a(cDNTaskInfo); if (a == 0 || a == -2) { this.hKc.add(cDNTaskInfo); } return a; } catch (RemoteException e) { x.e("MicroMsg.CDNDownloadClient", "addDownloadTask, " + e.getMessage()); } } this.hKc.add(cDNTaskInfo); aAl(); return 0; } public final boolean yj(String str) { boolean z = false; x.i("MicroMsg.CDNDownloadClient", "pauseDownloadTask: " + str); if (bi.oW(str)) { x.w("MicroMsg.CDNDownloadClient", "pauseDownloadTask, url invalid"); return z; } if (this.hKb != null) { try { this.hKc.remove(new CDNTaskInfo(str)); return this.hKb.yj(str); } catch (RemoteException e) { x.e("MicroMsg.CDNDownloadClient", "pauseDownloadTask, " + e.getMessage()); } } x.i("MicroMsg.CDNDownloadClient", "pauseDownloadTask false, service interface is null"); return z; } public final int b(CDNTaskInfo cDNTaskInfo) { if (cDNTaskInfo == null || bi.oW(cDNTaskInfo.downloadUrl)) { x.w("MicroMsg.CDNDownloadClient", "resumeDownloadTask, info invalid"); return -1; } x.i("MicroMsg.CDNDownloadClient", "resumeDownloadTask: " + cDNTaskInfo.downloadUrl); cDNTaskInfo.hKp = true; if (this.hKb != null) { try { int b = this.hKb.b(cDNTaskInfo); if (b != 0 && b != -2) { return b; } this.hKc.add(cDNTaskInfo); return b; } catch (RemoteException e) { x.e("MicroMsg.CDNDownloadClient", "resumeDownloadTask, " + e.getMessage()); } } this.hKc.add(cDNTaskInfo); aAl(); return 0; } public final boolean yk(String str) { boolean z = false; x.i("MicroMsg.CDNDownloadClient", "removeDownloadTask: " + str); if (bi.oW(str)) { x.w("MicroMsg.CDNDownloadClient", "removeDownloadTask, url invalid"); return z; } if (this.hKb != null) { try { this.hKc.remove(new CDNTaskInfo(str)); return this.hKb.yk(str); } catch (RemoteException e) { x.e("MicroMsg.CDNDownloadClient", "removeDownloadTask, " + e.getMessage()); } } x.i("MicroMsg.CDNDownloadClient", "removeDownloadTask false, service interface is null"); return z; } public final CDNTaskState yl(String str) { CDNTaskState cDNTaskState = null; if (bi.oW(str)) { x.w("MicroMsg.CDNDownloadClient", "queryDownloadTask, url invalid"); return cDNTaskState; } else if (this.hKb == null) { return cDNTaskState; } else { try { return this.hKb.yl(str); } catch (RemoteException e) { x.e("MicroMsg.CDNDownloadClient", "queryDownloadTask, " + e.getMessage()); return cDNTaskState; } } } final void aAg() { if (this.hKb != null) { try { this.hKb.aAg(); } catch (RemoteException e) { x.e("MicroMsg.CDNDownloadClient", "addIPCTaskMarker: " + e); } } } }