text
stringlengths
10
2.72M
package com.xiaodao.generate.mapper; import com.xiaodao.generate.domain.GenTable; import com.xiaodao.generate.domain.GenTableColumn; import java.sql.SQLException; import java.util.List; import java.util.Set; /** * @Author gaolei * @Date 2019/10/11 23:28 * @Version 1.0 */ public interface IDataDao { /** * 获取所有的表格 * * @return */ Set<String> getAllTable() throws SQLException; /** * 获取表格注释 * * @param dataBase * @param tableName * @return */ String getTableComments(String dataBase, String tableName) throws SQLException; /** * 获取表格字段 * * @param tableName * @return */ List<GenTableColumn> getTableFileds(String tableName) throws SQLException; }
/** * Created by jason chou on 2016/11/3. */import java.util.Scanner; public class overscorejava { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); double g; //over all grade double t; // test double p; //programs double hw; // homework System.out.print("enter your test score"); t = keyboard.nextDouble(); System.out.print("entr your programs score"); p = keyboard.nextDouble(); System.out.print("enter your homework score"); hw = keyboard.nextDouble(); g = (0.3*t+0.3*p+0.4*hw); System.out.print("the result of overall grade is"+g); } }
package com.tencent.mm.plugin.exdevice.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import com.tencent.mm.plugin.exdevice.ui.ExdeviceAddDataSourceUI.10; class ExdeviceAddDataSourceUI$10$1 implements OnClickListener { final /* synthetic */ 10 iAr; ExdeviceAddDataSourceUI$10$1(10 10) { this.iAr = 10; } public final void onClick(DialogInterface dialogInterface, int i) { this.iAr.iAm.iAe.remove(this.iAr.iAq); this.iAr.iAm.iAd.aQ(this.iAr.iAm.iAe); this.iAr.iAm.iAd.notifyDataSetChanged(); } }
package com.rudecrab.springsecurity.model.vo; import lombok.Data; import java.util.Set; /** * @author RudeCrab */ @Data public class UserPageVO { private Long id; private String username; private Set<Long> roleIds; private Set<Long> companyIds; }
package ls.example.t.zero2line.util; public class UnitTextClass { private static UnitTextClass instance; public UnitTextClass (){ } public static UnitTextClass getInstance(){ if (instance==null){ synchronized (UnitTextClass.class){ if (instance==null){ instance=new UnitTextClass(); } } } return instance; } public float UnitTestOne(){ float index_first=1l; float random =(float) Math.random()*1l; float result = index_first / random; return result; } }
package com.miguelcr.picasso; import android.graphics.Typeface; import android.media.Image; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; public class MainActivity extends AppCompatActivity { ImageView starwarsTroop; TextView title; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); starwarsTroop = (ImageView) findViewById(R.id.ivStarWars); title = (TextView) findViewById(R.id.title); Picasso.with(MainActivity.this) .load("https://milnersblog.files.wordpress.com/2015/09/battle-stormtrooper-star-wars-ep7-the-force-awakens-characters-cut-out-with-transparent-background_31.png") //.resize(200, 200) .placeholder(R.drawable.ic_loading) .into(starwarsTroop); Typeface fontStarWars = Typeface.createFromAsset(getAssets(),"star_wars.ttf"); title.setTypeface(fontStarWars); } }
package application; import databaseApplication.DatabaseApp; import javafx.application.Application; import javafx.stage.Stage; //this class defines the form for adding a new client -- a new stage public class Launcher extends Application { @Override public void start(Stage primaryStage) throws Exception { DatabaseApp.estConnection(); MainView mainView = new MainView(primaryStage); /* * Stage stage = new Stage(); stage.setScene(new ItemsScene(new ItemsView())); * stage.show(); */ //new ItemFormStage(); } public static void main(String[] args) { launch(args); DatabaseApp.closeConnecton(); } }
/* * FileName: ExcelEngine.java * Description: * Company: 南宁超创信息工程有限公司 * Copyright: ChaoChuang (c) 2006 * History: 2006-1-5 (guig) 1.0 Create */ package com.spower.excel.engine; /** * @author guig * @version 1.0 2006-1-5 */ public interface ExcelConfig { ExcelEngine getExcelEngine(); }
public class Verre { int contenance; int volumeRempli; Verre( int contenance ) { // appel du constructeur qui a deux paramètre de type int this( contenance, 0 ); } Verre( int contenance, int volumeRempli ) { this.contenance = contenance; ajouter( volumeRempli ); } // on verse volumeVerseDansLeVerre cl dans le verre, // éventuellement ca déborde void ajouter( int volumeVerseDansLeVerre ) { volumeRempli += volumeVerseDansLeVerre; if( volumeRempli > contenance ) volumeRempli = contenance; } // on penche le verre jusqu'à avoir fait couler 'volumeQueOnVeutVider' cl // ou bien que le verre soit vide // la méthode retourne le volume d'eau qui s'est réellement échappé du verre int vider( int volumeQueOnVeutVider ) { if( volumeQueOnVeutVider > volumeRempli ) volumeQueOnVeutVider = volumeRempli; volumeRempli -= volumeQueOnVeutVider; return volumeQueOnVeutVider; } }
/* * 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.banda.employeeapp; /** * * @author : Banda. B * @studentNo : 212195166 * @group : 3A * @version : 1.0 * */ public class Employee implements Comparable{ private int employeeID; private String name; private String surname; private String phoneNumber; private double monthlySalary; private int age; public Employee() { } public Employee(int employeeID, String name, String surname, String phoneNumber, double monthlySalary, int age) { this.employeeID = employeeID; this.name = name; this.surname = surname; this.phoneNumber = phoneNumber; this.monthlySalary = monthlySalary; this.age = age; } public int getEmployeeID() { return employeeID; } public void setEmployeeID(int employeeID) { this.employeeID = employeeID; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public double getMonthlySalary() { return monthlySalary; } public void setMonthlySalary(double monthlySalary) { this.monthlySalary = monthlySalary; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int compareTo(Object o) { Employee emp = (Employee) o; return (this.employeeID - emp.employeeID); } @Override public int hashCode() { int hash = 3; hash = 29 * hash + this.employeeID; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Employee other = (Employee) obj; if (this.employeeID != other.employeeID) { return false; } if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } if ((this.surname == null) ? (other.surname != null) : !this.surname.equals(other.surname)) { return false; } if ((this.phoneNumber == null) ? (other.phoneNumber != null) : !this.phoneNumber.equals(other.phoneNumber)) { return false; } if (Double.doubleToLongBits(this.monthlySalary) != Double.doubleToLongBits(other.monthlySalary)) { return false; } if (this.age != other.age) { return false; } return true; } @Override public String toString() { return "\n******* Employee Information ********" + "\nFirst Name = " + name + "\nLast Name = " + surname + "\nEmployee ID = " + employeeID + "\nPhone Number = " + phoneNumber + "\nMonthly Salary = " + monthlySalary + "\nAge = " + age + "\n"; } }
package com.example.nhom11.controller; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.example.nhom11.dao.CustomerDAOTuan; import com.example.nhom11.dao.impl.CustomerDAOTuanImpl; import com.example.nhom11.model.Account; import com.example.nhom11.model.Customer; import com.example.nhom11.model.Role; import com.example.nhom11.utils.RestGoogleUtil; import com.google.gson.Gson; import com.google.gson.JsonObject; @WebServlet(urlPatterns = "/login-google") public class LoginGoogleController extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String code = req.getParameter("code"); if (code == null || code.isEmpty()) { RequestDispatcher dis = req.getRequestDispatcher("login.jsp"); dis.forward(req, resp); } else { //Lay thong tin Customer String accessToken = RestGoogleUtil.getToken(code); String u = RestGoogleUtil.getUserInJson(accessToken); JsonObject jo = new Gson().fromJson(u, JsonObject.class); Account a = new Account(0, null, null, jo.get("id").getAsString(), null, Role.CUSTOMER); Customer c = new Customer(0, jo.get("name").getAsString(), null, jo.get("email").getAsString(), null, null, a); CustomerDAOTuan cd = new CustomerDAOTuanImpl(); long customerId = cd.checkIfGoogleAccountExist(c.getAccount().getGoogleId()); if (customerId == 0) { // Customer chua co tai khoan trong he thong c = cd.add(c); //Them Customer vao he thong if (c.getId() > 0) { // Them thanh cong // Them Customer vao Session HttpSession session = req.getSession(); session.setAttribute("person", c); resp.sendRedirect(req.getContextPath()+"/"); } else { // Them that bai req.setAttribute("notification", "Tài khoản đã tồn tại"); req.getRequestDispatcher("login.jsp").forward(req, resp); ; } } else { //Customer da co tai khoan trong he thong c.setId(customerId); HttpSession session = req.getSession(); session.setAttribute("person", c); resp.sendRedirect(req.getContextPath()+"/"); } } } }
package co.aurasphere.courseware.j2ee.spring.boot.webflux; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @RestController @RequestMapping("/courseware") public class CoursewareWebfluxController { @GetMapping("/list") public Flux<ControllerResponse> getWebfluxList(@RequestParam("size") Integer listSize) { List<ControllerResponse> elementsList = Stream.generate(ControllerResponse::new).limit(listSize) .collect(Collectors.toList()); return Flux.fromIterable(elementsList); } @GetMapping("/single") public Mono<ControllerResponse> getWebfluxSingleElement() { return Mono.fromSupplier(ControllerResponse::new); } }
package solution; /** * User: jieyu * Date: 10/13/16. */ public class ValidPalindrome125 { public boolean isPalindrome(String s) { String str = s.toLowerCase(); int low = 0, high = str.length() - 1; while (low < high) { if ((str.charAt(low) < '0' || str.charAt(low) > '9') && (str.charAt(low) < 'a' || str.charAt(low) > 'z')) { low++; continue; } if ((str.charAt(high) < '0' || str.charAt(high) > '9') && (str.charAt(high) < 'a' || str.charAt(high) > 'z')) { high--; continue; } if (str.charAt(low) != str.charAt(high)) return false; low++; high--; } return true; } public static void main(String[] args) { ValidPalindrome125 vp = new ValidPalindrome125(); vp.isPalindrome("ab@a"); } }
package BLL.Polish; import DAL.DAL_Factory; import DAL.Polish.DAL_Polish; import basicas.polish.Polish; public class BLL_Polish { public void insert(Polish p) throws Exception { DAL_Polish dao = DAL_Factory.getDAL_Polish(); // validações if (p.getName().trim().equals("")) { throw new Exception("Informe o NOME"); } if (p.getBrand() == null) { throw new Exception("Selecione uma MARCA"); } // /*Polish teste = dao.findByName(p.getName()); if (teste != null && teste.getBrand().getName() == p.getBrand().getName()) { throw new Exception( "Ja existe esmalte desta marca e nome no sistema"); }*/ if (p.getFinish() == null) { throw new Exception("Selecione um ACABAMENTO"); } if (p.getColor().trim().equals("")) { throw new Exception("Informe a COR"); } dao.insert(p); } public Polish update(Polish p) throws Exception { DAL_Polish dao = DAL_Factory.getDAL_Polish(); // validações if (p.getName().trim().equals("")) { throw new Exception("Informe o NOME"); } if (p.getBrand() == null) { throw new Exception("Selecione uma MARCA"); } // Polish teste = dao.findByName(p.getName()); if (teste != null && teste.getId() != p.getId() && teste.getBrand().getName() == p.getBrand().getName()) { throw new Exception( "Ja existe esmalte desta marca e nome no sistema"); } if (p.getFinish() == null) { throw new Exception("Selecione um ACABAMENTO"); } if (p.getColor().trim().equals("")) { throw new Exception("Informe a COR"); } return dao.update(p); } public void delete(Polish obj) throws Exception { DAL_Polish dao = DAL_Factory.getDAL_Polish(); if (obj == null) { throw new Exception("Selecione um esmalte válido a ser excluído"); } dao.delete(obj); } }
package com.training.ee.ejb; import javax.ejb.LocalBean; import javax.ejb.Stateless; @Stateless @LocalBean public class MyStateless { // private int toplam; public MyStateless() { } public int calcAdd(final int a, final int b) { int tempTotal = a + b; // this.toplam += tempTotal; return tempTotal; } public int calcSubstract(final int a, final int b) { int tempTotal = a - b; // this.toplam += tempTotal; return tempTotal; } }
package com.ssm.lab.test; import com.ssm.lab.bean.ExperimentWorkload; import com.ssm.lab.bean.ExperimentWorkloadItem; import com.ssm.lab.dao.ExperimentWorkloadItemMapper; import com.ssm.lab.dao.ExperimentWorkloadMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:applicationContext.xml"}) public class ExperimentWorkloadItemMapperTest { @Autowired ExperimentWorkloadItemMapper mapper; @Test public void getAll() { List<ExperimentWorkloadItem> items = mapper.selectByExample(null); for (ExperimentWorkloadItem item : items) { System.out.println(item.getTeacher().getUserName() + " " + item.getTeacherWorkload()); } } @Test public void getById() { ExperimentWorkloadItem item = mapper.selectByPrimaryKey(1); System.out.println(item.getTeacher().getUserName() + " " + item.getTeacherWorkload()); } @Test public void getByExperimentWorkloadId() { List<ExperimentWorkloadItem> items = mapper.selectByExperimentWorkloadId(1); for (ExperimentWorkloadItem item : items) { System.out.println(item.getTeacher().getUserName() + " " + item.getTeacherWorkload()); } } }
package in.hocg.app.dao; import in.hocg.app.bean.MessageBoardBean; import in.hocg.defaults.base.dao.SoftDeletedDao; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; /** * Created by hocgin on 16-12-23. */ @Repository @Transactional public class MessageBoardDao extends SoftDeletedDao<MessageBoardBean> { }
package kyle.game.besiege.party; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; public class ClickListenerWithHover extends ClickListener { Label label; public ClickListenerWithHover(Label label) { this.label = label; } @Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { return true; } @Override public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) { if (label.getActions().size == 0) { label.setColor(Color.LIGHT_GRAY); } } @Override public void exit(InputEvent event, float x, float y, int pointer, Actor toActor) { if (label.getActions().size == 0) { label.setColor(Color.WHITE); } } }
package com.jim.multipos.ui.start_configuration.currency; import com.jim.multipos.core.Presenter; public interface CurrencyPresenter extends Presenter { void initCurrency(); void setCurrency(int position); void setAppRunFirstTimeValue(boolean state); }
package jzoffer; import java.util.ArrayList; /** * 从尾到头打印链表 * * 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。 * @author ZhaoJun * @date 2019/8/12 15:30 */ public class Solution3 { public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ArrayList<Integer> result = new ArrayList<>(); generate(listNode,result); return result; } private void generate(ListNode listNode, ArrayList<Integer> result) { if (listNode != null) { generate(listNode.next, result); result.add(listNode.val); } } public static class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } }
package corgi.hub.core.mqtt.common; import corgi.hub.core.mqtt.bean.HubSession; /** * Created by Terry LIANG on 2017/1/7. */ public interface HubContext { HubSession getSession(String clientId); boolean sessionExist(String clientId); void putSession(String clientId, HubSession session); HubSession remove(String clientId); ISubscriptionManager getSubscriptionManager(); String getNodeName(); }
package enthu_leitner; public class e_1164 { public static void main(String[] args) { System.out.println("a"+'b'+63); System.out.println("a"+63); System.out.println('b'+new Integer(63)); String s = 'b'+63+"a"; String s = 63 + new Integer(10); } }
package com.sourceit.converter.jaxb; import com.sourceit.entity.Department; import com.sourceit.entity.Employee; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.File; import java.util.LinkedHashMap; public class JaxbConverter { public static File JAXB_RESULT = new File("XML_Result\\JAXB_Result.xml"); public static File JAXB_INPUT = new File("XML_Result\\JAXB_Input.xml"); public static void convertObjectToXML(Object input) { try { JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class, Department.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(input, System.out); marshaller.marshal(input, JAXB_RESULT); } catch (Exception e) { e.printStackTrace(); } } public static void convertObjectsToXML(Object input) { try { JAXBContext jaxbContext = JAXBContext.newInstance(EmployeeList.class, DepartmentList.class, LinkedHashMap.class, DepartmentsWithEmployeesList.class, DepartmentWithEmployees.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(input, JAXB_RESULT); } catch (Exception e) { e.printStackTrace(); } } public static DepartmentsWithEmployeesList convertXmlToObjects(File inputFile) { DepartmentsWithEmployeesList result = null; try { JAXBContext jaxbContext = JAXBContext.newInstance(EmployeeList.class, DepartmentList.class, LinkedHashMap.class, DepartmentsWithEmployeesList.class, DepartmentWithEmployees.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); result = (DepartmentsWithEmployeesList) unmarshaller.unmarshal(inputFile); } catch (Exception e) { e.printStackTrace(); } return result; } public static Object convertXmlToObject(File inputFile) { Object result = new Employee(); try { JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); result = unmarshaller.unmarshal(inputFile); } catch (Exception e) { e.printStackTrace(); } return result; } }
package com.smxknife.java.ex1; public class OddDemo1 { public static void main(String[] args) { for (int i = -10; i < 10; i++) { output(i); } } public static void output(int i) { System.out.print(i + " isOdd : "); System.out.print(isOdd(i)); System.out.print(" , isEven : "); System.out.println(isEven(i)); } public static boolean isOdd(int i) { return i % 2 == 1; } public static boolean isEven(int i) { return i % 2 == 0; } }
/* * 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.ngrinder.recorder.browser; import java.util.Set; import com.teamdev.jxbrowser.security.HttpSecurityAction; import com.teamdev.jxbrowser.security.HttpSecurityHandler; import com.teamdev.jxbrowser.security.SecurityProblem; /** * {@link HttpSecurityHandler} instance which will ignore all the security problems the browser * emits. * * @author JunHo Yoon * @since 1.0 */ public class SilentSecurityHandler implements HttpSecurityHandler { @Override public HttpSecurityAction onSecurityProblem(Set<SecurityProblem> problems) { return HttpSecurityAction.CONTINUE; } }
package org.five.ticket.service.bulider.ticket; import org.five.ticket.entity.ticket.TicketEntity; import org.five.ticket.service.bulider.ticket.AbstractTicketBulider; import org.five.ticket.vo.TicketVo; public class MovieDisplayTicketBulider extends AbstractTicketBulider { @Override public TicketEntity buildTicket(TicketVo ticketVo) { return null; } }
package com.finddreams.androidnewstack.service; /** * Created by lx on 17-11-13. */ public interface StockService { }
package com.encore.rest.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.encore.rest.service.BookService; import com.encore.rest.vo.Book; @RestController @RequestMapping("api") public class BookRestController { @Autowired private BookService bookService; //http://127.0.0.1:8888/rest/api/book @GetMapping("book") public ResponseEntity<List<Book>> getAllBook() throws Exception{ List<Book> books = bookService.getBooks(); if(books.isEmpty()) return new ResponseEntity(HttpStatus.NO_CONTENT); else return new ResponseEntity(books,HttpStatus.OK); } // 특정한 isbn에 해당하는 책 1권을 받아오는 요청을 작성 //http://127.0.0.1:8888/rest/api/book/1233-111-111 @GetMapping("book/{isbn}") public ResponseEntity<Book> getBookByIsbn(@PathVariable String isbn) throws Exception{ Book book = bookService.searchByIsbn(isbn); if(book==null) return new ResponseEntity(HttpStatus.NO_CONTENT); else return new ResponseEntity(book,HttpStatus.OK); } //특정한 책을 등록하는 기능..insert..doPost() @PostMapping("book") public ResponseEntity<Book> insertBook(@RequestBody Book book) throws Exception{ boolean check = bookService.insertBook(book); if(!check) return new ResponseEntity(HttpStatus.NO_CONTENT); else return new ResponseEntity(HttpStatus.OK); } /* * Post Man은 Rest API 서버 개발자들이 INSERT(@PostMapping), DELETE(@DeleteMapping),UPDATE(@PutMapping) * 코드 작성시 확인하기 위한 클라이언트 Tool이다. * * DML에 해당하는 코드는 화면으로 데이터를 입력하고 * 그결과를 확인해야 하기 때문에 이런 클라이언트 Tool이 필요하다. * * 하지만, 최종적으로는 Seweager를 만들어서 클라이언트 개발자들에게 배포하는것 이 * Restful API 서버사이드 개발자가 사용한다 */ //특정한 책을 수정하는 기능..update..doPut() @PutMapping("book") public ResponseEntity<Book> updateBook(@RequestBody Book book) throws Exception{ boolean check = bookService.update(book); if(!check) return new ResponseEntity(HttpStatus.NO_CONTENT); else return new ResponseEntity(HttpStatus.OK); } //특정한 책을 삭제하는 기능..delete..doDelete() @DeleteMapping("book/{isbn}") public ResponseEntity<List<Book>> deleteBook(@PathVariable String isbn) throws Exception{ boolean check = bookService.delete(isbn); if(!check) return new ResponseEntity<List<Book>>(HttpStatus.NO_CONTENT); else return new ResponseEntity<List<Book>>(HttpStatus.OK); } }
package com.programacion.movil.estemanp.androidmvcapplication; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.programacion.movil.estemanp.androidmvcapplication.View.EventListActivity; import com.programacion.movil.estemanp.androidmvcapplication.View.LandingActivity; public class OptionActivity extends AppCompatActivity { Button btnList, btnMap, btnNotification; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_option); btnList = (Button)findViewById(R.id.btnListaEventos); btnMap = (Button)findViewById(R.id.btnMaps); btnNotification = (Button)findViewById(R.id.btnNotifications); btnList.setOnClickListener(new View.OnClickListener(){ public void onClick(View arg0){ Intent intent = new Intent(OptionActivity.this,EventListActivity.class); startActivity(intent); } }); btnMap.setOnClickListener(new View.OnClickListener(){ public void onClick(View arg0){ Intent intent = new Intent(OptionActivity.this,MapsActivity.class); startActivity(intent); } }); btnNotification.setOnClickListener(new View.OnClickListener(){ public void onClick(View arg0){ Intent intent = new Intent(OptionActivity.this,MapsActivity.class); startActivity(intent); } }); } }
/* * Copyright 2013 Cloudera Inc. * * 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.kitesdk.data.filesystem; import au.com.bytecode.opencsv.CSVReader; import org.kitesdk.data.DatasetDescriptor; import org.kitesdk.data.DatasetReaderException; import org.kitesdk.data.spi.AbstractDatasetReader; import org.kitesdk.data.spi.ReaderWriterState; import com.google.common.base.Preconditions; import org.apache.avro.Schema; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericRecord; import org.apache.avro.generic.IndexedRecord; import org.apache.avro.reflect.ReflectData; import org.apache.avro.specific.SpecificData; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.nio.charset.Charset; import java.util.Locale; import java.util.NoSuchElementException; class CSVFileReader<E> extends AbstractDatasetReader<E> { private static final Logger logger = LoggerFactory .getLogger(CSVFileReader.class); public static final String CHARSET_PROPERTY = "kite.csv.charset"; public static final String DELIMITER_PROPERTY = "kite.csv.delimiter"; public static final String QUOTE_CHAR_PROPERTY = "kite.csv.quote-char"; public static final String ESCAPE_CHAR_PROPERTY = "kite.csv.escape-char"; public static final String LINES_TO_SKIP_PROPERTY = "kite.csv.lines-to-skip"; // old properties public static final String OLD_CHARSET_PROPERTY = "cdk.csv.charset"; public static final String OLD_DELIMITER_PROPERTY = "cdk.csv.delimiter"; public static final String OLD_QUOTE_CHAR_PROPERTY = "cdk.csv.quote-char"; public static final String OLD_ESCAPE_CHAR_PROPERTY = "cdk.csv.escape-char"; public static final String OLD_LINES_TO_SKIP_PROPERTY = "cdk.csv.lines-to-skip"; public static final String DEFAULT_CHARSET = "utf8"; public static final String DEFAULT_DELIMITER = ","; public static final String DEFAULT_QUOTE = "\""; public static final String DEFAULT_ESCAPE = "\\"; public static final int DEFAULT_LINES_TO_SKIP = 0; private final FileSystem fs; private final Path path; private final Schema schema; // configuration private final String charset; private final String delimiter; private final String quote; private final String escape; private final int linesToSkip; private Class<E> recordClass = null; private CSVReader reader = null; // state private ReaderWriterState state = ReaderWriterState.NEW; private boolean hasNext = false; private String[] next = null; public CSVFileReader(FileSystem fileSystem, Path path, DatasetDescriptor descriptor) { this.fs = fileSystem; this.path = path; this.schema = descriptor.getSchema(); this.state = ReaderWriterState.NEW; Schema schema = descriptor.getSchema(); Preconditions.checkArgument(Schema.Type.RECORD.equals(schema.getType()), "Schemas for CSV files must be records of primitive types"); this.charset = coalesce( descriptor.getProperty(CHARSET_PROPERTY), descriptor.getProperty(OLD_CHARSET_PROPERTY), DEFAULT_CHARSET); this.delimiter= coalesce( descriptor.getProperty(DELIMITER_PROPERTY), descriptor.getProperty(OLD_DELIMITER_PROPERTY), DEFAULT_DELIMITER); this.quote = coalesce( descriptor.getProperty(QUOTE_CHAR_PROPERTY), descriptor.getProperty(OLD_QUOTE_CHAR_PROPERTY), DEFAULT_QUOTE); this.escape = coalesce( descriptor.getProperty(ESCAPE_CHAR_PROPERTY), descriptor.getProperty(OLD_ESCAPE_CHAR_PROPERTY), DEFAULT_ESCAPE); final String linesToSkipString = coalesce( descriptor.getProperty(LINES_TO_SKIP_PROPERTY), descriptor.getProperty(OLD_LINES_TO_SKIP_PROPERTY)); int lines = DEFAULT_LINES_TO_SKIP; if (linesToSkipString != null) { try { lines = Integer.valueOf(linesToSkipString); } catch (NumberFormatException ex) { logger.debug("Defaulting lines to skip, failed to parse: {}", linesToSkipString); // lines remains set to the default } } this.linesToSkip = lines; } /** * Returns the first non-null value from the sequence or null if there is no * non-null value. */ private static <T> T coalesce(T... values) { for (T value : values) { if (value != null) { return value; } } return null; } @Override @SuppressWarnings("unchecked") public void open() { Preconditions.checkState(state.equals(ReaderWriterState.NEW), "A reader may not be opened more than once - current state:%s", state); // may be null if not using specific records this.recordClass = SpecificData.get().getClass(schema); FSDataInputStream incoming; try { incoming = fs.open(path); } catch (IOException ex) { throw new DatasetReaderException("Cannot open path: " + path, ex); } this.reader = new CSVReader( new InputStreamReader(incoming, Charset.forName(charset)), delimiter.charAt(0), quote.charAt(0), escape.charAt(0), linesToSkip, false /* strict quotes off: don't ignore unquoted strings */, true /* ignore leading white-space */ ); // initialize by reading the first record this.hasNext = advance(); this.state = ReaderWriterState.OPEN; } @Override public boolean hasNext() { Preconditions.checkState(state.equals(ReaderWriterState.OPEN), "Attempt to read from a file in state:%s", state); return hasNext; } @Override public E next() { Preconditions.checkState(state.equals(ReaderWriterState.OPEN), "Attempt to read from a file in state:%s", state); if (!hasNext) { throw new NoSuchElementException(); } try { E record = makeRecord(); return record; } finally { this.hasNext = advance(); } } private boolean advance() { try { next = reader.readNext(); } catch (IOException ex) { throw new DatasetReaderException("Could not read record", ex); } return (next != null); } @Override public void close() { if (!state.equals(ReaderWriterState.OPEN)) { return; } logger.debug("Closing reader on path:{}", path); try { reader.close(); } catch (IOException e) { throw new DatasetReaderException("Unable to close reader path:" + path, e); } state = ReaderWriterState.CLOSED; } @Override public boolean isOpen() { return (this.state == ReaderWriterState.OPEN); } private E makeRecord() { if (recordClass != null) { E record = makeReflectRecord(); if (record != null) { return record; } } return makeGenericRecord(); } @SuppressWarnings("unchecked") private E makeGenericRecord() { GenericRecord record = new GenericData.Record(schema); fillIndexed(record, next); return (E) record; } @SuppressWarnings("unchecked") private E makeReflectRecord() { E record = (E) ReflectData.get().newInstance(recordClass, schema); if (record instanceof IndexedRecord) { fillIndexed((IndexedRecord) record, next); } else { fillReflect(record, next, schema); } return record; } private static void fillIndexed(IndexedRecord record, String[] data) { Schema schema = record.getSchema(); for (int i = 0, n = schema.getFields().size(); i < n; i += 1) { final Schema.Field field = schema.getFields().get(i); if (i < data.length) { record.put(i, makeValue(data[i], field)); } else { record.put(i, makeValue(null, field)); } } } private static void fillReflect(Object record, String[] data, Schema schema) { for (int i = 0, n = schema.getFields().size(); i < n; i += 1) { final Schema.Field field = schema.getFields().get(i); final Object value = makeValue(i < data.length ? data[i] : null, field); try { final PropertyDescriptor propertyDescriptor = new PropertyDescriptor( field.name(), record.getClass(), null, setter(field.name())); propertyDescriptor.getWriteMethod().invoke(record, value); } catch (IntrospectionException ex) { throw new IllegalStateException("Cannot set property " + field.name() + " on " + record.getClass().getName(), ex); } catch (InvocationTargetException ex) { throw new IllegalStateException("Cannot set property " + field.name() + " on " + record.getClass().getName(), ex); } catch (IllegalAccessException ex) { throw new IllegalStateException("Cannot set property " + field.name() + " on " + record.getClass().getName(), ex); } } } private static String setter(String name) { return "set" + name.substring(0, 1).toUpperCase(Locale.ENGLISH) + name.substring(1); } private static Object makeValue(String string, Schema.Field field) { Object value = makeValue(string, field.schema()); if (value != null || nullOk(field.schema())) { return value; } else { // this will fail if there is no default value return ReflectData.get().getDefaultValue(field); } } /** * Returns a the value as the first matching schema type or null. * * Note that if the value may be null even if the schema does not allow the * value to be null. * * @param string a String representation of the value * @param schema a Schema * @return the string coerced to the correct type from the schema or null */ private static Object makeValue(String string, Schema schema) { if (string == null) { return null; } try { switch (schema.getType()) { case BOOLEAN: return Boolean.valueOf(string); case STRING: return string; case FLOAT: return Float.valueOf(string); case DOUBLE: return Double.valueOf(string); case INT: return Integer.valueOf(string); case LONG: return Long.valueOf(string); case ENUM: // TODO: translate to enum class if (schema.hasEnumSymbol(string)) { return string; } else { try { return schema.getEnumSymbols().get(Integer.valueOf(string)); } catch (IndexOutOfBoundsException ex) { return null; } } case UNION: Object value = null; for (Schema possible : schema.getTypes()) { value = makeValue(string, possible); if (value != null) { return value; } } return null; default: // FIXED, BYTES, MAP, ARRAY, RECORD are not supported throw new DatasetReaderException( "Unsupported field type:" + schema.getType()); } } catch (NumberFormatException ex) { return null; } } /** * Returns whether null is allowed by the schema. * * @param schema a Schema * @return true if schema allows the value to be null */ private static boolean nullOk(Schema schema) { if (Schema.Type.NULL == schema.getType()) { return true; } else if (Schema.Type.UNION == schema.getType()) { for (Schema possible : schema.getTypes()) { if (nullOk(possible)) { return true; } } } return false; } }
package am.repository; import am.data.hibernate.model.apps.ApplicationQuota; import am.data.hibernate.model.apps.RegisteredApplication; import am.main.api.AppLogger; import am.main.api.db.DBManager; import am.main.session.AppSession; import javax.inject.Inject; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Map; /** * Created by ahmed.motair on 2/6/2018. */ public class ApplicationRepository { private final String CLASS = ApplicationRepository.class.getSimpleName(); @Inject private DBManager dbManager; @Inject private AppLogger logger; public RegisteredApplication getRegisteredAppByID(AppSession appSession, String appID) throws Exception{ String METHOD = "getRegisteredAppByID"; AppSession session = appSession.updateSession(CLASS, METHOD); logger.startDebug(session, appID); Map<String, Object> parameters = new HashMap<>(); parameters.put(RegisteredApplication.APP_ID, appID); RegisteredApplication application = dbManager.getSingleResult(session, true, RegisteredApplication.class, parameters); logger.endDebug(session, application); return application; } public RegisteredApplication getRegAppByUsername(AppSession appSession, String username) throws Exception{ String METHOD = "getRegAppByUsername"; AppSession session = appSession.updateSession(CLASS, METHOD); logger.startDebug(session, username); Map<String, Object> parameters = new HashMap<>(); parameters.put(RegisteredApplication.USER_NAME, username); RegisteredApplication application = dbManager.getSingleResult(session, true, RegisteredApplication.class, parameters); logger.endDebug(session, application); return application; } public ApplicationQuota getApplicationTodayQuota(AppSession appSession, String appID) throws Exception{ String METHOD = "getApplicationTodayQuota"; AppSession session = appSession.updateSession(CLASS, METHOD); logger.startDebug(session, appID); Map<String, Object> parameters = new HashMap<>(); parameters.put(ApplicationQuota.APP_ID, appID); parameters.put(ApplicationQuota.QUOTA_DATE, new SimpleDateFormat("yyyy-MM-dd")); ApplicationQuota quota = dbManager.getSingleResult(session, true, ApplicationQuota.class, parameters); logger.endDebug(session, quota); return quota; } }
package com.example.anusha.newsapi; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.LoaderManager; import android.support.v4.content.AsyncTaskLoader; import android.support.v4.content.Loader; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<String> { ProgressBar pb; RecyclerView rv; ArrayList<NewsModel> newsModels; final static int ID=123; String news="https://newsapi.org/v2/everything?q=bitcoin&apiKey=1503739161854d7b9d37ed4de68142b5"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rv=findViewById(R.id.recycler); pb = findViewById(R.id.progressBar); newsModels=new ArrayList<>(); rv.setLayoutManager(new GridLayoutManager(this,2)); rv.setAdapter(new NewsAdapter(this,newsModels) ); // new NewsTasks().execute(); getSupportLoaderManager().initLoader(ID,null,this); } @NonNull @Override public Loader<String> onCreateLoader(int i, @Nullable Bundle bundle) { return new AsyncTaskLoader<String>(this) { @Nullable @Override public String loadInBackground() { try { URL url = new URL(news); Log.i("newsapi",url.toString()); HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); InputStream is =urlConnection.getInputStream(); BufferedReader reader=new BufferedReader(new InputStreamReader(is)); StringBuilder builder = new StringBuilder(); String l=""; while ((l=reader.readLine())!=null){ builder.append(l); } return builder.toString(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onStartLoading() { super.onStartLoading(); forceLoad(); pb.setVisibility(View.VISIBLE); } }; } @Override public void onLoadFinished(@NonNull Loader<String> loader, String data) { pb.setVisibility(View.GONE); //newsModels = new ArrayList<>(); Toast.makeText(MainActivity.this, ""+data, Toast.LENGTH_SHORT).show(); if (data!=null){ try { JSONObject jsonObject = new JSONObject(data); JSONArray jsonArray = jsonObject.getJSONArray("articles"); for (int i=0;i<jsonArray.length();i++){ JSONObject newsinfo=jsonArray.getJSONObject(i); String title=newsinfo.getString("title"); Log.i("newsapi",title); String desc=newsinfo.getString("description"); Log.i("newsapi",desc); String img=newsinfo.getString("urlToImage"); Log.i("newsapi",img); Toast.makeText(MainActivity.this, title+"\n"+desc+"\n"+img, Toast.LENGTH_SHORT).show(); // Toast.makeText(MainActivity.this, BookTitle+"\n"+BookDescription+"\n"+BookImage, Toast.LENGTH_SHORT).show(); newsModels.add(new NewsModel(title,img,desc)); } } catch (JSONException e) { e.printStackTrace(); } // rv.setLayoutManager(new LinearLayoutManager(getApplicationContext())); //rv.setAdapter(new NewsAdapter(this,newsModels) ); //rv.setAdapter(new NewsAdapter(getApplicationContext(),newsModels)); } } @Override public void onLoaderReset(@NonNull Loader<String> loader) { } /* public class NewsTasks extends AsyncTask<String,Void,String>{ @Override protected void onPreExecute() { super.onPreExecute(); pb.setVisibility(View.VISIBLE); } @Override protected String doInBackground(String... strings) { try { URL url = new URL(news); Log.i("newsapi",url.toString()); HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); InputStream is =urlConnection.getInputStream(); BufferedReader reader=new BufferedReader(new InputStreamReader(is)); StringBuilder builder = new StringBuilder(); String l=""; while ((l=reader.readLine())!=null){ builder.append(l); } return builder.toString(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); pb.setVisibility(View.GONE); //newsModels = new ArrayList<>(); Toast.makeText(MainActivity.this, ""+s, Toast.LENGTH_SHORT).show(); if (s!=null){ try { JSONObject jsonObject = new JSONObject(s); JSONArray jsonArray = jsonObject.getJSONArray("articles"); for (int i=0;i<jsonArray.length();i++){ JSONObject newsinfo=jsonArray.getJSONObject(i); String title=newsinfo.getString("title"); Log.i("newsapi",title); String desc=newsinfo.getString("description"); Log.i("newsapi",desc); String img=newsinfo.getString("urlToImage"); Log.i("newsapi",img); Toast.makeText(MainActivity.this, title+"\n"+desc+"\n"+img, Toast.LENGTH_SHORT).show(); // Toast.makeText(MainActivity.this, BookTitle+"\n"+BookDescription+"\n"+BookImage, Toast.LENGTH_SHORT).show(); newsModels.add(new NewsModel(title,img,desc)); } } catch (JSONException e) { e.printStackTrace(); } // rv.setLayoutManager(new LinearLayoutManager(getApplicationContext())); //rv.setAdapter(new NewsAdapter(this,newsModels) ); //rv.setAdapter(new NewsAdapter(getApplicationContext(),newsModels)); } } } */ }
package com.future.msuser.controller; import com.future.msuser.auth.Login; import com.future.msuser.domain.dto.UserLoginDTO; import com.future.msuser.domain.entity.User; import com.future.msuser.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; /** * @Date 2019/11/15 17:51 */ @RestController public class UserController { @Autowired private UserService userService; /** * 1. 如果用户没有登录,那么返回http 401 * 2. 如果已经登录了,那么正常访问 * 使用AOP 实现登录状态校验 * @param id * @return */ @Login @GetMapping("/users/{id}") public User findById(@PathVariable Integer id){ return this.userService.findById(id); } @PostMapping("/login") public String login(@RequestBody UserLoginDTO loginDTO){ return this.userService.login(loginDTO); } }
package scriptinterface.execution.returnvalues; public class ExecutionWrongArgCount extends ExecutionError { private int expectedArgNr, givenArgNr; public ExecutionWrongArgCount(int expectedArgNr, int givenArgNr) { super("WRONG_ARGUMENT_COUNT"); this.expectedArgNr = expectedArgNr; this.givenArgNr = givenArgNr; } public int getExpectedArgNr() { return expectedArgNr; } public int getGivenArgNr() { return givenArgNr; } @Override public String toString() { return "Wrong arg count(expected: " + this.expectedArgNr + ", given: " + this.givenArgNr + ")"; } @Override public String getStringRepresentation() { return "Too " + (getGivenArgNr() > getExpectedArgNr() ? "many" : "few") + " arguments (given " + getGivenArgNr() + ", expected " + getExpectedArgNr() + ")"; } }
package HomeworkDay4; public class SampleString { private CharArray d; static IntUtil u = new IntUtil(); public SampleString(){ d=new CharArray(); } public SampleString(char ch){ this(); d.set(0, ch); d.set(1, '\0'); } public SampleString(String str){ this(); char[] chArray=str.toCharArray(); int chArrayLength=chArray.length; for(int i=0;i<chArray.length;i++){ //System.out.println("chArray["+i+"] is: "+chArray[i]); d.set(i,chArray[i]); } d.set(chArrayLength, '\0'); //System.out.println("size is :"+d.size()); } public SampleString(char[] ch){ this(); for(int i=0;i<ch.length;i++){ //System.out.println("chArray["+i+"] is: "+chArray[i]); d.set(i,ch[i]); } d.set(ch.length, '\0'); //System.out.println("size is :"+d.size()); } public SampleString add(SampleString b){ int objLength=this.d.size(); //System.out.println("objlength is: "+objLength); int bLength=b.d.size(); //System.out.println("blength is: "+bLength); char[] concatArray=new char[objLength+bLength]; for(int i=0;i<objLength;i++){ concatArray[i]=this.d.get(i); } int i=objLength; int j=0; while(j<bLength){ concatArray[i]=b.d.get(j); i++; j++; } SampleString s=new SampleString(concatArray); return s; } public SampleString add(String str){ SampleString a=new SampleString(str); SampleString d=this.add(a); return d; } public void reverse(){ int i = 0 ; int j = d.size() - 1 ; while (i < j) { d.swap(i,j) ; ++i ; --j ; } System.out.println("size is :"+d.size()); } public void pLn(String t){ System.out.println(); char[] ch=t.toCharArray(); for(int i=0;i<t.length();i++){ System.out.print(ch[i]); } for(int i=0;i<d.size();i++){ System.out.print(d.get(i)); } } public SampleString clone(){ char[] ch=new char[this.d.size()]; for(int i=0;i<this.d.size();i++){ ch[i]=this.d.get(i); } SampleString c=new SampleString(ch); return c; } public SampleString append(SampleString a){ int objLength=this.d.size(); int aLength=a.d.size(); int i=objLength; int j=0; while(j<aLength){ this.d.set(i,a.d.get(j)); i++; j++; } return a; } public SampleString append(String str){ SampleString b=new SampleString(str); SampleString d=this.append(b); return d; } public boolean isEqual(SampleString a){ int objLength=this.d.size(); int aLength=a.d.size(); if(objLength==aLength){ for(int i=0;i<objLength;i++){ if(this.d.get(i)!=a.d.get(i)) return false; } return true; } return false; } public static void main(String[] args) { // TODO Auto-generated method stub SampleString str=new SampleString("abcd1232455252"); str.pLn("a="); //System.out.println("a.size() is: "); SampleString str1=new SampleString('p'); str1.pLn("str1= "); SampleString text=new SampleString("Hello,what are you doing"); text.pLn("text= "); SampleString copy=text.clone(); copy.pLn("copy = "); text.reverse(); text.pLn("reversed text= "); SampleString a = new SampleString("UCSC") ; SampleString b = new SampleString("Extension") ; SampleString c = a.add(b) ; a.pLn("a = ") ; b.pLn("b = ") ; c.pLn("c = ") ; SampleString d = c.add("USA") ; d.pLn("d = ") ; a.append(b) ; a.pLn("a+b = ") ; a.append("World") ; a.pLn("a+b+World = ") ; SampleString m = new SampleString("123456789012345678901234567890123456789012345678901234567890") ; m.pLn("m = ") ; SampleString n= new SampleString("123456789012345678901234567890123456789012345678901234567890") ; n.pLn("n = ") ; u.myassert(m.isEqual(n)) ; SampleString o = new SampleString("12345678901234567890123456789012345678901234567890123456789") ; o.pLn("o = ") ; u.myassert(m.isEqual(o) == false) ; } }
package mat06.sim.missingitemreminder.models; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; public class CategoryItem extends RealmObject { @PrimaryKey private String categoryName; public CategoryItem(String categoryName) { this.categoryName = categoryName; } public CategoryItem() { } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } }
package com.facebook.react.views.scroll; public interface FpsListener { void disable(String paramString); void enable(String paramString); boolean isEnabled(); } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\views\scroll\FpsListener.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.tencent.map.lib.gl.model; import android.graphics.Bitmap; public interface a$b { void a(Bitmap bitmap); }
package com.example.springbootshirodemo.service; import com.example.springbootshirodemo.pojo.User; /** * @program: springboot-shiro-demo * @description: 填写描述 * @author: 张军 * @create: 2019-11-18 12:33 **/ public interface UserService { public User findUserByName(String name); }
package com.lfd.day0202_05_array; import java.util.Arrays; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; public class MainActivity extends Activity { static{ System.loadLibrary("arrencode"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void sendArr(View view) { int[] arr = new int[]{1,2,3}; arrEncode(arr); System.out.println(Arrays.toString(arr)); } public native void arrEncode(int[] arr); }
package de.mufl.games.freebuild; public class Chunk { }
package com.perhab.napalm.statement; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * An implementation class of an interface annotated with {@link Execute} or {@link ExecuteParallel} can be marked as * ignored with this annotation. An ignored implementation will not be picked up by the {@link com.perhab.napalm.Runner} */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Ignore { }
import java.util.*; public class Problem3 { private Node rootNode = null; private String levelOrderTraversalStr = ""; private Stack<Node> nodeStack = new Stack<>(); private Stack<String> nodeString = new Stack<>(); private Queue<Node> nodeQueue = new LinkedList<>(); private StringBuilder stringBuilder = new StringBuilder(); public static void main(String[] args) { Problem3 problem3 = new Problem3(); Scanner scanner = new Scanner(System.in); String[] input = "(8 (10 (5)) (12))".replaceAll("\\s", "").split(""); System.out.println(Arrays.toString(input)); problem3.generateTree(input); // problem3.printLevelOrderTraversal(); } private void generateTree(String[] data) { StringBuilder value = new StringBuilder(); Node newNode = null; for (int i = 0; i < data.length; i++) { if (data[i].equals("(")) { i++; while (!data[i].equals(")")) { } } } // for (char datum : data) { // if (datum == '(') { // // ok prepare for new node // if (newNode != null) { // newNode.setValue(value.toString()); // nodeStack.push(newNode); // value = new StringBuilder(); // } // newNode = new Node(); // } else if (datum == ')') { // Node topStackNode = nodeStack.pop(); // if (nodeStack.isEmpty()) { //// rootNode = topStackNode; // if (newNode != null) { // if (topStackNode.getLeftChild() == null) // topStackNode.setLeftChild(newNode); // else // topStackNode.setRightChild(newNode); // } // nodeQueue.add(topStackNode); // return; // } // if (newNode != null) { // newNode.setValue(value.toString()); // if (topStackNode.getLeftChild() == null) // topStackNode.setLeftChild(newNode); // else // topStackNode.setRightChild(newNode); // nodeStack.push(topStackNode); // } else { // Node peekNode = nodeStack.peek(); // if (peekNode.getLeftChild() == null) // peekNode.setLeftChild(topStackNode); // else // peekNode.setRightChild(topStackNode); // } // newNode = null; // value = new StringBuilder(); // } else { // if (datum != ' ') // value.append(datum); // } // } } private void printLevelOrderTraversal() { while (!nodeQueue.isEmpty()) { Node node = nodeQueue.remove(); if (node.getValue() != null) System.out.print(node.getValue() + " "); if (node.getLeftChild() != null) { printIfNotVisited(node.getLeftChild()); } if (node.getRightChild() != null) { printIfNotVisited(node.getRightChild()); } } } private void printIfNotVisited(Node node) { if (!node.isVisited()) { node.setVisited(true); nodeQueue.add(node); } } }
package com.tencent.mm.plugin.sns.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.sns.model.r; class t$9 implements OnCancelListener { final /* synthetic */ t nNL; final /* synthetic */ r nNQ; t$9(t tVar, r rVar) { this.nNL = tVar; this.nNQ = rVar; } public final void onCancel(DialogInterface dialogInterface) { g.Ek(); g.Eh().dpP.c(this.nNQ); } }
package pom.pages; import static org.testng.Assert.assertTrue; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; public class LogoutPage { WebDriver driver; public LogoutPage(WebDriver idriver) { this.driver=idriver; } @FindBy(id="logoutLbl") WebElement logout; public void click() { assertTrue(driver.findElement(By.id("logoutLbl")).getText().equals("Logout")); logout.click(); } }
/* * 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 contoh; /** * * @author LAB_TI */ import java.net.InetAddress; import java.net.UnknownHostException; public class LocalHostDemo { public static void main(String[] args) { System.out.println("Looking up localhost "); InetAddress localAddress } }
package com.example.helloworld; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Date; /** * @author CBeann * @create 2019-07-25 14:45 */ @RestController public class HelloController { @RequestMapping("/hello") public String hello(){ return "hello world;"+new Date(); } }
package ElementsOfProgrammingInterview.chapter10.Exercise9.KNodeInOrderTraversal; import ElementsOfProgrammingInterview.chapter10.BinaryTreeNode; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; public class Solution { // Author's solution static BinaryTreeNode<Integer> kThElementInOrderBinaryTree(BinaryTreeNode<Integer> treeNode, int k) { // brute-force solution => return list all elements // perform in-oder walk var interTreeNode = treeNode; while (interTreeNode != null) { int leftSize = interTreeNode != null ? interTreeNode.left.size : 0; if (leftSize + 1 < k) { // kth node must be in the right of the subtree k -= leftSize + 1; interTreeNode = interTreeNode.right; } else if (leftSize == k - 1) { return interTreeNode; } else { interTreeNode = interTreeNode.left; } } return null; } static BinaryTreeNode<Integer> trivialSolutionFromInOrderTraversal(BinaryTreeNode<Integer> treeNode, int k) { Deque<BinaryTreeNode<Integer>> listNodes = new ArrayDeque<>(); List<BinaryTreeNode<Integer>> inOrderBinaryTrees = new ArrayList<>(); var currentNode= treeNode; while (!listNodes.isEmpty() || currentNode != null) { if (inOrderBinaryTrees.size() == k) { return inOrderBinaryTrees.get(k - 1); } if (currentNode != null) { listNodes.addFirst(currentNode); currentNode = currentNode.left; } else { currentNode = listNodes.removeFirst(); inOrderBinaryTrees.add(currentNode); currentNode = currentNode.right; } } return null; } public static void main(String[] args) { var root = new BinaryTreeNode<>(1); root.left = new BinaryTreeNode<>(2); root.right = new BinaryTreeNode<>(3); root.left.left = new BinaryTreeNode<>(4); root.left.right = new BinaryTreeNode<>(5); root.right.right = new BinaryTreeNode<>(6); root.right.left = new BinaryTreeNode<>(7); var trivialSolutionResult = trivialSolutionFromInOrderTraversal(root, 3); assert trivialSolutionResult != null; System.out.println(trivialSolutionResult.data); } }
package com.lec.ex02phone; //a제품 : DMB송수신불가, 5G, TV리모콘 미탑재 public class AModel implements IAcor { private String modelName; public AModel() { modelName= "A모델"; } @Override public void dmbReceive() { System.out.println(modelName+"은 DMB 송수신 불가"); } @Override public void lte() { System.out.println(modelName +"은5G"); } @Override public void tvRemoteControl() { System.out.println(modelName+"은TV리모콘 미탑재"); } }
package integracion.cliente; import java.util.Collection; import negocio.cliente.TransferCliente; import negocio.cliente.TransferClienteEmpresa; import negocio.cliente.TransferClienteNormal; /** * The Interface DAOCliente. */ public interface DAOCliente { /** * Alta cliente. * * @param transferCliente * the transfer cliente * @return the integer */ public Integer altaCliente(TransferCliente transferCliente); /** * Baja cliente. * * @param id * the id * @return true, if successful */ public boolean bajaCliente(Integer id); /** * Existe cliente. * * @param id * the id * @return true, if successful */ public boolean existeCliente(int id); /** * Gets the cliente empresa id. * * @param id * the id * @return the cliente empresa id */ public TransferClienteEmpresa getClienteEmpresaId(Integer id); /** * Gets the cliente id. * * @param id * the id * @return the cliente id */ public TransferCliente getClienteId(Integer id); /** * Gets the cliente normal id. * * @param id * the id * @return the cliente normal id */ public TransferClienteNormal getClienteNormalId(Integer id); /** * Leer cliente por identificacion fiscal. * * @param identificacionFiscal * the identificacion fiscal * @return the transfer cliente */ public TransferCliente leerClientePorIdentificacionFiscal(String identificacionFiscal); /** * Listar clientes. * * @return the collection */ public Collection<TransferCliente> listarClientes(); /** * Modificar cliente. * * @param transferCliente * the transfer cliente * @return true, if successful */ public boolean modificarCliente(TransferCliente transferCliente); }
import java.util.*; // Definition for a binary tree node. class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } /** * 95. Unique Binary Search Trees II * leetcode上的大佬又多,解题又牛B,什么题都能DP.jpg🙄 * 连这个二分递归我都看了半天,哭了😭DP自己就想不出来怎么实现 * DP利用已求的n小的树列表来求子树,右子树的排列规律是和小的数字一样的, * 只需把右子树节点数对应n的树,对应的节点值加上当前中间点的值,即可得到右子树的树列表 */ class Solution { private List<TreeNode> generate(int start, int end) { List<TreeNode> list = new ArrayList<>(); if (start > end) list.add(null); for (int i = start; i <= end; i++) { List<TreeNode> left = generate(start, i - 1); // 把左右子树可能的列表分别生成 List<TreeNode> right = generate(i + 1, end); for (TreeNode lNode : left) { for (TreeNode rNode : right) { TreeNode root = new TreeNode(i); // 再组装 root.left = lNode; root.right = rNode; list.add(root); } } } return list; } public List<TreeNode> generateTrees(int n) { if (n == 0) return new ArrayList<>(); return generate(1, n); } public void levelOrderTraversal(TreeNode t, int n) { Queue<TreeNode> queue = new LinkedList<>(); queue.offer(t); int i = 0; while (!queue.isEmpty() && i < n) { TreeNode parent = queue.poll(); if (parent != null) { System.out.print(parent.val + " "); queue.offer(parent.left); queue.offer(parent.right); i++; } else System.out.print("null "); } System.out.println(); } public static void main(String[] args) { Solution s = new Solution(); Scanner scan = new Scanner(System.in); while (scan.hasNext()) { int n = scan.nextInt(); List<TreeNode> trees = s.generateTrees(n); trees.forEach((t) -> s.levelOrderTraversal(t, n)); } scan.close(); } }
package de.zarncke.lib.io.store; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; import java.util.Calendar; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.zip.Adler32; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; import java.util.zip.ZipEntry; import de.zarncke.lib.io.ByteBufferInputStream; import de.zarncke.lib.region.ByteBufferRegion; import de.zarncke.lib.region.Region; /** * Base class for JARs based on backing ByteBuffer. * Provides read-only functions. * * @author gunnar */ public abstract class AbstractReadOnlyJar { /* * Header signatures */ public static long LOCSIG = 0x04034b50L; // "PK\003\004" public static long EXTSIG = 0x08074b50L; // "PK\007\008" public static long CENSIG = 0x02014b50L; // "PK\001\002" public static long ENDSIG = 0x06054b50L; // "PK\005\006" /* * Header sizes in bytes (including signatures) */ public static final int LOCHDR = 30; // LOC header size public static final int EXTHDR = 16; // EXT header size public static final int CENHDR = 46; // CEN header size public static final int ENDHDR = 22; // END header size /* * Local file (LOC) header field offsets */ public static final int LOCVER = 4; // version needed to extract public static final int LOCFLG = 6; // general purpose bit flag public static final int LOCHOW = 8; // compression method public static final int LOCTIM = 10; // modification time public static final int LOCCRC = 14; // uncompressed file crc-32 value public static final int LOCSIZ = 18; // compressed size public static final int LOCLEN = 22; // uncompressed size public static final int LOCNAM = 26; // filename length public static final int LOCEXT = 28; // extra field length /* * Extra local (EXT) header field offsets */ public static final int EXTCRC = 4; // uncompressed file crc-32 value public static final int EXTSIZ = 8; // compressed size public static final int EXTLEN = 12; // uncompressed size /* * Central directory (CEN) header field offsets */ public static final int CENVEM = 4; // version made by public static final int CENVER = 6; // version needed to extract public static final int CENFLG = 8; // encrypt, decrypt flags public static final int CENHOW = 10; // compression method public static final int CENTIM = 12; // modification time public static final int CENCRC = 16; // uncompressed file crc-32 value public static final int CENSIZ = 20; // compressed size public static final int CENLEN = 24; // uncompressed size public static final int CENNAM = 28; // filename length public static final int CENEXT = 30; // extra field length public static final int CENCOM = 32; // comment length public static final int CENDSK = 34; // disk number start public static final int CENATT = 36; // internal file attributes public static final int CENATX = 38; // external file attributes public static final int CENOFF = 42; // LOC header offset /* * End of central directory (END) header field offsets */ public static final int ENDSUB = 8; // number of entries on this disk public static final int ENDTOT = 10; // total number of entries public static final int ENDSIZ = 12; // central directory size in bytes public static final int ENDOFF = 16; // offset of first CEN header public static final int ENDCOM = 20; // zip file comment length static class DeferredPathEntry extends AbstractStore { private final String path; private final String name; private final Directory topLevelDirectory; public DeferredPathEntry(final String path, final String name, final Directory topLevelDirectory) { this.name = name; this.path = path; this.topLevelDirectory = topLevelDirectory; } @Override public boolean exists() { return false; } @Override public Store element(final String elementName) { return this.topLevelDirectory.locate(this.path, elementName); } @Override public String getName() { return this.name; } @Override public Store getParent() { return this.topLevelDirectory; } @Override public boolean iterationSupported() { return true; } @Override public Iterator<Store> iterator() { return this.topLevelDirectory.iterator(); } } public class Directory extends AbstractStore { protected int endPos; protected int dirPos; protected List<Entry> entries; protected Directory(final List<Entry> entries, final int dirPos, final int endPos) { this.entries = entries; this.dirPos = dirPos; this.endPos = endPos; } @Override public boolean exists() { return true; } public List<Entry> getEntries() { return this.entries; } @Override public Store element(final String name) { return locate(null, name); } Store locate(final String path, final String name) { String childPath = path == null ? name : path + "/" + name; for (Entry e : this.entries) { if (e.getName().equals(childPath)) { return e; } } return new DeferredPathEntry(path, name, this); } @Override public String getName() { return null; } @Override @SuppressWarnings("unchecked") public Iterator<Store> iterator() { // TODO expand path of entries (Map.hierarchify) return ((List<Store>) (List) getEntries()).iterator(); } @Override public boolean iterationSupported() { return true; } int findMaxExtendOf(final Entry entry) { int bestOffset = this.endPos; for (Entry e : this.entries) { if (e.offsetOfLocalHeader > entry.offsetOfData && e.offsetOfLocalHeader < bestOffset) { bestOffset = e.offsetOfLocalHeader; } } return bestOffset; } } public class Entry extends AbstractStore { protected String name; protected int offsetOfLocalHeader; protected int offsetOfDirEntry; protected int offsetOfData; protected int size; protected int csize; protected int method; protected Entry(final String name, final int size, final int csize, final int offsetOfLocalHeader, final int offsetOfDirEntry, final int offsetOfData, final int method) { this.name = name; this.size = size; this.csize = csize; this.offsetOfLocalHeader = offsetOfLocalHeader; this.offsetOfDirEntry = offsetOfDirEntry; this.offsetOfData = offsetOfData; this.method = method; } @Override public boolean exists() { return true; } @Override public String getName() { return this.name; } @Override public long getSize() { return this.size; } @Override public String toString() { return this.name + " at " + this.offsetOfLocalHeader + "/" + this.offsetOfDirEntry + " with " + this.size + " bytes at " + this.offsetOfData; } /** * @return a ByteBuffer containing the containers data area with its position set to 0 and its limit set to the * end of the area */ protected ByteBuffer getDataView() { ByteBuffer duplicate = getBaseBuffer().duplicate(); int end = this.csize >= 0 ? this.csize : AbstractReadOnlyJar.this.directory.findMaxExtendOf(this); duplicate.position(this.offsetOfData).limit(this.offsetOfData + end); return duplicate.slice(); } @Override public InputStream getInputStream() throws IOException { ByteBufferInputStream bbin = new ByteBufferInputStream(getDataView()); switch (this.method) { case ZipEntry.STORED: return bbin; case ZipEntry.DEFLATED: return new InflaterInputStream(bbin, new Inflater(true), 4096); default: throw new IOException("unknown compression method " + this.method); } } @Override public Store getParent() { return AbstractReadOnlyJar.this.directory; } @Override public boolean canRead() { return true; } @Override public Region asRegion() { return new ByteBufferRegion(getDataView()); } } static class InconsistentDirectory extends Exception { private static final long serialVersionUID = 1L; } long mappedSize; private Directory directory; protected abstract void ensureMapping(final long newSize) throws IOException; public abstract void close(); protected synchronized Directory getCentralDirectory() throws IOException { if (this.directory == null) { this.directory = readCentralDirectory(); } return this.directory; } public Store getStore() throws IOException { return getCentralDirectory(); } private Directory readCentralDirectory() throws IOException { ByteBuffer fullBuffer = getBaseBuffer().duplicate(); fullBuffer.order(ByteOrder.LITTLE_ENDIAN); List<Entry> entries = null; int endPos = fullBuffer.limit() - ENDHDR; while (endPos >= 0) { int sig = fullBuffer.getInt(endPos); try { if (sig == ENDSIG) { // we only support one disk zips if (fullBuffer.getShort(endPos + 4) != 0 || fullBuffer.getShort(endPos + 6) != 0) { throw new InconsistentDirectory(); } int entryNum = fullBuffer.getShort(endPos + ENDSUB); if (fullBuffer.getShort(endPos + ENDTOT) != entryNum) { throw new InconsistentDirectory(); } int len = fullBuffer.getInt(endPos + ENDSIZ); int dirPos = fullBuffer.getInt(endPos + ENDOFF); if (dirPos + len != endPos) { throw new InconsistentDirectory(); } if (dirPos <= 0 || dirPos > endPos) { throw new InconsistentDirectory(); } // we found a plausible end marker entries = new LinkedList<Entry>(); int entryPos = dirPos; for (int i = 0; i < entryNum; i++) { if (fullBuffer.getInt(entryPos) != CENSIG) { throw new InconsistentDirectory(); } int nameLen = fullBuffer.getShort(entryPos + CENNAM); if (entryPos + nameLen > endPos) { throw new InconsistentDirectory(); } String name = extractString(fullBuffer, entryPos + CENHDR, nameLen); // int flag = fullBuffer.getShort(entryPos + CENFLG); int method = fullBuffer.getShort(entryPos + CENHOW); int csize = fullBuffer.getInt(entryPos + CENSIZ); int size = fullBuffer.getInt(entryPos + CENLEN); int extLen = fullBuffer.getShort(entryPos + CENEXT); int commentLen = fullBuffer.getShort(entryPos + CENCOM); int localHeaderOffset = fullBuffer.getInt(entryPos + CENOFF); int totalHeaderLen = CENHDR + nameLen + extLen + commentLen; Entry e = readLocalHeader(localHeaderOffset); if (!e.name.equals(name)) { throw new InconsistentDirectory(); } Entry createdEntry = createEntry(entryPos, name, method, csize, size, localHeaderOffset, e.offsetOfData); entries.add(createdEntry); entryPos += totalHeaderLen; if (entryPos > endPos) { throw new InconsistentDirectory(); } } if (entryPos != endPos) { throw new InconsistentDirectory(); } return createDirectory(entries, endPos, dirPos); } } catch (InconsistentDirectory e) { // try next possible offset } endPos--; } throw new IOException("no valid central directory found"); } protected Entry createEntry(final int entryPos, final String name, final int method, final int csize, final int size, final int localHeaderOffset, final int offsetOfData) { return new Entry(name, size, csize, localHeaderOffset, entryPos, offsetOfData, method); } protected Directory createDirectory(final List<Entry> entries, final int endPos, final int dirPos) { return new Directory(entries, dirPos, endPos); } private static String extractString(final ByteBuffer buffer, final int startPos, final int len) { String name = ""; if (len > 0) { ByteBuffer nameBuf = buffer.duplicate(); nameBuf.position(startPos).limit(startPos + len); name = Charset.forName("UTF-8").decode(nameBuf).toString(); } return name; } private Entry readLocalHeader(final int offset) throws InconsistentDirectory { ByteBuffer fullBuffer = getBaseBuffer().duplicate(); fullBuffer.position(offset); ByteBuffer buffer = fullBuffer.slice(); buffer.order(ByteOrder.LITTLE_ENDIAN); int sig = buffer.getInt(); if (sig != LOCSIG) { throw new InconsistentDirectory(); } // get the entry name and create the ZipEntry first int nameLen = buffer.getShort(LOCNAM); String name = extractString(buffer, LOCHDR, nameLen); int flag = buffer.getShort(LOCFLG); int method = buffer.getShort(LOCHOW); int size = -1; int csize = -1; if ((flag & 1) == 1) { // throw new ZipException("encrypted ZIP entry not supported"); } if ((flag & 8) == 8) { /* EXT descriptor present */ // return new Entry(name, -1, -1, offset, -1, offsetOfData, method); } else { csize = buffer.getInt(LOCSIZ); size = buffer.getInt(LOCLEN); } int extLen = buffer.getShort(LOCEXT); int totalHeaderLen = LOCHDR + nameLen + extLen; int offsetOfData = offset + totalHeaderLen; return new Entry(name, size, csize, offset, -1, offsetOfData, method); } public static int adler32(final ByteBuffer buffer) { ByteBuffer local = buffer.duplicate(); local.clear(); Adler32 a = new Adler32(); byte[] temp = new byte[4096]; while (local.hasRemaining()) { int l = Math.min(local.remaining(), 4096); local.get(temp, 0, l); a.update(temp, 0, l); } return (int) a.getValue(); } public static int msdosDateTime() { Calendar c = Calendar.getInstance(); int dateTime = c.get(Calendar.SECOND); dateTime += c.get(Calendar.MINUTE) << 5; dateTime += c.get(Calendar.HOUR) << 11; dateTime += c.get(Calendar.DAY_OF_MONTH) << 16; dateTime += c.get(Calendar.MONTH) << 21; dateTime += c.get(Calendar.YEAR) - 1980 << 25; return dateTime; } protected long getMappedSize() { return this.mappedSize; } protected abstract ByteBuffer getBaseBuffer(); }
package gr.james.influence.game; import gr.james.influence.util.collections.GraphState; public class GameResult { public int score = 0; public GraphState<Double> fullState = null; public Move m1; public Move m2; public GameResult(int score, GraphState<Double> fullState, Move m1, Move m2) { this.score = score; this.fullState = fullState; this.m1 = m1; this.m2 = m2; } @Override public String toString() { return String.format("{score=%d,state=%.2f}", score, fullState.getAverage()); } }
public class number_test { public static void main(String[] args) { int number = 4; System.out.println(++number); } }
/** * 2 ways for receiver to get message * 1. consumer.receive() or consumer.receive(int timeout); * 2. register a MessageListener. * First method uses p2p, receiver will wait until message arrives * Second method will use async and register a monitor, callback its onMessage when receives message */ import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.command.ActiveMQQueue; public class MessageSendAndReceive { public static void main(String[] args) throws JMSException { ConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); Connection connection = factory.createConnection(); connection.start(); //Destination for message creation Queue queue = new ActiveMQQueue("testQueue"); final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); //create message to send Message message = session.createTextMessage("Hello JMS!"); MessageProducer producer = session.createProducer(queue); producer.send(message); System.out.println("Send Message Completed!"); MessageConsumer comsumer = session.createConsumer(queue); comsumer.setMessageListener(new MessageListener() { @Override public void onMessage(Message msg) { TextMessage textMsg = (TextMessage) msg; try { System.out.println("Receives message: " + textMsg.getText()); System.exit(0); } catch (JMSException e) { e.printStackTrace(); } } }); } }
package com.apprisingsoftware.xmasrogue.io; import com.apprisingsoftware.util.NormalDoubleSupplier; import com.apprisingsoftware.xmasrogue.util.Coord; import java.awt.Color; import java.util.Collection; import java.util.function.DoubleSupplier; import java.util.stream.Collectors; import java.util.stream.IntStream; public final class ProgressBarScreen implements AsciiScreen { private final int length; private final Color fullColor, emptyColor; private final NormalDoubleSupplier value; private final String text; private final Color textColor; private final int textOffset; private boolean justCreated; private int lastCell; public ProgressBarScreen(int length, Color fullColor, Color emptyColor, DoubleSupplier value, String text, Color textColor, int textOffset) { if (length <= 0 || fullColor == null || emptyColor == null || value == null) throw new IllegalArgumentException(); this.length = length; this.fullColor = fullColor; this.emptyColor = emptyColor; this.value = new NormalDoubleSupplier(value); this.text = text; this.textColor = textColor; this.textOffset = textOffset; justCreated = true; lastCell = length - 1; } public ProgressBarScreen(int length, Color fullColor, Color emptyColor, DoubleSupplier value, String text, Color textColor) { this(length, fullColor, emptyColor, value, text, textColor, (length - text.length()) / 2); } private static Color getIntermediateColor(Color zeroColor, Color oneColor, double factor) { if (zeroColor == null || oneColor == null || factor < 0 || factor > 1) throw new IllegalArgumentException(); float[] zeroHSB = Color.RGBtoHSB(zeroColor.getRed(), zeroColor.getGreen(), zeroColor.getBlue(), null); float[] oneHSB = Color.RGBtoHSB(oneColor.getRed(), oneColor.getGreen(), oneColor.getBlue(), null); float[] intermediateHSB = { (float) (zeroHSB[0] + (oneHSB[0] - zeroHSB[0]) * factor), (float) (zeroHSB[1] + (oneHSB[1] - zeroHSB[1]) * factor), (float) (zeroHSB[2] + (oneHSB[2] - zeroHSB[2]) * factor) }; int intermediateColor = Color.HSBtoRGB(intermediateHSB[0], intermediateHSB[1], intermediateHSB[2]); return new Color(intermediateColor); } @Override public AsciiTile getTile(int x, int y) { double fraction = value.get(); int currentCell = fraction != 1 ? (int) (length * fraction) : length - 1; Color bgColor; if (x < currentCell) bgColor = fullColor; else if (x > currentCell) bgColor = emptyColor; else bgColor = getIntermediateColor(emptyColor, fullColor, fraction != 1 ? length * fraction % 1 : 1); // x % 1 -> fPart(x) return new AsciiTile(charAt(x), textColor, bgColor); } private char charAt(int x) { try { return text.charAt(x - textOffset); } catch (StringIndexOutOfBoundsException e) { return ' '; } } @Override public boolean isTransparent(int x, int y) { return !inBounds(x, y); } @Override public Collection<Coord> getUpdatedTiles() { if (justCreated) { justCreated = false; return IntStream.range(0, length).mapToObj(x -> new Coord(x, 0)).collect(Collectors.toList()); } else { int oneEnd = lastCell; this.lastCell = value.get() != 1 ? (int) (length * value.get()) : length - 1; int otherEnd = lastCell; // Ensure that oneEnd < otherEnd so that rangeClosed will work properly if (oneEnd > otherEnd) { oneEnd = (otherEnd ^= oneEnd ^= otherEnd) ^ oneEnd; // See https://en.wikipedia.org/wiki/XOR_swap_algorithm } return IntStream.rangeClosed(oneEnd, otherEnd).mapToObj(x -> new Coord(x, 0)).collect(Collectors.toList()); } } @Override public int getWidth() { return length; } @Override public int getHeight() { return 1; } }
package com.company; public class Main { public static void main(String[] args) { int divisibleNum = 2; while() for(int num1 = 2; num1 <= 20; num1++){ if(divisibleNum % num1 != 0){ // System.out.println(divisibleNum); divisibleNum++; } } System.out.println(divisibleNum); } }
/* static - allows for a method to run without an instance of a class. * static methods are a telling sign that a class isn't to be instantiated. * marking a constructor as private is a good way of preventing unintentional instantiation. * used to create members of an object prior to be used by itself. * accessible to all objects of its class and without reference to an object. * static variables are essentially global variables (within the Class as a namespace). * static variables are shared throughout all the instances of the class. caveats * no reference to this. * can only access static data, and can only call static methods. * static methods cannot use non-static instance variables. * static methods cannot use non-static methods. * static variables contain the same value across all the classes. * static variables are initialized before any object of the class can be created and before static methods of that class can run. * the static block is runs to do setup before a class can be constructed into objects. Style * constants should be in all caps! final - good for constants, as it prevents * thus final static variables are essentially macros in C. There's a Object wrapper for each Primitive type. * Starts with a capital letter! * boolean -> Boolean * char -> Character * byte -> Byte * you get the idea. This is important for things liek ArrayLists, which need an object type. Autoboxing - Java 5+. Automatic conversion of primtitive to wrapper objects. AKA interchangeable. * works in arguments, return values, boolean expressions, operations, and assignment. * parsing methods to convert strings to primitives and vv. */
package com.example.healthmanage.ui.activity.mypoint; import android.os.Bundle; import android.view.View; import androidx.lifecycle.Observer; import androidx.recyclerview.widget.GridLayoutManager; import com.example.healthmanage.BR; import com.example.healthmanage.R; import com.example.healthmanage.base.BaseActivity; import com.example.healthmanage.base.BaseAdapter; import com.example.healthmanage.databinding.ActivityMyPointBinding; import com.example.healthmanage.ui.activity.mypoint.getpoint.GetPointActivity; import com.example.healthmanage.ui.activity.mypoint.mywallet.MyWalletActivity; import com.example.healthmanage.bean.recyclerview.ExchangeCommodityRecyclerView; import com.example.healthmanage.widget.TitleToolBar; import java.util.List; public class MyPointActivity extends BaseActivity<ActivityMyPointBinding, MyPointViewModel> implements TitleToolBar.OnTitleIconClickCallBack, View.OnClickListener { TitleToolBar titleToolBar = new TitleToolBar(); BaseAdapter exchangeCommodityAdapter; @Override protected void initData() { titleToolBar.setTitle("我的积分"); titleToolBar.setLeftIconVisible(true); viewModel.setTitleToolBar(titleToolBar); viewModel.getExchangeCommodity(); } @Override protected void registerUIChangeEventObserver() { super.registerUIChangeEventObserver(); exchangeCommodityAdapter = new BaseAdapter(this, null, R.layout.recycler_view_item_exchange_commodity, BR.ExchangeCommodityRecyclerView); dataBinding.recyclerViewExchangeCommodity.setLayoutManager(new GridLayoutManager(this, 2)); dataBinding.recyclerViewExchangeCommodity.setAdapter(exchangeCommodityAdapter); viewModel.exchangeCommodityMutableLiveData.observe(this, new Observer<List<ExchangeCommodityRecyclerView>>() { @Override public void onChanged(List<ExchangeCommodityRecyclerView> exchangeCommodityRecyclerViews) { exchangeCommodityAdapter.setRecyclerViewList(exchangeCommodityRecyclerViews); exchangeCommodityAdapter.notifyDataSetChanged(); } }); dataBinding.tvWallet.setOnClickListener(this::onClick); dataBinding.tvGrowth.setOnClickListener(this::onClick); dataBinding.tvGetPoint.setOnClickListener(this::onClick); } @Override public void initViewListener() { super.initViewListener(); titleToolBar.setOnClickCallBack(this); } @Override public void onRightIconClick() { } @Override public void onBackIconClick() { finish(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tv_wallet: startActivity(MyWalletActivity.class); break; case R.id.tv_growth: break; case R.id.tv_get_point: startActivity(GetPointActivity.class); break; } } @Override protected int initVariableId() { return BR.ViewModel; } @Override protected int setContentViewSrc(Bundle savedInstanceState) { return R.layout.activity_my_point; } }
package com.actionimpl; import java.io.InputStream; import java.util.List; import com.javabean.Music; import com.javabean.Song; public interface SongImpl { void saveSong(Song song,String filepath); void removeSong(int id); void updataSong(Song song); List<Song> selectSong(); Song selectByName(String sname); InputStream getImageBySname(String sname); }
package com.lhf.ssm.service; import com.lhf.ssm.bean.TUser; import java.util.List; /** * @author shkstart * @create 2018-09-03 8:59 */ public interface UserService { List<TUser> getUsers(); }
package com.xm.user.dao; import com.xm.user.domain.BlogCatalog; import org.apache.ibatis.annotations.Param; import java.util.List; /** * Created by xm on 2017/2/21. */ public interface BlogCatalogDao { public int addBlogCatalog(BlogCatalog blogCatalog); public int countBlogCatalog(String uid); public List<BlogCatalog> queryBlogCatalog(@Param("uid")String uid,@Param("limit")int limit,@Param("offset")int offset); public int deleteBlogCatalog(@Param("idList")List<Integer> idList,@Param("uid")String uid); public int updateBlogCatalog(@Param("name")String name,@Param("id")int id,@Param("uid")String uid); }
/** * DNet eBusiness Suite * Copyright: 2010-2013 Nan21 Electronics SRL. All rights reserved. * Use is subject to license terms. */ package net.nan21.dnet.module.bd.presenter.impl.attr.model; import net.nan21.dnet.core.api.annotation.Ds; import net.nan21.dnet.core.api.annotation.SortField; import net.nan21.dnet.core.presenter.model.AbstractTypeWithCodeDs; import net.nan21.dnet.module.bd.domain.impl.attr.AttributeCategory; @Ds(entity = AttributeCategory.class, sort = {@SortField(field = AttributeCategory_Ds.f_code)}) public class AttributeCategory_Ds extends AbstractTypeWithCodeDs<AttributeCategory> { public AttributeCategory_Ds() { super(); } public AttributeCategory_Ds(AttributeCategory e) { super(e); } }
package com.tencent.mm.openim.b; import android.content.Context; import android.graphics.Bitmap; import android.text.SpannableString; import android.text.style.ImageSpan; import com.tencent.mm.a.e; import com.tencent.mm.ab.l; import com.tencent.mm.ak.o; import com.tencent.mm.bp.a; import com.tencent.mm.kernel.g; import com.tencent.mm.openim.PluginOpenIM; import com.tencent.mm.openim.a.b; import com.tencent.mm.openim.d.c; import com.tencent.mm.protocal.c.ayc; import com.tencent.mm.protocal.c.ayd; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.w; import java.util.HashMap; import java.util.Iterator; public final class j implements b { private HashMap<String, b> euy = new HashMap(); public j() { e.cr(Vi()); c cVar = new c(); cVar.field_appid = "3552365301"; cVar.field_language = w.fD(ad.getContext()); g.Ek(); ((PluginOpenIM) g.n(PluginOpenIM.class)).getAppIdInfoStg().b(cVar, new String[]{"appid", "language"}); if (cVar.sKx == -1) { oG("3552365301"); } } private static String Vi() { StringBuilder stringBuilder = new StringBuilder(); g.Ek(); return stringBuilder.append(g.Ei().dqp).append("openim/").toString(); } public final void a(int i, int i2, String str, l lVar) { if (lVar.getType() == 453 && i == 0 && i2 == 0) { c cVar = (c) lVar; b bVar = (b) this.euy.get(cVar.eus + cVar.aem); if (bVar.euB.isEmpty()) { this.euy.remove(cVar.eus + cVar.aem); return; } while (bVar.euC.size() < 10 && !bVar.euB.isEmpty()) { bVar.euC.add(bVar.euB.removeFirst()); } g.Eh().dpP.a(new c(cVar.eus, cVar.aem, bVar.euC), 0); } } public final SpannableString d(Context context, String str, int i) { return com.tencent.mm.pluginsdk.ui.d.j.a(context, (CharSequence) str, i); } public final CharSequence a(Context context, String str, String str2, float f) { Bitmap oC = oC(str); if (oC == null) { return str2; } CharSequence a = com.tencent.mm.pluginsdk.ui.d.j.a(context, " " + str2, f); int fromDPToPix = (int) (((float) a.fromDPToPix(context, 2)) + f); ImageSpan imageSpan = new ImageSpan(ad.getContext(), oC); imageSpan.getDrawable().setBounds(0, 0, fromDPToPix, fromDPToPix); a.setSpan(imageSpan, 0, 1, 33); return a; } public final Bitmap oC(String str) { a aVar = new a(this, (byte) 0); if (bi.oW(str)) { return null; } com.tencent.mm.ak.a.a.c.a aVar2 = new com.tencent.mm.ak.a.a.c.a(); aVar2.dXy = true; aVar2.dXA = Vi() + com.tencent.mm.a.g.u(str.getBytes()); o.Pj().a(str, null, aVar2.Pt(), new 1(this, aVar)); return aVar.bitmap; } public final int oD(String str) { c cVar = new c(); cVar.field_appid = str; g.Ek(); ((PluginOpenIM) g.n(PluginOpenIM.class)).getAppIdInfoStg().b(cVar, new String[]{"appid"}); if (cVar.sKx != -1) { return cVar.field_appRec.rde; } oG(str); return 0; } public final String g(String str, String str2, int i) { c cVar = new c(); cVar.field_appid = str; g.Ek(); ((PluginOpenIM) g.n(PluginOpenIM.class)).getAppIdInfoStg().b(cVar, new String[]{"appid"}); if (cVar.sKx == -1) { oG(str); return null; } String c = c(cVar.field_acctTypeId, str2, i, w.fD(ad.getContext())); if (c == null) { return c(cVar.field_acctTypeId, str2, i, "en"); } return c; } public final String h(String str, String str2, int i) { String c = c(str, str2, i, w.fD(ad.getContext())); if (c == null) { return c(str, str2, i, "en"); } return c; } private static String c(String str, String str2, int i, String str3) { com.tencent.mm.openim.d.a aVar = new com.tencent.mm.openim.d.a(); aVar.field_acctTypeId = str; aVar.field_language = str3; g.Ek(); ((PluginOpenIM) g.n(PluginOpenIM.class)).getAccTypeInfoStg().b(aVar, new String[]{"acctTypeId", "language"}); if (aVar.sKx == -1) { return null; } Iterator it; if (i == b.a.eui) { it = aVar.field_accTypeRec.raK.iterator(); while (it.hasNext()) { ayd ayd = (ayd) it.next(); if (str2.equals(ayd.aAL)) { return ayd.bSc; } } return null; } it = aVar.field_accTypeRec.raL.iterator(); while (it.hasNext()) { ayc ayc = (ayc) it.next(); if (str2.equals(ayc.aAL)) { return ayc.url; } } return null; } public final String i(String str, String str2, int i) { String d = d(str, str2, i, w.fD(ad.getContext())); if (d == null) { return d(str, str2, i, "en"); } return d; } private String d(String str, String str2, int i, String str3) { c cVar = new c(); cVar.field_appid = str; cVar.field_language = str3; g.Ek(); ((PluginOpenIM) g.n(PluginOpenIM.class)).getAppIdInfoStg().b(cVar, new String[]{"appid", "language"}); Iterator it; if (cVar.sKx == -1) { aF(str, str3); return null; } else if (i == b.a.eui) { it = cVar.field_appRec.raK.iterator(); while (it.hasNext()) { ayd ayd = (ayd) it.next(); if (str2.equals(ayd.aAL)) { return ayd.bSc; } } return null; } else { it = cVar.field_appRec.raL.iterator(); while (it.hasNext()) { ayc ayc = (ayc) it.next(); if (str2.equals(ayc.aAL)) { return ayc.url; } } return null; } } public final String aE(String str, String str2) { String t = t(str, str2, w.fD(ad.getContext())); if (t == null) { return t(str, str2, "en"); } return t; } private String t(String str, String str2, String str3) { com.tencent.mm.openim.d.e eVar = new com.tencent.mm.openim.d.e(); eVar.field_appid = str; eVar.field_language = str3; eVar.field_wordingId = str2; g.Ek(); ((PluginOpenIM) g.n(PluginOpenIM.class)).getWordingInfoStg().b(eVar, new String[]{"appid", "language", "wordingId"}); if (eVar.sKx != -1) { return eVar.field_wording; } u(str, str3, str2); return null; } private void oG(String str) { aF(str, w.fD(ad.getContext())); } private void aF(String str, String str2) { u(str, str2, ""); } private void u(String str, String str2, String str3) { if (!bi.oW(str)) { b bVar; if (!this.euy.containsKey(str + str2)) { bVar = new b(this, (byte) 0); if (!bi.oW(str3)) { bVar.euC.add(str3); } this.euy.put(str + str2, bVar); g.Eh().dpP.a(new c(str, str2, bVar.euC), 0); } if (!bi.oW(str3)) { bVar = (b) this.euy.get(str + str2); if (!bVar.euB.contains(str3) && !bVar.euC.contains(str3)) { bVar.euB.add(str3); } } } } public final void aD(String str, String str2) { Object obj; Object obj2 = null; c cVar = new c(); cVar.field_appid = str; cVar.field_language = w.fD(ad.getContext()); g.Ek(); ((PluginOpenIM) g.n(PluginOpenIM.class)).getAppIdInfoStg().b(cVar, new String[]{"appid", "language"}); if (cVar.sKx == -1 || bi.bG(cVar.field_updateTime) > 172800) { obj2 = 1; } if (obj2 == null && !bi.oW(str2)) { com.tencent.mm.openim.d.e eVar = new com.tencent.mm.openim.d.e(); eVar.field_appid = str; eVar.field_language = w.fD(ad.getContext()); eVar.field_wordingId = str2; g.Ek(); ((PluginOpenIM) g.n(PluginOpenIM.class)).getWordingInfoStg().b(eVar, new String[]{"appid", "language", "wordingId"}); if (eVar.sKx == -1 || bi.bG(cVar.field_updateTime) > 172800) { obj = 1; if (obj != null) { u(str, w.fD(ad.getContext()), str2); } } } obj = obj2; if (obj != null) { u(str, w.fD(ad.getContext()), str2); } } }
package net.thumbtack.asurovenko; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import io.restassured.http.ContentType; import org.glassfish.jersey.test.JerseyTest; import org.junit.Test; import javax.ws.rs.core.Application; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import static io.restassured.RestAssured.given; import static org.junit.Assert.*; public class TodoTaskTest extends JerseyTest { private Gson gson = new GsonBuilder().create(); @Override protected Application configure() { return new MyApplication(); } /*@Before public void raiseServer() { URI baseUri = UriBuilder.fromUri("http://localhost/").port(9998).build(); MyApplication config = new MyApplication(); Server server = JettyHttpContainerFactory.createServer(baseUri, config); }*/ @Test public void testAddTask() { TodoTask newTask = new TodoTask("Task description - addTask", true); TodoTask t = given() .body(gson.toJson(newTask)) .contentType(ContentType.JSON) .when() .post("http://localhost:9998/task/") .then() .statusCode(200) .extract() .as(TodoTask.class); assertEquals(true, t.isDone()); assertEquals("Task description - addTask", t.getDescription()); assertTrue(t.getId() != 0); } @Test public void testEditTask() { TodoTask addTask = given() .body(gson.toJson(new TodoTask("Task description - editTask", false))) .contentType(ContentType.JSON) .when() .post("http://localhost:9998/task/") .then() .statusCode(200) .extract() .as(TodoTask.class); TodoTask changeTask = given() .queryParam("description", "Change description") .queryParam("done", true) .when() .post("http://localhost:9998/task/" + String.valueOf(addTask.getId())) .then() .statusCode(200) .extract() .as(TodoTask.class); assertEquals(true, changeTask.isDone()); assertEquals("Change description", changeTask.getDescription()); assertTrue(changeTask.getId() == addTask.getId()); } @Test public void testGetTask() { TodoTask addTask = given() .body(gson.toJson(new TodoTask("Task description - addTask", true))) .contentType(ContentType.JSON) .when() .post("http://localhost:9998/task/") .then() .statusCode(200) .extract() .as(TodoTask.class); TodoTask newTask = given() .when() .get("http://localhost:9998/task/" + String.valueOf(addTask.getId())) .then() .statusCode(200) .extract() .as(TodoTask.class); assertEquals(true, newTask.isDone()); assertEquals("Task description - addTask", newTask.getDescription()); assertTrue(newTask.getId() == addTask.getId()); } @Test public void testDeleteTask() { TodoTask task = given() .body(gson.toJson(new TodoTask("des 1", true))) .contentType(ContentType.JSON) .when() .post("http://localhost:9998/task/") .then() .statusCode(200) .extract() .as(TodoTask.class); given() .when() .delete("http://localhost:9998/task/" + String.valueOf(task.getId())) .then() .statusCode(200); given() .when() .get("http://localhost:9998/task/" + String.valueOf(task.getId())) .then() .statusCode(404); } @Test public void testDeleteAllTask() { TodoTask task1 = given() .body(gson.toJson(new TodoTask("des 1", true))) .contentType(ContentType.JSON) .when() .post("http://localhost:9998/task/") .then() .statusCode(200) .extract() .as(TodoTask.class); TodoTask task2 = given() .body(gson.toJson(new TodoTask("des 22", false))) .contentType(ContentType.JSON) .when() .post("http://localhost:9998/task/") .then() .statusCode(200) .extract() .as(TodoTask.class); TodoTask task3 = given() .body(gson.toJson(new TodoTask("des 333", true))) .contentType(ContentType.JSON) .when() .post("http://localhost:9998/task/") .then() .statusCode(200) .extract() .as(TodoTask.class); given() .when() .delete("http://localhost:9998/task/") .then() .statusCode(200); given() .when() .get("http://localhost:9998/task/" + String.valueOf(task1.getId())) .then() .statusCode(404); given() .when() .get("http://localhost:9998/task/" + String.valueOf(task2.getId())) .then() .statusCode(404); given() .when() .get("http://localhost:9998/task/" + String.valueOf(task3.getId())) .then() .statusCode(404); } @Test public void testGetAllTask() { TodoTask task1 = new TodoTask("description 1", true); TodoTask task2 = new TodoTask("description 22", false); TodoTask task3 = new TodoTask("description 333", true); List<TodoTask> list = new ArrayList<>(); list.add( given() .body(gson.toJson(task1)) .contentType(ContentType.JSON) .when() .post("http://localhost:9998/task/") .then() .statusCode(200) .extract() .as(TodoTask.class)); list.add( given() .body(gson.toJson(task2)) .contentType(ContentType.JSON) .when() .post("http://localhost:9998/task/") .then() .statusCode(200).extract() .as(TodoTask.class)); list.add( given() .body(gson.toJson(task3)) .contentType(ContentType.JSON) .when() .post("http://localhost:9998/task/") .then() .statusCode(200).extract() .as(TodoTask.class)); String strList = given() .body(gson.toJson(task3)) .contentType(ContentType.JSON) .when() .get("http://localhost:9998/task/") .then() .statusCode(200) .extract() .body().asString(); Type type = new TypeToken<List<TodoTask>>() { }.getType(); List<TodoTask> list1 = gson.fromJson(strList, type); assertEquals(list, list1); } }
package com.lqs.hrm.entity; import java.util.Date; public class DepartmentLevel { /** * This field was generated by MyBatis Generator. This field corresponds to the database column department_level.dl_id * @mbg.generated Mon May 25 00:12:53 CST 2020 */ private Integer dlId; /** * This field was generated by MyBatis Generator. This field corresponds to the database column department_level.level * @mbg.generated Mon May 25 00:12:53 CST 2020 */ private Integer level; /** * This field was generated by MyBatis Generator. This field corresponds to the database column department_level.level_desc * @mbg.generated Mon May 25 00:12:53 CST 2020 */ private String levelDesc; /** * This field was generated by MyBatis Generator. This field corresponds to the database column department_level.last_operator_date * @mbg.generated Mon May 25 00:12:53 CST 2020 */ private Date lastOperatorDate; /** * This field was generated by MyBatis Generator. This field corresponds to the database column department_level.operator_empJobId * @mbg.generated Mon May 25 00:12:53 CST 2020 */ private String operatorEmpjobid; /** * This field was generated by MyBatis Generator. This field corresponds to the database column department_level.level_note * @mbg.generated Mon May 25 00:12:53 CST 2020 */ private String levelNote; /** * This method was generated by MyBatis Generator. This method returns the value of the database column department_level.dl_id * @return the value of department_level.dl_id * @mbg.generated Mon May 25 00:12:53 CST 2020 */ public Integer getDlId() { return dlId; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column department_level.dl_id * @param dlId the value for department_level.dl_id * @mbg.generated Mon May 25 00:12:53 CST 2020 */ public void setDlId(Integer dlId) { this.dlId = dlId; } /** * This method was generated by MyBatis Generator. This method returns the value of the database column department_level.level * @return the value of department_level.level * @mbg.generated Mon May 25 00:12:53 CST 2020 */ public Integer getLevel() { return level; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column department_level.level * @param level the value for department_level.level * @mbg.generated Mon May 25 00:12:53 CST 2020 */ public void setLevel(Integer level) { this.level = level; } /** * This method was generated by MyBatis Generator. This method returns the value of the database column department_level.level_desc * @return the value of department_level.level_desc * @mbg.generated Mon May 25 00:12:53 CST 2020 */ public String getLevelDesc() { return levelDesc; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column department_level.level_desc * @param levelDesc the value for department_level.level_desc * @mbg.generated Mon May 25 00:12:53 CST 2020 */ public void setLevelDesc(String levelDesc) { this.levelDesc = levelDesc; } /** * This method was generated by MyBatis Generator. This method returns the value of the database column department_level.last_operator_date * @return the value of department_level.last_operator_date * @mbg.generated Mon May 25 00:12:53 CST 2020 */ public Date getLastOperatorDate() { return lastOperatorDate; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column department_level.last_operator_date * @param lastOperatorDate the value for department_level.last_operator_date * @mbg.generated Mon May 25 00:12:53 CST 2020 */ public void setLastOperatorDate(Date lastOperatorDate) { this.lastOperatorDate = lastOperatorDate; } /** * This method was generated by MyBatis Generator. This method returns the value of the database column department_level.operator_empJobId * @return the value of department_level.operator_empJobId * @mbg.generated Mon May 25 00:12:53 CST 2020 */ public String getOperatorEmpjobid() { return operatorEmpjobid; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column department_level.operator_empJobId * @param operatorEmpjobid the value for department_level.operator_empJobId * @mbg.generated Mon May 25 00:12:53 CST 2020 */ public void setOperatorEmpjobid(String operatorEmpjobid) { this.operatorEmpjobid = operatorEmpjobid; } /** * This method was generated by MyBatis Generator. This method returns the value of the database column department_level.level_note * @return the value of department_level.level_note * @mbg.generated Mon May 25 00:12:53 CST 2020 */ public String getLevelNote() { return levelNote; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column department_level.level_note * @param levelNote the value for department_level.level_note * @mbg.generated Mon May 25 00:12:53 CST 2020 */ public void setLevelNote(String levelNote) { this.levelNote = levelNote; } /** * 操作人名称 */ private String operatorEmpName = ""; public String getOperatorEmpName() { return operatorEmpName; } public void setOperatorEmpName(String operatorEmpName) { this.operatorEmpName = operatorEmpName; } }
package com.tencent.mm.plugin.bottle.ui; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import com.tencent.mm.R; import com.tencent.mm.aa.f.c; import com.tencent.mm.aa.o; import com.tencent.mm.aa.q; import com.tencent.mm.aq.g; import com.tencent.mm.model.au; import com.tencent.mm.plugin.bottle.a; import com.tencent.mm.pluginsdk.ui.preference.HeadImgPreference; import com.tencent.mm.pluginsdk.ui.tools.l; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.ab; import com.tencent.mm.ui.base.h; import com.tencent.mm.ui.base.preference.CheckBoxPreference; import com.tencent.mm.ui.base.preference.MMPreference; import com.tencent.mm.ui.base.preference.Preference; import com.tencent.mm.ui.base.preference.f; import com.tencent.mm.ui.base.s; import java.util.HashMap; import java.util.Map.Entry; public class BottlePersonalInfoUI extends MMPreference implements c { private SharedPreferences duR; private HashMap<Integer, Integer> eGU = new HashMap(); private f eOE; private c hlv; private int status; public void onCreate(Bundle bundle) { super.onCreate(bundle); q.Kp().d(this); initView(); } public void onDestroy() { a.ezo.vl(); q.Kp().e(this); super.onDestroy(); } protected final void initView() { boolean z = true; setMMTitle(R.l.settings_title); this.eOE = this.tCL; this.eOE.addPreferencesFromResource(R.o.bottle_wizard_step2); this.duR = this.duR; this.status = com.tencent.mm.model.q.GJ(); if (getIntent().getBooleanExtra("is_allow_set", true)) { this.hlv = new c(this, this.eOE); } else { f fVar = this.eOE; fVar.aaa("settings_sex"); fVar.aaa("settings_district"); fVar.aaa("settings_signature"); fVar.aaa("bottle_settings_change_avatar_alert"); } CheckBoxPreference checkBoxPreference = (CheckBoxPreference) this.eOE.ZZ("bottle_settings_show_at_main"); if ((this.status & 32768) == 0) { z = false; } checkBoxPreference.qpJ = z; setBackBtn(new 1(this)); } public void onResume() { HeadImgPreference headImgPreference = (HeadImgPreference) this.eOE.ZZ("bottle_settings_change_avatar"); Bitmap a = com.tencent.mm.aa.c.a(ab.XV(com.tencent.mm.model.q.GF()), false, -1); if (a == null) { a = com.tencent.mm.aa.c.a(com.tencent.mm.model.q.GF(), false, -1); } if (a != null) { headImgPreference.O(a); } headImgPreference.mVS = new 3(this); if (this.hlv != null) { this.hlv.update(); } super.onResume(); } public void onPause() { c.auq(); au.HU(); com.tencent.mm.model.c.DT().set(7, Integer.valueOf(this.status)); for (Entry entry : this.eGU.entrySet()) { int intValue = ((Integer) entry.getKey()).intValue(); int intValue2 = ((Integer) entry.getValue()).intValue(); au.HU(); com.tencent.mm.model.c.FQ().b(new g(intValue, intValue2)); x.d("MicroMsg.BottleSettignsPersonalInfoUI", "switch " + intValue + " " + intValue2); } this.eGU.clear(); super.onPause(); } public final int Ys() { return R.o.bottle_settings_pref_personal_info; } public final boolean a(f fVar, Preference preference) { int i = 2; String str = preference.mKey; if (str.equals("bottle_settings_change_avatar")) { au.HU(); if (com.tencent.mm.model.c.isSDCardAvailable()) { l.a(this, 2, null); return true; } s.gH(this); return false; } else if (str.equals("settings_district")) { return this.hlv.aus(); } else { if (str.equals("settings_signature")) { return this.hlv.aur(); } if (str.equals("bottle_settings_show_at_main")) { boolean z = this.duR.getBoolean("bottle_settings_show_at_main", true); x.d("MicroMsg.BottleSettignsPersonalInfoUI", "switch change : open = " + z + " item value = 32768 functionId = 14"); if (z) { this.status |= 32768; } else { this.status &= -32769; } if (z) { i = 1; } this.eGU.put(Integer.valueOf(14), Integer.valueOf(i)); return true; } else if (!str.equals("bottle_settings_clear_data")) { return false; } else { h.a(this.mController.tml, this.mController.tml.getString(R.l.contact_info_clear_data), "", this.mController.tml.getString(R.l.app_clear), this.mController.tml.getString(R.l.app_cancel), new 2(this), null); return true; } } } public void onActivityResult(int i, int i2, Intent intent) { Context applicationContext; String d; Intent intent2; switch (i) { case 2: if (intent != null) { applicationContext = getApplicationContext(); au.HU(); d = l.d(applicationContext, intent, com.tencent.mm.model.c.Gb()); if (d != null) { intent2 = new Intent(); intent2.putExtra("CropImageMode", 1); intent2.putExtra("CropImage_OutputPath", q.Kp().c(ab.XV(com.tencent.mm.model.q.GF()), true, false)); intent2.putExtra("CropImage_ImgPath", d); a.ezn.a(intent2, 4, this, intent); return; } return; } return; case 3: applicationContext = getApplicationContext(); au.HU(); d = l.d(applicationContext, intent, com.tencent.mm.model.c.Gb()); if (d != null) { intent2 = new Intent(); intent2.putExtra("CropImageMode", 1); intent2.putExtra("CropImage_OutputPath", d); intent2.putExtra("CropImage_ImgPath", d); a.ezn.a((Activity) this, intent2, 4); return; } return; case 4: if (intent != null) { d = intent.getStringExtra("CropImage_OutputPath"); if (d == null) { x.e("MicroMsg.BottleSettignsPersonalInfoUI", "crop picture failed"); return; } else { new o(this.mController.tml, d).b(2, null); return; } } return; default: return; } } public final void jX(String str) { if (str != null && str.equals(ab.XV(com.tencent.mm.model.q.GF()))) { Bitmap decodeResource; Bitmap a = com.tencent.mm.aa.c.a(str, false, -1); if (a == null) { a = com.tencent.mm.aa.c.a(com.tencent.mm.model.q.GF(), false, -1); } if (a == null) { decodeResource = BitmapFactory.decodeResource(getResources(), R.g.default_avatar); } else { decodeResource = a; } ((HeadImgPreference) this.eOE.ZZ("bottle_settings_change_avatar")).O(decodeResource); } } }
package com.example.karan.instagramlogin.rest.services; import com.example.karan.instagramlogin.models.AuthToken; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; public interface Auth { @FormUrlEncoded @POST("oauth/access_token") Call<AuthToken>getAuthToken(@Field("client_id")String clientid,@Field("client_secret")String client_secret,@Field("grant_type")String grant_type ,@Field("redirect_uri")String redirect_uri,@Field("code")String code); }
package tom.graphic.BeanUtils; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.awt.Toolkit; import java.beans.PropertyEditorSupport; import java.io.PrintStream; // Referenced classes of package tom.graphic.BeanUtils: // FileNameEditor public class ImageEditor extends FileNameEditor { Image value; static String lastValue = ""; public ImageEditor() { value = null; super.value = "Select..."; } public String getAsText() { return lastValue; } public Object getValue() { return value; } public void paintValue(Graphics g, Rectangle rectangle) { if (value != null || value.getWidth(null) > 2) { g.setColor(Color.black); g.clearRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height); g.drawImage(value, rectangle.x, rectangle.y, null); } else { super.paintValue(g, rectangle); } } public void setAsText(String s) throws IllegalArgumentException { setValue(Toolkit.getDefaultToolkit().getImage(s)); lastValue = s; } public void setValue(Object obj) { value = (Image)obj; System.out.println("W:" + value.getWidth(null) + " " + value.getHeight(null)); firePropertyChange(); } }
/** * Copyright (c) 2016, 指端科技. */ package com.rofour.baseball.service.manager.impl; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Service; import com.rofour.baseball.common.WebUtils; import com.rofour.baseball.controller.model.manager.QuotaInfo; import com.rofour.baseball.dao.manager.bean.QuotaBean; import com.rofour.baseball.dao.manager.mapper.QuotaMapper; import com.rofour.baseball.exception.BusinessException; import com.rofour.baseball.service.manager.QuotaService; import static java.awt.SystemColor.info; /** * @ClassName: QuotaImpl * @Description: 指标配置接口实现 * @author xl * @date 2016年7月18日 下午3:46:02 */ @Service("quotaService") public class QuotaImpl implements QuotaService { @Autowired @Qualifier("quotaMapper") private QuotaMapper dao; @Autowired private WebUtils webUtils; /** * @Description: 按主键查询指标 * @param quotaId * @return * @see com.rofour.baseball.service.manager.QuotaService#selectById(int) */ @Override public QuotaInfo selectById(int quotaId) { QuotaBean quotaBean = dao.selectById(quotaId); if (quotaBean == null) { throw new BusinessException("105"); } QuotaInfo quotaInfo = new QuotaInfo(); BeanUtils.copyProperties(quotaBean, quotaInfo); return quotaInfo; } /** * @Description: 查询所有指标 * @return * @see com.rofour.baseball.service.manager.QuotaService#selectAll() */ @Override public List<QuotaInfo> selectAll(QuotaInfo quotaIfo) { List<QuotaBean> quotaBeans = dao.selectAll(quotaIfo); if (quotaBeans == null || quotaBeans.isEmpty()) { throw new BusinessException("105"); } List<QuotaInfo> quotaInfos = new ArrayList<QuotaInfo>(); for (QuotaBean item : quotaBeans) { QuotaInfo quotaInfo = new QuotaInfo(); BeanUtils.copyProperties(item, quotaInfo); quotaInfos.add(quotaInfo); } return quotaInfos; } /** * @Description: 查询在用指标总数 * @return * @see com.rofour.baseball.service.manager.QuotaService#getQuotaCount() */ @Override public int getQuotaCount() { return dao.getQuotaCount(); } /** * @Description: 删除指标 * @param quotaId * @return * @see com.rofour.baseball.service.manager.QuotaService#deleteById(int) */ @Override public int deleteById(int quotaId, HttpServletRequest request) { int rtn = dao.deleteById(quotaId); if (rtn == 0) { throw new BusinessException("105"); } QuotaInfo info = new QuotaInfo(); info.setQuotaId(quotaId); webUtils.userDeleteLog(request, 9, info); return rtn; } /** * @Description: 批量删除 * @param quotaIds * @return * @see com.rofour.baseball.service.manager.QuotaService#deleteBatchByIds(java.util.List) */ @Override public int deleteBatchByIds(List<Integer> quotaIds, HttpServletRequest request) { int rtn = dao.deleteBatchByIds(quotaIds); if (rtn == 0) { throw new BusinessException("105"); } QuotaInfo info = new QuotaInfo(); for (Integer item : quotaIds) { info.setQuotaId(item); webUtils.userDeleteLog(request, 9, info); } return rtn; } /** * @Description: 批量启用 * @param quotaIds * @return * @see com.rofour.baseball.service.manager.QuotaService#activeBatchByIds(java.util.List) */ @Override public int activeBatchByIds(List<Integer> quotaIds, HttpServletRequest request) { int rtn = dao.activeBatchByIds(quotaIds); if (rtn == 0) { throw new BusinessException("105"); } QuotaInfo info = new QuotaInfo(); for (Integer item : quotaIds) { info.setQuotaId(item); webUtils.userDeleteLog(request, 9, info); } return rtn; } /** * @Description: 新增指标 * @param info * @return * @see com.rofour.baseball.service.manager.QuotaService#insert(com.rofour.baseball.controller.model.manager.QuotaInfo) */ @Override public int insert(QuotaInfo info, HttpServletRequest request) { QuotaBean quotaBean = new QuotaBean(); if (info == null) { throw new BusinessException("110"); } BeanUtils.copyProperties(info, quotaBean); int rtn = dao.isQuotaIdExist(quotaBean); if (rtn > 0) { throw new BusinessException("01042"); } rtn = dao.isQuotaExist(quotaBean); if (rtn > 0) { throw new BusinessException("01041"); } rtn = dao.insert(quotaBean); webUtils.userDeleteLog(request, 9, info); return rtn; } /** * @Description: 更新指标 * @param quotaId * @return * @see com.rofour.baseball.service.manager.QuotaService#updateById(int) */ @Override public int updateById(QuotaInfo info, HttpServletRequest request) { if (info == null) { throw new BusinessException("110"); } QuotaBean quotaBean = new QuotaBean(); BeanUtils.copyProperties(info, quotaBean); int rtn = 0; if(quotaBean.getOldQuotaId()!=quotaBean.getQuotaId()){ rtn = dao.isQuotaIdExist(quotaBean);//验证新的ID是否存在 if (rtn > 0) {//Id已存在 throw new BusinessException("01042"); } rtn = dao.isQuotaExist(quotaBean);//验证名称和字段 if (rtn > 0) { throw new BusinessException("01041"); } rtn = dao.updateDelById(quotaBean);//删除原纪录 rtn = dao.insert(quotaBean); }else{ rtn = dao.isQuotaExist(quotaBean);//验证名称和字段 if (rtn > 1) { throw new BusinessException("01041"); } rtn = dao.updateById(quotaBean);// } // webUtils.userDeleteLog(request, 9, info); return rtn; } }
package org.sbbs.app.security.service.impl; import java.util.Iterator; import java.util.List; import org.sbbs.app.security.dao.UrlSecurityResourceDao; import org.sbbs.app.security.model.UrlSecurityResource; import org.sbbs.app.security.service.UrlSecurityResourceManager; import org.sbbs.base.service.impl.BaseManagerImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service("urlSecurityResourceManager") public class UrlSecurityResourceManagerImpl extends BaseManagerImpl<UrlSecurityResource, Long> implements UrlSecurityResourceManager { private UrlSecurityResourceDao urlSecurityResourceDao; @Autowired public UrlSecurityResourceManagerImpl( UrlSecurityResourceDao urlSecurityResourceDao) { super(urlSecurityResourceDao); this.urlSecurityResourceDao = urlSecurityResourceDao; } @Override public void initUrlResourceRepo(List resList) { // this.urlSecurityResourceDao.clearUrlResourceRepo(); for (Iterator iterator = resList.iterator(); iterator.hasNext();) { UrlSecurityResource res = (UrlSecurityResource) iterator.next(); this.urlSecurityResourceDao.save(res); } } }
package com.framework.model; import java.io.Serializable; import java.util.Date; public class SysCommonFileInfo implements Serializable { /** * */ private static final long serialVersionUID = -4388795785789498506L; private Integer id; private String businessId; private String businessType; private String fileType; private String fileName; private String path; private String waterPath; private String thumbPath; private Date createDate; private String createBy; private Date modifyDate; private String modifyBy; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getBusinessId() { return businessId; } public void setBusinessId(String businessId) { this.businessId = businessId; } public String getBusinessType() { return businessType; } public void setBusinessType(String businessType) { this.businessType = businessType; } public String getFileType() { return fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getWaterPath() { return waterPath; } public void setWaterPath(String waterPath) { this.waterPath = waterPath; } public String getThumbPath() { return thumbPath; } public void setThumbPath(String thumbPath) { this.thumbPath = thumbPath; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public Date getModifyDate() { return modifyDate; } public void setModifyDate(Date modifyDate) { this.modifyDate = modifyDate; } public String getModifyBy() { return modifyBy; } public void setModifyBy(String modifyBy) { this.modifyBy = modifyBy; } }
package chap06.sec13.exam02_constructor_access_package1; public class B { // Çʵå A a1 = new A(true); A a2 = new A(1); // A a3 = new A("a"); }
package com.example.taras.task_course; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.view.ContextThemeWrapper; import android.support.v7.widget.PopupMenu; import android.text.Html; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ExpandableListView; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleExpandableListAdapter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class History extends Activity implements PopupMenu.OnMenuItemClickListener { private DBHelper usersDB; private ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_history); listView = (ListView) findViewById(R.id.listView); usersDB = new DBHelper(this); SQLiteDatabase database = usersDB.getWritableDatabase(); Cursor cursor = database.query(DBHelper.TABLE_PAY, null, null, null, null, null, null); List<String> payment = new ArrayList<>(); while (cursor.moveToNext()) { String userName = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_USER_NAME)); String year = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_YEAR)); String month = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_MONTH)); String lightVol = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_LIGHT)); String lightPay = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_LIGHT_MONEY)); String gasVol = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_GAS)); String gasPay = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_GAS_MONEY)); String waterVol = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_WATER)); String waterPay = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_WATER_MONEY)); String sumUp = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_SUM_UP)); if (MainProgram.getActiveUser().equals(userName)) { payment.add(year + " " + month + ": " + "\nсвітло(" + lightVol + " кВт/год, " + lightPay + " грн." + "), " + "\nгаз(" + gasVol + " " + " куб." + ", " + gasPay + " грн." + "), " + "\nвода(" + waterVol + " " + " куб." + ", " + waterPay + " грн." + "), " + "\nсума: " + sumUp + " грн."); } } cursor.close(); database.close(); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, payment); listView.setAdapter(adapter); //Очистити базу ImageView image = (ImageView) findViewById(R.id.btn_clear_db); image.setOnClickListener(onClickListener); } //Popup View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View v) { showPopup(v); } }; public void showPopup(View v) { Context wrapper = new ContextThemeWrapper(this, R.style.MyPopupMenu); PopupMenu popup = new PopupMenu(wrapper, v); popup.setOnMenuItemClickListener(this); popup.inflate(R.menu.menu_clear); popup.show(); } @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.menu_clear: SQLiteDatabase database = usersDB.getWritableDatabase(); listView.setAdapter(null); database.delete(DBHelper.TABLE_PAY, DBHelper.KEY_USER_NAME + " = ?", new String[]{MainProgram.getActiveUser()}); database.close(); default: return false; } } }
package boundary; import entity.Commande; import entity.Ingredient; import entity.Pain; import entity.Sandwich; import javax.ejb.Stateless; import javax.persistence.*; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * Created by Vivien on 13/02/2017. */ @Stateless public class SandwichResource { @PersistenceContext EntityManager em; /** * Methode permettant de recuperer un sandiwch a partir de son id * @param id id du sandwich * @return sandiwh recupere */ public Sandwich findById(String id) { return this.em.find(Sandwich.class, id); } /** * Methode permettant d'obtenir la liste de tous les sandwich avec l'id de la commande * @param id commande * @return liste des sandwich */ public List<Sandwich> findAll(String commandeId) { Query q = this.em.createQuery("SELECT p FROM Sandwich p where p.commande.id= :id"); q.setParameter("id", commandeId); return q.getResultList(); } /** * Methode permettant d'obtenir la liste de tous les sandwich * @return liste des sandwich */ public List<Sandwich> findAll() { Query q = this.em.createNamedQuery("Sandwich.findAll", Sandwich.class); q.setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH); return q.getResultList(); } /** * Methode permettant d'enregistrer un Sandwich * @param s sandwich à enregistrer * @param cheminId id sandich * @return Sandwich enregistre */ public Sandwich save(Sandwich s, String cheminId) { s.setId(UUID.randomUUID().toString()); s.setCommande(this.em.find(Commande.class, cheminId)); s.setIngredients(new ArrayList<>()); this.em.merge(s); return s; } /** * Methode permettant de supprimer un Sandwich * @param id id du Sandwich a supprimer */ public void delete(String id) { try { Sandwich ref = this.em.getReference(Sandwich.class, id); this.em.remove(ref); } catch (EntityNotFoundException e) { } } /** * Methode permettant d'ajouter un ingredient a un sandwich * @param id id du sandiwh a ajouter * @param ing ingredient a rajouter */ public Sandwich addOneIngredient(String id, Ingredient ing) { Sandwich sandwich = this.em.getReference(Sandwich.class, id); sandwich.addIngredient(ing); return this.em.merge(sandwich); } /** * Methode permettant d'ajouter un pain a un sandwich * @param id id du sandiwh a ajouter * @param pain pain a rajouter */ public Sandwich addPain(String id, Pain pain) { Sandwich sandwich = this.em.getReference(Sandwich.class, id); sandwich.setType_pain(pain); return this.em.merge(sandwich); } }
package net.sourceforge.vrapper.utils; import java.util.HashMap; import net.sourceforge.vrapper.keymap.KeyMap; import net.sourceforge.vrapper.platform.KeyMapProvider; /** * Uses a {@link HashMap} to store different keymaps. {@link KeyMap} instances * are created lazily when they are looked up for the first time. * * @author Matthias Radig */ public class DefaultKeyMapProvider implements KeyMapProvider { private final HashMap<String, KeyMap> keymaps = new HashMap<String, KeyMap>(); public KeyMap getKeyMap(String id) { if (!keymaps.containsKey(id)) { keymaps.put(id, new KeyMap()); } return keymaps.get(id); } }
package tarea06paciente; import java.io.Serializable; public class Paciente implements Serializable { private static final long serialVersionUID = 1L; private int habitacion; private int cama; private String nombre; private String apellido1; private String apellido2; private String dieta; // Nota: Con el modificador transient indicamos que un atributo no ha de // serializarse // Al atributo no se le incluye el valor en el objeto serializado. // Cuando es deserializado el atributo es inicializado con su valor por defecto // según // su tipo. // Ejemplo: Si no quisieramos serializar dieta hariamos: // private transient String dieta; public Paciente(int habitacion, int cama, String nombre, String apellido1, String apellido2, String dieta) { this.habitacion = habitacion; this.cama = cama; this.nombre = nombre; this.apellido1 = apellido1; this.apellido2 = apellido2; this.dieta = dieta; } public Paciente() { } public int getHabitacion() { return habitacion; } public void setHabitacion(int habitacion) { this.habitacion = habitacion; } public int getCama() { return cama; } public void setCama(int cama) { this.cama = cama; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellido1() { return apellido1; } public void setApellido1(String apellido1) { this.apellido1 = apellido1; } public String getApellido2() { return apellido2; } public void setApellido2(String apellido2) { this.apellido2 = apellido2; } public String getDieta() { return dieta; } public void setDieta(String dieta) { this.dieta = dieta; } @Override public String toString() { return habitacion + "-" + cama + " , " + nombre + " , " + apellido1 + " , " + apellido2 + " , " + dieta; } }
package mk.ukim.finki.os.examples.ExamIO.charcount; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; public class CharCount { public static void main(String[] args) throws IOException { CharCount charCount = new CharCount(); List<byte[]> result = charCount.read("data\\input.txt"); int s = result.size(); System.out.print("["); for (byte[] element : result) { System.out.print("["); for (byte b : element) { System.out.print(b - '0'); } s--; System.out.print("]"); if(s>0){ System.out.print(","); } } System.out.print("]"); } private List<byte[]> read(String input) throws IOException { List<byte[]> result = new ArrayList<>(); try( InputStream is = new FileInputStream(input) ){ int b, len; while((b = is.read()) != -1){ len = b - '0'; System.out.println("len : " + len); byte[] element = readElement(is,len); result.add(element); } } return result; } private byte[] readElement(InputStream is, int len) throws IOException { byte[] element = new byte[len]; for(int i= 0;i<len;i++){ int b = is.read(); if(b==-1){ throw new IllegalStateException("Nema " + len + " bajti vo fajlot za da se porocita element."); } element[i] = (byte)b; } return element; } }
package com.studio.saradey.aplicationvk.ui.fragment; import android.content.Intent; import android.os.Bundle; import android.view.View; import com.arellomobile.mvp.presenter.InjectPresenter; import com.studio.saradey.aplicationvk.MyAplication; import com.studio.saradey.aplicationvk.R; import com.studio.saradey.aplicationvk.mvp.presenter.BaseFeedPresenter; import com.studio.saradey.aplicationvk.mvp.presenter.NewsFeedPresenter; import com.studio.saradey.aplicationvk.rest.api.WallApi; import com.studio.saradey.aplicationvk.ui.activity.CreatePostActivity; import javax.inject.Inject; public class NewsFeedFragment extends BaseFeedFragment { //Для отображения записей текущего пользователя будем // использовать фрагмент, наследованный от NewsFeedFragment. @Inject WallApi mWallApi; @InjectPresenter NewsFeedPresenter mPresenter; public NewsFeedFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MyAplication.getApplicationComponent().inject(this); } @Override protected BaseFeedPresenter onCreateFeedPresenter() { return mPresenter; } @Override public int onCreateToolbarTitle() { return R.string.screen_name_news; } //Реализуем слушатели для FAB и переопределяем метод needFab в CommentsFragment @Override public void onResume() { super.onResume(); getBaseActivity().mFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), CreatePostActivity.class); startActivityForResult(intent, 0); } }); } @Override public boolean needFab() { return true; } }
package com.iuce.diaryandroidproject2; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Window; import android.view.WindowManager; public class AcilisActivity extends Activity { private static String TAG = AcilisActivity.class.getName(); private static long SLEEP_TIME = 4; // Bekletilecek saniye @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); // Splash ekrandan // basligi kaldirir this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Bilgi cubugunu // kaldirir setContentView(R.layout.activity_acilisekrani); IntentLauncher launcher = new IntentLauncher(); launcher.start(); } private class IntentLauncher extends Thread { @Override public void run() { try { // Sleeping Thread.sleep(SLEEP_TIME * 500); } catch (Exception e) { Log.e(TAG, e.getMessage()); } // Start main activity Intent intent = new Intent(AcilisActivity.this, LoginActivity.class); AcilisActivity.this.startActivity(intent); AcilisActivity.this.finish(); } } }
/* * This file is part of jGui API, licensed under the MIT License (MIT). * * Copyright (c) 2016 johni0702 <https://github.com/johni0702> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package de.johni0702.minecraft.gui.popup; import de.johni0702.minecraft.gui.GuiRenderer; import de.johni0702.minecraft.gui.RenderInfo; import de.johni0702.minecraft.gui.container.GuiContainer; import de.johni0702.minecraft.gui.container.GuiPanel; import de.johni0702.minecraft.gui.container.GuiScrollable; import de.johni0702.minecraft.gui.container.GuiVerticalList; import de.johni0702.minecraft.gui.element.GuiButton; import de.johni0702.minecraft.gui.element.GuiElement; import de.johni0702.minecraft.gui.element.GuiTextField; import de.johni0702.minecraft.gui.element.advanced.GuiDropdownMenu; import de.johni0702.minecraft.gui.function.Typeable; import de.johni0702.minecraft.gui.layout.CustomLayout; import de.johni0702.minecraft.gui.layout.HorizontalLayout; import de.johni0702.minecraft.gui.layout.VerticalLayout; import de.johni0702.minecraft.gui.utils.Colors; import de.johni0702.minecraft.gui.utils.Consumer; import de.johni0702.minecraft.gui.utils.lwjgl.Dimension; import de.johni0702.minecraft.gui.utils.lwjgl.ReadableDimension; import de.johni0702.minecraft.gui.utils.lwjgl.ReadablePoint; import de.johni0702.minecraft.gui.versions.MCVer; import java.io.File; import java.io.IOException; import java.nio.file.InvalidPathException; import java.util.*; import java.util.concurrent.CompletableFuture; //#if MC>=11400 import de.johni0702.minecraft.gui.versions.MCVer.Keyboard; //#else //$$ import org.lwjgl.input.Keyboard; //#endif public class GuiFileChooserPopup extends AbstractGuiPopup<GuiFileChooserPopup> implements Typeable { public static GuiFileChooserPopup openSaveGui(GuiContainer container, String buttonLabel, String...fileExtensions) { GuiFileChooserPopup popup = new GuiFileChooserPopup(container, fileExtensions, false).setBackgroundColor(Colors.DARK_TRANSPARENT); popup.acceptButton.setI18nLabel(buttonLabel); popup.open(); return popup; } public static GuiFileChooserPopup openLoadGui(GuiContainer container, String buttonLabel, String...fileExtensions) { GuiFileChooserPopup popup = new GuiFileChooserPopup(container, fileExtensions, true).setBackgroundColor(Colors.DARK_TRANSPARENT); popup.acceptButton.setI18nLabel(buttonLabel).setDisabled(); popup.open(); return popup; } private Consumer<File> onAccept = (file) -> {}; private Runnable onCancel = () -> {}; private final GuiScrollable pathScrollable = new GuiScrollable(popup) { @Override public void draw(GuiRenderer renderer, ReadableDimension size, RenderInfo renderInfo) { scrollX(0); super.draw(renderer, size, renderInfo); } }; private final GuiPanel pathPanel = new GuiPanel(pathScrollable).setLayout(new HorizontalLayout()); private final GuiVerticalList fileList = new GuiVerticalList(popup); private final GuiTextField nameField = new GuiTextField(popup).onEnter(new Runnable() { @Override public void run() { if (acceptButton.isEnabled()) { acceptButton.onClick(); } } }).onTextChanged(new Consumer<String>() { @Override public void consume(String oldName) { updateButton(); } }).setMaxLength(Integer.MAX_VALUE); private final GuiButton acceptButton = new GuiButton(popup).onClick(new Runnable() { @Override public void run() { String fileName = nameField.getText(); if (!load && fileExtensions.length > 0) { if (!hasValidExtension(fileName)) { fileName = fileName + "." + fileExtensions[0]; } } onAccept.consume(new File(folder, fileName)); close(); } }).setSize(50, 20); private final GuiButton cancelButton = new GuiButton(popup).onClick(new Runnable() { @Override public void run() { onCancel.run(); close(); } }).setI18nLabel("gui.cancel").setSize(50, 20); { fileList.setLayout(new VerticalLayout().setSpacing(1)); popup.setLayout(new CustomLayout<GuiPanel>() { @Override protected void layout(GuiPanel container, int width, int height) { pos(pathScrollable, 0, 0); size(pathScrollable, width, 20); pos(cancelButton, width - width(cancelButton), height - height(cancelButton)); pos(acceptButton, x(cancelButton) - 5 - width(acceptButton), y(cancelButton)); size(nameField, x(acceptButton) - 5, 20); pos(nameField, 0, height - height(nameField)); pos(fileList, 0, y(pathScrollable) + height(pathScrollable) + 5); size(fileList, width, y(nameField) - y(fileList) - 5); } @Override public ReadableDimension calcMinSize(GuiContainer container) { return new Dimension(300, 200); } }); } private final String[] fileExtensions; private final boolean load; private File folder; public GuiFileChooserPopup(GuiContainer container, String[] fileExtensions, boolean load) { super(container); this.fileExtensions = fileExtensions; this.load = load; setFolder(new File(".")); } protected void updateButton() { String name = nameField.getText(); File file = new File(folder, name); // File name must not contain boolean valid = !name.contains(File.separator); // Name must not contain any illegal characters (depends on OS) try { //noinspection ResultOfMethodCallIgnored file.toPath(); } catch (InvalidPathException ignored) { valid = false; } // If we're loading, the file must exist if (load) { valid &= file.exists(); } acceptButton.setEnabled(valid); } public void setFolder(File folder) { if (!folder.isDirectory()) { throw new IllegalArgumentException("Folder has to be a directory."); } try { this.folder = folder = folder.getCanonicalFile(); } catch (IOException e) { close(); throw new RuntimeException(e); } updateButton(); for (GuiElement element : new ArrayList<>(pathPanel.getElements().keySet())) { pathPanel.removeElement(element); } for (GuiElement element : new ArrayList<>(fileList.getListPanel().getElements().keySet())) { fileList.getListPanel().removeElement(element); } File[] files = folder.listFiles(); if (files != null) { Arrays.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { if (f1.isDirectory() && !f2.isDirectory()) { return -1; } else if (!f1.isDirectory() && f2.isDirectory()) { return 1; } return f1.getName().compareToIgnoreCase(f2.getName()); } }); for (final File file : files) { if (file.isDirectory()) { fileList.getListPanel().addElements(new VerticalLayout.Data(0), new GuiButton().onClick(new Runnable() { @Override public void run() { setFolder(file); } }).setLabel(file.getName() + File.separator)); } else { if (hasValidExtension(file.getName())) { fileList.getListPanel().addElements(new VerticalLayout.Data(0), new GuiButton().onClick(new Runnable() { @Override public void run() { setFileName(file.getName()); } }).setLabel(file.getName())); } } } } fileList.setOffsetY(0); File[] roots = File.listRoots(); if (roots != null && roots.length > 1) { // Windows can have multiple file system roots // So we place a dropdown menu (skinned like a button) at the front of the path final GuiDropdownMenu<File> dropdown = new GuiDropdownMenu<File>(pathPanel) { private final GuiButton skin = new GuiButton(); @Override protected ReadableDimension calcMinSize() { ReadableDimension dim = super.calcMinSize(); return new Dimension(dim.getWidth() - 5 - MCVer.getFontRenderer().fontHeight, dim.getHeight()); } @Override public void layout(ReadableDimension size, RenderInfo renderInfo) { super.layout(size, renderInfo); if (renderInfo.layer == 0) { skin.layout(size, renderInfo); } } @Override public void draw(GuiRenderer renderer, ReadableDimension size, RenderInfo renderInfo) { super.draw(renderer, size, renderInfo); if (renderInfo.layer == 0) { skin.setLabel(getSelectedValue().toString()); skin.draw(renderer, size, renderInfo); } } }; List<File> actualRoots = new ArrayList<>(); File selected = null; for (File root : roots) { // Windows apparently also has file system roots that aren't directories, so we'll have to filter those if (root.isDirectory()) { actualRoots.add(root); if (folder.getAbsolutePath().startsWith(root.getAbsolutePath())) { selected = root; } } } assert selected != null; // First set values and current selection dropdown.setValues(actualRoots.toArray(new File[actualRoots.size()])).setSelected(selected); // then add selection handler afterwards dropdown.onSelection(new Consumer<Integer>() { @Override public void consume(Integer old) { setFolder(dropdown.getSelectedValue()); } }); } LinkedList<File> parents = new LinkedList<>(); while (folder != null) { parents.addFirst(folder); folder = folder.getParentFile(); } for (final File parent : parents) { pathPanel.addElements(null, new GuiButton().onClick(new Runnable() { @Override public void run() { setFolder(parent); } }).setLabel(parent.getName() + File.separator)); } pathScrollable.setOffsetX(Integer.MAX_VALUE); } public void setFileName(String fileName) { this.nameField.setText(fileName); this.nameField.setCursorPosition(fileName.length()); updateButton(); } private boolean hasValidExtension(String name) { for (String fileExtension : fileExtensions) { if (name.endsWith("." + fileExtension)) { return true; } } return false; } @Override protected GuiFileChooserPopup getThis() { return this; } public GuiFileChooserPopup onAccept(Consumer<File> onAccept) { this.onAccept = onAccept; return this; } public GuiFileChooserPopup onCancel(Runnable onCancel) { this.onCancel = onCancel; return this; } @Override public boolean typeKey(ReadablePoint mousePosition, int keyCode, char keyChar, boolean ctrlDown, boolean shiftDown) { if (keyCode == Keyboard.KEY_ESCAPE) { cancelButton.onClick(); return true; } return false; } public GuiButton getAcceptButton() { return this.acceptButton; } public GuiButton getCancelButton() { return this.cancelButton; } }
package jupiterpa.warehouse; import lombok.*; import lombok.experimental.*; import jupiterpa.util.*; @Data @Accessors(chain = true) public class MaterialDocument { EID documentNumber; EID materialId; int quantity; EID salesOrderId; EID deliveryId; int partner; }
package com.wipe.zc.journey.ui.fragment; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.TextView; import com.easemob.chat.EMChat; import com.easemob.chat.EMChatManager; import com.easemob.chat.EMContactListener; import com.easemob.chat.EMContactManager; import com.easemob.chat.EMMessage; import com.easemob.chat.EMNotifier; import com.easemob.exceptions.EaseMobException; import com.wipe.zc.journey.R; import com.wipe.zc.journey.domain.ChatMessage; import com.wipe.zc.journey.global.MyApplication; import com.wipe.zc.journey.ui.activity.ChatActivity; import com.wipe.zc.journey.ui.activity.HomeActivity; import com.wipe.zc.journey.ui.adapter.FriendsAdapter; import com.wipe.zc.journey.util.LogUtil; import com.wipe.zc.journey.util.ToastUtil; import com.wipe.zc.journey.util.ViewUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class FriendsFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener { private View view; private SwipeRefreshLayout srl_friends; private RecyclerView rv_friends; private List list = new ArrayList(); private FriendsAdapter adapter; private MessageReceiver msgReceiver; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = View.inflate(MyApplication.getContext(), R.layout.fragment_friends, null); //初始化标题 ((HomeActivity) getActivity()).setTitleText("好友"); initWidget(); setReceiver(); return view; } @Override public void onStart() { super.onStart(); //注册监听 initMessageBroadCastReceiver(); if (adapter != null) { adapter.notifyDataSetChanged(); } } @Override public void onStop() { super.onStop(); getActivity().unregisterReceiver(msgReceiver); } /** * 设置消息接收 */ private void setReceiver() { IntentFilter filter = new IntentFilter("im.add.broadcast.action"); getActivity().registerReceiver(receiver, filter); } /** * 初始化控件 */ private void initWidget() { srl_friends = (SwipeRefreshLayout) view.findViewById(R.id.srl_friends); rv_friends = (RecyclerView) view.findViewById(R.id.rv_friends); TextView tv_friends_add = (TextView) view.findViewById(R.id.tv_friends_add); //设置SwipeRefreshLayout的刷新颜色 srl_friends.setColorSchemeColors(Color.RED, Color.YELLOW, Color.BLUE, Color.GREEN); srl_friends.setOnRefreshListener(this); // //环信初始化 // EMContactManager.getInstance().setContactListener( // new MyContactListener()); // EMChat.getInstance().setAppInited(); //初始化RecyclerView initRecyclerView(); //初始化好友列表 initFriendsList(); //设置点击事件 tv_friends_add.setOnClickListener(this); } /** * 初始化RecyclerView的基本设置 */ private void initRecyclerView() { //控制布局方式 rv_friends.setLayoutManager(new LinearLayoutManager(getActivity())); //创建适配器 adapter = new FriendsAdapter(list, (HomeActivity) getActivity()); //设置适配器 rv_friends.setAdapter(adapter); //控制间隔 //rv_friends.addItemDecoration(); //控制条目添加移除动画 } /** * 初始化好友列表 */ private void initFriendsList() { try { List<String> list_friends = EMContactManager.getInstance().getContactUserNames(); if (list_friends != null) { list.clear(); list.addAll(list_friends); adapter.notifyDataSetChanged(); } } catch (Exception e) { e.printStackTrace(); } } /** * 刷新监听 */ public void onRefresh() { initFriendsList(); srl_friends.setRefreshing(false); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.tv_friends_add: View addView = LayoutInflater.from(getActivity()).inflate(R.layout .layout_friends_add, null); final EditText et_friends_add_name = (EditText) addView.findViewById(R.id .et_friends_add_name); final EditText et_friends_add_verify = (EditText) addView.findViewById(R.id .et_friends_add_verify); final View ve_friends_add_name = addView.findViewById(R.id.ve_friends_add_name); final View ve_friends_add_verify = addView.findViewById(R.id.ve_friends_add_verify); new AlertDialog.Builder(getActivity()).setTitle("添加好友").setView(addView) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (ViewUtil.checkEmptyData(et_friends_add_name, ve_friends_add_name) && ViewUtil.checkEmptyData (et_friends_add_verify, ve_friends_add_verify)) { dialog.dismiss(); String idStr = et_friends_add_name.getText().toString().trim(); String reasonStr = et_friends_add_verify.getText().toString() .trim(); try { EMContactManager.getInstance().addContact(idStr, reasonStr); ToastUtil.shortToast("成功发送请求,等待对方相应"); } catch (EaseMobException e) { e.printStackTrace(); Log.i("TAG", "addContacterrcode==>" + e.getErrorCode()); }// 需异步处理 } else { //信息输入不完整 ToastUtil.shortToast("请输入完整请求信息"); } } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }).create().show(); break; } } // private class MyContactListener implements EMContactListener { // @Override // public void onContactAdded(List<String> list) { //添加好友 // FriendsFragment.this.list.clear(); // FriendsFragment.this.list.addAll(list); // adapter.notifyItemInserted(0); // } // // @Override // public void onContactDeleted(List<String> list) { // // } // // @Override // public void onContactInvited(String s, String s1) { //收到好友请求 // //显示好友请求 // //收到好友邀请 // LogUtil.i("环信好友", "好友:" + s + "申请说明" + s1); // System.out.println("环信好友------好友:" + s + "申请说明" + s1); // } // // @Override // public void onContactAgreed(String s) { //请求同意 // EMNotifier.getInstance(MyApplication.getContext()).notifyOnNewMsg(); // } // // @Override // public void onContactRefused(String s) { // // } // } BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String result = intent.getExtras().getString("data"); list.clear(); if(result == null){ return; } if (result.contains("-")) { String[] results = result.split("-"); list.addAll(Arrays.asList(results)); } else { list.add(result); } } }; /** * 初始化接受消息监听 */ public void initMessageBroadCastReceiver() { EMChat.getInstance().setAppInited(); msgReceiver = new MessageReceiver(); IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance() .getNewMessageBroadcastAction()); intentFilter.setPriority(3); getActivity().registerReceiver(msgReceiver, intentFilter); } class MessageReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { adapter.notifyDataSetChanged(); ((HomeActivity) getActivity()).setUnreadSign(); } } }
package com.poly.slide3; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; public class ListDemo2 { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); //Set<Integer> list = new HashSet<>(); list.add(20); list.add(20); list.add(10); list.add(30); System.out.println("Elements: " + list.toString()); for (int i = 0; i < list.size(); i++) { System.out.print(" " + list.get(i)); } System.out.println("\n--------------------"); for (Integer item : list) { System.out.println(" " + item); } System.out.println("\n--------------------"); Iterator<Integer> it = list.iterator(); while (it.hasNext()){ Integer item = it.next(); System.out.print(" " + item); } System.out.println("\n--------------------"); list.forEach(item -> System.out.println(" " + item)); } }
package english.parser.implementations.map; import include.learning.perceptron.PackedScoreMap; import include.linguistics.Word; import include.linguistics.english.WordETag; import english.pos.ETag; @SuppressWarnings("serial") public final class WordETagMap extends PackedScoreMap<WordETag> { public WordETagMap(final String input_name, final int table_size) { super(input_name, table_size); } @Override public WordETag loadKeyFromString(final String str) { String[] args = str.split("/"); return new WordETag(new Word(args[0]), new ETag(args[1])); } @Override public String generateStringFromKey(final WordETag key) { return key.first().toString() + "/" + key.second().toString(); } @Override public WordETag allocate_key(final WordETag key) { return new WordETag(key); } }
package com.cw.picker.data; import android.provider.MediaStore; import android.text.TextUtils; import com.cw.picker.entity.Folder; import java.util.ArrayList; public class LoaderM { protected String mineFilter(String[] mineTypes) { if (mineTypes == null) return ""; StringBuilder sb = new StringBuilder(); for (int i = 0; i < mineTypes.length; i++) { if (i == 0) sb.append(" AND ("); sb.append(MediaStore.Files.FileColumns.MIME_TYPE).append("='").append(mineTypes[i]).append("'"); if (i != mineTypes.length - 1) { sb.append(" OR "); } else { sb.append(")"); } } return sb.toString(); } protected String getParent(String path) { String sp[] = path.split("/"); return sp[sp.length - 2]; } protected int hasDir(ArrayList<Folder> folders, String dirName) { for (int i = 0; i < folders.size(); i++) { Folder folder = folders.get(i); if (TextUtils.equals(folder.getName(), dirName)) { return i; } } return -1; } }
package com.ajith.beintouch; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.constraintlayout.widget.ConstraintSet; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.google.firebase.auth.FirebaseAuth; import java.util.ArrayList; public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageHolder> { private ArrayList<Message> messages; private String senderImg, receiverImg; private Context context; public MessageAdapter(ArrayList<Message> messages, String senderImg, String receiverImg, Context context) { this.messages = messages; this.senderImg = senderImg; this.receiverImg = receiverImg; this.context = context; } @NonNull @Override public MessageHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.message_holder,parent,false); return new MessageHolder(view); } @Override public void onBindViewHolder(@NonNull MessageHolder holder, int position) { holder.txtMessage.setText(messages.get(position).getContet()); ConstraintLayout constraintLayout = holder.ccll; if (messages.get(position).getSender().equals(FirebaseAuth.getInstance().getCurrentUser().getEmail())){ Glide.with(context).load(senderImg).error(R.drawable.account_img).placeholder(R.drawable.account_img).into(holder.profImage); ConstraintSet constraintSet = new ConstraintSet(); constraintSet.clone(constraintLayout); constraintSet.clear(R.id.profile_cardView,ConstraintSet.LEFT); constraintSet.clear(R.id.txt_message_content,ConstraintSet.LEFT); constraintSet.connect(R.id.profile_cardView,ConstraintSet.RIGHT,R.id.ccLayout,ConstraintSet.RIGHT,0); constraintSet.connect(R.id.txt_message_content,ConstraintSet.RIGHT,R.id.profile_cardView,ConstraintSet.LEFT,0); constraintSet.applyTo(constraintLayout); }else { Glide.with(context).load(receiverImg).error(R.drawable.account_img).placeholder(R.drawable.account_img).into(holder.profImage); ConstraintSet constraintSet = new ConstraintSet(); constraintSet.clone(constraintLayout); constraintSet.clear(R.id.profile_cardView,ConstraintSet.RIGHT); constraintSet.clear(R.id.txt_message_content,ConstraintSet.RIGHT); constraintSet.connect(R.id.profile_cardView,ConstraintSet.LEFT,R.id.ccLayout,ConstraintSet.LEFT,0); constraintSet.connect(R.id.txt_message_content,ConstraintSet.LEFT,R.id.profile_cardView,ConstraintSet.RIGHT,0); constraintSet.applyTo(constraintLayout); } } @Override public int getItemCount() { return messages.size(); } class MessageHolder extends RecyclerView.ViewHolder{ ConstraintLayout ccll; TextView txtMessage; ImageView profImage; public MessageHolder(@NonNull View itemView) { super(itemView); ccll = itemView.findViewById(R.id.ccLayout); txtMessage = itemView.findViewById(R.id.txt_message_content); profImage = itemView.findViewById(R.id.small_profile_img); } } }
package Types; import java.util.List; public class Loop { List<String> tokens; Variables vars; int depth; Cond cond; Stmtseq stmtseq; public Loop(List tokens,Variables vars, int depth) { this.tokens = tokens; this.depth = depth; this.vars = vars; } public void Parse() { if(Print.printTree) Print.tree(this.getClass().getName(),tokens, depth); if(!tokens.get(0).equals("WHILE")) { Print.error(this.getClass().getName() + " ERROR: Expected 'while'"); } if(!tokens.contains("BEGIN")) { Print.error(this.getClass().getName() + " ERROR: Missing 'begin'"); } if(!tokens.contains("ENDWHILE")) { Print.error(this.getClass().getName() + " ERROR: Missing 'endwhile'"); } cond = new Cond(tokens.subList(1, tokens.indexOf("BEGIN")),vars,depth+1); stmtseq = new Stmtseq(tokens.subList(tokens.indexOf("BEGIN")+1, tokens.lastIndexOf("ENDWHILE")),vars,depth+1); cond.Parse(); stmtseq.Parse(); } public void Exec() { cond.Exec(); while(cond.value) { stmtseq.Exec(); cond.Exec(); } } public void Exec(Variables vars2) { // TODO Auto-generated method stub } }
package com.smxknife.flink.demo._table; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.apache.flink.streaming.api.datastream.DataStreamSource; import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.table.api.EnvironmentSettings; import org.apache.flink.table.api.Table; import org.apache.flink.table.api.bridge.java.StreamTableEnvironment; import static org.apache.flink.table.api.Expressions.$; /** * @author smxknife * 2021/6/8 */ public class CreateTableFromDataStream { public static void main(String[] args) throws Exception { final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); // 使用flink默认的tablestream,创建Table的上下文环境(TableEnvironment) // 注意这里需要指定settings,否则会报错 final EnvironmentSettings settings = EnvironmentSettings.newInstance().useOldPlanner().build(); final StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env, settings); final DataStreamSource<String> socketTextStream = env.socketTextStream("localhost", 8888); final SingleOutputStreamOperator<Persion> personStream = socketTextStream.map(input -> { final String[] array = input.split(" "); return new Persion(array[0].trim(), array[1].trim(), Integer.valueOf(array[2].trim())); }); // 默认使用属性名作为字段 // final Table table1 = tableEnv.fromDataStream(personStream); // table1.printSchema(); // 自定义属性名 final Table table2 = tableEnv.fromDataStream(personStream, $("id").as("p_id"), $("name").as("p_name"), $("age").as("p_age")); // table2.printSchema(); // 这里是从socket中读,是流计算,所以要execute // 这里如果调用tableEnv.execute,会报错 env.execute("xxxxx"); } @NoArgsConstructor @AllArgsConstructor @Data public static class Persion { private String id; private String name; private int age; } }
package com.cookiesncrumbs.msalvio.cpe50_ay1718_1stsem_android; /** * Created by msalvio on 04/10/2017. */ public class MenuItem { private int _id; private String name; private double price; public MenuItem(String name, double price) { this.name = name; this.price = price; } public MenuItem(int _id, String name, double price) { this._id = _id; this.name = name; this.price = price; } public int get_id() { return _id; } public void set_id(int _id) { this._id = _id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }
import org.junit.After; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.net.MalformedURLException; import java.util.concurrent.TimeUnit; /** * Created by Deft on 2017/6/3. */ public class test { private static WebDriver driver; @BeforeClass public static void openPage() throws MalformedURLException { System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe"); driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } @Test public void a () throws InterruptedException { driver.get(Settings.DOMAIN + "/ToFindNanny.jsp"); WebElement register = driver.findElement(By.cssSelector(".glyphicon.glyphicon-user")); register.click(); Thread.sleep(3000); WebElement email = driver.findElement(By.className("swal2-input")); String user = System.currentTimeMillis() + "@qq.com"; email.sendKeys(user); WebElement button1 = driver.findElement(By.cssSelector(".swal2-confirm.swal2-styled")); button1.click(); Thread.sleep(3000); WebElement password = driver.findElement(By.className("swal2-input")); password.sendKeys("1"); WebElement button2 = driver.findElement(By.cssSelector(".swal2-confirm.swal2-styled")); button2.click(); Thread.sleep(3000); WebElement repeatPassword = driver.findElement(By.className("swal2-input")); repeatPassword.sendKeys("1"); WebElement button3 = driver.findElement(By.cssSelector(".swal2-confirm.swal2-styled")); button3.click(); Thread.sleep(1000); WebElement button5 = driver.findElement(By.cssSelector(".swal2-confirm.swal2-styled")); button5.click(); Thread.sleep(1000); WebElement logout = driver.findElement(By.id("logout")); logout.click(); Thread.sleep(1000); WebElement button4 = driver.findElement(By.cssSelector(".swal2-confirm.swal2-styled")); button4.click(); Thread.sleep(1000); WebElement login = driver.findElement(By.cssSelector(".glyphicon.glyphicon-log-in.theme-login")); login.click(); Thread.sleep(3000); WebElement email1 = driver.findElement(By.id("input_email")); email1.sendKeys( user); Thread.sleep(3000); WebElement password1 = driver.findElement(By.id("input_password")); password1.sendKeys("1"); Thread.sleep(8000); WebElement loginButton = driver.findElement(By.id("loginIn")); loginButton.click(); Thread.sleep(8000); Assert.assertEquals("登入成功!", driver.findElement(By.id("swal2-content")).getText()); } @After public void closePage() throws InterruptedException { driver.quit(); } }
/* */ package boardFinder.demo.controller; import boardFinder.demo.domain.RidingTerrain; import boardFinder.demo.service.RidingTerrainService; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * * @author Erik */ @RestController @RequestMapping("/ridingterrain") @CrossOrigin(origins = "http://localhost:4200") public class RidingTypeController { private RidingTerrainService rTService; @Autowired public RidingTypeController(RidingTerrainService rTService) { this.rTService = rTService; } @GetMapping public List<RidingTerrain> getAllRidingTypes() { return rTService.getAllRidingTypes(); } }
import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class linkedlistfailfast { public static void main(String[] args) { List<String> ll = new LinkedList<>(); ll.add("d"); ll.add("e"); ll.add("l"); ll.add("L"); Iterator<String> i = ll.iterator(); while(i.hasNext()) { System.out.println(i.next()); ll.add("s"); } } }
package vc.lang.impl; import java.util.Arrays; public abstract class Syntax { public static final Tokenizer.TokenMatcher doTermination; public static final int MIN_SYMBOL_LEN = 2, MAX_SYMBOL_LEN = 21; public static final byte[] STACK_SHAKE_KEY = "shake".getBytes(), BIN_OP_ADD_KEY = "+".getBytes(), BIN_OP_SUB_KEY = "-".getBytes(), BIN_OP_MUL_KEY = "*".getBytes(), BIN_OP_DIV_KEY = "/".getBytes(), BIN_OP_EQ_KEY = "=".getBytes(), BIN_OP_GT_KEY = ">".getBytes(), BIN_OP_LT_KEY = "<".getBytes(), VEC_LIT_OPEN_KEY = "[".getBytes(), EVAL_KEY = "eval".getBytes(), FUNC_REG_KEY = "as".getBytes(), DO_TRUE_KEY = "if".getBytes(), DO_FALSE_KEY = "else".getBytes(), END_DO_KEY = "endif".getBytes(), NUM_ASSERT_KEY = "num!".getBytes(), STR_ASSERT_KEY = "str!".getBytes(), VEC_ASSERT_KEY = "vec!".getBytes(), SEQ_LEN_KEY = "len".getBytes(), SEQ_NTH_KEY = "nth".getBytes(), SEQ_SET_KEY = "set".getBytes(), SEQ_QNTH_KEY = "quoted-nth".getBytes(), SEQ_USET_KEY = "unquoted-set".getBytes(); static { doTermination = (token) -> { return Arrays.equals(token, END_DO_KEY) || Arrays.equals(token, DO_FALSE_KEY); }; } }
package divers; import java.io.*; import java.util.*; import khaliss_bank_project.Client; public class LoadSaveFile { /*-----------------Class pour la lecture du fichier cible-----------------*/ public static void getListFromFile(String path, ArrayList<Client> listeClient) { File file = new File(path); String[] names = null; try { Scanner inputStream = new Scanner(file); //Flux d'entrée String str = inputStream.next(); names = str.split(","); // On choisit la virgule comme séparateur int nbG = names.length; //Avoir le nombre de courbe ArrayList<String[]> lines = new ArrayList<>();// On stocke les lignes dans un objet ArrayList inputStream.hasNext(); //skip first line while(inputStream.hasNext()) lines.add(inputStream.next().split(",")); for(int i = 0 ; i < nbG ; ++i) { ArrayList<String> gVal = new ArrayList<>(); for(int j = 0 ; j < lines.size() ; ++j) { String f = lines.get(j)[i]; //On parse les valeurs en float gVal.add(f); } listeClient.add(new Client(gVal)); //Ajout des valeurs dans l'ArrayList } inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
package com.j2.iterator.dinermerger.after; import java.util.ArrayList; //import com.j2.iterator.dinermerger.MenuItem; public class PancakeHouseMenuIterator implements Iterator { //MenuItem[] items; ArrayList items; int position=0; public PancakeHouseMenuIterator(ArrayList items){ this.items = items; } public boolean hasNext(){ if(position>=items.size()) { return false; } else{ return true; } } public Object next() { Object object =(Object)items.get(position); position+=1; //return menuItem; return object; } }
package com.tongchen.mediatest; import android.Manifest; import android.annotation.TargetApi; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentUris; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.app.NotificationCompat; import android.support.v4.content.ContextCompat; import android.support.v4.content.FileProvider; import android.support.v7.app.AppCompatActivity; import android.text.format.Time; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends AppCompatActivity implements View.OnClickListener { public static final int TAKE_PHOTO = 1; public static final int CHOOSE_PHOTO = 2; private ImageView picture; private Uri imageUri; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViews(); } private void findViews() { Button notificationBtn = (Button) findViewById(R.id.btn_notification); Button cameraBtn = (Button) findViewById(R.id.btn_camera); Button albumBtn = (Button) findViewById(R.id.btn_album); Button audioBtn = (Button) findViewById(R.id.btn_audio); Button videoBtn = (Button) findViewById(R.id.btn_video); picture = (ImageView) findViewById(R.id.iv_picture); notificationBtn.setOnClickListener(this); cameraBtn.setOnClickListener(this); albumBtn.setOnClickListener(this); audioBtn.setOnClickListener(this); videoBtn.setOnClickListener(this); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case TAKE_PHOTO: if (resultCode == RESULT_OK) { try { // 将拍摄的照片显示出来 Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri)); picture.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } } break; case CHOOSE_PHOTO: if (resultCode == RESULT_OK) { if (Build.VERSION.SDK_INT >= 19) { handleImageOnKitKat(data); } else { handleImageBeforeKitKat(data); } } break; default: break; } } @TargetApi(19) private void handleImageOnKitKat(Intent data) { String imagePath = null; Uri uri = data.getData(); if (DocumentsContract.isDocumentUri(this, uri)) { // 如果是document类型的Uri,则通过document的id处理 String docId = DocumentsContract.getDocumentId(uri); if ("com.android.providers.media.documents".equals(uri.getAuthority())) { // 解析出数字格式的id String id = docId.split(":")[1]; String selection = MediaStore.Images.Media._ID + "=" + id; imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection); } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) { Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId)); imagePath = getImagePath(contentUri, null); } } else if ("content".equalsIgnoreCase(uri.getScheme())) { // 如果是 content 类型的Uri,则使用普通方式处理 imagePath = getImagePath(uri, null); } else if ("file".equalsIgnoreCase(uri.getScheme())) { // 如果是 file 类型的Uri,直接获取文件路径即可 imagePath = uri.getPath(); } // 根据文件路径显示图片 displayImage(imagePath); } private void handleImageBeforeKitKat(Intent data) { Uri uri = data.getData(); String imagePath = getImagePath(uri, null); displayImage(imagePath); } private String getImagePath(Uri uri, String selection) { String path = null; // 通过Uri和selection来获取真实的图片路径 Cursor cursor = getContentResolver().query(uri, null, selection, null, null); if (cursor != null) { if (cursor.moveToFirst()) { path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); } cursor.close(); } return path; } private void displayImage(String imagePath) { if (imagePath != null) { Bitmap bitmap = BitmapFactory.decodeFile(imagePath); picture.setImageBitmap(bitmap); } else { Toast.makeText(MainActivity.this, "获取图片失败", Toast.LENGTH_SHORT).show(); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_notification: TimerTask timerTask = new TimerTask() { @Override public void run() { sendNotification(); } }; Timer timer = new Timer(); timer.schedule(timerTask, 2000); break; case R.id.btn_camera: takePhoto(); break; case R.id.btn_album: choosePhoto(); break; case R.id.btn_audio: AudioActivity.start(MainActivity.this); break; case R.id.btn_video: VideoActivity.start(MainActivity.this); break; default: break; } } private void sendNotification() { Intent intent = new Intent(MainActivity.this, NotificationActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Notification notification = new NotificationCompat.Builder(this) .setContentTitle("通知标题") .setContentText("这里是通知内容") .setWhen(System.currentTimeMillis()) .setContentIntent(pendingIntent) .setSmallIcon(R.mipmap.ic_launcher) .setAutoCancel(true) .setVibrate(new long[]{0, 1000, 0, 0}) .setSound(Uri.fromFile(new File("/system/media/audio/ringtones/Luna.ogg"))) .setLights(Color.YELLOW, 1000, 1000) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_round)) .build(); manager.notify(1, notification); } private void takePhoto() { File outputImage = new File(getExternalCacheDir(), getNowTime() + ".jpg"); try { outputImage.createNewFile(); } catch (IOException e) { e.printStackTrace(); } if (Build.VERSION.SDK_INT >= 24) { imageUri = FileProvider.getUriForFile(MainActivity.this, "com.tongchen.mediatest.provider", outputImage); } else { imageUri = Uri.fromFile(outputImage); } // 启动相机 Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent, TAKE_PHOTO); } /** * 获取当前时间 * * @return */ private String getNowTime() { String timeString; Time time = new Time(); time.setToNow(); String year = thanTen(time.year); String month = thanTen(time.month + 1); String monthDay = thanTen(time.monthDay); String hour = thanTen(time.hour); String minute = thanTen(time.minute); String second = thanTen(time.second); timeString = year + "-" + month + "-" + monthDay + "-" + hour + "-" + minute + "-" + second; return timeString; } /** * 十以下加零 * * @param str * @return */ private String thanTen(int str) { String string = null; if (str < 10) { string = "0" + str; } else { string = "" + str; } return string; } private void choosePhoto() { if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); } else { openAlbum(); } } private void openAlbum() { Intent intent = new Intent("android.intent.action.GET_CONTENT"); intent.setType("image/*"); startActivityForResult(intent, CHOOSE_PHOTO); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case 1: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { openAlbum(); } else { Toast.makeText(MainActivity.this, "你没有给权限", Toast.LENGTH_SHORT).show(); } break; } } }
class Fibonacci { public static void main(String[] args) { int arr[]; arr= new int[10]; int i; arr[0]=0; arr[1]=1; System.out.println("These are the first 10 Fibonacci Numbers\n"); System.out.println(arr[0]); System.out.println("\n"); System.out.println(arr[1]); System.out.println("\n"); for (i=2;i<10;i++) { arr[i]=arr[i-1]+arr[i-2]; System.out.println(arr[i]); System.out.println("\n"); } } }
package khmil; import java.util.Scanner; public class Frequency { private static Scanner a = new Scanner(System.in); public static String getString() { System.out.print("Enter String: "); String input = a.nextLine(); return input; } public static char getChar() { System.out.print("Enter char: "); char symbol = a.nextLine().charAt(0); return symbol; } public static void Counting(String str, char symb) { int count = 0; for (int i = 0; i < str.length(); i++) { if (symb == str.charAt(i)) { count++; } } System.out.println("Frequency: " + count); } public static void main(String[] args) { Counting(getString(), getChar()); } }
/* * 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 ejb.session.stateless; import entity.Fare; import entity.Flight; import entity.FlightSchedule; import entity.FlightSchedulePlan; import java.util.Date; import java.util.List; import javax.ejb.Remote; import util.exception.DeleteFlightSchedulePlanException; import util.exception.FlightScheduleExistException; import util.exception.FlightScheduleNotFountException; import util.exception.FlightSchedulePlanExistException; import util.exception.FlightSchedulePlanNotFoundException; import util.exception.GeneralException; import util.exception.UpdateFlightSchedulePlanException; /** * * @author Administrator */ @Remote public interface FlightSchedulePlanSessionBeanRemote { public FlightSchedulePlan createNewSingleFlightSchedulePlan(FlightSchedulePlan newFlightSchedulePlan, Flight flight, Date departureDate, Date departureTime, Date durationTime) throws FlightSchedulePlanExistException, GeneralException; public FlightSchedulePlan createNewMultipleFlightSchedulePlan(FlightSchedulePlan newFlightSchedulePlan, Flight flight, List<Date> departureDates, List<Date> departureTimes, List<Date> durationTimes) throws FlightSchedulePlanExistException, GeneralException; public FlightSchedulePlan createNewRecurrentFlightSchedulePlan(FlightSchedulePlan newFlightSchedulePlan, Flight flight, Date departureTime, Date durationTime, Integer recurrence, Date startDateTime, Date endDateTime) throws FlightSchedulePlanExistException, GeneralException; public List<FlightSchedulePlan> retrieveAllFlightSchedulePlans(); public List<FlightSchedulePlan> retrieveFlightSchedulePlansByFlightNumber(String flightNumber) throws FlightSchedulePlanNotFoundException; public Long createReturnFlightSchedulePlan(FlightSchedulePlan newFlightSchedulePlan, Flight flight, Date layoverDurationTime) throws FlightSchedulePlanExistException, GeneralException, FlightScheduleExistException; public void deleteFlightSchedulePlan(FlightSchedulePlan flightSchedulePlan) throws FlightSchedulePlanNotFoundException, DeleteFlightSchedulePlanException; public void updateFlightSchedulePlanFares(FlightSchedulePlan flightSchedulePlan, List<Fare> fares); public void updateSingleFlightSchedule(FlightSchedulePlan flightSchedulePlan, FlightSchedule flightSchedule, Date departureDate, Date departureTime, Date durationTime) throws UpdateFlightSchedulePlanException; public void updateRecurrentDayFlightSchedule(FlightSchedulePlan flightSchedulePlan, Integer recurrence, Date endDate) throws UpdateFlightSchedulePlanException; public void updateRecurrentWeekFlightSchedule(FlightSchedulePlan flightSchedulePlan, Date endDate) throws UpdateFlightSchedulePlanException; }