text
stringlengths
10
2.72M
/** * All rights Reserved, Designed By www.gitcloud.com.cn * @Title: XssFilter.java * @Package com.git.cloud.common.xss * @Description: TODO(用一句话描述该文件做什么) * @author: chengbin * @date: 2018年8月14日 下午4:19:52 * @version V1.0 * @Copyright: 2018 www.gitcloud.com.cn Inc. All rights reserved. */ package com.git.cloud.common.xss; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.owasp.esapi.ESAPI; import org.springframework.stereotype.Component; /** * @ClassName: XssFilter * @Package: com.git.cloud.common.xss * @Description: TODO(这里用一句话描述这个类的作用) * @author: chengbin * @date: 2018年8月14日 下午4:19:52 * @Copyright: 2018 www.gitCloud.com Inc. All rights reserved. */ @Component public class XssFilter implements Filter{ private static final String FILTER_APPLIED = XssFilter.class.getName() + ".FILTERED"; /** * <p>Title: init</p> * <p>Description: </p> * @param filterConfig * @throws ServletException * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) */ @Override public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub } /** * <p>Title: doFilter</p> * <p>Description: </p> * @param request * @param response * @param chain * @throws IOException * @throws ServletException * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) */ @Override public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException { if( !( request instanceof HttpServletRequest ) || !( response instanceof HttpServletResponse ) ) { throw new ServletException( "XSSFilter just supports HTTP requests" ); } HttpServletRequest httpRequest = ( HttpServletRequest )request; String uri = httpRequest.getRequestURI(); // Apply Filter if( null != httpRequest.getAttribute( FILTER_APPLIED ) ) { chain.doFilter( request, response ); return; } try { request.setAttribute( FILTER_APPLIED, Boolean.TRUE ); SecurityRequestWrapper requestWrapper = new SecurityRequestWrapper( httpRequest ); ESAPI.httpUtilities().setCurrentHTTP((HttpServletRequest)requestWrapper, (HttpServletResponse)response); chain.doFilter( requestWrapper, response ); } finally { httpRequest.removeAttribute( FILTER_APPLIED ); } } /** * <p>Title: destroy</p> * <p>Description: </p> * @see javax.servlet.Filter#destroy() */ @Override public void destroy() { // TODO Auto-generated method stub } }
import java.util.ArrayList; import java.util.List; /* * @lc app=leetcode.cn id=57 lang=java * * [57] 插入区间 */ // @lc code=start class Solution { public int[][] insert(int[][] intervals, int[] newInterval) { List<int[]> result = new ArrayList<>(); int i=0; //左半部分 无交集 while(i < intervals.length && intervals[i][1] < newInterval[0]){ result.add(intervals[i]); i++; } //合并区间 while(i<intervals.length && intervals[i][0] <= newInterval[1]){ newInterval[0] = Math.min(intervals[i][0], newInterval[0]); newInterval[1] = Math.max(intervals[i][1], newInterval[1]); i++; } result.add(newInterval); //右半部分 while(i < intervals.length){ result.add(intervals[i]); i++; } return result.toArray(new int[result.size()][2]); } } // @lc code=end
public class ConnectingCars { public long minimizeCost(int[] positions, int[] lengths) { int[][] sorted = new int[positions.length][2]; for(int i = 0; i < sorted.length; ++i) { int min = Integer.MAX_VALUE; int index = -1; for(int j = 0; j < positions.length; ++j) { if(positions[j] < min) { min = positions[j]; index = j; } } sorted[i][0] = positions[index]; sorted[i][1] = lengths[index]; positions[index] = Integer.MAX_VALUE; } long result = Long.MAX_VALUE; for(int i = 0; i < sorted.length; ++i) { long poss = 0; int left = sorted[i][0]; int right = left + sorted[i][1]; for(int j = i - 1; 0 <= j; --j) { poss += (left - (sorted[j][0] + sorted[j][1])); left -= sorted[j][1]; } for(int j = i + 1; j < sorted.length; ++j) { poss += (sorted[j][0] - right); right += sorted[j][1]; } result = Math.min(result, poss); } return result; } }
package swea.d3; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; public class Solution_2806_NQueen { static int N; static int[] arr; static int ans; public static void main(String[] args) throws Exception { System.setIn(new FileInputStream("input.txt")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine()); for (int tc = 1; tc <= T; tc++) { N = Integer.parseInt(br.readLine()); arr = new int[N]; ans = 0; dfs(0); System.out.println("#" + tc + " " + ans); } } private static void dfs(int cur_row) { if (cur_row == N) { ans++; return; } for (int col = 0; col < N; col++) { boolean flag = true; for (int row = 0; row < cur_row; row++) { if (arr[row] == col || cur_row - row == Math.abs(arr[row] - col)) { flag = false; } } if (flag) { arr[cur_row] = col; dfs(cur_row + 1); } } } }
package online.lahloba.www.lahloba.ui.delivery_supervisor.bootom_sheet; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.LinearLayoutManager; import com.google.android.material.bottomsheet.BottomSheetBehavior; import com.google.android.material.bottomsheet.BottomSheetDialog; import com.google.android.material.bottomsheet.BottomSheetDialogFragment; import com.google.firebase.auth.FirebaseAuth; import java.util.ArrayList; import java.util.List; import online.lahloba.www.lahloba.data.model.OrderItem; import online.lahloba.www.lahloba.databinding.DeliverySupervisorAllocationBshBinding; import online.lahloba.www.lahloba.ui.adapters.DeliverySDeliveryAdapter; import online.lahloba.www.lahloba.ui.delivery_supervisor.DeliverySupervisorMainViewModel; import online.lahloba.www.lahloba.utils.StatusUtils; public class DeliverySAllocationBSH extends BottomSheetDialogFragment { private OrderItem orderItem; private List<String> deliveryIds; private boolean delivaryAvailable; private DeliverySDeliveryAdapter adapter; private DeliverySupervisorMainViewModel mViewModel; private DeliverySupervisorAllocationBshBinding binding; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { binding = DeliverySupervisorAllocationBshBinding .inflate(inflater, container, false); deliveryIds = new ArrayList<>(); adapter = new DeliverySDeliveryAdapter(getContext()); adapter.setDeliveryIds(deliveryIds); adapter.setmViewModel(mViewModel); adapter.setOrderItem(orderItem); binding.deliveryRV.setLayoutManager(new LinearLayoutManager(getContext())); binding.deliveryRV.setAdapter(adapter); mViewModel.startGetDeliveriesForCity(orderItem.getCityId(), StatusUtils.DELIVERY_AREA_TYPE_DELIVERY); return binding.getRoot(); } @Override public void onResume() { super.onResume(); mViewModel.getDeliveriesId().observe(this,deliveryIdsList->{ deliveryIds.clear(); adapter.notifyDataSetChanged(); delivaryAvailable = false; binding.setDeliveryAvailable(delivaryAvailable); if (deliveryIdsList== null)return; delivaryAvailable = true; binding.setDeliveryAvailable(delivaryAvailable); deliveryIds.addAll(deliveryIdsList); adapter.notifyDataSetChanged(); }); } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { BottomSheetDialog dialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState); dialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { BottomSheetDialog d = (BottomSheetDialog) dialog; FrameLayout bottomSheet = (FrameLayout) d.findViewById(com.google.android.material.R.id.design_bottom_sheet); BottomSheetBehavior.from(bottomSheet).setState(BottomSheetBehavior.STATE_EXPANDED); BottomSheetBehavior.from(bottomSheet).setPeekHeight(0); } }); return dialog; } @Override public void onPause() { super.onPause(); mViewModel.clearDeliveriesIdForCity(); mViewModel.startGetUserDetails(FirebaseAuth.getInstance().getUid()); } public void setOrderItem(OrderItem orderItem) { this.orderItem = orderItem; } public void setmViewModel(DeliverySupervisorMainViewModel mViewModel) { this.mViewModel = mViewModel; } }
package com.sise.internsystem.action; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.opensymphony.xwork2.ActionContext; import com.sise.internsystem.base.BaseAction; import com.sise.internsystem.entity.User; import com.sise.internsystem.util.QueryHelper; @Controller @Scope("prototype") public class UserAction extends BaseAction<User> { /**查看列表*/ public String list() throws Exception { new QueryHelper(User.class, "u").preparePageBean(userService, pageNum, 10); return "list"; } /** 添加*/ public String saveUI() throws Exception { return "saveUI"; } public String add() throws Exception { HttpServletResponse response=ServletActionContext.getResponse(); response.setCharacterEncoding("utf-8"); model.setPwd("123456"); model.setRole("teacher"); boolean f= userService.checkNo(model.getName()); if (f) { userService.save(model); }else{ response.setContentType("text/html;charset=utf-8"); response.getWriter().write("<script>alert('账户已存在');</script>"); response.getWriter().write("<script> window.location='user_list.action' ;window.close();</script>"); response.getWriter().flush(); } return "toList"; } public String editUI() throws Exception { User user = userService.getById(model.getId()); ActionContext.getContext().getValueStack().push(user); return "editUI"; } /** 修改*/ public String edit() throws Exception { User user = userService.getById(model.getId()); user.setGender(model.getGender()); user.setName(model.getName()); user.setTel(model.getTel()); userService.update(user); return "toList"; } /**删除*/ public String delete() throws Exception { userService.delete(model.getId()); return "toList"; } /** 初始化密码*/ public String initPassword() throws Exception { User user = userService.getById(model.getId()); user.setPwd("123456"); userService.update(user); return "toList"; } public String changeUI() throws Exception { User user= (User) ActionContext.getContext().getSession().get("user"); ActionContext.getContext().getValueStack().push(user); return "changeUI"; } /** 修改*/ public String change() throws Exception { User user = (User) ActionContext.getContext().getSession().get("user"); user.setGender(model.getGender()); user.setName(model.getName()); user.setTel(model.getTel()); userService.update(user); return "change"; } public String pwdUI() throws Exception { return "pwdUI"; } public String pwd() throws Exception { HttpServletResponse response=ServletActionContext.getResponse(); response.setCharacterEncoding("utf-8"); String pwd= ServletActionContext.getRequest().getParameter("password"); User user= (User) ActionContext.getContext().getSession().get("user"); user.setPwd(pwd); userService.update(user); response.setContentType("text/html;charset=utf-8"); response.getWriter().write( "<script>alert('修改成功');</script>"); return "change"; } public String search() throws Exception { String value= ServletActionContext.getRequest().getParameter("value"); QueryHelper q=new QueryHelper(User.class, "u"); if (value!=null) { q.addCondition(true, "u.name=?",value ); } q.preparePageBean(userService, pageNum, 10); return "search"; } }
package com.sezioo.permission.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.sezioo.permission.model.SysDept; public interface SysDeptMapper { int deleteByPrimaryKey(Integer id); int insert(SysDept record); int insertSelective(SysDept record); SysDept selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(SysDept record); int updateByPrimaryKey(SysDept record); List<SysDept> findAll(); List<SysDept> findDeptListByLevelPrefix(@Param("levelPrefix") String levelPrefix); int batchUpdateChildDept(@Param("deptList") List<SysDept> deptList); int countDeptByParentIdAndName(@Param("name") String name,@Param("parentId") Integer parentId,@Param("id") Integer id); }
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html */ package org.hibernate.benchmarks; import java.util.function.Consumer; import java.util.function.Function; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import org.hibernate.benchmarks.BenchmarkHQLParserTree; import org.hibernate.benchmarks.BenchmarkHQLSemanticModelInterpreter; import org.hibernate.benchmarks.BenchmarkSession; /** * @author Andrea Boriero */ public abstract class BaseBenchmarkSession implements BenchmarkSession { protected Class[] annotatedClasses; protected String[] hbmfiles = new String[0]; protected boolean createSchema; protected EntityManagerFactory entityManagerFactory; private BenchmarkHQLParserTree hqlParser; private BenchmarkHQLSemanticModelInterpreter hqlInterpreter; @Override public void setUp(Class[] annotatedClasses, String[] hbmfiles, boolean createSchema) { this.annotatedClasses = annotatedClasses; this.hbmfiles = hbmfiles; this.createSchema = createSchema; this.entityManagerFactory = buildEntityManagerFactory(); this.hqlParser = buildHqlParser(); hqlInterpreter = buildHqInterpreter(); System.out.println( "Running benchmark with HQL Parser: " + hqlParser.getClass().getName() ); System.out.println( "Running benchmark with HQL Interpreter: " + hqlInterpreter.getClass().getName() ); } protected abstract EntityManagerFactory buildEntityManagerFactory(); protected abstract BenchmarkHQLParserTree buildHqlParser(); protected abstract BenchmarkHQLSemanticModelInterpreter buildHqInterpreter(); @Override public BenchmarkHQLParserTree getHqlParser() { return hqlParser; } @Override public BenchmarkHQLSemanticModelInterpreter getHqlInterpreter() { return hqlInterpreter; } @Override public <T> T inTransaction(Function<EntityManager, T> function) { EntityManager em = entityManagerFactory.createEntityManager(); T result = null; try { em.getTransaction().begin(); result = function.apply( em ); em.getTransaction().commit(); } catch (Exception e) { if ( em.getTransaction().isActive() ) { em.getTransaction().rollback(); } } finally { em.close(); } return result; } @Override public void inTransaction(Consumer<EntityManager> consumer) { EntityManager em = entityManagerFactory.createEntityManager(); try { em.getTransaction().begin(); consumer.accept( em ); em.getTransaction().commit(); } catch (Exception e) { if ( em.getTransaction().isActive() ) { em.getTransaction().rollback(); } } finally { em.close(); } } @Override public void shutDown() { entityManagerFactory.close(); } }
import java.lang.reflect.Array; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; public class SearchMinimunLoss { static long minimumLoss(long[] price) { long [] SortedArr=Arrays.copyOf(price, price.length); List<Long> priceList=Arrays.stream(price).boxed().collect(Collectors.toList()); Arrays.sort(SortedArr); long minCost=Long.MAX_VALUE; for(int i=1;i<price.length;i++) { if(priceList.indexOf(SortedArr[i])<priceList.indexOf(SortedArr[i-1]) && SortedArr[i]-SortedArr[i-1] <minCost ) { minCost=SortedArr[i]-SortedArr[i-1]; } } return minCost; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); long[] price = new long[n]; for(int price_i = 0; price_i < n; price_i++){ price[price_i] = in.nextLong(); } long result = minimumLoss(price); System.out.println(result); in.close(); } }
package x20171025; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Scanner; /** * * @author Schwarczenberger Ferenc */ public class vissza { public static void main(String[] args)throws Exception { File theFile = new File("vissza.txt"); try { try (Scanner eyes = new Scanner(theFile)) { while (eyes.hasNextLine()) { String sor = eyes.nextLine(); System.out.println(sor); StringBuilder sb = new StringBuilder(sor); System.out.println("visszafelé: "+sb.reverse()); } } } catch(FileNotFoundException fnfe){ System.out.println("Error: "+fnfe.getMessage()); } } }
package com.applitools.hackathon.VisualAIRockStar.pages; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.testng.Reporter; import org.testng.asserts.SoftAssert; import com.applitools.hackathon.VisualAIRockStar.common.CommonActions; import com.applitools.hackathon.VisualAIRockStar.test.BaseTests; public class Home extends BaseTests { protected static By LOC_TABLE_HEADER = By.xpath("//table[@id='transactionsTable']//thead//tr//th"); protected static By LOC_AMOUNTS_COL = By.xpath("//table[@id='transactionsTable']//thead//tr//th[5]"); protected static By LOC_TABLE_BODY_ROWS = By.xpath("//table[@id='transactionsTable']//tbody//tr"); protected static By LOC_COMPARE_EXPENSES = By.id("showExpensesChart"); public static void verifyTableHeaders(SoftAssert asrt) { List<String> expectedHeader = new ArrayList<String>(); expectedHeader.add("STATUS"); expectedHeader.add("DATE"); expectedHeader.add("DESCRIPTION"); expectedHeader.add("CATEGORY"); expectedHeader.add("AMOUNT"); List<WebElement> actualHeader = driver.findElements(LOC_TABLE_HEADER); for (int i = 0; i < actualHeader.size(); i++) { CommonActions.verifyText(expectedHeader.get(i), actualHeader.get(i).getText(), asrt); } } public static void clickAmountsAndSorting(SoftAssert asrt) { Map<String, ArrayList<String>> tableDataBefore = Home.storeTableDataInMap(); List<String> amountsBefore = Home.storeAmountsColumn(); List<String> sortedList = Home.convertDoubleAndSort(amountsBefore); CommonActions.click(driver, LOC_AMOUNTS_COL); List<String> amountsAfter = Home.storeAmountsColumn(); Map<String, ArrayList<String>> tableDataAfter = Home.storeTableDataInMap(); Reporter.log("Verify row data is intact after sorting.", true); for (String key : tableDataAfter.keySet()) { List<String> rowDataBefore = tableDataBefore.get(key); List<String> rowDataAfter = tableDataAfter.get(key); asrt.assertEquals(rowDataAfter, rowDataBefore); } Reporter.log("Compare results of Amounts columns before and after sorting.", true); for (int i = 0; i < amountsAfter.size(); i++) { CommonActions.verifyText(amountsBefore.get(i), amountsAfter.get(i), asrt); } asrt.assertEquals(sortedList, amountsBefore); } public static Map<String, ArrayList<String>> storeTableDataInMap() { Map<String, ArrayList<String>> rowsData = new HashMap<String, ArrayList<String>>(); List<WebElement> rows = driver.findElements(LOC_TABLE_BODY_ROWS); for (WebElement e : rows) { ArrayList<String> colData = new ArrayList<String>(); List<WebElement> cols = e.findElements(By.tagName("td")); for (WebElement c : cols) { colData.add(c.getText()); } rowsData.put(colData.get(2), colData); } return rowsData; } public static List<String> storeAmountsColumn() { List<String> amounts = new ArrayList<String>(); List<WebElement> rows = driver.findElements(LOC_TABLE_BODY_ROWS); for (int i = 0; i < rows.size(); i++) { String value = driver .findElement(By.xpath("//table[@id='transactionsTable']//tbody//tr[" + (i + 1) + "]//td[5]")) .getText(); String replaceSpace = value.replaceAll(" ", ""); if (replaceSpace.contains(",")) { replaceSpace = replaceSpace.replaceFirst(",", ""); } String splitNumbers = replaceSpace.substring(0, replaceSpace.length() - 3); amounts.add(splitNumbers); } return amounts; } public static List<String> convertDoubleAndSort(List<String> list) { DecimalFormat df2 = new DecimalFormat("#.00"); List<Double> doubleList = new ArrayList<Double>(); for (int i = 0; i < list.size(); i++) { double d = Double.parseDouble(list.get(i)); doubleList.add(d); } Collections.sort(doubleList); for (int i = 0; i < doubleList.size(); i++) { String val = df2.format(doubleList.get(i)); list.remove(i); if (val.contains("-")) { list.add(i, val); } else { list.add(i, "+" + val); } } return list; } public static void clickAmountsColumnHeader() { CommonActions.click(driver, LOC_AMOUNTS_COL); } public static void clickCompareExpensesLink() { CommonActions.click(driver, LOC_COMPARE_EXPENSES); } public static void verifyCompareExpensesText(SoftAssert asrt) { asrt.assertEquals("Compare Expenses", driver.findElement(LOC_COMPARE_EXPENSES).getText()); } }
package com.example.dialogfragmentrecyclerview; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.viewpager.widget.PagerAdapter; import java.util.List; public class ViewPagerAdapter extends PagerAdapter { private List<View> viewList;//数据源 public ViewPagerAdapter(List<View> list){ viewList = list; } @Override public int getCount() { return viewList==null?0:viewList.size(); } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view == object; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { if(viewList != null) { container.removeView(viewList.get(position)); } } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { if(viewList != null) { container.addView(viewList.get(position)); return viewList.get(position); } return super.instantiateItem(container, position); } }
package leetCode.链表; /** * Definition for singly-linked list. */ class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public class Solution { public static void main(String[] args) { Solution solution = new Solution(); ListNode l1 = new ListNode(4); l1.next = new ListNode(8); l1.next.next = new ListNode(6); l1.next.next.next = new ListNode(6); solution.printListNode(l1); System.out.println(); ListNode l2 = new ListNode(9); l2.next = new ListNode(6); l2.next.next = new ListNode(7); solution.printListNode(l2); System.out.println(); ListNode result = solution.addTwoNumbers2(l1, l2); solution.printListNode(result); } public void printListNode(ListNode node){ while(node != null){ System.out.print(node.val + " "); node = node.next; } } /** * 回文链表 请检查一个链表是否为回文链表。 进阶: 你能在 O(n) 的时间和 O(1) 的额外空间中做到吗? * @param head * @return */ public boolean isPalindrome(ListNode head) { ListNode tempHead = head; if(head == null || head.next == null){ return true; } ListNode temp = null; while(head != null){ ListNode node = new ListNode(head.val); node.next = temp; temp = node; head = head.next; } while(tempHead != null){ if(tempHead.val != temp.val){ return false; } tempHead = tempHead.next; temp = temp.next; } return true; } /** * 一种好的方法,不需要额外的空间 * @param head * @return */ public boolean isPalindromeBetter(ListNode head) { ListNode slow = head; ListNode fast = head; ListNode prev = null; while (fast != null && fast.next != null) { fast = fast.next.next; // here we need to revese the first half of the LinkedList. ListNode next = slow.next; slow.next = prev; prev = slow; slow = next; } if (fast != null) slow = slow.next; while (slow != null && prev != null) if (slow.val != prev.val) return false; else { slow = slow.next; prev = prev.next; } return true; } /** * 合并两个有序链表 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 示例: 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4 * @param l1 * @param l2 * @return */ /*public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if(l1 == null){ return l2; } if(l2 == null){ return l1; } ListNode head = l1.val < l2.val?l1:l2; 错了 while(l2 != null){ ListNode next = l1.next; if(next != null){ if(next.val >= l2.val){ l1.next = l2; ListNode l2Next = l2.next; l2.next = next; l2 = l2Next; } else { l1 = next; } } else { next = l2; break; } } return head; }*/ /** * 这个方法超时了!!!!!! * 两数相加 题目描述提示帮助提交记录社区讨论阅读解答 给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。 你可以假设除了数字 0 之外,这两个数字都不会以零开头。 示例: 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807 */ public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if(l1 == null){ return l2; } if(l2 == null){ return l1; } int highNum = 0; int first = l1.val + l2.val + highNum; l1 = l1.next; l2 = l2.next; ListNode result = new ListNode(first % 10); ListNode head = result; highNum = first / 10; while(l1 !=null && l2 != null ){ first = l1.val + l2.val + highNum; l1 = l1.next; l2 = l2.next; result.next = new ListNode(first % 10); result = result.next; highNum = first / 10; } while(l1 != null && l2 == null){ first = l1.val + highNum; result.next = new ListNode(first % 10); result = result.next; highNum = first / 10; l1 = l1.next; } while(l1 == null && l2 != null){ first = l2.val + highNum; result.next = new ListNode(first % 10); result = result.next; highNum = first / 10; l2 = l2.next; } if(highNum != 0){ result.next = new ListNode(highNum); } return head; } //反转单向链表 private ListNode reverseLinkedList(ListNode head){ ListNode node = null; while(head != null){ ListNode next = head.next; head.next = node; node = head; head = next; } return node; } /** * 由于上面的方法超时了,现在重新来 * @param l1 * @param l2 * @return */ public ListNode addTwoNumbers2(ListNode l1, ListNode l2) { if(l1 == null){ return l2; } if(l2 == null){ return l1; } int highNum = 0; int temp = 0; ListNode head = l1; ListNode result = l1; while(l1 != null && l2 != null){ temp = l1.val + l2.val + highNum; l1.val = temp % 10; highNum = temp / 10; result = l1; l1 = l1.next; l2 = l2.next; } ListNode tempNode = l1 != null?l1:l2; result.next = tempNode; while(tempNode != null){ temp = tempNode.val + highNum; tempNode.val = temp % 10; highNum = temp / 10; result = tempNode; tempNode = tempNode.next; } if(highNum != 0){ result.next = new ListNode(highNum); } return head; } /** * 最好的思路 * @param l1 * @param l2 * @return */ public ListNode addTwoNumbersBest(ListNode l1, ListNode l2) { int sum = l1.val + l2.val; int carry = sum/10; ListNode result = new ListNode(sum%10); l1 = l1.next; l2 = l2.next; ListNode cache = result; while (l1 != null || l2 != null || carry > 0) { sum = carry; if (l1 != null) { sum += l1.val; } if (l2 != null) { sum += l2.val; } cache.next = new ListNode(sum%10); carry = sum/10; cache = cache.next; if (l1 !=null) { l1 = l1.next; } if (l2 != null) { l2 = l2.next; } } return result; } }
package me.ewriter.lambdasample; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import com.android.internal.util.Predicate; public class MainActivity extends AppCompatActivity { TextView textView; private static final String TAG = MainActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.text1); // 简化一个接口 simpleInterface(); // 简化一个 new Thread simpleNewThread(); // 静态方法引用 staticfunctionUse(); // 实例方法引用 InstanceMethodUse(); // 构造方法引用 ConstructMethodUse(); // Lambda 的域以及访问限制就不举例子了,总结下就是 // 局部变量 可读不可谢写 // 成员变量和静态变量 可读可写 // java.util.function 下常用的函数接口 commonInterface(); // Stream } private void simpleInterface() { // 传统的方法实现一个 接口 Converter<String, Integer> converter = new Converter<String, Integer>() { @Override public Integer convert(String from) { return Integer.parseInt(from); } }; Integer result = converter.convert("200"); Log.d(TAG, "normal result = " + result); // Lambda 简化一个接口 Converter<String, Integer> converter1 = (String str) -> Integer.parseInt(str); Integer integer2 = converter1.convert("123"); Log.d(TAG, "lambda result = " + integer2); } interface Converter<F, T> { T convert(F from); } private void simpleNewThread() { new Thread(new Runnable() { @Override public void run() { System.out.println("normal thread"); } }).start(); // 避免使用大量的匿名类 new Thread(() -> System.out.println("lambda thread")).start(); } static int String2Int(String from) { return Integer.valueOf(from); } /**静态方法引用*/ private void staticfunctionUse() { Converter<String, Integer> converter = new Converter<String, Integer>() { @Override public Integer convert(String from) { return String2Int(from); } }; converter.convert("123"); // 如果上面的转换方法用 Lambda 的静态方法引用 Converter<String, Integer> converter1 = MainActivity::String2Int; converter.convert("222"); } class Helper { public int String2int(String from) { return Integer.valueOf(from); } } /**实例方法引用*/ private void InstanceMethodUse() { //普通的方法 Converter<String, Integer> converter = new Converter<String, Integer>() { @Override public Integer convert(String from) { return new Helper().String2int(from); } }; converter.convert("123"); // 实例方法引用 Helper helper = new Helper(); Converter<String, Integer> converter1 = helper::String2int; converter1.convert("232"); } /**构造方法引用*/ private void ConstructMethodUse() { // 传统的方法, 用工厂方法构造两个对象 Factory factory = new Factory() { @Override public Animal create(String name, int age) { return new Dog(name, age); } }; factory.create("alias", 3); factory = new Factory() { @Override public Animal create(String name, int age) { return new Bird(name, age); } }; factory.create("smook", 2); // 下面用 Lambda 构造方法引用 Factory<Animal> dogFactory = Dog::new; Animal dog = dogFactory.create("alias", 3); Factory<Bird> birdFactory = Bird::new; Bird bird = birdFactory.create("smook", 4); } /** java.util.function 下常用的函数接口 * 这个包是在 api 24 加入的 https://developer.android.com/reference/java/util/function/package-summary.html * */ private void commonInterface() { // Predicate 接口, 输入一个参数,返回 Boolean 值 Predicate<String> predicate = s -> s.length() > 0; Log.d(TAG, predicate.apply("abc") + " ;" + predicate.apply("")); // Function 接口,接收一个参数,返回单一的结果 // Supplier 接口, 无输入,无输出 // Consumer 接口,单一输入,无返回 } }
package tests; import core.CustomTestListener; import org.testng.annotations.BeforeTest; import org.testng.annotations.Listeners; @Listeners({CustomTestListener.class}) public abstract class BaseTest { @BeforeTest public void openSite() { } }
package org.softRoad.security; import io.quarkus.elytron.security.common.BcryptUtil; import io.smallrye.jwt.build.Jwt; import org.eclipse.microprofile.config.ConfigProvider; import org.eclipse.microprofile.jwt.Claims; import org.softRoad.models.User; public class SecurityUtils { public static String createJwtToken(User user) { return Jwt .upn(user.phoneNumber) .claim(Claims.full_name.name(), user.displayName) .sign(); } public static String hashPassword(String password) { return BcryptUtil.bcryptHash(password, 10, ConfigProvider.getConfig().getValue("bcryptHash.salt", String.class).getBytes()); } public static String getAuthorizationHeader(User user) { return "Bearer " + createJwtToken(user); } }
package com.webrob.distributedmutex.model; /** * Created by Robert on 2015-01-05. */ public interface TimeoutListener { void timeout(); void sendOkToAllQueuedNodes(); }
package com.esum.comp.dbm.util.sql; import com.esum.framework.common.sql.Record; /** * Copyright(c) eSum Technologies., inc. All rights reserved. */ public abstract class MethodParser { private Record record; public MethodParser(Record record){ this.record = record; } protected String getValue(String field, String defaultValue) throws Exception{ if(field==null || field.equals("")) throw new Exception("Invalid Script : Field Name is NULL"); return record.getString(field, defaultValue); } public abstract String parse(String fieldInfo, String defaultValue) throws Exception; }
package Emma; /** * Created by rodrique on 3/16/2018. */ import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class Test { public class TestMethods { HisenseTv tv; LCD lcd; public TestMethods() { } @Before public void setUp() throws Exception { this.tv = new HisenseTv(); this.lcd = new LCD(); } @Test public void testSetWidth() throws Exception { this.tv.setWidth(25); Assert.assertEquals(25L, 25L); this.lcd.setWidth(27); Assert.assertEquals(27L, 27L); } @Test public void testSetHeight() throws Exception { this.tv.setHeight(25); Assert.assertEquals(25L, 25L); this.lcd.setHeight(93); Assert.assertEquals(93L, 93L); } @Test public void testGetWidth() throws Exception { this.lcd.setWidth(25); Assert.assertEquals(25L, (long)this.lcd.getWidth()); } @Test public void testGetHeight() throws Exception { this.lcd.setHeight(93); Assert.assertEquals(93L, (long)this.lcd.getHeight()); } @Test public void testGetArea() throws Exception { this.lcd.setWidth(5); this.lcd.setHeight(10); Assert.assertEquals(50L, (long)this.lcd.getArea()); } } }
package net.droidlabs.viking.bindings.map.bindings; import androidx.databinding.BindingAdapter; import com.google.maps.android.clustering.Cluster; import com.google.maps.android.clustering.ClusterItem; import com.google.maps.android.clustering.ClusterManager; import com.google.maps.android.clustering.algo.Algorithm; import java.util.Collection; import net.droidlabs.viking.bindings.map.GoogleMapView; import net.droidlabs.viking.bindings.map.InfoWindowAdapterFactory; import net.droidlabs.viking.bindings.map.RendererFactory; @SuppressWarnings({ "unused" }) public class ClusterBindings { private ClusterBindings() { } @BindingAdapter("gmv_clusterItems") public static <T> void clusterItems(GoogleMapView googleMapView, Collection<T> items) { if (items == null) { return; } googleMapView.clusterItems(items); } @BindingAdapter("gmv_rendererFactory") public static <T extends ClusterItem> void rendererFactory(GoogleMapView googleMapView, RendererFactory<T> rendererFactory) { googleMapView.setRendererFactory(rendererFactory); } @BindingAdapter("gmv_algorithm") public static <T extends ClusterItem> void algorithm(GoogleMapView googleMapView, Algorithm<T> algorithm) { googleMapView.setAlgorithm(algorithm); } @BindingAdapter("gmv_clusterItemInfoWindowAdapter") public static <T extends ClusterItem> void clusterItemInfoWindowAdapter( GoogleMapView googleMapView, InfoWindowAdapterFactory<T> infoWindowAdapterFactory) { googleMapView.setClusterItemInfoWindowAdapter(infoWindowAdapterFactory); } @BindingAdapter("gmv_clusterInfoWindowAdapter") public static <T extends Cluster> void clusterInfoWindowAdapter(GoogleMapView googleMapView, InfoWindowAdapterFactory<T> infoWindowAdapterFactory) { googleMapView.setClusterInfoWindowAdapter(infoWindowAdapterFactory); } @BindingAdapter("gmv_clusterClickListener") public static <T extends ClusterItem> void clusterClickListener(GoogleMapView googleMapView, ClusterManager.OnClusterClickListener<T> onClusterClickListener) { googleMapView.setOnClusterClickListener(onClusterClickListener); } @BindingAdapter("gmv_clusterItemClickListener") public static <T extends ClusterItem> void clusterItemClickListener( GoogleMapView googleMapView, ClusterManager.OnClusterItemClickListener<T> onClusterItemClickListener) { googleMapView.setOnClusterItemClickListener(onClusterItemClickListener); } @BindingAdapter("gmv_clusterInfoWindowClickListener") public static <T extends ClusterItem> void clusterInfoWindowClickListener( GoogleMapView googleMapView, ClusterManager.OnClusterInfoWindowClickListener<T> onClusterInfoWindowClickListener) { googleMapView.setOnClusterInfoWindowClickListener(onClusterInfoWindowClickListener); } @BindingAdapter("gmv_clusterItemInfoWindowClickListener") public static <T extends ClusterItem> void onClusterItemInfoWindowClickListener( GoogleMapView googleMapView, ClusterManager.OnClusterItemInfoWindowClickListener<T> onClusterItemInfoWindowClickListener) { googleMapView.setOnClusterItemInfoWindowClickListener(onClusterItemInfoWindowClickListener); } }
/* * 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 hoangduc.daos; import hoangduc.connection.MyConnection; import hoangduc.dtos.ServiceDTO; import java.io.Serializable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; /** * * @author ADMIN */ public class ServiceDAO implements Serializable { private Connection conn; private PreparedStatement preStm; private ResultSet rs; public void closeConnection() throws Exception { if (rs != null) { rs.close(); } if (preStm != null) { preStm.close(); } if (rs != null) { rs.close(); } } public List<ServiceDTO> findByLikeName(String search) throws Exception { List<ServiceDTO> result = null; int id = 0; String name, image, typepet; float price = 0; try { String sql = "Select ServiceID,ServiceName,SerivcePrice,ServiceImage,TypePetService From ServicePet Where ServiceName LIKE ? AND SerivceStatus = 0"; conn = MyConnection.getConnection(); preStm = conn.prepareStatement(sql); preStm.setString(1, "%" + search + "%"); rs = preStm.executeQuery(); result = new ArrayList<>(); while (rs.next()) { id = Integer.parseInt(rs.getString("ServiceID")); name = rs.getString("ServiceName"); image = rs.getString("ServiceImage"); price = rs.getFloat("SerivcePrice"); typepet = rs.getString("TypePetService"); ServiceDTO dto = new ServiceDTO(name, image, typepet); dto.setPrice(price); dto.setServiceid(id); result.add(dto); } } finally { closeConnection(); } return result; } public boolean serviceDelete(String id) throws Exception { boolean check = false; try { String sql = "Update ServicePet SET SerivceStatus = ? Where ServiceID = ?"; conn = MyConnection.getConnection(); preStm = conn.prepareStatement(sql); preStm.setString(1, "1"); preStm.setString(2, id); check = preStm.executeUpdate() > 0; } finally { closeConnection(); } return check; } public boolean serviceInsert(ServiceDTO dto) throws Exception { boolean check = false; try { String sql = "Insert INTO ServicePet(ServiceName,SerivcePrice,SerivceStatus,ServiceImage,TypePetService) VALUES(?,?,?,?,?)"; conn = MyConnection.getConnection(); preStm = conn.prepareStatement(sql); preStm.setString(1, dto.getServicename()); preStm.setFloat(2, dto.getPrice()); preStm.setBoolean(3, dto.isStatus()); preStm.setString(4, dto.getServiceimage()); preStm.setString(5, dto.getTypeofpet()); check = preStm.executeUpdate() > 0; } finally { closeConnection(); } return check; } public ServiceDTO findByPrimaryKey(int id) throws Exception { ServiceDTO dto = null; String name, image, type; float price = 0; try { String sql = "Select ServiceName,SerivcePrice,ServiceImage,TypePetService From ServicePet Where ServiceID = ?"; conn = MyConnection.getConnection(); preStm = conn.prepareStatement(sql); preStm.setInt(1, id); rs = preStm.executeQuery(); if (rs.next()) { name = rs.getString("ServiceName"); image = rs.getString("ServiceImage"); price = rs.getFloat("SerivcePrice"); type = rs.getString("TypePetService"); dto = new ServiceDTO(name, image, type); dto.setPrice(price); dto.setServiceid(id); } } finally { closeConnection(); } return dto; } public boolean Edit(ServiceDTO dto) throws Exception { boolean check = false; try { String sql = "Update ServicePet SET ServiceName = ?, SerivcePrice = ?, ServiceImage = ?, TypePetService = ? Where ServiceID = ?"; conn = MyConnection.getConnection(); preStm = conn.prepareStatement(sql); preStm.setString(1, dto.getServicename()); preStm.setFloat(2, dto.getPrice()); preStm.setString(3, dto.getServiceimage()); preStm.setString(4, dto.getTypeofpet()); preStm.setInt(5, dto.getServiceid()); check = preStm.executeUpdate() > 0; } finally { closeConnection(); } return check; } }
package com.softeem.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * Servlet Filter implementation class IndexFilter */ public class IndexFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 判断session是否有数据 HttpServletRequest request2 = (HttpServletRequest) request; HttpSession session = request2.getSession(); //获取session中的数据,如果没有,则需要进入servlet获取 Object categoryList = session.getAttribute("categoryList"); Object goodsList = session.getAttribute("goodsList"); if (categoryList ==null || goodsList == null) { // 没有数据: System.out.println("没有数据:跳转到index.do"); // false : index.do request2.getRequestDispatcher("index.do").forward(request, response); }else{ // true : 放行 chain.doFilter(request, response); } } public void init(FilterConfig fConfig) throws ServletException { } }
package com.n26.atrposki.utils.time; import org.springframework.stereotype.Component; /* * @author aleksandartrposki@gmail.com * @since 05.05.18 * * */ @Component public class TimeServiceImpl implements ITimeService{ @Override public long getUtcNow() { return System.currentTimeMillis(); } }
package com.cht.training; import java.util.InputMismatchException; import java.util.NoSuchElementException; import java.util.Scanner; public class Main69 { public static void main(String[] args) { System.out.println("Input int"); Scanner scanner =new Scanner(System.in); // scanner.close(); try{ System.out.println("your input is:" + scanner.nextInt()); } catch (InputMismatchException ime){ System.out.println("format is wrong, stack trace is:"); ime.printStackTrace(); } catch (NoSuchElementException nsee){ System.out.println("input is not enogh"); } catch (IllegalStateException ise) { System.out.println("illegal state"); } scanner.close(); System.out.println("close scanner"); } }
package org.carlook.gui.views; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewChangeListener; import com.vaadin.server.VaadinSession; import com.vaadin.shared.ui.ContentMode; import com.vaadin.ui.*; import com.vaadin.ui.renderers.ButtonRenderer; import org.carlook.gui.components.TopPanel; import org.carlook.gui.windows.ConfirmationWindow; import org.carlook.model.objects.entities.Auto; import org.carlook.model.objects.dao.AutoDAO; import org.carlook.model.objects.entities.User; import org.carlook.services.util.GridBuild; import org.carlook.services.util.Konstanten; import org.carlook.services.util.Roles; import java.sql.SQLException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; public class SucheView extends VerticalLayout implements View { User user; VerticalLayout content = new VerticalLayout(); HorizontalLayout suchFelder; TopPanel toppanel; Label spacer = new Label("&nbsp", ContentMode.HTML); public void enter(ViewChangeListener.ViewChangeEvent event) { user = (User) VaadinSession.getCurrent().getAttribute(Roles.CURRENT); if(user == null || !user.getRole().equals(Roles.KUNDE)) UI.getCurrent().getNavigator().navigateTo(Konstanten.START); else this.setUp(); } public void setUp() { toppanel = new TopPanel(); TextField markeFeld = new TextField("Marke:"); markeFeld.setDescription("Geben sie eine Automarke ein."); markeFeld.setValue(""); markeFeld.setId("markeField"); TextField baujahrFeld = new TextField("Baujahr:"); baujahrFeld.setDescription("Geben sie das Baujahr des Autos ein."); baujahrFeld.setValue(""); markeFeld.addValueChangeListener(e-> onTheFly(markeFeld.getValue(), baujahrFeld.getValue())); baujahrFeld.addValueChangeListener(e-> onTheFly(markeFeld.getValue(), baujahrFeld.getValue())); suchFelder = new HorizontalLayout(); suchFelder.addComponents(markeFeld, baujahrFeld); //Erstmal alle Autos anzeigen lassen onTheFly("", ""); this.addComponent(content); this.setComponentAlignment(content, Alignment.MIDDLE_CENTER); } public void onTheFly(String marke, String baujahr){ //Erstellung Tabelle mit Jobangeboten content.removeAllComponents(); content.addComponents(toppanel, new Label("&nbsp", ContentMode.HTML), suchFelder); List<Auto> autos = null; try { autos = AutoDAO.getInstance().searchAutos(marke, baujahr); } catch (SQLException ex) { Logger.getLogger(SucheView.class.getName()).log(Level.SEVERE, null, ex); } Grid<Auto> autoGrid = GridBuild.basicGrid(autos); autoGrid.setCaption(" <span style='color:#EAECEC; font-size:25px; text-shadow: 1px 1px 1px black; font-family: Roboto, sans-serif;'> " + (marke.equals("") ? "Alle Autos:" : "Ergebnisse für: " + marke) + " </span>"); ButtonRenderer<Auto> reservieren = new ButtonRenderer<>(clickEvent ->{ ConfirmationWindow window = new ConfirmationWindow("Wollen sie dieses Auto reservieren?", clickEvent.getItem().getAutoid()); UI.getCurrent().addWindow(window); }); autoGrid.addColumn(Auto -> "Reservieren", reservieren).setWidth(150); content.addComponents(spacer, autoGrid); } }
package trungph.com; public class ObjClass { String Class_id; String Class_name; String School_Year; public ObjClass(String ID, String NAME, String YEAR) { super(); Class_id = ID; Class_name = NAME; School_Year = YEAR; } public ObjClass() { } @Override public String toString() { return "Class ID: " + Class_id + "\nClass name: " + Class_name + "\nSchool Year: " + School_Year; } }
package com.foodaholic.interfaces; public interface ClickListener { void onClick(int position); }
package com.newbig.im.app.controller.admin; import com.newbig.im.app.AppApplication; import com.newbig.im.common.constant.AppConstant; import com.newbig.im.common.utils.JwtUtil; import com.newbig.im.service.GreetingService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.hamcrest.Matchers.containsString; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @SpringBootTest(classes = { AppApplication.class, MockServletContext.class }) public class ServerControllerMockTest { @Autowired private WebApplicationContext context; private MockMvc mockMvc; @MockBean private GreetingService service; @Before public void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); } @Test public void greetingShouldReturnMessageFromService() throws Exception { when(service.greet()).thenReturn("Hello Mock"); this.mockMvc.perform(get("/greeting").header(AppConstant.TOKEN_HEADER, JwtUtil.genToken("11",22L))).andDo(print()).andExpect(status().isOk()) .andExpect(content().string(containsString("Hello Mock"))); } }
/** * Leetcode做题-阶乘尾数 https://leetcode-cn.com/problems/factorial-zeros-lcci/ */ public class 阶乘尾数 { public int trailingZeroes(int n) { int count=0; while (n>=5){ n=n/5; count+=n; } return count; } }
package sch.frog.calculator.util; public interface IComparator<T> { public static final IComparator<String> STRING_DEFAULT_COMPARATOR = (a, b) -> a.compareTo(b); int compare(T a, T b); }
//Print the following pattern for the given N number of rows. //Pattern for N = 4 //1 //11 //111 //1111 package Pattern; import java.util.Scanner; public class Pattern3 extends Pattern2 { public static void main(String[] args) { Scanner s= new Scanner(System.in); int rows = s.nextInt(); int temp=0; while (temp<=rows) { int i =1; int j =1; while (j<=temp) { System.out.print(i); j+=1; } System.out.println(); temp+=1; } // TODO Auto-generated method stub } }
package com.mingrisoft; public class PNGSaver implements ImageSaver { @Override public void save() { System.out.println("将图片保存成PNG格式"); } }
package com.zhongyp.advanced.sync; /** * project: demo * author: zhongyp * date: 2018/3/20 * mail: zhongyp001@163.com */ public class SynchronizedDemo { public static void main(String[] args){ } }
package com.ibisek.outlanded.net; public interface HttpResponseHandler { /** * @param httpResponse * @return possible return value or simply null */ public Object handleResponse(ParsedHttpResponse httpResponse); }
package br.com.marciojose.bibliotecasjava; import br.com.marciojose.bibliotecasjava.Programa.BarraDeProgresso; import br.com.marciojose.bibliotecasjava.Programa.CopiadorDeArquivos; import br.com.marciojose.bibliotecasjava.Programa.FazerDeposito; import br.com.marciojose.bibliotecasjava.modelo.Conta; public class MainThreads { public static void main (String[] args) throws Exception { //execucaoThreadSimples(); fazerDepositoSincronizado(); } private static void execucaoThreadSimples() { BarraDeProgresso barraDeProgresso = new BarraDeProgresso(); Thread t1 = new Thread(barraDeProgresso); t1.start(); CopiadorDeArquivos copiadodeArquivos = new CopiadorDeArquivos(); Thread t2 = new Thread(copiadodeArquivos); t2.start(); } private static void fazerDepositoSincronizado() throws Exception{ Conta c1 = new Conta(500.0); FazerDeposito acao = new FazerDeposito(c1); Thread t1 = new Thread(acao); Thread t2 = new Thread(acao); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(c1.getSaldo()); } }
package com.cos.blog.web; import java.io.IOException; import java.io.PrintWriter; import java.util.List; 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.cos.blog.domain.board.Board; import com.cos.blog.domain.board.dto.CommonRespDto; import com.cos.blog.domain.board.dto.DetailRespDto; import com.cos.blog.domain.board.dto.SaveReqDto; import com.cos.blog.domain.board.dto.UpdateReqDto; import com.cos.blog.domain.reply.dto.SaveRespDto; import com.cos.blog.domain.user.User; import com.cos.blog.service.BoardService; import com.cos.blog.service.ReplyService; import com.cos.blog.util.Parse; import com.cos.blog.util.Script; import com.google.gson.Gson; @WebServlet("/board") public class BoardController extends HttpServlet { private static final long serialVersionUID = 1L; public BoardController() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doProcess(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doProcess(request, response); } protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String cmd = request.getParameter("cmd"); BoardService boardService = new BoardService(); ReplyService replyService = new ReplyService(); RequestDispatcher dis = null; HttpSession session = request.getSession(); if (cmd.equals("saveForm")) { User principal = (User) session.getAttribute("principal"); if (principal != null) { dis = request.getRequestDispatcher("board/saveForm.jsp"); } else { dis = request.getRequestDispatcher("user/loginForm.jsp"); } } else if (cmd.equals("save")) { int userId = Integer.parseInt(request.getParameter("userId")); String title = request.getParameter("title"); String content = request.getParameter("content"); SaveReqDto dto = SaveReqDto.builder() .userId(userId) .title(title) .content(content) .build(); int result = boardService.글쓰기(dto); if (result == 1) { // 정상 dis = request.getRequestDispatcher("index.jsp"); } else { Script.back(response, "글쓰기 실패"); } } else if (cmd.equals("list")) { int page = Integer.parseInt(request.getParameter("page")); // 최초 0, Next:+1, Prev:-1 List<Board> boards = boardService.목록보기(page); int boardCount = boardService.게시물갯수세기(); int lastPage = (boardCount - 1) / 4; double currentPosition = (double)page/lastPage*100; request.setAttribute("lastPage", lastPage); request.setAttribute("boardList", boards); request.setAttribute("currentPosition", currentPosition); dis = request.getRequestDispatcher("board/list.jsp"); } else if (cmd.equals("detail")) { int boardId = Integer.parseInt(request.getParameter("boardId")); List<SaveRespDto> replyList = replyService.댓글보기(boardId); DetailRespDto dto = boardService.상세보기(boardId); String content = Parse.makeYoutube(dto.getContent()); dto.setContent(content); request.setAttribute("board", dto); request.setAttribute("replyList", replyList); dis = request.getRequestDispatcher("board/openDetail.jsp"); } else if (cmd.equals("delete")) { int boardId = Integer.parseInt(request.getParameter("boardId")); int result = boardService.게시물삭제(boardId); CommonRespDto<String> respDto = new CommonRespDto<>(); respDto.setStatusCode(result); respDto.setData("성공"); Gson gson = new Gson(); String respData = gson.toJson(respDto); PrintWriter out = response.getWriter(); out.print(respData); out.flush(); return; } else if (cmd.equals("updateForm")) { int boardId = Integer.parseInt(request.getParameter("boardId")); DetailRespDto dto = boardService.상세보기(boardId); request.setAttribute("board", dto); dis = request.getRequestDispatcher("board/updateForm.jsp"); } else if (cmd.equals("update")) { int boardId = Integer.parseInt(request.getParameter("boardId")); String title = request.getParameter("title"); String content = request.getParameter("content"); UpdateReqDto dto = UpdateReqDto.builder() .boardId(boardId) .title(title) .content(content) .build(); int result = boardService.게시물수정(dto); if (result == 1) { dis = request.getRequestDispatcher("board?cmd=detail&id="+boardId); } else { Script.back(response, "글 수정 실패"); } } else if (cmd.equals("search")) { int page = Integer.parseInt(request.getParameter("page")); // 최초 0, Next:+1, Prev:-1 String keyword = request.getParameter("keyword"); List<Board> boards = boardService.키워드검색(keyword, page); int boardCount = boardService.게시물갯수세기(keyword); int lastPage = (boardCount - 1) / 4; double currentPosition = (double)page/lastPage*100; request.setAttribute("lastPage", lastPage); request.setAttribute("boardList", boards); request.setAttribute("currentPosition", currentPosition); dis = request.getRequestDispatcher("board/list.jsp"); } dis.forward(request, response); } }
package com.example.km.genericapp.network; import com.example.km.genericapp.constants.Urls; import com.example.km.genericapp.models.posts.BlogData; import com.example.km.genericapp.models.posts.BlogItem; import com.example.km.genericapp.models.posts.Comment; import com.example.km.genericapp.models.posts.Post; import com.example.km.genericapp.models.posts.User; import java.util.ArrayList; import io.reactivex.Observable; import io.reactivex.functions.Function; import io.reactivex.functions.Function3; import io.reactivex.schedulers.Schedulers; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.GET; import retrofit2.http.Path; /** * JSON placeholder API service. */ public class PostalApiService { private static PostalApiInterface retrofitService; private static PostalApiInterface getService() { if (retrofitService == null) { retrofitService = new Retrofit.Builder() .baseUrl(Urls.JSON_PLACEHOLDER_API_BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build().create(PostalApiInterface.class); } return retrofitService; } public static Observable<ArrayList<Post>> getPosts() { return getService().getPosts(); } public static Observable<ArrayList<User>> getUsers() { return getService().getUsers(); } public static Observable<ArrayList<Comment>> getComments() { return getService().getComments(); } public static Observable<ArrayList<BlogItem>> getBlogItems() { Observable<ArrayList<Post>> observablePosts = getService().getPosts().subscribeOn(Schedulers.newThread()); Observable<ArrayList<User>> observableUsers = getService().getUsers().subscribeOn(Schedulers.newThread()); Observable<ArrayList<Comment>> observableComments = getService().getComments().subscribeOn(Schedulers.newThread()); return Observable.zip(observablePosts, observableUsers, observableComments, new Function3<ArrayList<Post>, ArrayList<User>, ArrayList<Comment>, BlogData>() { @Override public BlogData apply(ArrayList<Post> posts, ArrayList<User> users, ArrayList<Comment> comments) { return new BlogData(posts, users, comments); } }).map(new Function<BlogData, ArrayList<BlogItem>>() { @Override public ArrayList<BlogItem> apply(BlogData blogData) throws Exception { return getBlogItems(blogData); } }); } private static ArrayList<BlogItem> getBlogItems(BlogData blogData) { ArrayList<BlogItem> blogItems = new ArrayList<>(); for (Post post : blogData.getPosts()) { User user = blogData.getUsers().get(post.getUserId() - 1); ArrayList<Comment> commentsForPost = getCommentsByPostId(blogData.getComments(), post.getId()); blogItems.add(new BlogItem(post, user, commentsForPost)); } return blogItems; } private static ArrayList<Comment> getCommentsByPostId(ArrayList<Comment> allComments, int postId) { ArrayList<Comment> commentsForPost = new ArrayList<>(); for (Comment comment : allComments) { if (comment.getPostId() == postId) { commentsForPost.add(comment); } } return commentsForPost; } public interface PostalApiInterface { @GET("posts/{id}") Observable<Post> getPost(@Path("id") int id); @GET("posts/") Observable<ArrayList<Post>> getPosts(); @GET("users/") Observable<ArrayList<User>> getUsers(); @GET("comments/") Observable<ArrayList<Comment>> getComments(); } }
package com.oaec.model; /* * javaBean */ public class Student { public Student() { super(); } private String sid; private String sname; private int sage; private char ssex; public Student(String sid, String sname, int sage, char ssex, String sphone) { super(); this.sid = sid; this.sname = sname; this.sage = sage; this.ssex = ssex; this.sphone = sphone; } private String sphone; public String getSid() { return sid; } public void setSid(String sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public int getSage() { return sage; } public void setSage(int sage) { this.sage = sage; } public char getSsex() { return ssex; } public void setSsex(char ssex) { this.ssex = ssex; } public String getSphone() { return sphone; } public void setSphone(String sphone) { this.sphone = sphone; } }
package L1_EstruturaSequencial; import java.util.Scanner; public class Ex16_L1 { public static void main(String[] args) {int metrosLitros = 3; int lataLitros = 18;//3m - 1l float valorLata = 80f;// 9m - 3l int latasC = 1; System.out.println("Quantos metros quadrados deseja pintar?"); Scanner myObj = new Scanner(System.in); float areaQuad = myObj.nextFloat(); for (float litrosC = (areaQuad/metrosLitros); litrosC>18; litrosC=(litrosC-18)){ latasC = latasC + 1; } System.out.println("Latas necessarias: " + latasC + "\nTotal pela tinta: R$" + (latasC * valorLata)); } }
/** * */ package de.weathermodule.weather.client.presenter; import de.smartmirror.smf.client.presenter.AbstractPresenter; import de.weathermodule.weather.client.model.WeatherModel; import de.weathermodule.weather.client.view.WeatherView; /** * @author julianschultehullern * */ public class WeatherPresenter extends AbstractPresenter<WeatherView, WeatherModel> { public WeatherPresenter(WeatherView view, WeatherModel model) { super(view, model); // TODO Auto-generated constructor stub } }
package prog2.examen.entities; public class Adulto extends Persona { public Adulto(long cedula) { super(cedula); } }
package com.seva.Persistence; import com.seva.models.LoginDTO; public interface UserDAO { /** * * @param loginId String * @return loginVO */ LoginDTO fetchLoginCredentialsByLoginId(String loginId); }
package com.taurus.openbravo.integracionPOS.main; import com.taurus.openbravo.soapclient.entities.files.FileContainer; //Debe conectarse (o usar las clases que se conectan) con los webservices (SAP y OB), public class GT_CLS_MainServiceTemp { public String obtenerXML(String tipo, FileContainer file) { /* Aqui debo ir a buscar los archivos pendientes a bajar, de acuerdo al tipo que sean (productos, clientes,etc) buscar archivo de clientes;*/ String xml = ""; /* * if (tipo.equals("PRODUCTO")) { xml = * getGt_CLS_ServiceObtenerXMLs().obtenerXMLProductos(file); } else { * xml = ""; } */ // Aquí pongo el String con el XML mientras /* xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?> " + " <Productos xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" Cliente=\"160\" Ambiente=\"Q00\" Tipo=\"WBBDLD04\" ArchivoOrigen=\"WBBDLD_00140003\"> " + " <Producto RegistroID=\"1\"> " + " <Basico ClavePrincipal=\"NOTE53\"> " + " <Descripcion>TestFromJava3</Descripcion> " + " <Grupo>001001001</Grupo> " + " <UnidadBase>PCE</UnidadBase> " + " <AgrupoadorPrecios /> " + " <EstatusBloqueo /> " + " <Sucursal>CD01</Sucursal> " + " <IndicadorABC>A</IndicadorABC> " + " <Marca /> " + " </Basico> " + " <Impuestos> " + " <ImpuestoClave>C0</ImpuestoClave> " + " </Impuestos> " + " <UnidadesMedida> " + " <UnidadMedida Clave=\"BX\" Cantidad=\"12.0000\"> " + " <CodigosBarras> " + " <CodigoBarras Tipo=\"IC\" Principal=\"\" Valor=\"212233445541121\" /> " + " <CodigoBarras Tipo=\"IC\" Principal=\"X\" Valor=\"2122334455132\" /> " + " <CodigoBarras Tipo=\"IC\" Principal=\"\" Valor=\"21223344551143\" /> " + " </CodigosBarras> " + " </UnidadMedida> " + " </UnidadesMedida> " + " </Producto> " + " </Productos> "; */ /*xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +"<Promociones xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" Cliente=\"160\" Ambiente=\"Q00\" Tipo=\"WPDBBY01\" ArchivoOrigen=\"WPDBBY_01545699_GRUPOMATERIALES\">" +" <Promocion RegistroID=\"1\">" +" <Basico>" +" <PromocionID>PROMO#00034</PromocionID>" +" <Destino>SD01</Destino>" +" <Tipo>MGP</Tipo>" +" </Basico>" +" <Mecanica>" +" <Condicion>BB04</Condicion>" +" <VigenciaInicio>20151201</VigenciaInicio>" +" <VigenciaFin>20151212</VigenciaFin>" +" <CantidadVenta>30.000</CantidadVenta>" +" <Descripcion>1 EN 30 SE PAGA CON PASTA RUEDA</Descripcion>" +" <ArticulosVenta>" +" <Articulo ClavePrincipal=\"\" UnidadMedida=\"\" />" +" <Articulo ClavePrincipal=\"SP113\" UnidadMedida=\"BX\" />" +" <Articulo ClavePrincipal=\"SP115\" UnidadMedida=\"BX\" />" +" <Articulo ClavePrincipal=\"SP116\" UnidadMedida=\"BX\" />" +" <Articulo ClavePrincipal=\"SP117\" UnidadMedida=\"BX\" />" +" </ArticulosVenta>" +" <Beneficios>" +" <Articulo ClavePrincipal=\"PR014\" UnidadMedida=\"BX\" Cantidad=\"1.000\" />" +" </Beneficios>" +" </Mecanica>" +" </Promocion>" +"</Promociones>";*/ /* xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<MovimientosInventario xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ClienteID=\"160\" Ambiente=\"Q00\" Destino=\"SD01\" Tipo=\"MOVSINV_009\" Referencia=\"4900216354\" ArchivoOrigen=\"0090153297.txt\">" + "<Movimiento Referencia=\"4900216354\" Consecutivo=\"0002\" Centro=\"SD01\" Almacen=\"A001\" Articulo=\"NOTE53\" Cantidad=\"8.000\" UnidadMedida=\"BX\" Tipo=\"S\" PedidoPOS=\"0000036671\" PedidoSAP=\"0000088456\" Factura=\"0090153297\" />" + "</MovimientosInventario>";*/ /*xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<Clientes xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" Cliente=\"160\" Ambiente=\"Q00\" Tipo=\"DEBMAS04\" ArchivoOrigen=\"DEBMAS_00118026\">" + " <Cliente RegID=\"1\">" + " <IDSAP>000012388</IDSAP>" + " <Tratamiento>Señor</Tratamiento>" + " <GrupoCuentas>Y001</GrupoCuentas>" + " <Nombre>Timothy Camarillo</Nombre>" + " <Telefono>57018950</Telefono>" + " <Zona>000</Zona>" + " <RFC>CAMT130305RS9</RFC>" + " <Direccion>" + " <Pais>MX</Pais>" + " <Localidad>FUENTES MARES</Localidad>" + " <Poblacion>VILLA JUAREZ</Poblacion>" + " <Distrito>CHIHUAHUA</Distrito>" + " <CP>31064</CP>" + " <Estado>CHI</Estado>" + " <Calle>CALLE 3 607</Calle>" + " </Direccion>" + " <CondicionesComerciales>" + " <Organizacion>GV01</Organizacion>" + " <CanalDistribucion>DG</CanalDistribucion>" + " <DiasCredito>Y002</DiasCredito>" + " <SucursalAsignada>CD01</SucursalAsignada>" + " <VendedorAsignado>DG4</VendedorAsignado>" + " <Multitienda>X</Multitienda>" + " </CondicionesComerciales>" + " <FormasPago>CEJPTZ</FormasPago>" + " <RutaVisita>" + " <Dia>04</Dia>" + " <Frecuencia>VS</Frecuencia>" + " <Bloqueo>X</Bloqueo>" + " </RutaVisita>" + " <Interlocutores>" + " <Interlocutor Tipo=\"AG\" TipoConsec=\"000\" IDSAP=\"0000100005\" />" + " <Interlocutor Tipo=\"RE\" TipoConsec=\"000\" IDSAP=\"0000100005\" />" + " <Interlocutor Tipo=\"RG\" TipoConsec=\"000\" IDSAP=\"0000100005\" />" + " <Interlocutor Tipo=\"WE\" TipoConsec=\"000\" IDSAP=\"0000100005\" />" + " <Interlocutor Tipo=\"WE\" TipoConsec=\"001\" IDSAP=\"0000500000\" />" + " <Interlocutor Tipo=\"WE\" TipoConsec=\"002\" IDSAP=\"0000500001\" />" + " <Interlocutor Tipo=\"WE\" TipoConsec=\"003\" IDSAP=\"0000500002\" />" + " <Interlocutor Tipo=\"WE\" TipoConsec=\"004\" IDSAP=\"0000500003\" />" + " <Interlocutor Tipo=\"WE\" TipoConsec=\"005\" IDSAP=\"0000500040\" />" + " <Interlocutor Tipo=\"WE\" TipoConsec=\"006\" IDSAP=\"0000500044\" />" + " </Interlocutores>" + " </Cliente>" + "</Clientes>"; */ /* xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?> " +" <Precios xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" Cliente=\"160\" Ambiente=\"Q00\" Tipo=\"COND_A02\" ArchivoOrigen=\"COND_A_01617624_OFERTA_FINAL\">" + " <Precio RegistroID=\"1\"> " + " <Basico ProductoClave=\"NOTE53\"> " + " <Destino>SD01</Destino> " + " <Organizacion>AV01</Organizacion> " + " <Canal>R2</Canal> " + " </Basico> " + " <Condiciones UnidadMedida=\"BX\" ClaseCondicion=\"VKA0\" Moneda=\"MXN\" VigenciaInicio=\"20160120\" VigenciaFin=\"20160131\"> " + " <CostoActualizado>0.00</CostoActualizado> " + " <PrecioBase>203.40</PrecioBase> " + " </Condiciones> " + " </Precio> " + " </Precios>";*/ xml= "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<Creditos xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" Cliente=\"160\" Ambiente=\"Q00\" Tipo=\"CRESTA01\" ArchivoOrigen=\"CRESTA_01650536_UNITARIO\">" + " <Credito RegID=\"1\" IDSAP=\"12345\" Limite=\"4000.0000\" Saldo=\"3958.3900\" Bloqueado=\"\" />" + "</Creditos>"; return xml; } }
package com.gobicloo; import android.content.Context; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Filter; import android.widget.Filterable; import android.widget.TextView; import com.gobicloo.object.Station; import java.util.ArrayList; import java.util.List; /** * Station Adapter for ListView */ public class StationAdapter extends ArrayAdapter<Station> implements Filterable { private List<Station> stationsFull; public StationAdapter(Context context, List<Station> stations) { super(context, 0, stations); this.stationsFull = stations; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null){ convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_station,parent, false); } // Get view StationViewHolder viewHolder = (StationViewHolder) convertView.getTag(); if(viewHolder == null){ viewHolder = new StationViewHolder(); viewHolder.name = (TextView) convertView.findViewById(R.id.station); viewHolder.availableBikes = (TextView) convertView.findViewById(R.id.availableStands); viewHolder.availableStands = (TextView) convertView.findViewById(R.id.availableBikes); convertView.setTag(viewHolder); } Station station = getItem(position); // Fill view viewHolder.name.setText(station.getNameForDisplay()); viewHolder.availableBikes.setText(String.valueOf(station.getAvailable_bikes() + " Bicloo")); viewHolder.availableStands.setText(String.valueOf(station.getAvailable_bike_stands() + " places restantes")); // Set color for bike availability if(station.getAvailable_bikes() == 0) { viewHolder.availableBikes.setTextColor(Color.RED); } else { viewHolder.availableBikes.setTextColor(Color.parseColor("#ff669900")); } // Set color for bike stands if(station.getAvailable_bike_stands() == 0) { viewHolder.availableStands.setTextColor(Color.RED); } else { viewHolder.availableStands.setTextColor(Color.parseColor("#ff669900")); } return convertView; } private class StationViewHolder { public TextView name; public TextView availableStands; public TextView availableBikes; } @Override public Filter getFilter() { Filter filter = new Filter() { @Override protected void publishResults(CharSequence constraint, FilterResults results) { stationsFull = (List<Station>) results.values; // TODO To fix notifyDataSetChanged(); } @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults results = new FilterResults(); List<Station> filteredArrayNames = new ArrayList<Station>(); if (constraint.toString().equals("BIKE_ALL")) { filteredArrayNames = new ArrayList<Station>(stationsFull); } else { // Perfom filtering for (Station station : stationsFull) { // status OPEN ou CLOSE if (constraint.toString().equals("OPEN") && station.getStatus().startsWith(constraint.toString())) { filteredArrayNames.add(station); } // ou available_bikes else if (constraint.toString().equals("BIKE_AVAILABLE") && station.getAvailable_bike_stands() > 0) { filteredArrayNames.add(station); } } } results.count = filteredArrayNames.size(); results.values = filteredArrayNames; return results; } }; return filter; } }
package com.citibank.ods.modules.product.player.functionality.valueobject; import com.citibank.ods.entity.pl.TplPlayerMovEntity; /** * @author atilio.l.araujo * */ public class PlayerMovementDetailFncVO extends BasePlayerDetailFncVO { public PlayerMovementDetailFncVO() { m_baseTplPlayerEntity = new TplPlayerMovEntity(); } }
package pdp.uz.payload; import lombok.Getter; import lombok.Setter; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.List; @Getter @Setter public class PackageDto implements Serializable { @NotNull private String name; @NotNull private String key; @NotNull private Long value; @NotNull private double price; @NotNull private Integer validityDay; private boolean addResidue; private List<Long> tariffsId; }
package us.gibb.dev.gwt.demo.client; import us.gibb.dev.gwt.command.CommandEventBus; import us.gibb.dev.gwt.view.AbstractWidgetView; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.HasText; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.inject.Inject; public class GoodbyeViewImpl extends AbstractWidgetView<CommandEventBus> implements GoodbyePresenter.View { private TextBox name; private Button button; private Label result; @Inject public GoodbyeViewImpl(CommandEventBus eventBus) { super(eventBus); //final Label label = new Label("N/A"); name = new TextBox(); button = new Button("Get Hello"); result = new Label("N/A"); VerticalPanel verticalPanel = new VerticalPanel(); verticalPanel.add(name); verticalPanel.add(button); verticalPanel.add(result); initWidget(verticalPanel); } @Override public HasText getName() { return name; } @Override public HasText getResult() { return result; } @Override public String getLocation() { return "goodbye"; } public HasClickHandlers getButton() { return button; } }
import Mixer.Randomizer; import Sorters.*; public class Tester { public static void main(String[] args) { Randomizer randomizer = new Randomizer(10000); int[] array = randomizer.getRandomArray(); // int[] array = {5, 4, 3, 2, 1}; // new BubbleSort(array.clone()); // new CombSort(array.clone()); // new BogoSort(array.clone()); // new SelectionSort(array.clone()); // new InsertionSort(array.clone()); // new MergeSort(array.clone()); // new RadixSort(array.clone()); // new QuickSort(array.clone()); new HeapSort(array.clone()); } }
package training.gamelessormore; import junit.framework.Assert; import org.junit.After; import org.junit.Before; import org.junit.Test; public class ModelTest { private static Model model; @Before public void setUp() { model = new Model(-20,20); } @After public void tearDown() { model = null; } @Test public void testPlayerWin() { model.setCurrentNumber(model.getUnknownNumber()); Assert.assertTrue(model.playerWin()); } @Test public void testUnknownNumberMoreThanCurrent() { model.setCurrentNumber(model.getUnknownNumber() + 1); Assert.assertFalse(model.unknownNumberMoreThanCurrent()); } @Test public void testIsOutOfBoundary() { model.setCurrentNumber(1000); Assert.assertTrue(model.isOutOfBoundary(model.getCurrentNumber())); } @Test public void testIsOutOfBoundary1() { model.setCurrentNumber(18); Assert.assertFalse(model.isOutOfBoundary(model.getCurrentNumber())); } }
package com.hackathon.edxchange.userservice.repository; import com.hackathon.edxchange.userservice.entity.UserEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UsersRepository extends JpaRepository<UserEntity,Long> { }
package amery.spring.scheduler.timer; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestTimer { public static void main(String[] args) { System.out.println("Test start."); ApplicationContext context = new ClassPathXmlApplicationContext("com/amery/spring/scheduler/timer/TestTimer-context.xml"); System.out.print("Test end..\n"); } }
package com.cheese.radio.base.arouter; import android.content.Context; import android.net.Uri; import android.os.Bundle; import com.alibaba.android.arouter.facade.Postcard; import com.alibaba.android.arouter.facade.callback.NavigationCallback; import com.alibaba.android.arouter.launcher.ARouter; import com.binding.model.App; import com.binding.model.Config; import com.cheese.radio.R; import com.cheese.radio.inject.component.ActivityComponent; import com.cheese.radio.ui.Constant; /** * Created by arvin on 2017/12/6. */ public class ARouterUtil { public static void navigation(String url, Bundle bundle) { build(url, bundle).navigation(); } public static void navigation(String url) { navigation(url, ""); } public static void navigation(Uri url) { ARouter.getInstance().build(url).navigation(); } public static void navigationWeb(String url,String title){ Bundle bundle = new Bundle(); bundle.putString(Config.title,title); bundle.putString(Constant.url,url); ARouterUtil.navigation(ActivityComponent.Router.webview,bundle); } public static void navigationBack(String url, Bundle bundle, Context context, NavigationCallback callback) { build(url, bundle).navigation(App.getCurrentActivity(),callback); } private static Postcard build(String url, Bundle bundle) { return ARouter.getInstance() .build(url) .withTransition(R.anim.push_right_in, R.anim.push_right_out) .with(bundle); } // public static void navigationUrl(String url) { // ARouter.getInstance() // .build(ActivityComponent.Router.web_view) // .withTransition(R.anim.push_right_in, R.anim.push_right_out) // .withString(Config.path, url) // .navigation(); // } public static void navigation(String path, String title) { Bundle bundle = new Bundle(); bundle.putString(Config.title,title); navigation(path, bundle); } public static void itemNavigation(String location,int id){ Bundle bundle = new Bundle(); bundle.putInt(Constant.id,id); String path = ActivityComponent.Router.cheese+location .toLowerCase() .replace("_info","") .replace("_list","s"); ARouterUtil.navigation(path,bundle); } public static void itemNavigation(String location,int id,String tagName){ Bundle bundle = new Bundle(); bundle.putInt(Constant.id,id); bundle.putString(Constant.title,tagName); String path = ActivityComponent.Router.cheese+location .toLowerCase() .replace("_info","") .replace("_list","s"); ARouterUtil.navigation(path,bundle); } public static void LocationNavigation(String location,Bundle bundle){ String path = ActivityComponent.Router.cheese+location .toLowerCase() .replace("_info","") .replace("_list","s"); ARouterUtil.navigation(path,bundle); } }
package ru.buryachenko.moviedescription.database; import androidx.room.Database; import androidx.room.RoomDatabase; @Database(entities = {MovieRecord.class, TagRecord.class}, version = 1, exportSchema = false) public abstract class MovieDatabase extends RoomDatabase { public abstract MovieDao movieDao(); public abstract TagDao tagDao(); }
package servlets; import dao.UserDAO; import models.Password; import models.User; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; import java.io.File; import java.io.IOException; import java.util.Date; @WebServlet(name = "RegistrationServlet") @MultipartConfig public class RegistrationServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("cp1251"); response.setContentType("text/html;charset=cp1251"); String username = request.getParameter("username"); String name = request.getParameter("firstname"); String password = request.getParameter("password"); String newsuperpass = Password.hashPassword(password); String about = request.getParameter("about"); Date date = new Date(); UserDAO dao = new UserDAO(); request.getSession().setAttribute("name", name); Part p = request.getPart("photo"); String localdir = "uploads"; String pathDir = getServletContext().getRealPath("") + File.separator + localdir; File dir = new File(pathDir); if (!dir.exists()) { dir.mkdir(); } String[] filename_data = p.getSubmittedFileName().split("\\."); String filename = Math.random() + "." + filename_data[filename_data.length - 1]; String fullpath = pathDir + File.separator + filename; p.write(fullpath); if (dao.usernameExist(username)) { String errorMessage = "такой пользователь уже существует"; request.getSession().setAttribute("errorMessage", errorMessage); response.sendRedirect(request.getRequestURI()); //RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/registration"); //dispatcher.forward(request, response); //response.sendRedirect("/reg.jsp"); } else { User user = new User(username, newsuperpass, (long) 1, date, about, localdir + "/" + filename); dao.save(user); RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/login"); dispatcher.forward(request, response); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("cp1251"); response.setCharacterEncoding("cp1251"); response.setContentType("text/html;charset=cp1251"); RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/reg.jsp"); dispatcher.forward(request, response); } }
package com.dbsys.rs.service.impl; import java.sql.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.dbsys.rs.lib.DateUtil; import com.dbsys.rs.lib.entity.Operator; import com.dbsys.rs.lib.entity.Token; import com.dbsys.rs.lib.entity.Token.StatusToken; import com.dbsys.rs.lib.OutOfDateEntityException; import com.dbsys.rs.lib.UnauthenticatedAccessException; import com.dbsys.rs.repository.OperatorRepository; import com.dbsys.rs.repository.TokenRepository; import com.dbsys.rs.service.TokenService; @Service @Transactional(readOnly = true) public class TokenServiceImpl implements TokenService { @Autowired private TokenRepository tokenRepository; @Autowired private OperatorRepository operatorRepository; @Override public Token get(String tokenString) throws OutOfDateEntityException, UnauthenticatedAccessException { Token token = tokenRepository.findOne(tokenString); if (token.isExpire()) throw new OutOfDateEntityException(); if (token.isLock()) throw new UnauthenticatedAccessException(); token.extend(1); tokenRepository.save(token); return token; } @Override @Transactional(readOnly = false) public Token create(String username, String password) throws UnauthenticatedAccessException { Operator operator = operatorRepository.findByUsername(username); if (!operator.authenticate(password)) throw new UnauthenticatedAccessException(); Date tanggalBuat = DateUtil.getDate(); Token token = new Token(tanggalBuat, operator); return tokenRepository.save(token); } @Override @Transactional(readOnly = false) public void lock(String tokenString) { tokenRepository.updateStatus(tokenString, StatusToken.LOCK); } }
package com.sbs.sbsattend.model; public class Person{ private String name; private int permission; private int ID; private double quotan; public double getQuotan() { return quotan; } public void setQuotan(double quotan) { this.quotan = quotan; } public Person(String name, int permission, int iD, double quotan) { super(); this.name = name; this.permission = permission; this.ID = iD; this.quotan = quotan; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPermission() { return permission; } public void setPermission(int permission) { this.permission = permission; } public int getID() { return ID; } public void setID(int iD) { ID = iD; } }
package org.maxhoffmann.dev.Chain; import java.util.ArrayList; import org.apache.log4j.Logger; public class ProcessChainTimeOperations { private static final Logger LOGGER = Logger.getLogger(ProcessChainTimeOperations.class); public ProcessChainTimeOperations() { } public void chainTimeOperations(ArrayList<String> generatedChains, ArrayList<String> generatedChainTimes) { ArrayList<String> processChains = new ArrayList<String>(); ArrayList<String> chainTimes = new ArrayList<String>(); processChains = generatedChains; chainTimes = generatedChainTimes; for ( int i = 0; i < 100 /*chainTimes.size()*/; i++ ) { LOGGER.info((i+1) + ".\tProzesskette:\t" + processChains.get(i) + "\n\tProzesszeiten:\t" + chainTimes.get(i) + "\n"); } } }
/* * File: Logger.java * Author: David Green DGreen@uab.edu * Assignment: 2018-1FallP1-3 - EE333 Fall 2018 * Vers: 1.0.0 09/02/2018 dgg - initial coding */ /** * Abstract Super Class for loggers * * @author David Green dgreen@uab.edu */ public abstract class Logger{ // Some useful definitions /** * DEBUG level -- most verbose, lots of details when searching for a bug */ public static final int DEBUG = 0; /** * INFO level -- information that is routine operation */ public static final int INFO = 10; /** * TIMESTAMP level -- periodic time stamp */ public static final int TIMESTAMP = 20; /** * WARNING level -- information that is not normal but which it is believe * that the code can accommodate the situation correctly although the user * may want to know for future reasons */ public static final int WARNING = 50; /** * ERROR level -- information that is about an error that impacts the proper * operation of the program */ public static final int ERROR = 100; /** * ALWAYS level -- always print the information */ public static final int ALWAYS = 100000; protected int threshold; /** * Default Constructor */ public Logger() { } /** * Log a message if `level` is greater than or equal to logger's threshold. * The actual logging routine will add a newline to the logEntry if * appropriate. * * @param level message's level * @param logEntry text to log (a newline will be added if appropriate) */ public abstract void log(int level, String logEntry); /** * Set a new log threshold for actual logging * * @param newThreshold level that must be met or exceeded for actual logging * when the logger is asked to log something */ public void setLogThreshold(int newThreshold) { threshold = newThreshold; } }
/* * 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 br.edu.ifrs.mostra.services; import br.edu.ifrs.mostra.daos.InstituicaoDao; import br.edu.ifrs.mostra.models.Instituicao; import com.google.gson.Gson; import java.util.List; import javax.ejb.Stateless; import javax.inject.Inject; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; /** * * @author jean */ @Stateless @Path("/instituicao") public class InstituicaoBean { @Inject private InstituicaoDao instituicaoDao; public List<Instituicao> listAll() { return this.instituicaoDao.listAll(); } @POST @Path("/create") @Produces(MediaType.APPLICATION_JSON) public String create(@FormParam("nome") String nome, @FormParam("sigla") String sigla, @FormParam("cidade") String cidade, @FormParam("estado") String estado, @FormParam("site") String site, @FormParam("tipo") int tipo) { Instituicao inst = new Instituicao(0, nome, sigla, cidade, estado, site, tipo); inst = this.instituicaoDao.save(inst); Gson gson = new Gson(); String newInst = gson.toJson(inst); return newInst; } }
package net.lantrack.framework.sysbase.util; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.nio.channels.FileChannel; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.lantrack.framework.core.config.Config; import net.lantrack.project.search.util.JDBCUtils; /** * * 数据备份工具类 * 数据库+文件,系统统一定义的目录下 * * @author liumy * */ public class BackUpsUtil { private static Logger logger = LoggerFactory.getLogger(BackUpsUtil.class); /** MySQL安装目录的Bin目录的绝对路径 */ // private static String mysqlBinPath = MySqlPath.getMysqlPath(); private static String mysqlBinPath; /** 访问MySQL数据库的用户名 */ private static String username = JDBCUtils.user; /** 访问MySQL数据库的密码 */ private static String password = JDBCUtils.password; /** 访问MySQL数据库的库名*/ private static String dbName; /** 访问MySQL数据库的库名*/ private static String ip; static DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); /** * * methodName: restoreStart * date: 2018年2月5日 上午10:34:57 * @param : * @author: liumy * @param fileName 要恢复的文件夹名字 * @param request */ public static void restoreStart(String fileName,HttpServletRequest request) { try { //获得系统的备份路径 // String rootPathTemp = request.getSession().getServletContext().getRealPath("/"); // String rootPath = rootPathTemp.replace("\\", "/").substring(0, rootPathTemp.length()-1); String rootPath =Config.backupsPath; //判断当前操作系统的名称 String osNameType = System.getProperty("os.name").toLowerCase(); rootPath = osNameType.contains("window") ? rootPath : File.separator+rootPath; // 拼接获得待还原的sql文件 ----- 还原数据库 restoreSql(rootPath+File.separator+Config.backupsPath +File.separator+fileName+File.separator+dbName+".sql", osNameType); //还原文件 String mobileFile=request.getSession().getServletContext().getRealPath("/")+File.separator+"mobile"; //rootPath+File.separator+Config.uploadPath restoreFile(mobileFile, rootPath+File.separator+Config.backupsPath+File.separator+fileName+File.separator+Config.uploadPath); System.out.println("还原成功"); } catch (Exception e) { logger.error("数据还原时出现异常,异常信息为:"+e.getMessage()); } } /** * * methodName: restoreSql * 恢复指定的数据库文件 * date: 2018年1月24日 上午11:13:56 * @param : * @author: liumy * @param sqlFile 之前备份的sql文件全路径 * @param osName 系统的类型 */ public static void restoreSql(String sqlPath,String osNameType) { //判断当前操作系统的名称 if(osNameType.contains("window")){ recoverWindows(sqlPath); }else { recoverLinux(sqlPath); } } /** * * methodName: recoverWindows * 恢复数据库 (Windows操作系统时) * date: 2018年1月24日 上午11:20:08 * @param : * @author: liumy * @param sqlPath 之前备份的sql文件全路径 * @return */ public static boolean recoverWindows(String sqlPath) { if (!mysqlBinPath.endsWith(File.separator)) { mysqlBinPath = mysqlBinPath + File.separator; } // String command = "cmd /c \"" +mysqlBinPath + "mysql\" -u" + username // + " -p" + password + " -D" + dbname + "<"; String command = "cmd /c \"" +mysqlBinPath + "mysql\" -h "+ip+" -u" + username + " -p" + password + " --default-character-set=utf8 -D" + dbName + "<"; if(command.indexOf("\\")!=-1) { command = command.replace("\\", "/"); } String tempPath = "C:/temp/"; String newPath = tempPath+dbName+".sql"; if(sqlPath.indexOf(" ")!=-1) { File dempDir = new File(tempPath); if(!dempDir.exists()) { dempDir.mkdirs(); } command += newPath; }else { command += sqlPath; } File binDir = new File(mysqlBinPath); if(!binDir.exists()) { return false; } try { Process process = Runtime.getRuntime().exec(command); process.waitFor(); File newfile = new File(newPath); if(newfile.isFile()) { newfile.delete(); } File dempDir = new File(tempPath); if(dempDir.exists()) { dempDir.delete(); } } catch (IOException e1) { logger.error("恢复数据库时出现IO异常,异常信息为:"+e1.getMessage()); return false; } catch (InterruptedException e) { logger.error("恢复数据库时出现中断异常,异常信息为:"+e.getMessage()); return false; } return true; } /** * * methodName: recoverLinux * 恢复数据库 (Linux操作系统时) * date: 2018年1月24日 上午11:20:08 * @param sqlPath 之前备份的sql文件全路径 * @return */ public static boolean recoverLinux(String sqlPath) { String command = "mysql -h " + ip + " -u" + username + " -p" + password + " --default-character-set=utf8 -D" + dbName +"<"+sqlPath; try { Process process = Runtime.getRuntime().exec(new String[] {"/bin/sh","-c",command}); //Process process = Runtime.getRuntime().exec("sh/ "+command);//实际测试失败 process.waitFor(); } catch (IOException e1) { logger.error("Linux系统上执行恢复数据库时出现IO异常,异常信息为:"+e1.getMessage()); return false; } catch (InterruptedException e) { logger.error("Linux系统上执行恢复数据库时出现中断异常,异常信息为:"+e.getMessage()); return false; } return true; } /** * * methodName: backups * 手动备份统一人口 * date: 2018年1月24日 上午9:58:49 * @param delTime 保存的天数后自动删除 * @param rootPath * @author: liumy */ public static void backups(String delTime,String rootPath,String upfilePath) { try { //String rootPathTemp = request.getSession().getServletContext().getRealPath("/"); //String rootPath = rootPathTemp.replace("\\", "/").substring(0, rootPathTemp.length()-1); //判断当前操作系统的名称 D:/apache-tomcat-8.0.33/webapps/god-server String osName = System.getProperty("os.name").toLowerCase(); rootPath = osName.contains("window") ? rootPath : File.separator+rootPath; //系统的统一备份文件夹;装文件备份的路径根路径 String backupPathTemp = rootPath+File.separator+Config.backupsPath; //String backupPathTemp = rootPath+"-file";//装文件备份的路径根路径 File file = new File(backupPathTemp); //当目录不存在则新建目录文件夹 if(!file.exists()){ file.mkdirs(); } //当天日期,作为存放数据库的名字 String newDate = format.format(new Date()); //当天最新的文件夹 //D:**\2017-06-06 File folder = new File(backupPathTemp+File.separator+newDate);//在装文件的路径下在创建以时间为目录的文件夹 if(!folder.exists()){ folder.mkdir(); } //进行数据备份 if(osName.contains("window")){ backupSql(folder.getPath()); }else { backupLinux(folder.getPath(), dbName); } //系统的上传文件,进行备份操作 //附件路径 String mobileFile=upfilePath+File.separator+"mobile"; //rootPath+File.separator+Config.uploadPath backUpFile(mobileFile, folder.getPath()+File.separator+Config.uploadPath); //如果没有时间就直接跳过,不在执行删除操作 if(!"".equals(delTime) && null!=delTime){ /* * 删除保留天数之外的文件 * 获得备份下的文件夹下文件夹的数量 */ String[] listfolder = file.list(); //文件夹以时间命名;判断使用要删除文件夹的数量,大于预期时间 if(listfolder.length>Integer.parseInt(delTime)){ String min=listfolder[0]; for(int i=1;i<listfolder.length;i++){ if(compareDateStr(min,listfolder[i])){ min=listfolder[i]; } } listfolder = sortFromSmall(listfolder); //删除不符合时间文件夹 for(int i=0;i<listfolder.length-Integer.parseInt(delTime);i++){ //System.out.println(rootPath+"-file"+File.separator+listfolder[i]); File delFile = new File(rootPath+"-file"+File.separator+listfolder[i]); //System.out.println(delFile); if(delFile.exists()){ delFile(delFile); delFile.delete(); } } } } } catch (Exception e) { e.printStackTrace(); logger.error("数据备份时出现异常,异常信息为:"+e.getMessage()); } } /** * * methodName: backUpFile * 备份系统上传过的文件 * date: 2018年1月23日 下午9:04:11 * @param : * @author: liumy * @param sourcePath 系统的上传文件地址 * D:/apache-tomcat-8.0.33/webapps/god-server-uploadfile * @param destinationPath 系统备份后的目标地址 * D:\apache-tomcat-8.0.33\webapps\\god-server-file\\2018-02-05\\upload * @throws FileNotFoundException */ public static void backUpFile(String sourcePath, String destinationPath) throws FileNotFoundException{ File sourceFile = new File(sourcePath); if(!sourceFile.exists()){ sourceFile.mkdirs(); } File deFile = new File(destinationPath); if(!deFile.exists()){ deFile.mkdirs(); } File[] fs=sourceFile.listFiles(); // 循环拷贝文件 for (File f : fs) { if(f.isFile()){ //调用文件拷贝的方法 copyFile(f,new File(destinationPath+File.separator+f.getName())); }else if(f.isDirectory()){ //递归调用 创建文件夹 backUpFile(f.getPath(),destinationPath+File.separator+f.getName()); } } } /** * * methodName: restoreFile * 系统文件还原 * date: 2018年1月24日 下午3:33:00 * @param : * @param sourcePath 原系统路径 * @param destinationPath 备份后的路径 * @throws FileNotFoundException * @author: liumy */ public static void restoreFile(String sourcePath, String destinationPath) throws FileNotFoundException{ File sourceFile = new File(sourcePath); if(!sourceFile.exists()){ sourceFile.mkdirs(); // throw new FileNotFoundException("文件不存在:"+source); } File deFile = new File(destinationPath); if(!deFile.exists()){ deFile.mkdirs(); } File[] fs=deFile.listFiles(); // 循环拷贝文件 for (File f : fs) { if(f.isFile()){ //调用文件拷贝的方法 copyFile(f,new File(sourcePath+File.separator+f.getName())); }else if(f.isDirectory()){ //递归调用 创建文件夹 restoreFile(sourcePath+File.separator+f.getName(),destinationPath+File.separator+f.getName()); } } } /** * * methodName: backUpSql * 备份数据库 执行的导出备份等 * date: 2018年1月23日 下午2:56:04 * @param : * @author: liumy * @param filePath 存放的路径 */ public static void backupSql(String filePath) { // D://MySQL Server 5.1//bin\ if (!mysqlBinPath.endsWith(File.separator)) { mysqlBinPath = mysqlBinPath + File.separator; } //System.out.println(ip); String command = mysqlBinPath + "mysqldump -h "+ip+" -u" + username + " -p" + password + " --set-charset=utf8 " + dbName ; OutputStream os=null ; PrintWriter pw = null ; BufferedReader reader = null ; try { //拼成一个新的sql文件名字 ; File backuFile = new File(filePath+File.separator+dbName+".sql"); //创建文件 if(!backuFile.exists()){ backuFile.createNewFile(); } os = new FileOutputStream(backuFile); pw = new PrintWriter(new OutputStreamWriter(os, "utf8")); Process process = Runtime.getRuntime().exec(command); InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8"); reader = new BufferedReader(inputStreamReader); String line = null; while ((line = reader.readLine()) != null) { pw.println(line); } pw.flush(); } catch (UnsupportedEncodingException e) { logger.error("备份数据库时出现不支持的编码格式异常,异常信息为:"+e.getMessage()); throw new RuntimeException(e); } catch (IOException e) { logger.error("备份数据库时出现IO异常,异常信息为:"+e.getMessage()); throw new RuntimeException(e); } finally { try { if (reader != null) { reader.close(); } if (os != null) { os.close(); } if (pw != null) { pw.close(); } } catch (IOException e) { logger.error("备份数据库时出现IO异常,异常信息为:"+e.getMessage()); } } } /** * 备份数据库 (Linux操作系统时) * * @param output 输出流 * @param dbname 要备份的数据库名 */ public static boolean backupLinux(String dest, String dbname){ File todayFolder = new File(dest); if(!todayFolder.exists()) { todayFolder.mkdirs(); } String command = "mysqldump -h " + ip + " -u" + username + " -p" + password + " --set-charset=utf8 " + dbname + " > "+dest+File.separator+dbname+".sql"; try { //Process process = Runtime.getRuntime().exec(command); //实际在linux系统下执行失败 Process process = Runtime.getRuntime().exec(new String[] {"/bin/sh","-c",command}); process.waitFor(); } catch (UnsupportedEncodingException e) { logger.error("Linux系统上执行备份数据库时出现不支持的编码格式异常,异常信息为:"+e.getMessage()); return false; } catch (IOException e) { logger.error("Linux系统上执行备份数据库时出现IO异常,异常信息为:"+e.getMessage()); return false; } catch (InterruptedException e) { logger.error("Linux系统上执行备份数据库时出现中断异常,异常信息为:"+e.getMessage()); return false; } return true; } /** * * methodName: copyFile * date: 2018年1月24日 下午3:40:55 * @param : * @author: liumy * @param source 文件原 * @param dest 目的地路径 */ public static void copyFile(File source,File dest ){ FileInputStream fi = null; FileOutputStream fo = null; FileChannel in = null; FileChannel out = null; try { if(!dest.exists()){ dest.createNewFile(); } //读取文件 fi = new FileInputStream(source); //写文件 fo = new FileOutputStream(dest); //获取通道 in = fi.getChannel(); //获取通道 out = fo.getChannel(); //连接2个通道,从in中读取写入out中 in.transferTo(0, in.size(),out); } catch (FileNotFoundException e) { logger.error("复制文件时出现找不到指定文件的异常,异常信息为:"+e.getMessage()); } catch (IOException e) { logger.error("复制文件时出现IO异常,异常信息为:"+e.getMessage()); } finally { try { if (fi != null) { fi.close(); } if (in != null) { in.close(); } if (fo != null) { fo.close(); } if (out != null) { out.close(); } } catch (IOException e) { logger.error("备份数据库时出现IO异常,异常信息为:"+e.getMessage()); } } } /** * 比较俩个日期格式字符串大小 * @param: * @param: * @throws ParseException * @author:louxiaolin */ public static boolean compareDateStr(String str1,String str2) throws ParseException{ Date date1 = format.parse(str1); Date date2 = format.parse(str2); //date1在date2以后 return date1.after(date2); } /** * * methodName: sortFromSmall * 时间小到大排序 * date: 2018年1月24日 下午6:14:03 * @param : * @author: liumy * @param args * @return * @throws ParseException */ public static String[] sortFromSmall(String[] args) throws ParseException{ for(int i=0;i<args.length;i++){ for(int j=i+1;j<args.length;j++){ if(compareDateStr(args[i],args[j])){ String str=args[i]; args[i]=args[j]; args[j]=str; } } } return args; } /** * methodName: delFile * 删除文件夹 * * @param:delFile * @author:luoxiaolin */ public static void delFile(File delFile) { if(delFile.isDirectory()){ File[] listFiles = delFile.listFiles(); for(File file:listFiles){ delFile(file); } } delFile.delete(); } }
import java.io.*; class PalindromeInt{ public static void main(String args[]) throws IOException{ int num,rem=0,rev=0; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the number"); num=Integer.parseInt(br.readLine()); int ori=num; while(num!=0){ rem=num%10; rev=rev*10+rem; num=num/10; } if(ori==rev){ System.out.println("Palindrome"); } else{ System.out.println("Not a Palindrome"); } } }
package hr.apps.cookies.mcpare.dialogs; import android.app.AlertDialog; import android.content.Context; /** * Created by lmita_000 on 4.8.2015.. */ public class NoticeDialog extends AlertDialog { protected NoticeDialog(Context context) { super(context); } @Override public void setMessage(CharSequence message) { super.setMessage(message); } }
package br.com.fiap.bean; import java.io.InputStream; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.servlet.http.Part; import br.com.fiap.dao.GenericDao; import br.com.fiap.entity.Livro; @ManagedBean(name="bLivro") @RequestScoped public class LivrosBean { private Livro livro; private Part figura; public LivrosBean() { livro = new Livro(); } public Livro getLivro() { return livro; } public void setLivro(Livro livro) { this.livro = livro; } public Part getFigura() { return figura; } public void setFigura(Part figura) { this.figura = figura; } // método de ação (action), que retorna o redirecionamento // conforme o resultado da execução public String incluirLivro() { try { InputStream inputStream = figura.getInputStream(); byte[] imagem = new byte[(int) figura.getSize()]; inputStream.read(imagem, 0, (int) figura.getSize()); livro.setImagem(imagem); GenericDao<Livro> dao = new GenericDao<Livro>(Livro.class); dao.adicionar(livro); return "sucesso"; // dispatching para sucesso.xhtml } catch (Exception e) { return "erro"; // dispatching para erro.xhtml } } public List<Livro> getListaLivros() { GenericDao<Livro> dao = new GenericDao<Livro>(Livro.class); return dao.listar(); } }
/** * Spring Security configuration. */ package com.eikesi.im.message.security;
package com.Premium.service; import com.Premium.bean.Project; public interface ProjectService { public void addProject(Project project); public Project getProjectDetails(); }
package com.buddybank.mdw.dataobject.util; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.imageio.ImageIO; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Uploads { private static final Logger logger = LoggerFactory.getLogger(Uploads.class); private static String getFullPath(final String uploadsPath){ final SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); final Date date = new Date(); final String sPath = formatter.format(date); final File dir=new File(uploadsPath+"/"+sPath); if (dir.exists()==false){ final boolean success = dir.mkdirs(); if (success==false){ logger.error("BB-piggydeposit-service: file system exception"); return null; } } final String fullPath=uploadsPath+"/"+sPath; return fullPath; } public static String saveImage(String basePath, String base64Img) throws IOException{ final String fullPath=getFullPath(basePath); final long timeMillis=System.currentTimeMillis(); String photoPath=fullPath+"/"+timeMillis+"_PHOTO.PNG"; String photo=base64Img; if (photo!=null && !photo.equals("")){ final byte[] bImgPhoto = Base64.decodeBase64(base64Img); final FileOutputStream fos = new FileOutputStream(new File(photoPath)); fos.write(bImgPhoto); fos.close(); } else{ photoPath=""; } return photoPath; } public static String getEncodedImage(String fullPath) throws IOException{ String photo=null; if (fullPath!=null && !fullPath.equals("")){ final BufferedImage image = ImageIO.read(new File(fullPath)); if (image!=null){ final ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(image, "PNG", bos); final byte[] imageBytes = bos.toByteArray(); photo=Base64.encodeBase64String(imageBytes); bos.close(); } } return photo; } }
package cz.muni.fi.pa165.monsterslayers.tests; import cz.muni.fi.pa165.monsterslayers.dao.UserRepository; import cz.muni.fi.pa165.monsterslayers.entities.User; import cz.muni.fi.pa165.monsterslayers.enums.HeroStatus; import cz.muni.fi.pa165.monsterslayers.enums.RightsLevel; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import javax.validation.ConstraintViolationException; /** * Test class for User entity * * @author Maksym Tsuhui */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/test-context.xml" }) @Transactional public class UserTests { @Autowired private UserRepository userRepository; private User user; private String name = "user name"; private String email = "user@name.com"; private String password = "userPassword"; private HeroStatus userStatus = HeroStatus.ACTIVE; private RightsLevel rightsLevel = RightsLevel.CLIENT; private String imageMimeType = "image type"; private byte[] image = new byte[1]; @Before public void setup() { user = new User(); user.setName(name); user.setEmail(email); user.setPassword(password); user.setRightsLevel(rightsLevel); user.setImage(image); user.setImageMimeType(imageMimeType); userRepository.save(user); } @Test public void attributesTest() { User found = userRepository.findOne(user.getId()); Assert.assertEquals(name, found.getName()); Assert.assertEquals(email, found.getEmail()); Assert.assertEquals(password, found.getPassword()); Assert.assertEquals(rightsLevel, found.getRightsLevel()); Assert.assertEquals(image, found.getImage()); Assert.assertEquals(imageMimeType, found.getImageMimeType()); } @Test(expected = DataAccessException.class) public void saveUniqueEmailTest() { User user1 = new User(); user1.setName(name); user1.setEmail(email); user1.setPassword(password); userRepository.save(user1); } @Test(expected = ConstraintViolationException.class) public void saveNullNameTest() { User user1 = new User(); user1.setEmail("email@other.cz"); user1.setPassword(password); userRepository.save(user1); } @Test(expected = ConstraintViolationException.class) public void saveNullEmailTest() { User user1 = new User(); user.setName(name); user1.setPassword(password); userRepository.save(user1); } @Test(expected = ConstraintViolationException.class) public void saveNullPasswordTest() { User user1 = new User(); user.setName(name); user1.setEmail("email@other.cz"); userRepository.save(user1); } @Test public void equalityTest() { Assert.assertEquals(user, user); Assert.assertNotEquals(user, null); User user1 = new User(); user1.setName(name); user1.setEmail(email); user1.setPassword(password); Assert.assertEquals(user, user1); user1.setEmail("other@email.cz"); Assert.assertNotEquals(user, user1); } @Test public void hashCodeTest() { User user1 = new User(); user1.setName(name); user1.setEmail(email); user1.setPassword(password); Assert.assertEquals(user.hashCode(), user1.hashCode()); } }
package visitor; import aquarium.jellies.Jelly; public class AquariumVisitor { public void admire(Jelly jelly) { } }
package com.advancementbureau.encrypt; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class DecryptOne { public static void main(String args[]) throws FileNotFoundException { File inputFile = new File("output.txt"); Scanner in = new Scanner(inputFile); PrintWriter out = new PrintWriter("outputOne.txt"); while (in.hasNextLine()) { String inLine = in.nextLine(); //String outLine = ""; char[] inLinePieces = inLine.toCharArray(); char[] outLinePieces = new char[inLinePieces.length]; for (int i = 0; i < inLinePieces.length; i++) { char outChar; char inChar = inLinePieces[i]; if (inChar == '~' || inChar == '`' || inChar == '^') { outChar = ' '; } else { outChar = (char) (inChar - 3); } outLinePieces[i] = outChar; } String outLine = new String(outLinePieces); out.println(outLine); } in.close(); out.close(); } }
package com.example.model; import java.sql.Time; import java.text.SimpleDateFormat; import java.util.Date; public class DateFormatter { public static final void convertToDate(Date date){ SimpleDateFormat ft = new SimpleDateFormat ("yyyy.MM.dd"); ft.format(date); } public static final void convertToTime(Time time){ SimpleDateFormat ft = new SimpleDateFormat ("HH:mm:ss"); ft.format(time); } }
/* * Parts of code created by 2011-2014, Peter Abeles */ package imagestitcher; /** * * @author cjhay */ import boofcv.abst.feature.associate.AssociateDescription; import boofcv.abst.feature.associate.ScoreAssociation; import boofcv.abst.feature.detdesc.DetectDescribePoint; import boofcv.abst.feature.detect.interest.ConfigFastHessian; import boofcv.alg.distort.ImageDistort; import boofcv.alg.distort.PixelTransformHomography_F32; import boofcv.alg.distort.impl.DistortSupport; import boofcv.alg.feature.UtilFeature; import boofcv.alg.interpolate.impl.ImplBilinearPixel_F32; import boofcv.alg.sfm.robust.DistanceHomographySq; import boofcv.alg.sfm.robust.GenerateHomographyLinear; import boofcv.factory.feature.associate.FactoryAssociation; import boofcv.factory.feature.detdesc.FactoryDetectDescribe; import boofcv.gui.image.ShowImages; import boofcv.core.image.ConvertBufferedImage; import boofcv.io.image.UtilImageIO; import boofcv.struct.feature.AssociatedIndex; import boofcv.struct.feature.SurfFeature; import boofcv.struct.feature.TupleDesc; import boofcv.struct.geo.AssociatedPair; import boofcv.struct.image.ImageFloat32; import boofcv.struct.image.ImageSingleBand; import boofcv.struct.image.MultiSpectral; import georegression.fitting.homography.ModelManagerHomography2D_F64; import georegression.struct.homography.Homography2D_F64; import georegression.struct.point.Point2D_F64; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.ddogleg.fitting.modelset.ModelManager; import org.ddogleg.fitting.modelset.ModelMatcher; import org.ddogleg.fitting.modelset.ransac.Ransac; import org.ddogleg.struct.FastQueue; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; import javax.swing.JOptionPane; /** * * @author cjramos */ public class Stitcher{ static String newPath; static int c; static int filter=0; public Stitcher(){ System.out.println("Stitcher successfully initialized"); } static String initializeImages(String path1, String path2,int counter){ //converts and initializes the input to BufferedImages BufferedImage imageA, imageB; c = counter; imageA = UtilImageIO.loadImage(path1); imageB = UtilImageIO.loadImage(path2); newPath = stitch(imageA,imageB,ImageFloat32.class); return newPath; //returns the new path of the created image } public static <T extends ImageSingleBand> String stitch(BufferedImage imageA, BufferedImage imageB, Class<T> imageType){ T inputA = ConvertBufferedImage.convertFromSingle(imageA, null, imageType); T inputB = ConvertBufferedImage.convertFromSingle(imageB, null, imageType); // Detect using the standard SURF feature descriptor and describer DetectDescribePoint detDesc = FactoryDetectDescribe.surfStable( new ConfigFastHessian(1, 2, 200, 1, 9, 4, 4), null,null, imageType); ScoreAssociation<SurfFeature> scorer = FactoryAssociation.scoreEuclidean(SurfFeature.class,true); AssociateDescription<SurfFeature> associate = FactoryAssociation.greedy(scorer,2,true); // fit the images using a homography. This works well for rotations and distant objects. ModelManager<Homography2D_F64> manager = new ModelManagerHomography2D_F64(); GenerateHomographyLinear modelFitter = new GenerateHomographyLinear(true); DistanceHomographySq distance = new DistanceHomographySq(); ModelMatcher<Homography2D_F64,AssociatedPair> modelMatcher = new Ransac<Homography2D_F64,AssociatedPair>(123,manager,modelFitter,distance,60,9); Homography2D_F64 H = computeTransform(inputA, inputB, detDesc, associate, modelMatcher); if(filter==0){ //checks if feature match is appropriate newPath = renderStitching(imageA,imageB,H); return newPath; } else{ JOptionPane.showMessageDialog(null, "Stitching Failed"); return "Failed"; } } public static String renderStitching(BufferedImage imageA, BufferedImage imageB,Homography2D_F64 fromAtoB){ // specify size of output image double scale = 0.70; int outputWidth = imageA.getWidth(); int outputHeight = imageA.getHeight(); String nPath; // Convert into a BoofCV color format MultiSpectral<ImageFloat32> colorA = ConvertBufferedImage.convertFromMulti(imageA, null,true, ImageFloat32.class); MultiSpectral<ImageFloat32> colorB = ConvertBufferedImage.convertFromMulti(imageB, null,true, ImageFloat32.class); // Where the output images are rendered into MultiSpectral<ImageFloat32> work = new MultiSpectral<ImageFloat32>(ImageFloat32.class,outputWidth,outputHeight,3); // Adjust the transform so that the whole image can appear inside of it Homography2D_F64 fromAToWork = new Homography2D_F64(scale,0,colorA.width/200,0,scale,colorA.height/200,0,0,1); Homography2D_F64 fromWorkToA = fromAToWork.invert(null); // Used to render the results onto an image PixelTransformHomography_F32 model = new PixelTransformHomography_F32(); ImageDistort<MultiSpectral<ImageFloat32>,MultiSpectral<ImageFloat32>> distort = DistortSupport.createDistortMS(ImageFloat32.class, model, new ImplBilinearPixel_F32(),false, null); // Render first image model.set(fromWorkToA); distort.apply(colorA,work); // Render second image Homography2D_F64 fromWorkToB = fromWorkToA.concat(fromAtoB,null); model.set(fromWorkToB); distort.apply(colorB,work); // Convert the rendered image into a BufferedImage BufferedImage output = new BufferedImage(work.width,work.height,imageA.getType()); ConvertBufferedImage.convertTo(work,output,true); Graphics2D g2 = output.createGraphics(); try { nPath = System.getProperty("user.home") + "/Desktop/Image Stitcher/output_"+c+".jpg"; ImageIO.write(output, "jpg",new File(nPath)); //outputs the stitched image inside the folder System.out.println("Success"); JOptionPane.showMessageDialog(null, "Successfully Stitched Input Images"); return nPath; //returns path of the new image } catch (IOException ex) { Logger.getLogger(Stitcher.class.getName()).log(Level.SEVERE, null, ex); return "Failed"; } // draw lines around the distorted image to make it easier to see /*Homography2D_F64 fromBtoWork = fromWorkToB.invert(null); Point2D_I32 corners[] = new Point2D_I32[4]; corners[0] = renderPoint(0,0,fromBtoWork); corners[1] = renderPoint(colorB.width,0,fromBtoWork); corners[2] = renderPoint(colorB.width,colorB.height,fromBtoWork); corners[3] = renderPoint(0,colorB.height,fromBtoWork); g2.setColor(Color.ORANGE); g2.setStroke(new BasicStroke(4)); g2.drawLine(corners[0].x,corners[0].y,corners[1].x,corners[1].y); g2.drawLine(corners[1].x,corners[1].y,corners[2].x,corners[2].y); g2.drawLine(corners[2].x,corners[2].y,corners[3].x,corners[3].y); g2.drawLine(corners[3].x,corners[3].y,corners[0].x,corners[0].y);*/ // ShowImages.showWindow(output,"Stitched Images"); } public static<T extends ImageSingleBand, FD extends TupleDesc> Homography2D_F64 computeTransform(T imageA, T imageB, DetectDescribePoint<T,FD> detDesc, AssociateDescription<FD> associate, ModelMatcher<Homography2D_F64, AssociatedPair> modelMatcher ){ int i; // get the length of the description List<Point2D_F64> pointsA = new ArrayList<Point2D_F64>(); FastQueue<FD> descA = UtilFeature.createQueue(detDesc,100); List<Point2D_F64> pointsB = new ArrayList<Point2D_F64>(); FastQueue<FD> descB = UtilFeature.createQueue(detDesc,100); // extract feature locations and descriptions from each image describeImage(imageA, detDesc, pointsA, descA); describeImage(imageB, detDesc, pointsB, descB); // Associate features between the two images associate.setSource(descA); associate.setDestination(descB); associate.associate(); // create a list of AssociatedPairs that tell the model matcher how a feature moved FastQueue<AssociatedIndex> matches = associate.getMatches(); List<AssociatedPair> pairs = new ArrayList<AssociatedPair>(); //Critical Part ------------------------------------------------------------------------------------------!!!!!! System.out.println("Matches:"+matches.size()); if(matches.size()<175){ //Images can't be stitched due to low feature matches System.out.println("Low feature match"); filter = 1; } else{ //if feature match is above 175 filter = 0; } for(i=0;i<matches.size();i++){ AssociatedIndex match = matches.get(i); Point2D_F64 a = pointsA.get(match.src); Point2D_F64 b = pointsB.get(match.dst); pairs.add(new AssociatedPair(a,b,false)); } // find the best fit model to describe the change between these images if( !modelMatcher.process(pairs) ) throw new RuntimeException("Model Matcher failed!"); // return the found image transform return modelMatcher.getModelParameters().copy(); } private static <T extends ImageSingleBand, FD extends TupleDesc> void describeImage(T image, DetectDescribePoint<T,FD> detDesc, List<Point2D_F64> points, FastQueue<FD> listDescs){ int i; detDesc.detect(image); listDescs.reset(); for(i=0;i<detDesc.getNumberOfFeatures();i++){ points.add( detDesc.getLocation(i).copy() ); listDescs.grow().setTo(detDesc.getDescription(i)); } } }
package buttley.nyc.esteban.magicbeans.model.boards.gamelevels; import buttley.nyc.esteban.magicbeans.model.boards.Board; import buttley.nyc.esteban.magicbeans.model.boards.BoardTypeEnum; import buttley.nyc.esteban.magicbeans.model.boards.widgets.WidgetPool; /** * Created by Spoooon on 1/18/2015. */ public class GameLevel extends Board { private int mLevel; private GameMode mMode; private boolean mIsInitializing = true; public GameLevel(WidgetPool widgetPool) { super(widgetPool); mBoardType = BoardTypeEnum.GAME_LEVEL; addAllWidgets(); setLevel(); setMode(); setPoopMeterLevel(); } @Override public void addAllWidgets() { } public int getLevel() { return mLevel; } public void setLevel() { if(mIsInitializing = true){ mLevel = 1; mIsInitializing = false; } else{ mLevel++; } } public void setPoopMeterLevel(){ // PoopMeterWidget poopMeter = (PoopMeterWidget) mEntityList.get(1); // int poopLevel = (25 + (mLevel * 5)); // if(poopLevel < 100){ // poopMeter.setmStartingPoopLevel(poopLevel); // }else { // poopMeter.setmStartingPoopLevel(99); // } } public void setMode(){ mMode = GameMode.STANDARD; } public enum GameMode { STANDARD, IRONBUTT, BLACKOUT; } public GameLevel getNextLevel(){ setLevel(); setPoopMeterLevel(); return this; } }
package com.karya.bean; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; public class BudgetMonthlyDistributionBean { private int bmdId; @NotNull @NotEmpty(message = "Please enter monthly distribution code") private String distName; @NotNull @NotEmpty(message = "Please enter fiscal year") private String fiscalYear; @NotNull @NotEmpty(message = "Please select respective month") private String respMonth; private String percentAllocate; public int getBmdId() { return bmdId; } public void setBmdId(int bmdId) { this.bmdId = bmdId; } public String getDistName() { return distName; } public void setDistName(String distName) { this.distName = distName; } public String getFiscalYear() { return fiscalYear; } public void setFiscalYear(String fiscalYear) { this.fiscalYear = fiscalYear; } public String getRespMonth() { return respMonth; } public void setRespMonth(String respMonth) { this.respMonth = respMonth; } public String getPercentAllocate() { return percentAllocate; } public void setPercentAllocate(String percentAllocate) { this.percentAllocate = percentAllocate; } }
package tasks; import java.io.File; import java.io.IOException; import java.sql.SQLException; import java.util.concurrent.ExecutionException; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import db.PairType; import taxonomy.TaxonomyCreator; public class CreateTaxonomy { private final static Options options; static { options = new Options(); options.addOption("h", "helper", true, "Path to the helper db input."); options.addOption("o", "taxonomyDb", true, "Path to the taxonomy db output."); options.addOption("p", "pairType", true, "Optional pair type to create taxonomy for."); options.addOption("t", "tmp", true, "Temporary directory to use."); } public static void main(String[] args) { CommandLineParser parser = new BasicParser(); CommandLine cmd; try { cmd = parser.parse(options, args); File helperDb = new File(cmd.getOptionValue("h")); File taxonomyDb = new File(cmd.getOptionValue("o")); File tmpDir = cmd.hasOption("t") ? new File(cmd.getOptionValue("t")) : null; PairType pairType = null; try { pairType = PairType.valueOf(cmd.getOptionValue("p")); } catch (Exception IllegalArgumentException) {} try { TaxonomyCreator creator = new TaxonomyCreator(taxonomyDb, helperDb, tmpDir); if (pairType == null) { creator.create(); } else { creator.create(pairType); } creator.close(); } catch (IOException | SQLException | InterruptedException | ExecutionException e) { e.printStackTrace(); } } catch (ParseException e) { e.printStackTrace(); } } }
package com.mobiwise.challangeapp.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.codehaus.jackson.annotate.JsonIgnoreProperties; @Entity @Table(name = "challangeDB") @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class Challange implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue @Column(name = "id") private long id; @Column(name="challangeName") private String challangeName; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getChallangeName() { return challangeName; } public void setChallangeName(String challangeName) { this.challangeName = challangeName; } public String getChallangeDesc() { return challangeDesc; } public void setChallangeDesc(String challangeDesc) { this.challangeDesc = challangeDesc; } public int getChallangeTime() { return challangeTime; } public void setChallangeTime(int challangeTime) { this.challangeTime = challangeTime; } @Column(name="ChallangeDesc") private String challangeDesc; @Column(name="ChallangeTime") private int challangeTime; }
package edu.mit.cci.simulation.web; import edu.mit.cci.simulation.model.CompositeSimulation; import org.springframework.roo.addon.web.mvc.controller.RooWebScaffold; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @RooWebScaffold(path = "compositesimulations", formBackingObject = CompositeSimulation.class) @RequestMapping("/compositesimulations") @Controller public class CompositeSimulationController { @RequestMapping(value = "/{id}", method = RequestMethod.GET, headers = "accept=text/xml") @ResponseBody public CompositeSimulation showXml(@PathVariable("id") Long id, Model model) { return CompositeSimulation.findCompositeSimulation(id); } @RequestMapping(value = "/{id}", method = RequestMethod.GET, headers = "accept=text/html") public String show(@PathVariable("id") Long id, Model model) { addDateTimeFormatPatterns(model); model.addAttribute("compositesimulation", CompositeSimulation.findCompositeSimulation(id)); model.addAttribute("itemId", id); return "compositesimulations/show"; } }
package com.base.widget; import android.animation.Animator; import android.animation.Animator.AnimatorListener; import android.animation.ValueAnimator; import android.animation.ValueAnimator.AnimatorUpdateListener; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Point; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.LinearInterpolator; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.base.animator.FaceFieldEvaluator; import com.base.animator.PointEvaluator; import com.base.utils.DeviceInfoUtils; import com.heihei.fragment.live.logic.GiftAnimationController; import com.heihei.fragment.live.logic.GiftAnimationController.FaceField; import com.heihei.fragment.live.logic.OnGiftAnimationListener; import com.heihei.model.AudienceGift; import com.wmlives.heihei.R; /** * 礼物雨的动画管理 * * @author admin * */ public class FaceRainView extends FrameLayout { public static final int DEFAULT_DURATION = 2500;// 移动时间 public static final int DEFAULT_NEXTLINE_RAIN_DURATION = 240;// 每行雨滴的间隔时间 public static final int DEFAULT_TEXT_DURATION = 350;// 礼物名称的缩放时间(1.5--1.0--0.0) private int animType; private OnGiftAnimationListener mOnGiftAnimationListener; public FaceRainView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public FaceRainView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public FaceRainView(Context context) { super(context); init(); } int width = DeviceInfoUtils.getScreenWidth(getContext()); int height = DeviceInfoUtils.getScreenHeight(getContext()); private void init() { // setBackgroundResource(R.color.hh_color_gift_bg); // setAlpha(70); bitmaps = new Bitmap[3]; if (tipView != null && indexOfChild(tipView) != -1) { removeView(tipView); tipView = null; } tipView = LayoutInflater.from(getContext()).inflate(R.layout.layout_facerain_tip, null); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); params.gravity = Gravity.CENTER; addView(tipView, params); } private void initAnimRes() { switch (animType) { case GiftAnimationController.ANIM_BIANBIAN: bitmaps[0] = BitmapFactory.decodeResource(getResources(), R.drawable.red_bianbian); bitmaps[1] = BitmapFactory.decodeResource(getResources(), R.drawable.green_bianbian); bitmaps[2] = BitmapFactory.decodeResource(getResources(), R.drawable.yellow_bianbian); break; case GiftAnimationController.ANIM_BUBBLE: bitmaps[0] = BitmapFactory.decodeResource(getResources(), R.drawable.pink_bubble); bitmaps[1] = BitmapFactory.decodeResource(getResources(), R.drawable.yellow_bubble); bitmaps[2] = BitmapFactory.decodeResource(getResources(), R.drawable.green_bubble); break; case GiftAnimationController.ANIM_FINGER: bitmaps[0] = BitmapFactory.decodeResource(getResources(), R.drawable.pink_finger); bitmaps[1] = BitmapFactory.decodeResource(getResources(), R.drawable.white_finger); bitmaps[2] = BitmapFactory.decodeResource(getResources(), R.drawable.green_finger); break; } } private Bitmap[] bitmaps; int lineCount = 30;// 行数 int columnCount = 6;// 列数 int itemWidth = width / columnCount; int itemHeight = height / lineCount; private View tipView; private int[][] aniArrTmp = { { 0, 1, 1, 0, 1, 1 }, { 1, 1, 1, 1, 0, 0 }, { 0, 1, 1, 1, 1, 0 }, { 1, 1, 1, 0, 0, 1 }, { 0, 1, 1, 0, 1, 0 }, { 0, 0, 1, 1, 1, 1 }, { 1, 1, 0, 1, 0, 0 }, { 0, 1, 1, 0, 1, 0 }, { 1, 0, 1, 1, 0, 1 }, { 1, 1, 0, 1, 0, 1 }, { 0, 1, 1, 0, 1, 1 }, { 1, 1, 1, 1, 0, 0 }, { 0, 1, 1, 1, 1, 0 }, { 1, 1, 1, 0, 0, 1 }, { 0, 1, 1, 0, 1, 0 }, { 0, 0, 1, 1, 1, 1 }, { 1, 1, 0, 1, 0, 0 }, { 0, 1, 1, 0, 1, 0 }, { 1, 0, 1, 1, 0, 1 }, { 1, 1, 0, 1, 0, 1 }, { 0, 1, 1, 0, 1, 1 }, { 1, 1, 1, 1, 0, 0 }, { 0, 1, 1, 1, 1, 0 }, { 1, 1, 1, 0, 0, 1 }, { 0, 1, 1, 0, 1, 0 }, { 0, 0, 1, 1, 1, 1 }, { 1, 1, 0, 1, 0, 0 }, { 0, 1, 1, 0, 1, 0 }, { 1, 0, 1, 1, 0, 1 }, { 1, 1, 0, 1, 0, 1 } }; public void start(int animType, OnGiftAnimationListener mOnGiftAnimationListener) { stop(); this.mOnGiftAnimationListener = mOnGiftAnimationListener; this.animType = animType; initAnimRes(); currentIndex = lineCount - 1; addNextLineView(); ValueAnimator ani = ValueAnimator.ofFloat(1.5f, 1.0f); ani.setDuration(DEFAULT_TEXT_DURATION); ani.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float scale = (float) animation.getAnimatedValue(); tipView.setScaleX(scale); tipView.setScaleY(scale); } }); ani.start(); } public void setData(AudienceGift aGift) { if (tipView != null) { TextView tv_nickname = (TextView) tipView.findViewById(R.id.tv_nickname); TextView tv_gift_name = (TextView) tipView.findViewById(R.id.tv_gift_name); tv_nickname.setText(aGift.fromUser.nickname); tv_gift_name.setText(aGift.gift.name + "送"); } } public void stop() { currentIndex = -1; mHandler.removeMessages(0); // removeAllViews(); } private boolean hasRunEndAnim = false; public void addNextLineView() { if (currentIndex < 0) { return; } mHandler.removeMessages(0); addLineFaces(currentIndex); if (!hasRunEndAnim && currentIndex == 0) { hasRunEndAnim = true; ValueAnimator anim = ValueAnimator.ofFloat(1.0f, 0.0f); anim.setDuration(DEFAULT_TEXT_DURATION); anim.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float scale = (float) animation.getAnimatedValue(); tipView.setScaleX(scale); tipView.setScaleY(scale); } }); anim.start(); } currentIndex = currentIndex - 1; if (currentIndex < 0) { return; } Message msg = Message.obtain(); msg.obj = this; mHandler.sendMessageDelayed(msg, DEFAULT_NEXTLINE_RAIN_DURATION); } private int currentIndex = -1; private static Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { FaceRainView view = (FaceRainView) msg.obj; view.addNextLineView(); }; }; /** * 增加一行view * * @param line */ private void addLineFaces(int line) { int i = line; for (int j = 0; j < columnCount; j++) { if (aniArrTmp[i][j] > 0) { addFace(i, j); } } // for (int j = 0; j < columnCount; j++) { // if (i == 0) { // 行1,列1,2,4,5 // if (j == 1 || j == 2 || j == 4 || j == 5) { // addFace(i, j); // } // } else if (i == 1) { // if (j == 0 || j == 1 || j == 2 || j == 3) { // addFace(i, j); // } // } else if (i == 2) { // if (j == 1 || j == 2 || j == 3 || j == 4) { // addFace(i, j); // } // } else if (i == 3) { // if (j == 0 || j == 1 || j == 2 || j == 5) { // addFace(i, j); // } // } else if (i == 4) { // if (j == 1 || j == 2 || j == 4) { // addFace(i, j); // } // } else if (i == 5) { // if (j == 2 || j == 3 || j == 4 || j == 5) { // addFace(i, j); // } // } else if (i == 6) { // if (j == 0 || j == 1) { // addFace(i, j); // } // } else if (i == 7) { // if (j == 2 || j == 4) { // addFace(i, j); // } // } else if (i == 8) { // if (j == 0 || j == 1 || j == 3 || j == 5) { // addFace(i, j); // } // } else if (i == 9) { // if (j == 0 || j == 4) { // addFace(i, j); // } // } // } } private void addFace(int line, int column) { int left = column * itemWidth; int top = -1 * itemHeight; int right = (column + 1) * itemWidth; int bottom = 0 * itemHeight; final ImageView image = new ImageView(getContext()); int index = (int) (Math.random() * bitmaps.length); Bitmap bp = bitmaps[index]; image.setImageBitmap(bp); LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); addView(image, 0, params); int x = (int) (Math.random() * (right - left) + left); int y = (int) (Math.random() * (bottom - bp.getHeight() - top) + top); Point startP = new Point(x, y); Point endP = new Point(x, height); ValueAnimator moveAnim = ValueAnimator.ofObject(new PointEvaluator(), startP, endP); moveAnim.setDuration(DEFAULT_DURATION); moveAnim.setInterpolator(new AccelerateDecelerateInterpolator()); moveAnim.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { Point p = (Point) animation.getAnimatedValue(); image.setTranslationX(p.x); image.setTranslationY(p.y); } }); // if (animType == GiftAnimationController.ANIM_FINGER) { // moveAnim.reverse(); // } else { // moveAnim.start(); // } moveAnim.start(); FaceField startF = new FaceField(); startF.degrees = (int) (Math.random() * (FaceField.DEGREES_MAX - FaceField.DEGREES_MIN)); startF.scale = (float) (Math.random() * (FaceField.SCALE_MAX - FaceField.SCALE_MIN)); ValueAnimator srAnim = ValueAnimator.ofObject(new FaceFieldEvaluator(), startF, startF); srAnim.setDuration(DEFAULT_DURATION); srAnim.setInterpolator(new LinearInterpolator()); srAnim.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { FaceField pf = (FaceField) animation.getAnimatedValue(); image.setRotation(pf.degrees - 30); image.setScaleX(pf.scale + 0.8f); image.setScaleY(pf.scale + 0.8f); } }); if (line == 0 && column == 1) { srAnim.addListener(new AnimatorListener() { @Override public void onAnimationStart(Animator animation) { // TODO Auto-generated method stub } @Override public void onAnimationRepeat(Animator animation) { // TODO Auto-generated method stub } @Override public void onAnimationEnd(Animator animation) { if (mOnGiftAnimationListener != null) { mOnGiftAnimationListener.onGiftAnimationEnd(FaceRainView.this); } } @Override public void onAnimationCancel(Animator animation) { // TODO Auto-generated method stub } }); } srAnim.start(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); removeAllViews(); } }
package com.deepak.order.model; /** * Deepak Singhvi */ public class User { private String emailId; private String userFirstName; private String userLastName; public User() { } public User(String userId, String firstName, String lastName) { this.emailId = userId; this.userFirstName = firstName; this.userLastName = lastName; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } public String getUserFirstName() { return userFirstName; } public void setUserFirstName(String userFirstName) { this.userFirstName = userFirstName; } public String getUserLastName() { return userLastName; } public void setUserLastName(String userLastName) { this.userLastName = userLastName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return emailId.equals(user.emailId); } @Override public int hashCode() { return emailId.hashCode(); } @Override public String toString() { return "com.deepak.order.model.User{" + "emailId='" + emailId + '\'' + ", userFirstName='" + userFirstName + '\'' + ", userLastName='" + userLastName + '\'' + '}'; } }
package com.sunny.concurrent.hashmap; import java.util.HashMap; import java.util.Map; import java.util.Random; /** * <Description> HashMap的死循环, JDK1.8不会出现该问题<br> * * @author Sunny<br> * @version 1.0<br> * @taskId: <br> * @createDate 2018/10/22 10:59 <br> * @see com.sunny.concurrent.hashmap <br> */ public class HashMapHangDemo { final Map<Integer, Object> holder = new HashMap<Integer, Object>(); public static void main(String[] args) { HashMapHangDemo demo = new HashMapHangDemo(); for (int i = 0; i < 100; i++) { demo.holder.put(i, null); } Thread thread = new Thread(demo.getConcurrencyCheckTask()); thread.start(); thread = new Thread(demo.getConcurrencyCheckTask()); thread.start(); System.out.println("Start get in main!"); for (int i = 0; ; ++i) { for (int j = 0; j < 10000; ++j) { demo.holder.get(j); // 如果出现hashmap的get hang住问题,则下面的输出就不会再出现了。 // 在我的开发机上,很容易在第一轮就观察到这个问题。 System.out.printf("Got key %s in round %s\n", j, i); } } } ConcurrencyTask getConcurrencyCheckTask() { return new ConcurrencyTask(); } private class ConcurrencyTask implements Runnable { Random random = new Random(); /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see Thread#run() */ @Override public void run() { System.out.println("Add loop started in task!"); while (true) { holder.put(random.nextInt() % (1024 * 1024 * 100), null); } } } }
package org.uth.jdgtest1; import org.uth.jdgtest1.listeners.ExpirationEventLogListener; import java.util.concurrent.TimeUnit; import org.infinispan.client.hotrod.*; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.impl.ConfigurationProperties; public class RemoteExpirationTest { public static void main( String[] args ) { if( args.length != 1 ) { RemoteExpirationTest.log("Usage: RemoteExpirationTest targetHost"); System.exit(0); } // Create a configuration for a locally-running server ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host(args[0]).port(ConfigurationProperties.DEFAULT_HOTROD_PORT); // Connect to the server RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); RemoteCache<Integer,String> cache = cacheManager.getCache(); ExpirationEventLogListener listener = new ExpirationEventLogListener(); try { cache.addClientListener( listener ); RemoteExpirationTest.log( "Adding 20 entries with 10 seconds expiration..."); long start = System.currentTimeMillis(); for( int loop = 0; loop < 20; loop++ ) { cache.put( loop, Integer.toString( loop ) ); cache.put(loop, Integer.toString(loop), 10, TimeUnit.SECONDS); } long end = System.currentTimeMillis(); RemoteExpirationTest.log( "Added 20 items in " + ( end - start) + "ms." ); RemoteExpirationTest.log( "Cache thinks it has " + cache.size() + "entries." ); for( int loop = 0; loop < 20; loop++ ) { String fetch = cache.get(loop); RemoteExpirationTest.log( "Fetched " + loop + " and received " + fetch ); } // Manual remove cache.remove(10); cache.remove(15); RemoteExpirationTest.log( "After manual remove cache thinks it has " + cache.size() + " entries." ); try { Thread.sleep(11000); } catch( Exception exc ) { } RemoteExpirationTest.log( "After 11 seconds cache thinks it has " + cache.size() + " entries." ); } finally { cache.removeClientListener( listener ); RemoteExpirationTest.log( "Clearing down cache (removing " + cache.size() + " entries)"); long start = System.currentTimeMillis(); cache.clear(); long end = System.currentTimeMillis(); RemoteExpirationTest.log( "Cache cleared in " + ( end - start ) + "ms."); } } private static void log( String message ) { System.out.println( "[RemoteExpirationTest] " + message ); } }
package org.point85.domain.collector; import java.util.Objects; import javax.persistence.AttributeOverride; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorType; import javax.persistence.Entity; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Table; import org.point85.domain.DomainUtils; import org.point85.domain.dto.CollectorDataSourceDto; import org.point85.domain.persistence.DataSourceConverter; import org.point85.domain.plant.NamedObject; @Entity @Table(name = "DATA_SOURCE") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "TYPE", discriminatorType = DiscriminatorType.STRING) @AttributeOverride(name = "primaryKey", column = @Column(name = "SOURCE_KEY")) public abstract class CollectorDataSource extends NamedObject { public static final int DEFAULT_UPDATE_PERIOD_MSEC = 10000; @Column(name = "HOST") private String host; @Column(name = "USER_NAME") private String userName; @Column(name = "PASSWORD") private String userPassword; // to avoid repeated column mapping error @Column(name = "TYPE", insertable = false, updatable = false) @Convert(converter = DataSourceConverter.class) private DataSourceType sourceType; @Column(name = "PORT") private Integer port; protected CollectorDataSource() { super(); } protected CollectorDataSource(String name, String description) { super(name, description); } protected CollectorDataSource(CollectorDataSourceDto dto) { super(dto.getName(), dto.getDescription()); host = dto.getHost(); port = dto.getPort(); userName = dto.getUserName(); userPassword = dto.getUserPassword(); sourceType = dto.getSourceType() != null ? DataSourceType.valueOf(dto.getSourceType()) : null; } public abstract String getId(); public abstract void setId(String id); public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getEncodedPassword() { return userPassword; } public String getUserPassword() { return userPassword != null ? DomainUtils.decode(userPassword) : null; } public void setPassword(String password) { this.userPassword = password != null ? DomainUtils.encode(password) : null; } public DataSourceType getDataSourceType() { return this.sourceType; } public void setDataSourceType(DataSourceType type) { this.sourceType = type; } public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } @Override public boolean equals(Object obj) { if (obj instanceof CollectorDataSource) { return super.equals(obj); } return false; } @Override public int hashCode() { return Objects.hash(getName(), getHost()); } @Override public String toString() { return getId(); } }
package cz.muni.fi.pa165.monsterslayers.service; import org.dozer.Mapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * Implementation of bean mapping service using Dozer framework. * * @author Tomáš Richter */ @Service public class MappingServiceImpl implements MappingService { @Autowired private Mapper dozer; @Override public <T> Collection<T> mapTo(Iterable<?> objects, Class<T> mapToClass) { Collection<T> mappedCollection = new ArrayList<>(); for (Object object : objects) { mappedCollection.add(dozer.map(object, mapToClass)); } return mappedCollection; } @Override public <K, V> Map<K, V> mapTo(Map<?, V> objects, Class<K> mapToClass) { Map<K, V> mappedMap = new HashMap<>(); for(Map.Entry<?, V> entry : objects.entrySet()){ mappedMap.put(dozer.map(entry.getKey(), mapToClass), entry.getValue()); } return mappedMap; } @Override public <T> T mapTo(Object object, Class<T> mapToClass) { return dozer.map(object, mapToClass); } }
package com.test.base; import java.util.ArrayDeque; import java.util.Deque; import java.util.HashSet; /** * 测试,打印图出来 * @author YLine * * 2019年12月6日 上午10:37:22 */ public class NodeUtil { public static void print(Node node) { if (null == node) { System.out.println("node = null"); return; } StringBuilder sBuilder = new StringBuilder(); Deque<Node> queue = new ArrayDeque<>(); queue.add(node); HashSet<Node> cacheSet = new HashSet<>(); cacheSet.add(node); while (!queue.isEmpty()) { Node tempNode = queue.pollFirst(); sBuilder.append(tempNode.val); sBuilder.append(" -> ["); for (Node neighborNode : tempNode.neighbors) { sBuilder.append(neighborNode.val); sBuilder.append(','); if (!cacheSet.contains(neighborNode)) { cacheSet.add(neighborNode); queue.add(neighborNode); } } sBuilder.append(']'); sBuilder.append('\n'); } System.out.println(sBuilder.toString()); } }
package test; import javafx.geometry.Point2D; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Created by dimaf on 27.02.2018. */ public class Main { public static void main(String[] args) { System.out.println(" Hello world "); try { // Properties properties = new Properties(); // properties.load(Files.newBufferedReader(Paths.get("conf.properties"))); // // String pathToTxt = properties.getProperty("pathToTxt"); // String pathToImage = properties.getProperty("pathToImage"); // System.out.println(pathToTxt); // // CloseableHttpClient aDefault = HttpClients.createDefault(); // CloseableHttpResponse execute = aDefault.execute(new HttpGet("http://google.com")); // try (BufferedReader x = new BufferedReader(new InputStreamReader(execute.getEntity().getContent()))) { // String line; // Path path = Paths.get(pathToImage); // path.toFile().mkdirs(); // try (BufferedWriter bufferedWriter = Files.newBufferedWriter(path.resolve("google.html"))) { // while ((line = x.readLine()) != null) { // bufferedWriter.write(line); // } // } // } } catch (Exception e) { e.printStackTrace(); } generatePolygon(6, new Point2D(1000, 1000), false); } public static List<Point2D> generatePolygon(int polygonSize, Point2D max, boolean equilateral) { Random random = new Random(); Point2D start = new Point2D(random.nextInt((int) max.getX()), random.nextInt((int) max.getY())); int startAngle = 0; ArrayList<Point2D> polygon = new ArrayList<>(); for (int i = 0; i < polygonSize; i++) { startAngle += getOuterAngle(polygonSize, equilateral); Point2D newPoint = newPoint(start, startAngle, getMagnitude(equilateral, max)); polygon.add(checkAndModify(newPoint, max)); start = newPoint; } return polygon; } private static int getMagnitude(boolean equilateral, Point2D max) { Random random = new Random(); int magnitude = random.nextInt((int) Math.min(max.getX(), max.getY()) / 2); return equilateral ? magnitude : (int) (magnitude * 0.1) + random.nextInt((int) (magnitude * 0.9)); } private static Point2D newPoint(Point2D start, int angle, int magnitude) { return start.add(new Point2D(Math.cos(Math.toRadians(angle)) * magnitude, Math.sin(Math.toRadians(angle)) * magnitude)); } private static Point2D checkAndModify(Point2D point, Point2D max) { double x = point.getX() < 0.0 ? 0.0 : point.getX() > max.getX() ? max.getX() : point.getX(); double y = point.getY() < 0.0 ? 0.0 : point.getY() > max.getY() ? max.getY() : point.getY(); return new Point2D(x, y); } private static int getOuterAngle(int size, boolean equilateral) { return equilateral ? 360 / size : 180 / size + new Random().nextInt(180 / size); } }
package com.infohold.bdrp.authority.manager.impl; import java.util.List; import org.apache.shiro.config.Ini; import org.apache.shiro.config.Ini.Section; import org.springframework.beans.BeansException; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.infohold.bdrp.authority.model.AuthPermission; import com.infohold.core.dao.GenericDao; import com.infohold.core.utils.StringUtils; //@Service("chainDefinitionSectionMetaSource") public class ChainDefinitionSectionMetaSourceManagerImpl /*implements FactoryBean<Ini.Section>*/{ // @Autowired // private GenericDao<AuthPermission, String> authPermissionDao; // // @Value("${app.authority.filterChainDefinitions}") // private String filterChainDefinitions; // // private String configPath; // // /** // * 默认premission字符串 // */ // public static final String PREMISSION_STRING="perms[\"{0}\"]"; // // public Section getObject() throws BeansException { // //获取所有Resource // List<AuthPermission> list = authPermissionDao.find("from AuthPermission", null); // // Ini ini = new Ini(); // //加载默认的url // ini.load(filterChainDefinitions); // Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME); // //循环Resource的url,逐个添加到section中。section就是filterChainDefinitionMap, // //里面的键就是链接URL,值就是存在什么条件才能访问该链接 // for(AuthPermission perm : list){ // //如果不为空值添加到section中 // if(StringUtils.isNotEmpty(perm.getUri()) && StringUtils.isNotEmpty(perm.getPermission())) { //// section.put(resource.getUri(), MessageFormat.format(PREMISSION_STRING,resource.getPermission())); // // section.put(perm.getUri(), perm.getPermission()); // } // } // //// section.put("/**", "authc"); // return section; // } //// protected Ini convertPathToIni(String path) { //// //// Ini ini = new Ini(); //// //// //SHIRO-178: Check for servlet context resource and not //// //only resource paths: //// if (!ResourceUtils.hasResourcePrefix(path)) { //// ini = getServletContextIniResource(path); //// if (ini == null) { //// String msg = "There is no servlet context resource corresponding to configPath '" + path + "' If " + //// "the resource is located elsewhere (not immediately resolveable in the servlet context), " + //// "specify an appropriate classpath:, url:, or file: resource prefix accordingly."; //// throw new ConfigurationException(msg); //// } //// } else { //// //normal resource path - load as usual: //// ini.loadFromPath(path); //// } //// //// return ini; //// } //// protected Ini getServletContextIniResource(String servletContextPath) { //// String path = WebUtils.normalize(servletContextPath); //// if (getServletContext() != null) { //// InputStream is = getServletContext().getResourceAsStream(path); //// if (is != null) { //// Ini ini = new Ini(); //// ini.load(is); //// if (CollectionUtils.isEmpty(ini)) { //// log.warn("ServletContext INI resource '" + servletContextPath + "' exists, but it did not contain " + //// "any data."); //// } //// return ini; //// } //// } //// return null; //// } // // /** // * 通过filterChainDefinitions对默认的url过滤定义 // * // * @param filterChainDefinitions 默认的url过滤定义 // */ // public void setFilterChainDefinitions(String filterChainDefinitions) { // this.filterChainDefinitions = filterChainDefinitions; // } // // public Class<?> getObjectType() { // return this.getClass(); // } // // public boolean isSingleton() { // return true; // } }
package com.despegar.university.exercises.concurrence.domain.utils; import static org.testng.Assert.assertEquals; import org.joda.time.LocalDateTime; import org.testng.annotations.Test; @Test public class DateUtilsTest { public void toStringTest() { String expected = "2015-01-10"; LocalDateTime date = new LocalDateTime(2015, 01, 10, 12, 00); String actual = DateUtils.toString(date); assertEquals(actual, expected); } }
package mx.santander.listener.dao; import mx.santander.listener.model.TycsServiceMessage; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface TycsServiceMessageDao extends CrudRepository<TycsServiceMessage, Long> { TycsServiceMessage findByApplicationId(String applicationId); TycsServiceMessage findByBuc(String buc); TycsServiceMessage findByTycVersion(String tycVersion); }
package Stream_Concept; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class map_for_stream { public static void main(String[] args) { /* Stream map() method is useful to map or transform an input collection into a new output collection. map takes function as an argument For example, mapping numeric values to the squares of the numeric values or mapping characters to their uppercase equivalent etc. */ int[] arr1 = {1, 3, 4, 5, 6, 9}; Arrays.stream(arr1).map(item -> item * 2).forEach(System.out::print); //print the length of object in list List < String > list = new ArrayList<>(); list.add("ankit"); list.add("anky"); list.add("vikesh"); list.add("ab"); System.out.println(); System.out.println("length of items"); List<Integer> lengthlist = list.stream().map(item -> item.length()).collect(Collectors.toList()); lengthlist.forEach(System.out::print); } }
package com.atomix.synctask; import java.io.BufferedReader; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.util.Log; import com.atomix.customview.SidraCustomProgressDialog; import com.atomix.interfacecallback.OnUploadComplete; import com.atomix.sidrainfo.SidraPulseApp; public class ImageUploadAsyncTask extends AsyncTask<String, Void, Void> { private Activity activity; private ProgressDialog progressDialog; private OnUploadComplete callback; private int responseStatus; private String data; int fieldNo; public ImageUploadAsyncTask(Activity x, OnUploadComplete callback2, int fieldNo) { this.activity = x; this.callback = (OnUploadComplete) callback2; this.fieldNo = fieldNo; } @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = SidraCustomProgressDialog.creator(activity); } @Override protected Void doInBackground(String... params) { String func_id = params[0]; String path = params[1]; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(SidraPulseApp.getInstance().getBaseUrl()); MultipartEntity reqEntry = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntry.addPart("func_id", new StringBody(func_id)); reqEntry.addPart("user_id", new StringBody(Integer.toString(SidraPulseApp.getInstance().getUserInfo().getUserID()))); reqEntry.addPart("access_token", new StringBody(SidraPulseApp.getInstance().getUserInfo().getAccessToken())); if (fieldNo == 1) { if (path.equalsIgnoreCase("") || path.length() < 2) { reqEntry.addPart("photo", new StringBody("")); } else { FileBody bin = new FileBody(new File(path), "image/jpeg"); reqEntry.addPart("photo", bin); } } else if (fieldNo == 2) { if (path.equalsIgnoreCase("") || path.length() < 2) { reqEntry.addPart("image", new StringBody("")); } else { FileBody bin = new FileBody(new File(path), "image/jpeg"); reqEntry.addPart("image", bin); } reqEntry.addPart("forum_id", new StringBody(params[2])); reqEntry.addPart("comment_text", new StringBody(params[3])); reqEntry.addPart("video", new StringBody(params[4])); } httppost.setEntity(reqEntry); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); InputStream is = resEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } is.close(); String thisdata = ""; thisdata = sb.toString().trim(); if (fieldNo == 1) { JSONObject jDataObj = new JSONObject(thisdata); responseStatus = jDataObj.getInt("status"); JSONObject jDataPhoto = jDataObj.getJSONObject("data"); String uploadedPhotoName = jDataPhoto.getString("photo_name"); data = uploadedPhotoName; } else if (fieldNo == 2) { JSONObject jDataObj = new JSONObject(thisdata); responseStatus = jDataObj.getInt("status"); JSONObject jDataPhoto = jDataObj.getJSONObject("data"); jDataPhoto.getString("comment_id"); Log.i("Comments_id","" + jDataPhoto.getString("comment_id")); Log.i("Status","" + jDataPhoto.getBoolean("status")); data = thisdata; } Log.i ("CommentsPostStatus","***#"+ thisdata); Log.i ("UploadStatus","***"+ responseStatus); } catch (Exception ex) { Log.i ("CommentsPostStatus_try","***#" + ex.getMessage()); return null; } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); if(progressDialog.isShowing()) { progressDialog.dismiss(); } callback.onUploadComplete(responseStatus, data); } } /*ServerComAsyncTask request = new ServerComAsyncTask(this,new OnRequestComplete() { @Override public void onRequestComplete(String result) { System.out.println("Result Finally :: "+ result); } }); request.execute("URL"); */
package demo; import lombok.Data; @Data public class Feed { private String query; private double bid; private int campaignID; private int queryGroupID; public Feed(String query, double bid, int campaignID, int queryGroupID) { this.query = query; this.bid = bid; this.campaignID = campaignID; this.queryGroupID = queryGroupID; } }
/* * Copyright (c) 2020. The Kathra Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. * * Contributors: * IRT SystemX (https://www.kathra.org/) * */ package org.kathra.resourcemanager.group.dao; import com.arangodb.springframework.annotation.Document; import com.arangodb.springframework.annotation.Relations; import org.kathra.core.model.Group; import org.kathra.core.model.Group.*; import org.kathra.resourcemanager.resource.dao.AbstractResourceDb; import java.util.List; import org.kathra.resourcemanager.user.dao.UserDb; import org.kathra.resourcemanager.binaryrepository.dao.BinaryRepositoryDb; import org.kathra.resourcemanager.assignation.dao.AssignationDb; import org.kathra.core.model.Resource.*; import org.kathra.resourcemanager.user.dao.UserGroupEdge; import org.kathra.resourcemanager.group.dao.GroupBinaryRepositoryEdge; import org.kathra.resourcemanager.group.dao.GroupAssignationEdge; import org.kathra.resourcemanager.group.dao.GroupGroupEdge; /** * Entity class GroupDb implementing db resource for class Group * * Auto-generated by resource-db-generator@1.3.0 at 2020-02-06T20:56:05.830Z * @author jboubechtoula */ @Document("Groups") public class GroupDb extends AbstractResourceDb<Group> { private String path; @Relations(edges = UserGroupEdge.class, lazy = true) private UserDb technicalUser; @Relations(edges = GroupBinaryRepositoryEdge.class, lazy = true) private List<BinaryRepositoryDb> binaryRepositories; @Relations(edges = GroupAssignationEdge.class, lazy = true) private List<AssignationDb> members; @Relations(edges = GroupGroupEdge.class, lazy = true) private GroupDb parent; private SourceRepositoryStatusEnum sourceRepositoryStatus; private SourceMembershipStatusEnum sourceMembershipStatus; private PipelineFolderStatusEnum pipelineFolderStatus; private BinaryRepositoryStatusEnum binaryRepositoryStatus; public GroupDb() { } public GroupDb(String id) { super(id); } public String getPath() { return this.path;} public void setPath(String path) { this.path=path;} public UserDb getTechnicalUser() { return this.technicalUser;} public void setTechnicalUser(UserDb technicalUser) { this.technicalUser=technicalUser;} public List<BinaryRepositoryDb> getBinaryRepositories() { return this.binaryRepositories;} public void setBinaryRepositories(List<BinaryRepositoryDb> binaryRepositories) { this.binaryRepositories=binaryRepositories;} public List<AssignationDb> getMembers() { return this.members;} public void setMembers(List<AssignationDb> members) { this.members=members;} public GroupDb getParent() { return this.parent;} public void setParent(GroupDb parent) { this.parent=parent;} public SourceRepositoryStatusEnum getSourceRepositoryStatus() { return this.sourceRepositoryStatus;} public void setSourceRepositoryStatus(SourceRepositoryStatusEnum sourceRepositoryStatus) { this.sourceRepositoryStatus=sourceRepositoryStatus;} public SourceMembershipStatusEnum getSourceMembershipStatus() { return this.sourceMembershipStatus;} public void setSourceMembershipStatus(SourceMembershipStatusEnum sourceMembershipStatus) { this.sourceMembershipStatus=sourceMembershipStatus;} public PipelineFolderStatusEnum getPipelineFolderStatus() { return this.pipelineFolderStatus;} public void setPipelineFolderStatus(PipelineFolderStatusEnum pipelineFolderStatus) { this.pipelineFolderStatus=pipelineFolderStatus;} public BinaryRepositoryStatusEnum getBinaryRepositoryStatus() { return this.binaryRepositoryStatus;} public void setBinaryRepositoryStatus(BinaryRepositoryStatusEnum binaryRepositoryStatus) { this.binaryRepositoryStatus=binaryRepositoryStatus;} }
/******************************************************************************* * Copyright (c) 2012 itemis AG (http://www.itemis.eu) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.xtext.guicemodules.ui.contentassist; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.*; import org.eclipse.xtext.xbase.annotations.ui.contentassist.XbaseWithAnnotationsProposalProvider; import org.eclipse.xtext.ui.editor.contentassist.ICompletionProposalAcceptor; import org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext; /** * Represents a generated, default implementation of interface {@link IProposalProvider}. * Methods are dynamically dispatched on the first parameter, i.e., you can override them * with a more concrete subtype. */ @SuppressWarnings("all") public class AbstractGuiceModulesProposalProvider extends XbaseWithAnnotationsProposalProvider { public void completeModulesAST_Imports(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeModulesAST_Modules(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeModuleAST_Name(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeModuleAST_Mixins(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { lookupCrossReference(((CrossReference)assignment.getTerminal()), context, acceptor); } public void completeModuleAST_Bindings(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeBindingAST_From(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeBindingAST_To(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeBindingAST_ToInstance(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeKeyAST_Annotation(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeKeyAST_Type(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeImportAST_ImportedNamespace(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void complete_ModulesAST(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_ModuleAST(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_BindingAST(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_KeyAST(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_ImportAST(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_QualifiedNameWithWildCard(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } }
package digit; import java.util.Scanner; public class StringExam { public static void main(String []args){ // String outS = new String(); // String passwd = getRandString(90000); // crackPasswd(passwd, outS, 0); // crackPasswd(passwd, outS); } /** * 循环方式 * @param passwd input password string. * @param outStr result string. */ static void crackPasswd(String passwd, String outStr){ char []sArray = passwd.toCharArray(); for (char tmpc:sArray){ char c = '0'; for(; c <= 'z'; c++){ if( !(Character.isLetter(c) || Character.isDigit(c)) ) continue; if (c == tmpc){ outStr += c; break; } } } System.out.println(outStr); } /** * 递归方式 @param passwd input the password string. @param outStr result string @param num start Character num */ static void crackPasswd(String passwd, String outStr, int num){ int len = passwd.length(); char c = '0'; for(; c <= 'z'; c++) { if( Character.isLetter(c) || Character.isDigit(c) ) if( passwd.toCharArray()[num] == c ){ outStr += c; break; } } if(num == len-1) { System.out.println(passwd); System.out.println(outStr); return; } crackPasswd(passwd, outStr, num+1); } static String get5CharRandString() { return getRandString(5); } static String getRandString(int strLen) { String s = ""; short start = '0'; short end = 'z'+1; for (int i = 0; i < strLen; i++) { while(true){ char c = (char) ( Math.random()*( end - start)+start ); if(Character.isDigit(c) || Character.isLetter(c)){ s += c; break; } } } return s; } static void examStringCaseSort(){ String strArray[] = new String[8]; for (int i = 0; i < 8; i++) { strArray[i] = get5CharRandString(); System.out.printf("%d-%s%n", i, strArray[i]); } String tmp; for (int i = 0; i <strArray.length-1 ; i++) for(int j = 0; j < (strArray.length-1) - i; j++)//比较左边中最大的数,移动到右边 //将最大值交换到最右边 /* x x x x x x Z(max) x x x x x Y Z(max) x x x x X Y Z(max) */ if( strArray[j].toUpperCase().toCharArray()[0] > strArray[j+1].toUpperCase().toCharArray()[0] ) { String s1 = strArray[j]; String s2 = strArray[j+1]; System.out.print(s1.toUpperCase().toCharArray()[0]); System.out.print(">"); System.out.print(s2.toUpperCase().toCharArray()[0]); System.out.println(); tmp = strArray[j]; strArray[j] = strArray[j + 1]; strArray[j + 1] = tmp; } for (String str : strArray) { System.out.println(str); } } static void formatExam(){ String name = "garen"; String title = "Legenery"; int kill = 8; System.out.printf("%s kill already %d enemies, get%s", name, kill, title); System.out.println("请输入地名:"); Scanner s = new Scanner(System.in); String local = s.next(); // // System.out.println("请输入公司类型:"); // Scanner companyType = new Scanner(System.in); // // System.out.println("请输入老板名字:"); // Scanner bossName = new Scanner(System.in); // // System.out.println("请输入金额:"); // Scanner money = new Scanner(System.in); // // System.out.println("请输入产品:"); // Scanner product = new Scanner(System.in); // // System.out.println("请输入价格计量单位:"); // Scanner unit = new Scanner(System.in); // // System.out.printf("%s最大" + // "%s倒闭了,"+ // "老板%s"+ // "拿着%s抵工资", ); System.out.println(local); } }
public class Cercle extends Figure { int rayon; Cercle (int r){ super("Cercle"); this.rayon = r; } public double aire() { return 3.14 * this.rayon * this.rayon; } public String toString() { return "je suis un cercle d'aire" + this.aire(); } }
package mtuci.nikitakutselay.mobileapplicationprogrammingcourse; import android.content.Intent; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.MenuInflater; import android.app.DialogFragment; import android.widget.Toast; import java.util.Timer; import java.util.TimerTask; import mtuci.nikitakutselay.mobileapplicationprogrammingcourse.util.RandomDelay; public class FeedbackActivity extends AppCompatActivity implements FeedbackDialog.FeedbackDialogListener { private Timer feedbackTimer; private TimerTask feedbackTimerTask; private final Handler feedbackHandler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_feedback); if (savedInstanceState != null) { return; } AuthorInfoFragment authorInfo = AuthorInfoFragment.newInstance( getString(R.string.lab2_name)); getSupportFragmentManager() .beginTransaction() .add(R.id.lab2AuthorInfoContainer, authorInfo) .commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.feedback_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_feedback: DialogFragment feedbackDialog = new FeedbackDialog(); feedbackDialog.show(getFragmentManager(), "feedback"); return true; case R.id.action_individual_task: Intent intent = new Intent(this, ApplicationListActivity.class); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onDialogPositiveClick(DialogFragment dialog) { LoadingFragment loading = new LoadingFragment(); getSupportFragmentManager() .beginTransaction() .replace(R.id.lab2AuthorInfoContainer, loading) .commit(); initializeFeedbackTimerTask(); } private void initializeFeedbackTimerTask() { if (feedbackTimer != null) { feedbackTimer.cancel(); feedbackTimer = null; } feedbackTimer = new Timer(); feedbackTimerTask = new TimerTask() { @Override public void run() { feedbackHandler.post(new Runnable() { @Override public void run() { AuthorInfoFragment authorInfo = AuthorInfoFragment.newInstance( getString(R.string.lab2_name)); getSupportFragmentManager() .beginTransaction() .replace(R.id.lab2AuthorInfoContainer, authorInfo) .commit(); Toast toast = Toast.makeText(getApplicationContext(), getText(R.string.feedback_sent_notification), Toast.LENGTH_LONG); toast.show(); } }); } }; RandomDelay randomDelay = new RandomDelay(); feedbackTimer.schedule(feedbackTimerTask, randomDelay.getDelay()); } }
/******************************************************************************* * Copyright 2013 SecureKey Technologies 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.openmidaas.library.model; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.openmidaas.library.MIDaaS; import org.openmidaas.library.common.Constants; import org.openmidaas.library.common.Constants.ATTRIBUTE_STATE; import org.openmidaas.library.common.WorkQueueManager; import org.openmidaas.library.common.WorkQueueManager.Worker; import org.openmidaas.library.model.core.AbstractAttribute; import org.openmidaas.library.model.core.CompleteAttributeVerificationDelegate; import org.openmidaas.library.model.core.CompleteVerificationCallback; import org.openmidaas.library.model.core.InitializeAttributeVerificationDelegate; import org.openmidaas.library.model.core.InitializeVerificationCallback; import com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat; import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber; /** * Phone Attribute Class. * It expects Phone Number in E-164 format recommended by International Telecommunication Union. */ public class PhoneAttribute extends AbstractAttribute<String>{ private final String TAG = "PhoneAttribute"; public enum VERIFICATION_METHOD{ sms, call } /** * Constructs a new phone attribute. A new instance must be * created via the provided factory method. * @param initPhoneDelegate - the delegate class that starts the phone verification process. * @param completePhoneDelegate - the delegate class that completes the phone verification process. */ protected PhoneAttribute(InitializeAttributeVerificationDelegate initPhoneDelegate, CompleteAttributeVerificationDelegate completePhoneDelegate) { mName = Constants.RESERVED_WORDS.phone_number.toString(); mInitVerificationDelegate = initPhoneDelegate; mCompleteVerificationDelegate = completePhoneDelegate; mState = ATTRIBUTE_STATE.NOT_VERIFIED; } /** * Checks to see if the provided phone number is a possible and valid number. * @param value: The value of the 'phone' attribute. It highly encouraged to use E-164 format for phone numbers. * Format is something like: +<CountryCode><City/AreaCode><LocalNumber> * For example: +14162223333 number is in valid E164 format for Toronto city in Canada. * Here '1' as country code, '416' as area code and 2223333 as 7 digit local number. * For more information see: http://en.wikipedia.org/wiki/E.164 */ @Override protected boolean validateAttribute(String value) { //Check if Null or empty if(value == null || value.isEmpty()) { MIDaaS.logError(TAG, "Phone attribute value is null/empty"); return false; } //checks if any alphabet is present Pattern pattern = Pattern.compile(".*[a-zA-Z].*"); Matcher mat = pattern.matcher(value); if(mat.find()){ MIDaaS.logError(TAG, "No alphabets ae allowed in the Phone attribute. Please make sure the number is in standard E-164 format of\"+<CountryCode><City/AreaCode><LocalNumber>\""); return false; } //Tests whether a phone number matches a valid pattern using libphonenumber library by Google. PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); try { PhoneNumber parsedNumber = phoneUtil.parse(value, null); //Check if its a possible number. It is faster than doing validation. //It checks the number based on length and other general rules which applies to all types of phone numbers. if(phoneUtil.isPossibleNumber(parsedNumber)){ // Validation function checks if it matches a valid pattern. // It takes into account starting digits, length and validates based on the country it belongs if(phoneUtil.isValidNumber(parsedNumber)){ if(value.equalsIgnoreCase(phoneUtil.format(parsedNumber, PhoneNumberFormat.E164))){ return true; }else{ MIDaaS.logError(TAG, "Unacceptable Format Error: Phone Number entered is valid but not in expected standard E-164 format."); return false; } } } } catch (NumberParseException e) { MIDaaS.logError(TAG, "NumberParseException was thrown: " + e.toString()); } MIDaaS.logError(TAG, "Phone Number entered is invalid. Please make sure the number is in standard E-164 format of\"+<CountryCode><City/AreaCode><LocalNumber>\""); return false; } /** * Starts the phone verification process by sending the phone number to the * Attribute Verification Service. */ @Override public void startVerification(final InitializeVerificationCallback callback) { WorkQueueManager.getInstance().addWorkerToQueue(new Worker() { @Override public void execute() { mInitVerificationDelegate.startVerification(PhoneAttribute.this, callback); } }); } /** * Completes the phone verification process by sending a one-time code to the * Attribute Verification Service. */ @Override public void completeVerification(final String code, final CompleteVerificationCallback callback) { WorkQueueManager.getInstance().addWorkerToQueue(new Worker() { @Override public void execute() { mCompleteVerificationDelegate.completeVerification(PhoneAttribute.this, code, callback); } }); } @Override public void setPendingData(String data) { mPendingData = data; } @Override public String toString() { if( (mValue != null) && (!mValue.isEmpty()) ) { return mValue; } MIDaaS.logError(TAG, "Phone number value is null"); return ""; } }
/* * 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 telas; import dao.UsuarioDAO; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import javax.swing.text.MaskFormatter; import static modelos.CalcularIdade.CalculaIdade; import modelos.Usuario; import modelos.RandomDates; /** * * @author Hamilton */ public class TelaCadastro extends javax.swing.JFrame { /** * Creates new form TelaCadastro */ public List<Usuario> lista = new ArrayList(); public TelaCadastro() { initComponents(); cbGestante.setVisible(false); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); txtGen = new javax.swing.JComboBox<>(); jLabel7 = new javax.swing.JLabel(); cbGestante = new javax.swing.JCheckBox(); txtEstado = new javax.swing.JComboBox<>(); txtNome = new javax.swing.JTextField(); txtCidade = new javax.swing.JTextField(); txtCpf = new javax.swing.JFormattedTextField(); txtNasc = new javax.swing.JFormattedTextField(); txtTel = new javax.swing.JFormattedTextField(); jLabel8 = new javax.swing.JLabel(); btnSalvar = new javax.swing.JButton(); btnSair = new javax.swing.JButton(); jLabel9 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel1.setBackground(new java.awt.Color(255, 255, 255)); jLabel1.setFont(new java.awt.Font("Corbel", 1, 36)); // NOI18N jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("CADASTRO"); jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 30, 230, 50)); jLabel2.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jLabel2.setText("Nome:"); jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 120, -1, -1)); jLabel3.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jLabel3.setText("Data de Nascimento:"); jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 180, -1, 20)); jLabel4.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jLabel4.setText("CPF:"); jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 150, -1, -1)); jLabel5.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jLabel5.setText("Telefone:"); jPanel1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 210, -1, -1)); jLabel6.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jLabel6.setText("Cidade:"); jPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 240, -1, -1)); txtGen.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N txtGen.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Homem", "Mulher" })); txtGen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtGenActionPerformed(evt); } }); jPanel1.add(txtGen, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 270, -1, -1)); jLabel7.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jLabel7.setText("Gênero:"); jPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 270, -1, -1)); cbGestante.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N cbGestante.setText("Gestante"); cbGestante.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cbGestanteActionPerformed(evt); } }); jPanel1.add(cbGestante, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 300, -1, -1)); txtEstado.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N txtEstado.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "CE" })); jPanel1.add(txtEstado, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 240, -1, -1)); txtNome.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtNomeActionPerformed(evt); } }); jPanel1.add(txtNome, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 110, 335, 30)); jPanel1.add(txtCidade, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 240, 70, -1)); try { txtCpf.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } txtCpf.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtCpfActionPerformed(evt); } }); jPanel1.add(txtCpf, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 150, 105, -1)); try { txtNasc.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } jPanel1.add(txtNasc, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 180, 66, -1)); try { txtTel.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##) # ####-####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } jPanel1.add(txtTel, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 210, 110, -1)); jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/cadastro.png"))); // NOI18N jLabel8.setPreferredSize(new java.awt.Dimension(100, 100)); jPanel1.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 190, 150, 150)); btnSalvar.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N btnSalvar.setText("Salvar"); btnSalvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSalvarActionPerformed(evt); } }); jPanel1.add(btnSalvar, new org.netbeans.lib.awtextra.AbsoluteConstraints(420, 340, -1, -1)); btnSair.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N btnSair.setText("Voltar"); btnSair.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSairActionPerformed(evt); } }); jPanel1.add(btnSair, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 350, -1, -1)); jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/bgc4.png"))); // NOI18N jPanel1.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 510, 380)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void txtGenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtGenActionPerformed String selectedItem = txtGen.getSelectedItem().toString(); if (selectedItem == "Mulher") { cbGestante.setVisible(true); } else { cbGestante.setVisible(false); } }//GEN-LAST:event_txtGenActionPerformed private void cbGestanteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbGestanteActionPerformed // TODO add your handling code here: }//GEN-LAST:event_cbGestanteActionPerformed private void txtCpfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCpfActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtCpfActionPerformed private void txtNomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNomeActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtNomeActionPerformed private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed if (txtNome.getText().isEmpty() || txtCpf.getValue() == null || txtNasc.getValue() == null || txtTel.getValue() == null || txtCidade.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "Por favor, preencha todos os campos!"); } else { JOptionPane.showMessageDialog(null, "Cadastro realizado com sucesso!"); Usuario usuario = new Usuario(); usuario.setNome(txtNome.getText()); usuario.setCpf(txtCpf.getText()); usuario.setNasc(txtNasc.getText()); usuario.setTelefone(txtTel.getText()); usuario.setCidade(txtCidade.getText()); usuario.setEstado(txtEstado.getSelectedItem().toString()); usuario.setGenero(txtGen.getSelectedItem().toString()); int dian = Integer.valueOf(txtNasc.getText().substring(0, 2)); int mesn = Integer.valueOf(txtNasc.getText().substring(3, 5)); int anon = Integer.valueOf(txtNasc.getText().substring(6, 10)); if (CalculaIdade(dian, mesn, anon) >= 60 || cbGestante.isSelected()) { usuario.prioridade = "ALTA"; } else { usuario.prioridade = "NORMAL"; } RandomDates randomdates = new RandomDates(); Date randomdate = randomdates.createRandomDate(2021, 2022); Date dhj = GregorianCalendar.getInstance().getTime(); if (dhj.before(randomdate)) { usuario.status = "VACINADO"; } else { usuario.status = "NÃO VACINADO"; } DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); usuario.devento = LocalDate.of(randomdate.getYear(), randomdate.getMonth(), randomdate.getDay()).format(formatter); UsuarioDAO usuariodao = new UsuarioDAO(); usuariodao.cadastrarUsuario(usuario); }//GEN-LAST:event_btnSalvarActionPerformed } private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed TelaInicial tinicial = new TelaInicial(); tinicial.setVisible(true); this.dispose(); }//GEN-LAST:event_btnSairActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TelaCadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TelaCadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TelaCadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaCadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TelaCadastro().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnSair; private javax.swing.JButton btnSalvar; private javax.swing.JCheckBox cbGestante; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JTextField txtCidade; private javax.swing.JFormattedTextField txtCpf; private javax.swing.JComboBox<String> txtEstado; private javax.swing.JComboBox<String> txtGen; private javax.swing.JFormattedTextField txtNasc; private javax.swing.JTextField txtNome; private javax.swing.JFormattedTextField txtTel; // End of variables declaration//GEN-END:variables }
/*PLEASE DO NOT EDIT THIS CODE*/ /*This code was generated using the UMPLE 1.29.0.4181.a593105a9 modeling language!*/ package ca.mcgill.ecse223.kingdomino.controller; // line 9 "../../../../../TransferObjects.ump" public class TODomino { //------------------------ // MEMBER VARIABLES //------------------------ //TODomino Attributes private int id; private String leftTileType; private String rightTileType; private int numLeftTileCrown; private int numRightTileCrown; //------------------------ // CONSTRUCTOR //------------------------ public TODomino(int aId, String aLeftTileType, String aRightTileType, int aNumLeftTileCrown, int aNumRightTileCrown) { id = aId; leftTileType = aLeftTileType; rightTileType = aRightTileType; numLeftTileCrown = aNumLeftTileCrown; numRightTileCrown = aNumRightTileCrown; } //------------------------ // INTERFACE //------------------------ public boolean setId(int aId) { boolean wasSet = false; id = aId; wasSet = true; return wasSet; } public boolean setLeftTileType(String aLeftTileType) { boolean wasSet = false; leftTileType = aLeftTileType; wasSet = true; return wasSet; } public boolean setRightTileType(String aRightTileType) { boolean wasSet = false; rightTileType = aRightTileType; wasSet = true; return wasSet; } public boolean setNumLeftTileCrown(int aNumLeftTileCrown) { boolean wasSet = false; numLeftTileCrown = aNumLeftTileCrown; wasSet = true; return wasSet; } public boolean setNumRightTileCrown(int aNumRightTileCrown) { boolean wasSet = false; numRightTileCrown = aNumRightTileCrown; wasSet = true; return wasSet; } public int getId() { return id; } public String getLeftTileType() { return leftTileType; } public String getRightTileType() { return rightTileType; } public int getNumLeftTileCrown() { return numLeftTileCrown; } public int getNumRightTileCrown() { return numRightTileCrown; } public void delete() {} public String toString() { return super.toString() + "["+ "id" + ":" + getId()+ "," + "leftTileType" + ":" + getLeftTileType()+ "," + "rightTileType" + ":" + getRightTileType()+ "," + "numLeftTileCrown" + ":" + getNumLeftTileCrown()+ "," + "numRightTileCrown" + ":" + getNumRightTileCrown()+ "]"; } }
package me.darkeet.android.demo.fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import me.darkeet.android.base.DRBaseStackFragment; import me.darkeet.android.demo.R; import me.darkeet.android.demo.constant.IntentConstants; import me.darkeet.android.jni.NativeMethod; import me.darkeet.android.jni.UninstallObserver; import me.darkeet.android.log.DebugLog; /** * Name: NativeFragment * User: Lee (darkeet.me@gmail.com) * Date: 2015/11/13 11:47 * Desc: JNI的基本使用 */ public class NativeFragment extends DRBaseStackFragment implements View.OnClickListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(getArguments().getString(IntentConstants.FRAGMENT_TITLE)); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.demo_fragment_jni, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.findViewById(R.id.btn_normal).setOnClickListener(this); view.findViewById(R.id.btn_observer).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_normal: invokeNormalMethod(); break; case R.id.btn_observer: invokeAppUninstall(); break; } } // JNI方法调用 private void invokeNormalMethod() { NativeMethod nativeMethod = new NativeMethod(); DebugLog.i("C实现有参的java方法:" + nativeMethod.sayHi("test")); DebugLog.i("C实现两个整数相加方法:" + nativeMethod.add(120, 130)); DebugLog.i("C实现数据元素加5的方法:" + nativeMethod.intMethod(new int[]{2, 5, 8})); nativeMethod.callPrint(); // C调用静态方法 nativeMethod.callMethod(); // C调用实例方法 } // 启动卸载应用监听 private void invokeAppUninstall() { UninstallObserver.startTask(mActivity); } }
/* // Definition for a Node. class Node { int val; Node next; Node random; public Node(int val) { this.val = val; this.next = null; this.random = null; } } */ class Solution { public Node copyRandomList(Node head) { //Edge case if(head == null) return head; //create pointer Node iter = head, next; //First pass - copy each node, //link them side by side in singly linked list while(iter != null) { next = iter.next; Node copy = new Node(iter.val); iter.next = copy; copy.next = next; iter = next; } //Second pass - assign random pointers for copies iter = head; while(iter != null) { if(iter.random != null) iter.next.random = iter.random.next; iter = iter.next.next; } //Third pass - restore original list, extract copy iter = head; Node dummyHead = new Node(0); Node copy, copyIter = dummyHead; while(iter != null) { next = iter.next.next; //extract copy : copy = iter.next; copyIter.next = copy; copyIter = copy; //restore original list : iter.next = next; iter = next; } return dummyHead.next; } }