text
stringlengths
10
2.72M
package io.ceph.rgw.client.model.admin; import io.ceph.rgw.client.AdminClient; import io.ceph.rgw.client.action.ActionFuture; import io.ceph.rgw.client.action.ActionListener; import org.apache.commons.lang3.Validate; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.core.traits.LocationTrait; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.function.BiConsumer; import java.util.function.Function; /** * Created by zhuangshuo on 2020/7/28. */ public class RemoveKeyRequest extends AdminRequest { private static final SdkField<String> ACCESS_KEY_FIELD = SdkField .builder(MarshallingType.STRING) .getter(getter(RemoveKeyRequest::getAccessKey)) .setter(setter(Builder::withAccessKey)) .traits(LocationTrait.builder().location(MarshallLocation.QUERY_PARAM).locationName("access-key") .unmarshallLocationName("access-key").build()).build(); private static final SdkField<String> UID_FIELD = SdkField .builder(MarshallingType.STRING) .getter(getter(RemoveKeyRequest::getUid)) .setter(setter(Builder::withUid)) .traits(LocationTrait.builder().location(MarshallLocation.QUERY_PARAM).locationName("uid") .unmarshallLocationName("uid").build()).build(); private static final SdkField<String> SUB_USER_FIELD = SdkField .builder(MarshallingType.STRING) .getter(getter(RemoveKeyRequest::getSubUser)) .setter(setter(Builder::withSubUser)) .traits(LocationTrait.builder().location(MarshallLocation.QUERY_PARAM).locationName("subuser") .unmarshallLocationName("subuser").build()).build(); private static final SdkField<String> KEY_TYPE_FIELD = SdkField .builder(MarshallingType.STRING) .getter(getter(RemoveKeyRequest::getKeyTypeAsString)) .setter(setter(Builder::withKeyType)) .traits(LocationTrait.builder().location(MarshallLocation.QUERY_PARAM).locationName("key-type") .unmarshallLocationName("key-type").build()).build(); private static final List<SdkField<?>> SDK_FIELDS = Collections.unmodifiableList(Arrays.asList(ACCESS_KEY_FIELD, UID_FIELD, SUB_USER_FIELD, KEY_TYPE_FIELD)); private final String accessKey; private final String uid; private final String subUser; private final KeyType keyType; public RemoveKeyRequest(Builder builder) { super(builder); this.accessKey = Validate.notBlank(builder.accessKey, "accessKey cannot be empty string"); this.uid = builder.uid; this.subUser = builder.subUser; this.keyType = builder.keyType; } private static <T> Function<Object, T> getter(Function<RemoveKeyRequest, T> g) { return obj -> g.apply((RemoveKeyRequest) obj); } private static <T> BiConsumer<Object, T> setter(BiConsumer<Builder, T> s) { return (obj, val) -> s.accept((Builder) obj, val); } public String getAccessKey() { return accessKey; } public String getUid() { return uid; } public String getSubUser() { return subUser; } public KeyType getKeyType() { return keyType; } private String getKeyTypeAsString() { return toString(keyType); } @Override public Builder toBuilder() { return new Builder(this); } @Override public List<SdkField<?>> sdkFields() { return SDK_FIELDS; } @Override public String toString() { return "RemoveKeyRequest{" + "accessKey='" + accessKey + '\'' + ", uid='" + uid + '\'' + ", subUser='" + subUser + '\'' + ", keyType=" + keyType + "} " + super.toString(); } public static class Builder extends AdminRequestBuilder<Builder, RemoveKeyRequest, RemoveKeyResponse> { private String accessKey; private String uid; private String subUser; private KeyType keyType; public Builder(AdminClient client) { super(client); } private Builder(RemoveKeyRequest request) { withAccessKey(request.accessKey); withUid(request.uid); withSubUser(request.subUser); withKeyType(request.keyType); } public Builder withAccessKey(String accessKey) { this.accessKey = accessKey; return self(); } public Builder withUid(String uid) { this.uid = uid; return self(); } public Builder withSubUser(String subUser) { this.subUser = subUser; return self(); } public Builder withKeyType(KeyType keyType) { this.keyType = keyType; return self(); } private Builder withKeyType(String keyType) { return withKeyType(KeyType.fromString(keyType)); } @Override public RemoveKeyRequest build() { return new RemoveKeyRequest(this); } @Override public RemoveKeyResponse run() { return client.removeKey(build()); } @Override public ActionFuture<RemoveKeyResponse> execute() { return client.removeKeyAsync(build()); } @Override public void execute(ActionListener<RemoveKeyResponse> listener) { client.removeKeyAsync(build(), listener); } } }
package dataservice; import java.io.File; import java.rmi.Remote; import java.util.ArrayList; import java.util.HashMap; import po.MatchPO; import po.TeamPO; import po.TeamPerformancePO; public interface TeamDataService extends Remote{ /** * * @return 所有球队列表 */ public ArrayList<TeamPO> getTeamList(); /** * 返回球队缩写->球队的Map * @return */ public HashMap<String, TeamPO> getTeamMap(); /** * @return 所有球队简称列表 */ public ArrayList<String> getTeamAbbrList(); /** * 判断球队是否存在 * @param teamAbbr * @return boolean */ public boolean existTeam(String teamAbbr); /** * 根据简称获取球队参与的比赛 * @param teamAbbr * @return 球队参与比赛的列表 */ public ArrayList<MatchPO> getTeamMatches(String teamAbbr); /** * 根据简称获取球队所有比赛表现 * @param teamAbbr * @return 返回球队参与比赛表现列表 */ public ArrayList<TeamPerformancePO> getTeamPerformances(String teamAbbr); /** * 根据简称获取球队数据 * @param teamAbbr * @return 球队数据 */ public TeamPO getTeam(String teamAbbr); /** * 根据简称获取球队标志 * @param teamAbbr * @return svg球队标志 */ public File getTeamIcon(String teamAbbr); }
package com.design.patterns; import com.design.patterns.tests.*; public class Main { public static void main(String[] args) { //Arrange ITestPattern testPattern; //Probar adapter //testPattern = new TestAdapter(); //Probar bridge //testPattern = new TestBridge(); // Probar singleton //testPattern = new TestSingleton(); //Probar factory method //testPattern = new TestFactoryMethod(); //Probar Prototype testPattern = new TestPrototype(); //Act testPattern.test(); } }
package ppe.testsvisuels; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import ppe.classes.Outils; import ppe.classes.PasserelleServicesWebXML; import ppe.classes.PointDeTrace; import ppe.classes.Trace; import ppe.classes.Utilisateur; public class TestPasserelleServicesWebXML { public static void main(String[] args) throws ParseException { String msg; // // test visuel de la méthode getTousLesUtilisateurs // ArrayList<Utilisateur> lesUtilisateurs = new ArrayList<Utilisateur>(); // msg = PasserelleServicesWebXML.getTousLesUtilisateurs("europa", Outils.sha1("mdputilisateur"), lesUtilisateurs); // // affichage de la réponse // System.out.println(msg); // // affichage du nombre d'utilisateurs // System.out.println("Nombre d'utilisateurs : " + lesUtilisateurs.size()); // // affichage de tous les utilisateurs // for (Utilisateur unUtilisateur : lesUtilisateurs) // { System.out.println(unUtilisateur.toString()); // } // test visuel de la méthode getLesUtilisateursQueJautorise // // test visuel de la méthode getLesUtilisateursQueJautorise // ArrayList<Utilisateur> lesUtilisateurs = new ArrayList<Utilisateur>(); // msg = PasserelleServicesWebXML.getLesUtilisateursQueJautorise("europa", Outils.sha1("mdputilisateur"), lesUtilisateurs); // // affichage de la réponse // System.out.println(msg); // // affichage du nombre d'utilisateurs // System.out.println("Nombre d'utilisateurs : " + lesUtilisateurs.size()); // // affichage de tous les utilisateurs // for (Utilisateur unUtilisateur : lesUtilisateurs) // { System.out.println(unUtilisateur.toString()); // } // // test visuel de la méthode getLesUtilisateursQuiMautorisent // ArrayList<Utilisateur> lesUtilisateurs = new ArrayList<Utilisateur>(); // msg = PasserelleServicesWebXML.getLesUtilisateursQuiMautorisent("europa", Outils.sha1("mdputilisateur"), lesUtilisateurs); // // affichage de la réponse // System.out.println(msg); // // affichage du nombre d'utilisateurs // System.out.println("Nombre d'utilisateurs : " + lesUtilisateurs.size()); // // affichage de tous les utilisateurs // for (Utilisateur unUtilisateur : lesUtilisateurs) // { System.out.println(unUtilisateur.toString()); // } // test visuel de la méthode getLesParcoursDunUtilisateur // test visuel de la méthode getUnParcoursEtSesPoints // test visuel de la méthode envoyerPosition // Date laDate = Outils.convertirEnDateHeure("24/01/2018 13:42:21"); // // PointDeTrace lePoint = new PointDeTrace(26, 0, 48.15, -1.68, 50, laDate, 80); // msg = PasserelleServicesWebXML.envoyerPosition("europa", Outils.sha1("mdputilisateur"), lePoint); // System.out.println(msg); } // fin Main } // fin class
package com.itheima.service.impl; import com.itheima.dao.UserDao; import com.itheima.pojo.Role; import com.itheima.pojo.SysUser; import com.itheima.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service("userService") public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { /* // 先设置假的权限 List<GrantedAuthority> authorities = new ArrayList(); authorities.add(new SimpleGrantedAuthority("ROLE_USER")); // 通过用户名查询密码 SysUser sysUser = userDao.findByUsername(username); //判断认证是否成功 if(sysUser!=null){ User user = new User(username,sysUser.getPassword(),authorities); return user; }*/ //设置真的权限 // 通过用户名查询密码 SysUser sysUser = userDao.findByUsername(username); if(sysUser!=null){ List<GrantedAuthority> authorities = new ArrayList(); List<Role> roleList = sysUser.getRoleList(); for (Role role : roleList) { authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName())); } User user = new User(username,sysUser.getPassword(),authorities); return user; } return null; } /** * 查询所有用户展示 * @return */ public List<SysUser> findAll() { return userDao.findAll(); } /** * 添加用户 * @param user */ public void save(SysUser user) { userDao.save(user); } /** * 为用户添加角色 * 清楚角色信息,新建角色信息 * @param userId * @param roleIds */ public void saveRole4User(Integer userId, Integer[] roleIds) { userDao.delAllRoleInfo(userId); if (roleIds!=null){ for (Integer roleId : roleIds) { userDao.addRole4UserByRoleId(userId,roleId); } } } /** * 查询用户详情信息---详情页面的数据准备 * 数据回显也使用该方法 * 查询某个用户的所有信息 * * @return */ public SysUser findById(Integer id) { return userDao.findById(id); } /** * 查询判断用户是否唯一 * @param username * @return */ public SysUser isUniqueUsername(String username) { return userDao.findUserByUsernameisUnique(username); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.jearl.util; import java.lang.reflect.InvocationTargetException; /** * * @author bamasyali */ public final class PropertyUtils { private PropertyUtils() { } public static <Y extends Object> Y getProperty(Object entity, String fieldName) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { return (Y) org.apache.commons.beanutils.PropertyUtils.getProperty(entity, fieldName); } public static void setProperty(Object entity, String fieldName, Object value) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { org.apache.commons.beanutils.PropertyUtils.setProperty(entity, fieldName, value); } }
/* * © Copyright 2016 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied * verbatim in the file “COPYING“. In applying this licence, CERN does not waive the privileges and immunities granted * to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction. */ package cern.molr; import cern.molr.mole.annotations.MoleSpringConfiguration; import org.junit.Test; /** * Test definitions common to several test suites * * @author tiagomr */ public class TestDefinitions { public static class JunitMission { @Test public void mission1() { } @Test public void mission2() { } public void mission3() { } } public static class RunnableMission implements Runnable { @Override public void run() { } public void otherMethod() { } } @MoleSpringConfiguration(locations = {"test-bean-definition.xml"}) public static class RunnableSpringMission implements Runnable { @Override public void run() { } public void otherMethod() { } } public static class EmptyMission { } }
package GoogleScreenshot; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Google_Homepage_Screenshot { public static void main(String[] args) throws InterruptedException, IOException { System.setProperty("webdriver.chrome.driver","C:\\Users\\new\\eclipse-workspace\\BrowserAutomation\\DriverFiles\\chromedriver.exe"); WebDriver driver=null; driver=new ChromeDriver(); String Url="https://www.google.com/"; driver.get(Url); Thread.sleep(10000); //driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().window().maximize(); File Google_Screenshot= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(Google_Screenshot, new File("./Screenshot/GOOGLE.PNG")); } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.test.web.servlet.result; import java.lang.reflect.Method; import org.hamcrest.Matcher; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.util.ClassUtils; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder; import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.MethodInvocationInfo; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import static org.hamcrest.MatcherAssert.assertThat; import static org.springframework.test.util.AssertionErrors.assertEquals; import static org.springframework.test.util.AssertionErrors.assertNotNull; import static org.springframework.test.util.AssertionErrors.assertTrue; /** * Factory for assertions on the selected handler or handler method. * * <p>An instance of this class is typically accessed via * {@link MockMvcResultMatchers#handler}. * * <p><strong>Note:</strong> Expectations that assert the controller method * used to process the request work only for requests processed with * {@link RequestMappingHandlerMapping} and {@link RequestMappingHandlerAdapter} * which is used by default with the Spring MVC Java config and XML namespace. * * @author Rossen Stoyanchev * @author Sam Brannen * @since 3.2 */ public class HandlerResultMatchers { /** * Protected constructor. * Use {@link MockMvcResultMatchers#handler()}. */ protected HandlerResultMatchers() { } /** * Assert the type of the handler that processed the request. */ public ResultMatcher handlerType(Class<?> type) { return result -> { Object handler = result.getHandler(); assertNotNull("No handler", handler); Class<?> actual = handler.getClass(); if (handler instanceof HandlerMethod handlerMethod) { actual = handlerMethod.getBeanType(); } assertEquals("Handler type", type, ClassUtils.getUserClass(actual)); }; } /** * Assert the controller method used to process the request. * <p>The expected method is specified through a "mock" controller method * invocation similar to {@link MvcUriComponentsBuilder#fromMethodCall(Object)}. * <p>For example, given this controller: * <pre class="code"> * &#064;RestController * public class SimpleController { * * &#064;RequestMapping("/") * public ResponseEntity&lt;Void&gt; handle() { * return ResponseEntity.ok().build(); * } * } * </pre> * <p>A test that has statically imported {@link MvcUriComponentsBuilder#on} * can be performed as follows: * <pre class="code"> * mockMvc.perform(get("/")) * .andExpect(handler().methodCall(on(SimpleController.class).handle())); * </pre> * @param obj either the value returned from a "mock" controller invocation * or the "mock" controller itself after an invocation */ public ResultMatcher methodCall(Object obj) { return result -> { if (!(obj instanceof MethodInvocationInfo invocationInfo)) { throw new AssertionError(""" The supplied object [%s] is not an instance of %s. Ensure \ that you invoke the handler method via MvcUriComponentsBuilder.on().""" .formatted(obj, MethodInvocationInfo.class.getName())); } Method expected = invocationInfo.getControllerMethod(); Method actual = getHandlerMethod(result).getMethod(); assertEquals("Handler method", expected, actual); }; } /** * Assert the name of the controller method used to process the request * using the given Hamcrest {@link Matcher}. */ public ResultMatcher methodName(Matcher<? super String> matcher) { return result -> { HandlerMethod handlerMethod = getHandlerMethod(result); assertThat("Handler method", handlerMethod.getMethod().getName(), matcher); }; } /** * Assert the name of the controller method used to process the request. */ public ResultMatcher methodName(String name) { return result -> { HandlerMethod handlerMethod = getHandlerMethod(result); assertEquals("Handler method", name, handlerMethod.getMethod().getName()); }; } /** * Assert the controller method used to process the request. */ public ResultMatcher method(Method method) { return result -> { HandlerMethod handlerMethod = getHandlerMethod(result); assertEquals("Handler method", method, handlerMethod.getMethod()); }; } private static HandlerMethod getHandlerMethod(MvcResult result) { Object handler = result.getHandler(); assertTrue("Not a HandlerMethod: " + handler, handler instanceof HandlerMethod); return (HandlerMethod) handler; } }
/* * EbookDaoImplJDBC.java * * Created on 2008Äê3ÔÂ6ÈÕ, ÉÏÎç8:45 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package tot.dao.jdbc; import tot.dao.AbstractDao; import tot.db.DBUtils; import tot.util.StringUtils; import tot.bean.*; import tot.exception.ObjectNotFoundException; import tot.exception.DatabaseException; import java.sql.*; import java.util.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * * @author Administrator */ public class EbookDaoImplJDBC extends AbstractDao{ private static Log log = LogFactory.getLog(EbookDaoImplJDBC.class); /** Creates a new instance of EbookDaoImplJDBC */ public EbookDaoImplJDBC() { } /* * get last id */ public int getLastId(){ DataField df=null; int returnValue=0; String sql=null; sql="select id from t_ebook order by id desc"; Collection lists =this.getDataList_Limit_Normal(sql,"id",1,0); Iterator iter = lists.iterator(); if (iter.hasNext()) { df= (DataField)iter.next(); } if(df!=null){ returnValue=Integer.parseInt(df.getFieldValue("id"))+1; }else{ returnValue=1; } return returnValue; } public boolean add(int categoryid,String title,String viewimg,String publisher,String pubdate,String content,String filesize, String readurl,String downurl,String label,String fdesc){ Connection conn = null; PreparedStatement ps = null; boolean returnValue=true; String sql="insert into t_ebook(CategoryId,Title,ViewImg,Publisher,PubDate,Content,FileSize,ReadUrl,DownUrl,Label,Fdesc) values(?,?,?,?,?,?,?,?,?,?,?)"; try{ conn = DBUtils.getConnection(); ps=conn.prepareStatement(sql); ps.setInt(1,categoryid); ps.setString(2,title); ps.setString(3,viewimg); ps.setString(4,publisher); ps.setString(5,pubdate); ps.setString(6,content); ps.setString(7,filesize); ps.setString(8,readurl); ps.setString(9,downurl); ps.setString(10,label); ps.setString(11,fdesc); if(ps.executeUpdate()!=1) returnValue=false; } catch(SQLException e){ log.error("add ebook error",e); } finally{ DBUtils.closePrepareStatement(ps); DBUtils.closeConnection(conn); } return returnValue; } public boolean mod(int id,int categoryid,String title,String viewimg,String publisher,String pubdate,String content,String filesize, String readurl,String downurl,String label,String fdesc){ Connection conn = null; PreparedStatement ps = null; boolean returnValue=true; String sql="update t_ebook set CategoryId=?,Title=?,ViewImg=?,Publisher=?,PubDate=?,Content=?,FileSize=?,ReadUrl=?,DownUrl=?,Label=?,Fdesc=? where id=?"; try{ conn = DBUtils.getConnection(); ps=conn.prepareStatement(sql); ps.setInt(1,categoryid); ps.setString(2,title); ps.setString(3,viewimg); ps.setString(4,publisher); ps.setString(5,pubdate); ps.setString(6,content); ps.setString(7,filesize); ps.setString(8,readurl); ps.setString(9,downurl); ps.setString(10,label); ps.setString(11,fdesc); ps.setInt(12,id); if(ps.executeUpdate()!=1) returnValue=false; } catch(SQLException e){ log.error("mod ebook error",e); } finally{ DBUtils.closePrepareStatement(ps); DBUtils.closeConnection(conn); } return returnValue; } public boolean del(int id) throws ObjectNotFoundException,DatabaseException{ return exe("delete from t_ebook where id="+id); } public void batDel(String[] s){ this.bat("delete from t_ebook where id=?",s); } public void batRecommend(String[] s,int val){ this.bat("update t_ebook set IsRecommend="+val+" where id=?",s); } public void upHits(int id) throws ObjectNotFoundException,DatabaseException{ exe("update t_ebook set Hits=Hits+1 where id="+id); } public void upAgree(int id) throws ObjectNotFoundException,DatabaseException{ exe("update t_ebook set Agree=Agree+1 where id="+id); } public void upDegree(int id) throws ObjectNotFoundException,DatabaseException{ exe("update t_ebook set Degree=Degree+1 where id="+id); } public Collection getList_Limit(int categoryid,int isrecommend,String key,int orderby,int currentpage,int pagesize){ String str="id"; if(orderby==1){ str="Hits"; }else if(orderby==2){ str="Agree"; }else if(orderby==3){ str="degree"; } if(DBUtils.getDatabaseType() == DBUtils.DATABASE_MYSQL){ StringBuffer sql=new StringBuffer(512); sql.append("SELECT t_ebook.id as eid,t_ebook.Title as etitle,t_ebook.ViewImg,Publisher,PubDate,FileSize,ReadUrl,DownUrl,IsRecommend,Fdesc,Hits,Agree,t_category.Title as ctitle from t_ebook,t_category where t_ebook.CategoryId=t_category.id"); if(categoryid>0) sql.append(" and t_ebook.CategoryId="+categoryid); if(isrecommend>=0) sql.append(" and t_ebook.IsRecommend="+isrecommend); if(key!=null) sql.append(" and t_ebook.Label like '%"+key+"%'"); sql.append(" order by t_ebook."+str+" desc"); return getDataList_mysqlLimit(sql.toString(),"id,Title,ViewImg,Publisher,PubDate,FileSize,ReadUrl,DownUrl,IsRecommend,Fdesc,Hits,Agree,CategoryTitle",pagesize,(currentpage-1)*pagesize); } else if (DBUtils.getDatabaseType() == DBUtils.DATABASE_SQLSERVER) { StringBuffer sql=new StringBuffer(512); sql.append("SELECT TOP "); sql.append(pagesize); sql.append(" id,Title FROM t_ebook WHERE (id <=(SELECT MIN(id) FROM (SELECT TOP "); sql.append((currentpage-1)*pagesize+1); sql.append(" id FROM t_ebook"); sql.append(" ORDER BY id DESC) AS t))"); sql.append(" ORDER BY id DESC"); return getData(sql.toString(),"id,Title"); } else{ StringBuffer sql=new StringBuffer(512); sql.append("select id,Title from t_ebook"); return getDataList_Limit_Normal(sql.toString(),"id,Title",pagesize,(currentpage-1)*pagesize); } } public int getTotalCount(int categoryid,int isrecommend,String key){ StringBuffer sql=new StringBuffer(512); sql.append("SELECT count(*) FROM t_ebook,t_category where t_ebook.CategoryId=t_category.id "); if(categoryid>0) sql.append(" and t_ebook.CategoryId="+categoryid); if(isrecommend>0) sql.append(" and t_ebook.IsRecommend="+isrecommend); if(key!=null) sql.append(" and t_ebook.Label like '%"+key+"%'"); return(this.getDataCount(sql.toString())); } public DataField get(int id){ String fields="CategoryId,Title,ViewImg,Publisher,PubDate,Content,FileSize,ReadUrl,DownUrl,Label,IsRecommend,Hits,Agree,Degree,Fdesc"; return getFirstData("select "+fields+" from t_ebook where id="+id,fields); } public DataField getShow(int id){ String fields="Title,ViewImg,Publisher,PubDate,Content,FileSize,ReadUrl,DownUrl,Label,IsRecommend,Hits,Agree,Degree,Fdesc,CategoryId"; StringBuffer sql=new StringBuffer(); sql.append("SELECT t_ebook.Title as etitle,t_ebook.ViewImg,Publisher,PubDate,Content,FileSize,ReadUrl,DownUrl,Label,IsRecommend,Hits,Agree,Degree,Fdesc,t_category.Title as ctitle FROM t_ebook,t_category where t_ebook.CategoryId=t_category.id and t_ebook.id="+id); return getFirstData(sql.toString(),fields); } }
package com.drms.dao; import java.util.List; import com.drms.model.ListValue; public interface ListValueDao { List<ListValue> getAllLOV(); }
/** #dynamic-programming #01knapsack */ import java.util.Scanner; public class PoloPenguinAndTest { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int testcase = sc.nextInt(); for (int t = 0; t < testcase; t++) { int n = sc.nextInt(); int w = sc.nextInt(); int c, p, T; Item[] arr = new Item[n + 1]; arr[0] = new Item(0, 0); for (int i = 1; i <= n; i++) { c = sc.nextInt(); p = sc.nextInt(); T = sc.nextInt(); arr[i] = new Item(c * p, T); } int result = Knapsack(arr, w); System.out.println(result); } } public static int Knapsack(Item[] arr, int W) { int[][] K = new int[arr.length][W + 1]; for (int i = 1; i < arr.length; i++) { for (int j = 0; j <= W; j++) { if (arr[i].cost > j) { K[i][j] = K[i - 1][j]; } else { int tmp1 = arr[i].profit + K[i - 1][j - arr[i].cost]; int tmp2 = K[i - 1][j]; K[i][j] = Math.max(tmp1, tmp2); } } } return K[arr.length - 1][W]; } } class Item { int profit; int cost; Item(int profit, int cost) { this.profit = profit; this.cost = cost; } }
/* * Copyright 2014 Victor Melnik <annimon119@gmail.com>, and * individual contributors as indicated by the @authors tag. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.annimon.jecp.android; import android.app.Activity; import android.content.res.AssetManager; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; import com.annimon.jecp.ApplicationListener; import com.annimon.jecp.Jecp; public abstract class Application extends Activity { static AssetManager sAssetManager; private ApplicationListener listener; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); sAssetManager = getAssets(); Jecp.helper = new JecpHelper(this); onCreate(); } public void init(ApplicationListener listener) { this.listener = listener; final PaintSurfaceView view = new PaintSurfaceView(this, listener); view.setFocusable(true); setContentView(view); } protected abstract void onCreate(); @Override protected void onPause() { listener.onPauseApp(); super.onPause(); } @Override protected void onDestroy() { listener.onDestroyApp(); super.onDestroy(); } }
package com.itheima.day_06.demo_02; import java.util.Comparator; import java.util.TreeSet; public class TreeSetDemo_02 { /* 按总成绩降序排列集合内的对象 */ public static void main(String[] args) { TreeSet<Student> set = new TreeSet<>(new Comparator<Student>() { @Override public int compare(Student s1, Student s2) { //主要判断条件,总成绩差值 int num1 = s2.getSum() - s1.getSum(); //次要判断条件1,语文成绩差值 int num2 = num1 == 0 ? s2.getChinese() - s1.getChinese() : num1; //次要判断条件2,姓名差值 int num3 = num2 == 0 ? s2.getName().compareTo(s1.getName()) : num2; return num3; } }); set.add(new Student("张三", 98, 97)); set.add(new Student("李四", 99, 96)); set.add(new Student("王五", 98, 97)); set.add(new Student("赵六", 95, 97)); set.add(new Student("赵六", 95, 97)); for (Student student : set) { System.out.println(student + " ," + student.getSum()); } } }
package com.sinodynamic.hkgta.service.crm.backoffice.admin; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.sinodynamic.hkgta.dao.crm.NotificationOnOffSettingDao; import com.sinodynamic.hkgta.dto.crm.UserPreferenceSettingDto; import com.sinodynamic.hkgta.entity.crm.UserPreferenceSetting; import com.sinodynamic.hkgta.entity.crm.UserPreferenceSettingPK; import com.sinodynamic.hkgta.service.ServiceBase; @Service public class NotificationOnOffServiceImpl extends ServiceBase<UserPreferenceSetting> implements NotificationOnOffService{ @Autowired private NotificationOnOffSettingDao notificationOnOffSettingDao; @Transactional public List<UserPreferenceSettingDto> getNotificationSettings(Long customerId) throws Exception{ return notificationOnOffSettingDao.getNotificationOnOffSetting(customerId); } @Transactional public void updateNotificationSetting(String userId, String paramId, String paramValue) throws Exception{ UserPreferenceSettingPK pk = new UserPreferenceSettingPK(); pk.setParamId(paramId); pk.setUserId(userId); UserPreferenceSetting setting = notificationOnOffSettingDao.get(UserPreferenceSetting.class, pk); if (setting == null){ setting = new UserPreferenceSetting(); setting.setId(pk); setting.setParamValue(paramValue); setting.setUpdateDate(new Date()); notificationOnOffSettingDao.save(setting); } else { setting.setParamValue(paramValue); setting.setUpdateDate(new Date()); notificationOnOffSettingDao.update(setting); } } }
package algo3.fiuba.modelo.cartas.moldes_cartas.cartas_campo; import algo3.fiuba.modelo.cartas.AccionCarta; import algo3.fiuba.modelo.cartas.efectos.EfectoNulo; import algo3.fiuba.modelo.jugador.Jugador; import algo3.fiuba.modelo.cartas.CartaCampo; import algo3.fiuba.modelo.cartas.efectos.EfectoSogen; import java.util.List; public class Sogen extends CartaCampo { public Sogen(Jugador jugador) { super("Sogen", new EfectoNulo()); super.setEfecto(new EfectoSogen(this, jugador)); setJugador(jugador); } }
package dailymanagement.demo.bean; import org.springframework.stereotype.Component; import java.util.Date; import java.util.List; /** * 项目表 * pid:项目ID * pname:项目名 * pRealname:牵头人 * beginTime:创建时间 * closeTime:结项时间 * introduction:项目简介 * */ @Component public class Project { private Integer pid; private String pname; private String pRealname; private Date beginTime; private Date closeTime; private String introduction; private List<Game> game; public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname == null ? null : pname.trim(); } public String getpRealname() { return pRealname; } public void setpRealname(String pRealname) { this.pRealname = pRealname == null ? null : pRealname.trim(); } public Date getBeginTime() { return beginTime; } public void setBeginTime(Date beginTime) { this.beginTime = beginTime; } public Date getCloseTime() { return closeTime; } public void setCloseTime(Date closeTime) { this.closeTime = closeTime; } public String getIntroduction() { return introduction; } public void setIntroduction(String introduction) { this.introduction = introduction == null ? null : introduction.trim(); } public List<Game> getGame() { return game; } public void setGame(List<Game> game) { this.game = game; } @Override public String toString() { return "Project{" + "pid=" + pid + ", pname='" + pname + '\'' + ", pRealname='" + pRealname + '\'' + ", beginTime=" + beginTime + ", closeTime=" + closeTime + ", introduction='" + introduction + '\'' + ", game=" + game + '}'; } }
package selenium.basics.poi; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Properties; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeDriverService; public class SeleniumWithPropertyFile { public static void main(String[] args) { FileReader config = null; FileReader locators = null; Properties configFile = new Properties(); Properties locatorsFile = new Properties(); WebDriver driver = null; try { System.out.println("user.dir" + System.getProperty("user.dir")); config = new FileReader(System.getProperty("user.dir") + "\\src\\selenium\\basics\\poi\\config.properties"); configFile.load(config); locators = new FileReader(System.getProperty("user.dir") + "\\src\\selenium\\basics\\poi\\locators.properties"); locatorsFile.load(locators); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (configFile.get("browser").equals("chrome")) { System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, System.getProperty("user.dir") + "\\drivers\\chromedriver.exe"); driver = new ChromeDriver(); } else { System.out.println(configFile.get("browser") + "is not supported. please try with chrome!"); System.exit(0); } driver.get(configFile.getProperty("url")); WebElement wikiSearch = driver.findElement(By.id(locatorsFile.getProperty("searchInput"))); wikiSearch.sendKeys(locatorsFile.getProperty("searchText")); WebElement searchButton = driver.findElement(By.xpath(locatorsFile.getProperty("searchButton"))); searchButton.click(); if (locatorsFile.getProperty("title").equals(driver.getTitle())) System.out.println(driver.getTitle() + "\nMatched"); else System.out.println("Actual:" + driver.getTitle() + "\nExepcted:" + locatorsFile.getProperty("title") + "\nNot matched"); driver.close(); } }
package com.kh.portfolio.board.svc; import java.util.List; import java.util.Map; import com.kh.portfolio.board.vo.BoardCategoryVO; import com.kh.portfolio.board.vo.BoardFileVO; import com.kh.portfolio.board.vo.BoardVO; import com.kh.portfolio.board.vo.NoticeVO; import com.kh.portfolio.common.PageCriteria; public interface NoticeSVC { //게시글작성 int noticeWrite(NoticeVO notictVO); //게시글수정 int noticeModify(NoticeVO notictVO); //게시글삭제 int noticeDelete(String nnum); //게시글보기 Map<String,Object> noticeView(String nnum); List<NoticeVO> noticeMain(); //게시글목록 //1)전체 List<NoticeVO> noticeList(); //2)검색어 없는 게시글페이징 List<NoticeVO> noticeList( int startRec, int endRec); //3)검색어 있는 게시글검색(요청페이지, 검색유형, 검색어) List<NoticeVO> noticeList( String reqPage, String searchType,String keyword); //페이지 제어 PageCriteria noticeGetPageCriteria(String reqPage, String searchType,String keyword); PageCriteria mainGetPageCriteria(String reqPage, String searchType, String keyword); }
package com.nway.web.common.event; import java.util.Map; public class DbRecordAddEvent extends GenericEvent { private static final long serialVersionUID = 1819246511527898381L; public DbRecordAddEvent(Map<String, String> source) { super(source); } }
package me.libraryaddict.disguise.disguisetypes.watchers; import com.comphenix.protocol.wrappers.BlockPosition; import com.google.common.base.Optional; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; import me.libraryaddict.disguise.disguisetypes.FlagWatcher; /** * @author Navid */ public class EnderCrystalWatcher extends FlagWatcher { public EnderCrystalWatcher(Disguise disguise) { super(disguise); } public void setBeamTarget(BlockPosition position) { setData(MetaIndex.ENDER_CRYSTAL_BEAM, Optional.of(position)); sendData(MetaIndex.ENDER_CRYSTAL_BEAM); } public Optional<BlockPosition> getBeamTarget() { return getData(MetaIndex.ENDER_CRYSTAL_BEAM); } public void setShowBottom(boolean bool) { setData(MetaIndex.ENDER_CRYSTAL_PLATE, bool); sendData(MetaIndex.ENDER_CRYSTAL_PLATE); } public boolean isShowBottom() { return getData(MetaIndex.ENDER_CRYSTAL_PLATE); } }
import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /* * @lc app=leetcode.cn id=56 lang=java * * [56] 合并区间 定于区间: class Interval { int start; int end; }; 区间a、b, 满足a.start <= b.start, if(b.start > a.end){ //b.start > a.end 不存在交集 不能合并 //存储a, 更新start end }else{ //b.start <= a.end 存在交集 可以合并. 合并后区间:[a.start, max(a.end, b.end)] int statr = a.start; int end = max(a.end, b.end) } */ // @lc code=start class Solution { public int[][] merge(int[][] intervals) { if(intervals.length < 2){ return intervals; } //排序,升序 Arrays.sort(intervals, new Comparator<int[]>(){ @Override public int compare(int n1[], int[] n2){ return n1[0]==n2[0] ? n1[1]-n2[1] : n1[0]-n2[0]; } }); List<int[]> resultList = new ArrayList<>(); int start = intervals[0][0]; int end = intervals[0][1]; for (int i = 1; i < intervals.length; i++) { int[] interval = intervals[i]; if(interval[0] > end){ //b.start > a.end 不存在交集 不能合并 resultList.add(new int[]{start, end}); start = interval[0]; end = interval[1]; }else{ //b.start <= a.end 存在交集 可以合并 end = Math.max(end, interval[1]); } } //添加最后一个 resultList.add(new int[]{start, end}); int[][] result = new int[resultList.size()][2]; for(int j=0; j < resultList.size(); j++){ result[j] = resultList.get(j); } return result; } } // @lc code=end
package com.huangg.admin.web.controller.admin.sysmsg; import com.huangg.admin.web.controller.admin.BaseController; import com.huangg.admin.web.entity.SysMsg; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.*; @Controller public class SysMsgController extends BaseController { private final static String BASE_URL="/admin/sysmsg/"; @RequestMapping(value = BASE_URL+"list",method = RequestMethod.GET) public String list(){ return BASE_URL+"list"; } @RequestMapping(value = BASE_URL+"listdata") @ResponseBody public Object listdata(){ int page=0; int size=10; if (size <= 0) { size = 10; } Map out = new HashMap<String, Object>(); List<SysMsg> datas = new ArrayList<>(); SysMsg sysMsg=new SysMsg(); sysMsg.setId(1); sysMsg.setCreate_time(new Date()); sysMsg.setMessage("hello"); sysMsg.setOper_user("huangg"); sysMsg.setOrdernumber(3); sysMsg.setPlatform(1); sysMsg.setStatus(1); sysMsg.setTitle("fffff"); sysMsg.setUpd_time(new Date()); datas.add(sysMsg); int count = 1; out.put("recordsTotal", count); out.put("recordsFiltered", count); out.put("data", datas); return out; } @RequestMapping(value = BASE_URL+"add",method = RequestMethod.GET) public String add(){ return BASE_URL+"add"; } }
package br.assembleia.service; import br.assembleia.entidades.Cargo; import java.util.List; public interface CargoService { void salvar(Cargo cargo) throws IllegalArgumentException; List<Cargo> listarTodos(); void editar(Cargo cargo); void deletar(Cargo cargo); }
package com.bluetooth.tomtom.bluetooth; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import java.util.Set; public class Bluetooth extends AppCompatActivity { private BluetoothAdapter mBluetoothAdapter; public void startBluetoothSession() { // Check for Bluetooth support in the first place. // Emulator doesn't support Bluetooth and will return null. mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { Log.d("Bluetooth Experiment", "\nBluetooth NOT supported. Aborting."); return; } // Check if Bluetooth enable. if (mBluetoothAdapter.disable()) { mBluetoothAdapter.enable(); } } public void endBluetoothSession() { // Check if Bluetooth enable. if (mBluetoothAdapter.enable()) { mBluetoothAdapter.disable(); } } public void startBluetoothDiscovery() { // Starting the device discovery mBluetoothAdapter.startDiscovery(); } public Set<BluetoothDevice> pairedBluetoothDevices() { // Listing paired devices Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices(); //for (BluetoothDevice device : devices) { //Log.d("\nFound device: " + device); //} return devices; } }
import java.lang.*; import java.util.*; import java.io.File; import java.io.FileInputStream; import java.security.MessageDigest; class Remove_Duplicate { Remove_Duplicate(String path)//parameterised constructor { TravelDirectory(path); } public void TravelDirectory(String path)//to travel whole directory { File directorypath=new File(path); String str; //hashtable to store file name and checksum Hashtable<String,String> ht=new Hashtable<String,String>(); //get all file name from directory File arr[]=directorypath.listFiles(); for(File filename:arr) { if(filename.getName().endsWith(".txt")) { str= CheckSum(filename.getAbsolutePath()); ht.put(filename.getName(),str); } } Enumeration it=ht.keys(); while(it.hasMoreElements())//to display hashtable elements { System.out.println(it.nextElement()+""); } } public String CheckSum(String d_name)//to reterive checksum { try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); FileInputStream fileInput = new FileInputStream(d_name); byte[] dataBytes = new byte[1024]; int bytesRead = 0; while ((bytesRead = fileInput.read(dataBytes)) != -1) { messageDigest.update(dataBytes, 0, bytesRead); } byte[] digestBytes = messageDigest.digest(); StringBuffer sb = new StringBuffer(""); for (int i = 0; i < digestBytes.length; i++) { sb.append(Integer.toString((digestBytes[i] & 0xff) + 0x100, 16).substring(1)); } fileInput.close(); return(sb.toString()); } catch(Exception eobj) { System.out.println(eobj); return eobj.toString(); } } } class Demo { public static void main(String args[]) { Remove_Duplicate dobj=new Remove_Duplicate("Demo"); } }
import java.util.*; import java.lang.Iterable; public class PlayGame { //Use ArrayList to record the handcards for each player ArrayList<Integer> P0 = new ArrayList<Integer>(); ArrayList<Integer>P1 = new ArrayList<Integer>(); ArrayList<Integer> P2 = new ArrayList<Integer>(); ArrayList<Integer> P3 = new ArrayList<Integer>(); //Database for All cards String[] card = {"","R0","B0","C2","D2","H2","S2","C3","D3","H3","S3","C4","D4","H4","S4","C5","D5","H5","S5", "C6","D6","H6","S6","C7","D7","H7","S7","C8","D8","H8","S8","C9","D9","H9","S9","C10","D10","H10", "S10","CJ","DJ","HJ","SJ","CQ","DQ","HQ","SQ","CK","DK","HK","SK","CA","DA","HA","SA"}; //Start the game public static void main(String[] args){ PlayGame dc = new PlayGame(); //Variables t0~t03 to record the # of card that each player have int t0=0; int t1=0; int t2=0; int t3=0; int i=1; //The ith card to be given int x=0; //Decide which player receive the card //Deal Card to 4 players while(i<55) { x=(int)((Math.random())*4); switch(x) { //Use "if" to make sure the # of hand-card will be 14,14,13,13 for Player 0 to 3 case 0: if(t0<14) { dc.P0.add(i); t0++; i++;} break; case 1: if(t1<14) {dc.P1.add(i); t1++; i++;} break; case 2: if(t2<13) {dc.P2.add(i); t2++; i++;} break; case 3: if(t3<13) {dc.P3.add(i); t3++; i++;} break; default: //If someone who have already got his maximum # of card get another new card this turn, this turn will be skipped continue; } } //Deal Cards output System.out.println("Deal Cards:"); dc.outputP0(); dc.outputP1(); dc.outputP2(); dc.outputP3(); //Drop Cards process System.out.println("Drop Cards:"); dc.dropcard0(); dc.dropcard1(); dc.dropcard2(); dc.dropcard3(); //Output the result after dropping card dc.outputP0(); dc.outputP1(); dc.outputP2(); dc.outputP3(); System.out.println("Game Start"); dc.checkwinner(); //Check whether Player0 or Player1 win before drawing a card //Process of drawing cards (the process of the game) while(dc.P0.size()!=0||dc.P1.size()!=0||dc.P2.size()!=0||dc.P3.size()!=0) //Continue next round if no one wins { //Player0 draw a card from Player1 System.out.println("Player0 draws a card from Player1."); int D0 = (int)(Math.random()*(dc.P1.size())); //Decide which card will be drawn dc.P0.add(dc.P1.get(D0)); //Add the card into P0's hand-card dc.P1.remove(D0); //Remove the card from P1's hand-card Collections.sort(dc.P0); //Sort the hand-card of P0 dc.dropcard0(); //Drop cards from P1's hand-card if a pair form dc.outputP0(); dc.outputP1(); dc.checkwinner(); //Check if anyone wins after this process //Player1 draw a card from Player2 System.out.println("Player1 draws a card from Player2."); int D1 = (int)(Math.random()*(dc.P2.size())); dc.P1.add(dc.P2.get(D1)); dc.P2.remove(D1); Collections.sort(dc.P1); dc.dropcard1(); dc.outputP1(); dc.outputP2(); dc.checkwinner(); //Player2 draw a card from Player3 System.out.println("Player2 draws a card from Player3."); int D2 = (int)(Math.random()*(dc.P3.size())); dc.P2.add(dc.P3.get(D2)); dc.P3.remove(D2); Collections.sort(dc.P2); dc.dropcard2(); dc.outputP2(); dc.outputP3(); dc.checkwinner(); //Player3 draw a card from Player0 System.out.println("Player3 draws a card from Player0."); int D3 = (int)(Math.random()*(dc.P0.size())); dc.P3.add(dc.P0.get(D3)); dc.P0.remove(D3); Collections.sort(dc.P3); dc.dropcard3(); dc.outputP3(); dc.outputP0(); dc.checkwinner(); // the program finished } } //Output P0's hand-card void outputP0() { System.out.printf("Player0: "); for(int i=0;i<P0.size();i++) System.out.print((card[(int)(P0.get(i))]+" ")); System.out.println(); } //Output P1's hand-card void outputP1() { System.out.printf("Player1: "); for(int i=0;i<P1.size();i++) System.out.print((card[(int)(P1.get(i))]+" ")); System.out.println(); } //Output P2's hand-card void outputP2() { System.out.printf("Player2: "); for(int i=0;i<P2.size();i++) System.out.print((card[(int)(P2.get(i))]+" ")); System.out.println(); } //Output P3's hand-card void outputP3() { System.out.printf("Player3: "); for(int i=0;i<P3.size();i++) System.out.print((card[(int)(P3.get(i))]+" ")); System.out.println(); } //P0 drop card void dropcard0() { for (int i=0;i<P0.size()-1;i++) { if(P0.get(i)==1||P0.get(i)==2) continue; else if((((P0.get(i))-3)/4)==(((P0.get(i+1))-3)/4)) {P0.remove(i); P0.remove(i); i--;} } } //P1 drop card void dropcard1() { for (int i=0;i<P1.size()-1;i++) { if(P1.get(i)==1||P1.get(i)==2) continue; else if((((P1.get(i))-3)/4)==(((P1.get(i+1))-3)/4)) {P1.remove(i); P1.remove(i); i--;} } } //P2 drop card void dropcard2() { for (int i=0;i<P2.size()-1;i++) { if(P2.get(i)==1||P2.get(i)==2) continue; else if((((P2.get(i))-3)/4)==(((P2.get(i+1))-3)/4)) {P2.remove(i); P2.remove(i); i--;} } } //P3 drop card void dropcard3() { for (int i=0;i<P3.size()-1;i++) { if(P3.get(i)==1||P3.get(i)==2) continue; else if((((P3.get(i))-3)/4)==(((P3.get(i+1))-3)/4)) {P3.remove(i); P3.remove(i); i--;} } } //Check if anyone wins the game void checkwinner() { int win0=0; int win1=0; int win2=0; int win3=0; if(P0.size()==0) win0=1; if(P1.size()==0) win1=1; if(P2.size()==0) win2=1; if(P3.size()==0) win3=1; int winner=win0+win1+win2+win3; if(winner==2) //If there are 2 winners { if(win0==1 && win1==1) System.out.println("Player0 and Player1 win"); if(win0==1 && win2==1) System.out.println("Player0 and Player2 win"); if(win0==1 && win3==1) System.out.println("Player0 and Player3 win"); if(win1==1 && win2==1) System.out.println("Player1 and Player2 win"); if(win1==1 && win3==1) System.out.println("Player1 and Player3 win"); if(win2==1 && win3==1) System.out.println("Player2 and Player3 win"); System.out.println("Basic game over"); } else if(winner==1) //If only 1 winner { if(P0.size()==0) { System.out.println("Player0 wins"); System.out.println("Basic game over"); System.exit(0);} else if(P1.size()==0) { System.out.println("Player1 wins"); System.out.println("Basic game over"); System.exit(0);} else if(P2.size()==0) { System.out.println("Player2 wins"); System.out.println("Basic game over"); System.exit(0);} else if(P3.size()==0) { System.out.println("Player3 wins"); System.out.println("Basic game over"); System.exit(0);} } } }
package uk.co.mtford.jalp; import org.junit.After; import org.junit.Before; import org.junit.Test; import uk.co.mtford.jalp.abduction.Result; import uk.co.mtford.jalp.abduction.logic.instance.IInferableInstance; import uk.co.mtford.jalp.abduction.logic.instance.PredicateInstance; import uk.co.mtford.jalp.abduction.logic.instance.term.CharConstantInstance; import uk.co.mtford.jalp.abduction.logic.instance.term.VariableInstance; import uk.co.mtford.jalp.abduction.parse.program.ParseException; import uk.co.mtford.jalp.abduction.tools.UniqueIdGenerator; import java.io.FileNotFoundException; import java.util.LinkedList; import java.util.List; import static org.junit.Assert.assertTrue; /** * Created with IntelliJ IDEA. * User: mtford * Date: 02/06/2012 * Time: 07:59 * To change this template use File | Settings | File Templates. */ public class DefinitionTest { JALPSystem system; public DefinitionTest() { } @Before public void noSetup() { } @After public void noTearDown() { } /* boy(john). girl(jane). girl(mary). likes(X,Y) :- boy(X),girl(Y). Q = likes(john,Y) We expect two results, Y/jane or Y/mary */ @Test public void definitionTest1() throws InterruptedException, ParseException, JALPException, uk.co.mtford.jalp.abduction.parse.query.ParseException, FileNotFoundException { UniqueIdGenerator.reset(); system = new JALPSystem("examples/basic/definition/definition.alp"); List<IInferableInstance> query = new LinkedList<IInferableInstance>(); VariableInstance Y = new VariableInstance("Y"); PredicateInstance likes = new PredicateInstance("likes",new CharConstantInstance("john"),Y); query.add(likes); List<Result> result = system.query(query); for (Result r:result) { r.reduce(likes.getVariables()); } assertTrue(result.size()==2); assertTrue(result.get(0).getAssignments().get(Y).equals(new CharConstantInstance("mary"))); assertTrue(result.get(1).getAssignments().get(Y).equals(new CharConstantInstance("jane"))); } }
package com.micHon.officer; public enum OfficerRank { SERGANT, CAPTAIN, GENERAL }
/* class greater { public static void main(String ar[]) { int a=10,b=15,c=5; if(a>b) { System.out.print("a is greater"); } else if(b>c) { System.out.print("b is greater"); } else { System.out.print("c is greater"); } } } */ /* class greater { public static void main(String ar[]) { int a=10,b=15,c=5; if(a>b&& a>c) { System.out.print("a is greater"); } if(b>a&& b>c) { System.out.print("b is greater"); } if(c>a&& c>b) { System.out.print("c is greater"); } } } */ /* class greater { public static void main(String ar[]) { int a=20,b=15,c=5,max=a; if(b>max) { max=b; } if(c>max) { max=c; } System.out.print(max); } } */ /* class greater { public static void main(String ar[]) { int a=10,b=15,c=5,max; if(a>b) { if(a>c) max=a; else max=c; } else { if(b>c) max=b; else max=c; } System.out.print(max); } } */
package web; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class Webserver1 { public static void main(String[] args)throws Exception { ServerSocket serverSocket = new ServerSocket(7777); System.out.println("Ready Server"); while(true) { Socket socket = serverSocket.accept(); System.out.println(socket.getInetAddress()); Scanner inScanner = new Scanner(socket.getInputStream()); OutputStream out = socket.getOutputStream(); File file = new File("c:\\zzz\\img\\face12.jpg"); out.write(new String("HTTP/1.1 200 OK\r\n").getBytes()); out.write(new String("Cache-Control: private\r\n").getBytes()); out.write(new String("Content-Length: "+file.length()+"\r\n").getBytes()); out.write(new String("Content-Type: image/jpeg; charset=UTF-8\r\n\r\n").getBytes()); FileInputStream fin = new FileInputStream(file); byte[] buffer = new byte[1024*8]; while(true) { int count = fin.read(buffer); if(count == -1){ break;} out.write(buffer,0,count); } out.flush(); // out.close(); // socket.close(); } } }
package com.learn.diagrammultithreading.immutable; import lombok.AllArgsConstructor; @AllArgsConstructor public class PrintPersonThread extends Thread { private final Person person; @Override public void run(){ while(true){ try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(this.getName()+" prints "+person); } } }
package mx.com.otss.saec.request; import android.util.Log; import com.android.volley.Response; import com.android.volley.toolbox.StringRequest; import java.util.HashMap; import java.util.Map; public class ListadoAdeudosRequest extends StringRequest{ private static final String LISTADO_ADEUDO_REQUEST_URL = "http://192.168.1.90/proyecto/selects/Adeudo.php"; private Map<String, String> params; public ListadoAdeudosRequest(String idusuario, Response.Listener<String> listener) throws SecurityException{ super(Method.POST, LISTADO_ADEUDO_REQUEST_URL, listener, null); params = new HashMap<>(); params.put("campus", idusuario); Log.i("Info: ", "" + params); Log.i("url", ""+ LISTADO_ADEUDO_REQUEST_URL); } @Override public Map<String, String> getParams() { return params; } }
package com.arthur.leetcode; import java.util.Deque; import java.util.LinkedList; /** * @title: No1004 * @Author ArthurJi * @Date: 2021/2/19 0:01 * @Version 1.0 */ public class No1004 { public static void main(String[] args) { System.out.println(new No1004().longestOnes2(new int[]{0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1}, 3)); } public int longestOnes(int[] A, int K) { // 自己写的,,,,错误解答 int len = 0; int temp = 0; int before = 0; Deque<Integer> deque = new LinkedList<>(); for (int i = 0; i < A.length; i++) { if(A[i] == 1) { temp++; } else if(A[i] == 0 && K != 0) { temp++; K--; deque.add(i); } else if(A[i] == 0 && K == 0) { temp -= (deque.peek() - before); before = deque.removeFirst(); deque.add(i); } len = Math.max(len, temp); } return len; } public int longestOnes1(int[] A, int K) { //滑动窗口 int left = 0; int right = 0; int length = A.length; int res = 0; while(right < length) { if(A[right] == 0) { K--; } if(K < 0) { while(A[left++] != 0); //这里挺关键 K++; } res = Math.max(res, right - left + 1); right++; } return res; } public int longestOnes2(int[] A, int K) { //滑动窗口 int left = 0; int res = 0; for (int i = 0; i < A.length; i++) { if(A[i] == 0) { K--; } if(K < 0) { while(A[left++] != 0); K++; } res = Math.max(res, i - left + 1); } return res; } } /* 1004. 最大连续1的个数 III 给定一个由若干 0 和 1 组成的数组 A,我们最多可以将 K 个值从 0 变成 1 。 返回仅包含 1 的最长(连续)子数组的长度。 示例 1: 输入:A = [1,1,1,0,0,0,1,1,1,1,0], K = 2 输出:6 解释: [1,1,1,0,0,1,1,1,1,1,1] 粗体数字从 0 翻转到 1,最长的子数组长度为 6。 示例 2: 输入:A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3 输出:10 解释: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1] 粗体数字从 0 翻转到 1,最长的子数组长度为 10。 解题思路 重点:题意转换。把「最多可以把 K 个 0 变成 1,求仅包含 1 的最长子数组的长度」转换为 「找出一个最长的子数组,该子数组内最多允许有 K 个 0 」。 经过上面的题意转换,我们可知本题是求最大连续子区间,可以使用滑动窗口方法。滑动窗口的限制条件是:窗口内最多有 K 个 0。 可以使用我多次分享的滑动窗口模板解决,模板在代码之后。 代码思路: 使用 leftleft 和 rightright 两个指针,分别指向滑动窗口的左右边界。 rightright 主动右移:rightright 指针每次移动一步。当 A[right]A[right] 为 00,说明滑动窗口内增加了一个 00; leftleft 被动右移:判断此时窗口内 00 的个数,如果超过了 KK,则 leftleft 指针被迫右移,直至窗口内的 00 的个数小于等于 KK 为止。 滑动窗口长度的最大值就是所求。 示例 以 A= [1,1,1,0,0,0,1,1,1,1,0], K = 2 为例,下面的动图演示了滑动窗口的两个指针的移动情况。 该动图对应的 PPT 在下面,可以点击逐步观看: 1 / 22 代码 提供 Python, C++, Java 三种代码可供阅读。 class Solution { public int longestOnes(int[] A, int K) { int N = A.length; int res = 0; int left = 0, right = 0; int zeros = 0; while (right < N) { if (A[right] == 0) zeros ++; while (zeros > K) { if (A[left++] == 0) zeros --; } res = Math.max(res, right - left + 1); right ++; } return res; } } 时间复杂度:O(N)O(N),因为每个元素只遍历了一次。 空间复杂度:O(1)O(1),因为使用了常数个空间。 分享滑动窗口模板 《挑战程序设计竞赛》这本书中把滑动窗口叫做「虫取法」,我觉得非常生动形象。因为滑动窗口的两个指针移动的过程和虫子爬动的过程非常像:前脚不动,把后脚移动过来;后脚不动,把前脚向前移动。 我分享一个滑动窗口的模板,能解决大多数的滑动窗口问题: def findSubArray(nums): N = len(nums) # 数组/字符串长度 left, right = 0, 0 # 双指针,表示当前遍历的区间[left, right],闭区间 sums = 0 # 用于统计 子数组/子区间 是否有效,根据题目可能会改成求和/计数 res = 0 # 保存最大的满足题目要求的 子数组/子串 长度 while right < N: # 当右边的指针没有搜索到 数组/字符串 的结尾 sums += nums[right] # 增加当前右边指针的数字/字符的求和/计数 while 区间[left, right]不符合题意:# 此时需要一直移动左指针,直至找到一个符合题意的区间 sums -= nums[left] # 移动左指针前需要从counter中减少left位置字符的求和/计数 left += 1 # 真正的移动左指针,注意不能跟上面一行代码写反 # 到 while 结束时,我们找到了一个符合题意要求的 子数组/子串 res = max(res, right - left + 1) # 需要更新结果 right += 1 # 移动右指针,去探索新的区间 return res 滑动窗口中用到了左右两个指针,它们移动的思路是:以右指针作为驱动,拖着左指针向前走。右指针每次只移动一步,而左指针在内部 while 循环中每次可能移动多步。右指针是主动前移,探索未知的新区域;左指针是被迫移动,负责寻找满足题意的区间。 模板的整体思想是: 定义两个指针 left 和 right 分别指向区间的开头和结尾,注意是闭区间;定义 sums 用来统计该区间内的各个字符出现次数; 第一重 while 循环是为了判断 right 指针的位置是否超出了数组边界;当 right 每次到了新位置,需要增加 right 指针的求和/计数; 第二重 while 循环是让 left 指针向右移动到 [left, right] 区间符合题意的位置;当 left 每次移动到了新位置,需要减少 left 指针的求和/计数; 在第二重 while 循环之后,成功找到了一个符合题意的 [left, right] 区间,题目要求最大的区间长度,因此更新 res 为 max(res, 当前区间的长度) 。 right 指针每次向右移动一步,开始探索新的区间。 模板中的 sums 需要根据题目意思具体去修改,本题是求和题目因此把sums 定义成整数用于求和;如果是计数题目,就需要改成字典用于计数。当左右指针发生变化的时候,都需要更新 sums 。 另外一个需要根据题目去修改的是内层 while 循环的判断条件,即: 区间 [left, right][left,right] 不符合题意 。对于本题而言,就是该区间内的 0 的个数 超过了 2 。 作者:fuxuemingzhu 链接:https://leetcode-cn.com/problems/max-consecutive-ones-iii/solution/fen-xiang-hua-dong-chuang-kou-mo-ban-mia-f76z/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/
package com.xwolf.eop.erp.entity; import com.alibaba.fastjson.annotation.JSONField; import lombok.Data; import java.util.Date; @Data public class Employees { private Integer eid; private String ecode; private String dcode; private String jcode; private String eno; private String ename; private String ecardno; private Date birth; private String mobile; private String email; private String blog; private String qq; private String weixin; private String otherSocial; @JSONField(format = "yyyy-MM-dd") private Date inDate; @JSONField(format = "yyyy-MM-dd") private Date leaveDate; private String dealInCode; private String dealLeaveCode; private Byte state; }
package com.moonlike.hl.account.activity; import android.app.Activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.moonlike.hl.account.R; import com.moonlike.hl.account.dao.InaccountDAO; import com.moonlike.hl.account.domain.Tb_inaccount; import java.util.Calendar; public class IncomeActivity extends Activity { protected static final int DATE_DIALOG_ID = 0; private EditText et_money, et_handler, et_mark; private TextView tv_time; private Spinner spinner; private Button btn_ok, btn_cancel; private int mYear, mMonth, mDay; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.income_account); initView(); tv_time.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //TODO showDialog(DATE_DIALOG_ID); } }); final Calendar c = Calendar.getInstance(); mYear = c.get(Calendar.YEAR); mMonth = c.get(Calendar.MONTH)+1; mDay = c.get(Calendar.DAY_OF_MONTH); updateDisplay(); btn_cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { et_money.setText(""); et_handler.setText(""); et_mark.setText(""); spinner.setSelection(0); } }); btn_ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String money = et_money.getText().toString().trim(); if (money.equals("")) return ; if (!money.equals("")) { InaccountDAO dao = new InaccountDAO(IncomeActivity.this); Tb_inaccount tb_inaccount = new Tb_inaccount(dao.getMaxId() + 1, Double .parseDouble(money), tv_time.getText().toString().trim(), spinner .getSelectedItem().toString(), et_handler.getText().toString().trim() , et_mark.getText().toString().trim()); dao.add(tb_inaccount); Toast.makeText(IncomeActivity.this,"保存成功",Toast.LENGTH_SHORT).show(); et_money.setText(""); }else Toast.makeText(IncomeActivity.this,"保存失败",Toast.LENGTH_LONG).show(); } }); } private void updateDisplay() { tv_time.setText(new StringBuilder().append(mYear).append("-").append(mMonth).append("-") .append(mDay)); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DATE_DIALOG_ID: return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay); } return null; } private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog .OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mYear = year; mMonth = monthOfYear; mDay = dayOfMonth; updateDisplay(); } }; private void initView() { et_money = (EditText) findViewById(R.id.et_income_money); et_handler = (EditText) findViewById(R.id.et_income_handler); et_mark = (EditText) findViewById(R.id.et_income_mark); tv_time = (TextView) findViewById(R.id.tv_income_time); spinner = (Spinner) findViewById(R.id.spinner_income); btn_ok = (Button) findViewById(R.id.bt_income_ok); btn_cancel = (Button) findViewById(R.id.bt_income_cancel); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_income, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package com.xpecya.xds; import java.util.Iterator; import java.util.Objects; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.Consumer; abstract class AbstractGraph<T> implements Graph<T> { /** * 转换一个图的底层结构 * @param anotherGraph 另一个图 */ AbstractGraph(Graph<T> anotherGraph) {} /** * 不含任何参数的构造函数 */ AbstractGraph() {} @Override public Spliterator<Edge<T>> edgeSpliterator() { return Spliterators.spliteratorUnknownSize(this.edgeIterator(), 0); } @Override public void forEachEdge(Consumer<? super Edge<T>> edgeConsumer) { Objects.requireNonNull(edgeConsumer); Iterator<Edge<T>> iterator = this.edgeIterator(); while(iterator.hasNext()) { Edge<T> edge = iterator.next(); edgeConsumer.accept(edge); } } /** * Edge的默认实现 * 子类可以根据实际情况自己另外实现 */ class DefaultEdge implements Graph.Edge<T> { private T start; private T end; DefaultEdge(T start, T end) { this.start = start; this.end = end; } @Override public T start() { return start; } @Override public T end() { return end; } } }
package exercicio02; public class CalculadoraImaginaria { public static int resultado, resultado2, resu; public static void calculandonaMoral(int operador, int x, int y, int x2, int y2) { if(operador==0) { resultado=x+x2; resultado2= y +y2; System.out.println("O resultado da soma e:" + resultado+ "+" + resultado2 + "i"); } else if(operador==1) { resultado=x-x2; resultado2= y-y2; System.out.println("O resultado da subtração e:" + resultado+ "-" + resultado2); } else if(operador==2) { resultado=((x*x2)+(y*y2)); resultado2= ((x*x2)+(y*y2)); System.out.println("O resultado da multiplicação e:" + resultado+ "*" + resultado2); } else if(operador==3) { resu=((x*x2)+(y*-y2)); resultado=((x*-y)+(y*x2)); resultado2=((x2*x2)-(y2*y2)); if(resultado < 0) { System.out.println("O resultado da divisao e:" + resu+ "/" + resultado+ " - " +resultado2+ "i"); } else { System.out.println("O resultado da divisao e:" + resu+ "/" + resultado+ " + " +resultado2+ "i"); } } } }
package com.tirtle.security; import javax.servlet.http.HttpServletRequest; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.tirtle.model.RegisteredUser; import com.tirtle.model.RegisteredUserManager; /** * Provides helper functions to deal with GAE user accounts. * * @todo Should be using Spring Security, but I'm too lazy to set it up. */ @Component public class GaeUserAuthenticator { private static final String SIGN_UP_URL = "/login/"; @Autowired private RegisteredUserManager registeredUserManager; /** * Return current GAE user. * * @return User */ public User getUser() { UserService userService = UserServiceFactory.getUserService(); return userService.getCurrentUser(); } /** * Return current RegisteredUser. * * @return RegisteredUser */ public RegisteredUser getRegisteredUser() { User user = getUser(); if (user == null) { return null; } return registeredUserManager.getFromGaeUser(user); } /** * Return url to redirect user to signup page. * * @return String */ public String getRegistrationUrl() { return SIGN_UP_URL; } /** * Return url to redirect user to login page. * * @param request HttpServletRequest * @return String */ public String getLoginUrl(HttpServletRequest request) { UserService userService = UserServiceFactory.getUserService(); String url = request.getRequestURI(); String query = request.getQueryString(); if (query != null) { url += '?' + query; } return userService.createLoginURL(url); } }
package com.election.server; import java.rmi.*; import java.rmi.server.UnicastRemoteObject; import com.rmi.middleware.*; import com.rmi.server.*; import com.rmi.client.*; /** * VoteListServant. * * @class VoteServant * @param String candidateId the version of the candidate id. * @param Vector<Vote> voteList the candidate vote list. */ @SpringBootApplication @ComponentScan("com.election") public class VoteListServant extends UnicastRemoteObject implements Vote { /* javalint-disable-next-line PrivateFieldCouldBeFinal */ private Vector<Vote> voteList; public VoteListServant() throws RemoteException { voteList = new Vector<Vote>(); } public Vote newVote(Vote v) throws RemoteException { Vote s = new VoteServant(getId, candidateId); voteList.addElement(s); return s; } public Vector<Vote> allVotes() throws RemoteException { return voteList; } }
package com.cy.bean.bus; import java.io.Serializable; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; /** * 公交站 * @author CY * */ @Entity public class Station implements Serializable { private static final long serialVersionUID = -435108012105793594L; /** * id */ @Id @GeneratedValue private Integer id; /** * 公交站名称 */ @Column(length=20,nullable=false,unique=true) private String name; /** * 经过该公交站的公交路线 */ @OneToMany(cascade=CascadeType.ALL,mappedBy="station") private Set<Line_Station> line_Stations; public Station() { } public Station(String name) { this.name = name; } public Station(Integer id) { this.id = id; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Line_Station> getLine_Stations() { return line_Stations; } public void setLine_Stations(Set<Line_Station> line_Stations) { this.line_Stations = line_Stations; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Station other = (Station) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
/* * Created on Mar 14, 2007 * */ package com.citibank.ods.modules.product.prodriskcatprvt.form; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import com.citibank.ods.common.util.ODSValidator; import com.citibank.ods.entity.pl.TplProdRiskCatPrvtMovEntity; import com.citibank.ods.modules.product.prodriskcatprvt.functionality.valueobject.ProdRiskCatPrvtMovementListFncVO; /** * @author leonardo.nakada * */ public class ProdRiskCatPrvtMovementListForm extends BaseProdRiskCatPrvtListForm { //Nome do Usuário private String m_lastUpdUserIdSrc = ""; /** * @return Returns the lastUpdUserIdSrc. */ public String getLastUpdUserIdSrc() { return m_lastUpdUserIdSrc; } /** * @param updUserIdSrc The lastUpdUserIdSrc to set. */ public void setLastUpdUserIdSrc( String updUserIdSrc ) { m_lastUpdUserIdSrc = updUserIdSrc; } /* * Realiza validação de tamanho de campo */ public ActionErrors validate( ActionMapping actionMapping_, HttpServletRequest request_ ) { ActionErrors errors = new ActionErrors(); errors = super.validate( actionMapping_, request_ ); ODSValidator.validateMaxLength( ProdRiskCatPrvtMovementListFncVO.C_LAST_UPD_USER_ID_DESCRIPTION, m_lastUpdUserIdSrc, TplProdRiskCatPrvtMovEntity.C_LAST_UPD_USER_ID_SIZE, errors ); return errors; } }
package com.sky.design.state; public class EveningState extends State { @Override public void WriterProgram(Work work) { if(work.getTaskFinished()){ work.setState(new RestState()); work.WriterProgram(); } else{ if(work.getHour()<21){ System.out.println("当前时间:"+work.getHour()+"点,加班哦,疲惫至极。"); } else{ work.setState(new SleepingState()); work.WriterProgram(); } } } }
package com.pan.al.test.outerinterclass; //匿名内部类 public class Outer1 { public static String s1 = "this is s1 in Outer"; public static String s2 = "this is s2 in Outer"; private static String s3 = "this is s3 in Outer"; public String s4="this is s4 in outer"; public void method1(Inner inner) { System.out.println(inner.say()); } private static String method2() { return "this is method2 in Outer"; } /** * 1.匿名内部类只能被使用一次,创建匿名内部类时它会立即创建一个该类的实例,该类的定义也就立即消失。 * 2.使用匿名内部类的时候必须实现接口或者继承一个类(有且只有一个) * 3.匿名内部类因为没有类名,可知匿名内部类不能定义构造器 * 4.匿名内部类不存在任何的静态变量和方法的 * 5.当匿名内部类和外部类有同名变量(方法)时,默认访问的是匿名内部类的变量(方法),要访问外部类的变量(方法)则需要加上外部类的类名 * 6.内部类可以访问外部类私有变量和方法。 * @param args */ public static void main(String[] args) { Outer1 outer = new Outer1(); // 测试1,Inner为接口 outer.method1(new Inner() { String s1 = "this is s1 in Inner"; public String say() { // 外部类和匿名内部类中有同名变量s1,使用匿名内部类自己的 // System.out.println(outer.s4); return s1; } }); // 测试2,Inner1为抽象类 outer.method1(new Inner1() { String s2 = "this is s2 in Inner1"; public String say() { // 匿名内部类中有同名变量s2,使用外部类的同名的,要用类名.变量 return Outer1.s2; } }); // 测试3,Inner2为普通类 outer.method1(new Inner2() { public String say() { // 访问外部类私有变量s3 return s3; } }); // 测试4,Inner2为普通类 outer.method1(new Inner2() { public String say() { // 访问外部类私有方法method1() return method2(); } }); } }
package cn.ablocker.FoodBlog.response; public class UserNameResponse extends BaseResponse { private String userName; // 用户名 public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }
package web; public class GlobalConfig { public static final int recordsPerPage = 10; public enum Protocol { SMTP, SMTPS, TLS } public static int port = 465; public static String host = "smtp.gmail.com"; public static String from = "gestiondons2020@gmail.com"; public static boolean auth = true; public static boolean secureConnection = true; public static String username = "gestiondons2020@gmail.com"; public static String password = "gestiondons123$"; public static GlobalConfig.Protocol protocol = Protocol.SMTPS; // private boolean debug = true; }
package org.dajlab.mondialrelayapi.soap; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p> * Classe Java pour anonymous complex type. * * <p> * Le fragment de schéma suivant indique le contenu attendu figurant dans cette * classe. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="WSI2_RechercheCPResult" type="{http://www.mondialrelay.fr/webservice/}ret_WSI2_RechercheCP" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "wsi2RechercheCPResult" }) @XmlRootElement(name = "WSI2_RechercheCPResponse") public class WSI2RechercheCPResponse { @XmlElement(name = "WSI2_RechercheCPResult") protected RetWSI2RechercheCP wsi2RechercheCPResult; /** * Obtient la valeur de la propriété wsi2RechercheCPResult. * * @return possible object is {@link RetWSI2RechercheCP } * */ public RetWSI2RechercheCP getWSI2RechercheCPResult() { return wsi2RechercheCPResult; } /** * Définit la valeur de la propriété wsi2RechercheCPResult. * * @param value * allowed object is {@link RetWSI2RechercheCP } * */ public void setWSI2RechercheCPResult(RetWSI2RechercheCP value) { this.wsi2RechercheCPResult = value; } }
package de.haw.wpcgar.structure.biomes; import de.haw.wpcgar.generator.WorldGenerator; import de.haw.wpcgar.structure.Biome; import de.haw.wpcgar.structure.params.HeightMap; import de.haw.wpcgar.structure.params.Temperature; import edu.hawhamburg.shared.math.Vector; /** * Forest biome. * @author Adrian Helberg * * The forest growth is determined by the parameters height and temperature. * The greater the value of the height, the more likely the mixing ratio * of deciduous to coniferous forest is in the direction of coniferous forest. * The greater the value of the temperature, the denser the forest */ public class Forest extends Biome { public Forest(WorldGenerator generator) { super(generator, new Vector(0, 0.5, 0, "forest")); } @Override public boolean check(double x, double y) { double height = getValue(HeightMap.class, x, y); double temperature = getValue(Temperature.class, x, y); return height > 0.1 && height < 0.75 && temperature > 35 && temperature < 50; } @Override public Vector getColor() { return color; } }
package scut218.pisces.beans; import java.sql.Date; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import scut218.pisces.Constants; import scut218.pisces.base.MyApplication; import scut218.pisces.utils.UserUtil; /** * Created by Lenovo on 2018/3/14. * 用户类,有基本信息 */ public class User { private String id; private String password; private String nickname; private String phone; private String gender; private java.sql.Date birthday; private String photoPath; private String whatsup; private String school; private int grade; public static User me; public static HashMap<String,User> userMap=new HashMap<>();//附近的人和好友都放在里面 public static List<Friend> friendList=new ArrayList<>();//好友id列表 public static List<String> nearbyIdList=new ArrayList<>();//附近的人id列表 public User() { this.id=""; this.password=""; this.nickname=""; this.phone=""; this.gender=""; this.photoPath= MyApplication.getContext().getFilesDir().getPath()+"/default.jpg"; this.whatsup=""; this.school=""; this.birthday=new java.sql.Date(new java.util.Date().getTime()); this.grade=0; } public User(String id,String password,String nickname,String phone,String gender,String photoPath, String whatsup,String school,Date birthday,int grade) { this.id=id; this.password=password; this.nickname=nickname; this.phone=phone; this.gender=gender; this.photoPath=photoPath; this.whatsup=whatsup; this.school=school; this.birthday=birthday; this.grade=grade; } public Date getBirthday() { return birthday; } public int getGrade() { return grade; } public String getGender() { return gender; } public String getId() { return id; } public String getNickname() { return nickname; } public String getPassword() { return password; } public String getPhone() { return phone; } public String getPhotoPath() { return photoPath; } public String getSchool() { return school; } public String getWhatsup() { return whatsup; } public void setBirthday(Date birthday) { this.birthday = birthday; } public void setGender(String gender) { this.gender = gender; } public void setId(String id) { this.id = id; } public void setGrade(int grade) { this.grade = grade; } public void setNickname(String nickname) { this.nickname = nickname; } public void setPassword(String password) { this.password = password; } public void setPhone(String phone) { this.phone = phone; } public void setPhotoPath(String photoPath) { this.photoPath = photoPath; } public void setSchool(String school) { this.school = school; } public void setWhatsup(String whatsup) { this.whatsup = whatsup; } }
package xtrus.ex.mci.inbound; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.framework.FrameworkSystemVariables; import com.esum.framework.core.component.listener.DummyListener; import com.esum.framework.core.component.table.InfoTableManager; import com.esum.framework.core.exception.SystemException; import xtrus.ex.mci.ExMciCode; import xtrus.ex.mci.ExMciConfig; import xtrus.ex.mci.ExMciException; import xtrus.ex.mci.server.MciServer; import xtrus.ex.mci.table.ExMciServerInfoRecord; import xtrus.ex.mci.table.ExMciServerInfoTable; /** * Expressway MCI Server¸¦ start/stopÇÑ´Ù. */ public class ExMciServerListener extends DummyListener { private static Logger log = LoggerFactory.getLogger(ExMciServerListener.class); private String nodeId; private Map<String, MciServer> mciServers; public ExMciServerListener() throws SystemException { this.nodeId = System.getProperty(FrameworkSystemVariables.NODE_ID); this.mciServers = new HashMap<String, MciServer>(); } public void startup() throws SystemException { this.traceId = "[" + getComponentId() + "][" + nodeId + "] "; log.info(traceId+"MCI server starting. nodeId : "+nodeId); ExMciServerInfoTable serverInfo = InfoTableManager.getInstance().getInfoTable(ExMciConfig.MCI_SERVER_INFO_TABLE_ID); List<ExMciServerInfoRecord> infoRecords = serverInfo.getMciServerInfos(nodeId); if(infoRecords!=null && infoRecords.size()>0) { for(ExMciServerInfoRecord infoRecord : infoRecords) { MciServer mciServer = new MciServer(traceId, infoRecord); try { mciServer.startup(); } catch (Exception e) { throw new ExMciException(ExMciCode.ERROR_SERVER_START, "startup()", e.getMessage(), e); } mciServers.put(infoRecord.getInterfaceId(), mciServer); log.info(traceId + "New MCI Server started. listen port : "+infoRecord.getServerPort()+", file listen port : "+infoRecord.getServerFilePort()); } } else { log.info(traceId+"MCI Server information is not exists."); } } public void shutdown() throws SystemException { if(this.mciServers==null || this.mciServers.size()==0) return; Iterator<String> i = mciServers.keySet().iterator(); while(i.hasNext()) { MciServer mciServer = mciServers.get(i.next()); if (mciServer != null) { try { mciServer.shutdown(); } catch (Exception e) { throw new ExMciException(ExMciCode.ERROR_SERVER_STOP, "shutdown()", e.getMessage(), e); } mciServer = null; } } mciServers.clear(); } public void reload(String[] reloadIds) throws SystemException { log.debug(traceId+"Reloading MciServerListener."); String[] ids = new String[reloadIds.length-1]; for(int i=0; i<ids.length; i++) { ids[i] = reloadIds[i+1]; } log.info(traceId + "reloadIds[0] :"+reloadIds[0]); if(reloadIds[0].equals(ExMciConfig.MCI_SERVER_INFO_TABLE_ID)) { log.info(traceId + "Restarting EX_MCI_SERVER_INFO."); ExMciServerInfoTable infoTable = InfoTableManager.getInstance().getInfoTable(ExMciConfig.MCI_SERVER_INFO_TABLE_ID); for(int i=0;i<ids.length;i++) { MciServer mciServer = mciServers.get(ids[i]); try { log.info(traceId+"["+ids[i]+"] MCI Server shutdowning..."); if(mciServer!=null) mciServer.shutdown(); } catch (Exception ex) { throw new ExMciException(ExMciCode.ERROR_SERVER_STOP, "shutdown()", ex.getMessage(), ex); } mciServer = null; log.info(traceId+"["+ids[i]+"] MCI Server shudowned."); ExMciServerInfoRecord info = (ExMciServerInfoRecord)infoTable.getInfoRecord(ids[i]); if(info!=null && info.isUseFlag()) { log.info(traceId+"["+ids[i]+"] MCI Server restarting..."); mciServer = new MciServer(traceId, info); try { mciServer.startup(); } catch (Exception e) { throw new ExMciException(ExMciCode.ERROR_SERVER_START, "startup()", e.getMessage(), e); } mciServers.put(info.getInterfaceId(), mciServer); log.info(traceId + "["+ids[i]+"] MCI Server restarted. listen port : "+info.getServerPort()+", file listen port : "+info.getServerFilePort()); } } log.info(traceId + "MCI info reloading completed."); } } }
/* * Copyright 2017 Rundeck, Inc. (http://rundeck.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.rundeck.client.api.model; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import java.util.Date; import java.util.Map; /** * Parameters to run a job */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public class JobRun { private String asUser; private String argString; private String loglevel; private String filter; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ssX") private Date runAtTime; private Map<String, String> options; public String getAsUser() { return asUser; } public void setAsUser(String asUser) { this.asUser = asUser; } public String getArgString() { return argString; } public void setArgString(String argString) { this.argString = argString; } public String getLoglevel() { return loglevel; } public void setLoglevel(String loglevel) { this.loglevel = loglevel; } public String getFilter() { return filter; } public void setFilter(String filter) { this.filter = filter; } public Date getRunAtTime() { return runAtTime; } public void setRunAtTime(Date runAtTime) { this.runAtTime = runAtTime; } public Map<String, String> getOptions() { return options; } public void setOptions(Map<String, String> options) { this.options = options; } @Override public String toString() { return "org.rundeck.client.api.model.JobRun{" + "asUser='" + asUser + '\'' + ", argString='" + argString + '\'' + ", loglevel='" + loglevel + '\'' + ", filter='" + filter + '\'' + ", runAtTime=" + runAtTime + ", options=" + options + '}'; } }
package Collections; import java.util.*; public class CollectionsLecture { public static void main(String[] args) { // creating ArrayLists ArrayList<Integer> numbers = new ArrayList<>(); // array list of numbers numbers.add(1); numbers.add(2); numbers.add(3); // PEEKING INTO LIST // System.out.println(numbers); // [1, 2, 3] // GET ELEMENTS // System.out.println(numbers.get(0)); // ADDING ELEMENTS // numbers.add(20); // System.out.println(numbers); // 1, 2, 3, 20 // // numbers.add(0, 21 ); // System.out.println(numbers); // 21, 1, 2, 3, 20 // EDITING ELEMENTS // numbers.set(0, 100); // System.out.println(numbers); // [100, ...,...] // numbers.set(1, 200); // System.out.println(numbers); // [100, 200, ...] // REMOVING ELEMENTS numbers.remove(1); // System.out.println(numbers); // [1, 3] ArrayList<String> names = new ArrayList<>(); // array list of names names.add("Stephen"); names.add("Liz"); names.add("Miley"); // System.out.println(names); // [Stephen, Liz, Miley] names.remove(0); // System.out.println(names); // [Liz, Miley] // REORDERING LIST Collections.sort(numbers); System.out.println(numbers); Collections.reverse(numbers); System.out.println(numbers); // INFO ABOUT LIST AND GETTING ELEMENTS // System.out.println(numbers.indexOf(3)); // 0 (it's reversed) [3, 1] // System.out.println(numbers); // ANOTHER WAY TO MAKE LIST List<String> name = new ArrayList<>(Arrays.asList( "Stephen", "Liz", "Miley" )); // System.out.println(name); // [Stephen, Liz, Miley] // ArrayList numbers = new ArrayList(); // numbers.add(1); // numbers.add(2); // numbers.add(3); int number = (int)numbers.get(0); // System.out.println(number); // [1, 2, 3] // ArrayList<String> roasts = new ArrayList<>(); roasts.add("medium"); roasts.add("light"); roasts.add("medium"); roasts.add("dark"); // .contains // System.out.println(roasts.contains("espresso")); // false // System.out.println(roasts.contains("dark")); // true // .lastIndexOf // System.out.println(roasts.lastIndexOf("medium")); // 2 // .isEmpty // System.out.println(roasts.isEmpty()); // false // .remove // System.out.println(roasts.remove("espresso")); // false // HASH MAP // ======================================================= // We'll start by defining a hash map HashMap<String, String> usernames = new HashMap<>(); // and putting some data into it usernames.put("Ryan", "ryanorsinger"); usernames.put("Zach", "zgulde"); usernames.put("Fernando", "fmendozaro"); usernames.put("Justin", "jreich5"); System.out.println(usernames); // {Ryan=ryanorsinger, Zach=zgulde, Fernando=fmendozaro, Justin=jreich5} // GETTING VALUES FROM AND INFO ABOUT HASH MAP System.out.println(usernames); // {Ryan=ryanorsinger, Zach=zgulde, Fernando=fmendozaro, Justin=jreich5} System.out.println(usernames.get("Justin")); // jreich5 System.out.println(usernames.get("Phillip")); // nul System.out.println(usernames.getOrDefault("Jason", "gocodeup")); // gocodeup // UPDATING HASH MAPS usernames.put("Ryan", "rorsinger"); System.out.println(usernames); // {Ryan=rorsinger, Zach=zgulde, Fernando=fmendozaro, Justin=jreich5} // usernames.putIfAbsent("Zach", "zgulde"); usernames.putIfAbsent("Zach", "coderdude24"); System.out.println(usernames); // REPLACE usernames.replace("Ryan", "torvalds"); System.out.println(usernames); // {Ryan=torvalds, Zach=zgulde, Fernando=fmendozaro, Justin=jreich5} // checking if keys or values are present System.out.println(usernames.containsKey("Justin")); // true System.out.println(usernames.containsValue("fmendozaro")); // true // removing parts from hash map usernames.remove("Zach"); System.out.println(usernames); //{Ryan=torvalds, Fernando=fmendozaro, Justin=jreich5} // usernames.clear(); // System.out.println(usernames); // {} } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jclouds.openstack.poppy.v1.domain; import java.util.List; import org.jclouds.javax.annotation.Nullable; import org.jclouds.json.SerializedNames; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; /** * Representation of an OpenStack Poppy Access Restriction. */ @AutoValue public abstract class Restriction { /** * @see Builder#name(String) */ public abstract String getName(); /** * @see Builder#rules(List) */ @Nullable public abstract List<RestrictionRule> getRules(); @SerializedNames({ "name", "rules" }) private static Restriction create(String name, List<RestrictionRule> rules) { return builder().name(name).rules(rules).build(); } public static Builder builder() { return new AutoValue_Restriction.Builder(); } public Builder toBuilder(){ return builder() .name(getName()) .rules(getRules()); } public static final class Builder { private String name; private List<RestrictionRule> rules; Builder() { } Builder(Restriction source) { name(source.getName()); rules(source.getRules()); } /** * Required. * @param name Specifies the name of this restriction. The minimum length for name is 1. * The maximum length is 256. * @return The Restriction builder. */ public Restriction.Builder name(String name) { this.name = name; return this; } /** * Optional. * @param rules Specifies a collection of rules that determine if this restriction should be applied to an asset. * @return The Restriction builder. */ public Restriction.Builder rules(List<RestrictionRule> rules) { this.rules = rules; return this; } public Restriction build() { String missing = ""; if (name == null) { missing += " name"; } if (!missing.isEmpty()) { throw new IllegalStateException("Missing required properties:" + missing); } Restriction result = new AutoValue_Restriction( this.name, rules != null ? ImmutableList.copyOf(this.rules) : null); return result; } } }
package com.vivek.sampleapp.activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.vivek.sampleapp.R; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; public class HomeActivity extends BaseActivity implements View.OnClickListener{ @Bind(R.id.textViewHome) TextView textView; // @Override // protected void onResume() { // Log.d("vvk","onresume Homeactivity"); // super.onResume(); // } // // @Override // protected void onDestroy() { // Log.d("vvk","ondestroy Homeactivity"); // super.onDestroy(); // // } // // @Override // protected void onStop() { // Log.d("vvk","onstop Homeactivity"); // super.onStop(); // // } // // @Override // protected void onPause() { // super.onPause(); // Log.d("vvk", "onpause Homeactivity"); // } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); ButterKnife.bind(this); findViewById(R.id.buttonFragmentActivity).setOnClickListener(this); findViewById(R.id.buttonRVActivity).setOnClickListener(this); findViewById(R.id.buttonDrawerActivity).setOnClickListener(this); findViewById(R.id.buttontabLayoutActivity).setOnClickListener(this); findViewById(R.id.buttonOpenGallaryPicasso).setOnClickListener(this); findViewById(R.id.buttonOpenGallaryVivek).setOnClickListener(this); } @OnClick(R.id.buttonListActivity ) @Override public void onClick(View v) { Intent i = null; switch (v.getId()) { case R.id.buttonListActivity: i = new Intent(this,ListViewActivity.class); break; case R.id.buttonFragmentActivity: i = new Intent(this,FragmentActivity.class); break; case R.id.buttonRVActivity: i = new Intent(this,RecyclerViewActivity.class); break; case R.id.buttonDrawerActivity: i = new Intent(this,DrawerActivity.class); break; case R.id.buttontabLayoutActivity: i = new Intent(this, TabLayoutActivity.class); break; case R.id.buttonOpenGallaryPicasso: i = new Intent(this,GalleryActivity.class); i.putExtra("usePicasso",true); break; case R.id.buttonOpenGallaryVivek: i = new Intent(this,GalleryActivity.class); i.putExtra("usePicasso",false); break; } startActivity(i); } }
package com.gxjtkyy.standardcloud.admin.domain.vo.request; import com.gxjtkyy.standardcloud.common.domain.vo.RequestVO; import com.gxjtkyy.standardcloud.common.validation.annotation.EnumType; import com.gxjtkyy.standardcloud.common.validation.annotation.NotEmpty; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * 更新请求体 * @Package com.gxjtkyy.standardcloud.admin.domain.vo.request * @Author lizhenhua * @Date 2018/7/2 11:13 */ @Setter @Getter @ToString(callSuper = true) public class UpdateTemplateReq extends RequestVO{ /**id*/ @NotEmpty private String templateId; /**节点*/ @NotEmpty private String node; /**dataModel*/ @EnumType(enums = {"TABLE","TEXT","ATTACH"}) private String dataModel; /**dataDirection*/ @EnumType(enums = {"H","V","M"}) private String dataDirection; /**模板描述*/ private String templateDesc; }
package com.example.onemap; import android.app.Activity; /** * drawer中的list的detail * 需求為picture、png、activity */ public class DrawerListDetails { public final String title; public final int image; public final Class<? extends Activity> activityClass; public DrawerListDetails(String title,int image, Class<? extends Activity> activityClass){ this.image = image; this.title = title; this.activityClass = activityClass; }// end of DrawerListDetials }// end of DrawerListDetials
package com.git.cloud.cloudservice.service.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import com.git.cloud.cloudservice.dao.IModelDao; import com.git.cloud.cloudservice.dao.IPackageDefDao; import com.git.cloud.cloudservice.dao.IScriptDao; import com.git.cloud.cloudservice.dao.IScriptParamDao; import com.git.cloud.cloudservice.model.vo.ModelModelVO; import com.git.cloud.cloudservice.model.vo.PackageModelVO; import com.git.cloud.cloudservice.model.vo.ScriptModelVO; import com.git.cloud.cloudservice.model.vo.ScriptParamModelVO; import com.git.cloud.cloudservice.service.IPackageDefService; import com.git.cloud.common.exception.RollbackableBizException; /** * 脚本管理 * @ClassName: PackageDefServiceImpl * @Description:TODO * @author caohaihong * @date 2014-11-27 下午3:47:17 */ public class PackageDefServiceImpl implements IPackageDefService { private IPackageDefDao packageDefDao; private IModelDao modelDao; private IScriptDao scriptDao; private IScriptParamDao scriptParamDao; private Object String; /* @Override public Object load(String id, String type) throws RollbackableBizException { if ("1".equals(type)) { return this.getPackageDefDao().load(id); } else if ("2".equals(type)) { return modelDao.load(id); } else if ("3".equals(type)) { ScriptModelVO s = scriptDao.load(id); List<ScriptParamModelVO> list = this.getScriptParamDao().loadParamsByScriptId(s.getId()); s.setScriptParamModelVOs(list); return s; } else if ("4".equals(type)) { return scriptParamDao.load(id); } return null; } */ public Object load(String id, String type) throws RollbackableBizException { if ("1".equals(type)) { return this.loadPackageForLog(id); } else if ("2".equals(type)) { return this.loadModelForLog(id); } else if ("3".equals(type)) { ScriptModelVO s = (ScriptModelVO)this.loadScriptForLog(id); List<ScriptParamModelVO> list = this.getScriptParamDao().loadParamsByScriptId(s.getId()); s.setScriptParamModelVOs(list); return s; } else if ("4".equals(type)) { return this.loadScriptParamForLog(id); } return null; } public Map loadScriptParamsByScript(String scriptId) { HashMap map = new HashMap(); map.put("pid", scriptId); Map p = scriptParamDao.search(map); return p; } @Override public List loadTree() { return this.getPackageDefDao().loadTree(); } @Override public PackageModelVO load(String id) { PackageModelVO packageModelVO = this.getPackageDefDao().load(id); return packageModelVO; } // @Override // public void delete(String id, String type) throws RollbackableBizException { // if ("1".equals(type)) { // this.deletePackageForLog(id); // } // if ("2".equals(type)) { // this.deleteModelForLog(id); // } // if ("3".equals(type)) { // this.deleteScriptForLog(id); // } // if ("4".equals(type)) { // this.deleteScriptParamForLog(id); // } // } // public Object save(Object object) throws RollbackableBizException { // if (object instanceof PackageModelVO){ // PackageModelVO packageModelVO = (PackageModelVO)object; //// if (packageModelVO.getId() == null || "".equals(packageModelVO.getId())) { //// return this.savePackageForLog(packageModelVO); //// }else { //// return this.updatePackageForLog(packageModelVO); //// } // return packageModelVO; // // } // else if (object instanceof ModelModelVO){ // ModelModelVO modelModelVO = (ModelModelVO)object; // if (modelModelVO.getId() == null || "".equals(modelModelVO.getId())) { // return this.saveModelForLog(modelModelVO); // }else { // return this.updateModelForLog(modelModelVO); // } // } // else if (object instanceof ScriptModelVO){ // ScriptModelVO scriptModelVO = (ScriptModelVO)object; // if (scriptModelVO.getId() == null || "".equals(scriptModelVO.getId())) { // return this.saveScriptForLog(scriptModelVO); // }else { // return this.updateScriptForLog(scriptModelVO); // } // } // else if (object instanceof ScriptParamModelVO){ // ScriptParamModelVO scriptParamModelVO = (ScriptParamModelVO)object; // if (scriptParamModelVO.getId() == null || "".equals(scriptParamModelVO.getId())) { // return this.savescriptParamForLog(scriptParamModelVO); // }else { // return this.updateScriptParamForLog(scriptParamModelVO); // } // } // return null; // } @Override public Map search(Map map) { // TODO Auto-generated method stub return null; } public IPackageDefDao getPackageDefDao() { return packageDefDao; } public void setPackageDefDao(IPackageDefDao packageDefDao) { this.packageDefDao = packageDefDao; } public IModelDao getModelDao() { return modelDao; } public void setModelDao(IModelDao modelDao) { this.modelDao = modelDao; } public IScriptDao getScriptDao() { return scriptDao; } public void setScriptDao(IScriptDao scriptDao) { this.scriptDao = scriptDao; } public IScriptParamDao getScriptParamDao() { return scriptParamDao; } public void setScriptParamDao(IScriptParamDao scriptParamDao) { this.scriptParamDao = scriptParamDao; } @Override public List loadDict(java.util.Map<String, String> params) { return getPackageDefDao().loadDict(params); } /* (non-Javadoc) * <p>Title:saveModelForLog</p> * <p>Description:</p> * @param modelVO * @return * @throws RollbackableBizException * @see com.git.cloud.cloudservice.service.IPackageDefService#saveModelForLog(com.git.cloud.cloudservice.model.vo.ModelModelVO) */ @Override public ModelModelVO saveModelForLog(ModelModelVO object) throws RollbackableBizException { return getModelDao().save(object); } /* (non-Javadoc) * <p>Title:savePackageForLog</p> * <p>Description:</p> * @param packageModelVO * @return * @throws RollbackableBizException * @see com.git.cloud.cloudservice.service.IPackageDefService#savePackageForLog(com.git.cloud.cloudservice.model.vo.PackageModelVO) */ @Override public PackageModelVO savePackageForLog(PackageModelVO object) throws RollbackableBizException { PackageModelVO p = getPackageDefDao().save(object); return p; } /* (non-Javadoc) * <p>Title:savePackageForLog</p> * <p>Description:</p> * @param scriptVO * @return * @throws RollbackableBizException * @see com.git.cloud.cloudservice.service.IPackageDefService#savePackageForLog(com.git.cloud.cloudservice.model.vo.ScriptModelVO) */ @Override public ScriptModelVO saveScriptForLog(ScriptModelVO object) throws RollbackableBizException { return getScriptDao().save(object); } /* (non-Javadoc) * <p>Title:savescriptParamForLog</p> * <p>Description:</p> * @param scriptParamVO * @return * @throws RollbackableBizException * @see com.git.cloud.cloudservice.service.IPackageDefService#savescriptParamForLog(com.git.cloud.cloudservice.model.vo.ScriptParamModelVO) */ @Override public ScriptParamModelVO savescriptParamForLog(ScriptParamModelVO object) throws RollbackableBizException { return getScriptParamDao().save(object); } /* (non-Javadoc) * <p>Title:updateModelForLog</p> * <p>Description:</p> * @param object * @return * @throws RollbackableBizException * @see com.git.cloud.cloudservice.service.IPackageDefService#updateModelForLog(java.lang.Object) */ @Override public ModelModelVO updateModelForLog(ModelModelVO object) throws RollbackableBizException { return getModelDao().save(object); } /* (non-Javadoc) * <p>Title:updatePackageForLog</p> * <p>Description:</p> * @param object * @return * @throws RollbackableBizException * @see com.git.cloud.cloudservice.service.IPackageDefService#updatePackageForLog(java.lang.Object) */ @Override public PackageModelVO updatePackageForLog(PackageModelVO object) throws RollbackableBizException { return getPackageDefDao().save(object); } /* (non-Javadoc) * <p>Title:updateScriptForLog</p> * <p>Description:</p> * @param object * @return * @throws RollbackableBizException * @see com.git.cloud.cloudservice.service.IPackageDefService#updateScriptForLog(java.lang.Object) */ @Override public ScriptModelVO updateScriptForLog(ScriptModelVO object) throws RollbackableBizException { return getScriptDao().save(object); } /* (non-Javadoc) * <p>Title:updateScriptParamForLog</p> * <p>Description:</p> * @param object * @return * @throws RollbackableBizException * @see com.git.cloud.cloudservice.service.IPackageDefService#updateScriptParamForLog(java.lang.Object) */ @Override public ScriptParamModelVO updateScriptParamForLog(ScriptParamModelVO object) throws RollbackableBizException { return getScriptParamDao().save(object); } /* (non-Javadoc) * <p>Title:deleteModelForLog</p> * <p>Description:</p> * @param id * @throws RollbackableBizException * @see com.git.cloud.cloudservice.service.IPackageDefService#deleteModelForLog(java.lang.String) */ @Override public void deleteModelForLog(String id) throws RollbackableBizException { this.getModelDao().delete(id); } /* (non-Javadoc) * <p>Title:deletePackageForLog</p> * <p>Description:</p> * @param id * @throws RollbackableBizException * @see com.git.cloud.cloudservice.service.IPackageDefService#deletePackageForLog(java.lang.String) */ @Override public void deletePackageForLog(String id) throws RollbackableBizException { this.getPackageDefDao().delete(id); } /* (non-Javadoc) * <p>Title:deleteScriptForLog</p> * <p>Description:</p> * @param id * @throws RollbackableBizException * @see com.git.cloud.cloudservice.service.IPackageDefService#deleteScriptForLog(java.lang.String) */ @Override public void deleteScriptForLog(String id) throws RollbackableBizException { this.getScriptDao().delete(id); } /* (non-Javadoc) * <p>Title:deleteScriptParamForLog</p> * <p>Description:</p> * @param id * @throws RollbackableBizException * @see com.git.cloud.cloudservice.service.IPackageDefService#deleteScriptParamForLog(java.lang.String) */ @Override public void deleteScriptParamForLog(String id) throws RollbackableBizException { this.getScriptParamDao().delete(id); } /* (non-Javadoc) * <p>Title:loadModelForLog</p> * <p>Description:</p> * @param id * @return * @throws RollbackableBizException * @see com.git.cloud.cloudservice.service.IPackageDefService#loadModelForLog(java.lang.String) */ @Override public ModelModelVO loadModelForLog(String id) throws RollbackableBizException { return modelDao.load(id); } /* (non-Javadoc) * <p>Title:loadPackageForLog</p> * <p>Description:</p> * @param id * @return * @throws RollbackableBizException * @see com.git.cloud.cloudservice.service.IPackageDefService#loadPackageForLog(java.lang.String) */ @Override public PackageModelVO loadPackageForLog(String id) throws RollbackableBizException { return this.getPackageDefDao().load(id); } /* (non-Javadoc) * <p>Title:loadScriptForLog</p> * <p>Description:</p> * @param id * @return * @throws RollbackableBizException * @see com.git.cloud.cloudservice.service.IPackageDefService#loadScriptForLog(java.lang.String) */ @Override public ScriptModelVO loadScriptForLog(String id) throws RollbackableBizException { return scriptDao.load(id); } /* (non-Javadoc) * <p>Title:loadScriptParamForLog</p> * <p>Description:</p> * @param id * @return * @throws RollbackableBizException * @see com.git.cloud.cloudservice.service.IPackageDefService#loadScriptParamForLog(java.lang.String) */ @Override public ScriptParamModelVO loadScriptParamForLog(String id) throws RollbackableBizException { return scriptParamDao.load(id); } //检查包下面有没有模板 @Override public List<ModelModelVO> getParamByPackageId(String id) throws RollbackableBizException { // TODO Auto-generated method stub @SuppressWarnings("unchecked") List<ModelModelVO> list= packageDefDao.findByPackageId(id); return list; } //检查模板下面有没有脚本 @Override public List<ScriptModelVO> getParamByModelId(String id) throws RollbackableBizException { // TODO Auto-generated method stub @SuppressWarnings("unchecked") List<ScriptModelVO> list= modelDao.findByModelId(id); return list; } @Override public Object save(ModelModelVO modelModelVO) throws RollbackableBizException { // TODO Auto-generated method stub return modelModelVO; } @Override public Object save(ScriptModelVO scriptModelVO) throws RollbackableBizException { // TODO Auto-generated method stub return scriptModelVO; } @Override public Object save(ScriptParamModelVO scriptParamModelVO) throws RollbackableBizException { // TODO Auto-generated method stub return scriptParamModelVO; } @Override public Object save(PackageModelVO packageModelVO) throws RollbackableBizException { // TODO Auto-generated method stub return packageModelVO; } @Override public String checkPackageName(String packageName) { // TODO Auto-generated method stub Object packageObject = packageDefDao.checkPackageName(packageName); return (packageObject==null) ? (0+"") : (1+""); } @Override public boolean checkModelName(String modelName, String packageId) { // TODO Auto-generated method stub Integer count = packageDefDao.checkModelName(modelName, packageId); if(count != null && count == 0) return true; return false; } @Override public boolean checkScriptName(java.lang.String scriptName, java.lang.String modelId) { Integer count = packageDefDao.checkScriptName(scriptName, modelId); if(count != null && count == 0) return true; return false; } }
package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import bean.Product; public class ProductDAO { public static void main(String[] args) { System.out.println(new ProductDAO().ListProduct().size()); } public Product getProduct(int id) { Product result = null; try { Class.forName("com.mysql.jdbc.Driver"); Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/cart?characterEncoding=UTF-8&serverTimezone=GMT", "root", "15659170386"); String sql = "select * from product where id = ?"; PreparedStatement ps = c.prepareStatement(sql); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); if (rs.next()) { result = new Product(); result.setId(id); String name = rs.getString(2); float price = rs.getFloat(3); result.setName(name); result.setPrice(price); } ps.close(); c.close(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } public List<Product> ListProduct() { List<Product> products = new ArrayList<Product>(); try { Class.forName("com.mysql.jdbc.Driver"); Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/cart?characterEncoding=UTF-8&serverTimezone=GMT", "root", "15659170386"); String sql = "select * from product order by id desc"; PreparedStatement ps = c.prepareStatement(sql); ResultSet rs = ps.executeQuery(); while (rs.next()) { Product product = new Product(); int id = rs.getInt(1); String name = rs.getString(2); float price = rs.getFloat(3); product.setId(id); product.setName(name); product.setPrice(price); products.add(product); } ps.close(); c.close(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return products; } public static ArrayList<Product> listLastViewProduct(String cookie){ ArrayList<Product> products = new ArrayList<>(); HashSet<Integer> noRepeatRecords = new HashSet<>(); String[] records = cookie.split("#"); int count = 5; int i = records.length - 1; while(noRepeatRecords.size() < count && i >= 0){ noRepeatRecords.add(Integer.valueOf(records[i])); i --; } Iterator<Integer> it = noRepeatRecords.iterator(); while(it.hasNext()){ products.add(new ProductDAO().getProduct(it.next())); } return products; } }
package apascualco.blog.springboot; import apascualco.blog.springboot.persistence.entidades.*; import apascualco.blog.springboot.persistence.repositorio.*; import apascualco.blog.springboot.utils.PersistenciaUtils; 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.test.context.junit4.SpringRunner; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest public class CocheRepositorioTests { @Autowired private CocheREPO cocheREPO; @Autowired private CarroceriaREPO carroceriaREPO; @Autowired private TapiceriaREPO tapiceriaREPO; @Autowired private MotorREPO motorREPO; @Autowired private RuedasREPO ruedasREPO; @Test public void buscarTodos() { long count = cocheREPO.count(); assertTrue(cocheREPO.findAll().size() == count); } @Test public void insertarCoche() { long cocheCount = this.cocheREPO.count(); long carroceriaCount = this.carroceriaREPO.count(); long tapiceriaCount = this.tapiceriaREPO.count(); long motorCount = this.motorREPO.count(); long ruedas = this.ruedasREPO.count(); CocheEntidad cocheEntidad = PersistenciaUtils.generarCocheEntidad(carroceriaREPO, tapiceriaREPO, motorREPO, ruedasREPO); CarroceriaEntidad carroceriaEntidad = cocheEntidad.getCarroceria(); TapiceriaEntidad tapiceriaEntidad = cocheEntidad.getTapiceria(); MotorEntidad motorEntidad = cocheEntidad.getMotor(); RuedasEntidad ruedasEntidad = cocheEntidad.getRuedas(); assertNotNull(carroceriaEntidad.getId()); assertNotNull(tapiceriaEntidad.getId()); assertNotNull(motorEntidad.getId()); assertNotNull(ruedasEntidad.getId()); assertTrue(carroceriaREPO.count() > carroceriaCount); assertTrue(tapiceriaREPO.count() > tapiceriaCount); assertTrue(motorREPO.count() > motorCount); assertTrue(ruedasREPO.count() > ruedas); assertTrue(cocheREPO.count() == cocheCount); cocheREPO.save(cocheEntidad); assertTrue(cocheREPO.count() > cocheCount); } @Test public void deleteCoche() { long cocheCount = this.cocheREPO.count(); long carroceriaCount = this.carroceriaREPO.count(); long tapiceriaCount = this.tapiceriaREPO.count(); long motorCount = this.motorREPO.count(); long ruedas = this.ruedasREPO.count(); cocheREPO.delete(String.valueOf(this.cocheREPO.count())); assertTrue(cocheCount > cocheREPO.count()); assertTrue(carroceriaREPO.count() < carroceriaCount); assertTrue(tapiceriaREPO.count() < tapiceriaCount); assertTrue(motorREPO.count() < motorCount); assertTrue(ruedasREPO.count() < ruedas); } }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.oauth.as.preferences; import java.util.Iterator; import pl.edu.icm.unity.oauth.as.preferences.OAuthPreferences.OAuthClientSettings; import pl.edu.icm.unity.server.utils.UnityMessageSource; import com.vaadin.ui.Component; import com.vaadin.ui.FormLayout; import com.vaadin.ui.Label; /** * Shows a single {@link OAuthClientSettings}. * * @author K. Benedyczak */ public class OAuthSPSettingsViewer extends FormLayout { protected UnityMessageSource msg; protected Label autoConfirm; protected Label defaultIdentity; public OAuthSPSettingsViewer(UnityMessageSource msg) { this.msg = msg; setSpacing(true); setMargin(true); autoConfirm = new Label(); autoConfirm.setCaption(msg.getMessage("OAuthPreferences.autoConfirm")); defaultIdentity = new Label(); defaultIdentity.setCaption(msg.getMessage("OAuthPreferences.defaultIdentity")); addComponents(autoConfirm, defaultIdentity); } public void setInput(OAuthClientSettings spSettings) { if (spSettings == null) { setVisibleRec(false); return; } setVisibleRec(true); if (spSettings.isDoNotAsk()) { if (spSettings.isDefaultAccept()) autoConfirm.setValue(msg.getMessage("OAuthPreferences.accept")); else autoConfirm.setValue(msg.getMessage("OAuthPreferences.decline")); } else autoConfirm.setValue(msg.getMessage("no")); String selIdentity = spSettings.getSelectedIdentity(); if (selIdentity != null) { defaultIdentity.setValue(selIdentity); defaultIdentity.setVisible(true); } else defaultIdentity.setVisible(false); } private void setVisibleRec(boolean how) { Iterator<Component> children = iterator(); while (children.hasNext()) { Component c = children.next(); c.setVisible(how); } } }
package com.m2miage.boundary; import com.m2miage.entity.Demande; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.CrudRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; //@RepositoryRestResource(collectionResourceRel="demande", path="demande") public interface DemandeRessource extends JpaRepository<Demande,String> { }
import org.junit.Test; import java.util.Arrays; import static org.junit.Assert.assertEquals; public class GrudgerPlayerTest { @Test public void shouldCooperateInUntilTheOtherPlayerCheats(){ assertEquals(Input.COOPERATE, new GrudgerPlayer().getInput(Arrays.asList(Input.COOPERATE))); } @Test public void shouldCheatWhenTheOtherPlayerCheats(){ assertEquals(Input.CHEAT, new GrudgerPlayer().getInput(Arrays.asList(Input.CHEAT))); } @Test public void shouldContinueCheatingTillTheEndWhenTheOtherPlayerCheats(){ assertEquals(Input.CHEAT, new GrudgerPlayer().getInput(Arrays.asList(Input.COOPERATE,Input.CHEAT, Input.COOPERATE))); } }
public class Solution { public int kthSmallest(int[][] matrix, int k) { // Write your solution here HashSet<String> visited = new HashSet<>(); PriorityQueue<Cell> minHeap = new PriorityQueue<>(new Comparator<Cell>() { public int compare(Cell c1, Cell c2) { if (c1.value == c2.value) { return 0; } return c1.value < c2.value ? -1 : 1; } }); int row = matrix.length; int col = matrix[0].length; minHeap.offer(new Cell(matrix[0][0], 0, 0)); int i = 0; Cell current = null; while (i < k) { current = minHeap.poll(); if (current.r + 1 < row) { if (!visited.contains(pos(current.r + 1, current.c))) { minHeap.offer(new Cell(matrix[current.r + 1][current.c], current.r + 1, current.c)); visited.add(pos(current.r + 1, current.c)); } } if (current.c + 1 < col) { if (!visited.contains(pos(current.r, current.c + 1))) { minHeap.offer(new Cell(matrix[current.r][current.c + 1], current.r, current.c + 1)); visited.add(pos(current.r, current.c + 1)); } } i++; } return current.value; } private String pos(int a, int b) { return a + "" + b; } } class Cell { public int value; public int r; public int c; public Cell(int value, int r, int c) { this.value = value; this.c = c; this.r = r; } }
package com.danerdaner.activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.danerdaner.simple_voca.R; import com.danerdaner.simple_voca.TestAnswer; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Random; import java.util.Stack; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; public class Test_TestActivity extends AppCompatActivity { private TextView problem_number; private TextView problem_word; private TextView problem_announce; private TextView category_name; private String Category_name; private String test_type; private Button[] problem_answer = new Button[4]; private Random r; // Pair 대용으로 사용한 SimpleEntry Class (Key, Value Type을 이용해서 pair 저장) private Stack<AbstractMap.SimpleEntry<Integer,String[]>> answers = new Stack<>(); private Boolean[] corrects = new Boolean[20]; private int currentNum=0; // 정답 답변 정보 private ArrayList<TestAnswer> myAnswers = new ArrayList<>(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_test); Intent intent = getIntent(); ArrayList<String[]> TestList = (ArrayList<String[]>) intent.getSerializableExtra("list"); test_type = intent.getStringExtra("test_type"); Category_name = intent.getStringExtra("category_name"); r = new Random(System.currentTimeMillis()); // Seed 설정 category_name = findViewById(R.id.test_test_category_name); category_name.setText(Category_name); problem_number = findViewById(R.id.test_test_category_number); problem_word = findViewById(R.id.test_test_category_word); problem_announce = findViewById(R.id.test_test_category_announce); problem_answer[0] = findViewById(R.id.test_test_number_1); problem_answer[1] = findViewById(R.id.test_test_number_2); problem_answer[2] = findViewById(R.id.test_test_number_3); problem_answer[3] = findViewById(R.id.test_test_number_4); makeProblem(TestList,currentNum); // 테스트를 다 봤으면 Intent를 이용해 Test_ResultActivity로 넘어갈 것. } private void makeProblem(ArrayList<String[]> TestList, int problemNum){ int answerNum = r.nextInt(4); // 정답 번호 TestAnswer problemAnswer = new TestAnswer(); String[] selections = new String[4]; problem_number.setText((problemNum+1)+" / "+TestList.size()); problem_word.setText(TestList.get(problemNum)[0]); problem_announce.setText("[" + TestList.get(problemNum)[2] + "]"); problemAnswer.setProblem(new String[]{TestList.get(problemNum)[0], TestList.get(problemNum)[2]}); problemAnswer.setAnswer(answerNum); problem_answer[answerNum].setText(TestList.get(problemNum)[1]); // Answer Setting selections[answerNum] = TestList.get(problemNum)[1]; // 정답 Button OnClick 설정 if(problemNum < 19) { problem_answer[answerNum].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { myAnswers.get(problemNum).setCorrect(true); makeProblem(TestList, problemNum+1); } }); } else{ // 20번 문제까지 다 풀었을 경우 problem_answer[answerNum].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { myAnswers.get(problemNum).setCorrect(true); // 화면전환 Intent intent = new Intent(Test_TestActivity.this, Test_ResultActivity.class); intent.addFlags(intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("answers", myAnswers); intent.putExtra("category_name", Category_name); intent.putExtra("test_type", test_type); startActivity(intent); } }); } // 중복제거용 remove와 복원용 Stack 활용 answers.push(new AbstractMap.SimpleEntry<>(problemNum, TestList.remove(problemNum))); for(int i=0;i<4; i++){ // 정답인 버튼만 빼고 설정 if(i == answerNum) continue; // n = 선택지로 쓰일 단어 인덱스 int n = r.nextInt(TestList.size()); problem_answer[i].setText(TestList.get(n)[1]); selections[i] = TestList.get(n)[1]; // 오답 Button OnClick 설정 if(problemNum < 19) { problem_answer[i].setOnClickListener(new WrongAnswer(problemNum,i,TestList)); }else{ problem_answer[i].setOnClickListener(new WrongAnswerLast(problemNum,i,TestList)); } // 중복제거용 remove와 복원용 Stack 활용 answers.push(new AbstractMap.SimpleEntry<>(n,TestList.remove(n))); } while(!answers.isEmpty()){ AbstractMap.SimpleEntry<Integer,String[]> toPut = answers.pop(); TestList.add(toPut.getKey(),toPut.getValue()); } problemAnswer.setSelects(selections); myAnswers.add(problemAnswer); } private class WrongAnswer implements View.OnClickListener { private int problemNum; private int selectionNum; private ArrayList<String[]> TestList; public WrongAnswer(int problemNum, int selectionNum, ArrayList<String[]> TestList){ this.problemNum = problemNum; this.selectionNum = selectionNum; this.TestList = TestList; } @Override public void onClick(View view) { myAnswers.get(problemNum).setCorrect(false); myAnswers.get(problemNum).setWrongAnswer(selectionNum); makeProblem(TestList, problemNum + 1); } } private class WrongAnswerLast implements View.OnClickListener { private int problemNum; private int selectionNum; private ArrayList<String[]> TestList; public WrongAnswerLast(int problemNum, int selectionNum, ArrayList<String[]> TestList){ this.problemNum = problemNum; this.selectionNum = selectionNum; this.TestList = TestList; } @Override public void onClick(View view) { myAnswers.get(problemNum).setCorrect(false); myAnswers.get(problemNum).setWrongAnswer(selectionNum); // 화면전환 Intent intent = new Intent(Test_TestActivity.this, Test_ResultActivity.class); intent.putExtra("answers", myAnswers); intent.putExtra("category_name", Category_name); intent.putExtra("test_type", test_type); startActivity(intent); } } @Override protected void onPause() { super.onPause(); finish(); } @Override protected void onStop() { super.onStop(); finish(); } @Override protected void onDestroy() { super.onDestroy(); finish(); } }
package leetCode; import java.util.LinkedList; import java.util.List; public class PermutationSequence { public String getPermutation(int n, int k) { k = k - 1; List<Integer> intList = new LinkedList<Integer>(); String result = ""; for (int i = 1; i <= n; i++) { intList.add(i); } int index = 0; for (int i = 0; i < n; i++) { if (intList.size() == 1) { result += intList.get(0); break; } else { int m = factorial(intList.size() - 1); index = k / m; k = k % m; result += intList.get(index); intList.remove(index); } } return result; } public int factorial(int k) { int i = 1; for (int j = 2; j <= k; j++) { i = i * j; } return i; } }
package com.sky.design.factory; //学雷锋的大学生的工厂 public class VolunteerFactory implements IFactory { @Override public LeiFeng CreateLeiFeng() { return new Volunteer(); } }
package co.sblock.effects.effect.godtier.passive; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import co.sblock.Sblock; import co.sblock.effects.effect.BehaviorCooldown; import co.sblock.effects.effect.BehaviorGodtier; import co.sblock.effects.effect.BehaviorPassive; import co.sblock.effects.effect.Effect; import co.sblock.users.UserAspect; import co.sblock.utilities.Potions; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import net.md_5.bungee.api.ChatColor; /** * Effect granting the user the absorption PotionEffect every minute. Due to the nature of * absorption granting free health, this has a longer duration and cooldown than most other passive * effects. * * @author Jikoo */ public class EffectAbsorption extends Effect implements BehaviorCooldown, BehaviorGodtier, BehaviorPassive { public EffectAbsorption(Sblock plugin) { super(plugin, 1000, 3, 20, "Absorbant"); } @Override public String getCooldownName() { return "Effect:Absorption"; } @Override public long getCooldownDuration() { return 55000; } @Override public Collection<UserAspect> getAspects() { return Arrays.asList(UserAspect.HEART, UserAspect.TIME); } @Override public List<String> getDescription(UserAspect aspect) { ArrayList<String> list = new ArrayList<>(); if (aspect == UserAspect.HEART) { list.add(aspect.getColor() + "Hale and Hearty"); } else if (aspect == UserAspect.TIME) { list.add(aspect.getColor() + "Futureproof"); } list.add(ChatColor.WHITE + "An apple a day keeps the doctor away."); list.add(ChatColor.GRAY + "Gain extra life."); return list; } @Override public void applyEffect(LivingEntity entity, int level) { if (level < 1) { level = 1; } int duration = entity instanceof Player ? 1200 : Integer.MAX_VALUE; Potions.applyIfBetter(entity, new PotionEffect(PotionEffectType.ABSORPTION, duration, level - 1)); } }
package com.androidbook.networking; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.TextSwitcher; import android.widget.TextView; import android.widget.ViewSwitcher; import android.widget.Gallery.LayoutParams; public class WebViewDemo extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.web); final TextSwitcher pageTitle = (TextSwitcher)findViewById(R.id.pagetitle); pageTitle.setFactory(new ViewSwitcher.ViewFactory() { public View makeView() { TextView tv = new TextView(WebViewDemo.this); tv.setLayoutParams(new TextSwitcher.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); return tv; } }); final ImageSwitcher favImage = (ImageSwitcher)findViewById(R.id.favicon); favImage.setFactory(new ViewSwitcher.ViewFactory() { public View makeView() { ImageView iv = new ImageView(WebViewDemo.this); iv.setBackgroundColor(0xFF000000); iv.setScaleType(ImageView.ScaleType.FIT_CENTER); iv.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); return iv; } }); Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left); Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right); favImage.setInAnimation(in); favImage.setOutAnimation(out); pageTitle.setInAnimation(in); pageTitle.setOutAnimation(out); final EditText et = (EditText) findViewById(R.id.url); final WebView wv = (WebView) findViewById(R.id.web_holder); wv.loadUrl("http://www.perlgurl.org/"); Button go = (Button) findViewById(R.id.go_button); go.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { wv.loadUrl(et.getText().toString()); } }); WebViewClient webClient = new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); String title = wv.getTitle(); pageTitle.setText(title); } }; // this doesn't currently work... not sure why WebChromeClient webChrome = new WebChromeClient() { @Override public void onReceivedIcon(WebView view, Bitmap icon) { super.onReceivedIcon(view, icon); favImage.setImageDrawable(new BitmapDrawable(icon)); } }; wv.setWebViewClient(webClient); wv.setWebChromeClient(webChrome); wv.setInitialScale(30); } }
package ma.mghandi.radeesportail; import java.util.Map; /** * Created by mghandi on 10/03/2018. */ public class Resiliation { private String id; private String name; private String contract_number; private String gerance; private String localite; private String nature; private String etat; private String date; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContract_number() { return contract_number; } public void setContract_number(String contract_number) { this.contract_number = contract_number; } public String getGerance() { return gerance; } public void setGerance(String gerance) { this.gerance = gerance; } public String getLocalite() { return localite; } public void setLocalite(String localite) { this.localite = localite; } public String getNature() { return nature; } public void setNature(String nature) { this.nature = nature; } public String getEtat() { return etat; } public void setEtat(String etat) { this.etat = etat; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public void setListData(Map<String,Object> classObj){ this.name = classObj.get("name").toString(); this.contract_number = classObj.get("contract_number").toString(); this.etat = classObj.get("state").toString(); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.innovaciones.reporte.service; import com.innovaciones.reporte.dao.DetalleEgresoDAO; import com.innovaciones.reporte.model.DetalleEgreso; import java.io.Serializable; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * * @author fyaulema */ @Service @ManagedBean(name = "detalleEgresoService") @ViewScoped public class DetalleEgresoServiceImpl implements DetalleEgresoService, Serializable { private DetalleEgresoDAO detalleInventarioDAO; public void setDetalleEgresoDAO(DetalleEgresoDAO detalleInventarioDAO) { this.detalleInventarioDAO = detalleInventarioDAO; } @Override @Transactional public DetalleEgreso addDetalleEgreso(DetalleEgreso detalleInventario) { return detalleInventarioDAO.addDetalleEgreso(detalleInventario); } @Override @Transactional public List<DetalleEgreso> getDetalleEgresos() { return detalleInventarioDAO.getDetalleEgresos(); } @Override @Transactional public DetalleEgreso getDetalleEgresoById(Integer id) { return detalleInventarioDAO.getDetalleEgresoById(id); } @Override @Transactional public DetalleEgreso getDetalleEgresoByCodigo(String codigo) { return detalleInventarioDAO.getDetalleEgresoByCodigo(codigo); } @Override @Transactional public List<DetalleEgreso> getDetalleEgresosByEstado(Integer estado) { return detalleInventarioDAO.getDetalleEgresosByEstado(estado); } @Override @Transactional public List<DetalleEgreso> getDetalleEgresoByIdCabeceraEgreso(Integer idCabeceraEgreso) { return detalleInventarioDAO.getDetalleEgresoByIdCabeceraEgreso(idCabeceraEgreso); } @Override @Transactional public List<DetalleEgreso> getDetalleEgresoByIdCabeceraEgresoEstado(Integer idCabeceraEgreso, Integer estado) { return detalleInventarioDAO.getDetalleEgresoByIdCabeceraEgresoEstado(idCabeceraEgreso, estado); } }
package com.cb.cbfunny.fragment; import android.content.Intent; import android.graphics.Rect; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.android.volley.VolleyError; import com.cb.cbfunny.Constans; import com.cb.cbfunny.R; import com.cb.cbfunny.bean.GzhkMenu; import com.cb.cbfunny.bean.GzhkMenuList; import com.cb.cbfunny.gzhk.GzhkTabListActivity; import com.cb.cbfunny.utils.ArticleParseUtils; import com.cb.cbfunny.utils.StringUtils; import com.cb.cbfunny.utils.SystemManage; import com.cb.cbfunny.utils.ToastUtil; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.backends.pipeline.PipelineDraweeController; import com.facebook.drawee.view.SimpleDraweeView; import com.facebook.imagepipeline.request.ImageRequest; import com.squareup.okhttp.Request; import com.zhy.http.okhttp.callback.ResultCallback; import com.zhy.http.okhttp.request.OkHttpRequest; import org.json.JSONObject; import java.util.ArrayList; /** * Created by long on 2016/1/16. */ public class GzhkFragment extends BaseFragment { public static final String TAG = "GzhkFragment"; private RecyclerView mRecyclerView; private GzhkAdapter adapter; private GzhkMenuList mGzhkMenuList; private ArrayList<GzhkMenu> DataList = new ArrayList<GzhkMenu>(); public static GzhkFragment getInstance() { return new GzhkFragment(); } @Override public String getFragmentTag() { return TAG; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 获取缓存数据 mGzhkMenuList = (GzhkMenuList) getCacheFromDisk(GzhkMenuList.class.getName()); if(mGzhkMenuList==null){ mGzhkMenuList = new GzhkMenuList(); }else{ DataList.addAll(mGzhkMenuList.getGzhkMenuList()); } } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fmlayout_gzhkcontent, container, false); initView(view); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { // 加载数据 initData(); super.onActivityCreated(savedInstanceState); } private void initData() { if(DataList.size()==0||mGzhkMenuList.needUpdate()){ getWallpaperTabs(); } } private void initView(View view) { mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview); mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)); mRecyclerView.addItemDecoration(new SpacesItemDecoration(10)); adapter = new GzhkAdapter(DataList); adapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() { @Override public void onItemClickListener(View itemView, int position) { Intent intent = new Intent(getActivity(),GzhkTabListActivity.class); intent.putExtra(Constans.PARAM_GZHK_MENU,DataList.get(position)); startActivity(intent); } }); mRecyclerView.setAdapter(adapter); } /** * 从服务器获取数据 */ private void getWallpaperTabs() { if(!SystemManage.checkNetWorkStatue(getActivity())){ ToastUtil.showToast(getActivity(), "木有网络", 0); }else{ new OkHttpRequest.Builder().url(StringUtils.getGzhkTabsUrl(resolution)) .get(new ResultCallback<String>() { @Override public void onBefore(Request request) { super.onBefore(request); } @Override public void onError(Request request, Exception e) { } @Override public void onResponse(String response) { ArrayList<GzhkMenu> list = ArticleParseUtils.getGzhkMenuTabs(response); if (list != null && list.size() > 0) { DataList.clear(); DataList.addAll(list); mGzhkMenuList.updateLastTime(); mGzhkMenuList.setGzhkMenuList(list); adapter.notifyDataSetChanged(); saveObjToFile(mGzhkMenuList, mGzhkMenuList.getClass().getName()); } } }); } } @Override public void onErrorResponse(VolleyError error) { } @Override public void onResponse(JSONObject response) { } @Override public void onResponse(String response) { } public class GzhkAdapter extends RecyclerView.Adapter<GzhkAdapter.ViewHoler>{ private OnRecyclerViewItemClickListener onItemClickListener; private ArrayList<GzhkMenu> dataList; public GzhkAdapter(ArrayList<GzhkMenu> dataList){ this.dataList = dataList; } @Override public GzhkAdapter.ViewHoler onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.gzhk_list_item,parent,false); final ViewHoler holer = new ViewHoler(view); holer.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(onItemClickListener!=null){ int pos = holer.getAdapterPosition(); if(pos!=RecyclerView.NO_POSITION){ onItemClickListener.onItemClickListener(holer.itemView,pos); } } } }); return holer; } @Override public void onBindViewHolder(final GzhkAdapter.ViewHoler holder, int position) { GzhkMenu gzhkMenu = dataList.get(position); // ControllerListener listener = new BaseControllerListener<ImageInfo>(){ // @Override // public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) { // if(imageInfo!=null){ // 目前这里的宽高一样导致没有瀑布流的效果 // int width = imageInfo.getWidth(); // int height = imageInfo.getHeight(); // float aspect = (float)width/(float)height; // Random random = new Random(); // float aspect = random.nextFloat(); // if(aspect<0.6){ // aspect = 0.6f; // } // if(aspect>1){ // aspect = 1; // } // holder.xzCover.setAspectRatio(aspect); // } // } // }; // 随机生成一些比例 // int width = mWidth/2-40; // Random random = new Random(); // float aspect = 0.5f+random.nextFloat(); // if(aspect>1){ // aspect = 1; // } // holder.xzCover.setAspectRatio(aspect); // int height = (int) (width/aspect); // String resolution = width+"x"+height; PipelineDraweeController controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder() .setOldController(holder.xzCover.getController()) .setImageRequest(ImageRequest.fromUri(StringUtils.getGzhkImageUrl(gzhkMenu.getCover(),"500x600"))) // .setControllerListener(listener) .build(); holder.xzCover.setController(controller); holder.xzTitle.setText(gzhkMenu.getName()); } @Override public int getItemCount() { return dataList==null?0:dataList.size(); } public class ViewHoler extends RecyclerView.ViewHolder{ SimpleDraweeView xzCover; TextView xzTitle; public ViewHoler(View itemView) { super(itemView); xzCover = (SimpleDraweeView) itemView.findViewById(R.id.gifview); xzTitle = (TextView) itemView.findViewById(R.id.title); } } public void setOnItemClickListener(OnRecyclerViewItemClickListener onItemClickListener){ this.onItemClickListener = onItemClickListener; } } public class SpacesItemDecoration extends RecyclerView.ItemDecoration { private int space; public SpacesItemDecoration(int space) { this.space=space; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { outRect.left=space; outRect.right=space; outRect.bottom=space; outRect.top=space; // if(parent.getChildAdapterPosition(view)==0){ // } } } public interface OnRecyclerViewItemClickListener { public void onItemClickListener(View itemView,int position); } }
package enem; import java.nio.ByteBuffer; public class Aluno { private static final short LNOME = 50, LENDERECO = 60, LSEXO = 1, LEMAIL = 40; public static final short RECORD_SIZE = 157; private int matricula; // 04 bytes private String nome; // 50 bytes private String endereco; // 60 bytes private short idade; // 02 bytes private String sexo; // 01 byte private String email; // 40 bytes public Aluno(){ this.matricula = 0; String str = ""; this.nome = this.redimensionar(str, LNOME); this.endereco = this.redimensionar(str, LENDERECO); this.idade = 0; this.sexo = this.redimensionar(str, LSEXO); this.email = this.redimensionar(str, LEMAIL); } public Aluno(int matricula, String nome){ this(); this.matricula = matricula; this.nome = this.redimensionar(nome, LNOME); } public Aluno(int matricula, String nome, String endereco, short idade, String sexo, String email){ this.matricula = matricula; this.nome = this.redimensionar(nome, LNOME); this.endereco = this.redimensionar(endereco, LENDERECO); this.idade = idade; this.sexo = this.redimensionar(sexo, LSEXO); this.email = this.redimensionar(email, LEMAIL); } public Aluno(ByteBuffer buf) { byte[] bufStr; this.matricula = buf.getInt(); bufStr = new byte[LNOME]; buf.get(bufStr); this.nome = new String(bufStr); bufStr = new byte[LENDERECO]; buf.get(bufStr); this.endereco = new String(bufStr); this.idade = buf.getShort(); bufStr = new byte[LSEXO]; buf.get(bufStr); this.sexo = new String(bufStr); bufStr = new byte[LEMAIL]; buf.get(bufStr); this.email = new String(bufStr); } public int getMatricula() { return matricula; } public void setMatricula(int matricula) { this.matricula = matricula; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = this.redimensionar(nome, LNOME); } public String getEndereco() { return endereco; } public void setEndereco(String endereco) { this.endereco = this.redimensionar(endereco, LENDERECO); } public short getIdade() { return idade; } public void setIdade(short idade) { this.idade = idade; } public String getSexo() { return sexo; } public void setSexo(String sexo) { this.sexo = this.redimensionar(sexo, LSEXO); } public String getEmail() { return email; } public void setEmail(String email) { this.email = this.redimensionar(email, LEMAIL); } private String redimensionar(String str, int tam){ int dif = tam - str.length(); for (int i = 0; i < dif; i++) str += " "; return str.substring(0,tam); } public ByteBuffer getBuffer(){ ByteBuffer buf = ByteBuffer.allocate(RECORD_SIZE); buf.putInt(this.matricula); buf.put(this.nome.getBytes()); buf.put(this.endereco.getBytes()); buf.putShort(this.idade); buf.put(this.sexo.getBytes()); buf.put(this.email.getBytes()); buf.flip(); return buf; } public boolean equals(Aluno aluno) { return this.matricula == aluno.matricula; } public String toString() { return "Matricula:" + Integer.toString(this.matricula) + "\n" + "Nome :" + this.nome + "\n" + "Enderešo :" + this.endereco + "\n" + "Idade :" + Integer.toString(this.idade) + "\n" + "Sexo :" + this.sexo + "\n" + "E-mail :" + this.email ; } }
import java.util.ArrayList; import java.util.List; import lombok.Getter; @Getter public class Validos { List<Telefone> validos = new ArrayList<>(); public Validos(List<Telefone> telefones){ for(Telefone telefone: telefones) if(telefone.eTelefoneValido()) validos.add(telefone); } }
package com.orlanth23.popularmovie.adapter; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.orlanth23.popularmovie.R; import com.orlanth23.popularmovie.model.Trailer; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; public class TrailerAdapter extends RecyclerView.Adapter<TrailerAdapter.ViewHolder> { private ArrayList<Trailer> trailers; private Context context; public TrailerAdapter(Context p_context, ArrayList<Trailer> p_trailers) { trailers = p_trailers; context = p_context; } // This method will start the youtube activity private static void watchYoutubeVideo(Context context, String id){ Intent appIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:" + id)); Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + id)); try { context.startActivity(appIntent); } catch (ActivityNotFoundException ex) { context.startActivity(webIntent); } } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View itemView = inflater.inflate(R.layout.cardview_trailer, parent, false); return new ViewHolder(itemView); } @Override public void onBindViewHolder(ViewHolder holder, int position) { final Trailer trailer = trailers.get(position); holder.videoTitle.setText(trailer.getName()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { watchYoutubeVideo(context, trailer.getKey()); } }); } @Override public int getItemCount() { return trailers.size(); } class ViewHolder extends RecyclerView.ViewHolder{ @BindView(R.id.video_title) TextView videoTitle; ViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } }
package com.osteching.litemongo; import java.net.UnknownHostException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.mongodb.DB; import com.mongodb.Mongo; import com.mongodb.MongoException; public final class MongoDbConnection { private static final Logger logger = LoggerFactory.getLogger(MongoDbConnection.class); private Mongo mongo = null; private DB db = null; private MongoDbConnection() { try { logger.debug("get MongoDB connection"); mongo = new Mongo(Conf.getInstance().getHost(), Conf.getInstance().getPort()); db = mongo.getDB(Conf.getInstance().getDB()); if (null != Conf.getInstance().getUsername() && 0 != Conf.getInstance().getUsername().trim().length() && null != Conf.getInstance().getPassword() && 0 != Conf.getInstance().getPassword().trim().length()) { boolean authed = db.authenticate(Conf.getInstance().getUsername(), Conf .getInstance().getPassword().toCharArray()); if (!authed) { logger.warn("authentication failed"); throw new IllegalArgumentException( "---authentication with given username and password failed---"); } } } catch (UnknownHostException e) { logger.warn(e.getMessage()); } catch (MongoException e) { logger.warn(e.getMessage()); } } private static final class Holder { private static final MongoDbConnection _conn = new MongoDbConnection(); } public static MongoDbConnection getConn() { return Holder._conn; } public DB getDb() { return db; } public void close() { if (null != db) { db.cleanCursors(true); } if (null != mongo) { mongo.close(); } } // TODO other util method in Mongo }
package lib.basenet.request; /** * Created by zhaoyu1 on 2017/12/11. */ public interface BaseRequestBody { /** * content-type * * @return */ String getBodyContentType(); /** * body内容 * * @return */ byte[] getBody(); }
package DataStructures.arrays; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; /** Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. Example 1: Given intervals [1,3],[6,9] insert and merge [2,5] would result in [1,5],[6,9]. Example 2: Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] would result in [1,2],[3,10],[12,16]. This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. Make sure the returned intervals are also sorted. */ class Interval { int start; int end; Interval(int s, int e) { this.start = s; this.end = e; } } public class MergeIntervals { public ArrayList<Interval> mergeInterval(ArrayList<Interval> list) { ArrayList<Interval> result = new ArrayList<>(); if(list == null || list.size() == 0) return result; Collections.sort(list, new Comparator<Interval>() { @Override public int compare(Interval i1, Interval i2) { return Integer.compare(i1.start, i2.start); } }); Interval prev = list.get(0); for(int i=1; i < list.size(); i++) { Interval curr = list.get(i); if(curr.start > prev.end) { result.add(prev); prev = curr; } else { prev = new Interval(prev.start, Math.max(prev.end, curr.end)); } } result.add(prev); return result; } public static ArrayList<Interval> insertRange(ArrayList<Interval> intervalsList, Interval insert) { ArrayList<Interval> result = new ArrayList<Interval>(); for (Interval interval : intervalsList) { if (interval.end < insert.start) result.add(interval); else if (interval.start > insert.end) { result.add(insert); insert = interval; } else if (interval.end >= insert.start || interval.start <= insert.end) { insert = new Interval(Math.min(interval.start,insert.start), Math.max(interval.end, insert.end)); } } result.add(insert); return result; } public static void main(String ar[]) { MergeIntervals m = new MergeIntervals(); ArrayList<Interval> list = new ArrayList<>(); list.add(new Interval(1,5)); list.add(new Interval(2,3)); //list.add(new Interval(8,10)); //list.add(new Interval(11,18)); //o/p #1,6 #8,10 #15,18 is not needed System.out.print(m.mergeInterval(list)); } }
package com.fb.controller.platform; import com.fb.controller.BaseController; import com.fb.kit.ToolsUtils; import com.fb.model.TItemPaymentOrder; import com.fb.model.TItemPaymentWater; import com.jfinal.ext.route.ControllerBind; import com.jfinal.plugin.activerecord.Page; @ControllerBind(controllerKey = "/platform/merchantOrder") public class OrderController extends BaseController { protected static final com.jfinal.log.Logger LOG = com.jfinal.log.Logger.getLogger(OrderController.class); public void search(){ String sellerMobile = getPara("sellerMobile"); String buyerMobile = getPara("buyerMobile"); String waterId =getPara("waterId"); String oderTime = getPara("orderTime"); String[] orderTime = ToolsUtils.rangeDate(oderTime); String status = getPara("status"); Page<TItemPaymentOrder> page = TItemPaymentOrder.me.findPage(pageSort("id", "desc"),sellerMobile,buyerMobile,waterId,orderTime[0], orderTime[1],status); setAttr("page",page); keepPara("sellerMobile","buyerMobile","waterId","orderTime","status"); } }
package negocios; import dados.IRepositorioMateriaPrima; import exceptions.MateriaPrimaJaExisteException; import exceptions.MateriaPrimaNaoExisteException; import negocios.beans.MateriaPrima; import exceptions.FormatacaoInvalidaException; import java.util.List; public class ControladorMateriaPrimas { IRepositorioMateriaPrima repositorio; public ControladorMateriaPrimas(IRepositorioMateriaPrima instanciaInterface) { if (instanciaInterface != null) { this.repositorio = instanciaInterface; } else { // argumento invalido IllegalArgumentException x = new IllegalArgumentException("Reposit�rio inv�lido."); throw x; } } public void cadastrar(MateriaPrima materiaPrima) throws MateriaPrimaJaExisteException, FormatacaoInvalidaException { if (materiaPrima == null) { throw new FormatacaoInvalidaException(); } else { if (this.repositorio.existe(materiaPrima.getCodigo()) == false) { this.repositorio.inserir(materiaPrima); this.repositorio.salvarArquivo(); } else if (this.repositorio.existe(materiaPrima.getCodigo()) == true) { throw new MateriaPrimaJaExisteException(materiaPrima.getCodigo()); } } } public MateriaPrima buscar(int codigo) throws MateriaPrimaNaoExisteException { if (this.repositorio.existe(codigo) == true) { return this.repositorio.buscar(codigo); } else { throw new MateriaPrimaNaoExisteException(); } } public void remover(MateriaPrima materiaPrima) throws MateriaPrimaNaoExisteException, FormatacaoInvalidaException { if (materiaPrima == null) { throw new FormatacaoInvalidaException(); } else if (this.repositorio.materiaPrimaContem(materiaPrima) == true) { this.repositorio.remover(materiaPrima.getCodigo()); this.repositorio.salvarArquivo(); } else if (this.repositorio.materiaPrimaContem(materiaPrima) == false) { throw new MateriaPrimaNaoExisteException(); } } public void alterar(MateriaPrima novaMateriaPrima) throws MateriaPrimaNaoExisteException, FormatacaoInvalidaException { if (novaMateriaPrima == null) { throw new FormatacaoInvalidaException(); } else if ((novaMateriaPrima != null && this.repositorio.existe(novaMateriaPrima.getCodigo()) == true)) { this.repositorio.alterar(novaMateriaPrima); this.repositorio.salvarArquivo(); } else if ((this.repositorio.existe(novaMateriaPrima.getCodigo()) == false)) { throw new MateriaPrimaNaoExisteException(); } } public int getQuantidade(int codigo) throws MateriaPrimaNaoExisteException { if (this.repositorio.existe(codigo) == true) { MateriaPrima materiaPrima = this.repositorio.buscar(codigo); return materiaPrima.getQuantidade(); } else { throw new MateriaPrimaNaoExisteException(); } } public boolean existe(int codigo) throws MateriaPrimaNaoExisteException { boolean alt = false; if (repositorio.existe(codigo)) { alt = true; } else { throw new MateriaPrimaNaoExisteException(); } return alt; } public List<MateriaPrima> listaMateriaPrimas() { return this.repositorio.listar(); } }
package com.zyzd.glidedemo.ui; import android.app.Activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.zyzd.glidedemo.R; import com.zyzd.glidedemo.transformation.RotateTransformation; public class CustomTransformationsActivity extends Activity { private ImageView mImageViewHorizontal; private ImageView mImageViewVertical; public static final String imageUrl = "http://i.imgur.com/rFLNqWI.jpg"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_custom_transformations); mImageViewHorizontal = (ImageView) findViewById(R.id.imageView_horizontal); mImageViewVertical = (ImageView) findViewById(R.id.imageView_vertical); loadImageOriginal(); loadImageRotated(); } private void loadImageOriginal() { Glide.with(this) .load(imageUrl) .into(mImageViewHorizontal); } private void loadImageRotated() { Glide.with(this) .load(imageUrl) .transform(new RotateTransformation(this, 90f)) .into(mImageViewVertical); } }
package controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import model.Emp; import model.MemberDataBean; import service.MemberService; @Controller @RequestMapping("/member/") public class MemberController { // �α��� ���� ���� ModelAndView mv = new ModelAndView(); @Autowired public MemberService memberservice; @RequestMapping("login") /* 01.로그인 */ public ModelAndView login() throws Exception { mv.clear(); mv.setViewName("user/user_login"); return mv; } @RequestMapping("loginPro") // jsp���� name���� ���� -> loginPro(String m_id, String m_pw, // HttpServletRequest req) public ModelAndView loginPro(String m_id, String m_pw, HttpSession session) throws Exception { System.out.println("==========================================================="); System.out.println(m_id + ":" + m_pw); // 회원/직원 구분 int isMem = memberservice.isMember(m_id); if (isMem == 0) { // 직원로그인 기능 Emp emp = memberservice.empLogin(m_id, m_pw); session.setAttribute("emp", emp); System.out.println("toString 직원" + emp); if (emp == null) { mv.setViewName("redirect:/member/login"); mv.addObject("loginNotOk", "1"); } else { mv.setViewName("redirect:/admin/emp"); } } else { // 회원로그인 기능 MemberDataBean member = memberservice.user_login(m_id, m_pw); session.setAttribute("member", member); System.out.println("toString멤버" + member); if (member == null) { mv.setViewName("redirect:/member/login"); mv.addObject("loginNotOk", "1"); } else { mv.setViewName("redirect:/main"); } } return mv; } @RequestMapping("logout") /* 03. 로그아웃 */ public String logout(HttpServletRequest req, HttpServletResponse res) throws Exception { HttpSession session = req.getSession(false); if (session != null) { session.invalidate(); } return "redirect:/main"; } @RequestMapping("memJoin") /* 회원가입 */ public ModelAndView memJoin(MemberDataBean member) { mv.clear(); // String id = member.getM_id(); // String passwd = member.getM_pw(); mv.setViewName("user/user_join"); return mv; } @RequestMapping("memJoin2") public ModelAndView memJoin2(MemberDataBean member, String wRoadAdderess, String wRestAddress, String wPostCode) throws Exception { mv.clear(); member.setM_add(wPostCode + " " + wRoadAdderess + " " + wRestAddress); member.setE_num("1"); int maxMemNum = memberservice.getMaxNum(); member.setM_num(String.valueOf(maxMemNum + 1)); memberservice.insertMember(member); mv.setViewName("user/user_login"); return mv; } @RequestMapping("memInformation") /* 내정보 */ public ModelAndView memInformation(HttpSession session) { mv.clear(); MemberDataBean member = (MemberDataBean) session.getAttribute("member"); System.out.println(member.getM_add()); String[] addrs = member.getM_add().split(" "); String wRoadAdderess = addrs[1]; String wRestAddress = addrs[2]; String wPostCode = addrs[0]; mv.addObject("wRoadAdderess", wRoadAdderess); mv.addObject("wRestAddress", wRestAddress); mv.addObject("wPostCode", wPostCode); mv.setViewName("user/user_meminformation"); return mv; } @RequestMapping("memUpdate") /* 내정보수정 */ public ModelAndView memUpdate(MemberDataBean member, HttpSession session, String wRoadAdderess, String wRestAddress, String wPostCode) throws Exception { mv.clear(); member.setM_add(wPostCode + " " + wRoadAdderess + " " + wRestAddress); System.out.println(member); memberservice.user_meminformation(member); MemberDataBean memberAfter = memberservice.user_login(member.getM_id(), member.getM_pw()); session.setAttribute("member", memberAfter); String[] addrs = memberAfter.getM_add().split(" "); String wRoad = addrs[1]; String wRest = addrs[2]; String wPost = addrs[0]; mv.addObject("wRoadAdderess", wRoad); mv.addObject("wRestAddress", wRest); mv.addObject("wPostCode", wPost); mv.setViewName("user/user_meminformation"); return mv; } }
package kr.co.shop.batch.kcp.model.master.base; import lombok.Data; import java.io.Serializable; import kr.co.shop.common.bean.BaseBean; @Data public class BaseRvKcpComparison extends BaseBean implements Serializable { /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : KCP거래번호 */ private String kcpDealNum; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 거래일시 */ private java.sql.Timestamp pymntDtm; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 원거래일시 */ private java.sql.Timestamp pymntOrgDtm; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 입금/취소처리일시 */ private java.sql.Timestamp lgdDtm; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 은행입금/취소일시 */ private java.sql.Timestamp lgdBankDtm; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 거래구분 */ private String pymntStatCode; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 주문번호 */ private String orderNum; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 결제금액(입금/취소금액) */ private java.lang.Integer pymntAmt; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 수수료 */ private java.lang.Integer pymntCharge; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 무이자수수료 */ private java.lang.Integer freeCharge; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 부가세 */ private java.lang.Integer pymntSurTax; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 정산금액 */ private java.lang.Integer accountsAmt; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 마감일자 */ private java.sql.Timestamp deadlineDtm; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 수납월 */ private String receiveMonth; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 정산일자 */ private java.sql.Timestamp accountsDtm; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 에스크로수수료 */ private java.lang.Integer escrowCharge; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 에스크로부가세 */ private java.lang.Integer escrowSurtax; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 은행코드 */ private String bankCode; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 가상계좌번호 */ private String lgdAccountnum; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 입금처리고유번호 */ private String lgdCasseqno; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 입금인성명 */ private String lgdPayer; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 할부개월수 */ private String istmtCount; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 승인번호 */ private String prmtNum; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 매입카드사코드 */ private String crdtCardCode; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 가맹점번호 */ private String merchantName; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 상품코드 */ private String prdtCode; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 결제수단 */ private String pymntMeans; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 데이터입력일시 */ private java.sql.Timestamp rgstDtm; }
package Recursion; import java.util.Scanner; public class StringPalin2 { static boolean isPalin(String s,int i,int last){ if(s.charAt(i)!=s.charAt(last)) return false; if(i<last) return isPalin(s, i+1, last-1); return true; } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter the string: "); String s = in.next(); boolean res = isPalin(s, 0, s.length()-1); if(res == true) System.out.println(s+" is a palindrome"); else System.out.println(s+" is not a palindrome"); in.close(); } }
/* * Copyright (c) 2015. * * The author of these files, Austin Wellman, allows modification, reproduction and private use of them. It, derived works, and works including derived files cannot be published to an app store, packaged and redistributed, used commercially, or sublicensed. * * The author is not responsible for anything this software causes to happen and is provided as-is with no guarantee of anything. * * During the building process, gradle pulls the following files covered under the Apache License 2.0 which is located in the root of this repository as the file "included_licenses/APACHE_2.0.txt": * gson * spring-android-core * spring-android-rest-template * support-annotations */ package com.atwelm.aezwidget.responses.interfaces; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import com.atwelm.aezwidget.data.ExecutionResponseCallback; import com.atwelm.aezwidget.responses.generic.GenericExecutionResponse; import org.springframework.core.io.Resource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import java.io.BufferedInputStream; /** * A core cell object that is meant to be contained in a {@link com.atwelm.aezwidget.responses.interfaces.AEZLayout} that * also contains logic to execute network requests based on what the cell is created with */ public abstract class AEZCell { private static final String LOG_TAG = "AEZCell"; private static RestTemplate mRestTemplate; private static RestTemplate getRestTemplate() { if (mRestTemplate == null) { mRestTemplate = new RestTemplate(); } return mRestTemplate; } protected Bitmap mIconBitmap; /** * Gets the URL to execute when the cell is tapped * @return The URL */ public abstract String getExecutionUrl(); /** * Gets the execution type of the URL (GET or POST) to be executed when the cell is tapped * @return the execution type */ public abstract String getExecutionType(); /** * Gets the body to be included with the URL to be executed when the cell is tapped * @return The body data */ public abstract String getExecutionBody(); /** * Gets the headers to be included with the URL to be executed when the cell is tapped * @return The headers */ public abstract HttpHeaders getExecutionHeaders(); /** * Gets the label to be displayed on the cell * @return The user viewable label */ public abstract String getLabel(); /** * Gets the URL of the icon url, if any. Returns null if there is none. * @return The icon url if exists, or null. */ public abstract String getIconUrl(); // TODO: make asynchronous /** * Synchronously gets the icon bitmap, if available. If it has not already been fetched, it may take some time to fetch. * @return */ public final Bitmap getIconBitmap() { String iconUrl = getIconUrl(); if (mIconBitmap == null && iconUrl != null) { Log.d(LOG_TAG, "getIconBitmap at url=\"" + iconUrl + "\""); try { ResponseEntity<Resource> responseEntity = getRestTemplate().getForEntity(iconUrl, Resource.class); BufferedInputStream bis = new BufferedInputStream(responseEntity.getBody().getInputStream()); mIconBitmap = BitmapFactory.decodeStream(bis); return mIconBitmap; } catch (Exception e) { Log.e(LOG_TAG, e.toString()); e.printStackTrace(); mIconBitmap = null; } } return mIconBitmap; } /** * Indicates if it is an executable cell * @return */ public boolean isExecutable() { String executionType = getExecutionType(); String executionUrl = getExecutionUrl(); return executionType != null && executionUrl != null && (executionType.equals("GET") || executionType.equals("POST") || executionType.equals("PUT")); } /** * Executes the URL and associated details for the cell * @param callback The callback when completed */ public final void execute(final ExecutionResponseCallback callback) { if (!isExecutable()) { return; } Thread t = new Thread(new Runnable() { @Override public void run() { try { String executionType = getExecutionType(); String executionUrl = getExecutionUrl(); String executionBody = getExecutionBody(); HttpHeaders executionHeaders = getExecutionHeaders(); HttpEntity<String> requestEntity = new HttpEntity<String>(executionBody, executionHeaders); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<GenericExecutionResponse> responseEntity = restTemplate.exchange(executionUrl, HttpMethod.valueOf(executionType), requestEntity, GenericExecutionResponse.class); int returnStatus = responseEntity.getStatusCode().value(); if (returnStatus <= 200 && returnStatus < 300) { GenericExecutionResponse response = responseEntity.getBody(); if (callback != null) { callback.success(response); } } else { if (callback != null) { callback.failure(returnStatus); } } } catch (HttpStatusCodeException hsce) { callback.failure(hsce.getStatusCode().value()); } catch (RestClientException rce) { // TODO: Make this more specific since it includes scenarios such as when the network cannot be reached callback.failure(-1); } } }); t.start(); } }
/* * 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 diagram; import java.util.ArrayList; /** * * @author Go Eun Sung */ public class Diagram { ArrayList<Layer> diagrams = new ArrayList<>(); //method public void deleteCircle() { for (int i = 0; i < diagrams.size(); i++) { for (int j = 0; j < diagrams.get(i).layers.size(); j++) { if (diagrams.get(i).layers.get(j) instanceof Circle) { diagrams.get(i).layers.remove(j); } } } } // use Visible public void removeLayer() { for (int i = 0; i < diagrams.size(); i++) { if (!diagrams.get(i).isVisible()) { diagrams.remove(i); } } } //clasify public void classify() { ArrayList<Shape> level = new ArrayList(); Diagram d = new Diagram(); Layer s = new Layer(); for (int i = 0; i < this.diagrams.size(); i++) { for (int j = 0; j < this.diagrams.get(i).layers.size(); j++) { level.add(this.diagrams.get(i).layers.get(j)); } } this.diagrams.clear(); s.layers.add(level.get(0)); level.remove(0); for (int j = 0; j < level.size();) { if (level.get(j).getClass() == level.get(level.size() - 1).getClass()) { s.layers.add(level.get(j)); level.remove(j); } else { j++; } d.diagrams.add(s); s.layers.clear(); } for (int i = 0; i < d.diagrams.size() - 1; i++) { this.diagrams.add(d.diagrams.get(i)); } } }
package properties; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JButton; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.util.ArrayList; import net.miginfocom.swing.MigLayout; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class MainWindow { private JFrame frmTerminkalender; private JTable tAppointments; private ArrayList<Appointment> appointments = new ArrayList<>(); /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { MainWindow window = new MainWindow(); window.frmTerminkalender.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public MainWindow() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { //--------------------- Gui initialization -------------------- frmTerminkalender = new JFrame(); frmTerminkalender.setTitle("Terminkalender"); frmTerminkalender.setResizable(false); frmTerminkalender.setBounds(100, 100, 450, 300); frmTerminkalender.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmTerminkalender.getContentPane().setLayout(new MigLayout("", "[grow][][][][][][][][][][][][][]", "[grow][grow][][][][][][][]")); tAppointments = new JTable(); tAppointments.setModel(new DefaultTableModel( new Object[][] { }, new String[] { "Titel", "Zeitpunkt" } )); frmTerminkalender.getContentPane().add(tAppointments, "cell 0 0 14 8,grow"); //------------------ Configuration evaluation ----------------- if(PropertyManager.getProperty("Add")) { JButton btnAdd = new JButton("Add"); frmTerminkalender.getContentPane().add(btnAdd, "cell 11 8"); btnAdd.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { CreateAppointmentDialog dialog = new CreateAppointmentDialog(); dialog.setVisible(true); dialog.addWindowListener(new WindowListener() { @Override public void windowClosed(WindowEvent e) { // TODO Auto-generated method stub appointments.add(dialog.getCreatedAppointment()); updateTable(); } @Override public void windowActivated(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowClosing(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowDeactivated(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowDeiconified(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowIconified(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowOpened(WindowEvent arg0) { // TODO Auto-generated method stub } }); } }); } if(PropertyManager.getProperty("Edit")) { JButton btnEdit = new JButton("Edit"); frmTerminkalender.getContentPane().add(btnEdit, "cell 12 8"); btnEdit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int selectedIndex = tAppointments.getSelectedRow(); if(selectedIndex < appointments.size() && selectedIndex > -1) { Appointment appointment = appointments.get(selectedIndex); CreateAppointmentDialog dialog = new CreateAppointmentDialog(appointment); dialog.setVisible(true); dialog.addWindowListener(new WindowListener() { @Override public void windowClosed(WindowEvent e) { // TODO Auto-generated method stub updateTable(); } @Override public void windowActivated(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowClosing(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowDeactivated(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowDeiconified(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowIconified(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowOpened(WindowEvent arg0) { // TODO Auto-generated method stub } }); } } }); } if(PropertyManager.getProperty("Delete")) { JButton btnDelete = new JButton("Delete"); frmTerminkalender.getContentPane().add(btnDelete, "cell 13 8"); btnDelete.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub int selectedIndex = tAppointments.getSelectedRow(); if(selectedIndex < appointments.size() && selectedIndex > -1) { appointments.remove(selectedIndex); updateTable(); } } }); } } private void updateTable() { DefaultTableModel model = (DefaultTableModel) tAppointments.getModel(); for(int i = 0; i < model.getRowCount(); i++) { model.removeRow(i); } for(int i = 0; i < appointments.size(); i++) { model.addRow(new Object[]{appointments.get(i).getTitle(), appointments.get(i).getTime()}); } } }
package main.com.java.basics.stream; import com.google.common.base.Predicates; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.PredicateUtils; /** * @author Heena Hussain * */ public class RemoveNullFromList { public static void main(String[] args) { List<Integer> list = Lists.newArrayList(null,1,null); // Arrays.asList throw error while (list.remove(null)); System.out.println("Size1: " + list.size()); list = Lists.newArrayList(null,1,null); list.removeAll(Collections.singleton(null)); System.out.println("Size2: " + list.size()); // Using Guava list = Lists.newArrayList(null,1,null); // list.removeIf(Predicates.isNull()); Iterables.removeIf(list, Predicates.isNull()); System.out.println("Size3: " + list.size()); //without modifying the source list List<Integer> newlist = Lists.newArrayList(Iterables.filter(list, Predicates.notNull())); System.out.println("Size4: " + newlist.size()); // Using Apache commons list = Lists.newArrayList(null,1,null); CollectionUtils.filter(list, PredicateUtils.notNullPredicate()); System.out.println("Size5: " + newlist.size()); // USING LAMBDA list = Lists.newArrayList(null,1,null); list = list.stream().filter(Predicates.notNull()).collect(Collectors.toList()); // list = list.parallelStream().filter(Predicates.notNull()).collect(Collectors.toList()); // list.removeIf(Objects::isNull); System.out.println("Size6: " + list.size()); List<Integer> parallel = Lists.newArrayList(null, 1, 2, null, 3, null); List<Integer> listWithoutNulls = parallel.parallelStream() .filter(Objects::nonNull) .collect(Collectors.toList()); } }
package com.example.mysdapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class DrawActivity extends AppCompatActivity { String userGet; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_draw); PaintView paintView = new PaintView(this); setContentView(paintView); } }
package raft.server; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import raft.server.util.Preconditions; import raft.server.util.ThreadFactoryImpl; import java.util.concurrent.*; /** * Author: ylgrgyq * Date: 18/5/12 */ abstract class AsyncProxy { private static final Logger logger = LoggerFactory.getLogger(AsyncProxy.class.getName()); private static final ThreadFactory defaultThreadFactory = new ThreadFactoryImpl("RaftAsyncProxy-"); private static final long DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_MILLIS = 10_000; private final ExecutorService pool; private volatile boolean unexpectedException = false; AsyncProxy() { this(Executors.newSingleThreadExecutor(defaultThreadFactory)); } AsyncProxy(ExecutorService pool) { Preconditions.checkNotNull(pool); this.pool = pool; } CompletableFuture<Void> notify(Runnable job) { if (!unexpectedException) { return CompletableFuture .runAsync(job, pool) .whenComplete((r, ex) -> { if (ex != null) { logger.error("notify failed, will not accept any new notification job afterward", ex); unexpectedException = true; } }); } else { throw new IllegalStateException("proxy shutdown due to unexpected exception, please check log to debug"); } } CompletableFuture<Void> shutdown() { return CompletableFuture .runAsync(pool::shutdown, pool); } }
package com.in.main.service; import java.util.List; import com.in.main.pojo.Employee; public interface EmployeServic { List<Employee> getall(Employee employee); Employee saveemployee(Employee employee); Employee updateemployee(Employee employee); void deleteemployee(int EmployeeId); }
package com.jeremiaslongo.apps.spotifystreamer.model; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import static com.jeremiaslongo.apps.spotifystreamer.util.LogUtils.makeLogTag; public class TrackModel implements Parcelable{ // TAG public static final String TAG = makeLogTag(TrackModel.class); // Keys private static final String KEY_NAME = "name"; private static final String KEY_ALBUM_NAME = "album_name"; private static final String KEY_ALBUM_ART_LARGE = "album_art_large"; private static final String KEY_ALBUM_ART_ICON = "album_art_icon"; private static final String KEY_PREVIEW_URL = "preview_url"; // Data private String name; private String album_name; private String album_art_large; private String album_art_icon; private String preview_url; // Constructor public TrackModel (String n, String an, String aal, String aai, String pu) { this.name = n; this.album_name = an; this.album_art_large = aal; this.album_art_icon = aai; this.preview_url = pu; } public String getName() { return this.name; } public String getAlbumName() { return this.album_name; } public String getAlbumArtLarge() { return this.album_art_large; } public String getAlbumArtIcon() { return this.album_art_icon; } public String getPreviewUrl() { return this.preview_url; } @Override public int describeContents(){ return 0; } @Override public void writeToParcel(Parcel dest, int flags){ // Create a bundle for the key/value pairs Bundle bundle = new Bundle(); // insert the key value pairs to the bundle bundle.putString(KEY_NAME, name); bundle.putString(KEY_ALBUM_NAME, album_name); bundle.putString(KEY_ALBUM_ART_LARGE, album_art_large); bundle.putString(KEY_ALBUM_ART_ICON, album_art_icon); bundle.putString(KEY_PREVIEW_URL, preview_url); // write the key/value pairs to the parcel dest.writeBundle(bundle); } // Parcelable Creator public static final Parcelable.Creator<TrackModel> CREATOR = new Creator<TrackModel>() { @Override public TrackModel createFromParcel(Parcel source) { // read the bundle containing key/value pairs from the parcel Bundle bundle = source.readBundle(); // instantiate a TrackModel using values from the bundle return new TrackModel( bundle.getString(KEY_NAME), bundle.getString(KEY_ALBUM_NAME), bundle.getString(KEY_ALBUM_ART_LARGE), bundle.getString(KEY_ALBUM_ART_ICON), bundle.getString(KEY_PREVIEW_URL) ); } @Override public TrackModel[] newArray(int size) { return new TrackModel[size]; } }; }
/** * Copyright 2016 OKLink 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 com.oklink.bitcoinj.core; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import org.bitcoinj.core.Address; import org.bitcoinj.core.Block; import org.bitcoinj.core.Coin; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.Message; import org.bitcoinj.core.MessageSerializer; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.ProtocolException; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutPoint; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.core.VarInt; import org.bitcoinj.core.VerificationException; import com.oklink.bitcoinj.script.OKScript; import com.oklink.bitcoinj.script.OKSuperKey; //todo ! public class OKTransaction extends Transaction { public OKTransaction(NetworkParameters params, byte[] payload, int offset, Message parent, MessageSerializer setSerializer, int length) throws ProtocolException { super(params, payload, offset, parent, setSerializer, length); // TODO Auto-generated constructor stub } public OKTransaction(NetworkParameters params, byte[] payload, int offset) throws ProtocolException { super(params, payload, offset); // TODO Auto-generated constructor stub } public OKTransaction(NetworkParameters params, byte[] payload, Message parent, MessageSerializer setSerializer, int length) throws ProtocolException { super(params, payload, parent, setSerializer, length); // TODO Auto-generated constructor stub } public OKTransaction(NetworkParameters params, byte[] payloadBytes) throws ProtocolException { super(params, payloadBytes); // TODO Auto-generated constructor stub } public OKTransaction(NetworkParameters params) { super(params); } /** * * @param value * @param address * @param superAddr 超级赎回地址 * @return */ public TransactionOutput addOutput(Coin value, Address address, Address superAddr) { return addOutput(new OKTransactionOutput(params, this, value, address, superAddr)); } /** * * @param value * @param pubkey * @param superAddr 超级赎回地址 * @return */ public TransactionOutput addOutput(Coin value, ECKey pubkey, Address superAddr) { return addOutput(new OKTransactionOutput(params, this, value, pubkey, superAddr)); } @Override public TransactionOutput addOutput(Coin value, Address address) { return this.addOutput(value, address, OKSuperKey.superKeyAddress(getParams())); } @Override public TransactionOutput addOutput(Coin value, ECKey pubkey) { return this.addOutput(value, pubkey, OKSuperKey.superKeyAddress(getParams())); } @Override protected void parse() throws ProtocolException { cursor = offset; version = readUint32(); optimalEncodingMessageSize = 4; // First come the inputs. long numInputs = readVarInt(); optimalEncodingMessageSize += VarInt.sizeOf(numInputs); inputs = new ArrayList<TransactionInput>((int) numInputs); for (long i = 0; i < numInputs; i++) { OKTransactionInput input = new OKTransactionInput(params, this, payload, cursor, serializer); inputs.add(input); long scriptLen = readVarInt(TransactionOutPoint.MESSAGE_LENGTH); optimalEncodingMessageSize += TransactionOutPoint.MESSAGE_LENGTH + VarInt.sizeOf(scriptLen) + scriptLen + 4; cursor += scriptLen + 4; } // Now the outputs long numOutputs = readVarInt(); optimalEncodingMessageSize += VarInt.sizeOf(numOutputs); outputs = new ArrayList<TransactionOutput>((int) numOutputs); for (long i = 0; i < numOutputs; i++) { OKTransactionOutput output = new OKTransactionOutput(params, this, payload, cursor, serializer); outputs.add(output); long scriptLen = readVarInt(8); optimalEncodingMessageSize += 8 + VarInt.sizeOf(scriptLen) + scriptLen; cursor += scriptLen; } lockTime = readUint32(); optimalEncodingMessageSize += 4; length = cursor - offset; } /** * 校验TX超级赎回地址是否为指定公钥地址 * @param superPubHash160 : hash160 bytes */ public void verifySuperPublicKey(byte[] superPubHash160) throws VerificationException{ try { for (TransactionOutput output : outputs) { OKScript pubScript = (OKScript) output.getScriptPubKey(); System.out.println(pubScript); if(pubScript.allowSuperRedeem()){ if(!Arrays.equals(pubScript.getSuperPubKey(), superPubHash160)){ throw new OKVerificationException.UnexpectedSuperPublicKey(); } } } } catch (IllegalArgumentException e) { throw new VerificationException.ExcessiveValue(); } } /** * 校验TX超级赎回地址是否为指定公钥地址 * @param superPubAddress */ public void verifySuperPublicKey(Address superPubAddress) throws VerificationException{ verifySuperPublicKey(superPubAddress.getHash160()); } /** * 校验TX超级赎回地址是否为指定公钥地址 * @param superPubBase58 : base58编码地址 */ public void verifySuperPublicKey(String superPubBase58) throws VerificationException{ verifySuperPublicKey(Address.fromBase58(this.getParams(), superPubBase58)); } }
package com.empresa.entity; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class BoletaJSON { @Id String numBoleta; public String getNumBoleta() { return numBoleta; } public void setNumBoleta(String numBoleta) { this.numBoleta = numBoleta; } }
package com.ywd.blog.service.impl; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ywd.blog.dao.BlogRecommendDao; import com.ywd.blog.entity.BlogRecommend; import com.ywd.blog.service.BlogRecommendService; @Service("blogRecommendService") public class BlogRecommendServiceImpl implements BlogRecommendService { @Autowired private BlogRecommendDao blogRecommendDao; @Override public List<BlogRecommend> list(Map<String, Object> map) { return blogRecommendDao.list(map); } @Override public Long getTotal(Map<String, Object> map) { return blogRecommendDao.getTotal(map); } @Override public int add(BlogRecommend BlogRecommend) { return blogRecommendDao.add(BlogRecommend); } @Override public int update(BlogRecommend BlogRecommend) { return blogRecommendDao.update(BlogRecommend); } @Override public int delete(Integer id) { return blogRecommendDao.delete(id); } }
package com.example.macintosh.moviesprojectstage1; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.example.macintosh.moviesprojectstage1.database.Trailer; import com.squareup.picasso.Picasso; import java.util.List; public class TrailerAdapter extends RecyclerView.Adapter<TrailerAdapter.TrailerViewHolder>{ private List<Trailer> mTrailerList; private Context mContext; TrailerViewHolder trailerViewHolder; private TrailerAdapterOnClickHandler mTrailerAdapterClickHandler; public interface TrailerAdapterOnClickHandler { void onClickHandler(Trailer trailer); } public TrailerAdapter(Context context, TrailerAdapterOnClickHandler trailerAdapterOnClickHandler){ mContext = context; mTrailerAdapterClickHandler = trailerAdapterOnClickHandler; } @NonNull @Override public TrailerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { int layoutIdforListItem = R.layout.list_item_trailers; Context context = parent.getContext(); View view = LayoutInflater.from(context).inflate(layoutIdforListItem,parent,false); trailerViewHolder = new TrailerViewHolder(view); return trailerViewHolder; } @Override public void onBindViewHolder(@NonNull TrailerViewHolder holder, int position) { // Trailer currentTrailer = mTrailerList.get(position); int trailerNumber = position+1; holder.txtView.setText(mContext.getString(R.string.trailer_1_dummy_string)); holder.txtView.append(" "); holder.txtView.append(String.valueOf(trailerNumber)); Picasso.with(mContext).load(R.drawable.youtubeicon).into(holder.mIconYoutube); } @Override public int getItemCount() { if(mTrailerList == null){ return 0; } return mTrailerList.size(); } public void setTrailerData(List<Trailer> trailerList){ mTrailerList = trailerList; notifyDataSetChanged(); } public class TrailerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { ImageView mIconYoutube; TextView txtView; public TrailerViewHolder(View itemView){ super(itemView); this.mIconYoutube = itemView.findViewById(R.id.youtubeicon); this.txtView = itemView.findViewById(R.id.list_itemTV); itemView.setOnClickListener(this); } @Override public void onClick(View view) { int adapterPosition = getAdapterPosition(); Trailer trailer = mTrailerList.get(adapterPosition); mTrailerAdapterClickHandler.onClickHandler(trailer); } } }
package uchet.repository; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import uchet.models.Sku; import java.util.List; public interface SkuRepository extends CrudRepository<Sku, Integer>, JpaSpecificationExecutor<Sku> { Sku findByCode(String code); Sku findByName(String name); List<Sku> findByContractorIdOrderByName(int contractorId); @Query("select MAX(code) from Sku sku") int findMaxSkuCode(); @Query("select s from Sku s join fetch s.unit un join fetch s.contractor sup WHERE un.id = sku_unit_id AND sup.id = contractor_id ORDER BY s.name") @Override List<Sku> findAll(); @Query("SELECT s FROM Sku s WHERE s.id <> :id AND code = :code") Sku findByCodeForUpdate(@Param("code") String code, @Param("id") int id); @Query("SELECT s FROM Sku s WHERE s.id <> :id AND name = :name") Sku findByNameForUpdate(@Param("name") String name, @Param("id") int id); }
package com.ict.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; public class DAO { Connection conn; PreparedStatement pstm; ResultSet rs; private DAO dao ; private Connection getConnection() { try { Class.forName("oracle.jdbc.OracleDriver"); String url = "jdbc:oracle:thin:@localhost:1521:xe"; String user = "nohsam"; String password = "1111"; conn = DriverManager.getConnection(url,user,password); } catch (Exception e) { } return conn; } public ArrayList<VO> getList(){ conn = getConnection(); ArrayList<VO> list = new ArrayList<>(); try { String sql = "select * from members2 order by no"; pstm = conn.prepareStatement(sql); rs = pstm.executeQuery(); while(rs.next()) { VO vo = new VO(); vo.setNo(rs.getString("no")); vo.setId(rs.getString("id")); vo.setPw(rs.getString("pw")); vo.setName(rs.getString("name")); vo.setAge(rs.getString("age")); vo.setAddr(rs.getString("addr")); vo.setRegdate(rs.getString("regdate").substring(0, 10)); list.add(vo); } } catch (Exception e) { } return list; } }
package controller.admin; import dao.AdminAuthDao; import entity.Admin; import helper.SessionManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.DigestUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import validator.form.LoginFormValidator; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; /** * Created by wsit on 6/13/17. */ @Controller @RequestMapping("/admin") public class AdminAuthController { @Autowired private AdminAuthDao adminAuthDao; @RequestMapping( method = RequestMethod.GET, value="/login") public ModelAndView showLogin(){ ModelAndView modelAndView = new ModelAndView("admin/login").addObject("loginForm", new LoginFormValidator()); return modelAndView; } @RequestMapping(method = RequestMethod.POST,value = "/login") public ModelAndView doLogin(HttpServletRequest request, @ModelAttribute("loginForm")@Valid LoginFormValidator loginForm, BindingResult result, RedirectAttributes redirectAttributes){ if(result.hasErrors()){ return new ModelAndView("admin/login").addObject("loginForm",loginForm); } String email = loginForm.getEmail(); String password = loginForm.getPassword(); String md5Password = DigestUtils.md5DigestAsHex(password.getBytes()); Admin admin = adminAuthDao.login(email, md5Password); if(admin == null) { result.rejectValue("email","error.email","Incorrect Email Or Password"); return new ModelAndView("admin/login").addObject("loginForm",loginForm); } else { SessionManager.setAdminOnSession(request, admin); // redirectAttributes.addFlashAttribute("SUCCESS_MESSAGE","Log in Successful"); return new ModelAndView("redirect:/admin"); } } @RequestMapping(value = "/logout", method = RequestMethod.GET) public ModelAndView logout(HttpServletRequest request,RedirectAttributes redirectAttributes){ SessionManager.destroySession(request); return new ModelAndView("redirect:/admin/login"); } }
/* * (C) Copyright ${year} Nuxeo SA (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * Antoine Taillefer */ package org.nuxeo.training.operations; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.ecm.automation.core.Constants; import org.nuxeo.ecm.automation.core.annotations.Context; import org.nuxeo.ecm.automation.core.annotations.Operation; import org.nuxeo.ecm.automation.core.annotations.OperationMethod; import org.nuxeo.ecm.automation.core.annotations.Param; import org.nuxeo.ecm.core.api.ClientException; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DocumentModel; /** * @author Antoine Taillefer (ataillefer@nuxeo.com) */ @Operation(id = TrainingLifecycleOperation.ID, category = Constants.CAT_DOCUMENT, label = "TrainingLifecycleOperation", description = "") public class TrainingLifecycleOperation { private static final Log log = LogFactory.getLog(TrainingLifecycleOperation.class); public static final String ID = "TrainingLifecycleOperation"; @Context protected CoreSession session; @Param(name = "archivePath") protected String archivePath; @OperationMethod public DocumentModel run(DocumentModel input) throws ClientException { // TODO return null; } }
/* * Copyright 1999-2017 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.bvt.sql.mysql.select; import com.alibaba.druid.DbType; import com.alibaba.druid.sql.MysqlTest; import com.alibaba.druid.sql.SQLUtils; import com.alibaba.druid.sql.ast.SQLStatement; public class MySqlSelectTest_297 extends MysqlTest { public void test_0() throws Exception { String sql = "select sn,properties->'$.zoneId',properties->'$.regionId',ip,owner,gmt_create \n" + "from resource_instance where type=16 and (properties->'$.idkp'='1647796581073291')"; SQLStatement stmt = SQLUtils .parseSingleStatement(sql, DbType.mysql); assertEquals("SELECT sn, properties -> '$.zoneId', properties -> '$.regionId'\n" + "\t, ip, owner, gmt_create\n" + "FROM resource_instance\n" + "WHERE type = 16\n" + "\tAND properties -> '$.idkp' = '1647796581073291'", stmt.toString()); } public void test_1() throws Exception { String sql = "select `current_date`, 1 + `current_date`"; SQLStatement stmt = SQLUtils .parseSingleStatement(sql, DbType.mysql); assertEquals("SELECT `current_date`, 1 + `current_date`", stmt.toString()); } public void test_2() throws Exception { String sql = "select `current_timestamp`, 1 + `current_timestamp`"; SQLStatement stmt = SQLUtils .parseSingleStatement(sql, DbType.mysql); assertEquals("SELECT `current_timestamp`, 1 + `current_timestamp`", stmt.toString()); } public void test_3() throws Exception { String sql = "select `current_time`, 1 + `current_time`"; SQLStatement stmt = SQLUtils .parseSingleStatement(sql, DbType.mysql); assertEquals("SELECT `current_time`, 1 + `current_time`", stmt.toString()); } public void test_4() throws Exception { String sql = "select `curdate`, 1 + `curdate`"; SQLStatement stmt = SQLUtils .parseSingleStatement(sql, DbType.mysql); assertEquals("SELECT `curdate`, 1 + `curdate`", stmt.toString()); } public void test_5() throws Exception { String sql = "SELECT `current_date`, 1 + `current_date`"; SQLStatement stmt = SQLUtils .parseSingleStatement(sql, DbType.mysql); assertEquals("SELECT `current_date`, 1 + `current_date`", stmt.toString()); } public void test_6() throws Exception { String sql = "SELECT `time`, a, `date`, b, `timestamp` from t"; SQLStatement stmt = SQLUtils .parseSingleStatement(sql, DbType.mysql); assertEquals("SELECT `time`, a, `date`, b, `timestamp`\n" + "FROM t", stmt.toString()); } public void test_7() throws Exception { String sql = "SELECT `current_date`, a, `current_time`, b, `current_timestamp` from t"; SQLStatement stmt = SQLUtils .parseSingleStatement(sql, DbType.mysql); assertEquals("SELECT `current_date`, a, `current_time`, b, `current_timestamp`\n" + "FROM t", stmt.toString()); } public void test_8() throws Exception { String sql = "SELECT `current_user`, a, `localtime`, b, `localtimestamp` from t"; SQLStatement stmt = SQLUtils .parseSingleStatement(sql, DbType.mysql); assertEquals("SELECT `current_user`, a, `localtime`, b, `localtimestamp`\n" + "FROM t", stmt.toString()); } }