text
stringlengths
10
2.72M
package com.rc.portal.vo; import java.util.Date; public class TMemberBalance { private Long id; private Integer streamType; private Long price; private Long balance; private String remark; private Date createDate; private Long memberId; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getStreamType() { return streamType; } public void setStreamType(Integer streamType) { this.streamType = streamType; } public Long getPrice() { return price; } public void setPrice(Long price) { this.price = price; } public Long getBalance() { return balance; } public void setBalance(Long balance) { this.balance = balance; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } }
package instructable.server.dal; import org.json.JSONObject; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; /** * Created by Amos Azaria on 23-Jul-15. */ public class FieldChanged implements IFieldChanged { private final String fieldName; private final SingleInstance singleInstance; FieldChanged(SingleInstance singleInstance, String fieldName) { this.singleInstance = singleInstance; this.fieldName = fieldName; } /** * May be called also if this is the first time the field is assigned a value. * Called by FieldHolder itself only * @param fieldVal */ @Override public void fieldChanged(JSONObject fieldVal) { //update DB, mayAlreadyExist //insert into instanceValTableName () values (userId,conceptName,instanceName,fieldName,fieldVal.toString()) on duplicate key update fieldJSonValColName=fieldVal.toString() try ( Connection connection = InstDataSource.getDataSource().getConnection(); PreparedStatement pstmt = connection.prepareStatement("insert into "+ DBUtils.instanceValTableName+" (" + DBUtils.userIdColName + "," + DBUtils.conceptColName + "," + DBUtils.instanceColName + "," + DBUtils.fieldColName + "," + DBUtils.fieldJSonValColName + ") values (?,?,?,?,?) on duplicate key update " + DBUtils.fieldJSonValColName + "=?"); ) { pstmt.setString(1, singleInstance.userId); pstmt.setString(2, singleInstance.conceptName); pstmt.setString(3, singleInstance.instanceName); pstmt.setString(4, fieldName); pstmt.setString(5, fieldVal.toString()); pstmt.setString(6, fieldVal.toString()); //PreparedStatement pstmt = con.prepareStatement("update "+instanceValTableName+" set "+fieldJSonValColName+" = "+fieldVal.toString()+" where "+userIdColName+"="+userId + " and "+conceptColName+"="+conceptName+" and "+instanceColName+"="+instanceName+" and "+fieldColName+"="+fieldName); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } }
package org.idea.plugin.atg.psi.reference.contribution; import com.intellij.patterns.XmlPatterns; import com.intellij.psi.*; import com.intellij.psi.xml.XmlAttribute; import com.intellij.psi.xml.XmlAttributeValue; import com.intellij.psi.xml.XmlTag; import com.intellij.psi.xml.XmlTagChild; import com.intellij.util.ProcessingContext; import org.idea.plugin.atg.Constants; import org.idea.plugin.atg.psi.reference.AtgComponentReferenceCreator; import org.idea.plugin.atg.psi.reference.JspFileReference; import org.idea.plugin.atg.psi.reference.WebContextResourceReference; import org.jetbrains.annotations.NotNull; import java.util.HashMap; public class JspUltimateReferenceContributor extends PsiReferenceContributor { @Override public void registerReferenceProviders(@NotNull PsiReferenceRegistrar registrar) { registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue() .withParent(XmlPatterns.xmlAttribute().withLocalName(Constants.Keywords.BEAN_ATTRIBUTE) .withParent(XmlPatterns.xmlTag().withLocalName(Constants.Keywords.IMPORT_BEAN_TAG))), new JspUltimateReferenceProvider()); registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue() .withParent(XmlPatterns.xmlAttribute().withLocalName(Constants.Keywords.NAME_ATTRIBUTE) .withParent(XmlPatterns.xmlTag().withLocalName(Constants.Keywords.DROPLET_TAG))), new JspUltimateImportedReferenceProvider()); registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue() .withParent(XmlPatterns.xmlAttribute().withLocalName(Constants.Keywords.BEAN_ATTRIBUTE)), new JspUltimateImportedReferenceProvider()); registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue() .withParent(XmlPatterns.xmlAttribute().withLocalName(Constants.Keywords.BEAN_VALUE_ATTRIBUTE)), new JspUltimateImportedReferenceProvider()); registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue() .withParent(XmlPatterns.xmlAttribute().withLocalName(Constants.Keywords.PAGE_ATTRIBUTE) .withParent(XmlPatterns.xmlTag().withLocalName(Constants.Keywords.INCLUDE_TAG))), new JspIncludeReferenceProvider()); registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue() .withParent(XmlPatterns.xmlAttribute().withLocalName(Constants.Keywords.SRC_ATTRIBUTE) .withParent(XmlPatterns.xmlTag().withLocalName(Constants.Keywords.SCRIPT_TAG, Constants.Keywords.IMG_TAG))), new WebReferenceProvider()); } static class JspUltimateReferenceProvider extends PsiReferenceProvider { @Override public PsiReference @NotNull [] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) { return AtgComponentReferenceCreator.createReferences((XmlAttributeValue) element, null, new HashMap<>()).toArray(new PsiReference[0]); } } static class JspUltimateImportedReferenceProvider extends PsiReferenceProvider { @Override public PsiReference @NotNull [] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) { HashMap<String, String> importedBeans = new HashMap<>(); XmlTag parentTag = (XmlTag) element.getParent().getParent(); while (parentTag != null) { XmlTagChild prevSiblingInTag = parentTag; while (prevSiblingInTag != null) { prevSiblingInTag = prevSiblingInTag.getPrevSiblingInTag(); if (prevSiblingInTag instanceof XmlTag && Constants.Keywords.IMPORT_BEAN_TAG.equals(((XmlTag) prevSiblingInTag).getLocalName())) { XmlAttribute bean = ((XmlTag) prevSiblingInTag).getAttribute(Constants.Keywords.BEAN_ATTRIBUTE); if (bean != null) { XmlAttributeValue beanValue = bean.getValueElement(); if (beanValue != null) { String beanName = beanValue.getValue(); String shortBeanName = beanName.contains("/") ? beanName.substring(beanName.lastIndexOf('/') + 1) : beanName; importedBeans.put(shortBeanName, beanName); } } } } PsiElement parentElement = parentTag.getParent(); parentTag = parentElement instanceof XmlTag ? (XmlTag) parentElement : null; } return AtgComponentReferenceCreator.createReferences((XmlAttributeValue) element, null, importedBeans).toArray(new PsiReference[0]); } } static class JspIncludeReferenceProvider extends PsiReferenceProvider { @NotNull @Override public PsiReference @NotNull [] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) { return new PsiReference[]{new JspFileReference((XmlAttributeValue) element)}; } } static class WebReferenceProvider extends PsiReferenceProvider { @NotNull @Override public PsiReference @NotNull [] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) { return new PsiReference[]{new WebContextResourceReference((XmlAttributeValue) element)}; } } }
package kr.or.kosta.java5; public class VarargsExample { public static int sum(int[] args) { int sum = 0; for (int i : args) { sum += 1; } return sum; } public static int sum2(int...args) { int sum = 0; for (int i : args) { sum += 1; } return sum; } public static void main(String[] args) { int[] array = {10, 30, 70}; sum(array); sum2(array); } }
package Base; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import Pages.CustomiseStatementPage; import Pages.DepositBalPage; import Pages.EditCustPage; import Pages.LogInPage; import Pages.MiniStatementPage; import Pages.NewAccountPage; import Pages.NewCustRegistration; import Pages.NewCustomerPage; public class TestBase { public static WebDriver driver; public static LogInPage logInPage; public static NewCustomerPage newCustomerPage; public static NewAccountPage newAccountpage; public static DepositBalPage newDepositpage; public static NewCustRegistration newCustRegistrationPage; public static EditCustPage editCustPage; public static CustomiseStatementPage customizePage; public static MiniStatementPage miniStatementPage; @BeforeTest public void testSetup() { driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); driver.get("http://demo.guru99.com/V4/index.php"); logInPage = PageFactory.initElements(driver, LogInPage.class); newCustomerPage = PageFactory.initElements(driver, NewCustomerPage.class); newAccountpage = PageFactory.initElements(driver, NewAccountPage.class); newDepositpage = PageFactory.initElements(driver, DepositBalPage.class); newCustRegistrationPage = PageFactory.initElements(driver, NewCustRegistration.class); editCustPage = PageFactory.initElements(driver, EditCustPage.class); customizePage = PageFactory.initElements(driver, CustomiseStatementPage.class); miniStatementPage = PageFactory.initElements(driver, MiniStatementPage.class); } @AfterTest public void tearDown() { driver.quit(); } }
package GUI; import GUI_Components.BEGEOT_BUNOUF_CustomJFrame; import GUI_Components.BEGEOT_BUNOUF_CustomJTextField; import UsefulFunctions.BEGEOT_BUNOUF_Database_Connection; import javax.swing.*; import java.awt.*; import java.sql.ResultSet; import java.sql.SQLException; /** * Fenêtre permettant de se connecter au logiciel (version 4). * <p> * Cette classe hérite de {@link BEGEOT_BUNOUF_CustomJFrame} * * @author Hugues */ public class BEGEOT_BUNOUF_GUI_Login extends BEGEOT_BUNOUF_CustomJFrame { private static final int DIM_X = 500; private static final int DIM_Y = 500; private JPanel panel; private JLabel labelLogo; public JTextField fieldMatricule; public JPasswordField fieldPassword; public JButton buttonLogin; public JLabel labelIncorrect; /** * Création de l'interface de login * <<<<<<< Updated upstream */ public BEGEOT_BUNOUF_GUI_Login() { super("Login", true, DIM_X, DIM_Y); // Adds the logo image ImageIcon imageIcon = new ImageIcon(PATH_LOGO_FULL); // load the image to a imageIcon Image image = imageIcon.getImage(); // transform it Image newimg = image.getScaledInstance((int) (DIM_X * 0.6), DIM_Y / 3, java.awt.Image.SCALE_SMOOTH); // scale it the smooth way imageIcon = new ImageIcon(newimg); // transform it back labelLogo.setIcon(imageIcon); labelIncorrect.setVisible(false); buttonLogin.addActionListener(e -> loginVerifier()); add(panel); pack(); revalidate(); setVisible(true); } private void createUIComponents() { fieldMatricule = new BEGEOT_BUNOUF_CustomJTextField("NUMERIC", false, 8); fieldPassword = new BEGEOT_BUNOUF_CustomJTextField("ALL", true, 20); } /** * Lance les vérification du login en testant successivement les tables "etudiant" et "professeur" */ private void loginVerifier() { boolean etudiant = loginTest("etudiant"); boolean professeur = loginTest("professeur"); boolean admin = loginTest("administration"); if (etudiant) new BEGEOT_BUNOUF_GUI_USER_Etudiant(Integer.parseInt(fieldMatricule.getText())); else if (professeur) new BEGEOT_BUNOUF_GUI_USER_Professeur(Integer.parseInt(fieldMatricule.getText())); else if (admin) new BEGEOT_BUNOUF_GUI_USER_Admin(); if (etudiant || professeur || admin) dispose(); else labelIncorrect.setVisible(true); } /** * Vérifie si les valeurs entrées correspondent aux valeurs d'une table précise * * @param table Nom de la table SQL à vérifier * @return Retourne true si les valeurs correspondent, sinon retourne false */ private boolean loginTest(String table) { boolean result = false; String inputM = fieldMatricule.getText(); String inputMDP = String.valueOf(fieldPassword.getPassword()); BEGEOT_BUNOUF_Database_Connection database = new BEGEOT_BUNOUF_Database_Connection(); String query = "SELECT Matricule, Password " + "FROM " + table + " " + "WHERE Matricule = " + inputM + " " + "AND Password = '" + inputMDP + "' ;"; if (inputM.length() != 0) { try { ResultSet resultat = database.run_Statement_READ(query); if (resultat.next()) result = true; } catch (SQLException e1) { e1.printStackTrace(); } } database.Database_Deconnection(); return result; } }
import java.util.*; public class Hits { public static void main(String args[]) { Scanner scr = new Scanner(System.in); System.out.println("Enter the size of Square matrix "); int n = scr.nextInt(); int MatrixA[][] = new int[n][n]; int MatrixATrans[][] = new int[n][n]; int simpleh[] = new int[n]; int hub1[] = new int[n]; double hub2[] = new double[n]; int auth1[] = new int[n]; double auth2[] = new double[n]; int toph1 = 0; int topa1 = 0; int toph2 = 0; int topa2 = 0; System.out.println("Enter the elements of the matrix"); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) MatrixA[i][j] = scr.nextInt(); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) MatrixATrans[i][j] = MatrixA[j][i]; for (int i = 0; i < n; i++) simpleh[i] = 1; for (int i = 0; i < n; i++) { int sum = 0; for (int j = 0; j < n; j++) { sum = sum + (MatrixATrans[i][j] * simpleh[i]); } auth1[i] = sum; } for (int i = 0; i < n; i++) { int sum = 0; for (int j = 0; j < n; j++) { sum = sum + (MatrixA[i][j] * auth1[i]); } hub1[i] = sum; } int high1 = 0; int high2 = 0; for (int i = 0; i < n; i++) { if (hub1[i] > hub1[high1]) high1 = i; if (auth1[i] > auth1[high2]) high2 = i; } topa1 = high2; toph1 = high1; int hubtotal = 0; int authtotal = 0; for (int i = 0; i < n; i++) { hubtotal = hubtotal + hub1[i] * hub1[i]; authtotal = authtotal + auth1[i] * auth1[i]; } double modhub = Math.sqrt(hubtotal); double modauth = Math.sqrt(authtotal); for (int i = 0; i < n; i++) { hub2[i] = hub1[i] / modhub; auth2[i] = auth1[i] / modauth; } int high21 = 0; int high22 = 0; for (int i = 0; i < n; i++) { if (hub2[i] > hub2[high21]) high21 = i; if (auth2[i] > auth2[high22]) high22 = i; } topa2 = high22; toph2 = high21; ////////////////////////////////////////////// Printing ////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// System.out.println(); System.out.println(); System.out.println("Entered Matrix"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print(MatrixA[i][j] + " "); System.out.println(); } System.out.println(); System.out.println("Transpose Matrix"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print(MatrixATrans[i][j] + " "); System.out.println(); } System.out.println(); System.out.println("For k = 1"); System.out.println(); for (int i = 0; i < n; i++) { System.out.print("Node " + Integer.toString(i + 1)); System.out.print("\tHub " + Integer.toString(hub1[i])); System.out.print("\tAuthority " + Integer.toString(auth1[i])); System.out.println(); } System.out.println( "Top Hub : Node " + Integer.toString(toph1 + 1) + " : Value : " + Integer.toString(hub1[toph1])); System.out.println( "Top Authority : Node " + Integer.toString(topa1 + 1) + " : Value : " + Integer.toString(auth1[topa1])); System.out.println(); System.out.println("For k = 2"); System.out.println(); for (int i = 0; i < n; i++) { System.out.print("Node " + Integer.toString(i + 1)); System.out.print("\tHub " + String.format("%.4f", hub2[i])); System.out.print("\tAuthority " + String.format("%.4f", auth2[i])); System.out.println(); } System.out.println( "Top Hub : Node " + Integer.toString(toph2 + 1) + " : Value : " + String.format("%.4f", hub2[toph2])); System.out.println("Top Authority : Node " + Integer.toString(topa2 + 1) + " : Value : " + String.format("%.4f", auth2[topa2])); } }
import java.io.IOException; public class Poker{ public static void main(String[] args) { User usuario = new User(); while(usuario.getPoints() != 0 ) { Deck d = new Deck(); String aux; int bet; // Prints how many points the user has System.out.println(usuario); // Read the bet while (true) { try { System.out.println("Type how many points you want to bet"); System.out.print(">> "); bet = EntradaTeclado.leInt(); usuario.makeBet(bet); break; } catch(IOException ex) { System.out.println("Please, type a integer."); } catch(IllegalArgumentException e) { System.out.print("You don't have enough points to "); System.out.println("make this bet. Please, try again"); } } for (int i = 0; i < 3; i++) { // Print the hand System.out.println(); System.out.println(d); System.out.println("Choose the cards you want to change"); System.out.println("Or just press ENTER if you're satisfied"); System.out.print(">> "); // Read the cards to change while(true) { try { aux = EntradaTeclado.leString(); break; } catch(IOException e) { System.out.println("Please only type numbers"); } } // If the user didn't type anything, keep the cards if (aux.length() == 0) break; // Change the cards the user asked for d.changeHand(aux); } // Compute the user's hand usuario.hand(d.getHand()); System.out.println(); } System.out.println("You lost"); } }
package pers.jim.app.model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel(description="返回结果") public class LoginResult { @ApiModelProperty("Token") private String token; public LoginResult(String token) { this.token = token; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } }
package com.example.retail.controllers.retailer.discounts_retailer; import com.example.retail.models.discounts.CustomerOrdersDiscount; import com.example.retail.services.discounts.CustomerOrdersDiscountServices; import com.example.retail.util.CreateResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.List; @RestController @RequestMapping(value = "/api/v1/retailer/discount") @CrossOrigin(origins = "*") public class DiscountsRetailerControler { @Autowired CustomerOrdersDiscountServices customerOrdersDiscountServices; @Autowired CreateResponse createResponse; @RequestMapping(value = "/create", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Object> createSpecialDiscount(HttpServletRequest request, @RequestBody CustomerOrdersDiscount customerOrdersDiscount) { return customerOrdersDiscountServices.createSpecialDiscount(request, customerOrdersDiscount); } @RequestMapping(value = "/findAll", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Object> findAllDiscounts() { try { List<CustomerOrdersDiscount> result = customerOrdersDiscountServices.findAllDiscounts(); int resultCount = result.size(); return ResponseEntity.status(200).body( createResponse.createSuccessResponse( 200, resultCount + " item(s) found", result ) ); } catch (Exception e) { return ResponseEntity.status(500).body( createResponse.createErrorResponse( 500, e.getMessage(), "NA" ) ); } } }
public class MatixMul { public static void main(String[] args) { int i, j, k,term=0; int[][] arr1 = { { 1, 2, 3 }, { 4, 5, 6 } }; int[][] arr2 = { { 3, 2 }, { 6, 5 }, { 1, 4 } }; int[][] res = new int[2][2]; // arr1 =new int[2][3]; // arr2 =new int[3][2]; // arr1= {{1,2,3},{4,5,6}}; // arr2= {{3,2},{6,5},{1,4}}; for (i = 0; i <= 1; i++) { for (j = 0; j <= 1; j++) { for (k = 0; k <= 2; k++) { term =term + arr1[i][k] * arr2[k][j]; res[i][j] = term; } term=0; } } for (i = 0; i <= 1; i++) { for (j = 0; j <= 1; j++) { System.out.print(" "+res[i][j]); } System.out.println(); } } }
package com.sda.javagdy5.factorial; import java.math.BigInteger; public class FactorialIterative implements Factorial { @Override public BigInteger calculate(int number) { BigInteger currentValue = BigInteger.ONE; for (int i = 0; i < number; i++) { currentValue = currentValue.multiply(BigInteger.valueOf(i + 1)); } return currentValue; } }
package com.mengxuegu.springboot.filter; import javax.servlet.*; import java.io.IOException; /** * 自定义Filter * @Author: yaya * @Description: * @Date: Create in 下午 08:12 2019/11/3 */ public class MyFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("Filter 过滤完成"); } @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("Filter 初始化开始"); } @Override public void destroy() { System.out.println("Filter 销毁"); } }
/** * Solutii Ecommerce, Automatizare, Validare si Analiza | Seava.ro * Copyright: 2013 Nan21 Electronics SRL. All rights reserved. * Use is subject to license terms. */ package seava.ad.business.api.security; import java.util.List; import seava.ad.domain.impl.security.AccessControl; import seava.ad.domain.impl.security.AccessControlDs; import seava.j4e.api.service.business.IEntityService; /** * Interface to expose business functions specific for {@link AccessControlDs} domain * entity. */ public interface IAccessControlDsService extends IEntityService<AccessControlDs> { /** * Find by unique key */ public AccessControlDs findByUnique(AccessControl accessControl, String dsName); /** * Find by unique key */ public AccessControlDs findByUnique(Long accessControlId, String dsName); /** * Find by reference: accessControl */ public List<AccessControlDs> findByAccessControl(AccessControl accessControl); /** * Find by ID of reference: accessControl.id */ public List<AccessControlDs> findByAccessControlId(String accessControlId); }
package com.mediacom.repo; import java.util.List; import javax.persistence.EntityManager; //import javax.persistence.criteria.CriteriaBuilder; //import javax.persistence.criteria.CriteriaQuery; //import javax.persistence.criteria.Root; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import com.mediacom.domain.Member; //import com.mediacom.domain.MemberRowMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; //import com.mediacom.util.ApplicationContextProvider; //import org.springframework.context.ApplicationContext; //import org.springframework.context.ApplicationContextAware; //meat and potatoes - here you'll see why this is using hibernate as opposed to just straight up jdbc work..tldr; it's just cleaner and seperated @Repository //interchangable with Component which is generic, @repo means this is on the persistance (e.g. data accessing) level, @controller aplies to the presentation level, and @service applies to the web service level @Transactional //this class will be dealing with adding, removing ,etc... public class MemberDaoImpl implements MemberDao { private final static Logger log = LoggerFactory.getLogger(MemberDaoImpl.class); //stuff gets written to the jboss /log folder file @Autowired private EntityManager em; //persists in a session then dies @Autowired private JdbcTemplate jdbcTemplate; @SuppressWarnings({ "unchecked", "rawtypes" }) public Member findById(int id) { //Hibernate persistant (right) way return em.find(Member.class, id); //JDBC way - e.g. specific query using what's set up from the application config /* Member searchResult = new Member(); String sql = "SELECT * FROM MEMBER WHERE ID=?"; try{ searchResult = (Member)jdbcTemplate.queryForObject( sql, new Object[] { id }, new BeanPropertyRowMapper(Member.class)); }catch(Exception e){ System.out.println("Issue searching the database! : " + searchResult.toString()); log.error("Issue inserting into database! : " + searchResult.toString()); e.printStackTrace(); } return searchResult; */ } @SuppressWarnings({ "unchecked", "rawtypes" }) public Member findByEmail(String email) { //Correct Hibernate way CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Member> criteria = builder.createQuery(Member.class); Root<Member> member = criteria.from(Member.class); /* * Swap criteria statements if you would like to try out type-safe criteria queries, a new * feature in JPA 2.0 criteria.select(member).orderBy(cb.asc(member.get(Member_.name))); */ criteria.select(member).where(builder.equal(member.get("email"), email)); return em.createQuery(criteria).getSingleResult(); //JDBC Way /* Member searchResult = new Member(); String sql = "SELECT * FROM MEMBER WHERE EMAIL=?"; try{ searchResult = (Member)jdbcTemplate.queryForObject( sql, new Object[] { email }, new BeanPropertyRowMapper(Member.class)); }catch(Exception e){ System.out.println("Issue searching the database! : " + searchResult.toString()); log.error("Issue inserting into database! : " + searchResult.toString()); e.printStackTrace(); } System.out.println("Search Results : " + searchResult.getName()); return searchResult; */ } @SuppressWarnings({ "rawtypes", "unchecked" }) public List<Member> findAllOrderedByName() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Member> criteria = cb.createQuery(Member.class); Root<Member> member = criteria.from(Member.class); /* * Swap criteria statements if you would like to try out type-safe criteria queries, a new * feature in JPA 2.0 criteria.select(member).orderBy(cb.asc(member.get(Member_.name))); */ criteria.select(member).orderBy(cb.asc(member.get("name"))); return em.createQuery(criteria).getResultList(); /* List<Member> members = null; String sql = "SELECT * FROM MEMBER ORDER BY NAME ASC"; try{ members = jdbcTemplate.query(sql, new BeanPropertyRowMapper(Member.class)); }catch(Exception e){ System.out.println("Issue searching the database!"); log.error("Issue inserting into database!"); e.printStackTrace(); } return members; */ } public void register(Member member) { em.persist(member); log.info("Attempting to register a new member - " + member.getName() + " " + member.getId()); //Below would be required if jdbcTemplate wasn't autowired from applicationContext already /* String sql = "INSERT INTO member (name, email, phone_number)" + " VALUES (?, ?, ?)"; try{ jdbcTemplate.update(sql, member.getName(), member.getEmail(), member.getPhoneNumber()); }catch(Exception e){ System.out.println("Issue inserting into database! : " + member.toString()); log.error("Issue inserting into database! : " + member.toString()); e.printStackTrace(); } */ } public void delete(Member member){ em.remove(member); /* String sql = "DELETE FROM member WHERE contact_id=?"; try{ jdbcTemplate.update(sql, member.getId()); }catch(Exception e){ System.out.println("Issue deleting from the database! : " + member.toString()); log.error("Issue deleting from the database! : " + member.toString()); e.printStackTrace(); } */ } }
package com.farm.monitor; import java.util.List; import com.farm.db.DataIdValue; import com.farm.db.DatabaseHandler; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; /* * Activity for creating a new field */ public class CreateFieldActivity extends Activity implements OnClickListener { Spinner farmSpinner; EditText fieldNameEditText; Button saveFieldButton; DatabaseHandler db; Intent intent; Bundle b; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_field); initializeControls(); initialize(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.create_field, menu); return true; } /* * creates activity controls */ void initializeControls() { farmSpinner = (Spinner) findViewById(R.id.spinnerCreateFieldFarmName); fieldNameEditText = (EditText) findViewById(R.id.editTextCreateFieldFieldName); saveFieldButton = (Button) findViewById(R.id.buttonCreateFieldSaveField); saveFieldButton.setOnClickListener(this); } void initialize() { getActionBar().hide(); db = new DatabaseHandler(); initSpinners(); intent = new Intent(); } private void initSpinners() { try { List<DataIdValue> farms = getFarms(); ArrayAdapter<DataIdValue> dataAdapter = new ArrayAdapter<DataIdValue>(this, R.layout.spinnertext, farms); farmSpinner.setAdapter(dataAdapter); } catch (Exception e) { Toast.makeText(this, "" + e, Toast.LENGTH_LONG).show(); System.err.println(e); } } /* * gets all farms */ public List<DataIdValue> getFarms() { return db.getAllFarms(); } /* * gets text from controls and creates a new field */ @Override public void onClick(View v) { if (v.equals(saveFieldButton)) { if (fieldNameEditText.getText().toString().equals("") == true) { Toast.makeText(this, "Enter Farm Name", Toast.LENGTH_LONG).show(); return; } String farmName = farmSpinner.getSelectedItem().toString(); String fieldName = fieldNameEditText.getText().toString().trim(); saveField(farmName, fieldName); intent.setClass(getApplicationContext(), CreatePerimeterActivity.class); startActivity(intent); this.finish(); } } /* * Saves field information to database */ public long saveField(String farmName, String fieldName) { try { int farmId = db.getFarmId(farmName); long fieldId = db.saveField(farmId, 0, fieldName); intent.putExtra("farmid", farmId); intent.putExtra("fieldid", fieldId); intent.putExtra("placetype", 2); return fieldId; } catch (Exception e) { Toast.makeText(this, "" + e, Toast.LENGTH_LONG).show(); } return -1; } }
/* * UniTime 3.5 (University Timetabling Application) * Copyright (C) 2014, UniTime LLC, and individual contributors * as indicated by the @authors tag. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.unitime.timetable.spring.security; import java.util.List; import java.util.Map; import org.jasig.cas.client.validation.Assertion; import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken; import org.springframework.security.core.userdetails.AuthenticationUserDetailsService; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.unitime.commons.Debug; import org.unitime.timetable.defaults.ApplicationProperty; import org.unitime.timetable.interfaces.ExternalUidTranslation; import org.unitime.timetable.interfaces.ExternalUidTranslation.Source; import org.unitime.timetable.security.context.UniTimeUserContext; @Service("unitimeAuthenticationUserDetailsService") public class UniTimeAuthenticationUserDetailsService implements AuthenticationUserDetailsService<CasAssertionAuthenticationToken> { private ExternalUidTranslation iTranslation = null; public UniTimeAuthenticationUserDetailsService() { if (ApplicationProperty.ExternalUserIdTranslation.value()!=null) { try { iTranslation = (ExternalUidTranslation)Class.forName(ApplicationProperty.ExternalUserIdTranslation.value()).getConstructor().newInstance(); } catch (Exception e) { Debug.error("Unable to instantiate external uid translation class, "+e.getMessage()); } } } @Override public UserDetails loadUserDetails(CasAssertionAuthenticationToken token) throws UsernameNotFoundException { Assertion assertion = token.getAssertion(); Map attributes = assertion.getPrincipal().getAttributes(); String userId = token.getName(); if (ApplicationProperty.AuthenticationCasIdAttribute.value() != null) { Object value = attributes.get(ApplicationProperty.AuthenticationCasIdAttribute.value()); if (value != null) { if (value instanceof List) { for (Object o: ((List)value)) { userId = o.toString(); break; } } else { userId = value.toString(); } } } else if (iTranslation != null) { userId = iTranslation.translate(userId, Source.LDAP, Source.User); } String name = null; if (ApplicationProperty.AuthenticationCasNameAttribute.value() != null) { Object value = attributes.get(ApplicationProperty.AuthenticationCasNameAttribute.value()); if (value != null) { if (value instanceof List) { for (Object o: ((List)value)) { name = o.toString(); break; } } else { name = value.toString(); } } } if (ApplicationProperty.AuthenticationCasIdTrimLeadingZerosFrom.isTrue()) { while (userId.startsWith("0")) userId = userId.substring(1); } return new UniTimeUserContext(userId, token.getName(), name, null); } }
package com.ibeiliao.pay.impl.service; import com.ibeiliao.order.utils.OrderNO; import com.ibeiliao.pay.ServiceException; import com.ibeiliao.pay.api.ApiCode; import com.ibeiliao.pay.api.ApiResultBase; import com.ibeiliao.pay.api.Constants; import com.ibeiliao.pay.api.dto.request.GetPaymentParamRequest; import com.ibeiliao.pay.api.dto.request.PaymentNotifyRequest; import com.ibeiliao.pay.api.dto.response.GetPaymentParamResponse; import com.ibeiliao.pay.api.dto.response.PaymentNotifyResponse; import com.ibeiliao.pay.api.enums.BalanceType; import com.ibeiliao.pay.api.enums.PayCode; import com.ibeiliao.pay.api.enums.UserType; import com.ibeiliao.pay.balance.impl.dao.SchoolBalanceDao; import com.ibeiliao.pay.balance.impl.entity.SchoolBalancePO; import com.ibeiliao.pay.common.utils.DateUtil; import com.ibeiliao.pay.impl.DeviceSource; import com.ibeiliao.pay.impl.dao.AlipayRecordDao; import com.ibeiliao.pay.impl.dao.JdpayRecordDao; import com.ibeiliao.pay.impl.dao.JhjUserDao; import com.ibeiliao.pay.impl.dao.PayRecordDao; import com.ibeiliao.pay.impl.entity.AlipayRecordPO; import com.ibeiliao.pay.impl.entity.JdpayRecordPO; import com.ibeiliao.pay.impl.entity.JhjUserPO; import com.ibeiliao.pay.impl.entity.PayRecordPO; import com.ibeiliao.pay.impl.thirdpay.PayUtil; import com.ibeiliao.pay.impl.thirdpay.alipay.AlipayNotify; import com.ibeiliao.pay.impl.thirdpay.jdpay.JdpayNotify; import com.ibeiliao.pay.impl.thirdpay.jdpay.response.JdpayNotifyResponse; import com.ibeiliao.pay.impl.thirdpay.jdpay.response.PayTradeVo; import com.ibeiliao.pay.impl.thirdpay.jdpay.response.Result; import com.ibeiliao.pay.impl.thirdpay.jhj.JhjAsyncResponse; import com.ibeiliao.pay.impl.thirdpay.jhj.JhjCore; import com.ibeiliao.pay.impl.thirdpay.jhj.JhjSyncResponse; import com.ibeiliao.platform.context.PlatformContext; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.text.SimpleDateFormat; import java.util.*; /** * PaymentNotifyService 支付回调业务测试 * * 测试环境:本地 MySQL、ZooKeeper,启动 id-generator-impl * <pre> * 对于报错:java.lang.VerifyError: Expecting a stackmap frame at branch target * 增加VM参数:-noverify ,因为JDK7 开始 class 格式增加了 stackmap,用于校验byte code是否正确 * </pre> * @author linyi 2016/7/15 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath*:spring-context-consumer.xml") @PrepareForTest( { JhjCore.class }) public class PaymentNotifyServiceTest { @Rule public PowerMockRule rule = new PowerMockRule(); @Autowired private PaymentNotifyService paymentNotifyService; @Autowired private PaymentService paymentService; @Autowired private SchoolBalanceDao schoolBalanceDao; @Autowired private AlipayRecordDao alipayRecordDao; @Autowired private JdpayRecordDao jdpayRecordDao; @Autowired private PayRecordDao payRecordDao; @Autowired private JhjUserDao jhjUserDao; @Before public void init() { PowerMockito.mockStatic(JhjCore.class); } /** * 测试招行一网通回调,参数为null的情况 * * 期望结果:抛出 ServiceException * @throws Exception */ @Test(expected = ServiceException.class) public void testCmbNotifyWithNullRequest() throws Exception { paymentNotifyService.cmbNotify(null); } /** * 测试招行一网通回调,参数为null的情况 * 期望结果:抛出 ServiceException * @throws Exception */ @Test(expected = ServiceException.class) public void testCmbNotifyWithErrorParameter() throws Exception { PaymentNotifyRequest request = new PaymentNotifyRequest(); paymentNotifyService.cmbNotify(request); } /** * 测试招行一网通回调,参数正常的情况 * 期望结果:处理成功,并且 seller 增加余额 * @throws Exception */ @Test public void testCmbNotify() throws Exception { Random rand = new Random(); long sellerId = System.currentTimeMillis(); long amount = 1000 + rand.nextInt(500); long orderNo = createPaymentRequest(sellerId, amount, PayCode.CMB, Constants.BIZ_TYPE_KINDERGARTEN_FEE); long oldBalance = getBalance(sellerId, BalanceType.CAN_BE_WITHDRAW_BALANCE); PaymentNotifyRequest request = createCmbPaymentNotifyRequest(orderNo, amount); PaymentNotifyResponse response = paymentNotifyService.cmbNotify(request); Assert.assertTrue(ApiResultBase.isSuccess(response)); long newBalance = getBalance(sellerId, BalanceType.CAN_BE_WITHDRAW_BALANCE); Assert.assertTrue(oldBalance + amount == newBalance); } /** * 测试支付宝的回调:等待买家支付的状态 AlipayNotify.WAIT_BUYER_PAY * 期望结果:处理成功,但幼儿园的余额不会增加 * @throws Exception */ @Test public void testAlipayNotifyForWaitBuyerPay() throws Exception { Random rand = new Random(); long sellerId = System.currentTimeMillis(); long amount = 1000 + rand.nextInt(500); long tradeFee = PayUtil.getAlipayTradeFee(amount); long orderNo = createPaymentRequest(sellerId, amount, PayCode.ALIPAY, Constants.BIZ_TYPE_KINDERGARTEN_FEE); long oldBalance = getBalance(sellerId, BalanceType.CAN_BE_WITHDRAW_BALANCE); // 支付宝的回调金额要加上 tradeFee PaymentNotifyRequest request = createPaymentNotifyRequest(orderNo, amount + tradeFee, AlipayNotify.WAIT_BUYER_PAY); PaymentNotifyResponse response = paymentNotifyService.alipayNotify(request); Assert.assertTrue(ApiResultBase.isSuccess(response)); // 幼儿园的金额不变 long newBalance = getBalance(sellerId, BalanceType.CAN_BE_WITHDRAW_BALANCE); Assert.assertTrue(oldBalance == newBalance); } /** * 测试京东支付的回调:等待买家支付的状态 JdpayNotify.TRADE_WAITING * 期望结果:处理成功,但幼儿园的余额不会增加 * @throws Exception */ @Test public void testJdpayNotifyForWaitBuyerPay() throws Exception { Random rand = new Random(); long sellerId = System.currentTimeMillis(); long amount = 1000 + rand.nextInt(500); long orderNo = createPaymentRequest(sellerId, amount, PayCode.JDPAY, Constants.BIZ_TYPE_KINDERGARTEN_FEE); long oldBalance = getBalance(sellerId, BalanceType.CAN_BE_WITHDRAW_BALANCE); JdpayNotifyResponse notifyResponse = createJdpayNotifyRequest(orderNo, amount, String.valueOf(JdpayNotify.TRADE_WAITING)); PaymentNotifyResponse response = paymentNotifyService.jdpayAsyncNotify(notifyResponse,"172.168.2.127"); Assert.assertTrue(ApiResultBase.isSuccess(response)); // 幼儿园的金额不变 long newBalance = getBalance(sellerId, BalanceType.CAN_BE_WITHDRAW_BALANCE); Assert.assertTrue(oldBalance == newBalance); } /** * 测试京东支付回调:交易成功 JdpayNotify.TRADE_SUCCESS * 期望结果:处理成功,幼儿园的余额增加,但不包括费率 */ @Test public void testJdpayNotifyForTradeSuccess() throws Exception { long sellerId = System.currentTimeMillis(); testJdpayNotifyForSuccess(sellerId, JdpayNotify.TRADE_SUCCESS); } /** * 测试支付宝回调:交易成功 AlipayNotify.TRADE_SUCCESS * 支付宝 + 缴费会产生费率 * 期望结果:处理成功,幼儿园的余额增加,但不包括费率 * @throws Exception */ @Test public void testAlipayNotifyForTradeSuccess() throws Exception { long sellerId = System.currentTimeMillis(); testAlipayNotifyForSuccess(sellerId, AlipayNotify.TRADE_SUCCESS); } /** * 测试支付宝回调:交易结束 AlipayNotify.TRADE_FINISHED * 期望结果:处理成功,幼儿园的余额增加,但不包括费率 * @throws Exception */ @Test public void testAlipayNotifyForTradeFinished() throws Exception { long sellerId = System.currentTimeMillis(); testAlipayNotifyForSuccess(sellerId, AlipayNotify.TRADE_FINISHED); } /** * 测试支付宝回调:交易结束 AlipayNotify.TRADE_FINISHED,但金额是对不上的情况。 * 期望结果:失败 * @throws Exception */ @Test(expected = ServiceException.class) public void testAlipayNotifyForWithWrongAmount() throws Exception { Random rand = new Random(); long sellerId = System.currentTimeMillis(); long amount = 1000 + rand.nextInt(500); long orderNo = createPaymentRequest(sellerId, amount, PayCode.ALIPAY, Constants.BIZ_TYPE_KINDERGARTEN_FEE); // 回调里,金额相差1 long tmpAmount = amount + PayUtil.getAlipayTradeFee(amount) + 1; PaymentNotifyRequest request = createPaymentNotifyRequest(orderNo, tmpAmount, AlipayNotify.TRADE_FINISHED); paymentNotifyService.alipayNotify(request); } /** * 功能:测试金惠家的支付回调功能,支付成功的正常情况 * 预期结果:在所有参数正确的情况下,回调成功,幼儿园金额增加 * @author linyi 2016-08-18 */ @Test public void testJhjNotifyForSuccess() { Random rand = new Random(); long sellerId = System.currentTimeMillis(); long amount = 1000 + rand.nextInt(500); long orderNo = createPaymentRequest(sellerId, amount, PayCode.JHJ, Constants.BIZ_TYPE_KINDERGARTEN_FEE); // mock 验签功能 PowerMockito.when(JhjCore.toJhjAsyncResponse("test")) .thenReturn(createJhjAsyncResponse(orderNo, amount, JhjAsyncResponse.SUCCESS)); PowerMockito.when(JhjCore.isWaitBuyerPay(JhjAsyncResponse.SUCCESS)).thenReturn(false); PaymentNotifyRequest request = createJhjNotifyRequest("test"); long oldBalance = getBalance(sellerId, BalanceType.CAN_BE_WITHDRAW_BALANCE); PaymentNotifyResponse response = paymentNotifyService.jhjAsyncNotify(request); Assert.assertTrue(ApiResultBase.isSuccess(response)); // 幼儿园的金额要匹配 long newBalance = getBalance(sellerId, BalanceType.CAN_BE_WITHDRAW_BALANCE); Assert.assertTrue(oldBalance + amount == newBalance); // 对比 PayRecord 的数据 PayRecordPO payRecordPO = payRecordDao.getByOrderNo(orderNo); Assert.assertNotNull(payRecordPO); Assert.assertTrue(payRecordPO.getOriginAmount() == amount); Assert.assertTrue(payRecordPO.getAmount() == amount); // 不应有交易费率 Assert.assertTrue(payRecordPO.getTradeFee() == 0); Assert.assertTrue(payRecordPO.getPayCode() == PayCode.JHJ.getCode()); } /** * 功能:测试金惠家的支付回调功能,等待买家支付的正常情况 * 预期结果:在所有参数正确的情况下,回调成功,幼儿园金额不变 * @author linyi 2016-08-19 */ @Test public void testJhjNotifyForWaitBuyerPay() { Random rand = new Random(); long sellerId = System.currentTimeMillis(); long amount = 1000 + rand.nextInt(500); long orderNo = createPaymentRequest(sellerId, amount, PayCode.JHJ, Constants.BIZ_TYPE_KINDERGARTEN_FEE); // mock 验签功能 PowerMockito.when(JhjCore.toJhjAsyncResponse("test")) .thenReturn(createJhjAsyncResponse(orderNo, amount, JhjAsyncResponse.WAIT_BUYER_PAY)); PowerMockito.when(JhjCore.isWaitBuyerPay(JhjAsyncResponse.WAIT_BUYER_PAY)).thenReturn(true); PaymentNotifyRequest request = createJhjNotifyRequest("test"); long oldBalance = getBalance(sellerId, BalanceType.CAN_BE_WITHDRAW_BALANCE); PaymentNotifyResponse response = paymentNotifyService.jhjAsyncNotify(request); Assert.assertTrue(ApiResultBase.isSuccess(response)); // 幼儿园的金额要匹配 long newBalance = getBalance(sellerId, BalanceType.CAN_BE_WITHDRAW_BALANCE); Assert.assertTrue(oldBalance == newBalance); } /** * 功能:测试金惠家的支付回调功能,支付成功但金额错误的情况 * 预期结果:回调失败 * @author linyi 2016-08-19 */ @Test(expected = ServiceException.class) public void testJhjNotifyForWrongAmount() { Random rand = new Random(); long sellerId = System.currentTimeMillis(); long amount = 1000 + rand.nextInt(500); long orderNo = createPaymentRequest(sellerId, amount, PayCode.JHJ, Constants.BIZ_TYPE_KINDERGARTEN_FEE); // mock 验签功能 // 金额加上一分钱 PowerMockito.when(JhjCore.toJhjAsyncResponse("test")) .thenReturn(createJhjAsyncResponse(orderNo, amount + 1, JhjAsyncResponse.SUCCESS)); PowerMockito.when(JhjCore.isWaitBuyerPay(JhjAsyncResponse.SUCCESS)).thenReturn(false); PaymentNotifyRequest request = createJhjNotifyRequest("test"); paymentNotifyService.jhjAsyncNotify(request); } /** * 功能:测试金惠家的签约(绑卡)回调功能,测试绑卡成功的情况 * 预期结果:绑卡成功,并保存bindId */ @Test public void testJhjContractNotify() { short userType = UserType.NORMAL_USER.getType(); long userId = System.currentTimeMillis(); // mock 验签功能 JhjSyncResponse bindCardResponse = createBindCardJhjSyncResponse(userType, userId); PowerMockito.when(JhjCore.decodeBindCard("test")) .thenReturn(bindCardResponse); PaymentNotifyRequest request = createJhjNotifyRequest("test"); PaymentNotifyResponse response = paymentNotifyService.jhjContractNotify(request); Assert.assertTrue(ApiResultBase.isSuccess(response)); JhjUserPO jhjUserPO = jhjUserDao.getByTypeAndUserId(userType, userId); Assert.assertNotNull(jhjUserPO); Assert.assertEquals(bindCardResponse.getBindId(), jhjUserPO.getBindId()); } /** * 功能:测试金惠家的签约(绑卡)回调功能,测试金惠家返回用户ID错误的情况 * 预期结果:失败并抛出异常 */ @Test(expected = ServiceException.class) public void testJhjContractNotifyWithWrongUserId() { // mock 验签功能 JhjSyncResponse bindCardResponse = new JhjSyncResponse(); bindCardResponse.setOriUserId("10101"); PowerMockito.when(JhjCore.decodeBindCard("test")) .thenReturn(bindCardResponse); PaymentNotifyRequest request = createJhjNotifyRequest("test"); paymentNotifyService.jhjContractNotify(request); } /** * 功能:测试金惠家的签约(绑卡)回调功能,测试金惠家返回bindId错误的情况 * 预期结果:失败并抛出异常 */ @Test(expected = ServiceException.class) public void testJhjContractNotifyWithWrongBindId() { short userType = UserType.NORMAL_USER.getType(); long userId = System.currentTimeMillis(); // mock 验签功能 JhjSyncResponse bindCardResponse = createBindCardJhjSyncResponse(userType, userId); bindCardResponse.setBindId(""); PowerMockito.when(JhjCore.decodeBindCard("test")) .thenReturn(bindCardResponse); PaymentNotifyRequest request = createJhjNotifyRequest("test"); paymentNotifyService.jhjContractNotify(request); } // --------------- private methods /** * 创建绑卡的 response,只需要 oriUserId 和 bindId * @return */ private JhjSyncResponse createBindCardJhjSyncResponse(short userType, long userId) { JhjSyncResponse response = new JhjSyncResponse(); response.setBindId(UUID.randomUUID().toString()); response.setOriUserId(userType + "_" + userId); return response; } /** * 创建一个 JhjAsyncResponse 对象,用于测试 * @param orderNo 支付平台订单号 * @param amount 金额:分 * @param status 订单交易状态,例如:JhjAsyncResponse.SUCCESS * @return */ private JhjAsyncResponse createJhjAsyncResponse(long orderNo, long amount, int status) { JhjAsyncResponse response = new JhjAsyncResponse(); response.setOrderId(orderNo + ""); response.setAmount(amount); response.setStatus(status); return response; } /** * 测试 [支付宝] 成功 [缴费] 的情况 * 期望结果:处理成功,幼儿园的余额增加,但不包括费率 * @param sellerId 买家ID * @param tradeStatus 必须传入 AlipayNotify.TRADE_FINISHED 或 AlipayNotify.TRADE_SUCCESS */ private void testAlipayNotifyForSuccess(long sellerId, String tradeStatus) { Assert.assertTrue(AlipayNotify.TRADE_FINISHED.equals(tradeStatus) || AlipayNotify.TRADE_SUCCESS.equals(tradeStatus)); Random rand = new Random(); long amount = 1000 + rand.nextInt(500); long tradeFee = PayUtil.getAlipayTradeFee(amount); long orderNo = createPaymentRequest(sellerId, amount, PayCode.ALIPAY, Constants.BIZ_TYPE_KINDERGARTEN_FEE); long oldBalance = getBalance(sellerId, BalanceType.CAN_BE_WITHDRAW_BALANCE); // 支付宝回调的 amount 要加上费率 PaymentNotifyRequest request = createPaymentNotifyRequest(orderNo, amount + tradeFee, tradeStatus); PaymentNotifyResponse response = paymentNotifyService.alipayNotify(request); Assert.assertTrue(ApiResultBase.isSuccess(response)); // 幼儿园的金额要匹配 long newBalance = getBalance(sellerId, BalanceType.CAN_BE_WITHDRAW_BALANCE); Assert.assertTrue(oldBalance + amount == newBalance); // 对比 PayRecord 的数据 PayRecordPO payRecordPO = payRecordDao.getByOrderNo(orderNo); Assert.assertNotNull(payRecordPO); Assert.assertTrue(payRecordPO.getOriginAmount() == amount); Assert.assertTrue(payRecordPO.getAmount() == amount + tradeFee); // 交易费率 Assert.assertTrue(payRecordPO.getPayCode() == PayCode.ALIPAY.getCode()); // 对比 AlipayRecord 的数据 AlipayRecordPO alipayRecordPO = alipayRecordDao.get(payRecordPO.getPayId()); Assert.assertNotNull(alipayRecordPO); Assert.assertEquals(PayUtil.toSingleString(request.getResult().get("trade_no"), ""), alipayRecordPO.getTradeNo()); Assert.assertEquals(PayUtil.toSingleString(request.getResult().get("total_fee"), ""), PayUtil.fenToYuan(amount + tradeFee)); Assert.assertEquals(PayUtil.toSingleString(request.getResult().get("notify_type"), ""), "trade_status_sync"); Assert.assertEquals(PayUtil.toSingleString(request.getResult().get("notify_id"), ""), alipayRecordPO.getAlipayNotifyId()); // 重复请求一次 try { paymentNotifyService.alipayNotify(request); } catch (ServiceException e) { Assert.assertTrue(e.getCode() == ApiCode.SUCCESS); } } /** * 测试 [京东支付] 成功 [缴费] 的情况 * 期望结果:处理成功,幼儿园的余额增加,但不包括费率 * @param sellerId 买家ID * @param tradeStatus 必须传入 AlipayNotify.TRADE_FINISHED 或 AlipayNotify.TRADE_SUCCESS */ private void testJdpayNotifyForSuccess(long sellerId, int tradeStatus) { Assert.assertTrue(JdpayNotify.TRADE_SUCCESS == tradeStatus); Random rand = new Random(); long amount = 1000 + rand.nextInt(500); long orderNo = createPaymentRequest(sellerId, amount, PayCode.JDPAY, Constants.BIZ_TYPE_KINDERGARTEN_FEE); long oldBalance = getBalance(sellerId, BalanceType.CAN_BE_WITHDRAW_BALANCE); JdpayNotifyResponse notifyResponse = createJdpayNotifyRequest(orderNo, amount, String.valueOf(tradeStatus)); PaymentNotifyResponse response = paymentNotifyService.jdpayAsyncNotify(notifyResponse, "172.16.2.148"); Assert.assertTrue(ApiResultBase.isSuccess(response)); // 幼儿园的金额要匹配 long newBalance = getBalance(sellerId, BalanceType.CAN_BE_WITHDRAW_BALANCE); Assert.assertTrue(oldBalance + amount == newBalance); // 对比 PayRecord 的数据 PayRecordPO payRecordPO = payRecordDao.getByOrderNo(orderNo); Assert.assertNotNull(payRecordPO); Assert.assertTrue(payRecordPO.getOriginAmount() == amount); Assert.assertTrue(payRecordPO.getPayCode() == PayCode.JDPAY.getCode()); // 对比 JdpayRecord 的数据 JdpayRecordPO jdpayRecordPO = jdpayRecordDao.get(payRecordPO.getPayId()); Assert.assertNotNull(jdpayRecordPO); Assert.assertEquals(notifyResponse.getTradeNum(), jdpayRecordPO.getTradeNum()); Assert.assertEquals(notifyResponse.getAmount().toString(), String.valueOf(amount)); // 重复请求一次 try { paymentNotifyService.jdpayAsyncNotify(notifyResponse, "172.168.2.148"); } catch (ServiceException e) { Assert.assertTrue(e.getCode() == ApiCode.SUCCESS); } } /** * 创建一个支付宝的回调请求 * @param orderNo 支付平台订单号 * @param amount 订单金额,分 * @param tradeStatus 交易状态,见 {@link com.ibeiliao.pay.impl.thirdpay.alipay.AlipayNotify} * @return PaymentNotifyRequest */ private PaymentNotifyRequest createPaymentNotifyRequest(long orderNo, long amount, String tradeStatus) { Date now = new Date(); String strNow = DateUtil.formatDateTime(now); PaymentNotifyRequest request = new PaymentNotifyRequest(); Map<String, String[]> params = new HashMap<>(); params.put("notify_id", new String[] {randomId()}); params.put("out_trade_no", new String[] {orderNo + ""}); params.put("total_fee", new String[] {PayUtil.fenToYuan(amount)}); params.put("payment_type", new String[]{"1"}); params.put("notify_type", new String[]{"trade_status_sync"}); params.put("buyer_id", new String[]{randomId()}); params.put("buyer_email", new String[] {"test@alipay.com"}); params.put("trade_status", new String[] {tradeStatus}); params.put("trade_no", new String[]{newAlipayTradeNo()}); params.put("discount", new String[] {"0.00"}); params.put("gmt_create", new String[] {strNow}); params.put("gmt_payment", new String[]{strNow}); request.setResult(params); request.setClientIp("127.0.0.1"); return request; } /** * 创建一个京东的回调请求 * @param orderNo 支付平台订单号 * @param amount 订单金额,分 * @param tradeStatus 交易状态 * @return PaymentNotifyRequest */ private JdpayNotifyResponse createJdpayNotifyRequest(long orderNo, long amount, String tradeStatus) { JdpayNotifyResponse response = new JdpayNotifyResponse(); response.setAmount(amount); response.setDevice(""); response.setMerchant("123"); response.setNote("测试"); response.setPayList(new ArrayList<PayTradeVo>()); Result result = new Result(); result.setCode("0000"); result.setDesc("success"); response.setResult(result); response.setStatus(tradeStatus); response.setTradeNum(String.valueOf(orderNo)); response.setTradeType("0"); response.setVersion("V2.0"); return response; } /** * 创建一个模拟招行回调请求数据。 * 签名是不对的。 * @param orderNo 订单号 * @param amount 金额 * @return */ private PaymentNotifyRequest createCmbPaymentNotifyRequest(long orderNo, long amount) { Date now = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String strNow = sdf.format(now); PaymentNotifyRequest request = new PaymentNotifyRequest(); Map<String, String[]> params = new HashMap<>(); // Succeed=Y&CoNo=000091&BillNo=0001003092&Amount=.35&Date=20160814&MerchantPara=orderNo=160831753995952000&Msg=00200000912016081416281498500000000010&Signature=143|120|24|155|252|223|35|58|106|106|60|76|183|92|99|29|97|45|171|65|156|58|218|97|47|38|237|192|222|141|222|207|16|167|155|142|129|24|60|9|152|253|69|53|198|128|186|4|167|8|249|168|173|106|42|212|231|22|237|112|231|30|36|122| params.put("Succeed", new String[] {"Y"}); params.put("CoNo", new String[] {"000091"}); params.put("BillNo", new String[] {randomNumber(10)}); params.put("Amount", new String[] {PayUtil.fenToYuan(amount)}); params.put("Date", new String[] {strNow}); params.put("MerchantPara", new String[] {"orderNo=" + orderNo}); params.put("Msg", new String[] {"0020000091" + strNow + randomNumber(20)}); params.put("Signature", new String[] {"143|120|24|155|252|223|35|58|106|106|60|76|183|92|99|29|97|45|171|65|156|58|218|97|47|38|237|192|222|141|222|207|16|167|155|142|129|24|60|9|152|253|69|53|198|128|186|4|167|8|249|168|173|106|42|212|231|22|237|112|231|30|36|122|"}); request.setResult(params); request.setClientIp("127.0.0.1"); String queryString = PayUtil.toSingleString(params.get("Succeed"), "") + "&" + PayUtil.toSingleString(params.get("CoNo"), "") + "&" + PayUtil.toSingleString(params.get("Succeed"), "") + "&" + PayUtil.toSingleString(params.get("BillNo"), "") + "&" + PayUtil.toSingleString(params.get("Amount"), "") + "&" + PayUtil.toSingleString(params.get("Date"), "") + "&" + PayUtil.toSingleString(params.get("MerchantPara"), "") + "&" + PayUtil.toSingleString(params.get("Msg"), "") + "&" + PayUtil.toSingleString(params.get("Signature"), ""); request.setQueryString(queryString); return request; } /** * 创建一个金惠家的支付通知请求 * @param data 数据 * @return PaymentNotifyRequest */ private PaymentNotifyRequest createJhjNotifyRequest(String data) { PaymentNotifyRequest request = new PaymentNotifyRequest(); request.setClientIp("127.0.0.1"); request.setQueryString(data); request.setResult(null); return request; } private String newAlipayTradeNo() { return String.valueOf(System.currentTimeMillis()); } /** * 返回一个随机的ID * @return */ private String randomId() { return UUID.randomUUID().toString().replaceAll("-", ""); } private String randomNumber(int len) { Random random = new Random(); StringBuilder buf = new StringBuilder(len); for (int i=0; i < len; i++) { buf.append(random.nextInt(10000) % 10); } return buf.toString(); } /** * 创建一个支付单 * @param sellerId 卖家ID * @param amount 余额 * @param payCode 支付渠道 * @param type 业务类型 * @return */ private long createPaymentRequest(long sellerId, long amount, PayCode payCode, int type) { // 构造参数 GetPaymentParamRequest request = new GetPaymentParamRequest(); request.setSellerId(sellerId); request.setSellerName("seller name " + sellerId); request.setSellerType(UserType.KINDERGARTEN); request.setUserIp("127.0.0.1"); request.setBuyerId(5335); request.setBuyerName("buyer name"); request.setBuyerType(UserType.NORMAL_USER); request.setOrderId(System.currentTimeMillis()); request.setOrderNo(OrderNO.next(request.getBuyerId(), request.getOrderId())); request.setItemName("图画课"); request.setItemDesc("A套餐-高级图画课32课时"); request.setAmount(amount); request.setVersion("1.0"); request.setPayCode(payCode); request.setType(type); PlatformContext.getContext().setPlatformId(5000); // 创建成功 GetPaymentParamResponse response = paymentService.createClientPaymentParam(request, "", DeviceSource.APP, ""); Assert.assertTrue(ApiResultBase.isSuccess(response)); return request.getOrderNo(); } /** * 读取学校的余额 * @param schoolId 学校ID * @param balanceType 余额类型 * @return */ private long getBalance(long schoolId, BalanceType balanceType) { SchoolBalancePO po = schoolBalanceDao.getBySchoolIdAndBalanceType(schoolId, balanceType.getType()); return (po == null ? 0 : po.getBalance()); } }
package eu.lsem.bakalarka.dao; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import eu.lsem.bakalarka.model.Directory; import java.util.List; public interface DirectoriesDao { public List<Directory> getChildDirectories(Integer id); public void insertDirectory(Directory dir); public Directory getDirectory(Integer id); public int updateDirectoryName(Integer id, String name); public int deleteDirectoriesAndMoveTheses(Integer rootDirId); public List<Directory> getDirectoriesPath(Integer directoryId); }
package beertab; import com.sun.javafx.application.LauncherImpl; import javafx.application.Application; public class Main { public static final double conDbStart = 20; public static final double conDbSuccess = 30; public static final double conDbFailUnknownHost = 21; public static final double conDbFailIO = 22; public static final double conDbFailUnknownError = 29; public static void main(String[] args) { // Launch splashscreen (Preloader) before main LauncherImpl.launchApplication(Beertab.class, BeertabPreloader.class, args); } }
package ru.job4j.servlets.webarchitecturejsp.presentation; import ru.job4j.servlets.webarchitecturejsp.logic.DBStore; import ru.job4j.servlets.webarchitecturejsp.logic.ValidateService; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; /** * После запускаа TomCat Приложение можно запустить вбив в браузер http://localhost:8082/chapter_007/usersjsp */ @WebServlet("/usersjsp") public class UsersServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setAttribute("users", ValidateService.getValidateService().findAll()); HttpSession session = req.getSession(); String role = ValidateService.getValidateService().findByLogin((String) session.getAttribute("login")).getRole(); if (role.equals("admin")) { getServletContext().getRequestDispatcher("/WEB-INF/users.jsp").forward(req, resp); } else if (role.equals("user")) { getServletContext().getRequestDispatcher("/WEB-INF/usersLimited.jsp").forward(req, resp); } } @Override public void destroy() { try { DBStore.getInstance().close(); } catch (Exception e) { e.printStackTrace(); } } }
package edu.buet.cse.spring.ch10.v1.client; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import edu.buet.cse.spring.ch10.v1.model.User; import edu.buet.cse.spring.ch10.v1.service.ChirperService; public class App { public static void main(String... args) { ApplicationContext appContext = new ClassPathXmlApplicationContext("/edu/buet/cse/spring/ch10/v1/client/spring-beans.xml"); ChirperService chirperService = appContext.getBean("chirperService", ChirperService.class); User user = chirperService.getUser(1L); System.out.println(user); } }
package mygroup; import java.io.UnsupportedEncodingException; /** * @author liming.gong */ public class TestUtf { public static void main(String[] args) { try { final String UTF8 = "UTF-8"; final String UTF16 = "UTF-16"; // new String(getBytes(UTF8), UTF8) 等于什么也没有做 // new String(getBytes(UTF8), UTF8) 先编码再解码,也等于什么也没做 // getBytes(UTF16) 会在字符串的最后面加上BOM,两个字节 /* 5 5 5 5 5 5 12 */ String h = "hello"; System.out.println(h.length()); System.out.println(h.getBytes().length); System.out.println(h.codePointCount(0, h.length())); System.out.println(new String(h.getBytes(UTF8), UTF8).length()); System.out.println(new String(h.getBytes(UTF16), UTF16).length()); System.out.println(new String(h.getBytes(UTF16), UTF16).getBytes(UTF8).length); System.out.println(new String(h.getBytes(UTF8), UTF8).getBytes(UTF16).length); System.out.println(); /* 4 10 4 4 4 10 10 */ String h1 = "你好哦!"; System.out.println(h1.length()); System.out.println(h1.getBytes().length); System.out.println(h1.codePointCount(0, h1.length())); System.out.println(new String(h1.getBytes(UTF8), UTF8).length()); System.out.println(new String(h1.getBytes(UTF16), UTF16).length()); System.out.println(new String(h1.getBytes(UTF16), UTF16).getBytes(UTF8).length); System.out.println(new String(h1.getBytes(UTF8), UTF8).getBytes(UTF16).length); System.out.println(); /* 7 11 7 7 7 11 16 */ String h2 = "hello实验"; System.out.println(h2.length()); System.out.println(h2.getBytes().length); System.out.println(h2.codePointCount(0,h2.length())); System.out.println(new String(h2.getBytes(UTF8), UTF8).length()); System.out.println(new String(h2.getBytes(UTF16), UTF16).length()); System.out.println(new String(h2.getBytes(UTF16), UTF16).getBytes(UTF8).length); System.out.println(new String(h2.getBytes(UTF8), UTF8).getBytes(UTF16).length); System.out.println(); //3 System.out.println("水".getBytes().length); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }
/** * create two pointer, one is slow, one is fast. travel the original list, * fast pointer move two steps, slow pointer move one steps. put the value, * which the slow pointer point to, into a stack * when fast pointer at the end, the slow point would point to the middle node. * and then, slow point move one step continue, compare the value of stack and the * value the slow pointer point to */ import java.util.Stack; public class Solution06 { public static class linkedNode { public int val; public linkedNode next; public linkedNode(int x) { this.val = x; } } public static boolean ifpalindrome (linkedNode head) { linkedNode current = head; linkedNode runner = head; Stack<Integer> stack = new Stack<Integer>(); while (runner != null && runner.next != null) { stack.push(current.val); current = current.next; runner = runner.next.next; } // if the number of list is odd, we have to skip this node if (runner != null) current = current.next; while(current != null) { if (current.val != stack.pop()) return false; else current = current.next; } return true; } public static void main(String[] args) { // TODO Auto-generated method stub //int number[] = {0,1,2,1,0}; int number[] = {0,1,2,1,0,1}; linkedNode a = new linkedNode(number[0]); linkedNode current = a; for (int i = 1; i < number.length; i++) { current.next = new linkedNode(number[i]); current = current.next; } linkedNode c = a; while(c != null) { System.out.print(c.val + " "); c = c.next; } System.out.println(); if (ifpalindrome(a)) System.out.println("It's palindrome"); else System.out.println("It is not palindrome"); } }
package com.starmicronics.starprntsdk; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import com.starmicronics.starprntsdk.functions.ApiFunctions; import static com.starmicronics.starioextension.StarIoExt.Emulation; import static com.starmicronics.starioextension.ICommandBuilder.BlackMarkType; public class ApiFragment extends ItemListFragment implements CommonAlertDialogFragment.Callback { private static final String BLACK_MARK_TYPE_SELECT_DIALOG = "BlackMarkTypeSelectDialog"; private static final int BLACK_MARK_MENU_INDEX = 23; private ProgressDialog mProgressDialog; private BlackMarkType mBlackMarkType; private boolean mIsForeground; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mProgressDialog = new ProgressDialog(getActivity()); mProgressDialog.setMessage("Communicating..."); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mProgressDialog.setCancelable(false); addTitle("Sample"); addMenu("Generic"); addMenu("Font Style"); addMenu("Initialization"); addMenu("Code Page"); addMenu("International"); addMenu("Feed"); addMenu("Character Space"); addMenu("Line Space"); addMenu("Emphasis"); addMenu("Invert"); addMenu("Under Line"); addMenu("Multiple"); addMenu("Absolute Position"); addMenu("Alignment"); addMenu("Logo"); addMenu("Cut Paper"); addMenu("Peripheral"); addMenu("Sound"); addMenu("Bitmap"); addMenu("Barcode"); addMenu("PDF417"); addMenu("QR Code"); addMenu("Black Mark"); addMenu("Page Mode"); } @Override public void onResume() { super.onResume(); mIsForeground = true; } @Override public void onPause() { super.onPause(); mIsForeground = false; if (mProgressDialog != null) { mProgressDialog.dismiss(); } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { super.onItemClick(parent, view, position, id); if (position == BLACK_MARK_MENU_INDEX) { // Black Mark BlackMarkTypeSelectDialogFragment dialog = BlackMarkTypeSelectDialogFragment.newInstance(BLACK_MARK_TYPE_SELECT_DIALOG); dialog.show(getChildFragmentManager()); } else { // Others print(position); } } @Override public void onDialogResult(String tag, Intent data) { boolean isCanceled = data.hasExtra(CommonAlertDialogFragment.LABEL_NEGATIVE); if (isCanceled) return; if (tag.equals(BLACK_MARK_TYPE_SELECT_DIALOG)) { int index = data.getIntExtra(CommonActivity.BUNDLE_KEY_BLACK_MARK_TYPE_INDEX, 0); switch (index) { default: case 0: mBlackMarkType = BlackMarkType.Invalid; break; case 1: mBlackMarkType = BlackMarkType.Valid; break; case 2: mBlackMarkType = BlackMarkType.ValidWithDetection; break; } print(BLACK_MARK_MENU_INDEX); // Black Mark } } private void print(int selectedIndex) { mProgressDialog.show(); byte[] data; PrinterSetting setting = new PrinterSetting(getActivity()); Emulation emulation = setting.getEmulation(); int paperSize = getActivity().getIntent().getIntExtra(CommonActivity.BUNDLE_KEY_PAPER_SIZE, -1); switch (selectedIndex) { case 1: data = ApiFunctions.createGenericData(emulation); break; case 2: data = ApiFunctions.createFontStyleData(emulation); break; case 3: data = ApiFunctions.createInitializationData(emulation); break; case 4: data = ApiFunctions.createCodePageData(emulation); break; case 5: data = ApiFunctions.createInternationalData(emulation); break; case 6: data = ApiFunctions.createFeedData(emulation); break; case 7: data = ApiFunctions.createCharacterSpaceData(emulation); break; case 8: data = ApiFunctions.createLineSpaceData(emulation); break; case 9: data = ApiFunctions.createEmphasisData(emulation); break; case 10: data = ApiFunctions.createInvertData(emulation); break; case 11: data = ApiFunctions.createUnderLineData(emulation); break; case 12: data = ApiFunctions.createMultipleData(emulation); break; case 13: data = ApiFunctions.createAbsolutePositionData(emulation); break; case 14: data = ApiFunctions.createAlignmentData(emulation); break; case 15: data = ApiFunctions.createLogoData(emulation); break; case 16: data = ApiFunctions.createCutPaperData(emulation); break; case 17: data = ApiFunctions.createPeripheralData(emulation); break; case 18: data = ApiFunctions.createSoundData(emulation); break; case 19: data = ApiFunctions.createBitmapData(emulation, paperSize, getActivity()); break; case 20: data = ApiFunctions.createBarcodeData(emulation); break; case 21: data = ApiFunctions.createPdf417Data(emulation); break; case 22: data = ApiFunctions.createQrCodeData(emulation); break; case 23: data = ApiFunctions.createBlackMarkData(emulation, mBlackMarkType); break; case 24: data = ApiFunctions.createPageModeData(emulation, paperSize, getActivity()); break; default: data = ApiFunctions.createGenericData(emulation); break; } Communication.sendCommands(this, data, setting.getPortName(), setting.getPortSettings(), 10000, getActivity(), mCallback); // 10000mS!!! } private final Communication.SendCallback mCallback = new Communication.SendCallback() { @Override public void onStatus(boolean result, Communication.Result communicateResult) { if (!mIsForeground) { return; } if (mProgressDialog != null) { mProgressDialog.dismiss(); } String msg; switch (communicateResult) { case Success : msg = "Success!"; break; case ErrorOpenPort: msg = "Fail to openPort"; break; case ErrorBeginCheckedBlock: msg = "Printer is offline (beginCheckedBlock)"; break; case ErrorEndCheckedBlock: msg = "Printer is offline (endCheckedBlock)"; break; case ErrorReadPort: msg = "Read port error (readPort)"; break; case ErrorWritePort: msg = "Write port error (writePort)"; break; default: msg = "Unknown error"; break; } CommonAlertDialogFragment dialog = CommonAlertDialogFragment.newInstance("CommResultDialog"); dialog.setTitle("Communication Result"); dialog.setMessage(msg); dialog.setPositiveButton("OK"); dialog.show(getChildFragmentManager()); } }; }
package com.yqyan.user.center.config; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Configuration; /** * @Author yanyaqiang * @Date 2019/4/26 10:14 **/ @Configuration @MapperScan("com.yqyan.user.center.dao") public class MybatisConfig { }
/* * 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.pinchofintelligence.duolingoemersion.server; import com.pinchofintelligence.duolingoemersion.crawlers.music.TrackInformation; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * * @author Roland */ public class DatabaseAdapter { public static List<TrackInformation> getTracksWithCorrectLanguage(HashMap<String, TrackInformation> tracksDatabase, String language) { Iterator it = tracksDatabase.entrySet().iterator(); List<TrackInformation> tracksWithCorrectLanguage = new ArrayList<>(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); TrackInformation lyric = (TrackInformation) pairs.getValue(); if(lyric.getLyrics_body() != null){ if(lyric.getLyrics_language().equals(language)){ tracksWithCorrectLanguage.add(lyric); } } } return tracksWithCorrectLanguage; } }
package edu.yccc.cis174.vinceAtanasov.exam; /** * @author Vince * */ import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class JavaExam implements Exam { // Creating empty lists for the questions, possible answers and the answer key, // which will host the data from the text files. public List<Question> questions = new ArrayList<Question>(); public List<Answer> possibleAnswers = new ArrayList<Answer>(); public List<String> correctAnswers = new ArrayList<String>(); // Creating an empty list for the student's input. public List<String> userAnswers = new ArrayList<String>(); // Creating variables for nextQuestion and nextAnswer. public String nextQuestion; public String nextAnswer; // Creating counter variables for getNextQuestion and getNextAnswer. public int counter = 0; public int counterAns = 0; // Method that reads the file with the questions and returns list with them. public List<Question> loadQuestions() { Scanner scanner = null; try { // Creating scanner that reads the questions.txt file. scanner = new Scanner(new File("javaQuestions.txt")); // Loop that goes over the file and adding each line as a string element to the // list. The result is full list with the questions. while (scanner.hasNextLine()) { Question q = new Question(); q.setQuestion(scanner.nextLine()); questions.add(q); } } catch (FileNotFoundException e) { e.printStackTrace(); } // Closing the scanner. finally { scanner.close(); } return questions; } // Method that reads the file with the possible answers and returns list with // them. public List<Answer> loadAnswers() { Scanner scanner = null; try { // Creating scanner that reads the questions.txt file. scanner = new Scanner(new File("javaAnswers.txt")); // Loop that goes over the file and adding each line as a string element to the // list. The result is full list with the questions. while (scanner.hasNextLine()) { Answer a = new Answer(); a.setPossibleAnswer(scanner.nextLine()); possibleAnswers.add(a); } } catch (FileNotFoundException e) { e.printStackTrace(); } // Closing the scanner. finally { scanner.close(); } return possibleAnswers; } // Method that reads the file with the correct answers and returns list with // them. public List<String> loadCorrectAnswers() { Scanner scanner = null; try { // Creating scanner that reads the questions.txt file. scanner = new Scanner(new File("javaCorrectAnswers.txt")); // Loop that goes over the file and adding each line as a string element to the // list. The result is full list with the questions. while (scanner.hasNextLine()) { correctAnswers.add(scanner.nextLine()); } } catch (FileNotFoundException e) { e.printStackTrace(); } // Closing the scanner. finally { scanner.close(); } return correctAnswers; } // Method that calculates the student's score. public float calculateGrade() { // Creating variables for correct answers, total questions and the grade itself. int correct = 0; int total = correctAnswers.size(); float grade = 0; // Loop that goes around the list with user's answers and correct answers. for (int i = 0; i < correctAnswers.size(); i++) { // Creating variable result which compare the elements from the two list index // by index. int result = (userAnswers.get(i).compareTo(correctAnswers.get(i))); // Condition that increments the variable correct with one every time when there // is match between the lists' elements by index. if (result == 0) { correct++; } } // Calculating the grade of the student. grade = (float) ((double) correct / total * 100); return grade; } // Method that writes a file. We'are passing arguments for user name and grade. public void writeExamResult(String userName, float grade) { // Creating empty BufferedWriter out. BufferedWriter out = null; try { // Creating FileWriter with the path for the text file. FileWriter fStream = new FileWriter("Examresults.txt", true); out = new BufferedWriter(fStream); // Writing out the user name and the result to a text file. out.write(" "); out.write(userName + " "); out.write(grade + ";" + "\n"); out.close(); } catch (Exception e) { e.printStackTrace(); } } // Method that gets the next question from the list with questions. public String getNextQuestion() { // Condition for getting the exact question, starting from the first question in // the list. This will happen until the method reaches the end of the list with // questions. if (counter < questions.size()) { nextQuestion = questions.get(counter).getQuestion(); // Incrementing the counter with one, so next time the method is called it will // get the following question from the list. counter++; } // When the end of the list is reached the next question will take this value. else { nextQuestion = "You completed the test!"; } return nextQuestion; } // Method that gets the next possible answers for the question from the list // with possible answers. public String getNextAnswer() { // Condition for getting the exact possible answers for the current question. if (counterAns < possibleAnswers.size()) { nextAnswer = possibleAnswers.get(counterAns).getPossibleAnswer(); // Incrementing the counter with one, so next time the method is called it will // get the exact answers for the following question. counterAns++; } return nextAnswer; } }
package main.java.com.gzmini.bo; import java.sql.Connection; import java.sql.Types; import java.util.ArrayList; import java.util.List; import main.java.com.gzmini.vo.EnglishSentenceVo; import main.java.com.gzmini.common.DataBase; public class EnglishSentenceBo extends DataBase { public EnglishSentenceBo(Connection acon){ this.con =acon; } public int NewSentence(EnglishSentenceVo englishsentencevo) throws Exception { int o_Result = 0; try { this.cstmt = this.con.prepareCall("{call NewSentence(?,?)}"); this.cstmt.setString(1,englishsentencevo.getSentence()); this.cstmt.registerOutParameter(2, Types.INTEGER); this.cstmt.execute(); o_Result = this.cstmt.getInt(2); } catch(Exception err) { throw err; } finally { if (this.cstmt != null) this.cstmt.close(); } return o_Result; } public void UpdateSentence(EnglishSentenceVo englishsentencevo) throws Exception { try { this.cstmt = this.con.prepareCall("{call UpdateSentence(?,?,?)}"); this.cstmt.setInt(1,englishsentencevo.getId()); this.cstmt.setString(2,englishsentencevo.getSentence()); this.cstmt.registerOutParameter(3, Types.INTEGER); this.cstmt.execute(); int o_Result = this.cstmt.getInt(3); if (o_Result != 0) { o_Result = -1; } } catch(Exception err) { throw err; } finally { if (this.cstmt != null) this.cstmt.close(); } } public void DeleteSentence(int id) throws Exception { try { this.cstmt = this.con.prepareCall("{call DeleteSentence(?,?)}"); this.cstmt.setInt(1,id); this.cstmt.registerOutParameter(2, Types.INTEGER); this.cstmt.execute(); int o_Result = this.cstmt.getInt(2); if (o_Result != 0) { o_Result = -1; } } catch(Exception err) { throw err; } finally { if (this.cstmt != null) this.cstmt.close(); } } public EnglishSentenceVo getEnglishSentenceById(int id) throws Exception { String Sql = "select * from TB_SENTENCE where id=" + id; try { this.stmt = this.con.createStatement(); this.rs = this.stmt.executeQuery(Sql); EnglishSentenceVo englishsentencevo = new EnglishSentenceVo(); if (rs != null && rs.next()) { englishsentencevo.setId(rs.getInt("id")); englishsentencevo.setSentence(rs.getString("sentence")); } return englishsentencevo; } catch(Exception err) { throw err; } finally { if (this.stmt != null) this.stmt.close(); } } public int getEnglishSentenceRowCounts() throws Exception { int rowCounts = 0; String Sql = "select count(*) as rowcounts from TB_SENTENCE"; try { this.stmt = this.con.createStatement(); this.rs = this.stmt.executeQuery(Sql); if (rs != null) { rowCounts = (rs.getInt("rowcounts")); } return rowCounts; } catch(Exception err) { throw err; } finally { if (this.stmt != null) this.stmt.close(); } } public List<EnglishSentenceVo> getEnglishSentenceList() throws Exception { List<EnglishSentenceVo> englishsentenceList = new ArrayList<EnglishSentenceVo>(); String Sql = "select * from TB_SENTENCE order by id desc"; try { this.stmt = this.con.createStatement(); this.rs = this.stmt.executeQuery(Sql); while (rs != null && rs.next()) { EnglishSentenceVo englishsentencevo = new EnglishSentenceVo(); englishsentencevo.setId(rs.getInt("id")); englishsentencevo.setSentence(rs.getString("sentence")); englishsentenceList.add(englishsentencevo); } return englishsentenceList; } catch(Exception err) { throw err; } finally { if (this.stmt != null) this.stmt.close(); } } }
package fr.lteconsulting; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Partie { public Joueur deroulerPartie( Joueur joueur1, Joueur joueur2 ) { FabriqueDeck fabriqueDeck = new FabriqueDeck(); List<Carte> deck = fabriqueDeck.genere32Cartes(); Collections.shuffle( deck ); distribuerCarte( deck, new Joueur[] { joueur1, joueur2 } ); int tour = 0; List<Carte> encours = new ArrayList<>(); while( tour++ < 5000 ) { // System.out.println( "Joueur1 : " + joueur1.getNbCartes() + " cartes" ); // System.out.println( "Joueur2 : " + joueur2.getNbCartes() + " cartes" ); Carte c1 = joueur1.donneCarte(); Carte c2 = joueur2.donneCarte(); if( c1 == null ) return joueur1; if( c2 == null ) return joueur2; int comparaison = compareCartes( c1, c2 ); // System.out.println( c1 + " vs " + c2 + " => " + comparaison ); encours.add( c1 ); encours.add( c2 ); if( comparaison > 0 ) { donneEncoursA( encours, joueur1 ); } else if( comparaison < 0 ) { donneEncoursA( encours, joueur2 ); } else { encours.add( joueur1.donneCarte() ); encours.add( joueur2.donneCarte() ); } } return null; } private void donneEncoursA( List<Carte> encours, Joueur destinataire ) { for( Carte carte : encours ) destinataire.prendCarte( carte ); encours.clear(); } // TODO : Carte pourrait implémenter Comparable private int compareCartes( Carte c1, Carte c2 ) { return Integer.compare( c1.getValeur(), c2.getValeur() ); } private void distribuerCarte( List<Carte> deck, Joueur[] joueurs ) { int current = 0; for( Carte carte : deck ) { joueurs[(current++) % joueurs.length].prendCarte( carte ); } } }
package com.shivam.spring_aop.aspect; public @interface Loggable { }
package cn.demo.overlay; import android.app.Activity; import cn.demo.overlaylibrary.LauncherClient; import cn.demo.overlaylibrary.LauncherClientCallbacks; class Util { static LauncherClient getClient(Activity a, LauncherClientCallbacks cb) { return new LauncherClient(a, cb, "cn.demo.server", true); } }
package com.wonders.task.htxx.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import com.wonders.task.htxx.dao.BaseinfoDao; import com.wonders.task.htxx.model.bo.DwContractBaseinfo; import com.wonders.task.htxx.service.BaseinfoService; @Service("baseinfoService") public class BaseinfoServiceImpl implements BaseinfoService{ @Autowired(required=false) private BaseinfoDao baseinfoDao; public void setBaseinfoDao(@Qualifier("baseinfoDao")BaseinfoDao baseinfoDao) { this.baseinfoDao = baseinfoDao; } @Override public void save(DwContractBaseinfo dwContractBaseinfo) { this.baseinfoDao.save(dwContractBaseinfo); } @Override public String findOneData(String sql) { return this.baseinfoDao.executeSQLReturnOneData(sql); } @Override public String findOneData2(String sql) { return this.baseinfoDao.executeSQLReturnOneData2(sql); } @Override public DwContractBaseinfo findByType(String type) { return baseinfoDao.findByType(type); } @Override public List<Object[]> findBySql(String sql) { return this.baseinfoDao.executeSqlWithResult(sql); } @Override public boolean isResultExist(String sql) { List<Object[]> list = this.baseinfoDao.executeSqlWithResult(sql); if(list==null || list.size()<1) return false; return true; } @Override public void executeUpdateUpdate(String sql) { baseinfoDao.executeSqlUpdate(sql); } }
package tools; import java.io.BufferedReader; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import model.MyUrl; import src.FileCharsetDetector; public class WrongPathChecker { /** * 判断include标签中的路径是否有效. * * @param rootPath * 项目根路径 * @param strPath * 引用路径 * @return 返回true或者false */ public boolean isValidIncludePath(final String rootPath, final String strPath) { String include; Pattern pattern = Pattern.compile("/$"); Matcher matcher = pattern.matcher(rootPath); if (matcher.find()) { include = "_include/"; } else { include = "/_include/"; } File folder = new File(rootPath + include + strPath); if (folder.exists()) { return true; } return false; } /** * 判断内部引用路径是否有效. * * @param file * 引用路径的文件 * @param strPath * 引用路径 * @return 返回true或者false */ public boolean isValidIntercalPath(final File file, final String strPath) { String path = ""; try { if (file.exists()) { path = file.getParent(); } else { throw new FileNotFoundException(); } } catch (FileNotFoundException e) { e.printStackTrace(); } File intercalFile = new File(path + "\\" + strPath); if (intercalFile.exists()) { return true; } return false; } /** * 在文件中搜索引用超链接中的错误路径. * * @param file * 需要检测的文件 */ public List<MyUrl> searchWrongIntercalPath(final File file) { List<MyUrl> wrongInternalPathList = new ArrayList<MyUrl>(); // 检索引入超链接[超链接文本](超链接地址 "悬浮显示")的正则 String intercalRex = "\\[[^\\(\\)]*\\]\\([^\\(\\)]+\\)"; Pattern intercalPattern = Pattern.compile(intercalRex); // 检查是否为外部网址链接的正则 String httpRex = "(http://|https://)(([a-zA-z0-9]|-){1,}\\.){1,}[a-zA-z0-9]{1,}-*"; Pattern httpPattern = Pattern.compile(httpRex); // 检测是否为锚点链接[文字](#锚点位置)的正则 String anchorRex = "^\\#"; Pattern anchorPattern = Pattern.compile(anchorRex); LineNumberReader lineReader = null; try { // 读取文件时指定字符编码 lineReader = new LineNumberReader(new BufferedReader( new InputStreamReader(new FileInputStream(file), "UTF-8"))); String readLine = null; // 读取文件内容 while ((readLine = lineReader.readLine()) != null) { Matcher intercalMatcher = intercalPattern.matcher(readLine); while (intercalMatcher.find()) { // 假如这一行存在可以匹配引入超链接正则表达式的字符串 // 将路径字符串从引入超链接的字符串中切割出来 String intercalPath = intercalMatcher.group(0) .replaceAll("\\[[^\\(\\)]*\\]\\(", "").replaceAll("\\)", "") .split("\\s")[0]; // 检测路径是否为内部路径,是否为锚点链接,以及路径是否正确 Matcher httpMatcher = httpPattern.matcher(intercalPath); Matcher anchorMatcher = anchorPattern.matcher(intercalPath); if (!httpMatcher.find() && !anchorMatcher.find() && !isValidIntercalPath(file, intercalPath.trim())) { MyUrl myUrl = new MyUrl(); myUrl.setFile(file.getParent() + "\\" + file.getName()); myUrl.setUrl(intercalPath); // 若路径不可用,将这个网址所属的文件名和网址字符串插入到错误路径list wrongInternalPathList.add(myUrl); } } } } catch (IOException e) { e.printStackTrace(); } finally { // 关闭流 close(lineReader); } return wrongInternalPathList; } /** * 关闭流. * * @param able * 需要关闭的流 */ private void close(final Closeable able) { if (able != null) { try { able.close(); } catch (IOException e) { e.printStackTrace(); } } } }
package com.zeed.oauth2.oauth2testapp.repository; import com.zeed.oauth2.oauth2testapp.model.TestUser; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface TestUserRepository extends JpaRepository<TestUser, Long> { TestUser findTopByUsername(String username); }
package com.bowlong.util; public class Ref<T> { public Ref() { } public Ref(T v) { val = v; } public final String toString() { if (val == null) return nullStr; return val.toString(); } static final String nullStr = "val is null"; public T val; }
package ch.springcloud.lite.core.codec; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import ch.springcloud.lite.core.type.VariantType; public class DefaultCloudCodec implements CloudCodec { ObjectMapper mapper; public DefaultCloudCodec(ObjectMapper mapper) { this.mapper = mapper; } @Override public String encode(Object object, VariantType type) { try { if (object == null) { return ""; } return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { e.printStackTrace(); throw new IllegalArgumentException(String.valueOf(object)); } } @Override public Object decode(String val, Class<?> type) { try { if (val == null) { return null; } return mapper.readValue(val, type); } catch (JsonProcessingException e) { e.printStackTrace(); throw new RuntimeException(e); } } }
package com.SkyBlue.base.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestAttribute; import org.springframework.web.bind.annotation.RequestMapping; import com.SkyBlue.base.serviceFacade.BaseServiceFacade; import com.SkyBlue.base.to.BusinessPlaceBean; import com.SkyBlue.common.mapper.DatasetBeanMapper; import com.tobesoft.xplatform.data.PlatformData; @Controller public class BusinessPlaceController{ @Autowired private BaseServiceFacade baseServiceFacade; @Autowired private DatasetBeanMapper datasetBeanMapper; /* 부서목록을 조회하는 메서드 */ @RequestMapping("/base/findBusinessPlaceList.do") public void findBusinessPlaceList(@RequestAttribute("inData") PlatformData inData, @RequestAttribute("outData") PlatformData outData) throws Exception { List<BusinessPlaceBean> businessPlaceList=baseServiceFacade.findBusinessPlaceList(); datasetBeanMapper.beansToDataset(outData, businessPlaceList, BusinessPlaceBean.class); /* * beansToDataset : bean --> dataset * */ } /*부서관리 (등록/삭제/수정)*/ @RequestMapping("/base/batchBusinessPlaceList.do") public void batchBusinessPlaceList(@RequestAttribute("inData") PlatformData inData, @RequestAttribute("outData") PlatformData outData) throws Exception { /* * datasetToBean도 있다. * * datasetToBeans : dataset --> bean * * */ List<BusinessPlaceBean> businessPlaceList=datasetBeanMapper.datasetToBeans(inData, BusinessPlaceBean.class); baseServiceFacade.batchBusinessPlaceList(businessPlaceList); findBusinessPlaceList(inData,outData); } }
package com.mod.course_service.document.response; import com.mod.course_service.document.Topic; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; @Data @AllArgsConstructor @NoArgsConstructor public class CourseEventResponse { private String eventType; private CourseResponse course; private List<Topic> topics; private String title; }
package com.timmy.framework.imageLoaderFw; import android.Manifest; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import com.timmy.R; import com.timmy.base.BaseActivity; import com.timmy.framework.annotationRuntime.ViewInjectUtils; import com.timmy.framework.annotationRuntime.annotations.ContentView; import com.timmy.framework.annotationRuntime.annotations.OnViewClick; import com.timmy.framework.annotationRuntime.annotations.ViewInject; import com.timmy.framework.imageLoaderFw.TimmyImageLoader.TimmyImageLoader; import com.timmy.framework.imageLoaderFw.TimmyImageLoader.config.ImageLoaderConfig; import com.timmy.framework.imageLoaderFw.TimmyImageLoader.policy.ReversePolicy; import com.timmy.library.util.Toast; import java.util.Arrays; @ContentView(R.layout.activity_image_loader) public class ImageLoaderActivity extends BaseActivity { // @ViewInject(R.id.btn_load_one) // Button mBtnLoadOne; // @ViewInject(R.id.btn_load_images) // Button mBtnLoadMore; @ViewInject(R.id.iv_image) ImageView mImageView; @ViewInject(R.id.rv_recycleView) RecyclerView mRecyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ViewInjectUtils.inject(this); initToolBar(); //申请权限 //开启权限 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(ImageLoaderActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); }else { initImageLoad(); initView(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case 1: if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) { Toast.toastShort("拒绝权限将导致功能无法使用!"); finish(); }else{ initImageLoad(); initView(); } break; default: break; } } private void initView() { mRecyclerView.setLayoutManager(new GridLayoutManager(this,3)); ImageAdapter imageAdapter = new ImageAdapter(this); imageAdapter.setData(Arrays.asList(imageThumbUrls)); mRecyclerView.setAdapter(imageAdapter); imageAdapter.notifyDataSetChanged(); } private void initImageLoad() { ImageLoaderConfig config = new ImageLoaderConfig.Builder() // .setBitmapCache(new DoubleCache(this)) .setErrorPlaceholder(R.mipmap.composer_place) .setLoadingPlaceholder(R.mipmap.ic_good) .setLoadPolicy(new ReversePolicy()) .create(); TimmyImageLoader.getInstance().init(config); TimmyImageLoader.getInstance().displayImage(mImageView,imageThumbUrls[0]); } @OnViewClick({R.id.btn_load_one,R.id.btn_load_images}) public void loadImage(View view){ switch (view.getId()){ case R.id.btn_load_one: mImageView.setVisibility(View.VISIBLE); mRecyclerView.setVisibility(View.GONE); break; case R.id.btn_load_images: mImageView.setVisibility(View.GONE); mRecyclerView.setVisibility(View.VISIBLE ); break; } } public final static String[] imageThumbUrls =new String[] { "http://img.my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383291_6518.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383291_8239.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383290_9329.jpg",//DB123421AC "http://img.my.csdn.net/uploads/201407/26/1406383290_1042.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383275_3977.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383265_8550.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383264_3954.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383264_4787.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383264_8243.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383248_3693.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383243_5120.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383242_3127.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383242_9576.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383242_1721.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383219_5806.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383214_7794.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383213_4418.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383213_3557.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383210_8779.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383172_4577.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383166_3407.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383166_2224.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383166_7301.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383165_7197.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383150_8410.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383131_3736.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383130_5094.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383130_7393.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383129_8813.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383100_3554.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383093_7894.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383092_2432.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383092_3071.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383091_3119.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383059_6589.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383059_8814.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383059_2237.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383058_4330.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383038_3602.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382942_3079.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382942_8125.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382942_4881.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382941_4559.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382941_3845.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382924_8955.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382923_2141.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382923_8437.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382922_6166.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382922_4843.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382905_5804.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382904_3362.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382904_2312.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382904_4960.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382900_2418.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382881_4490.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382881_5935.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382880_3865.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382880_4662.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382879_2553.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382862_5375.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382862_1748.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382861_7618.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382861_8606.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382861_8949.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382841_9821.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382840_6603.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382840_2405.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382840_6354.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382839_5779.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382810_7578.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382810_2436.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382809_3883.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382809_6269.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382808_4179.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382790_8326.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382789_7174.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382789_5170.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382789_4118.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382788_9532.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382767_3184.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382767_4772.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382766_4924.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382766_5762.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382765_7341.jpg" }; }
package DS; public class Queue { private int capacity; private int arr[]; private int front = 0; private int rear = 0; private int count = 0; public Queue(int capacity){ arr = new int[capacity]; this.capacity = capacity; } public void push(int item){ if (count >= capacity){ expandQ(); } arr[rear] = item; rear = (rear +1) % capacity; count++; } public int pop(){ Integer item = null; if (count != 0){ item = arr[front]; front = (front +1) % capacity; count --; }else{ System.out.println("Empty Queue"); } return item; } private void expandQ(){ int bigArr[] = new int[capacity*2]; for (int i =0;i<count;i++){ bigArr[i]=arr[front]; front = (front+1)%capacity; } capacity = capacity*2; front = 0; rear = count; arr = bigArr; } public void print(){ for (int i = 1; i < count; i++) { System.out.print(arr[(front+i)%capacity]+" "); } } public static void main(String[] args) { // TODO Auto-generated method stub Queue Q = new Queue(10); for (int i=0;i<50;i++){ Q.push(i); } Q.pop(); Q.pop(); Q.pop(); Q.pop(); Q.pop(); Q.pop(); Q.pop(); for (int i=100;i<290;i++){ Q.push(i); } Q.pop(); Q.pop(); Q.pop(); for (int i=100;i<290;i++){ Q.push(i); } Q.print(); } }
/* * 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 TesteCodigo; import java.util.Queue; import java.util.LinkedList; import java.util.Random; /** * * @author mauricio.moreira */ public class TesteQueue { public static void main(String[] args) { Queue<Integer> fila = new LinkedList<>(); Random gen = new Random(); for (int i = 0; i < 10; i++) { int value = gen.nextInt(100); System.out.println(value); fila.add(value); } System.out.println("Elementos da Fila: " + fila); System.out.println("Tamanho da fila: " + fila.size()); int head = fila.peek(); System.out.println("Primeiro elemento: " + head); int removed = fila.remove(); System.out.println("Elemento retirado: " + removed); if (fila.peek() != null) { //Integer remove = fila.remove(); System.out.println("Elemento removido: " + fila.poll()); } System.out.println(fila); } }
package com.example.v3.design.chain; /** * 责任链模式 * */
package com.z3pipe.z3core.base; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; /** * @author zhengzhuanzi on 2018/9/17. */ public abstract class BaseSdFileReadWriter { /** * 写到文件中 * 这种写入方式为覆盖写入,会导致之前的数据覆盖 * * @param filePath 文件路径 * @param data 写入的数据内容 */ protected boolean writeBinaryStream(String filePath, String data) { return writeBinaryStream(filePath, data, false); } /** * 写到文件中 * * @param filePath 文件路径 * @param data 写入的数据内容 * @param append 是否追加 */ protected boolean writeBinaryStream(String filePath, String data, boolean append) { return writeBinary(filePath, data.getBytes(), append); } /** * 写到文件中 * * @param filePath 文件路径 * @param data 写入的数据内容 * @param append 是否追加 */ protected boolean writeBinary(String filePath, byte[] data, boolean append) { FileOutputStream outStream = null; boolean result; try { //获取输出流 outStream = new FileOutputStream(filePath, append); outStream.write(data); result = true; } catch (Exception e) { e.printStackTrace(); result = false; } finally { try { if (outStream != null) { outStream.close(); } } catch (Exception e) { e.printStackTrace(); } } return result; } /** * 从文件中读取 * * @return */ protected String readBinaryStream(String filePath) { try { //关闭流 return new String(readBinary(filePath)); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 从文件中读取 * * @return */ protected byte[] readBinary(String filePath) { FileInputStream inStream = null; ByteArrayOutputStream outStream = null; try { File file = new File(filePath); //获得输入流 inStream = new FileInputStream(file); //new一个缓冲区 byte[] buffer = new byte[1024]; int len = 0; //使用ByteArrayOutputStream类来处理输出流 outStream = new ByteArrayOutputStream(); while ((len = inStream.read(buffer)) != -1) { //写入数据 outStream.write(buffer, 0, len); } //得到文件的二进制数据 return outStream.toByteArray(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (outStream != null) { outStream.close(); } } catch (Exception e) { e.printStackTrace(); } try { if (inStream != null) { inStream.close(); } } catch (Exception e) { e.printStackTrace(); } } return null; } }
package com.example.applemac.myapplication; import android.app.Activity; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import java.io.FileInputStream; import java.net.HttpURLConnection; /** * Created by applemac on 05/09/17. */ public class PhotoProcess { Context context = null; Activity activity = null; public PhotoProcess(Context context, Activity activity) { this.context = context; this.activity = activity; } public void listPhoto() { Log.i("TESTAPP", " ###### listPhoto: "); int i=0,j=0; PhotoReaderDBHelper mDbHelper = new PhotoReaderDBHelper(context); SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor resultSet = db.rawQuery("Select * from " + PhotoEntry.TABLE_NAME + " where " + PhotoEntry.STATUS + " is NULL",null); resultSet.moveToFirst(); Log.i("TESTAPP", " ###### listPhoto count : " + resultSet.getCount()); if(resultSet.getCount() == 0) { return; } TableLayout l1 = (TableLayout) activity.findViewById(R.id.table1); l1.setStretchAllColumns(true); l1.bringToFront(); do { TableRow tr = new TableRow(context); tr.setId(Integer.valueOf(resultSet.getString(0))); ImageView i1 = new ImageView(context); TextView t1 = new TextView(context); ImageView i2 = new ImageView(context); final String urlID = resultSet.getString(3); t1.setText(resultSet.getString(2)); t1.setPadding(8, 8, 8, 8); // t1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)); t1.setMaxWidth(200); try { FileInputStream io = context.openFileInput(resultSet.getString(4)); Bitmap img = BitmapFactory.decodeStream(io); i1.setImageBitmap(img); } catch (Exception e) { e.printStackTrace(); } i2.setImageDrawable( activity.getResources().getDrawable(R.drawable.ic_delete_black_24dp)); tr.addView(i1); tr.addView(t1); tr.addView(i2); l1.addView(tr); i++; i1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(activity, PhotoDetailActivity.class); intent.putExtra("urlID",urlID); activity.startActivity(intent); } }); t1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(activity, PhotoDetailActivity.class); intent.putExtra("urlID",urlID); activity.startActivity(intent); } }); i2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { PhotoReaderDBHelper mDbHelper = new PhotoReaderDBHelper(context); SQLiteDatabase db = mDbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(PhotoEntry.STATUS, "deleted"); // db.update(PhotoEntry.TABLE_NAME, values, PhotoEntry._ID + "", new String[] { String.valueOf(view.getId())}); // listPhoto(); } }); if(i == 5) { break; } }while(resultSet.moveToNext()); } }
package com.tencent.mm.plugin.notification.c; class a$7 implements Runnable { final /* synthetic */ long bAw; final /* synthetic */ a lHC; a$7(a aVar, long j) { this.lHC = aVar; this.bAw = j; } public final void run() { a.a(this.lHC, this.bAw); } }
package eAdmission; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.List; import jxl.read.biff.BiffException; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import eAdmission.TBase.Browsers; public class LayoutChecker extends Page { public static void verifyCommonElements(WebDriver driver) throws BiffException, IOException { DataSheet dtSht = new DataSheet("Checkpoints"); LayoutChecker.checkWidth(driver, dtSht, "app-title", driver.findElement(By.id("app-title"))); LayoutChecker.checkHeight(driver, dtSht, "app-title", driver.findElement(By.id("app-title"))); LayoutChecker.checkY(driver, dtSht, "app-title", driver.findElement(By.id("app-title"))); LayoutChecker.checkWidth(driver, dtSht, "help-area-content", driver.findElement(By.id("help-area-content"))); LayoutChecker.checkHeight(driver, dtSht, "help-area-content", driver.findElement(By.id("help-area-content"))); LayoutChecker.checkY(driver, dtSht, "help-area-content", driver.findElement(By.id("help-area-content"))); // TODO Auto-generated constructor stub } public static void checkWidth(WebDriver driver, DataSheet dtSht, String element_name, WebElement we) throws BiffException, IOException { Helper.verifyValue( dtSht.getDimensions(element_name, "Name") + " width", Integer.toString(we.getSize().width), dtSht.getDimensions(element_name, "width")); } public static void checkHeight(WebDriver driver, DataSheet dtSht, String element_name, WebElement we) throws BiffException, IOException { Helper.verifyValue(dtSht.getDimensions(element_name, "Name") + " height", Integer.toString(we.getSize().height), dtSht.getDimensions(element_name, "height")); } public static void checkY(WebDriver driver, DataSheet dtSht, String element_name, WebElement we) throws BiffException, IOException { Helper.verifyValue(dtSht.getDimensions(element_name, "Name") + " y", Integer.toString(we.getLocation().y), dtSht.getDimensions(element_name, "y")); } public static void layoutNazy(WebDriver driver, Browsers browser) throws FileNotFoundException, UnsupportedEncodingException, InterruptedException { Thread.sleep(1000); List<WebElement> h1 = driver.findElements(By.tagName("h1")); List<WebElement> h2 = driver.findElements(By.tagName("h2")); List<WebElement> p = driver.findElements(By.tagName("p")); List<WebElement> span = driver.findElements(By.tagName("span")); List<WebElement> div = driver.findElements(By.tagName("div")); LayoutChecker.spitDataToFile(driver, span, browser); LayoutChecker.spitDataToFile(driver, p, browser); LayoutChecker.spitDataToFile(driver, h1, browser); LayoutChecker.spitDataToFile(driver, h2, browser); LayoutChecker.spitDataToFile(driver, div, browser); } public static void spitDataToFile(WebDriver driver, List<WebElement> we, Browsers browser) throws FileNotFoundException, UnsupportedEncodingException { WebElement we_first = we.get(0); File file = new File("C:\\Layout-" + browser + "-" + we_first.getTagName() + ".txt"); WebElement we_relative = driver.findElement(By.id("app-title")); PrintWriter writer = new PrintWriter(file.getAbsolutePath(), "UTF-8"); for (int i = 0; i < we.size(); i++) { WebElement we_current = we.get(i); if (we_current.isDisplayed() && we_current.getText().equals("*") == false) { writer.println("----------------------------------------"); writer.println("Text=" + we_current.getText()); writer.println("----------------------------------------"); writer.println("x=" + (we_current.getLocation().x - we_relative .getLocation().x)); writer.println("y=" + (we_current.getLocation().y - we_relative .getLocation().y)); writer.println("height=" + we_current.getSize().height); writer.println("width=" + we_current.getSize().width); } } writer.close(); } }
package message; import client.Group; import client.Group; /** * Class representing data to be transfered, e.g. data from server to client. * @author KEJ * */ public class DataMessage extends Message{ private String[] data; public DataMessage(String sender, Group group, String[] data){ super(sender, group); this.data = data; } public String[] getData(){ return data; } }
package ai.boundless.reward.particle.initializers; import java.util.Random; import ai.boundless.reward.particle.Particle; /** * The type Rotation speed initializer. */ public class RotationSpeedInitializer implements ParticleInitializer { private float mMinRotationSpeed; private float mMaxRotationSpeed; /** * Instantiates a new Rotation speed initializer. * * @param minRotationSpeed the min rotation speed * @param maxRotationSpeed the max rotation speed */ public RotationSpeedInitializer(float minRotationSpeed, float maxRotationSpeed) { mMinRotationSpeed = minRotationSpeed; mMaxRotationSpeed = maxRotationSpeed; } @Override public void initParticle(Particle p, Random r) { float rotationSpeed = r.nextFloat() * (mMaxRotationSpeed - mMinRotationSpeed) + mMinRotationSpeed; p.mRotationSpeed = rotationSpeed; } }
package com.jst.mapper.fornt; import java.util.List; import java.util.Map; import com.jst.model.Edu_User; import com.jst.model.SysSubject; public interface FrontUserMapper { //ͨ���û�����ȡ���� public Edu_User getPwd(String userName); //ע���û� public void addUser(Edu_User user); public Edu_User getById(int user_id); }
package lambda_test; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; /** * Description: * * @author Baltan * @date 2018/2/22 16:01 */ public class FilterFileDemo { public static void main(String[] args) { ArrayList<File> list = new ArrayList<>(); // 也可用FileFilter接口并重写其accept方法 Predicate<File> filter = pathname -> { if (pathname.getName().endsWith(".mp3")) { return true; } return false; }; File dir = new File("/Users/Baltan/Music/网易云音乐"); getAllFiles(dir, list, filter); for (File file : list) { System.out.println(file.getName()); } } //获取指定文件目录下所有符合条件的文件集合 public static void getAllFiles(File dir, List<File> list, Predicate<File> filter) { if (dir.isDirectory()) { File[] files = dir.listFiles(); for (File file : files) { if (file.isDirectory()) { getAllFiles(file, list, filter); } else { if (filter.test(file)) { list.add(file); } } } } else { if (filter.test(dir)) { list.add(dir); } } } }
/* * 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.kkstudio.springcrud.util; import java.util.HashMap; import java.util.Map; /** * * @author Xiangsheng Li */ public class QueryParameter { private Map parameters = null; private QueryParameter(String name, Object value) { this.parameters = new HashMap(); this.parameters.put(name, value); } public static QueryParameter with(String name, Object value) { return new QueryParameter(name, value); } public QueryParameter and(String name, Object value) { this.parameters.put(name, value); return this; } public Map parameters() { return this.parameters; } }
package tcp; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.Scanner; public class TCPClient2 { Scanner sc; public static void main(String[] args) { new TCPClient2().ClientMain(); } TCPClient2() { sc = new Scanner(System.in); } void ClientMain() { Socket socket; // 서버 연결 try { socket = new Socket("localHost", 10000); System.out.println("접속완료"); System.out.println("닉네임을 결정해 주세요."); String name = sc.nextLine(); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); out.writeUTF(name); out.flush(); // 메시지 보내기 : 전체에게 ClientSender cs = new ClientSender(socket); cs.start(); // 메시지 받기 : 서버에서 ClientReceiver cr = new ClientReceiver(socket); cr.start(); } catch (IOException e) { e.printStackTrace(); } } class ClientSender extends Thread { Socket socket; DataOutputStream out; ClientSender(Socket socket) throws IOException { this.socket = socket; out = new DataOutputStream(socket.getOutputStream()); } @Override public void run() { while (true) { System.out.println("입력) "); String msg = sc.nextLine(); try { out.writeUTF(msg); out.flush(); if (msg.equalsIgnoreCase("x")) { break; } } catch (IOException e) { e.printStackTrace(); } } } } class ClientReceiver extends Thread { Socket socket; DataInputStream in; ClientReceiver(Socket socket) throws IOException { this.socket = socket; in = new DataInputStream(socket.getInputStream()); } @Override public void run() { while (true) { try { System.out.println(in.readUTF()); } catch (IOException e) { e.printStackTrace(); } } } } }
package expe; public class qq { }
package cn.edu.hebtu.software.sharemate.Activity; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.annotation.Nullable; import android.support.constraint.ConstraintLayout; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.WindowManager; import android.widget.DatePicker; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.request.RequestOptions; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.Map; <<<<<<< HEAD ======= import cn.edu.hebtu.software.sharemate.tools.UpLoadUtil; >>>>>>> 3cee04cf64a9bbfa741281d002153c65e87cb041 import cn.edu.hebtu.software.sharemate.Bean.UserBean; import cn.edu.hebtu.software.sharemate.Fragment.MyFragment; import cn.edu.hebtu.software.sharemate.R; import cn.edu.hebtu.software.sharemate.SaveUser; import cn.edu.hebtu.software.sharemate.tools.UpLoadUtil; public class PersonalActivity extends AppCompatActivity { private Uri cropUri; private File file; private File cropFile; private TextView tv_name; private TextView tv_sex; private TextView tv_id; private TextView tv_address; private TextView tv_birth; private TextView tv_introduce; private ImageView iv_back; private ImageView iv_head; private LinearLayout layoutName; private LinearLayout layoutSex; private LinearLayout layoutBirth; private LinearLayout layoutAddress; private LinearLayout layoutIntro; private LinearLayout rootLayout; <<<<<<< HEAD private String sex; private String birth; private UserBean user; private static final int CODE_PHOTO_REQUEST = 1; private static final int CROP_SMALL_PICTURE = 2; private String sign; private String path; private ArrayList<Integer> type = new ArrayList<>(); ======= private String name; private String sex; private String birth; //user应该从数据库中获得 private UserBean user; private static final int CODE_PHOTO_REQUEST = 1; private static final int CROP_SMALL_PICTURE = 2; >>>>>>> 3cee04cf64a9bbfa741281d002153c65e87cb041 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_personal); type = getIntent().getIntegerArrayListExtra("type"); path = getResources().getString(R.string.server_path); file = new File(Environment.getExternalStorageDirectory() + "/CoolImage/"); rootLayout = findViewById(R.id.root); user = (UserBean) getIntent().getSerializableExtra("user"); sign = getIntent().getStringExtra("sign"); findView(); setContent(); setListener(); } private void findView() { iv_back = findViewById(R.id.back); iv_head = findViewById(R.id.head); tv_name = findViewById(R.id.user); tv_id = findViewById(R.id.num); <<<<<<< HEAD ======= tv_id.setText("" + user.getUserId()); >>>>>>> 3cee04cf64a9bbfa741281d002153c65e87cb041 tv_sex = findViewById(R.id.sex); tv_birth = findViewById(R.id.birth); tv_address = findViewById(R.id.address); tv_introduce = findViewById(R.id.introduction); <<<<<<< HEAD ======= if (user.getUserIntroduce() == null || user.getUserIntroduce().length() < 7) { tv_introduce.setText(user.getUserIntroduce()); } else { tv_introduce.setText(user.getUserIntroduce().substring(0, 6) + "..."); } >>>>>>> 3cee04cf64a9bbfa741281d002153c65e87cb041 layoutName = findViewById(R.id.ly_name); layoutAddress = findViewById(R.id.ly_address); layoutBirth = findViewById(R.id.ly_birth); layoutIntro = findViewById(R.id.ly_intro); layoutSex = findViewById(R.id.ly_sex); <<<<<<< HEAD } public void setContent(){ tv_address.setText(user.getUserAddress()); tv_birth.setText(user.getUserBirth()); tv_sex.setText(user.getUserSex()); String userId = String.format("%06d",user.getUserId()); tv_id.setText(userId); tv_name.setText(user.getUserName()); String photoPath = user.getUserPhotoPath(); RequestOptions mRequestOptions = RequestOptions.circleCropTransform() .diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(true); Glide.with(this).load(photoPath).apply(mRequestOptions).into(iv_head); if (user.getUserIntroduce() == null || user.getUserIntroduce().length() < 7) { tv_introduce.setText(user.getUserIntroduce()); } else { tv_introduce.setText(user.getUserIntroduce().substring(0, 6) + "..."); } ======= >>>>>>> 3cee04cf64a9bbfa741281d002153c65e87cb041 } private void setListener() { perOnClickListener listener = new perOnClickListener(); iv_head.setOnClickListener(listener); iv_back.setOnClickListener(listener); <<<<<<< HEAD layoutName.setOnClickListener(listener); ======= iv_head.setOnClickListener(listener); >>>>>>> 3cee04cf64a9bbfa741281d002153c65e87cb041 layoutSex.setOnClickListener(listener); layoutIntro.setOnClickListener(listener); layoutBirth.setOnClickListener(listener); layoutAddress.setOnClickListener(listener); } public class perOnClickListener implements View.OnClickListener { @Override public void onClick(View v) { <<<<<<< HEAD switch (v.getId()) { ======= switch (v.getId()){ case R.id.back: PersonalActivity.this.finish(); break; >>>>>>> 3cee04cf64a9bbfa741281d002153c65e87cb041 case R.id.head: Intent intent = new Intent(Intent.ACTION_PICK, null); intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(intent, CODE_PHOTO_REQUEST); break; case R.id.ly_name: Intent userIntent = new Intent(); userIntent.setClass(PersonalActivity.this, NameActivity.class); userIntent.putExtra("user", user); startActivityForResult(userIntent,3); break; case R.id.ly_sex: showSexDialog(); break; case R.id.ly_birth: showBirthDialog(); break; case R.id.ly_address: Intent addIntent = new Intent(); addIntent.setClass(PersonalActivity.this, AddressActivity.class); addIntent.putExtra("user", user); addIntent.putExtra("msg", "常住地"); startActivityForResult(addIntent,4); break; case R.id.ly_intro: Intent introIntent = new Intent(); introIntent.setClass(PersonalActivity.this, AddressActivity.class); introIntent.putExtra("user", user); introIntent.putExtra("msg", "个性签名"); startActivityForResult(introIntent,5); break; case R.id.back: SaveUser saveUser = new SaveUser(); saveUser.execute(user,path); if("my".equals(sign)){ Intent myIntent = new Intent(PersonalActivity.this,MainActivity.class); myIntent.putExtra("flag","my"); myIntent.putExtra("userId",user.getUserId()); myIntent.putIntegerArrayListExtra("type",type); Log.e("personal",user.getUserId()+""); startActivity(myIntent); }else if("set".equals(sign)){ Intent myIntent = new Intent(PersonalActivity.this,SettingActivity.class); myIntent.putExtra("user",user); myIntent.putIntegerArrayListExtra("type",type); startActivity(myIntent); } } } } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { switch (requestCode) { case CODE_PHOTO_REQUEST: if (data != null) { startPhotoZoom(data.getData()); } break; case CROP_SMALL_PICTURE: if (data != null) { if (!cropUri.equals("")) { RequestOptions mRequestOptions = RequestOptions.circleCropTransform() .diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(true); Glide.with(this).load(cropUri).apply(mRequestOptions).into(iv_head); } } //文本数据全部添加到Map里 final Map<String,Object> paramMap = new HashMap<>(); paramMap.put("userId",user.getUserId()); UpLoadUtil upLoadUtil = new UpLoadUtil(); upLoadUtil.execute(cropUri.getPath(),paramMap,path); break; } if(requestCode == 3 && resultCode == 200){ user = (UserBean)data.getSerializableExtra("responseUser"); setContent(); } if(requestCode == 4 && resultCode == 200){ user = (UserBean)data.getSerializableExtra("responseUser"); setContent(); } if(requestCode == 5 && resultCode == 200){ user = (UserBean)data.getSerializableExtra("responseUser"); setContent(); } } //性别选择器 private void showSexDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("请选择你的性别"); View v = getLayoutInflater().inflate(R.layout.activity_sex, null); final ImageView manView = v.findViewById(R.id.iv_man); final ImageView womanView = v.findViewById(R.id.iv_woman); final TextView manText = v.findViewById(R.id.man); final TextView womanText = v.findViewById(R.id.woman); manView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { manView.setImageResource(R.drawable.mans); womanView.setImageResource(R.drawable.woman); sex = manText.getText().toString(); } }); womanView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { manView.setImageResource(R.drawable.man); womanView.setImageResource(R.drawable.womans); sex = womanText.getText().toString(); } }); builder.setView(v); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { tv_sex.setText(sex); user.setUserSex(sex); dialog.dismiss(); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } //生日日期选择器 private void showBirthDialog() { final PopupWindow popupWindow = new PopupWindow(this); popupWindow.setWidth(ConstraintLayout.LayoutParams.MATCH_PARENT); View view = getLayoutInflater().inflate(R.layout.activity_birth, null); TextView okText = view.findViewById(R.id.tv_ok); TextView canaleText = view.findViewById(R.id.tv_cancle); final DatePicker datePicker = (DatePicker) view.findViewById(R.id.datepicker); Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); datePicker.init(year, month, day, new DatePicker.OnDateChangedListener() { @Override public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar calendar = Calendar.getInstance(); calendar.set(year, monthOfYear, dayOfMonth); SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd"); birth = format.format(calendar.getTime()); } }); popupWindow.setContentView(view); addBackgroundAlpha((float) 0.50); popupWindow.showAtLocation(rootLayout, Gravity.BOTTOM, 0, 0); okText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { tv_birth.setText(birth); user.setUserBirth(birth); popupWindow.dismiss(); addBackgroundAlpha((float) 1); } }); canaleText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { popupWindow.dismiss(); addBackgroundAlpha((float) 1); } }); } //修改activity的透明度 private void addBackgroundAlpha(float alpha) { WindowManager.LayoutParams params = getWindow().getAttributes(); params.alpha = alpha; getWindow().setAttributes(params); } <<<<<<< HEAD //修改头像 对图片进行裁剪 private void startPhotoZoom(Uri uri) { if (!file.exists()) { file.mkdirs(); } cropFile = new File(Environment.getExternalStorageDirectory() + "/CoolImage", System.currentTimeMillis() + ".jpg"); if (cropFile.exists()) { cropFile.delete(); }else{ ======= //修改头像 @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { switch (requestCode) { case CODE_PHOTO_REQUEST: if (data != null) { startPhotoZoom(data.getData()); } break; case CROP_SMALL_PICTURE: if (data != null) { if (!cropUri.equals("")) { RequestOptions mRequestOptions = RequestOptions.circleCropTransform() .diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(true); Glide.with(this).load(cropUri).apply(mRequestOptions).into(iv_head); } } UpLoadUtil upLoadUtil = new UpLoadUtil(); upLoadUtil.execute(cropUri.getPath()); break; } } //对图片进行裁剪 private void startPhotoZoom(Uri uri) { if (!file.exists()) { file.mkdirs(); } //保存裁剪后的图片 cropFile = new File(Environment.getExternalStorageDirectory() + "/CoolImage", System.currentTimeMillis() + ".jpg"); if (cropFile.exists()) { cropFile.delete(); Log.e("delete", "delete"); } else { >>>>>>> 3cee04cf64a9bbfa741281d002153c65e87cb041 try { cropFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } cropUri = Uri.fromFile(cropFile); Intent intent = new Intent("com.android.camera.action.CROP"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("outputX", 300); intent.putExtra("outputY", 300); intent.putExtra("scale", true); intent.putExtra("return-data", false); intent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri); <<<<<<< HEAD ======= Log.e("cropUri = ", cropUri.toString()); >>>>>>> 3cee04cf64a9bbfa741281d002153c65e87cb041 intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); intent.putExtra("noFaceDetection", true); startActivityForResult(intent, CROP_SMALL_PICTURE); } }
package ru.vssoft.backend.utils.jwt; import lombok.Getter; import org.springframework.security.core.GrantedAuthority; import org.springframework.stereotype.Service; import ru.vssoft.backend.model.User; import ru.vssoft.backend.payload.response.LoginResponse; import java.util.List; import java.util.stream.Collectors; @Service @Getter public class JwtTokenFactory { private final JwtAccessToken jwtAccessToken; private final JwtRefreshToken jwtRefreshToken; public JwtTokenFactory(JwtAccessToken jwtAccessToken, JwtRefreshToken jwtRefreshToken) { this.jwtAccessToken = jwtAccessToken; this.jwtRefreshToken = jwtRefreshToken; } public LoginResponse response(User user) { String token = jwtAccessToken.build(user); String refreshToken = jwtRefreshToken.build(user); List<String> roles = user.getAuthorities().stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.toList()); return new LoginResponse( token, refreshToken, user.getId(), user.getUsername(), roles ); } }
package com.tencent.mm.plugin.wallet_payu.create.ui; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; import com.tencent.mm.plugin.wallet_payu.create.a.d; import com.tencent.mm.plugin.wxpay.a$f; import com.tencent.mm.plugin.wxpay.a$g; import com.tencent.mm.ui.base.MMAutoHeightViewPager; import com.tencent.mm.ui.base.MMPageControlView; import java.util.ArrayList; public class WalletPayUOpenIntroView extends LinearLayout { private ArrayList<View> Vp; private Context mContext; private MMAutoHeightViewPager pEF; private MMPageControlView pEG; private a pEH; private d[] pEI; public WalletPayUOpenIntroView(Context context, AttributeSet attributeSet, int i) { super(context, attributeSet); this.mContext = context; View inflate = LayoutInflater.from(this.mContext).inflate(a$g.payu_view_open_intro, this, true); this.pEF = (MMAutoHeightViewPager) inflate.findViewById(a$f.pager); this.pEG = (MMPageControlView) inflate.findViewById(a$f.controller); this.pEG.setVisibility(0); this.pEF.setOnPageChangeListener(new 1(this)); } public WalletPayUOpenIntroView(Context context, AttributeSet attributeSet) { this(context, attributeSet, -1); } public void setPagerData(d[] dVarArr) { this.pEI = dVarArr; this.Vp = new ArrayList(); if (this.pEI != null) { for (int i = 0; i < this.pEI.length; i++) { this.Vp.add(LayoutInflater.from(this.mContext).inflate(a$g.payu_view_open_intro_item, null)); } } this.pEH = new a(this, (byte) 0); this.pEF.setAdapter(this.pEH); this.pEG.eS(this.pEI == null ? 0 : this.pEI.length, 0); } }
/* * Copyright 2012 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.uberfire.java.nio.fs.jgit; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.ExecutorService; import com.gitblit.FileSettings; import com.gitblit.GitBlit; import com.gitblit.GitBlitException; import com.gitblit.models.PathModel; import com.gitblit.models.RepositoryModel; import com.gitblit.utils.JGitOutputStream; import com.gitblit.utils.JGitUtils; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.storage.file.FileRepository; import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider; import org.uberfire.java.nio.IOException; import org.uberfire.java.nio.channels.AsynchronousFileChannel; import org.uberfire.java.nio.channels.SeekableByteChannel; import org.uberfire.java.nio.file.AccessDeniedException; import org.uberfire.java.nio.file.AccessMode; import org.uberfire.java.nio.file.AtomicMoveNotSupportedException; import org.uberfire.java.nio.file.CopyOption; import org.uberfire.java.nio.file.DirectoryNotEmptyException; import org.uberfire.java.nio.file.DirectoryStream; import org.uberfire.java.nio.file.FileAlreadyExistsException; import org.uberfire.java.nio.file.FileStore; import org.uberfire.java.nio.file.FileSystem; import org.uberfire.java.nio.file.FileSystemAlreadyExistsException; import org.uberfire.java.nio.file.FileSystemNotFoundException; import org.uberfire.java.nio.file.LinkOption; import org.uberfire.java.nio.file.NoSuchFileException; import org.uberfire.java.nio.file.NotDirectoryException; import org.uberfire.java.nio.file.NotLinkException; import org.uberfire.java.nio.file.OpenOption; import org.uberfire.java.nio.file.Path; import org.uberfire.java.nio.file.attribute.BasicFileAttributeView; import org.uberfire.java.nio.file.attribute.BasicFileAttributes; import org.uberfire.java.nio.file.attribute.FileAttribute; import org.uberfire.java.nio.file.attribute.FileAttributeView; import org.uberfire.java.nio.file.spi.FileSystemProvider; import org.uberfire.java.nio.fs.base.GeneralPathImpl; import static org.uberfire.commons.util.Preconditions.*; public class JGitFileSystemProvider implements FileSystemProvider { public static final String DEFAULT_PASSWORD = "defaultPassword"; public static final String DEFAULT_USER = "defaultUser"; private final JGitFileSystem fileSystem; private boolean isDefault; public static final String REPOSITORIES_ROOT_DIR = ".vfsjgit"; public static final String CACHE_DIR = ".cache"; private static Map<String, JGitRepositoryConfiguration> repositoryConfigurations = new HashMap<String, JGitRepositoryConfiguration>(); private static Map<Path, File> inmemoryCommitCache = new HashMap<Path, File>(); public JGitFileSystemProvider() { this.fileSystem = new JGitFileSystem(this); } @Override public synchronized void forceAsDefault() { this.isDefault = true; } @Override public boolean isDefault() { return isDefault; } @Override public String getScheme() { return "jgit"; } //Clone a git repository or create a new git repository if giturl parameter is not present. @Override public FileSystem newFileSystem(final URI uri, final Map<String, ?> env) throws IllegalArgumentException, IOException, SecurityException, FileSystemAlreadyExistsException { validateURI(uri); String rootJGitRepositoryName = getRootJGitRepositoryName(uri.getPath()); if (repositoryConfigurations.containsKey(rootJGitRepositoryName)) { throw new FileSystemAlreadyExistsException("FileSystem identifed by URI: " + uri + " already exists"); } String gitURL = (String) env.get("giturl"); String userName = (String) env.get("username"); String password = (String) env.get("password"); if (userName == null) { userName = DEFAULT_USER; } if (password == null) { password = DEFAULT_PASSWORD; } UsernamePasswordCredentialsProvider credential = new UsernamePasswordCredentialsProvider(userName, password); if (gitURL == null || "".equals(gitURL)) { //Create a new git repository System.out.print("Creating repository " + rootJGitRepositoryName + "... "); JGitUtils.createAndConfigRepository(new File(REPOSITORIES_ROOT_DIR), rootJGitRepositoryName); System.out.println("Creating done."); } else { // Clone an existing git repository try { System.out.print("Fetching repository " + rootJGitRepositoryName + "... "); JGitUtils.cloneRepository(new File(REPOSITORIES_ROOT_DIR), rootJGitRepositoryName, gitURL, true, credential); System.out.println("Fetching done."); } catch (Exception e) { throw new IOException(e); } } JGitRepositoryConfiguration jGitRepositoryConfiguration = new JGitRepositoryConfiguration(); jGitRepositoryConfiguration.setRepositoryName(rootJGitRepositoryName); jGitRepositoryConfiguration.setGitURL(gitURL); jGitRepositoryConfiguration.setUserName(userName); jGitRepositoryConfiguration.setPassword(password); repositoryConfigurations.put(rootJGitRepositoryName, jGitRepositoryConfiguration); //TODO: Set up FileSystem more properly to represent the status of git repository FileSystem jGitFileSystem = new JGitFileSystem(this); return jGitFileSystem; } private void validateURI(URI uri) { if (!uri.getScheme().equalsIgnoreCase(getScheme())) { throw new IllegalArgumentException( "URI does not match this provider"); } else if (uri.getAuthority() != null) { throw new IllegalArgumentException("Authority component should not present"); } else if (uri.getPath() == null) { throw new IllegalArgumentException("Path component is undefined"); } else if (uri.getQuery() != null) { throw new IllegalArgumentException("Query component should not present"); } else if (uri.getFragment() != null) { throw new IllegalArgumentException("Fragment component shoud not present"); } } //Fetch an existing git repository. @Override public FileSystem getFileSystem(final URI uri) throws IllegalArgumentException, FileSystemNotFoundException, SecurityException { final String rootJGitRepositoryName = getRootJGitRepositoryName(uri.getPath()); if (!repositoryConfigurations.containsKey(rootJGitRepositoryName)) { throw new FileSystemNotFoundException("FileSystem identifed by URI: " + uri + " does not exist"); } // JGitRepositoryConfiguration jGitRepositoryConfiguration = repositoryConfigurations.get(rootJGitRepositoryName); // String userName = jGitRepositoryConfiguration.getUserName(); // String password = jGitRepositoryConfiguration.getPassword(); // UsernamePasswordCredentialsProvider credential = new UsernamePasswordCredentialsProvider(userName, password); // try { // if (jGitRepositoryConfiguration.getGitURL() != null) { // System.out.print("Fetching repository " + rootJGitRepositoryName + "... "); // JGitUtils.cloneRepository(new File(REPOSITORIES_ROOT_DIR), rootJGitRepositoryName, jGitRepositoryConfiguration.getGitURL(), true, credential); // System.out.println("Fetching done."); // } // } catch (Exception e) { // throw new IOException(e); // } // // //TODO: Set up FileSystem more properly to represent the status of git repository return new JGitFileSystem(this); } private static String getRootJGitRepositoryName(final String path) { String rootJGitRepositoryName = path; if (rootJGitRepositoryName.startsWith("/")) { rootJGitRepositoryName = rootJGitRepositoryName.substring(1); } if (rootJGitRepositoryName.indexOf("/") > 0) { rootJGitRepositoryName = rootJGitRepositoryName.substring(0, rootJGitRepositoryName.indexOf("/")); } return rootJGitRepositoryName; } private static String getPathRelativeToRootJGitRepository(final String path) { String rootJGitRepositoryName = getRootJGitRepositoryName(path); int indexOfEndOfRootJGitRepositoryName = path.indexOf(rootJGitRepositoryName) + rootJGitRepositoryName.length() + 1; String relativePath = indexOfEndOfRootJGitRepositoryName > path.length() ? "" : path.substring(indexOfEndOfRootJGitRepositoryName); if (relativePath.startsWith("/")) { relativePath = relativePath.substring(1); } return relativePath; } @Override public Path getPath(final URI uri) throws IllegalArgumentException, FileSystemNotFoundException, SecurityException { FileSystem fileSystem = getFileSystem(uri); return GeneralPathImpl.create(fileSystem, uri.getPath(), false); } @Override public FileSystem newFileSystem(final Path path, final Map<String, ?> env) throws IllegalArgumentException, UnsupportedOperationException, IOException, SecurityException { return null; } @Override public InputStream newInputStream(final Path path, final OpenOption... options) throws IllegalArgumentException, NoSuchFileException, IOException, SecurityException { final String rootJGitRepositoryName = getRootJGitRepositoryName(path.toString()); String relativePath = getPathRelativeToRootJGitRepository(path.toString()); Repository repo; try { repo = getRepository(rootJGitRepositoryName); } catch (java.io.IOException e) { throw new IOException(); } byte[] byteContent = JGitUtils.getByteContent(repo, null, relativePath); return new ByteArrayInputStream(byteContent); /* final File file = path.toFile(); if (!file.exists()) { throw new NoSuchFileException(file.toString()); } try { return new FileInputStream(path.toFile()); } catch (FileNotFoundException e) { throw new NoSuchFileException(e.getMessage()); }*/ } @Override public OutputStream newOutputStream(final Path path, final OpenOption... options) throws IllegalArgumentException, UnsupportedOperationException, IOException, SecurityException { final String rootJGitRepositoryName = getRootJGitRepositoryName(path.toString()); //String relativePath = getPathRelativeToRootJGitRepository(path.toString()); Repository repository; try { repository = getRepository(rootJGitRepositoryName); File rootCacheDir = new File(CACHE_DIR); if (!rootCacheDir.exists()) { rootCacheDir.mkdir(); } File tempFile = newTempFile(); inmemoryCommitCache.put(path, tempFile); return new JGitOutputStream(new FileOutputStream(tempFile), this); } catch (java.io.IOException e) { e.printStackTrace(); throw new IOException(); } } static File newTempFile() throws java.io.IOException { return File.createTempFile("noz", null, new File(CACHE_DIR)); } @Override public FileChannel newFileChannel(final Path path, final Set<? extends OpenOption> options, final FileAttribute<?>... attrs) throws IllegalArgumentException, UnsupportedOperationException, IOException, SecurityException { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public AsynchronousFileChannel newAsynchronousFileChannel(final Path path, final Set<? extends OpenOption> options, final ExecutorService executor, FileAttribute<?>... attrs) throws IllegalArgumentException, UnsupportedOperationException, IOException, SecurityException { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public SeekableByteChannel newByteChannel(final Path path, final Set<? extends OpenOption> options, final FileAttribute<?>... attrs) throws IllegalArgumentException, UnsupportedOperationException, FileAlreadyExistsException, IOException, SecurityException { final File file = checkNotNull("path", path).toFile(); if (file.exists()) { throw new FileAlreadyExistsException(""); } try { file.createNewFile(); return new SeekableByteChannel() { @Override public long position() throws IOException { return 0; } @Override public SeekableByteChannel position(long newPosition) throws IOException { return null; } @Override public long size() throws IOException { return 0; } @Override public SeekableByteChannel truncate(long size) throws IOException { return null; } @Override public int read(ByteBuffer dst) throws java.io.IOException { return 0; } @Override public int write(ByteBuffer src) throws java.io.IOException { return 0; } @Override public boolean isOpen() { return false; } @Override public void close() throws java.io.IOException { } }; } catch (java.io.IOException e) { throw new IOException(); } } @Override public DirectoryStream<Path> newDirectoryStream(final Path dir, final DirectoryStream.Filter<Path> filter) throws NotDirectoryException, IOException, SecurityException { try { final String rootJGitRepositoryName = getRootJGitRepositoryName(dir.toString()); String relativePath = getPathRelativeToRootJGitRepository(dir.toString()); Repository repo = getRepository(rootJGitRepositoryName); final List<PathModel> files = JGitUtils.getFilesInPath(repo, relativePath, null); return new DirectoryStream<Path>() { @Override public void close() throws IOException { } @Override public Iterator<Path> iterator() { return new Iterator<Path>() { private int i = 0; @Override public boolean hasNext() { return i < files.size(); } @Override public Path next() { if (i < files.size()) { PathModel pathModel = files.get(i); i++; String uri = "/" + rootJGitRepositoryName + "/" + pathModel.path; return GeneralPathImpl.create(getDefaultFileSystem(), uri, false); } else { throw new NoSuchElementException(); } } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } catch (java.io.IOException e) { IOException i = new IOException(); i.initCause(e); throw i; } } @Override public void createDirectory(final Path dir, final FileAttribute<?>... attrs) throws UnsupportedOperationException, FileAlreadyExistsException, IOException, SecurityException { checkNotNull("dir", dir).toFile().mkdirs(); } @Override public void createSymbolicLink(final Path link, final Path target, final FileAttribute<?>... attrs) throws UnsupportedOperationException, FileAlreadyExistsException, IOException, SecurityException { //To change body of implemented methods use File | Settings | File Templates. } @Override public void createLink(final Path link, final Path existing) throws UnsupportedOperationException, FileAlreadyExistsException, IOException, SecurityException { //To change body of implemented methods use File | Settings | File Templates. } @Override public void delete(final Path path) throws DirectoryNotEmptyException, IOException, SecurityException { checkNotNull("path", path).toFile().delete(); //toGeneralPathImpl(path).clearCache(); } @Override public boolean deleteIfExists(final Path path) throws DirectoryNotEmptyException, IOException, SecurityException { return checkNotNull("path", path).toFile().delete(); } @Override public Path readSymbolicLink(final Path link) throws UnsupportedOperationException, NotLinkException, IOException, SecurityException { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public void copy(final Path source, final Path target, final CopyOption... options) throws UnsupportedOperationException, FileAlreadyExistsException, DirectoryNotEmptyException, IOException, SecurityException { //To change body of implemented methods use File | Settings | File Templates. } @Override public void move(Path source, Path target, CopyOption... options) throws DirectoryNotEmptyException, AtomicMoveNotSupportedException, IOException, SecurityException { //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isSameFile(Path path, Path path2) throws IOException, SecurityException { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isHidden(final Path path) throws IllegalArgumentException, IOException, SecurityException { checkNotNull("path", path); return ((JGitlFileAttributes) getFileAttributeView(path, BasicFileAttributeView.class, null).readAttributes()).isHidden(); } @Override public FileStore getFileStore(final Path path) throws IOException, SecurityException { return new JGitFileStore(); } @Override public void checkAccess(Path path, AccessMode... modes) throws UnsupportedOperationException, AccessDeniedException, IOException, SecurityException { } @Override public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) { final String rootJGitRepositoryName = getRootJGitRepositoryName(path.toString()); String relativePath = getPathRelativeToRootJGitRepository(path.toString()); Repository repo; try { repo = getRepository(rootJGitRepositoryName); } catch (java.io.IOException e) { throw new IOException(); } if (type == BasicFileAttributeView.class) { PathModel pathModel = JGitUtils.getPathModel(repo, relativePath, null); return (V) new JGitFileAttributeView(pathModel); } return null; } @Override public <A extends BasicFileAttributes> A readAttributes(final Path path, final Class<A> type, final LinkOption... options) throws UnsupportedOperationException, IOException, SecurityException { checkNotNull("path", path); checkNotNull("type", type); final String rootJGitRepositoryName = getRootJGitRepositoryName(path.toString()); String relativePath = getPathRelativeToRootJGitRepository(path.toString()); Repository repo; try { repo = getRepository(rootJGitRepositoryName); } catch (java.io.IOException e) { throw new IOException(); } final PathModel pathModel = JGitUtils.getPathModel(repo, relativePath, null); if (pathModel == null ) { throw new NoSuchFileException(path.toString()); } if (type == BasicFileAttributes.class) { BasicFileAttributeView view = getFileAttributeView(path, BasicFileAttributeView.class, options); return (A) view.readAttributes(); } return null; } @Override public Map<String, Object> readAttributes(final Path path, final String attributes, final LinkOption... options) throws UnsupportedOperationException, IllegalArgumentException, IOException, SecurityException { final String rootJGitRepositoryName = getRootJGitRepositoryName(path.toString()); String relativePath = getPathRelativeToRootJGitRepository(path.toString()); Repository repo; try { repo = getRepository(rootJGitRepositoryName); } catch (java.io.IOException e) { throw new IOException(); } if (relativePath.length() == 0) { final Map<String, Object> result = new HashMap<String, Object>(); result.put("giturl", repo.getConfig().getString("remote", "origin", "url")); result.put("description", repo.getRepositoryState().getDescription()); return result; } else if (attributes.equals("*")) { PathModel pathModel = JGitUtils.getPathModel(repo, relativePath, null); JGitlFileAttributes attrs = new JGitlFileAttributes(pathModel); final Map<String, Object> result = new HashMap<String, Object>(); result.put("isRegularFile", attrs.isRegularFile()); result.put("isDirectory", attrs.isDirectory()); result.put("isSymbolicLink", attrs.isSymbolicLink()); result.put("isOther", attrs.isOther()); result.put("size", new Long(attrs.size())); result.put("fileKey", attrs.fileKey()); result.put("exists", attrs.exists()); result.put("isReadable", attrs.isReadable()); result.put("isExecutable", attrs.isExecutable()); result.put("isHidden", attrs.isHidden()); //todo check why errai can't serialize it result.put("lastModifiedTime", null); result.put("lastAccessTime", null); result.put("creationTime", null); return result; } throw new IOException(); } @Override public void setAttribute(Path path, String attribute, Object value, LinkOption... options) throws UnsupportedOperationException, IllegalArgumentException, ClassCastException, IOException, SecurityException { //To change body of implemented methods use File | Settings | File Templates. } private FileSystem getDefaultFileSystem() { return fileSystem; } public void commit(String commitMessage) { try { for (Path path : inmemoryCommitCache.keySet()) { final File tempFile = inmemoryCommitCache.get(path); final String rootJGitRepositoryName = getRootJGitRepositoryName(path.toString()); final JGitRepositoryConfiguration jGitRepositoryConfiguration = repositoryConfigurations.get(rootJGitRepositoryName); final String userName = jGitRepositoryConfiguration.getUserName(); final String password = jGitRepositoryConfiguration.getPassword(); final UsernamePasswordCredentialsProvider credential = new UsernamePasswordCredentialsProvider(userName, password); final String relativePath = getPathRelativeToRootJGitRepository(path.toString()); final Repository repository = getRepository(rootJGitRepositoryName); final PathModel pathModel = new PathModel(path.getFileName().toString(), relativePath, 0, 0, ""); JGitUtils.commit(repository, pathModel, new FileInputStream(tempFile), commitMessage, credential); tempFile.delete(); inmemoryCommitCache.remove(path); } } catch (java.io.IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) throws Exception { JGitFileSystemProvider j = new JGitFileSystemProvider(); String repositoryName = "mytestrepo"; JGitUtils.createAndConfigRepository(new File(REPOSITORIES_ROOT_DIR), repositoryName); Repository r = getRepository(repositoryName); ObjectId headId = r.resolve(Constants.HEAD); List<PathModel> files2 = JGitUtils.getFilesInPath(r, null, null); for (PathModel p : files2) { System.out.println("name: " + p.name); System.out.println("path: " + p.path); System.out.println("isTree: " + p.isTree()); } Map<String, String> env = new HashMap<String, String>(); String gitURL = "https://github.com/guvnorngtestuser1/mytestrepo.git"; String userName = "guvnorngtestuser1"; String password = "test1234"; env.put("giturl", gitURL); env.put("username", userName); env.put("password", password); URI uri = URI.create("jgit:///mytestrepo"); //j.newFileSystem(uri, env); //FileSystem fileSystem = j.getFileSystem(uri); Repository repository = getRepository(repositoryName); //Path p = new PathImpl("jgit:///guvnorng-playground"); //OutputStream os = j.newOutputStream(p, null); File source = new File("pom.xml"); System.out.println(source.getAbsolutePath()); PathModel pathModel = new PathModel("pom.xml", "mortgagesSample/sometestfile9", 0, 0, ""); String commitMessage = "test. pushed from jgit."; InputStream inputStream = new FileInputStream(source); UsernamePasswordCredentialsProvider credential = new UsernamePasswordCredentialsProvider("jervisliu", "uguess"); JGitUtils.commitAndPush(repository, pathModel, inputStream, commitMessage, credential); Repository repository2 = getRepository(repositoryName); List<PathModel> files = JGitUtils.getFilesInPath(repository2, null, null); for (PathModel p : files) { System.out.println("name: " + p.name); System.out.println("path: " + p.path); System.out.println("isTree: " + p.isTree()); } List<PathModel> files1 = JGitUtils.getFilesInPath(repository2, "mortgagesSample", null); for (PathModel p : files1) { System.out.println(p.name); System.out.println(p.path); System.out.println("isTree: " + p.isTree()); } String contentA = JGitUtils.getStringContent(repository2, null, "mortgagesSample/sometestfile9"); System.out.println(contentA); } public static Repository getRepository(String repositoryName) throws java.io.IOException { // bare repository, ensure .git suffix if (!repositoryName.toLowerCase().endsWith(Constants.DOT_GIT_EXT)) { repositoryName += Constants.DOT_GIT_EXT; } return new FileRepository(new File(REPOSITORIES_ROOT_DIR, repositoryName)); } private static void showRemoteBranches(String repositoryName) { try { FileSettings settings = new FileSettings("my.properties"); GitBlit.self().configureContext(settings, true); RepositoryModel model = GitBlit.self().getRepositoryModel(repositoryName); model.showRemoteBranches = true; GitBlit.self().updateRepositoryModel(model.name, model, false); } catch (GitBlitException g) { g.printStackTrace(); } } }
package com.jlgproject.adapter; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.Priority; import com.jlgproject.R; import com.jlgproject.activity.BusinessVideoPlay; import com.jlgproject.model.Video_Information_Bean; import com.jlgproject.model.Video_List_Bean; import java.util.ArrayList; import java.util.List; /** * @author 王锋 on 2017/7/20. */ public class BusinessVideoPlayAdapter extends BaseAdapter { private Context context; private List<Video_Information_Bean.DataBean.RecommendDetailBean> items; private String img; private String url; public BusinessVideoPlayAdapter(Context context, List<Video_Information_Bean.DataBean.RecommendDetailBean> items) { this.context = context; this.items = items; } public void setItems( List<Video_Information_Bean.DataBean.RecommendDetailBean> items) { this.items = items; } @Override public int getCount() { return items.size(); } @Override public Object getItem(int position) { return items.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, final ViewGroup parent) { VideoHolder vh; if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.sxy_other, null); vh = new VideoHolder(); vh.iv_item_sxy2 = (ImageView) convertView.findViewById(R.id.iv_item_sxy2); vh.tv_title_sxy2 = (TextView) convertView.findViewById(R.id.tv_title_sxy2); vh.tv_jianjian_sxy2 = (TextView) convertView.findViewById(R.id.tv_jianjian_sxy2); vh.tv_jianshi = (TextView) convertView.findViewById(R.id.tv_jianshi); vh.tv_time = (TextView) convertView.findViewById(R.id.tv_time); convertView.setTag(vh); } else { vh = (VideoHolder) convertView.getTag(); } Video_Information_Bean.DataBean.RecommendDetailBean recommendDetailBean = items.get(position); vh.tv_title_sxy2.setText( recommendDetailBean.getTitle()); vh.tv_jianjian_sxy2.setText(recommendDetailBean.getBrief()); vh.tv_time.setText(recommendDetailBean.getUpdateTime()); vh.tv_jianshi.setText("讲师:"+recommendDetailBean.getAuthor()); Glide.with(context).load(recommendDetailBean.getImg()).placeholder(R.mipmap.logo).priority(Priority.HIGH).into(vh.iv_item_sxy2); return convertView; } public class VideoHolder { ImageView iv_item_sxy2; TextView tv_title_sxy2, tv_jianjian_sxy2, tv_jianshi, tv_time; } }
package com.example.administrator.hyxdmvp.fragment.presenter.home; import android.support.v7.widget.RecyclerView; import com.example.administrator.hyxdmvp.AppConfig; import com.example.administrator.hyxdmvp.adapter.TreeAdapter; import com.example.administrator.hyxdmvp.adapter.nodeAdapter.WorkPlanAdapter; import com.example.administrator.hyxdmvp.adapter.nodeAdapter.UserManageAdapter; import com.example.administrator.hyxdmvp.base.BaseOkHttp; import com.example.administrator.hyxdmvp.bean.DropDownItem; import com.example.administrator.hyxdmvp.bean.MenuTreeBean; import com.example.administrator.hyxdmvp.bean.UserDataBean; import com.example.administrator.hyxdmvp.bean.UserManagerBean; import com.example.administrator.hyxdmvp.bean.list.WorkPlanBean; import com.example.administrator.hyxdmvp.fragment.view.home.IHomeFragment; import java.util.LinkedList; public class HomePresenter implements IHomePresenter { private IHomeFragment view; private RecyclerView listData; public HomePresenter(IHomeFragment view) { this.view = view; } @Override public void onDestroy() { view = null; } @Override public void getProjectPlan(String url, BaseOkHttp baseOkHttp) { } public void sendRecycleView(RecyclerView listData) { this.listData = listData; } public void getTreeList(final TreeAdapter treeAdapter) { MenuTreeBean menuBean = new MenuTreeBean(); BaseOkHttp<MenuTreeBean> baseOkHttp; baseOkHttp = new BaseOkHttp<MenuTreeBean>(menuBean, MenuTreeBean.class); baseOkHttp.getData(AppConfig.TreeMenuTestUrl(), new BaseOkHttp.CallBack<MenuTreeBean>() { @Override public void success(MenuTreeBean bean) { treeAdapter.setData(bean.getMyDynamicData()); } @Override public void fail(String s) { view.showToast(s); } }); menuBean = null; } // 获取工作计划列表 public void getWorkPlanList(final WorkPlanAdapter workPlanAdapter, String projectSearchAddUrl) { WorkPlanBean workPlanBean = new WorkPlanBean(); BaseOkHttp<WorkPlanBean> projectPlanBaseOkhttp = new BaseOkHttp<WorkPlanBean>(workPlanBean, WorkPlanBean.class); projectPlanBaseOkhttp.getData(AppConfig.WorkPlanUrl() + projectSearchAddUrl, new BaseOkHttp.CallBack<WorkPlanBean>() { @Override public void success(WorkPlanBean bean) { workPlanAdapter.setData(bean.getMyDynamicData()); listData.setAdapter(workPlanAdapter); } @Override public void fail(String s) { view.showToast(s); } }); workPlanBean = null; } // 获取下拉列表(人名) public void getSpinnerForUser(final WorkPlanAdapter workPlanAdapter) { UserDataBean userBean = new UserDataBean(); BaseOkHttp<UserDataBean> baseOkHttp; baseOkHttp = new BaseOkHttp<UserDataBean>(userBean, UserDataBean.class); baseOkHttp.getData(AppConfig.SpinnerForUserUrl(), new BaseOkHttp.CallBack<UserDataBean>() { @Override public void success(UserDataBean bean) { LinkedList<DropDownItem> mData = new LinkedList<DropDownItem>(); for (int i = 0; i < bean.getMyDynamicData().size(); i++) { mData.add(new DropDownItem(bean.getMyDynamicData().get(i).getF0002(), bean.getMyDynamicData().get(i).getF0002())); } workPlanAdapter.setDownList(mData); } @Override public void fail(String s) { view.showToast(s); } }); userBean = null; } //获取用户列表 public void getUserManagerBean(final UserManageAdapter userManageAdapter, String userManagerSearchAddUrl) { UserManagerBean userManagerBean = new UserManagerBean(); BaseOkHttp<UserManagerBean> userManagerBaseOkhttp = new BaseOkHttp<UserManagerBean>(userManagerBean, UserManagerBean.class); userManagerBaseOkhttp.getData(AppConfig.UserManagerUrl() + userManagerSearchAddUrl, new BaseOkHttp.CallBack<UserManagerBean>() { @Override public void success(UserManagerBean bean) { userManageAdapter.setData(bean.getMyDynamicData()); listData.setAdapter(userManageAdapter); } @Override public void fail(String s) { view.showToast(s); } }); userManagerBean = null; } }
package com.smxknife.disruptor.demo1; import com.lmax.disruptor.BlockingWaitStrategy; import com.lmax.disruptor.RingBuffer; import com.lmax.disruptor.dsl.Disruptor; import com.lmax.disruptor.dsl.ProducerType; import java.util.concurrent.Executors; /** * @author smxknife * 2020/2/24 */ public class Demo1 { public static void main(String[] args) { int bufferSize = 1024 * 1024; LongEventFactory eventFactory = new LongEventFactory(); Disruptor<LongEvent> disruptor = new Disruptor<>(eventFactory, bufferSize, Executors.defaultThreadFactory(), ProducerType.SINGLE, new BlockingWaitStrategy()); // 事件处理start // parallel(disruptor); // serial(disruptor); // diamond(disruptor); chain(disruptor); // 事件处理end RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer(); ringBuffer.publishEvent(new LongEventTranslator(), 10L); ringBuffer.publishEvent(new LongEventTranslator(), 100L); } private static void chain(Disruptor<LongEvent> disruptor) { disruptor.handleEventsWith(new C11EventHandler()).then(new C12EventHandler()); disruptor.handleEventsWith(new C21EventHandler()).then(new C22EventHandler()); disruptor.start(); } private static void diamond(Disruptor<LongEvent> disruptor) { disruptor.handleEventsWith(new C11EventHandler(), new C12EventHandler()).then(new C21EventHandler()); disruptor.start(); } private static void serial(Disruptor<LongEvent> disruptor) { disruptor.handleEventsWith(new C11EventHandler(), new C21EventHandler()); disruptor.start(); } private static void parallel(Disruptor<LongEvent> disruptor) { disruptor.handleEventsWith(new C11EventHandler(), new C21EventHandler()); disruptor.start(); } }
package com.google.android.gms.wearable; import com.google.android.gms.common.data.DataHolder; import com.google.android.gms.wearable.WearableListenerService.a; class WearableListenerService$a$1 implements Runnable { final /* synthetic */ DataHolder bdJ; final /* synthetic */ a bdK; WearableListenerService$a$1(a aVar, DataHolder dataHolder) { this.bdK = aVar; this.bdJ = dataHolder; } public final void run() { e eVar = new e(this.bdJ); try { this.bdK.bdI.a(eVar); } finally { eVar.release(); } } }
package com.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; import javax.persistence.*; @Entity @Table(name = "favorite") @Data @NoArgsConstructor @AllArgsConstructor @Builder public class Favorite { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @OneToOne @JoinColumn(name = "user_id") private User user; @OneToMany(mappedBy = "favorite", fetch = FetchType.LAZY, cascade = CascadeType.ALL) private List<Restaurant> restaurants; }
package com.wcy.netty.client.handler; import com.wcy.netty.protocol.response.LogoutResponsePacket; import com.wcy.netty.util.SessionUtil; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; public class LogoutResponseHandler extends SimpleChannelInboundHandler<LogoutResponsePacket> { @Override protected void channelRead0(ChannelHandlerContext ctx, LogoutResponsePacket msg) throws Exception { SessionUtil.unBindSession(ctx.channel()); } }
package com.example.lab5.room.database; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Update; import com.example.lab5.Category; import java.util.List; @Dao public interface CategoryDao { @Query("SELECT * FROM categories") List<Category> getCategories(); @Query("SELECT * FROM categories WHERE id = :id") Category getCategoryById(int id); @Query("SELECT * FROM categories WHERE id = :id") CategoryWithToDo getCategoryDetail(int id); @Insert void insert(Category category); @Update void update(Category category); @Delete void delete(Category category); }
package com.example.billage.frontend.ui.quest.subView.weekend; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.example.billage.R; import com.example.billage.backend.QuestChecker; import com.example.billage.backend.QuestProcessor; import com.example.billage.frontend.MainActivity; import com.example.billage.frontend.adapter.QuestAdapter; import com.example.billage.frontend.data.QuestList; import com.yy.mobile.rollingtextview.RollingTextView; import org.json.JSONException; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ public class Weekend extends Fragment { RollingTextView coin; public Weekend(RollingTextView coin) { this.coin = coin; // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { int completeRate = 0; int completeCount = 0; // Inflate the layout for this fragment\ View root = inflater.inflate(R.layout.quest_weekend, container, false); QuestProcessor questProcessor = new QuestProcessor(); ArrayList<QuestList> items = questProcessor.getWeekendQuestList(); for(int i = 0; i<items.size();i++){ if(items.get(i).getComplete().equals("true")){ completeCount++; } } completeRate = 100*completeCount/items.size(); ListView listview = (ListView) root.findViewById(R.id.weekend_list); QuestAdapter questAdapter = new QuestAdapter(getActivity(),items,listview,getActivity(),coin); listview.setAdapter(questAdapter); ProgressBar progressBar = root.findViewById(R.id.quest_progress); progressBar.setProgress(completeRate); TextView progress_text = root.findViewById(R.id.progress_text); progress_text.setText(completeRate+"%"); return root; } }
package jpa.project.repository.registedShoes; import com.querydsl.core.types.Projections; import com.querydsl.jpa.impl.JPAQueryFactory; import jpa.project.entity.*; import jpa.project.model.dto.registedShoes.RegistedShoesDto; import jpa.project.repository.RepositoryHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Slice; import javax.persistence.EntityManager; import java.util.List; import java.util.Optional; import static jpa.project.entity.QMember.*; import static jpa.project.entity.QRegistedShoes.*; import static jpa.project.entity.QShoes.*; import static jpa.project.entity.QShoesInSize.*; import static jpa.project.entity.QShoesSize.*; public class RegistedShoesRepositoryImpl implements RegistedShoesRepositoryCustom{ private final JPAQueryFactory queryFactory; @Autowired private EntityManager em; public RegistedShoesRepositoryImpl(EntityManager em) { this.queryFactory = new JPAQueryFactory(em); } @Override public Optional<RegistedShoes> findLowestPriceInShoes(Long id) { return em.createQuery("select r from RegistedShoes r join fetch r.shoesInSize sis " + "join fetch sis.shoes sh where sh.id=:id and r.shoesStatus=jpa.project.entity.ShoesStatus.BID and r.tradeStatus=jpa.project.entity.TradeStatus.SELL order by r.price asc", RegistedShoes.class).setParameter("id", id).getResultList().stream().findFirst(); } @Override public Slice<RegistedShoesDto> findRegistedShoesByTradeStatus(Long memberId,Long lastRegistedShoesId,TradeStatus tradeStatus,Pageable pageable) { List<RegistedShoesDto> registedShoesDtos = queryFactory.select(Projections.constructor(RegistedShoesDto.class,registedShoes.id, shoes.name, shoesSize.US, member.username, registedShoes.price , registedShoes.tradeStatus)).from(registedShoes) .join(registedShoes.shoesInSize, shoesInSize) .join(shoesInSize.shoes, shoes) .join(shoesInSize.size, shoesSize) .join(registedShoes.member, member) .where(member.id.eq(memberId), registedShoes.tradeStatus.eq(tradeStatus) ,registedShoes.id.lt(lastRegistedShoesId) , registedShoes.shoesStatus.eq(ShoesStatus.BID)) .fetch(); return RepositoryHelper.toSlice(registedShoesDtos,pageable); } }
package com.bufeng.ratelimiter.exception; /** * 限流异常类 * * @author liuhailong * @date 2019/8/30 */ public class RateLimiterException extends RuntimeException { private String rateLimiterKey; public String getRateLimiterKey() { return rateLimiterKey; } public RateLimiterException setRateLimiterKey(String rateLimiterKey) { this.rateLimiterKey = rateLimiterKey; return this; } public RateLimiterException(String rateLimiterKey, String message) { super(message); this.rateLimiterKey = rateLimiterKey; } public RateLimiterException(String rateLimiterKey) { this.rateLimiterKey = rateLimiterKey; } @Override public String getMessage() { return rateLimiterKey + "-" + super.getMessage(); } }
package de.unitrier.st.soposthistory.gt.GroundTruthApp; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.LinkedList; public class Toolkit { static boolean blockIsAlreadyInPairWithEdge_atPositionLeft(LinkedList<LinkedList<BlockPair>> allCreatedBlockPairsByClicks, int currentLeftVersion, int blockPositionToBeChecked){ if(currentLeftVersion >= allCreatedBlockPairsByClicks.size()) return false; for(int j=0; j<allCreatedBlockPairsByClicks.get(currentLeftVersion).size(); j++){ if(allCreatedBlockPairsByClicks.get(currentLeftVersion).get(j).leftBlockPosition == blockPositionToBeChecked){ return true; } } return false; } static boolean blockIsAlreadyInPairWithEdge_atPositionRight(LinkedList<LinkedList<BlockPair>> allCreatedBlockPairsByClicks, int currentLeftVersion, int blockPositionToBeChecked){ if(currentLeftVersion >= allCreatedBlockPairsByClicks.size()) return false; for(int j=0; j<allCreatedBlockPairsByClicks.get(currentLeftVersion).size(); j++){ if(allCreatedBlockPairsByClicks.get(currentLeftVersion).get(j).rightBlockPosition == blockPositionToBeChecked){ return true; } } return false; } static Integer getPositionOfLeftBlockRelatedToRightBlockOfSameBlockPair(LinkedList<LinkedList<BlockPair>> allCreatedBlockPairsByClicks, int currentLeftVersion, int blockPositionOfRightBlock){ if(currentLeftVersion >= allCreatedBlockPairsByClicks.size()) return null; for(int j=0; j<allCreatedBlockPairsByClicks.get(currentLeftVersion).size(); j++){ if(allCreatedBlockPairsByClicks.get(currentLeftVersion).get(j).rightBlockPosition == blockPositionOfRightBlock){ return allCreatedBlockPairsByClicks.get(currentLeftVersion).get(j).leftBlockPosition; } } return null; } static LinkedList<String> parseLines(String pathToExportedCSV){ BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new FileReader(pathToExportedCSV)); } catch (FileNotFoundException e) { System.err.println("Failed to read file with path '" + pathToExportedCSV + "'."); System.exit(0); } LinkedList<String> lines = new LinkedList<>(); String line; try { while((line = bufferedReader.readLine()) != null){ lines.add(line); } } catch (IOException e) { System.err.println("Failed to parse line from data at path " + pathToExportedCSV + "."); System.exit(0); } lines.remove(0); // first line contains header return lines; } }
package com.example.senior.adapter; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import com.example.senior.calendar.Constant; import com.example.senior.fragment.CalendarFragment; public class CalendarPagerAdapter extends FragmentStatePagerAdapter { private int mYear; // 声明当前日历所处的年份 // 碎片页适配器的构造函数,传入碎片管理器与年份 public CalendarPagerAdapter(FragmentManager fm, int year) { super(fm); mYear = year; } // 获取碎片Fragment的个数,一年有12个月 public int getCount() { return 12; } // 获取指定月份的碎片Fragment public Fragment getItem(int position) { return CalendarFragment.newInstance(mYear, position + 1); } // 获得指定月份的标题文本 public CharSequence getPageTitle(int position) { return new String(Constant.xuhaoArray[position + 1] + "月"); } }
package com.example.connectiondemo; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.os.AsyncTask; import android.os.Bundle; import android.app.Activity; import android.util.Log; import android.view.Menu; import android.widget.TextView; public class JsonActivity extends Activity { private class DownloadTask extends AsyncTask<Object, Object, Object> { StringBuffer texto = new StringBuffer(); @Override protected Object doInBackground(final Object... urls) { fillData(); return null; } @Override protected void onPostExecute(final Object result) { TextView textItem = (TextView) findViewById(R.id.text_json); textItem.setText(texto); } @Override protected void onPreExecute() { } protected void fillData() { String content = HttpHelper .getContent("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=fernandopcg"); Log.i("Prev", content); JSONArray array; try { array = new JSONArray(content); for (int i = 0; i < array.length(); i++) { JSONObject item = array.getJSONObject(i); String aux = item.getString("text"); Log.i("Json", aux); texto.append(aux).append("\n").append("-----------------------").append("\n"); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_json); new DownloadTask().execute(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.json, menu); return true; } }
public class Product { private int ProId; private String ProName; private int ProP; public int getProId() { return ProId; } public void setProId(int proId) { ProId = proId; } public String getProName() { return ProName; } public void setProName(String proName) { ProName = proName; } public int getProP() { return ProP; } public void setProP(int proP) { ProP = proP; } }
package com.xys.searchbox; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import android.widget.ImageView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText searchbox = (EditText) findViewById(R.id.et_searchbox); final ImageView cancelImg = (ImageView) findViewById(R.id.iv_clean); searchbox.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { if (s == null || s.length() == 0) { cancelImg.setVisibility(View.GONE); } else { cancelImg.setVisibility(View.VISIBLE); if (s.toString().trim().length() == 0) { // 全是空格 searchbox.setTextKeepState(""); } } } }); cancelImg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { searchbox.setTextKeepState(""); } }); } }
/** * Font package. * * This package contains classes and constructs needed for font rendering. At this time the font API * is under development. * * Package state: Under development (restructure needed) */ package fi.jjc.graphics.font;
package sample.Controllers; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.input.*; import javafx.scene.layout.AnchorPane; import javafx.stage.FileChooser; import javafx.stage.Stage; import sample.NewTask.Priority; import sample.NewTask.TaskNew; import sample.Serialize; import java.io.*; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.time.LocalDate; import java.util.ArrayList; import java.util.ResourceBundle; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.csv.CSVRecord; public class Controller implements Initializable, Serializable { public static ObservableList<TaskNew> toDo = FXCollections.observableArrayList(); public static ObservableList<TaskNew> inProgress = FXCollections.observableArrayList(); public static ObservableList<TaskNew> doneObs = FXCollections.observableArrayList(); @FXML public Button btn; public static Stage addNewTask = new Stage(); public ListView<TaskNew> toDoList = new ListView<>(toDo); public ListView<TaskNew> progress = new ListView<>(inProgress); public ListView<TaskNew> done = new ListView<>(doneObs); public ContextMenu menu; public ContextMenu menuProgress; public ContextMenu menuDone; public MenuItem DeleteProgress; public MenuItem EditProgress; public MenuItem DeleteDone; public MenuItem EditDone; public MenuItem Delete; public MenuItem Edit; //------------------------------------------LAB8-------------------------------------------// public MenuItem open; public MenuItem save; public MenuItem export; public MenuItem impor; public AnchorPane anchorPane; Serialize serialize = new Serialize(); @Override public void initialize(URL url, ResourceBundle resourceBundle) { toDoList.setItems(toDo); progress.setItems(inProgress); done.setItems(doneObs); //-------------------------------LAB8-------------------------------------// save.setOnAction(event -> { serialize.firstList = new ArrayList<>(toDo); //rzutuje na arraylist serialize.secondList = new ArrayList<>(inProgress); serialize.thirdList = new ArrayList<>(doneObs); try(ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("TestObject.ser"))){ outputStream.writeObject(serialize); } catch (IOException e) { e.printStackTrace(); } }); open.setOnAction(event -> { try(ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("TestObject.ser"))){ serialize = (Serialize) inputStream.readObject(); } catch (FileNotFoundException e){ System.err.println("File not found "+e); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } toDo= FXCollections.observableArrayList(serialize.firstList); toDoList.setItems(toDo); inProgress= FXCollections.observableArrayList(serialize.secondList); progress.setItems(inProgress); doneObs= FXCollections.observableArrayList(serialize.thirdList); done.setItems(doneObs); }); export.setOnAction(event -> { FileChooser fileChooser = new FileChooser(); //okienko Stage FCstage = (Stage) anchorPane.getScene().getWindow(); File workingDirectory = new File(System.getProperty("user.dir")); fileChooser.setInitialDirectory(workingDirectory); fileChooser.setTitle("Choose file to export data"); fileChooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("CSV", "*.csv") ); File file = fileChooser.showSaveDialog(FCstage); if (file != null) { serialize.firstList = new ArrayList<>(toDo); serialize.secondList = new ArrayList<>(inProgress); serialize.thirdList = new ArrayList<>(doneObs); generateCSVfile(file); } }); impor.setOnAction(event -> { FileChooser fileChooser = new FileChooser(); Stage FCstage = (Stage) anchorPane.getScene().getWindow(); File workingDirectory = new File(System.getProperty("user.dir")); fileChooser.setInitialDirectory(workingDirectory); fileChooser.setTitle("Choose file to import data"); fileChooser.getExtensionFilters().add( new FileChooser.ExtensionFilter("CSV", "*.csv") ); File file = fileChooser.showOpenDialog(FCstage); serialize.firstList = new ArrayList<>(toDo); serialize.secondList = new ArrayList<>(inProgress); serialize.thirdList = new ArrayList<>(doneObs); if (file != null) { try(Reader reader = new FileReader(file.getAbsolutePath())){ loadFromCSVfile(file); toDo= FXCollections.observableArrayList(serialize.firstList); toDoList.setItems(toDo); inProgress= FXCollections.observableArrayList(serialize.secondList); progress.setItems(inProgress); doneObs= FXCollections.observableArrayList(serialize.thirdList); done.setItems(doneObs); } catch (FileNotFoundException | NullPointerException e){ System.err.println("File not found "+e); } catch (IOException e) { } } }); //-------------------------------END-------------------------------------// btn.setOnMouseClicked(mouseEvent -> { try { createAddWindow(); } catch (IOException e) { e.printStackTrace(); } }); toDoList.setCellFactory(p -> new ListCell<TaskNew>() { @Override protected void updateItem(TaskNew item, boolean empty) { super.updateItem(item, empty); if(empty) setText(null); else { setText(getItem().getTitle()); Tooltip tooltip = new Tooltip(); tooltip.setText(getItem().getDescribe()); setTooltip(tooltip); } } }); progress.setCellFactory(p -> new ListCell<TaskNew>() { @Override protected void updateItem(TaskNew item, boolean empty) { super.updateItem(item, empty); if(empty) setText(null); else { setText(getItem().getTitle()); Tooltip tooltip = new Tooltip(); tooltip.setText(getItem().getDescribe()); setTooltip(tooltip); } } }); done.setCellFactory(p -> new ListCell<TaskNew>() { @Override protected void updateItem(TaskNew item, boolean empty) { super.updateItem(item, empty); if(empty) setText(null); else { setText(getItem().getTitle()); Tooltip tooltip = new Tooltip(); tooltip.setText(getItem().getDescribe()); setTooltip(tooltip); } } }); Delete.setOnAction(event -> { toDoList.getItems().remove(toDoList.getItems().get(toDoList.getFocusModel().getFocusedIndex())); }); DeleteProgress.setOnAction(event -> { progress.getItems().remove(progress.getItems().get(progress.getFocusModel().getFocusedIndex())); }); DeleteDone.setOnAction(event -> { done.getItems().remove(done.getItems().get(done.getFocusModel().getFocusedIndex())); }); Edit.setOnAction(event -> { addNewTask.show(); toDoList.getItems().remove(toDoList.getItems().get(toDoList.getFocusModel().getFocusedIndex())); }); EditProgress.setOnAction(event -> { addNewTask.show(); progress.getItems().remove(progress.getItems().get(progress.getFocusModel().getFocusedIndex())); }); EditDone.setOnAction(event -> { addNewTask.show(); done.getItems().remove(done.getItems().get(done.getFocusModel().getFocusedIndex())); }); //DRAG-AND-DROP (From ToDO to Progress) toDoList.setOnDragDetected(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (toDoList.getSelectionModel().getSelectedItem() == null) { return; } Dragboard dragboard = toDoList.startDragAndDrop(TransferMode.MOVE); ClipboardContent content = new ClipboardContent(); content.putString(toDoList.getSelectionModel().getSelectedItem().getTitle()); dragboard.setContent(content); }}); progress.setOnDragOver(new EventHandler<DragEvent>() { @Override public void handle(DragEvent dragEvent) { dragEvent.acceptTransferModes(TransferMode.MOVE); } }); progress.setOnDragDropped(new EventHandler<DragEvent>() { @Override public void handle(DragEvent dragEvent) { String text = dragEvent.getDragboard().getString(); String describe = dragEvent.getDragboard().getString(); Priority priority = TaskNew.getPriority(); LocalDate data = TaskNew.getLocalDate(); progress.getItems().add(new TaskNew(text,priority,data,describe)); toDo.remove(toDoList.getItems().get(toDoList.getFocusModel().getFocusedIndex())); toDoList.setItems(toDo); dragEvent.setDropCompleted(true); } }); //DRAG-AND_DROP (From Progress to Done) progress.setOnDragDetected(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (progress.getSelectionModel().getSelectedItem() == null) { return; } Dragboard dragboard = progress.startDragAndDrop(TransferMode.MOVE); ClipboardContent content = new ClipboardContent(); content.putString(progress.getSelectionModel().getSelectedItem().getTitle()); dragboard.setContent(content); }}); done.setOnDragOver(new EventHandler<DragEvent>() { @Override public void handle(DragEvent dragEvent) { dragEvent.acceptTransferModes(TransferMode.MOVE); } }); done.setOnDragDropped(new EventHandler<DragEvent>() { @Override public void handle(DragEvent dragEvent) { String text = dragEvent.getDragboard().getString(); String describe = dragEvent.getDragboard().getString(); Priority priority = TaskNew.getPriority(); LocalDate data = TaskNew.getLocalDate(); done.getItems().add(new TaskNew(text,priority,data,describe)); inProgress.remove(progress.getItems().get(progress.getFocusModel().getFocusedIndex())); progress.setItems(inProgress); dragEvent.setDropCompleted(true); } }); } @FXML public void createAddWindow() throws IOException { FXMLLoader loaderAddTask = new FXMLLoader(); loaderAddTask.setLocation(Controller.class.getResource("AddNewTask.fxml")); Parent root1 = loaderAddTask.load(); addNewTask.setTitle("Add New Task"); addNewTask.setScene(new Scene(root1,600,400)); addNewTask.show(); } public void generateCSVfile(File file){ try ( BufferedWriter writer = Files.newBufferedWriter(Paths.get(file.getAbsolutePath())); CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT .withHeader("title", "description", "priority", "localDate", "typeOfList")); ) { for (int i = 0; i < serialize.firstList.size(); i++){ csvPrinter.printRecord(serialize.firstList.get(i).getTitle(), serialize.firstList.get(i).getDescribe().replace("\n"," "), serialize.firstList.get(i).getPriority(), serialize.firstList.get(i).getLocalDate(), "First List"); } for (int i = 0; i < serialize.secondList.size(); i++){ csvPrinter.printRecord(serialize.secondList.get(i).getTitle(), serialize.secondList.get(i).getDescribe().replace("\n"," "), serialize.secondList.get(i).getPriority(), serialize.secondList.get(i).getLocalDate(), "Second List"); } for (int i = 0; i < serialize.thirdList.size(); i++){ csvPrinter.printRecord(serialize.thirdList.get(i).getTitle(), serialize.thirdList.get(i).getDescribe().replace("\n"," "), serialize.thirdList.get(i).getPriority(), serialize.thirdList.get(i).getLocalDate(), "Third List"); } csvPrinter.flush(); //oproznia strumien bazowy } catch (IOException e){ } } public void loadFromCSVfile(File file){ try ( Reader reader = Files.newBufferedReader(Paths.get(file.getAbsolutePath())); CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT //analizuje pliki csv .withFirstRecordAsHeader() .withIgnoreHeaderCase() .withTrim()); ) { serialize.firstList.clear(); serialize.secondList.clear(); serialize.thirdList.clear(); for (CSVRecord csvRecord : csvParser) { String title = csvRecord.get("title"); String describe = csvRecord.get("description"); String priority = csvRecord.get("priority"); LocalDate date = LocalDate.parse(csvRecord.get("localDate")); String typeOfList = csvRecord.get("typeOfList"); Priority priority1; if(priority.equals("VERY_HIGH")) {priority1=Priority.VERY_HIGH;} else if(priority.equals("HIGH")){priority1=Priority.HIGH;} else if(priority.equals("MEDIUM")){priority1=Priority.MEDIUM;} else {priority1=Priority.LOW;} System.out.println(priority); switch (typeOfList) { case "First List": serialize.firstList.add(new TaskNew(title, priority1, date, describe)); break; case "Second List": serialize.secondList.add(new TaskNew(title, priority1, date, describe)); break; case "Third List": serialize.thirdList.add(new TaskNew(title, priority1, date, describe)); break; } } } catch (IOException e){ } } }
package src; /** * * @author Mark Lonergan */ public class TestQueue extends javax.swing.JFrame { /** * Creates new form TestQueue */ public TestQueue() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); callPatientBtn = new javax.swing.JButton(); addPatientBtn = new javax.swing.JButton(); nameInput = new javax.swing.JTextField(); priorityInput = new javax.swing.JTextField(); jSeparator1 = new javax.swing.JSeparator(); jScrollPane1 = new javax.swing.JScrollPane(); displayQueue = new javax.swing.JTextArea(); jLabel3 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("Patient Name"); jLabel2.setText("Priority (1-5)"); callPatientBtn.setText("Call Next Patient"); callPatientBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { callPatientBtnActionPerformed(evt); } }); addPatientBtn.setText("Add Patient To Queue"); addPatientBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addPatientBtnActionPerformed(evt); } }); displayQueue.setColumns(20); displayQueue.setRows(5); jScrollPane1.setViewportView(displayQueue); jLabel3.setText("Waiting Room"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(addPatientBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(callPatientBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(priorityInput, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(nameInput, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 241, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(nameInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(priorityInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(callPatientBtn) .addComponent(addPatientBtn)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(76, 76, 76) .addComponent(jLabel3) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 168, Short.MAX_VALUE) .addContainerGap()))) ); pack(); }// </editor-fold>//GEN-END:initComponents private void addPatientBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addPatientBtnActionPerformed // TODO ADD Patient if (!waitingRoom.isFull()) { String name = nameInput.getText(); String tempPriority = priorityInput.getText(); int priority = 0; Patient newPatient = null; try { priority = Integer.parseInt(priorityInput.getText()); } catch (NumberFormatException ex) { System.out.println("Must input a number into priority"); } if ((nameInput.getText() != null) && (priorityInput.getText() != null)) { newPatient = new Patient(name, priority); // TODO From Here waitingRoom.enQueue(newPatient); //displayQueue.append(name + " " + tempPriority + "\n"); } else { System.out.println("Must fill in name and priority!"); } } else { displayQueue.append("Sorry Waiting Room Full\n"); } drawQueue(); }//GEN-LAST:event_addPatientBtnActionPerformed private void callPatientBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_callPatientBtnActionPerformed // TODO Call Next Patient if (!waitingRoom.isEmpty()) { waitingRoom.deQueue(waitingRoom.items.elements[0]); drawQueue(); } }//GEN-LAST:event_callPatientBtnActionPerformed private void drawQueue() { String output = ""; if (!waitingRoom.isEmpty()) { for (int i = 0; i < waitingRoom.numItems; i++) { output += waitingRoom.items.elements[i].patientName + " " + waitingRoom.items.elements[i].priority + "\n"; } } displayQueue.setText(output); } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TestQueue.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TestQueue.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TestQueue.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TestQueue.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TestQueue().setVisible(true); } }); } private PriorityQueue waitingRoom = new PriorityQueue(10); // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addPatientBtn; private javax.swing.JButton callPatientBtn; private javax.swing.JTextArea displayQueue; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator jSeparator1; private javax.swing.JTextField nameInput; private javax.swing.JTextField priorityInput; // End of variables declaration//GEN-END:variables } //problem when adding a patient with a greater priority //reheap up is problem (swap)
package com.sebprunier.jobboard.web; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.servlet.GuiceServletContextListener; import com.google.inject.servlet.ServletModule; public class JobboardGuiceServletContextListener extends GuiceServletContextListener { @Override protected Injector getInjector() { return Guice.createInjector(new ServletModule() { @Override protected void configureServlets() { super.configureServlets(); install(new JobboardWebModule()); } }); } }
package net.senmori.vanillatweaks.config.sections; import net.senmori.senlib.configuration.option.BooleanOption; import net.senmori.senlib.configuration.option.NumberOption; import net.senmori.senlib.configuration.option.SectionOption; public class BabyZombieOption extends SectionOption { public static BabyZombieOption newOption(String key) { return new BabyZombieOption(key); } public final BooleanOption ENABLED = addOption("Baby Zombies Enabled", BooleanOption.newOption("enabled", true)); public final NumberOption FIRE_TICKS = addOption("Baby Zombie Fire Ticks", NumberOption.newOption("length", 1)); public BabyZombieOption(String key) { super(key, key); } }
package NumberUtilitiesPkg; public class NumberUtilities { public static String getRange(int stop) { String s = ""; for(int i = 0 ; i < stop ; i++){ s += i; } return s; } public static String getRange(int start, int stop) { String s = ""; for(int i = start; i < stop ; i++){ s += i; } return s; } public static String getRange(int start, int stop, int step) { String s = ""; for(int i = start; i < stop ; i+=step){ s += i; } return s; } public static String getEvenNumbers(int start, int stop) { String s = ""; for(int i = start; i < stop; i++){ if(i % 2 == 0){ s += i; } } return s; } public static String getOddNumbers(int start, int stop) { String s = ""; for(int i = start; i < stop; i++){ if(i % 2 != 0){ s += i; } } return s; } public static String getExponentiations(int start, int stop, int exponent) { String s = ""; for(int x = start; x <= stop; x ++){ s+= (int)Math.pow(x, exponent); } return s; } }
package com.jpworks.datajdbc.employee.vo; import lombok.Builder; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Version; import org.springframework.data.relational.core.mapping.MappedCollection; import java.time.LocalDate; import java.util.Map; @Data @Builder public class Employee { @Id private Long id; private String firstName; private String lastName; private LocalDate birthDate; private LocalDate hireDate; private String phone; private Gender gender; private EmployeeStatus status; @Version private Integer version; @MappedCollection(keyColumn = "from_date") Map<LocalDate, Salary> salaries; @MappedCollection(keyColumn = "from_date") Map<LocalDate, Address> addresses; }
package org.slevin.dao; import java.math.BigDecimal; import java.util.Date; import org.slevin.common.BinaQueryItem; import org.slevin.common.SahibindenItem; import org.slevin.util.EmlakQueryItem; public interface SahibindenDao extends EntityDao<SahibindenItem> { public BinaQueryItem getDataForCreditSuitable(String urlTemp,Boolean creditSuitable,Long itemIndex) throws Exception; public long complatedCount() throws Exception; public void insertSehir() throws Exception; public void insertIlce() throws Exception; public void insertSemt() throws Exception; public void daireTapuluUpdate(String sorting) throws Exception; public void rezidansTapuluUpdate() throws Exception; public void mustakilEvTapuluUpdate() throws Exception; public void villaTapuluUpdate() throws Exception; public void ciftlikEviTapuluUpdate() throws Exception; public void koskTapuluUpdate() throws Exception; public void yaliTapuluUpdate() throws Exception; public void yaliDairesiTapuluUpdate() throws Exception; public void yazlikDairesiTapuluUpdate() throws Exception; public void prefabrikTapuluUpdate() throws Exception; public void kooperatifTapuluUpdate() throws Exception; public void daireTapusuzUpdate() throws Exception; public void rezidansTapusuzUpdate() throws Exception; public void mustakilEvTapusuzUpdate() throws Exception; public void villaTapusuzUpdate() throws Exception; public void ciftlikEviTapusuzUpdate() throws Exception; public void koskTapusuzUpdate() throws Exception; public void yaliTapusuzUpdate() throws Exception; public void yaliDairesiTapusuzUpdate() throws Exception; public void yazlikDairesiTapusuzUpdate() throws Exception; public void prefabrikTapusuzUpdate() throws Exception; public void kooperatifTapusuzUpdate() throws Exception; public void daireTapuluIlceUpdate(String sorting) throws Exception; public void daireTapuluLast24Hours() throws Exception; public void exportToFile() throws Exception; public void exportToFileByIlce(String directoryPath) throws Exception; public void batchPredict(Date startdate,Date endDate) throws Exception; public BigDecimal predict(EmlakQueryItem emlakQueryItem) throws Exception; }
package com.onplan.adviser.strategy; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import java.io.Serializable; /** * Strategy statistics. */ public final class StrategyStatistics implements Serializable { private long lastReceivedTickTimestamp; private long receivedTicks; private long eventsDispatchedCounter; private long lastCompletionNanoTime; private long maxCompletionNanoTime; private long cumulatedCompletionNanoTime; public long getLastCompletionNanoTime() { return lastCompletionNanoTime; } public void setLastCompletionNanoTime(final long lastCompletionNanoTime) { this.lastCompletionNanoTime = lastCompletionNanoTime; } public long getEventsDispatchedCounter() { return eventsDispatchedCounter; } public void setEventsDispatchedCounter(final long eventsDispatchedCounter) { this.eventsDispatchedCounter = eventsDispatchedCounter; } public long getLastReceivedTickTimestamp() { return lastReceivedTickTimestamp; } public void setLastReceivedTickTimestamp(long lastReceivedTickTimestamp) { this.lastReceivedTickTimestamp = lastReceivedTickTimestamp; } public long getReceivedTicks() { return receivedTicks; } public void setReceivedTicks(long receivedTicks) { this.receivedTicks = receivedTicks; } public long getMaxCompletionNanoTime() { return maxCompletionNanoTime; } public void setMaxCompletionNanoTime(long maxCompletionNanoTime) { this.maxCompletionNanoTime = maxCompletionNanoTime; } public long getCumulatedCompletionNanoTime() { return cumulatedCompletionNanoTime; } public void setCumulatedCompletionNanoTime(long cumulatedCompletionNanoTime) { this.cumulatedCompletionNanoTime = cumulatedCompletionNanoTime; } public void incrementReceivedTicks() { this.receivedTicks++; } public void incrementEventsDispatchedCounter() { this.eventsDispatchedCounter++; } public void incrementCumulatedCompletionNanoTime(final long lastCompletionNanoTime) { this.cumulatedCompletionNanoTime += lastCompletionNanoTime; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } StrategyStatistics strategyStatistics = (StrategyStatistics) o; return Objects.equal( this.lastReceivedTickTimestamp, strategyStatistics.lastReceivedTickTimestamp) && Objects.equal(this.receivedTicks, strategyStatistics.receivedTicks) && Objects.equal(this.eventsDispatchedCounter, strategyStatistics.eventsDispatchedCounter) && Objects.equal(this.lastCompletionNanoTime, strategyStatistics.lastCompletionNanoTime) && Objects.equal(this.maxCompletionNanoTime, strategyStatistics.maxCompletionNanoTime) && Objects.equal( this.cumulatedCompletionNanoTime, strategyStatistics.cumulatedCompletionNanoTime); } @Override public int hashCode() { return Objects.hashCode(lastReceivedTickTimestamp, receivedTicks, eventsDispatchedCounter, lastCompletionNanoTime, maxCompletionNanoTime, cumulatedCompletionNanoTime); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("lastReceivedTickTimestamp", lastReceivedTickTimestamp) .add("receivedTicks", receivedTicks) .add("eventsDispatchedCounter", eventsDispatchedCounter) .add("lastCompletionNanoTime", lastCompletionNanoTime) .add("maxCompletionNanoTime", maxCompletionNanoTime) .add("cumulatedCompletionNanoTime", cumulatedCompletionNanoTime) .toString(); } }
package com.tencent.mm.plugin.voip.model; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.PowerManager; import com.tencent.mm.plugin.voip.b.b; import com.tencent.mm.sdk.platformtools.ad; class o$1 extends BroadcastReceiver { final /* synthetic */ o oMC; o$1(o oVar) { this.oMC = oVar; } public final void onReceive(Context context, Intent intent) { String action = intent.getAction(); PowerManager powerManager = (PowerManager) ad.getContext().getSystemService("power"); if ("android.intent.action.USER_PRESENT".equals(action) && powerManager.isScreenOn()) { o.a(this.oMC, false); } else if ("android.intent.action.SCREEN_ON".equals(action)) { o.a(this.oMC, false); } else if ("android.intent.action.SCREEN_OFF".equals(action)) { o.a(this.oMC, true); if (!b.yU(o.a(this.oMC).mState) && !o.b(this.oMC)) { i.bJI().stopRing(); } } } }
/* * Sonar W3C Markup Validation Plugin * Copyright (C) 2010 Matthijs Galesloot * dev@sonar.codehaus.org * * 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.sonar.plugins.web.markup; import java.util.ArrayList; import java.util.List; import org.sonar.api.Extension; import org.sonar.api.Plugin; import org.sonar.api.Properties; import org.sonar.api.Property; import org.sonar.plugins.web.markup.constants.MarkupValidatorConstants; import org.sonar.plugins.web.markup.resourcetab.GwtPageTab; import org.sonar.plugins.web.markup.rules.DefaultMarkupProfile; import org.sonar.plugins.web.markup.rules.MarkupRuleRepository; /** * W3CMarkupValidation plugin. * * @author Matthijs Galesloot * @since 1.0 */ @Properties({ @Property(key = MarkupValidatorConstants.VALIDATION_URL, name = "W3C Validation URL", description = "URL of the W3C Markup Validation API", defaultValue = "http://validator.w3.org/check", global = true, project = true), @Property(key = MarkupValidatorConstants.PAUSE_BETWEEN_VALIDATIONS, name = "Pause between validations", description = "Pause between validation requests, in milliseconds", defaultValue = "1000", global = true, project = true), @Property(key = MarkupValidatorConstants.PROXY_HOST, name = "Proxy host", global = true, project = true), @Property(key = MarkupValidatorConstants.PROXY_PORT, name = "Proxy port", global = true, project = true) }) public final class W3CMarkupValidationPlugin implements Plugin { public String getDescription() { return null; } public List<Class<? extends Extension>> getExtensions() { List<Class<? extends Extension>> list = new ArrayList<Class<? extends Extension>>(); // W3C markup rules list.add(MarkupRuleRepository.class); list.add(DefaultMarkupProfile.class); list.add(W3CMarkupSensor.class); list.add(PageMetrics.class); list.add(GwtPageTab.class); return list; } public String getKey() { return null; } public String getName() { return null; } @Override public String toString() { return this.getClass().getSimpleName(); } }
package com.bingo.code.example.design.command.cancel; import java.util.ArrayList; import java.util.List; /** * �������࣬���������мӷ���ť��������ť�����г����ͻָ��İ�ť */ public class Calculator { /** * ����IJ�������ʷ��¼���ڳ���ʱ���� */ private List<Command> undoCmds = new ArrayList<Command>(); /** * �����������ʷ��¼���ڻָ�ʱ���� */ private List<Command> redoCmds = new ArrayList<Command>(); private Command addCmd = null; private Command substractCmd = null; public void setAddCmd(Command addCmd) { this.addCmd = addCmd; } public void setSubstractCmd(Command substractCmd) { this.substractCmd = substractCmd; } public void addPressed() { this.addCmd.execute(); //�Ѳ�����¼����ʷ��¼���� undoCmds.add(this.addCmd); } public void substractPressed() { this.substractCmd.execute(); //�Ѳ�����¼����ʷ��¼���� undoCmds.add(this.substractCmd); } public void undoPressed() { if (this.undoCmds.size() > 0) { //ȡ�����һ������������ Command cmd = this.undoCmds.get(this.undoCmds.size() - 1); cmd.undo(); //������лָ��Ĺ��ܣ��ǾͰ���������¼���ָ�����ʷ��¼���� this.redoCmds.add(cmd); //Ȼ������һ������ɾ������ this.undoCmds.remove(cmd); } else { System.out.println("�ܱ�Ǹ��û�пɳ���������"); } } public void redoPressed() { if (this.redoCmds.size() > 0) { //ȡ�����һ������������ Command cmd = this.redoCmds.get(this.redoCmds.size() - 1); cmd.execute(); //����������¼���ɳ�������ʷ��¼���� this.undoCmds.add(cmd); //Ȼ������һ������ɾ���� this.redoCmds.remove(cmd); } else { System.out.println("�ܱ�Ǹ��û�пɻָ�������"); } } }
package com.rishi.baldawa.iq; /* Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6. */ public class MaxSubArray { public int solution(int[] nums) { int maxSoFar = Integer.MIN_VALUE; int max = 0; for (int num : nums) { max += num; if (max > maxSoFar) { maxSoFar = max; } if (max < 0) { max = 0; } } return maxSoFar; } }
package analysis.experiments; import analysis.utils.AnalysisUtils; import analysis.utils.CsvWriter; import datastructures.interfaces.IDictionary; import datastructures.interfaces.IList; public class Experiment1 { // Note: please do not change these constants (or the constants in any of the other experiments) // while working on your writeup public static final int NUM_TRIALS = 5; public static final long MAX_DICTIONARY_SIZE = 20000; public static final long STEP = 100; public static void main(String[] args) { IList<Long> dictionarySizes = AnalysisUtils.makeDoubleLinkedList(0L, MAX_DICTIONARY_SIZE, STEP); // Note: You may be wondering what doing 'Experiment1::test1' do? // Basically, what's happening here is that we're telling Java to: // // a. Take the Experiment1.test1 static method and construct an object representing that method // b. Pass that "function object" to the runTrials method // // Then, what 'runTrials' can do is use that wrapper object to directly call our test1 method // whenever it wants. // // This may seem a little weird at first: we're basically treating a method as a "value" // so we can pass it around. On the other hand, why not? We can pass all kinds of things // ranging from ints and Strings and objects into methods -- why can't we also pass methods // themselves? // // For more information on how AnalysisUtils.runTrials uses the function object, see its // method header comment. // // You can do (ctrl or command) + click on AnalysisUtils.runTrials to jump to its source code // and see its method header comment. System.out.println("Starting experiment 1, test 1"); IList<Long> test1Results = AnalysisUtils.runTrials(dictionarySizes, Experiment1::test1, NUM_TRIALS); System.out.println("Starting experiment 1, test 2"); IList<Long> test2Results = AnalysisUtils.runTrials(dictionarySizes, Experiment1::test2, NUM_TRIALS); System.out.println("Saving experiment 1 results to file"); CsvWriter writer = new CsvWriter(); writer.addColumn("InputDictionarySize", dictionarySizes); writer.addColumn("Test1Results", test1Results); writer.addColumn("Test2Results", test2Results); writer.writeToFile("experimentdata/experiment1.csv"); System.out.println("All done!"); } /** * We will repeatedly call test1 and test2 with different dictionarySizes, and report that result. Your prediction * should estimate how test1 will end up comparing to test2 as the size of the dictionary changes. * * Both test1 and test2 have the same parameter and return meaning: * @param dictionarySize the size of the arrayDictionary. This will the the x-axis of your plot. * @return the amount of time this test took to run, in milliseconds. */ public static long test1(long dictionarySize) { // We don't include the cost of constructing the dictionary when running this test IDictionary<Long, Long> dictionary = AnalysisUtils.makeArrayDictionary(dictionarySize); long start = System.currentTimeMillis(); for (long i = 0L; i < dictionarySize; i++) { //Because our loop starts at 0, this means we're removing the current first element //of the ArrayDictionary every time dictionary.remove(i); } // Returns time elapsed. This will end up being the real-world amount of time // it took to remove all elements of the dictionary return System.currentTimeMillis() - start; } public static long test2(long dictionarySize) { IDictionary<Long, Long> dictionary = AnalysisUtils.makeArrayDictionary(dictionarySize); long start = System.currentTimeMillis(); for (long i = dictionarySize - 1; i >= 0; i--) { // Because this test goes from size - 1 down to 0, we end up removing the last element every time. dictionary.remove(i); } // Returns time elapsed. This will end up being the real-world amount of time // it took to remove all elements of the dictionary return System.currentTimeMillis() - start; } }
package br.usp.memoriavirtual.modelo.entidades; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; @Entity @SequenceGenerator(name = "AUTOR_ID", sequenceName = "AUTOR_SEQ", allocationSize = 1) public class Autor implements Serializable { public static enum Atividade { adaptador, arquiteto, arranjador, classificador, comentador, compilador, cozinheiro, designer, engenheiro, escritor, escultor, fundador, fotografo, horticulturista, ilustrador, interprete, jardineiro, pintor, reporter, revisor, roteirista } private static final long serialVersionUID = 238135871232282769L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AUTOR_ID") private long id; private String nome = ""; private String sobrenome = ""; private String codinome; private Atividade atividade; private String nascimento; private String obito; public Autor() { } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getSobrenome() { return sobrenome; } public void setSobrenome(String sobrenome) { this.sobrenome = sobrenome; } public String getCodinome() { return codinome; } public void setCodinome(String codinome) { this.codinome = codinome; } public Atividade getAtividade() { return atividade; } public void setAtividade(Atividade atividade) { this.atividade = atividade; } public String getNascimento() { return nascimento; } public void setNascimento(String nascimento) { this.nascimento = nascimento; } public String getObito() { return obito; } public void setObito(String obito) { this.obito = obito; } }
package com.yash.product_management.service; import java.io.IOException; import com.yash.product_management.model.Product; public interface ProductService { /** * used for showing the products which are already stored in db */ public void viewProducts(); /** * This method is used for adding products * @throws NumberFormatException * @throws IOException */ public void addProduct() throws NumberFormatException, IOException; /** * used for updating product * @throws NumberFormatException * @throws IOException */ public void updateProduct() throws NumberFormatException, IOException; /** * Used for deleting a entry in product table * @throws IOException */ public void deleteProduct() throws IOException; /** * used to search a product by id * @throws IOException */ public void searchProduct() throws IOException; /** * used to display products * @param product */ public void displayProduct(Product product); }
package com.tencent.mm.ipcinvoker.extension; import com.tencent.mm.ipcinvoker.c; import com.tencent.mm.ipcinvoker.e.a; import com.tencent.mm.ipcinvoker.e.b; import com.tencent.mm.ipcinvoker.extension.XIPCInvoker.WrapperParcelable; class XIPCInvoker$b implements c, a { c<WrapperParcelable> dnb; a dnc; XIPCInvoker$b(c<WrapperParcelable> cVar) { this.dnb = cVar; if (cVar instanceof a) { this.dnc = (a) cVar; } } public final void at(Object obj) { if (this.dnb != null) { this.dnb.at(new WrapperParcelable(null, obj)); } } public final void a(b bVar) { if (this.dnc != null) { this.dnc.a(bVar); } } }
/* * 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.mycompany.springwebapp.dao; import com.mycompany.springwebapp.model.Course; import java.util.List; /** * * @author Siron */ public interface CourseDao { public void insert(Course cm); public List<Course> selectAll(); public Course selectById(int id); public void update(Course cm); public void delete(int id); }
package com.ybh.front.model; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; public class Product_NetCNExample { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table FreeHost_Product_NetCN * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table FreeHost_Product_NetCN * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table FreeHost_Product_NetCN * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ protected List<Criteria> oredCriteria; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table FreeHost_Product_NetCN * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public Product_NetCNExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table FreeHost_Product_NetCN * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table FreeHost_Product_NetCN * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public String getOrderByClause() { return orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table FreeHost_Product_NetCN * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table FreeHost_Product_NetCN * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public boolean isDistinct() { return distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table FreeHost_Product_NetCN * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table FreeHost_Product_NetCN * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table FreeHost_Product_NetCN * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table FreeHost_Product_NetCN * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table FreeHost_Product_NetCN * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table FreeHost_Product_NetCN * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table FreeHost_Product_NetCN * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andUsernameIsNull() { addCriterion("username is null"); return (Criteria) this; } public Criteria andUsernameIsNotNull() { addCriterion("username is not null"); return (Criteria) this; } public Criteria andUsernameEqualTo(String value) { addCriterion("username =", value, "username"); return (Criteria) this; } public Criteria andUsernameNotEqualTo(String value) { addCriterion("username <>", value, "username"); return (Criteria) this; } public Criteria andUsernameGreaterThan(String value) { addCriterion("username >", value, "username"); return (Criteria) this; } public Criteria andUsernameGreaterThanOrEqualTo(String value) { addCriterion("username >=", value, "username"); return (Criteria) this; } public Criteria andUsernameLessThan(String value) { addCriterion("username <", value, "username"); return (Criteria) this; } public Criteria andUsernameLessThanOrEqualTo(String value) { addCriterion("username <=", value, "username"); return (Criteria) this; } public Criteria andUsernameLike(String value) { addCriterion("username like", value, "username"); return (Criteria) this; } public Criteria andUsernameNotLike(String value) { addCriterion("username not like", value, "username"); return (Criteria) this; } public Criteria andUsernameIn(List<String> values) { addCriterion("username in", values, "username"); return (Criteria) this; } public Criteria andUsernameNotIn(List<String> values) { addCriterion("username not in", values, "username"); return (Criteria) this; } public Criteria andUsernameBetween(String value1, String value2) { addCriterion("username between", value1, value2, "username"); return (Criteria) this; } public Criteria andUsernameNotBetween(String value1, String value2) { addCriterion("username not between", value1, value2, "username"); return (Criteria) this; } public Criteria andFtpnameIsNull() { addCriterion("ftpname is null"); return (Criteria) this; } public Criteria andFtpnameIsNotNull() { addCriterion("ftpname is not null"); return (Criteria) this; } public Criteria andFtpnameEqualTo(String value) { addCriterion("ftpname =", value, "ftpname"); return (Criteria) this; } public Criteria andFtpnameNotEqualTo(String value) { addCriterion("ftpname <>", value, "ftpname"); return (Criteria) this; } public Criteria andFtpnameGreaterThan(String value) { addCriterion("ftpname >", value, "ftpname"); return (Criteria) this; } public Criteria andFtpnameGreaterThanOrEqualTo(String value) { addCriterion("ftpname >=", value, "ftpname"); return (Criteria) this; } public Criteria andFtpnameLessThan(String value) { addCriterion("ftpname <", value, "ftpname"); return (Criteria) this; } public Criteria andFtpnameLessThanOrEqualTo(String value) { addCriterion("ftpname <=", value, "ftpname"); return (Criteria) this; } public Criteria andFtpnameLike(String value) { addCriterion("ftpname like", value, "ftpname"); return (Criteria) this; } public Criteria andFtpnameNotLike(String value) { addCriterion("ftpname not like", value, "ftpname"); return (Criteria) this; } public Criteria andFtpnameIn(List<String> values) { addCriterion("ftpname in", values, "ftpname"); return (Criteria) this; } public Criteria andFtpnameNotIn(List<String> values) { addCriterion("ftpname not in", values, "ftpname"); return (Criteria) this; } public Criteria andFtpnameBetween(String value1, String value2) { addCriterion("ftpname between", value1, value2, "ftpname"); return (Criteria) this; } public Criteria andFtpnameNotBetween(String value1, String value2) { addCriterion("ftpname not between", value1, value2, "ftpname"); return (Criteria) this; } public Criteria andFtppasswordIsNull() { addCriterion("Ftppassword is null"); return (Criteria) this; } public Criteria andFtppasswordIsNotNull() { addCriterion("Ftppassword is not null"); return (Criteria) this; } public Criteria andFtppasswordEqualTo(String value) { addCriterion("Ftppassword =", value, "ftppassword"); return (Criteria) this; } public Criteria andFtppasswordNotEqualTo(String value) { addCriterion("Ftppassword <>", value, "ftppassword"); return (Criteria) this; } public Criteria andFtppasswordGreaterThan(String value) { addCriterion("Ftppassword >", value, "ftppassword"); return (Criteria) this; } public Criteria andFtppasswordGreaterThanOrEqualTo(String value) { addCriterion("Ftppassword >=", value, "ftppassword"); return (Criteria) this; } public Criteria andFtppasswordLessThan(String value) { addCriterion("Ftppassword <", value, "ftppassword"); return (Criteria) this; } public Criteria andFtppasswordLessThanOrEqualTo(String value) { addCriterion("Ftppassword <=", value, "ftppassword"); return (Criteria) this; } public Criteria andFtppasswordLike(String value) { addCriterion("Ftppassword like", value, "ftppassword"); return (Criteria) this; } public Criteria andFtppasswordNotLike(String value) { addCriterion("Ftppassword not like", value, "ftppassword"); return (Criteria) this; } public Criteria andFtppasswordIn(List<String> values) { addCriterion("Ftppassword in", values, "ftppassword"); return (Criteria) this; } public Criteria andFtppasswordNotIn(List<String> values) { addCriterion("Ftppassword not in", values, "ftppassword"); return (Criteria) this; } public Criteria andFtppasswordBetween(String value1, String value2) { addCriterion("Ftppassword between", value1, value2, "ftppassword"); return (Criteria) this; } public Criteria andFtppasswordNotBetween(String value1, String value2) { addCriterion("Ftppassword not between", value1, value2, "ftppassword"); return (Criteria) this; } public Criteria andVolumeIsNull() { addCriterion("volume is null"); return (Criteria) this; } public Criteria andVolumeIsNotNull() { addCriterion("volume is not null"); return (Criteria) this; } public Criteria andVolumeEqualTo(String value) { addCriterion("volume =", value, "volume"); return (Criteria) this; } public Criteria andVolumeNotEqualTo(String value) { addCriterion("volume <>", value, "volume"); return (Criteria) this; } public Criteria andVolumeGreaterThan(String value) { addCriterion("volume >", value, "volume"); return (Criteria) this; } public Criteria andVolumeGreaterThanOrEqualTo(String value) { addCriterion("volume >=", value, "volume"); return (Criteria) this; } public Criteria andVolumeLessThan(String value) { addCriterion("volume <", value, "volume"); return (Criteria) this; } public Criteria andVolumeLessThanOrEqualTo(String value) { addCriterion("volume <=", value, "volume"); return (Criteria) this; } public Criteria andVolumeLike(String value) { addCriterion("volume like", value, "volume"); return (Criteria) this; } public Criteria andVolumeNotLike(String value) { addCriterion("volume not like", value, "volume"); return (Criteria) this; } public Criteria andVolumeIn(List<String> values) { addCriterion("volume in", values, "volume"); return (Criteria) this; } public Criteria andVolumeNotIn(List<String> values) { addCriterion("volume not in", values, "volume"); return (Criteria) this; } public Criteria andVolumeBetween(String value1, String value2) { addCriterion("volume between", value1, value2, "volume"); return (Criteria) this; } public Criteria andVolumeNotBetween(String value1, String value2) { addCriterion("volume not between", value1, value2, "volume"); return (Criteria) this; } public Criteria andIpaddressIsNull() { addCriterion("ipaddress is null"); return (Criteria) this; } public Criteria andIpaddressIsNotNull() { addCriterion("ipaddress is not null"); return (Criteria) this; } public Criteria andIpaddressEqualTo(String value) { addCriterion("ipaddress =", value, "ipaddress"); return (Criteria) this; } public Criteria andIpaddressNotEqualTo(String value) { addCriterion("ipaddress <>", value, "ipaddress"); return (Criteria) this; } public Criteria andIpaddressGreaterThan(String value) { addCriterion("ipaddress >", value, "ipaddress"); return (Criteria) this; } public Criteria andIpaddressGreaterThanOrEqualTo(String value) { addCriterion("ipaddress >=", value, "ipaddress"); return (Criteria) this; } public Criteria andIpaddressLessThan(String value) { addCriterion("ipaddress <", value, "ipaddress"); return (Criteria) this; } public Criteria andIpaddressLessThanOrEqualTo(String value) { addCriterion("ipaddress <=", value, "ipaddress"); return (Criteria) this; } public Criteria andIpaddressLike(String value) { addCriterion("ipaddress like", value, "ipaddress"); return (Criteria) this; } public Criteria andIpaddressNotLike(String value) { addCriterion("ipaddress not like", value, "ipaddress"); return (Criteria) this; } public Criteria andIpaddressIn(List<String> values) { addCriterion("ipaddress in", values, "ipaddress"); return (Criteria) this; } public Criteria andIpaddressNotIn(List<String> values) { addCriterion("ipaddress not in", values, "ipaddress"); return (Criteria) this; } public Criteria andIpaddressBetween(String value1, String value2) { addCriterion("ipaddress between", value1, value2, "ipaddress"); return (Criteria) this; } public Criteria andIpaddressNotBetween(String value1, String value2) { addCriterion("ipaddress not between", value1, value2, "ipaddress"); return (Criteria) this; } public Criteria andDbnameIsNull() { addCriterion("dbname is null"); return (Criteria) this; } public Criteria andDbnameIsNotNull() { addCriterion("dbname is not null"); return (Criteria) this; } public Criteria andDbnameEqualTo(String value) { addCriterion("dbname =", value, "dbname"); return (Criteria) this; } public Criteria andDbnameNotEqualTo(String value) { addCriterion("dbname <>", value, "dbname"); return (Criteria) this; } public Criteria andDbnameGreaterThan(String value) { addCriterion("dbname >", value, "dbname"); return (Criteria) this; } public Criteria andDbnameGreaterThanOrEqualTo(String value) { addCriterion("dbname >=", value, "dbname"); return (Criteria) this; } public Criteria andDbnameLessThan(String value) { addCriterion("dbname <", value, "dbname"); return (Criteria) this; } public Criteria andDbnameLessThanOrEqualTo(String value) { addCriterion("dbname <=", value, "dbname"); return (Criteria) this; } public Criteria andDbnameLike(String value) { addCriterion("dbname like", value, "dbname"); return (Criteria) this; } public Criteria andDbnameNotLike(String value) { addCriterion("dbname not like", value, "dbname"); return (Criteria) this; } public Criteria andDbnameIn(List<String> values) { addCriterion("dbname in", values, "dbname"); return (Criteria) this; } public Criteria andDbnameNotIn(List<String> values) { addCriterion("dbname not in", values, "dbname"); return (Criteria) this; } public Criteria andDbnameBetween(String value1, String value2) { addCriterion("dbname between", value1, value2, "dbname"); return (Criteria) this; } public Criteria andDbnameNotBetween(String value1, String value2) { addCriterion("dbname not between", value1, value2, "dbname"); return (Criteria) this; } public Criteria andDbpasswordIsNull() { addCriterion("dbpassword is null"); return (Criteria) this; } public Criteria andDbpasswordIsNotNull() { addCriterion("dbpassword is not null"); return (Criteria) this; } public Criteria andDbpasswordEqualTo(String value) { addCriterion("dbpassword =", value, "dbpassword"); return (Criteria) this; } public Criteria andDbpasswordNotEqualTo(String value) { addCriterion("dbpassword <>", value, "dbpassword"); return (Criteria) this; } public Criteria andDbpasswordGreaterThan(String value) { addCriterion("dbpassword >", value, "dbpassword"); return (Criteria) this; } public Criteria andDbpasswordGreaterThanOrEqualTo(String value) { addCriterion("dbpassword >=", value, "dbpassword"); return (Criteria) this; } public Criteria andDbpasswordLessThan(String value) { addCriterion("dbpassword <", value, "dbpassword"); return (Criteria) this; } public Criteria andDbpasswordLessThanOrEqualTo(String value) { addCriterion("dbpassword <=", value, "dbpassword"); return (Criteria) this; } public Criteria andDbpasswordLike(String value) { addCriterion("dbpassword like", value, "dbpassword"); return (Criteria) this; } public Criteria andDbpasswordNotLike(String value) { addCriterion("dbpassword not like", value, "dbpassword"); return (Criteria) this; } public Criteria andDbpasswordIn(List<String> values) { addCriterion("dbpassword in", values, "dbpassword"); return (Criteria) this; } public Criteria andDbpasswordNotIn(List<String> values) { addCriterion("dbpassword not in", values, "dbpassword"); return (Criteria) this; } public Criteria andDbpasswordBetween(String value1, String value2) { addCriterion("dbpassword between", value1, value2, "dbpassword"); return (Criteria) this; } public Criteria andDbpasswordNotBetween(String value1, String value2) { addCriterion("dbpassword not between", value1, value2, "dbpassword"); return (Criteria) this; } public Criteria andStarttimeIsNull() { addCriterion("starttime is null"); return (Criteria) this; } public Criteria andStarttimeIsNotNull() { addCriterion("starttime is not null"); return (Criteria) this; } public Criteria andStarttimeEqualTo(Date value) { addCriterion("starttime =", value, "starttime"); return (Criteria) this; } public Criteria andStarttimeNotEqualTo(Date value) { addCriterion("starttime <>", value, "starttime"); return (Criteria) this; } public Criteria andStarttimeGreaterThan(Date value) { addCriterion("starttime >", value, "starttime"); return (Criteria) this; } public Criteria andStarttimeGreaterThanOrEqualTo(Date value) { addCriterion("starttime >=", value, "starttime"); return (Criteria) this; } public Criteria andStarttimeLessThan(Date value) { addCriterion("starttime <", value, "starttime"); return (Criteria) this; } public Criteria andStarttimeLessThanOrEqualTo(Date value) { addCriterion("starttime <=", value, "starttime"); return (Criteria) this; } public Criteria andStarttimeIn(List<Date> values) { addCriterion("starttime in", values, "starttime"); return (Criteria) this; } public Criteria andStarttimeNotIn(List<Date> values) { addCriterion("starttime not in", values, "starttime"); return (Criteria) this; } public Criteria andStarttimeBetween(Date value1, Date value2) { addCriterion("starttime between", value1, value2, "starttime"); return (Criteria) this; } public Criteria andStarttimeNotBetween(Date value1, Date value2) { addCriterion("starttime not between", value1, value2, "starttime"); return (Criteria) this; } public Criteria andEndtimeIsNull() { addCriterion("endtime is null"); return (Criteria) this; } public Criteria andEndtimeIsNotNull() { addCriterion("endtime is not null"); return (Criteria) this; } public Criteria andEndtimeEqualTo(Date value) { addCriterion("endtime =", value, "endtime"); return (Criteria) this; } public Criteria andEndtimeNotEqualTo(Date value) { addCriterion("endtime <>", value, "endtime"); return (Criteria) this; } public Criteria andEndtimeGreaterThan(Date value) { addCriterion("endtime >", value, "endtime"); return (Criteria) this; } public Criteria andEndtimeGreaterThanOrEqualTo(Date value) { addCriterion("endtime >=", value, "endtime"); return (Criteria) this; } public Criteria andEndtimeLessThan(Date value) { addCriterion("endtime <", value, "endtime"); return (Criteria) this; } public Criteria andEndtimeLessThanOrEqualTo(Date value) { addCriterion("endtime <=", value, "endtime"); return (Criteria) this; } public Criteria andEndtimeIn(List<Date> values) { addCriterion("endtime in", values, "endtime"); return (Criteria) this; } public Criteria andEndtimeNotIn(List<Date> values) { addCriterion("endtime not in", values, "endtime"); return (Criteria) this; } public Criteria andEndtimeBetween(Date value1, Date value2) { addCriterion("endtime between", value1, value2, "endtime"); return (Criteria) this; } public Criteria andEndtimeNotBetween(Date value1, Date value2) { addCriterion("endtime not between", value1, value2, "endtime"); return (Criteria) this; } public Criteria andDomainIsNull() { addCriterion("Domain is null"); return (Criteria) this; } public Criteria andDomainIsNotNull() { addCriterion("Domain is not null"); return (Criteria) this; } public Criteria andDomainEqualTo(String value) { addCriterion("Domain =", value, "domain"); return (Criteria) this; } public Criteria andDomainNotEqualTo(String value) { addCriterion("Domain <>", value, "domain"); return (Criteria) this; } public Criteria andDomainGreaterThan(String value) { addCriterion("Domain >", value, "domain"); return (Criteria) this; } public Criteria andDomainGreaterThanOrEqualTo(String value) { addCriterion("Domain >=", value, "domain"); return (Criteria) this; } public Criteria andDomainLessThan(String value) { addCriterion("Domain <", value, "domain"); return (Criteria) this; } public Criteria andDomainLessThanOrEqualTo(String value) { addCriterion("Domain <=", value, "domain"); return (Criteria) this; } public Criteria andDomainLike(String value) { addCriterion("Domain like", value, "domain"); return (Criteria) this; } public Criteria andDomainNotLike(String value) { addCriterion("Domain not like", value, "domain"); return (Criteria) this; } public Criteria andDomainIn(List<String> values) { addCriterion("Domain in", values, "domain"); return (Criteria) this; } public Criteria andDomainNotIn(List<String> values) { addCriterion("Domain not in", values, "domain"); return (Criteria) this; } public Criteria andDomainBetween(String value1, String value2) { addCriterion("Domain between", value1, value2, "domain"); return (Criteria) this; } public Criteria andDomainNotBetween(String value1, String value2) { addCriterion("Domain not between", value1, value2, "domain"); return (Criteria) this; } public Criteria andCategoryIsNull() { addCriterion("category is null"); return (Criteria) this; } public Criteria andCategoryIsNotNull() { addCriterion("category is not null"); return (Criteria) this; } public Criteria andCategoryEqualTo(String value) { addCriterion("category =", value, "category"); return (Criteria) this; } public Criteria andCategoryNotEqualTo(String value) { addCriterion("category <>", value, "category"); return (Criteria) this; } public Criteria andCategoryGreaterThan(String value) { addCriterion("category >", value, "category"); return (Criteria) this; } public Criteria andCategoryGreaterThanOrEqualTo(String value) { addCriterion("category >=", value, "category"); return (Criteria) this; } public Criteria andCategoryLessThan(String value) { addCriterion("category <", value, "category"); return (Criteria) this; } public Criteria andCategoryLessThanOrEqualTo(String value) { addCriterion("category <=", value, "category"); return (Criteria) this; } public Criteria andCategoryLike(String value) { addCriterion("category like", value, "category"); return (Criteria) this; } public Criteria andCategoryNotLike(String value) { addCriterion("category not like", value, "category"); return (Criteria) this; } public Criteria andCategoryIn(List<String> values) { addCriterion("category in", values, "category"); return (Criteria) this; } public Criteria andCategoryNotIn(List<String> values) { addCriterion("category not in", values, "category"); return (Criteria) this; } public Criteria andCategoryBetween(String value1, String value2) { addCriterion("category between", value1, value2, "category"); return (Criteria) this; } public Criteria andCategoryNotBetween(String value1, String value2) { addCriterion("category not between", value1, value2, "category"); return (Criteria) this; } public Criteria andProductidIsNull() { addCriterion("productid is null"); return (Criteria) this; } public Criteria andProductidIsNotNull() { addCriterion("productid is not null"); return (Criteria) this; } public Criteria andProductidEqualTo(String value) { addCriterion("productid =", value, "productid"); return (Criteria) this; } public Criteria andProductidNotEqualTo(String value) { addCriterion("productid <>", value, "productid"); return (Criteria) this; } public Criteria andProductidGreaterThan(String value) { addCriterion("productid >", value, "productid"); return (Criteria) this; } public Criteria andProductidGreaterThanOrEqualTo(String value) { addCriterion("productid >=", value, "productid"); return (Criteria) this; } public Criteria andProductidLessThan(String value) { addCriterion("productid <", value, "productid"); return (Criteria) this; } public Criteria andProductidLessThanOrEqualTo(String value) { addCriterion("productid <=", value, "productid"); return (Criteria) this; } public Criteria andProductidLike(String value) { addCriterion("productid like", value, "productid"); return (Criteria) this; } public Criteria andProductidNotLike(String value) { addCriterion("productid not like", value, "productid"); return (Criteria) this; } public Criteria andProductidIn(List<String> values) { addCriterion("productid in", values, "productid"); return (Criteria) this; } public Criteria andProductidNotIn(List<String> values) { addCriterion("productid not in", values, "productid"); return (Criteria) this; } public Criteria andProductidBetween(String value1, String value2) { addCriterion("productid between", value1, value2, "productid"); return (Criteria) this; } public Criteria andProductidNotBetween(String value1, String value2) { addCriterion("productid not between", value1, value2, "productid"); return (Criteria) this; } public Criteria andOsIsNull() { addCriterion("os is null"); return (Criteria) this; } public Criteria andOsIsNotNull() { addCriterion("os is not null"); return (Criteria) this; } public Criteria andOsEqualTo(String value) { addCriterion("os =", value, "os"); return (Criteria) this; } public Criteria andOsNotEqualTo(String value) { addCriterion("os <>", value, "os"); return (Criteria) this; } public Criteria andOsGreaterThan(String value) { addCriterion("os >", value, "os"); return (Criteria) this; } public Criteria andOsGreaterThanOrEqualTo(String value) { addCriterion("os >=", value, "os"); return (Criteria) this; } public Criteria andOsLessThan(String value) { addCriterion("os <", value, "os"); return (Criteria) this; } public Criteria andOsLessThanOrEqualTo(String value) { addCriterion("os <=", value, "os"); return (Criteria) this; } public Criteria andOsLike(String value) { addCriterion("os like", value, "os"); return (Criteria) this; } public Criteria andOsNotLike(String value) { addCriterion("os not like", value, "os"); return (Criteria) this; } public Criteria andOsIn(List<String> values) { addCriterion("os in", values, "os"); return (Criteria) this; } public Criteria andOsNotIn(List<String> values) { addCriterion("os not in", values, "os"); return (Criteria) this; } public Criteria andOsBetween(String value1, String value2) { addCriterion("os between", value1, value2, "os"); return (Criteria) this; } public Criteria andOsNotBetween(String value1, String value2) { addCriterion("os not between", value1, value2, "os"); return (Criteria) this; } public Criteria andIdcIsNull() { addCriterion("idc is null"); return (Criteria) this; } public Criteria andIdcIsNotNull() { addCriterion("idc is not null"); return (Criteria) this; } public Criteria andIdcEqualTo(String value) { addCriterion("idc =", value, "idc"); return (Criteria) this; } public Criteria andIdcNotEqualTo(String value) { addCriterion("idc <>", value, "idc"); return (Criteria) this; } public Criteria andIdcGreaterThan(String value) { addCriterion("idc >", value, "idc"); return (Criteria) this; } public Criteria andIdcGreaterThanOrEqualTo(String value) { addCriterion("idc >=", value, "idc"); return (Criteria) this; } public Criteria andIdcLessThan(String value) { addCriterion("idc <", value, "idc"); return (Criteria) this; } public Criteria andIdcLessThanOrEqualTo(String value) { addCriterion("idc <=", value, "idc"); return (Criteria) this; } public Criteria andIdcLike(String value) { addCriterion("idc like", value, "idc"); return (Criteria) this; } public Criteria andIdcNotLike(String value) { addCriterion("idc not like", value, "idc"); return (Criteria) this; } public Criteria andIdcIn(List<String> values) { addCriterion("idc in", values, "idc"); return (Criteria) this; } public Criteria andIdcNotIn(List<String> values) { addCriterion("idc not in", values, "idc"); return (Criteria) this; } public Criteria andIdcBetween(String value1, String value2) { addCriterion("idc between", value1, value2, "idc"); return (Criteria) this; } public Criteria andIdcNotBetween(String value1, String value2) { addCriterion("idc not between", value1, value2, "idc"); return (Criteria) this; } public Criteria andVyearIsNull() { addCriterion("vyear is null"); return (Criteria) this; } public Criteria andVyearIsNotNull() { addCriterion("vyear is not null"); return (Criteria) this; } public Criteria andVyearEqualTo(Integer value) { addCriterion("vyear =", value, "vyear"); return (Criteria) this; } public Criteria andVyearNotEqualTo(Integer value) { addCriterion("vyear <>", value, "vyear"); return (Criteria) this; } public Criteria andVyearGreaterThan(Integer value) { addCriterion("vyear >", value, "vyear"); return (Criteria) this; } public Criteria andVyearGreaterThanOrEqualTo(Integer value) { addCriterion("vyear >=", value, "vyear"); return (Criteria) this; } public Criteria andVyearLessThan(Integer value) { addCriterion("vyear <", value, "vyear"); return (Criteria) this; } public Criteria andVyearLessThanOrEqualTo(Integer value) { addCriterion("vyear <=", value, "vyear"); return (Criteria) this; } public Criteria andVyearIn(List<Integer> values) { addCriterion("vyear in", values, "vyear"); return (Criteria) this; } public Criteria andVyearNotIn(List<Integer> values) { addCriterion("vyear not in", values, "vyear"); return (Criteria) this; } public Criteria andVyearBetween(Integer value1, Integer value2) { addCriterion("vyear between", value1, value2, "vyear"); return (Criteria) this; } public Criteria andVyearNotBetween(Integer value1, Integer value2) { addCriterion("vyear not between", value1, value2, "vyear"); return (Criteria) this; } public Criteria andAmountIsNull() { addCriterion("amount is null"); return (Criteria) this; } public Criteria andAmountIsNotNull() { addCriterion("amount is not null"); return (Criteria) this; } public Criteria andAmountEqualTo(Integer value) { addCriterion("amount =", value, "amount"); return (Criteria) this; } public Criteria andAmountNotEqualTo(Integer value) { addCriterion("amount <>", value, "amount"); return (Criteria) this; } public Criteria andAmountGreaterThan(Integer value) { addCriterion("amount >", value, "amount"); return (Criteria) this; } public Criteria andAmountGreaterThanOrEqualTo(Integer value) { addCriterion("amount >=", value, "amount"); return (Criteria) this; } public Criteria andAmountLessThan(Integer value) { addCriterion("amount <", value, "amount"); return (Criteria) this; } public Criteria andAmountLessThanOrEqualTo(Integer value) { addCriterion("amount <=", value, "amount"); return (Criteria) this; } public Criteria andAmountIn(List<Integer> values) { addCriterion("amount in", values, "amount"); return (Criteria) this; } public Criteria andAmountNotIn(List<Integer> values) { addCriterion("amount not in", values, "amount"); return (Criteria) this; } public Criteria andAmountBetween(Integer value1, Integer value2) { addCriterion("amount between", value1, value2, "amount"); return (Criteria) this; } public Criteria andAmountNotBetween(Integer value1, Integer value2) { addCriterion("amount not between", value1, value2, "amount"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(String value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(String value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(String value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(String value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(String value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(String value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusLike(String value) { addCriterion("status like", value, "status"); return (Criteria) this; } public Criteria andStatusNotLike(String value) { addCriterion("status not like", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<String> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<String> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(String value1, String value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(String value1, String value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andCorewhatIsNull() { addCriterion("corewhat is null"); return (Criteria) this; } public Criteria andCorewhatIsNotNull() { addCriterion("corewhat is not null"); return (Criteria) this; } public Criteria andCorewhatEqualTo(String value) { addCriterion("corewhat =", value, "corewhat"); return (Criteria) this; } public Criteria andCorewhatNotEqualTo(String value) { addCriterion("corewhat <>", value, "corewhat"); return (Criteria) this; } public Criteria andCorewhatGreaterThan(String value) { addCriterion("corewhat >", value, "corewhat"); return (Criteria) this; } public Criteria andCorewhatGreaterThanOrEqualTo(String value) { addCriterion("corewhat >=", value, "corewhat"); return (Criteria) this; } public Criteria andCorewhatLessThan(String value) { addCriterion("corewhat <", value, "corewhat"); return (Criteria) this; } public Criteria andCorewhatLessThanOrEqualTo(String value) { addCriterion("corewhat <=", value, "corewhat"); return (Criteria) this; } public Criteria andCorewhatLike(String value) { addCriterion("corewhat like", value, "corewhat"); return (Criteria) this; } public Criteria andCorewhatNotLike(String value) { addCriterion("corewhat not like", value, "corewhat"); return (Criteria) this; } public Criteria andCorewhatIn(List<String> values) { addCriterion("corewhat in", values, "corewhat"); return (Criteria) this; } public Criteria andCorewhatNotIn(List<String> values) { addCriterion("corewhat not in", values, "corewhat"); return (Criteria) this; } public Criteria andCorewhatBetween(String value1, String value2) { addCriterion("corewhat between", value1, value2, "corewhat"); return (Criteria) this; } public Criteria andCorewhatNotBetween(String value1, String value2) { addCriterion("corewhat not between", value1, value2, "corewhat"); return (Criteria) this; } public Criteria andAgent1IsNull() { addCriterion("agent1 is null"); return (Criteria) this; } public Criteria andAgent1IsNotNull() { addCriterion("agent1 is not null"); return (Criteria) this; } public Criteria andAgent1EqualTo(String value) { addCriterion("agent1 =", value, "agent1"); return (Criteria) this; } public Criteria andAgent1NotEqualTo(String value) { addCriterion("agent1 <>", value, "agent1"); return (Criteria) this; } public Criteria andAgent1GreaterThan(String value) { addCriterion("agent1 >", value, "agent1"); return (Criteria) this; } public Criteria andAgent1GreaterThanOrEqualTo(String value) { addCriterion("agent1 >=", value, "agent1"); return (Criteria) this; } public Criteria andAgent1LessThan(String value) { addCriterion("agent1 <", value, "agent1"); return (Criteria) this; } public Criteria andAgent1LessThanOrEqualTo(String value) { addCriterion("agent1 <=", value, "agent1"); return (Criteria) this; } public Criteria andAgent1Like(String value) { addCriterion("agent1 like", value, "agent1"); return (Criteria) this; } public Criteria andAgent1NotLike(String value) { addCriterion("agent1 not like", value, "agent1"); return (Criteria) this; } public Criteria andAgent1In(List<String> values) { addCriterion("agent1 in", values, "agent1"); return (Criteria) this; } public Criteria andAgent1NotIn(List<String> values) { addCriterion("agent1 not in", values, "agent1"); return (Criteria) this; } public Criteria andAgent1Between(String value1, String value2) { addCriterion("agent1 between", value1, value2, "agent1"); return (Criteria) this; } public Criteria andAgent1NotBetween(String value1, String value2) { addCriterion("agent1 not between", value1, value2, "agent1"); return (Criteria) this; } public Criteria andAgent2IsNull() { addCriterion("agent2 is null"); return (Criteria) this; } public Criteria andAgent2IsNotNull() { addCriterion("agent2 is not null"); return (Criteria) this; } public Criteria andAgent2EqualTo(String value) { addCriterion("agent2 =", value, "agent2"); return (Criteria) this; } public Criteria andAgent2NotEqualTo(String value) { addCriterion("agent2 <>", value, "agent2"); return (Criteria) this; } public Criteria andAgent2GreaterThan(String value) { addCriterion("agent2 >", value, "agent2"); return (Criteria) this; } public Criteria andAgent2GreaterThanOrEqualTo(String value) { addCriterion("agent2 >=", value, "agent2"); return (Criteria) this; } public Criteria andAgent2LessThan(String value) { addCriterion("agent2 <", value, "agent2"); return (Criteria) this; } public Criteria andAgent2LessThanOrEqualTo(String value) { addCriterion("agent2 <=", value, "agent2"); return (Criteria) this; } public Criteria andAgent2Like(String value) { addCriterion("agent2 like", value, "agent2"); return (Criteria) this; } public Criteria andAgent2NotLike(String value) { addCriterion("agent2 not like", value, "agent2"); return (Criteria) this; } public Criteria andAgent2In(List<String> values) { addCriterion("agent2 in", values, "agent2"); return (Criteria) this; } public Criteria andAgent2NotIn(List<String> values) { addCriterion("agent2 not in", values, "agent2"); return (Criteria) this; } public Criteria andAgent2Between(String value1, String value2) { addCriterion("agent2 between", value1, value2, "agent2"); return (Criteria) this; } public Criteria andAgent2NotBetween(String value1, String value2) { addCriterion("agent2 not between", value1, value2, "agent2"); return (Criteria) this; } public Criteria andRepaymoneyIsNull() { addCriterion("repaymoney is null"); return (Criteria) this; } public Criteria andRepaymoneyIsNotNull() { addCriterion("repaymoney is not null"); return (Criteria) this; } public Criteria andRepaymoneyEqualTo(BigDecimal value) { addCriterion("repaymoney =", value, "repaymoney"); return (Criteria) this; } public Criteria andRepaymoneyNotEqualTo(BigDecimal value) { addCriterion("repaymoney <>", value, "repaymoney"); return (Criteria) this; } public Criteria andRepaymoneyGreaterThan(BigDecimal value) { addCriterion("repaymoney >", value, "repaymoney"); return (Criteria) this; } public Criteria andRepaymoneyGreaterThanOrEqualTo(BigDecimal value) { addCriterion("repaymoney >=", value, "repaymoney"); return (Criteria) this; } public Criteria andRepaymoneyLessThan(BigDecimal value) { addCriterion("repaymoney <", value, "repaymoney"); return (Criteria) this; } public Criteria andRepaymoneyLessThanOrEqualTo(BigDecimal value) { addCriterion("repaymoney <=", value, "repaymoney"); return (Criteria) this; } public Criteria andRepaymoneyIn(List<BigDecimal> values) { addCriterion("repaymoney in", values, "repaymoney"); return (Criteria) this; } public Criteria andRepaymoneyNotIn(List<BigDecimal> values) { addCriterion("repaymoney not in", values, "repaymoney"); return (Criteria) this; } public Criteria andRepaymoneyBetween(BigDecimal value1, BigDecimal value2) { addCriterion("repaymoney between", value1, value2, "repaymoney"); return (Criteria) this; } public Criteria andRepaymoneyNotBetween(BigDecimal value1, BigDecimal value2) { addCriterion("repaymoney not between", value1, value2, "repaymoney"); return (Criteria) this; } public Criteria andEmailstatusIsNull() { addCriterion("emailstatus is null"); return (Criteria) this; } public Criteria andEmailstatusIsNotNull() { addCriterion("emailstatus is not null"); return (Criteria) this; } public Criteria andEmailstatusEqualTo(String value) { addCriterion("emailstatus =", value, "emailstatus"); return (Criteria) this; } public Criteria andEmailstatusNotEqualTo(String value) { addCriterion("emailstatus <>", value, "emailstatus"); return (Criteria) this; } public Criteria andEmailstatusGreaterThan(String value) { addCriterion("emailstatus >", value, "emailstatus"); return (Criteria) this; } public Criteria andEmailstatusGreaterThanOrEqualTo(String value) { addCriterion("emailstatus >=", value, "emailstatus"); return (Criteria) this; } public Criteria andEmailstatusLessThan(String value) { addCriterion("emailstatus <", value, "emailstatus"); return (Criteria) this; } public Criteria andEmailstatusLessThanOrEqualTo(String value) { addCriterion("emailstatus <=", value, "emailstatus"); return (Criteria) this; } public Criteria andEmailstatusLike(String value) { addCriterion("emailstatus like", value, "emailstatus"); return (Criteria) this; } public Criteria andEmailstatusNotLike(String value) { addCriterion("emailstatus not like", value, "emailstatus"); return (Criteria) this; } public Criteria andEmailstatusIn(List<String> values) { addCriterion("emailstatus in", values, "emailstatus"); return (Criteria) this; } public Criteria andEmailstatusNotIn(List<String> values) { addCriterion("emailstatus not in", values, "emailstatus"); return (Criteria) this; } public Criteria andEmailstatusBetween(String value1, String value2) { addCriterion("emailstatus between", value1, value2, "emailstatus"); return (Criteria) this; } public Criteria andEmailstatusNotBetween(String value1, String value2) { addCriterion("emailstatus not between", value1, value2, "emailstatus"); return (Criteria) this; } public Criteria andSmsstatusIsNull() { addCriterion("smsstatus is null"); return (Criteria) this; } public Criteria andSmsstatusIsNotNull() { addCriterion("smsstatus is not null"); return (Criteria) this; } public Criteria andSmsstatusEqualTo(String value) { addCriterion("smsstatus =", value, "smsstatus"); return (Criteria) this; } public Criteria andSmsstatusNotEqualTo(String value) { addCriterion("smsstatus <>", value, "smsstatus"); return (Criteria) this; } public Criteria andSmsstatusGreaterThan(String value) { addCriterion("smsstatus >", value, "smsstatus"); return (Criteria) this; } public Criteria andSmsstatusGreaterThanOrEqualTo(String value) { addCriterion("smsstatus >=", value, "smsstatus"); return (Criteria) this; } public Criteria andSmsstatusLessThan(String value) { addCriterion("smsstatus <", value, "smsstatus"); return (Criteria) this; } public Criteria andSmsstatusLessThanOrEqualTo(String value) { addCriterion("smsstatus <=", value, "smsstatus"); return (Criteria) this; } public Criteria andSmsstatusLike(String value) { addCriterion("smsstatus like", value, "smsstatus"); return (Criteria) this; } public Criteria andSmsstatusNotLike(String value) { addCriterion("smsstatus not like", value, "smsstatus"); return (Criteria) this; } public Criteria andSmsstatusIn(List<String> values) { addCriterion("smsstatus in", values, "smsstatus"); return (Criteria) this; } public Criteria andSmsstatusNotIn(List<String> values) { addCriterion("smsstatus not in", values, "smsstatus"); return (Criteria) this; } public Criteria andSmsstatusBetween(String value1, String value2) { addCriterion("smsstatus between", value1, value2, "smsstatus"); return (Criteria) this; } public Criteria andSmsstatusNotBetween(String value1, String value2) { addCriterion("smsstatus not between", value1, value2, "smsstatus"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table FreeHost_Product_NetCN * * @mbg.generated do_not_delete_during_merge Fri May 11 11:16:07 CST 2018 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table FreeHost_Product_NetCN * * @mbg.generated Fri May 11 11:16:07 CST 2018 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package fr.cg95.cvq.generator.plugins.enumeration; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.apache.log4j.Logger; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlOptions; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import fr.cg95.cvq.generator.ApplicationDocumentation; import fr.cg95.cvq.generator.ElementProperties; import fr.cg95.cvq.generator.IPluginGenerator; import fr.cg95.cvq.generator.UserDocumentation; import fr.cg95.cvq.generator.tool.XmlValidator; import fr.cg95.cvq.schema.referential.LocalReferentialDocument; import fr.cg95.cvq.schema.referential.LocalReferentialDocument.LocalReferential; /** * The enumeration plugin is interested in global (ie statically defined enumerations strings) * and local (ie up to the collectivity's choice) referential data. * * It generateds the following XML files : * <li> * <ul>An XML global referential file</ul> * <ul>An XML local referential file for each request defining a new one</ul> * <ul>An XML local referential file for common referential data types</ul> * </li> * * @author bor@zenexity.fr * @see Generator/src/xml/schemas/referential/ReferentialData.xsd */ public class EnumerationPlugin implements IPluginGenerator { private static Logger logger = Logger.getLogger(EnumerationPlugin.class); private static String LOCAL_REFERENTIAL_TYPE = "LocalReferentialDataType"; private static String XML_HEADER_DECLARATION = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; /** * The directory in which the XML local referential skeleton file is to be generated. */ private String localReferentialDir; /** * The current request name. */ private String currentRequestName; /** * The current request's namespace. */ private String currentRequestNamespace; /** * The name of the current element (is used as the enumeration type if it is an anonymous one). */ private String currentElementName; /** * To know when we have to parse user documentation to retrieve a local referential element's * information. */ private boolean waitingForLocalReferential; private LocalReferentialDocument requestLrdDoc; private LocalReferential.Data currentLocalReferentialData; public void initialize(Node configurationNode) { logger.debug("initialize()"); NodeList nodeList = configurationNode.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node childNode = nodeList.item(i); if (childNode.getNodeName().equals("output")) { NamedNodeMap childAttributesMap = childNode.getAttributes(); Node valueAttribute = childAttributesMap.getNamedItem("localdir"); logger.debug("initialize() local referential dir : " + valueAttribute.getNodeValue()); localReferentialDir = valueAttribute.getNodeValue(); } } } public void shutdown() { logger.debug("shutdown()"); } public void startRequest(String requestName, String targetNamespace) { logger.debug("startRequest() Name : " + requestName); logger.debug("startRequest() Target namespace : " + targetNamespace); currentRequestName = requestName; currentRequestNamespace = targetNamespace; } public void endRequest(String requestName) { logger.debug("endRequest() Name : " + requestName); generateLocalReferential(); requestLrdDoc = null; } public void startElement(String elementName, String type) { currentElementName = elementName; logger.debug("startElement() Type : " + type); if (type.indexOf(LOCAL_REFERENTIAL_TYPE) != -1) { // local referential : LocalReferentialDataType logger.debug("startElement() got a local referential : " + currentElementName); waitingForLocalReferential = true; } } public void endElement(String elementName) { currentElementName = null; waitingForLocalReferential = false; currentLocalReferentialData = null; } public void startElementProperties(ElementProperties elementProperties) { // local referential if (waitingForLocalReferential) { // not inherited so that's a request local referential type LocalReferential localReferential = null; if (requestLrdDoc == null) { requestLrdDoc = LocalReferentialDocument.Factory.newInstance(); localReferential = requestLrdDoc.addNewLocalReferential(); localReferential.setRequest(currentRequestName); } else { localReferential = requestLrdDoc.getLocalReferential(); } localReferential.addNewData(); localReferential.setDataArray(localReferential.sizeOfDataArray() - 1, currentLocalReferentialData); } } public void endElementProperties() { } public void onUserInformation(UserDocumentation userDocumentation) { if (waitingForLocalReferential && userDocumentation.getSourceUri().equalsIgnoreCase(SHORT_DESC)) { if (currentLocalReferentialData == null) currentLocalReferentialData = LocalReferential.Data.Factory.newInstance(); currentLocalReferentialData.setName(currentElementName); LocalReferential.Data.Label label = currentLocalReferentialData.addNewLabel(); label.setLang(userDocumentation.getLang()); label.setStringValue(userDocumentation.getText()); } } public void onApplicationInformation(ApplicationDocumentation applicationDocumentation) { } /** * Create and save the XML file containing all local referential data declared in a given * request. */ private void generateLocalReferential() { logger.debug("generateLocalReferential()"); if (requestLrdDoc == null) { logger.debug("generateLocalReferential() nothing to generate, returning"); return; } if (!XmlValidator.validate(requestLrdDoc)) { logger.error("generateLocalReferential() local referential file is not valid, cancelling generation ..."); return; } String currentNamespaceAlias = currentRequestNamespace.substring(currentRequestNamespace.lastIndexOf('/') + 1); StringBuffer outputFile = new StringBuffer().append(localReferentialDir).append("/") .append("local_referential_").append(currentNamespaceAlias).append(".xml"); writeXmlFile(outputFile.toString(), requestLrdDoc); } private final void writeXmlFile(final String filename, final XmlObject xmlObject) { XmlOptions opts = new XmlOptions(); opts.setSavePrettyPrint(); opts.setSavePrettyPrintIndent(4); opts.setUseDefaultNamespace(); opts.setCharacterEncoding("UTF-8"); String dataToWrite = xmlObject.xmlText(opts); FileOutputStream fos = null; try { fos = new FileOutputStream(filename); fos.write(XML_HEADER_DECLARATION.getBytes()); fos.write(dataToWrite.getBytes()); } catch (FileNotFoundException fnfe) { logger.error("writeXmlFile() unable to create file : " + filename.toString()); } catch (IOException ioe) { logger.error("writeXmlFile() error writing XML file " + ioe.getMessage()); } } }
package day38_inheritance_part2; public class VehicleTest { public static void main(String[] args) { Car c = new Car(); c.display(); } } class Vehicle { int maxSpeed=120; } class Car extends Vehicle { int maxSpeed=180; void display() { System.out.println("Maximum speed: "+super.maxSpeed); System.out.println("Maximum speed:"+ maxSpeed); } }
package ba.bitcamp.LabS07D03; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.JFrame; import javax.swing.JPanel; public class PainterPlus { /** * Lista boja koje korisnik može odabrati za crtanje. */ private static Color[] palette = new Color[] { Color.WHITE, Color.BLACK, Color.RED, Color.BLUE, Color.GREEN, Color.CYAN, Color.MAGENTA, new Color(133, 7, 42), }; static ColorPicker cp; /** * Veličina kvadratića u paleti boja. */ private static int colorPickerSize = 50; public static void main(String[] args) { PaintListener listener = new PaintListener(); Canvas canvasPanel = new Canvas(); canvasPanel.setBackground(Color.WHITE); canvasPanel.addMouseListener(listener); canvasPanel.addMouseMotionListener(listener); JFrame mainWindow = new JFrame("Paint+"); mainWindow.setContentPane(canvasPanel); cp = new ColorPicker(); mainWindow.add(cp); // postavljamo širinu prozora tako da vidimo sve boje mainWindow.setSize(palette.length * colorPickerSize, 500); mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainWindow.setVisible(true); } public static class PaintListener implements MouseListener, MouseMotionListener { private Color selectedColor = Color.RED; /** * Provjerava koordinate na kojima se nalazio kursor miša i poredi * s indeksima niza palette u kojem se nalaze boje iscrtane na dnu * ekrana. Ako se klik poklapa s nekom pojom, stavlja tu boju u * privatni atribut selectedColor. * * Obratite pažnju da ovdje koristimo dva privatna statička atributa klase * PainterPlus kojima imamo pristup jer je klasa PaintListener static * nested klasa koja pripada klasi PaintPlus. Ako bismo klasu PaintListener * izdvojili u poseban fajl, ovim atributima ne bismo imali pristup. */ @Override public void mousePressed(MouseEvent e) { Component source = (Component)e.getSource(); if (e.getY() >= source.getHeight() - colorPickerSize) { for (int i = 0; i < palette.length; i++) { if (e.getX() < colorPickerSize * (i+1)) { selectedColor = palette[i]; // ako bismo ovdje zaboravili break, for petlja // bi se nastavila izvršavati za ostale boje // a pošto bi uslov bio ispunjen i za njih, // bila bi odabrana posljednja broja u listi, a ne // ona na koju je korisnik kliknuo break; } } } } @Override public void mouseDragged(MouseEvent e) { Component source = (Component)e.getSource(); Graphics g = source.getGraphics(); g.setColor(cp.currentColor); int ovalDiameter = 10; g.fillOval(e.getX() - ovalDiameter/2, e.getY() - ovalDiameter/2, ovalDiameter, ovalDiameter); } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseClicked(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { } } public static class Canvas extends JPanel { /** * Crta onoliko pravougaonika različitih boja koliko imamo elemenata * u listi palette. * * Obratite pažnju da je palette privatni static atribut klase PainterPlus, * međutim da mu još uvijek imamo pristup iz nested static klase Canvas. * Ako bismo klasu Canvas izdvojili u poseban fajl, ne bismo više imali pristup * privatnim atributima. */ @Override public void paintComponent(Graphics g) { for (int i = 0; i < palette.length; i++) { g.setColor(palette[i]); g.fillRect(colorPickerSize * i, getHeight() - colorPickerSize, colorPickerSize, colorPickerSize); } } } }
package miniTenis; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.KeyEvent; public class Racquet { private static final int Y = 300; private static final int WITH = 50; private static final int HEIGHT = 100; int x = 0; int xa = 0; private MiniTenis game; public Racquet(MiniTenis game) { this.game = game; } public void move() { if (x + xa > 0 && x + xa < game.getWidth() - WITH) x = x + xa; } public void paint(Graphics2D g) { Toolkit t = Toolkit.getDefaultToolkit (); Image imagen = t.getImage ("miniJuego/miniTenis/tubo.png"); g.drawImage(imagen,x,Y, game); } public void keyReleased(KeyEvent e) { xa = 0; } public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT) xa = -game.speed; if (e.getKeyCode() == KeyEvent.VK_RIGHT) xa = game.speed; } public Rectangle getBounds() { return new Rectangle(x, Y, WITH, HEIGHT); } public int getTopY() { return Y - HEIGHT; } }
package com.bingo.code.example.design.strategy.payment; /** * ֧�������п� */ public class Card2 implements PaymentStrategy{ /** * �ʺ���Ϣ */ private String account = ""; /** * ���췽���������ʺ���Ϣ * @param account �ʺ���Ϣ */ public Card2(String account){ this.account = account; } public void pay(PaymentContext ctx) { System.out.println("���ڸ�"+ctx.getUserName()+"��"+this.account+"�ʺ�֧����"+ctx.getMoney()+"Ԫ"); //�������У�����ת�ʣ��Ͳ�ȥ���� } }
package essentials.validators; public class UserValidator { public static void main (String[] args) { System.out.println("Starting... "); System.out.println("Gather data..."); User user = new User(34.5, 198, "Przemek"); if (user.validateName()) { if (user.validateHeight() && user.validateAge()) { System.out.println("User: " + user.getName() + " is older than 30 and higher then 160cm"); } else { System.out.println("User: " + user.getName() + " is younger than 30 or lower than 160cm"); } } System.out.println("End of the program."); } }
package net.liuzd.spring.boot.v2.config; import tk.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Configuration; /** * @author miemie * @since 2018-08-12 */ @Configuration @MapperScan("net.liuzd.spring.boot.v2.mapper") public class MybatisConfig { }
package com.accounting.models; import java.io.Serializable; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @Entity @Table(name="tblReceivables") @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Receivables implements Serializable{ /** * */ private static final long serialVersionUID = 1L; @Id @Column(name="tblReceivables_FolioNumber", unique=true, nullable=false) private Long folioNumber; @Column(name="tblReceivables_TypeOfReceivable") private String receivableType; @Column(name="tblReceivables_TransactionDate") private Date transactionDate; @Column(name="tblReceivables_Amount") private Double amount; @ManyToOne @JoinColumn(name="tblEmployee_EmployeeId") private Employees employees; @ManyToOne @JoinColumn(name="tblChartOfAccount_ChartId") private ChartOfAccounts charts; public Receivables() { super(); } public Long getFolioNumber() { return folioNumber; } public void setFolioNumber(Long folioNumber) { this.folioNumber = folioNumber; } public Date getTransactionDate() { return transactionDate; } public void setTransactionDate(Date transactionDate) { this.transactionDate = transactionDate; } public Double getAmount() { return amount; } public void setAmount(Double amount) { this.amount = amount; } public String getReceivableType() { return receivableType; } public void setReceivableType(String receivableType) { this.receivableType = receivableType; } public Employees getEmployee() { return employees; } public void setEmployee(Employees employee) { this.employees = employee; } public ChartOfAccounts getChart() { return charts; } public void setChart(ChartOfAccounts chart) { this.charts = chart; } }