text
stringlengths
10
2.72M
/* * Lesson 9 Coding Activity Question 2 * * Write the code to print a random integer from -20 to 20 inclusive using Math.random(). * */ import java.lang.Math; class Lesson_9_Activity_Two { public static void main(String[] args) { System.out.println((int) (Math.random() * (41)) - 20); } }
package com.next.api; import com.next.api.controller.interceptor.UserTokenInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebMVCConfig implements WebMvcConfigurer { @Bean public UserTokenInterceptor userTokenInterceptor(){ return new UserTokenInterceptor(); } /** * 映射Tomcat虚拟目录 * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**") .addResourceLocations("file:G:/Documents/Pictures/") .addResourceLocations("classpath:META-INF/resources/"); } /** * 注册拦截器 * @param registry */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(userTokenInterceptor()) .addPathPatterns("/user/modifyUserinfo") .addPathPatterns("/user/uploadFace"); } }
package org.gtbank.rw.mvisa.handler; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.TimeZone; import org.apache.http.client.methods.CloseableHttpResponse; import org.gtbank.rw.mvisa.domain.MVisaUser; import org.gtbank.rw.mvisa.domain.Transaction; import org.gtbank.rw.mvisa.service.MVisaUserService; import org.gtbank.rw.mvisa.service.TransactionService; import org.gtbank.rw.mvisa.utils.MethodTypes; import org.gtbank.rw.mvisa.utils.TransactionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.tempuri.AppDevService; import org.tempuri.AppDevServiceSoap; @Service("cashOutPushPaymentsHandler") public class CashOutPushPaymentsHandler { String cashOutPushPayments; @Autowired MVisaUserService ms; @Autowired TransactionService ts; VisaAPIClient visaAPIClient; public void setupCashOutPushPaymentsRequest(String consumerAccountNumber, String agentAccountNumber, double amount) { this.visaAPIClient = new VisaAPIClient(); SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); TimeZone utc = TimeZone.getTimeZone("UTC"); sdfDate.setTimeZone(utc); Date now = new Date(); String strDate = sdfDate.format(now); this.cashOutPushPayments = "{" + "\"acquirerCountryCode\": \"643\"," + "\"acquiringBin\": \"400171\"," + "\"amount\": \"124.05\"," + "\"businessApplicationId\": \"CI\"," + "\"cardAcceptor\": {" + "\"address\": {" + "\"city\": \"Bangalore\"," + "\"country\": \"IND\"" + "}," + "\"idCode\": \"ID-Code123\"," + "\"name\": \"Card Accpector ABC\"" + "}," + "\"localTransactionDateTime\": \""+ strDate +"\"," + "\"merchantCategoryCode\": \"4829\"," + "\"recipientPrimaryAccountNumber\": \"4123640062698797\"," + "\"retrievalReferenceNumber\": \"430000367618\"," + "\"senderAccountNumber\": \"4541237895236\"," + "\"senderName\": \"Mohammed Qasim\"," + "\"senderReference\": \"1234\"," + "\"systemsTraceAuditNumber\": \"313042\"," + "\"transactionCurrencyCode\": \"USD\"," + "\"transactionIdentifier\": \"381228649430015\"" + "}"; } public void executeCashOutPushPayments(String agentAccountNumber, String consumerAccountNumber, double amount){ MVisaUser u = ms.getMVisaUserByAccountNumber(consumerAccountNumber); if(u == null){ return; } //Check if the angent's account has enough balance double agentAccountBalance = TransactionUtils.getAccountBalance(agentAccountNumber); if ( agentAccountBalance < amount){ return; } //Check validity of the consumer's account number if(TransactionUtils.getAccountStatus(consumerAccountNumber) != 1){ return; } AppDevService appDevService = new AppDevService(); AppDevServiceSoap appDevServiceSoap = appDevService.getAppDevServiceSoap(); try { //We first transfer the money from the client's account to the transit account appDevServiceSoap.transferFund("211/104140/1/5100/0", "211/184636/1/5107/0", 100, "OWN", "mVisa", "mVisa Transaction to Transit Account"); //We now proceed to preparing a request to visa API setupCashOutPushPaymentsRequest(consumerAccountNumber, agentAccountNumber, amount); //And we do the post to Visa Net String baseUri = "visadirect/"; String resourcePath = "mvisa/v1/merchantpushpayments"; CloseableHttpResponse response = this.visaAPIClient.doMutualAuthRequest(baseUri + resourcePath, "M Visa Transaction Test", this.cashOutPushPayments, MethodTypes.POST, new HashMap<String, String>()); /* * If the response code is 200, it means the transaction was * successful. We transfer the money from mvisa transit account to * Visa's account */ if (response.getStatusLine().getStatusCode() == 200) { appDevServiceSoap.transferFund("211/184636/1/5107/0", "211/184636/1/5002/0", 100, "OWN", "mVisa", "mVisa Transaction from Transit Account to Merchant Account"); } Transaction t = new Transaction(u, new Date(), cashOutPushPayments, response.toString()); ts.saveTransaction(t); response.close(); } catch (Exception e) { //TODO: Add logic to retry before marking the transaction as failed //Transfer the money back from the mvisa transit account to the consumer's account appDevServiceSoap.transferFund("211/184636/1/5107/0", "211/184636/1/5002/0", 100, "OWN", "mVisa", "Failed mVisa transaction. Transfer back the money from mvisa transit account to the consumer's account"); } } }
package com.metoo.foundation.dao; import org.springframework.stereotype.Repository; import com.metoo.core.base.GenericDAO; import com.metoo.foundation.domain.Document; @Repository("documentDAO") public class DocumentDAO extends GenericDAO<Document> { }
package com.cheese.radio.inject.component; import com.cheese.radio.inject.module.FragmentModule; import com.cheese.radio.inject.scope.FragmentScope; import com.cheese.radio.ui.demo.coordinatorLayout.fragment.DemoFragment; import com.cheese.radio.ui.home.circle.CircleFragment; import com.cheese.radio.ui.home.clock.ClockFragment; import com.cheese.radio.ui.home.mine.HomeMineFragment; import com.cheese.radio.ui.home.page.HomePageFragment; import com.cheese.radio.ui.media.anchor.entity.description.DescriptionFragment; import com.cheese.radio.ui.media.group.fragment.introduce.GroupIntroduceFragment; import com.cheese.radio.ui.media.group.fragment.story.PlayListFragment; import com.cheese.radio.ui.user.calendar.CalendarFragment; import dagger.Component; /** * project:cutv_ningbo * description: * create developer: admin * create time:11:29 * modify developer: admin * modify time:11:29 * modify remark: * * @version 2.0 */ @FragmentScope @Component(dependencies = AppComponent.class,modules={FragmentModule.class}) public interface FragmentComponent { void inject(HomeMineFragment fragment); void inject(HomePageFragment fragment); void inject(CircleFragment fragment); void inject(ClockFragment fragment); void inject(DescriptionFragment fragment); void inject(PlayListFragment fragment); void inject(GroupIntroduceFragment fragment); void inject(CalendarFragment fragment); void inject(DemoFragment fragment); }
package behavioral.strategy; public interface IStrategy { public void doA(); }
package exam.iz0_803; public class Exam_114 { } /* Given: class MarksOutOfBoundsException extends IndexOutOfBoundsException {} public class GradingProcess { void verify(int marks) throws IndexOutOfBoundsException { if (marks > 100) { throw new MarksOutOfBoundsException(); } if (marks > 50) { System.out.println("Pass"); } else { System.out.println("Fail"); } } public static void main(String[] args) { int marks = Integer.parseInt(args[2]); try { new GradingProcess().verify(marks); } catch (Exception e) { System.out.println(e.getClass()); } } } And the command line invoation: java GradingProcess 89 50 104 What is the result? A. Pass B. Fail C. class MarksOutOfBoundsException D. class IndexOutOfBoundsException E. class Exception Answer: C */
package pl.basistam.dataAccess.entities; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import pl.basistam.dataAccess.common.Role; import javax.persistence.*; import java.io.Serializable; @Entity @Data @AllArgsConstructor @NoArgsConstructor @Builder @Table(name = "users") public class User implements Serializable { @Id private String id; private String password; private String name; @Enumerated(EnumType.STRING) private Role role; }
package com.test.screens; import com.test.Configurations.FlickrAPISearch; import com.test.Configurations.Hooks; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileElement; import io.appium.java_client.ios.IOSDriver; import io.appium.java_client.ios.IOSElement; import io.appium.java_client.pagefactory.AppiumFieldDecorator; import io.appium.java_client.pagefactory.iOSFindBy; import org.json.simple.parser.ParseException; import org.openqa.selenium.Dimension; import org.openqa.selenium.Keys; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.*; public class FlickrSearchScreen { private AppiumDriver driver; private FlickrAPISearch flickrAPISearch; @iOSFindBy(className = "SearchField") private IOSElement flickrSearchField; @iOSFindBy(className = "StaticText") private List<IOSElement> flickrSearchResults; /* * FlickrSearchScreen class constructor to initialize the screen elements */ public FlickrSearchScreen() { this.driver = new Hooks().getDriver(); PageFactory.initElements(new AppiumFieldDecorator(this.driver),this); } /* * Wait until the Flickr Search Screen is displayed */ public void waitForFlickrSearchScreen() { WebDriverWait webDriverWait = new WebDriverWait(this.driver,40); webDriverWait.until(ExpectedConditions.visibilityOf(flickrSearchField)); } /* * Search on Flickr using the specified keyword */ public void searchOnFlickrByKeyword(String flickrSearchText) { waitForFlickrSearchScreen(); flickrSearchField.click(); flickrSearchField.sendKeys(flickrSearchText); flickrSearchField.sendKeys(Keys.RETURN); ((IOSDriver) driver).hideKeyboard("Return"); } /* * Returns the list of search results from Flickr */ public List<String> getFlickrSearchResults(String flickrSearchText) throws ParseException { flickrAPISearch = new FlickrAPISearch(); List<String> flickrSearchResult = new ArrayList<>(); int count = flickrAPISearch.getFlickrSearchResponses(flickrSearchText).size(); flickrSearchResults.forEach(iosElement -> flickrSearchResult.add(iosElement.getText())); while (flickrSearchResult.size() != count) { System.out.println("Search Results Size: " + flickrSearchResult.size()); Dimension dimensions = driver.manage().window().getSize(); Double screenHeightBegin = dimensions.getHeight() * 0.5; int scrollStart = screenHeightBegin.intValue(); Double screenHeightEnd = dimensions.getHeight() * 0.30; int scrollEnd = screenHeightEnd.intValue(); ((AppiumDriver<MobileElement>) driver).swipe(0, scrollStart, 0, scrollEnd, 1000); List<String> tempArray = new ArrayList<>(); flickrSearchResults.forEach(iosElement -> tempArray.add(iosElement.getText())); for(int i = tempArray.lastIndexOf(flickrSearchResult.get(flickrSearchResult.size()-1)); flickrSearchResult.size() < count; i++ ) { flickrSearchResult.add(tempArray.get(i+1)); } } return flickrSearchResult; } }
package com.nantian.foo.web.util; public class BaseConst { public static long MIDDLE_NODE=0; public static long AUTHORITY_LEAF=3; public static int RESPONSE_ERR=555; public static int SESSION_INVALID_ERR=556; public static long CORE_AUTHORITY_LIMIT=500; public static long NORMAL_AUTHORITY_LIMIT=1000; }
package water.eluosifangkuai.ui; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import water.eluosifangkuai.config.FrameConfig; import water.eluosifangkuai.config.GameConfig; import water.eluosifangkuai.dto.GameDto; /** * 绘制窗口 * @author Lenovo * */ public abstract class Layer { /** * 内边距 */ protected static final int PANDDING; /** * 边框宽度 */ protected static final int BORDER ; static{ //获得游戏配置 FrameConfig fCfg = GameConfig.getFrameConfig(); PANDDING = fCfg.getPadding(); BORDER = fCfg.getBorder(); } private static int WINDOW_W=Img.WINDOW.getWidth(null); private static int WINDOW_H=Img.WINDOW.getHeight(null); /* * 数字切片的宽度 */ protected static final int IMG_NUMBER_W=Img.NUMBER.getWidth(null)/10; /* * 数字切片的高度 */ private static final int IMG_NUMBER_H=Img.NUMBER.getHeight(null); /* * 矩形值槽(高度) */ protected static final int IMG_RECT_H = Img.RECT.getHeight(null); /* * 矩形值槽图片(宽度) */ private static final int IMG_RECT_W = Img.RECT.getWidth(null); /* * 矩形值槽(宽度) */ private final int rectW; /* * 默认字体 */ private static final Font DEF_FONT= new Font("黑体", Font.BOLD, 20); /** * 窗口左上角x坐标 */ protected final int x; /** * 窗口左上角y坐标 */ protected final int y; /** * 窗口宽度 */ protected final int w; /** * 窗口高度 */ protected final int h; /* * 游戏数据 */ protected GameDto dto=null; protected Layer(int x,int y,int w,int h){ this.x=x; this.y=y; this.h=h; this.w=w; this.rectW = this.w - (PANDDING << 1); } /** * 绘制窗口 */ protected void createWindow(Graphics g){ g.drawImage(Img.WINDOW, x, y, x+BORDER,y+BORDER, 0, 0, BORDER, BORDER, null);//左上 //(参数,显示起点x,显示起点y,显示终点x,显示终点y,切割起点x,切割起点y,切割终点x,切割终点y,null) //(a,b,c,d,a1,b1,c1,d1)表示将[从(a1,b1)到(c1,d1)的矩形区域]放大到[从(a,b)到(c,d)的矩形区域] //从左上角的坐标到右下角的坐标 g.drawImage(Img.WINDOW, x+BORDER, y, x+w-BORDER,y+BORDER, BORDER, 0, WINDOW_W-BORDER, BORDER, null);//中上 g.drawImage(Img.WINDOW, x+w-BORDER, y, x+w, y+BORDER, WINDOW_W-BORDER, 0, WINDOW_W, BORDER, null);//右上 g.drawImage(Img.WINDOW, x, y+BORDER, x+BORDER, y+h-BORDER, 0, BORDER, BORDER, WINDOW_H-BORDER, null);//左中 g.drawImage(Img.WINDOW, x+BORDER, y+BORDER, x+w-BORDER, y+h-BORDER, BORDER, BORDER, WINDOW_W-BORDER, WINDOW_H-BORDER, null);//中 g.drawImage(Img.WINDOW, x+w-BORDER, y+BORDER, x+w, y+h-BORDER, WINDOW_W-BORDER, BORDER, WINDOW_W, WINDOW_H-BORDER, null);//右中 g.drawImage(Img.WINDOW, x, y+h-BORDER, x+BORDER, y+h, 0, WINDOW_H-BORDER, BORDER, WINDOW_H, null);//左下 g.drawImage(Img.WINDOW, x+BORDER, y+h-BORDER, x+w-BORDER, y+h, BORDER, WINDOW_H-BORDER, WINDOW_W-BORDER, WINDOW_H, null);//中下 g.drawImage(Img.WINDOW, x+w-BORDER, y+h-BORDER, x+w, y+h, WINDOW_W-BORDER, WINDOW_H-BORDER, WINDOW_W, WINDOW_H, null);//右下 } /* * 刷新游戏具体内容 * * @author water * @param g 画笔 */ abstract public void paint(Graphics g); public void setDto(GameDto dto) { this.dto = dto; } protected void drawNumberLeftPad(int x, int y, int num, int maxBit, Graphics g){ //把要打印的数字转化成字符串 String strNum=Integer.toString(num); //循环绘制数字右对齐 for (int i = 0; i < maxBit; i++) { //判断是否满足绘制条件 if (maxBit-i<=strNum.length()) { //获得数字在字符串中的下标 int idx=i-maxBit+strNum.length(); //把数字num中的每一位取出 int bit = strNum.charAt(idx) - '0'; //绘制数字 g.drawImage(Img.NUMBER, this.x + x+ IMG_NUMBER_W*i, this.y + y, this.x + x + IMG_NUMBER_W*(i+1), this.y + y + IMG_NUMBER_H, bit * IMG_NUMBER_W, 0, (bit + 1) * IMG_NUMBER_W, IMG_NUMBER_H, null); } } } /* * 绘制值槽 */ protected void drawRect(int y, String title, String number, double percent, Graphics g) { // 各种值初始化 int rect_x = this.x + PANDDING; int rect_y = this.y + y; // 绘制背景 g.setColor(Color.BLACK); g.fillRect(rect_x, rect_y, this.rectW, IMG_RECT_H + 4); g.setColor(Color.WHITE); g.fillRect(rect_x + 1, rect_y + 1, this.rectW - 2, IMG_RECT_H + 2); g.setColor(Color.BLACK); g.fillRect(rect_x + 2, rect_y + 2, this.rectW - 4, IMG_RECT_H); // 求出宽度 int w = (int) (percent * (this.rectW - 4)); // 求出颜色 int subIdx = (int) (percent * IMG_RECT_W) - 1; // 绘制值槽 g.drawImage(Img.RECT, rect_x + 2, rect_y + 2, rect_x + 2 + w, rect_y + 2 + IMG_RECT_H, subIdx, 0, subIdx + 1,IMG_RECT_H, null); g.setColor(Color.WHITE); g.setFont(DEF_FONT); g.drawString(title, rect_x + 4, rect_y + 22); if (number!=null) { g.drawString(number, rect_x + 232, rect_y + 22); } } /* * 正中绘图 */ protected void drawImageAtCenter(Image img, Graphics g){ int imgW=img.getWidth(null); int imgH=img.getHeight(null); g.drawImage(img, this.x+(this.w-imgW>>1), this.y+(this.h-imgH>>1), null); } }
/**************************** Zhong Yang *********************************/ // This class is for implement "Load iRods" item in Data menu. package net.maizegenetics.analysis.data; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JRootPane; import javax.swing.tree.TreePath; import net.maizegenetics.analysis.data.FileLoadPlugin.TasselFileType; import net.maizegenetics.dna.map.TOPMUtils; import net.maizegenetics.dna.snp.ImportUtils; import net.maizegenetics.dna.snp.ReadPolymorphismUtils; import net.maizegenetics.dna.snp.ReadSequenceAlignmentUtils; import net.maizegenetics.gui.DialogUtils; import net.maizegenetics.plugindef.AbstractPlugin; import net.maizegenetics.plugindef.DataSet; import net.maizegenetics.plugindef.Datum; import net.maizegenetics.plugindef.PluginEvent; import net.maizegenetics.prefs.TasselPrefs; import net.maizegenetics.tassel.TASSELMainFrame; import net.maizegenetics.taxa.distance.ReadDistanceMatrix; import net.maizegenetics.trait.ReadPhenotypeUtils; import net.maizegenetics.util.ExceptionUtils; import net.maizegenetics.util.HDF5Utils; import net.maizegenetics.util.Report; import net.maizegenetics.util.TableReportUtils; import net.maizegenetics.util.Utils; import org.apache.log4j.Logger; import org.bio5.irods.iplugin.bean.TapasCoreFunctions; import org.bio5.irods.iplugin.utilities.IrodsUtilities; import org.bio5.irods.iplugin.views.IPlugin_OpenImage; import org.bio5.irods.iplugin.views.MainWindow; import org.irods.jargon.core.exception.JargonException; import org.irods.jargon.core.pub.io.IRODSFile; import org.irods.jargon.core.pub.io.IRODSFileFactory; import ch.systemsx.cisd.hdf5.HDF5Factory; import ch.systemsx.cisd.hdf5.IHDF5Reader; public class IRodsFileLoadPlugin extends AbstractPlugin { private PlinkLoadPlugin myPlinkLoadPlugin = null; private ProjectionLoadPlugin myProjectionLoadPlugin = null; private String[] myOpenFiles; private ArrayList myOpenFilesList = new ArrayList<String>(); private TasselFileType myFileType = TasselFileType.Unknown; private static final Logger myLogger = Logger .getLogger(FileLoadPlugin.class); private MainWindow irodsFileChooser = null; private IRODSFileFactory iRODSFileFactory; IRODSFile sourceIrodsFilePath = null; private List result = new ArrayList(); private ArrayList<String> alreadyLoaded = new ArrayList(); public IRodsFileLoadPlugin(Frame parentFame, boolean isInterative) { super(parentFame, isInterative); } public IRodsFileLoadPlugin(Frame parentFame, boolean isInterative, PlinkLoadPlugin plinkLoadPlugin, ProjectionLoadPlugin projectionLoadPlugin) { super(parentFame, isInterative); myPlinkLoadPlugin = plinkLoadPlugin; myProjectionLoadPlugin = projectionLoadPlugin; } public IRodsFileLoadPlugin(Frame parentFame, boolean isInterative, PlinkLoadPlugin plinkLoadPlugin, ProjectionLoadPlugin projectionLoadPlugin, MainWindow irodsFileChooser) { super(parentFame, isInterative); myPlinkLoadPlugin = plinkLoadPlugin; myProjectionLoadPlugin = projectionLoadPlugin; this.irodsFileChooser = irodsFileChooser; } public void setIRodsFileChooser(MainWindow irodsFileChooser){ this.irodsFileChooser = irodsFileChooser; } public TasselFileType getFileType(){ return myFileType; } public Logger getLogger(){ return myLogger; } public PlinkLoadPlugin getPlinkLoadPlugin(){ return myPlinkLoadPlugin; } public void setResult(DataSet tds){ result.add(tds); } public void setAlreadyLoaded(String myOpenFile){ alreadyLoaded.add(myOpenFile); } public DataSet performFunction(DataSet input) { try { if (isInteractive()) { FileLoadPluginDialogForIrods theDialog = new FileLoadPluginDialogForIrods(); theDialog.setLocationRelativeTo(getParentFrame()); theDialog.setVisible(true); if (theDialog.isCancel()) { return null; } myFileType = theDialog.getTasselFileType(); if (myFileType == TasselFileType.Plink) { return myPlinkLoadPlugin.performFunction(null); } if (myFileType == TasselFileType.ProjectionAlignment) { return myProjectionLoadPlugin.performFunction(null); } getOpenFilesByChooser(); theDialog.dispose(); } return DataSet.getDataSet(result, this); } finally { fireProgress(100); } } public DataSet guessAtUnknowns(String filename) { TasselFileType guess = TasselFileType.Sequence; DataSet tds = null; try { BufferedReader br = null; if (filename.startsWith("http")) { URL url = new URL(filename); br = new BufferedReader(new InputStreamReader(url.openStream())); } else { br = new BufferedReader(new FileReader(filename)); } String line1 = br.readLine().trim(); String[] sval1 = line1.split("\\s"); String line2 = br.readLine().trim(); String[] sval2 = line2.split("\\s"); if (line1.startsWith("<") || line1.startsWith("#")) { boolean isTrait = false; boolean isMarker = false; boolean isNumeric = false; boolean isMap = false; Pattern tagPattern = Pattern.compile("[<>\\s]+"); String[] info1 = tagPattern.split(line1); String[] info2 = tagPattern.split(line2); if (info1.length > 1) { if (info1[1].toUpperCase().startsWith("MARKER")) { isMarker = true; } else if (info1[1].toUpperCase().startsWith("TRAIT")) { isTrait = true; } else if (info1[1].toUpperCase().startsWith("NUMER")) { isNumeric = true; } else if (info1[1].toUpperCase().startsWith("MAP")) { isMap = true; } } if (info2.length > 1) { if (info2[1].toUpperCase().startsWith("MARKER")) { isMarker = true; } else if (info2[1].toUpperCase().startsWith("TRAIT")) { isTrait = true; } else if (info2[1].toUpperCase().startsWith("NUMER")) { isNumeric = true; } else if (info2[1].toUpperCase().startsWith("MAP")) { isMap = true; } } else { guess = null; String inline = br.readLine(); while (guess == null && inline != null && (inline.startsWith("#") || inline .startsWith("<"))) { if (inline.startsWith("<")) { String[] info = tagPattern.split(inline); if (info[1].toUpperCase().startsWith("MARKER")) { isMarker = true; } else if (info[1].toUpperCase() .startsWith("TRAIT")) { isTrait = true; } else if (info[1].toUpperCase() .startsWith("NUMER")) { isNumeric = true; } else if (info[1].toUpperCase().startsWith("MAP")) { isMap = true; } } } } if (isTrait || (isMarker && isNumeric)) { guess = TasselFileType.Phenotype; } else if (isMap) { guess = TasselFileType.GeneticMap; } else { throw new IOException( "Improperly formatted header. Data will not be imported."); } } else if ((line1.startsWith(">")) || (line1.startsWith(";"))) { guess = TasselFileType.Fasta; } else if (sval1.length == 1) { guess = TasselFileType.SqrMatrix; } else if ((line1.startsWith("#Nexus")) || (line1.startsWith("#NEXUS")) || (line1.startsWith("CLUSTAL")) || ((sval1.length == 2) && (sval2.length == 2))) { guess = TasselFileType.Sequence; } myLogger.info("guessAtUnknowns: type: " + guess); tds = processDatum(filename, guess); br.close(); } catch (Exception e) { } return tds; } public DataSet processDatum(String inFile, TasselFileType theFT) { Object result = null; String suffix = null; try { switch (theFT) { case Hapmap: { suffix = FileLoadPlugin.FILE_EXT_HAPMAP; if (inFile.endsWith(".gz")) { suffix = FileLoadPlugin.FILE_EXT_HAPMAP_GZ; } result = ImportUtils.readFromHapmap(inFile, this); break; } case HDF5: { IHDF5Reader reader = HDF5Factory.openForReading(inFile); boolean t4HDF5 = HDF5Utils.isTASSEL4HDF5Format(HDF5Factory .openForReading(inFile)); reader.close(); if (t4HDF5) { DialogUtils .showError( "This file is TASSEL4 HDF5 format. It will be converted to TASSEL5 " + "HDF5 format with the t5.h5 suffix added. This may take a few minutes.", getParentFrame()); String newInfile = inFile.replace(".h5", ".t5.h5"); MigrateHDF5FromT4T5.copyGenotypes(inFile, newInfile); inFile = newInfile; } suffix = FileLoadPlugin.FILE_EXT_HDF5; result = ImportUtils.readGuessFormat(inFile); break; } case VCF: { suffix = FileLoadPlugin.FILE_EXT_VCF; if (inFile.endsWith(".gz")) { suffix = FileLoadPlugin.FILE_EXT_VCF + ".gz"; } result = ImportUtils.readFromVCF(inFile, this); break; } case Sequence: { result = ReadSequenceAlignmentUtils.readBasicAlignments(inFile, 40); break; } case Fasta: { result = ImportUtils.readFasta(inFile); break; } case SqrMatrix: { result = ReadDistanceMatrix.readDistanceMatrix(inFile); break; } case Phenotype: { result = ReadPhenotypeUtils.readGenericFile(inFile); break; } case GeneticMap: { result = ReadPolymorphismUtils.readGeneticMapFile(inFile); break; } case Table: { result = TableReportUtils .readDelimitedTableReport(inFile, "\t"); break; } case TOPM: { result = TOPMUtils.readTOPM(inFile); break; } } } catch (Exception e) { e.printStackTrace(); StringBuilder builder = new StringBuilder(); builder.append("Error loading: "); builder.append(inFile); builder.append("\n"); builder.append(Utils.shortenStrLineLen( ExceptionUtils.getExceptionCauses(e), 50)); String str = builder.toString(); if (isInteractive()) { DialogUtils.showError(str, getParentFrame()); } else { myLogger.error(str); } } if (result != null) { String theComment = ""; if (result instanceof Report) { StringWriter sw = new StringWriter(); ((Report) result).report(new PrintWriter(sw)); theComment = sw.toString(); } String name = Utils.getFilename(inFile, suffix); Datum td = new Datum(name, result, theComment); // todo need to add logic of directories. DataSet tds = new DataSet(td, this); return tds; } return null; } private void getOpenFilesByChooser() { if(IPlugin_OpenImage.getIrodsImagej().getMainWindowStatus() == true){ irodsFileChooser = IPlugin_OpenImage.getIrodsImagej().getMainWindow(); irodsFileChooser.setVisible(true); }else{ IPlugin_OpenImage.getIrodsImagej().getMainWindow().setVisible(true); IPlugin_OpenImage.getIrodsImagej().getMainWindow().setVisibleFlag(true); if(IPlugin_OpenImage.getIrodsImagej().getMainWindowStatus() == true) IPlugin_OpenImage.getIrodsImagej().getTASSELMainFrame().setLoadDataFromIRodsMenuItemEnable(); } } public String[] getOpenFiles() { return myOpenFiles; } public void setOpenFiles(File[] openFiles) { if ((openFiles == null) || (openFiles.length == 0)) { myOpenFiles = null; return; } myOpenFiles = new String[openFiles.length]; for (int i = 0; i < openFiles.length; i++) { myOpenFiles[i] = openFiles[i].getPath(); } } public void setOpenFiles(File openFile) { if (openFile == null) { myOpenFiles = null; return; } myOpenFilesList.add(openFile.getPath()); myOpenFiles = (String[]) myOpenFilesList.toArray(new String[myOpenFilesList.size()]); } @Override public ImageIcon getIcon() { URL imageURL = IRodsFileLoadPlugin.class.getResource("/net/maizegenetics/analysis/images/iplant.gif"); if (imageURL == null) { return null; } else { return new ImageIcon(imageURL); } } @Override public String getButtonName() { return "Load iRods"; } @Override public String getToolTipText() { return "Load data from files on iRods server."; } } class FileLoadPluginDialogForIrods extends JDialog { /** * */ private static final long serialVersionUID = -1936743550229835010L; boolean isCancel = true; ButtonGroup conversionButtonGroup = new ButtonGroup(); JRadioButton hapMapRadioButton = new JRadioButton("Load Hapmap"); JRadioButton hdf5RadioButton = new JRadioButton("Load HDF5"); JRadioButton vcfRadioButton = new JRadioButton("Load VCF"); JRadioButton plinkRadioButton = new JRadioButton("Load Plink"); JRadioButton sequenceAlignRadioButton = new JRadioButton("Load Phylip"); JRadioButton fastaRadioButton = new JRadioButton("Load FASTA File"); JRadioButton numericalRadioButton = new JRadioButton( "Load Numerical (trait, covariates, or factors)"); JRadioButton loadMatrixRadioButton = new JRadioButton( "Load Square Numerical Matrix (i.e. kinship)"); JRadioButton guessRadioButton = new JRadioButton("Make Best Guess"); JRadioButton projectionAlignmentRadioButton = new JRadioButton( "Load Projection Alignment"); JRadioButton geneticMapRadioButton = new JRadioButton("Load a Genetic Map"); JRadioButton tableReportRadioButton = new JRadioButton( "Load a Table Report"); JRadioButton topmRadioButton = new JRadioButton( "Load a TOPM (Tags on Physical Map)"); public FileLoadPluginDialogForIrods() { super((Frame) null, "File Loader", true); try { jbInit(); pack(); } catch (Exception ex) { ex.printStackTrace(); } } private void jbInit() throws Exception { setTitle("File Loader"); setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE); setUndecorated(false); getRootPane().setWindowDecorationStyle(JRootPane.NONE); Container contentPane = getContentPane(); BoxLayout layout = new BoxLayout(contentPane, BoxLayout.Y_AXIS); contentPane.setLayout(layout); JPanel main = getMain(); contentPane.add(main); pack(); setResizable(false); conversionButtonGroup.add(projectionAlignmentRadioButton); conversionButtonGroup.add(hapMapRadioButton); conversionButtonGroup.add(hdf5RadioButton); conversionButtonGroup.add(vcfRadioButton); conversionButtonGroup.add(plinkRadioButton); conversionButtonGroup.add(sequenceAlignRadioButton); conversionButtonGroup.add(fastaRadioButton); conversionButtonGroup.add(loadMatrixRadioButton); conversionButtonGroup.add(numericalRadioButton); conversionButtonGroup.add(geneticMapRadioButton); conversionButtonGroup.add(tableReportRadioButton); conversionButtonGroup.add(topmRadioButton); conversionButtonGroup.add(guessRadioButton); guessRadioButton.setSelected(true); } private JPanel getMain() { JPanel inputs = new JPanel(); BoxLayout layout = new BoxLayout(inputs, BoxLayout.Y_AXIS); inputs.setLayout(layout); inputs.setAlignmentX(JPanel.CENTER_ALIGNMENT); inputs.add(Box.createRigidArea(new Dimension(1, 10))); inputs.add(getLabel()); inputs.add(Box.createRigidArea(new Dimension(1, 10))); inputs.add(getOptionPanel()); inputs.add(Box.createRigidArea(new Dimension(1, 10))); inputs.add(getButtons()); inputs.add(Box.createRigidArea(new Dimension(1, 10))); return inputs; } private JPanel getLabel() { JPanel result = new JPanel(); BoxLayout layout = new BoxLayout(result, BoxLayout.Y_AXIS); result.setLayout(layout); result.setAlignmentX(JPanel.CENTER_ALIGNMENT); JLabel jLabel1 = new JLabel("Choose File Type to Load."); jLabel1.setFont(new Font("Dialog", Font.BOLD, 18)); result.add(jLabel1); return result; } private JPanel getOptionPanel() { JPanel result = new JPanel(); BoxLayout layout = new BoxLayout(result, BoxLayout.Y_AXIS); result.setLayout(layout); result.setAlignmentX(JPanel.CENTER_ALIGNMENT); result.setBorder(BorderFactory.createEtchedBorder()); result.add(hapMapRadioButton); result.add(hdf5RadioButton); result.add(vcfRadioButton); result.add(plinkRadioButton); result.add(projectionAlignmentRadioButton); result.add(sequenceAlignRadioButton); result.add(fastaRadioButton); result.add(numericalRadioButton); result.add(loadMatrixRadioButton); result.add(geneticMapRadioButton); result.add(tableReportRadioButton); result.add(topmRadioButton); result.add(guessRadioButton); result.add(Box.createRigidArea(new Dimension(1, 20))); return result; } private JPanel getButtons() { JButton okButton = new JButton(); JButton cancelButton = new JButton(); cancelButton.setText("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { cancelButton_actionPerformed(e); } }); okButton.setText("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { okButton_actionPerformed(e); } }); JPanel result = new JPanel(new FlowLayout(FlowLayout.CENTER)); result.add(okButton); result.add(cancelButton); return result; } public FileLoadPlugin.TasselFileType getTasselFileType() { if (hapMapRadioButton.isSelected()) { return FileLoadPlugin.TasselFileType.Hapmap; } if (hdf5RadioButton.isSelected()) { return FileLoadPlugin.TasselFileType.HDF5; } if (vcfRadioButton.isSelected()) { return FileLoadPlugin.TasselFileType.VCF; } if (plinkRadioButton.isSelected()) { return FileLoadPlugin.TasselFileType.Plink; } if (projectionAlignmentRadioButton.isSelected()) { return FileLoadPlugin.TasselFileType.ProjectionAlignment; } if (sequenceAlignRadioButton.isSelected()) { return FileLoadPlugin.TasselFileType.Sequence; } if (fastaRadioButton.isSelected()) { return FileLoadPlugin.TasselFileType.Fasta; } if (loadMatrixRadioButton.isSelected()) { return FileLoadPlugin.TasselFileType.SqrMatrix; } if (numericalRadioButton.isSelected()) { return FileLoadPlugin.TasselFileType.Unknown; } if (geneticMapRadioButton.isSelected()) { return FileLoadPlugin.TasselFileType.GeneticMap; } if (tableReportRadioButton.isSelected()) { return FileLoadPlugin.TasselFileType.Table; } if (topmRadioButton.isSelected()) { return FileLoadPlugin.TasselFileType.TOPM; } return FileLoadPlugin.TasselFileType.Unknown; } public void okButton_actionPerformed(ActionEvent e) { isCancel = false; setVisible(false); } public void cancelButton_actionPerformed(ActionEvent e) { isCancel = true; setVisible(false); } public boolean isCancel() { return isCancel; } }
package Inputs; import Actions.Open; import Attributes.URLAtt; import Attributes.WebpageTag; import java.util.ArrayList; public class SEOpen extends SE{ public ArrayList<String> inputs = new ArrayList<>(); public SEOpen() { super(new Open()); inputs.add(new URLAtt().toString()); inputs.add(new WebpageTag().toString()); } }
package com.codingchili.realmregistry.model; import com.codingchili.common.RegisteredRealm; import com.codingchili.core.configuration.Attributes; /** * @author Robin Duda * * Contains realm metadata used in the realm-list. */ public class RealmMetaData extends Attributes { private long updated; private String id; private String description; private String host; private String resources; private String version; private String type; private String lifetime; private String name; private Boolean trusted; private Boolean secure; private Boolean binaryWebsocket; private int size; private int port; private int players = 0; public RealmMetaData() { } public RealmMetaData(RegisteredRealm settings) { this.setId(settings.getId()) .setBinaryWebsocket(settings.getBinaryWebsocket()) .setResources(settings.getResources()) .setVersion(settings.getVersion()) .setSize(settings.getSize()) .setHost(settings.getHost()) .setPort(settings.getPort()) .setPlayers(settings.getPlayers()) .setTrusted(settings.getTrusted()) .setUpdated(settings.getUpdated()) .setSecure(settings.getSecure()) .setName(settings.getName()) .setAttributes(settings.getAttributes()); } public String getName() { return name; } public RealmMetaData setName(String name) { this.name = name; return this; } public long getUpdated() { return updated; } private RealmMetaData setUpdated(long updated) { this.updated = updated; return this; } public Boolean getBinaryWebsocket() { return binaryWebsocket; } public RealmMetaData setBinaryWebsocket(Boolean binaryWebsocket) { this.binaryWebsocket = binaryWebsocket; return this; } public String getHost() { return host; } public RealmMetaData setHost(String host) { this.host = host; return this; } public int getPort() { return port; } public RealmMetaData setPort(int port) { this.port = port; return this; } public Boolean getSecure() { return secure; } private RealmMetaData setSecure(Boolean secure) { this.secure = secure; return this; } public String getId() { return id; } private RealmMetaData setId(String id) { this.id = id; return this; } public String getDescription() { return description; } private RealmMetaData setDescription(String description) { this.description = description; return this; } public String getResources() { return resources; } private RealmMetaData setResources(String resources) { this.resources = resources; return this; } public String getVersion() { return version; } private RealmMetaData setVersion(String version) { this.version = version; return this; } public int getSize() { return size; } private RealmMetaData setSize(int size) { this.size = size; return this; } public String getType() { return type; } private RealmMetaData setType(String type) { this.type = type; return this; } public String getLifetime() { return lifetime; } private RealmMetaData setLifetime(String lifetime) { this.lifetime = lifetime; return this; } public int getPlayers() { return players; } private RealmMetaData setPlayers(int players) { this.players = players; return this; } public Boolean getTrusted() { return trusted; } private RealmMetaData setTrusted(Boolean trusted) { this.trusted = trusted; return this; } }
package com.cinema.biz.model; import com.cinema.biz.model.base.TSimRepair; public class SimRepair extends TSimRepair { }
package model; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; public class Local { private StringProperty id_Local; private StringProperty nombre, direccion; public Local(String id_Local, String nombre, String direccion) { super(); this.id_Local = new SimpleStringProperty(id_Local); this.nombre = new SimpleStringProperty(nombre); this.direccion = new SimpleStringProperty(direccion); } /** * @return the id_Local */ public StringProperty getId_Local() { return id_Local; } /** * @param id_Local the id_Local to set */ public void setId_Local(StringProperty id_Local) { this.id_Local = id_Local; } /** * @return the nombre */ public StringProperty getNombre() { return nombre; } /** * @param nombre the nombre to set */ public void setNombre(StringProperty nombre) { this.nombre = nombre; } /** * @return the direccion */ public StringProperty getDireccion() { return direccion; } /** * @param direccion the direccion to set */ public void setDireccion(StringProperty direccion) { this.direccion = direccion; } }
package rubrica; public class Contatto { String name; String surname; String tel; String key; public Contatto(){ name = ""; surname = ""; tel = ""; key = ""; } public Contatto(String name_){ name = name_; surname = ""; tel = ""; key = ""; } public Contatto(String name_, String surname_){ name = name_; surname = surname_; tel = ""; key = ""; } public Contatto(String name_, String surname_, String tel_){ name = name_; surname = surname_; tel = tel_; key = ""; } public Contatto(String name_, String surname_, String tel_, String key_){ name = name_; surname = surname_; tel = tel_; key = key_; } public String toStr(){ return name + "|" + surname + "|" + tel + "|" + key; } }
package com.example.springboottest.smalldemo.vo; import com.fasterxml.jackson.annotation.*; import org.springframework.format.annotation.DateTimeFormat; /** * @JsonIgnoreProperties:使用在类声明处,和@JsonIgnore的区别是可以对多个属性作用 * 直接在value属性后面使用大括号逗号隔开, 属性ignoreUnknow为true表示忽略未定义的属性 * @Auther: WangHuidong * @Date: 2018/12/25 * @Description: */ //@JsonPropertyOrder对属性排序,属性alphabetic默认值是false,设置为true排序 @JsonPropertyOrder(alphabetic = true) public class UserVo { //@JsonInclude:使用在某个属性上,配合Value=JsonInclude.Include.NON_NULL, //如果属性值为空,返回前端不可见 @JsonInclude(value=JsonInclude.Include.NON_NULL) private String name;//姓名 //@JsonIgnore:使用在某个属性上,序列化和反序列化忽略这个属性 //最直接的效果就是返回的JSON属性是没有这个属性的,一般作用于密码这系列的属性 @JsonIgnore private String password;//密码 //@JsonFormat配合属性pattern标志事件格式,timezone是时区,local是区域 //把日期格式化为String //前端的String格式需要解析为日期格式可以使用@DateTimeFormat @JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss sss", locale = "AuthResources_zh_CN",timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss sss") private String birthday;//生日 //@JsonProperty:使用在某个属性上,有两个作用 //1.修改返回JSON数据的时候key值为value指定值 //2.配合属性access=JsonProperty.Access.WRITE_ONLY只可进行序列化,不能反序列化 //直观效果就是返回的数据没有该属性 @JsonProperty(value="d",access = JsonProperty.Access.WRITE_ONLY) private String desc;//描述 }
package gameData.Boards; import com.fasterxml.jackson.annotation.JsonProperty; import gameData.Battleships.Battleship; import gameData.Utils.CoordinatesUtil; import gameData.enums.Orientation; import gameData.GameCommon; import gameData.enums.TileState; /** * Created by paul.moon on 1/28/16. */ public abstract class BoardAbstract { @JsonProperty protected TileState[][] tiles; @JsonProperty protected int numberOfHitsNecessary; @JsonProperty protected int numberOfHitsReceived; /** * Default constructor * Instantiates the board with 3 rows/columns * Set all the tiles to TileState.WATER_U * * @return the instantiated object */ public BoardAbstract() { this.tiles = new TileState[GameCommon.minNumberRows][GameCommon.minNumberColumns]; resetBoard(); } public BoardAbstract(int nbRows, int nbColumns) { nbRows = nbRows >= GameCommon.minNumberRows ? nbRows : GameCommon.minNumberRows; nbColumns = nbColumns >= GameCommon.minNumberColumns ? nbColumns : GameCommon.minNumberColumns; this.tiles = new TileState[nbRows][nbColumns]; resetBoard(); } protected abstract void resetBoard(); public boolean checkSpaceIsFree(Battleship battleship) { if (battleship.getOrientation() == Orientation.HORIZONTAL) { return checkHorizontalSpaceIsFree(battleship.getOrigin(), battleship.getSize()); } else { return checkVerticalSpaceIsFree(battleship.getOrigin(), battleship.getSize()); } } public TileState checkState(int x, int y) { TileState state = null; if (CoordinatesUtil.coordinatesAreInBoud(tiles.length, tiles[0].length, x, y)) { state = tiles[x][y]; } return state; } private boolean checkVerticalSpaceIsFree(Coordinates origin, int shipSize) { for (int i = 0 ; i < shipSize ; i++) { if (tiles[origin.x + i][origin.y] == TileState.BOAT_U) { return false; } } return true; } private boolean checkHorizontalSpaceIsFree(Coordinates origin, int shipSize) { for (int i = 0 ; i < shipSize ; i++) { if (tiles[origin.x][origin.y + i] == TileState.BOAT_U) { return false; } } return true; } @Override public String toString() { StringBuilder s = new StringBuilder(); for (int x = 0; x < tiles.length; x++) { s.append("[ "); for (int y = 0; y < tiles[0].length; y++) { s.append(tiles[x][y]).append(" , "); } s.replace(s.length() - 3, s.length(), " ]"); s.append("\n"); } return s.toString(); } public boolean areAllBattleShipsSunk() { return numberOfHitsReceived == numberOfHitsNecessary; } /**GETTERS AND SETTERS**/ public int getNumberOfHitsNecessary() { return numberOfHitsNecessary; } public void setNumberOfHitsNecessary(int numberOfHitsNecessary) { this.numberOfHitsNecessary = numberOfHitsNecessary; } }
package comp303.fivehundred.util; /** * @author Stephanie Pataracchia 260407002 */ import org.junit.runner.RunWith; import org.junit.runners.Suite; import comp303.fivehundred.util.TestComparators; @RunWith(Suite.class) @Suite.SuiteClasses({ TestBySuitComparator.class, TestByRankComparator.class, TestBySuitNoTrumpComparator.class }) public class TestComparators { }
package co.bucketstargram.common; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class Trace { public static void init() { Calendar calendar = Calendar.getInstance(); StackTraceElement[] trace = new Throwable().getStackTrace(); Date date = calendar.getTime(); // for(int i = 0 ; i < trace.length ; i ++) { // System.out.println("trace[" + i + "] = " + trace[i]); // } String currentTime = (new SimpleDateFormat("yyyy-MM-dd a HH:mm:ss.SSS").format(date)); String callClassName = trace[1].getFileName(); if(callClassName.contains("_jsp")) { String str[] = callClassName.split("_"); callClassName = str[0] + ".jsp"; } System.out.println(currentTime + " | " + callClassName); } }
package com.limefriends.molde.menu_map.cache_manager; import android.util.Log; public class FileCacheNotFoundException extends Throwable { public FileCacheNotFoundException(String format) { Log.e("CacheNotFoundE", format); } }
/* * 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 Clases.empleados; import java.io.FileInputStream; import java.util.Date; /** * * @author jluis */ public class ListaMaestro { private int ID_LISTAEMPLEADOS; private int CODIGO; private String NOMBRES; private String APELLIDOS; private String SEXO; private String NIT; private String DIRECCION; private String TELEFONO; private FileInputStream FOTOGRAFIA; private Date F_NACIMIENTO; private String T_SANGRE; private String IRTRA; private String DPI; private String DPIEXTENDIDO; private String ESTUDIOS_ULTIMOS; private String ESTUDIOS_ACTUALES; private String ESTADO_CIVIL; private String NOMBRE_CONYUGE; private String CORREO_ELECTRO; private String PUESTO; private int DEPARTAMENTO; private String CUENTA_BANCO; private String IGSS; private Date FECHA_INGRESO; private Date FECHA_BAJA; private String MOTIVO_BAJA; private double ORDINARIO; private double BONIFICACION; private int longitudBytes; private String depto; private String f_nacimiento; private String f_ingreso; private int discapacidad; private String TipoDiscapa; private String NivelAcademico; private int evaluadopor; private String fechadebaja; private int marcaje; public int getMarcaje() { return marcaje; } public void setMarcaje(int marcaje) { this.marcaje = marcaje; } public String getFechadebaja() { return fechadebaja; } public void setFechadebaja(String fechadebaja) { this.fechadebaja = fechadebaja; } public int getEvaluadopor() { return evaluadopor; } public void setEvaluadopor(int evaluadopor) { this.evaluadopor = evaluadopor; } public int getDiscapacidad() { return discapacidad; } public void setDiscapacidad(int discapacidad) { this.discapacidad = discapacidad; } public String getTipoDiscapa() { return TipoDiscapa; } public void setTipoDiscapa(String TipoDiscapa) { this.TipoDiscapa = TipoDiscapa; } public String getNivelAcademico() { return NivelAcademico; } public void setNivelAcademico(String NivelAcademico) { this.NivelAcademico = NivelAcademico; } public String getF_nacimiento() { return f_nacimiento; } public void setF_nacimiento(String f_nacimiento) { this.f_nacimiento = f_nacimiento; } public String getF_ingreso() { return f_ingreso; } public void setF_ingreso(String f_ingreso) { this.f_ingreso = f_ingreso; } public String getDepto() { return depto; } public void setDepto(String depto) { this.depto = depto; } public int getID_LISTAEMPLEADOS() { return ID_LISTAEMPLEADOS; } public void setID_LISTAEMPLEADOS(int ID_LISTAEMPLEADOS) { this.ID_LISTAEMPLEADOS = ID_LISTAEMPLEADOS; } public int getCODIGO() { return CODIGO; } public void setCODIGO(int CODIGO) { this.CODIGO = CODIGO; } public String getNOMBRES() { return NOMBRES; } public void setNOMBRES(String NOMBRES) { this.NOMBRES = NOMBRES; } public String getAPELLIDOS() { return APELLIDOS; } public void setAPELLIDOS(String APELLIDOS) { this.APELLIDOS = APELLIDOS; } public String getSEXO() { return SEXO; } public void setSEXO(String SEXO) { this.SEXO = SEXO; } public String getNIT() { return NIT; } public void setNIT(String NIT) { this.NIT = NIT; } public String getDIRECCION() { return DIRECCION; } public void setDIRECCION(String DIRECCION) { this.DIRECCION = DIRECCION; } public String getTELEFONO() { return TELEFONO; } public void setTELEFONO(String TELEFONO) { this.TELEFONO = TELEFONO; } public FileInputStream getFOTOGRAFIA() { return FOTOGRAFIA; } public void setFOTOGRAFIA(FileInputStream FOTOGRAFIA) { this.FOTOGRAFIA = FOTOGRAFIA; } public int getLongitudBytes() { return longitudBytes; } public void setLongitudBytes(int longitudBytes) { this.longitudBytes = longitudBytes; } public Date getF_NACIMIENTO() { return F_NACIMIENTO; } public void setF_NACIMIENTO(Date F_NACIMIENTO) { this.F_NACIMIENTO = F_NACIMIENTO; } public String getT_SANGRE() { return T_SANGRE; } public void setT_SANGRE(String T_SANGRE) { this.T_SANGRE = T_SANGRE; } public String getIRTRA() { return IRTRA; } public void setIRTRA(String IRTRA) { this.IRTRA = IRTRA; } public String getDPI() { return DPI; } public void setDPI(String DPI) { this.DPI = DPI; } public String getDPIEXTENDIDO() { return DPIEXTENDIDO; } public void setDPIEXTENDIDO(String DPIEXTENDIDO) { this.DPIEXTENDIDO = DPIEXTENDIDO; } public String getESTUDIOS_ULTIMOS() { return ESTUDIOS_ULTIMOS; } public void setESTUDIOS_ULTIMOS(String ESTUDIOS_ULTIMOS) { this.ESTUDIOS_ULTIMOS = ESTUDIOS_ULTIMOS; } public String getESTUDIOS_ACTUALES() { return ESTUDIOS_ACTUALES; } public void setESTUDIOS_ACTUALES(String ESTUDIOS_ACTUALES) { this.ESTUDIOS_ACTUALES = ESTUDIOS_ACTUALES; } public String getESTADO_CIVIL() { return ESTADO_CIVIL; } public void setESTADO_CIVIL(String ESTADO_CIVIL) { this.ESTADO_CIVIL = ESTADO_CIVIL; } public String getNOMBRE_CONYUGE() { return NOMBRE_CONYUGE; } public void setNOMBRE_CONYUGE(String NOMBRE_CONYUGE) { this.NOMBRE_CONYUGE = NOMBRE_CONYUGE; } public String getCORREO_ELECTRO() { return CORREO_ELECTRO; } public void setCORREO_ELECTRO(String CORREO_ELECTRO) { this.CORREO_ELECTRO = CORREO_ELECTRO; } public String getPUESTO() { return PUESTO; } public void setPUESTO(String PUESTO) { this.PUESTO = PUESTO; } public int getDEPARTAMENTO() { return DEPARTAMENTO; } public void setDEPARTAMENTO(int DEPARTAMENTO) { this.DEPARTAMENTO = DEPARTAMENTO; } public String getCUENTA_BANCO() { return CUENTA_BANCO; } public void setCUENTA_BANCO(String CUENTA_BANCO) { this.CUENTA_BANCO = CUENTA_BANCO; } public String getIGSS() { return IGSS; } public void setIGSS(String IGSS) { this.IGSS = IGSS; } public Date getFECHA_INGRESO() { return FECHA_INGRESO; } public void setFECHA_INGRESO(Date FECHA_INGRESO) { this.FECHA_INGRESO = FECHA_INGRESO; } public Date getFECHA_BAJA() { return FECHA_BAJA; } public void setFECHA_BAJA(Date FECHA_BAJA) { this.FECHA_BAJA = FECHA_BAJA; } public String getMOTIVO_BAJA() { return MOTIVO_BAJA; } public void setMOTIVO_BAJA(String MOTIVO_BAJA) { this.MOTIVO_BAJA = MOTIVO_BAJA; } public double getORDINARIO() { return ORDINARIO; } public void setORDINARIO(double ORDINARIO) { this.ORDINARIO = ORDINARIO; } public double getBONIFICACION() { return BONIFICACION; } public void setBONIFICACION(double BONIFICACION) { this.BONIFICACION = BONIFICACION; } }
package com.goldsand.collaboration.connection; interface MessageSendListener { public void onDataSendDone(int id, boolean success); }
package pl.edu.pw.elka.blocks.domain; import pl.edu.pw.elka.blocks.dto.BlockDetailsDto; public class BlockFacade { private final BlockchainConnector blockchainConnector; public BlockFacade(BlockchainConnector blockchainConnector) { this.blockchainConnector = blockchainConnector; } public BlockDetailsDto fetchBlockDetails() { BlockDetails blockDetails = blockchainConnector.fetchCurrentBlockDetails(); return blockDetails.toDto(); } }
package com.legado.grupo.controller; //librerias import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.legado.grupo.dom.Asignatura; import com.legado.grupo.dom.Carrera; import com.legado.grupo.dom.Facultad; import com.legado.grupo.dom.Grupo; import com.legado.grupo.dom.Miembro; import com.legado.grupo.dom.Usuario; import com.legado.grupo.srv.AsignaturaService; import com.legado.grupo.srv.CarreraService; import com.legado.grupo.srv.FacultadService; import com.legado.grupo.srv.GrupoService; import com.legado.grupo.srv.MiembroService; import com.legado.grupo.srv.PeriodoService; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; //fin librerias @RestController public class GrupoRestController { // aributos globales @Autowired private FacultadService facultadSRV; @Autowired private CarreraService carreraSRV; @Autowired private AsignaturaService asignaturaSRV; @Autowired private PeriodoService periodoSRV; @Autowired private GrupoService grupoSRV; @Autowired private MiembroService miembroSRV; private String URL_LEGADO_USUARIOS = "172.16.147.108:9091"; private String URL_LEGADO_GRUPOS = "localhost:9092"; private static final Logger logger = Logger.getLogger(RestController.class.getName()); // fin atributos globales /* Obtener Lista de todas las carreras que pertenecen a una facultad */ @RequestMapping(value = "/get_lista_facultad", method = RequestMethod.GET) public List<Facultad> get_lista_facultad() { logger.log(Level.INFO, "GET: " + URL_LEGADO_GRUPOS + "/get_lista_facultad"); List<Facultad> facultades = facultadSRV.listar();//se carga lista de facultades return facultades;// retorna lista de facultades } /* Obtener Lista de todas las materias que pertenecen a una carrera */ @RequestMapping(value = "/get_materia_carrera", method = RequestMethod.GET) public List<Asignatura> get_materias_carrera(@RequestParam String id_carrera) { logger.log(Level.INFO, "GET: " + URL_LEGADO_GRUPOS + "/get_materia_carrera?id_carrera=" + id_carrera); List<Asignatura> materias = new ArrayList<>(); try { int idCarrera = Integer.parseInt(id_carrera); Carrera carrera = carreraSRV.buscarPorID(idCarrera);//se busca una carrera por id if (carrera != null) {// si no es vacio se cargan las materias materias = carrera.getAsignaturas(); } } catch (NumberFormatException ex) { logger.log(Level.INFO, ex.getClass().getSimpleName() + ": Se necesita un parametro numerico."); } finally { return materias;//devuelve lista de materias } } /* Obtener Lista de miebros de un grupo */ @RequestMapping(value = "/get_miembros", method = RequestMethod.GET) public List<Usuario> get_miembros(@RequestParam String id_grupo) { logger.log(Level.INFO, "GET: " + URL_LEGADO_USUARIOS + "/get_miembros?id_grupo=" + id_grupo); List<Usuario> usuarios = new ArrayList<>();//creamos lista de usarios tipo Usuario try { int idGrupo = Integer.parseInt(id_grupo);//casting a id grupo Grupo grupo = grupoSRV.buscarPorID(idGrupo); if (grupo != null) {// si existe el grupo entonces buscara a sus integrantes ObjectMapper mapper = new ObjectMapper(); for (Miembro m : grupo.getMiembros()) { try {//manejode errores String url = "http://" + URL_LEGADO_USUARIOS + "/get_usuario?id_usuario=" + m.getId_usuario(); Usuario u = mapper.readValue(new URL(url), Usuario[].class)[0]; if (u != null) {//si el usuario existe es agregado usuarios.add(u); } } catch (IOException e) { e.printStackTrace(); } } } } catch (NumberFormatException ex) { logger.log(Level.INFO, ex.getClass().getSimpleName() + ": Se necesita un parametro numerico."); } finally { return usuarios;//retorna la lista de usuarios } } /* Obtener Lista de grupos en los que está un usuario */ @RequestMapping(value = "/get_grupos_usuario", method = RequestMethod.GET) public String get_grupos_usuario(@RequestParam String id_usuario) { logger.log(Level.INFO, "GET: " + URL_LEGADO_GRUPOS + "/get_grupos_usuario?id_usuario=" + id_usuario); String jsonRespuesta = "[]"; try {//control de excepciones int idUsuario = Integer.parseInt(id_usuario); //Se buscan los grupos y se prepara el JSON de respuesta JsonArray jsonArray = new JsonArray();//array de objetos json for (Grupo g : grupoSRV.listarGruposDeUnUsuario(idUsuario)) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("id_grupo", g.getId_grupo());//se agregan propiedades al objeto json jsonObject.addProperty("nombre", g.getNombre()); jsonObject.addProperty("materia", g.getAsignatura().getNombre()); jsonObject.addProperty("carrera", g.getAsignatura().getCarrera().getNombre()); jsonObject.addProperty("facultad", g.getAsignatura().getCarrera().getFacultad().getNombre()); jsonObject.addProperty("periodo_academico", g.getPeriodo().getFechaInicio().toGMTString()); jsonArray.add(jsonObject);//se agrega el objeto json a un array } jsonRespuesta = jsonArray.toString(); } catch (NumberFormatException ex) { logger.log(Level.INFO, ex.getClass().getSimpleName() + ": Se necesita un parametro numerico."); } finally { return jsonRespuesta; } } /* Obtener Lista de grupos que pertenecen a una carrera y una materia especifica */ @RequestMapping(value = "/buscar_grupos", method = RequestMethod.GET) public String get_grupos_usuario(@RequestParam String id_carrera, String id_materia) { logger.log(Level.INFO, "GET: " + URL_LEGADO_GRUPOS + "/buscar_grupos?id_carrera=" + id_carrera + "&id_materia=" + id_materia); String jsonRespuesta = "[{}]"; try {//control de excepciones int idCarrera = Integer.parseInt(id_carrera);//castings int idMateria = Integer.parseInt(id_materia); //Se buscan los grupos y se prepara el JSON de respuesta JsonArray jsonArray = new JsonArray(); for (Grupo g : grupoSRV.listarGruposSegunAsignaturaYCarrera(idMateria, idCarrera)) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("id_grupo", g.getId_grupo());//se agrega propiedades del grupo jsonObject.addProperty("nombre", g.getNombre()); jsonObject.addProperty("materia", g.getAsignatura().getNombre()); jsonObject.addProperty("carrera", g.getAsignatura().getCarrera().getNombre()); jsonObject.addProperty("facultad", g.getAsignatura().getCarrera().getFacultad().getNombre()); jsonObject.addProperty("periodo_academico", g.getPeriodo().getFechaInicio().toGMTString()); jsonArray.add(jsonObject);//agregamos el objeo al array } jsonRespuesta = jsonArray.toString();//tranformamos a string el array } catch (NumberFormatException ex) { logger.log(Level.INFO, ex.getClass().getSimpleName() + ": Se necesita un parametro numerico."); } finally { return jsonRespuesta;// retornamos el array en forma de string } } /* Ingresar un usuario en un grupo, metodo GET */ @RequestMapping(value = "/add_miembro", method = RequestMethod.GET) public String add_miembro(@RequestParam String id_usuario, String id_grupo) { logger.log(Level.INFO, "GET: " + URL_LEGADO_GRUPOS + "/add_miembro?id_usuario=" + id_usuario + "&id_grupo=" + id_grupo); JsonObject jsonRespuesta = new JsonObject();// creamos un objeto json try {//control de excepciones int idUsuario = Integer.parseInt(id_usuario);//casting a los parametros int idGrupo = Integer.parseInt(id_grupo); Grupo grupo = grupoSRV.buscarPorID(idGrupo);//instancia de grupo y miembro Miembro miembro = new Miembro(idUsuario); //Existe el usuario? if (grupo != null) {//si existe un grupo ingresa if (!grupoSRV.existeMiembroEnGrupo(idUsuario, idGrupo)) { miembroSRV.agregar(miembro.getId_usuario(), grupo.getId_grupo());//agregamos el miembro en caso de no existir jsonRespuesta.addProperty("estado", "ok");//mensaje de confirmacion } else { jsonRespuesta.addProperty("estado", "existe");//mensaje de usuario enconrado } } else { jsonRespuesta.addProperty("estado", "error");//respuesta de error } } catch (NumberFormatException ex) {//validacion de numeros logger.log(Level.INFO, ex.getClass().getSimpleName() + ": Se necesita un parametro numerico."); jsonRespuesta.addProperty("estado", "error"); } catch (Exception ex) { logger.log(Level.INFO, ex.getClass().getSimpleName() + ": " + ex.getMessage()); jsonRespuesta.addProperty("estado", "error"); } finally { return jsonRespuesta.toString(); } } /* Obtener Lista de grupos segun los ids que se indiquen como parametro */ @RequestMapping(value = "/get_grupo", method = RequestMethod.GET) public String get_grupos(@RequestParam String id_grupo) { logger.log(Level.INFO, "GET: " + URL_LEGADO_GRUPOS + "/get_grupo?id_grupo=" + id_grupo); String jsonRespuesta = "[]"; try {//control de excepciones //Se separan los ids pasados como parametro String[] s_ids = id_grupo.split(","); int[] ids = new int[s_ids.length]; for (int i = 0; i < ids.length; i++) { ids[i] = Integer.parseInt(s_ids[i]); } //Se buscan los grupos y se prepara el JSON de respuesta JsonArray jsonArray = new JsonArray(); for (Grupo g : grupoSRV.buscar(ids)) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("id_grupo", g.getId_grupo()); jsonObject.addProperty("nombre", g.getNombre()); jsonObject.addProperty("materia", g.getAsignatura().getNombre()); jsonObject.addProperty("carrera", g.getAsignatura().getCarrera().getNombre()); jsonObject.addProperty("facultad", g.getAsignatura().getCarrera().getFacultad().getNombre()); jsonObject.addProperty("periodo_academico", g.getPeriodo().getFechaInicio().toGMTString()); jsonArray.add(jsonObject);//se agrega el objeto al array } jsonRespuesta = jsonArray.toString();//se trandorma a texto } catch (NumberFormatException ex) { logger.log(Level.INFO, ex.getClass().getSimpleName() + ": Se necesitan parametros numericos."); } finally { return jsonRespuesta; //retorna la respuesta } } /* Método para provar invocación de servicios REST externos */ @RequestMapping(value = "/get_usuario", method = RequestMethod.GET) public Usuario get_usuario(@RequestParam String id_usuario) { logger.log(Level.INFO, "GET: " + URL_LEGADO_GRUPOS + "/get_usuario?id_usuario=" + id_usuario); return new Usuario(1, "fxaviergb", "Xavier Garnica", "xg@ucuenca.ec"); } }
package kamyshevat.task3.controlStructures; public class TestArray { static int count0 = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0, count7 = 0, count8 = 0, count9 = 0, count10 = 0; public static void main(String[] args) { int[] array = new int[50]; for (int i = 0; i < array.length; i++) { array[i] = (int) (Math.random() * 11); System.out.print(array[i] + " "); } long startTime = System.nanoTime(); for (int i = 0; i < array.length; i++) { switchcase(array[i]); } long estimatedTime1 = System.nanoTime() - startTime; startTime = System.nanoTime(); for (int i = 0; i < array.length; i++) { ifelse(array[i]); } long estimatedTime2 = System.nanoTime() - startTime; System.out.println(estimatedTime1 + " " + estimatedTime2); } public static void switchcase(int num) { switch (num) { case 0: count0++; break; case 1: count1++; break; case 2: count2++; break; case 3: count3++; break; case 4: count4++; break; case 5: count5++; break; case 6: count6++; break; case 7: count7++; break; case 8: count8++; break; case 9: count9++; break; case 10: count10++; break; } } public static void ifelse(int num) { if (num == 0) count0++; else if (num == 1) count1++; else if (num == 2) count2++; else if (num == 3) count3++; else if (num == 4) count4++; else if (num == 5) count5++; else if (num == 6) count6++; else if (num == 7) count7++; else if (num == 8) count8++; else if (num == 9) count9++; else if (num == 10) count10++; } }
package com.wickvood.albumsearch.mvp.presenter; import android.util.Log; import com.arellomobile.mvp.InjectViewState; import com.arellomobile.mvp.MvpPresenter; import com.wickvood.albumsearch.App; import com.wickvood.albumsearch.NetworkService; import com.wickvood.albumsearch.mvp.model.SongResultModel; import com.wickvood.albumsearch.mvp.model.SongsModel; import com.wickvood.albumsearch.mvp.views.AlbumDetailView; import java.util.List; import javax.inject.Inject; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; @InjectViewState public class AlbumDetailPresenter extends MvpPresenter<AlbumDetailView> { @Inject NetworkService networkService; public AlbumDetailPresenter(){ App.getAppComponent().inject(this); } public void loadSongs(int albumId){ getViewState().onStartLoading(); networkService.getSongByAlbumId(albumId).enqueue(new Callback<SongResultModel>() { @Override public void onResponse(Call<SongResultModel> call, Response<SongResultModel> response) { if (response.code() == 200 && response.isSuccessful()){ SongResultModel resultModel = response.body(); assert resultModel != null; List<SongsModel> songsModelsList = resultModel.getResults(); songsModelsList.remove(0); onLoadingSuccess(songsModelsList); } else { getViewState().showError(String.valueOf(response.errorBody())); } } @Override public void onFailure(Call<SongResultModel> call, Throwable t) { onLoadingFailed(t); } }); } private void onLoadingSuccess(List<SongsModel> songsModelList){ getViewState().hideListProgress(); getViewState().setSongsModel(songsModelList); } private void onLoadingFailed(Throwable error) { getViewState().hideListProgress(); getViewState().showError(error.toString()); } public void onErrorCancel(){ getViewState().hideError(); } }
package Reader; import parameters.*; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.Set; public class ReadWithScanner { private final File fFilePath; private final Charset ENCODING = StandardCharsets.UTF_8; private Graph graph = new Graph(); // private ArrayList<Path> transmissions = new ArrayList<Path>(); private RequestedTransfer requestedTransfer; private int numSlices; private TransferCollections transferCollections; public ReadWithScanner() throws URISyntaxException, IOException { File fileParent= new File(System.getProperty("user.dir")); fFilePath = new File(fileParent,"inputGreedyGrasp.txt"); processReadLineByLine(); } public void printGraph() { System.out.println("Grafo: " + graph.toString()); } public Graph getGraph() { return graph; } public int getNumSlices(){ return numSlices; } public RequestedTransfer getRequestedTransfer() { return requestedTransfer; } public TransferCollections getTransferCollections() { return transferCollections; } public void processReadLineByLine() throws IOException { String lineIdentifier; String line; try (Scanner scanner = new Scanner(fFilePath, ENCODING.name())) { while (scanner.hasNextLine()) { lineIdentifier = scanner.nextLine(); line = scanner.nextLine(); processReadLine(lineIdentifier, line); } transferCollections.setRequestedTransfer(requestedTransfer); List<Transfer> transfers = transferCollections.getTransfers(); Set<Edge> edges = graph.getEdges(); for (Edge edge : edges) { for (Transfer transfer : transfers) { if (transfer.getPath().hasEdge(edge)) { edge.addTransfer(transfer); } } } scanner.close(); } } public void processReadLine(String lineIdentifier, String line) { if (lineIdentifier.equals("S")) { numSlices = Integer.parseInt(line); transferCollections = new TransferCollections(numSlices); } else if (lineIdentifier.equals("N")) { String[] nodes = line.split(" "); for (String node : nodes) { graph.addNode(node); } } else if (lineIdentifier.equals("G")) { String[] links = line.split(" "); String n1; String n2; int cost; for (String l : links) { n1 = l.substring(1, 2); n2 = l.substring(3, 4); cost = Integer.parseInt(l.substring(5, 6)); graph.addTwoWayVertex(n1, cost, n2, cost); } } else if (lineIdentifier.substring(0, 1).equals("T")) { LinkedList<NodePair> transmissionPath = new LinkedList<NodePair>(); String[] data = line.split(" "); boolean foundSeparator = false; int separatorIndex = 0; Transfer auxTransfer; int auxNodeOrigin; int auxNodeDestination; int auxTimeCompletion; int auxDataAmount; int auxMinCurrentSlices; int auxMaxCurrentSlices; int auxCurrentMaxTime; for (String d : data) { if (d.equals("/")) { foundSeparator = true; continue; } if (!foundSeparator) { transmissionPath.add(new NodePair(d, 0)); } else { break; } separatorIndex++; } auxNodeOrigin = graph.getNodeIdentifier(transmissionPath.get(0).getName()); auxNodeDestination = graph.getNodeIdentifier(transmissionPath.get(transmissionPath.size() - 1).getName()); auxTimeCompletion = Integer.parseInt(data[separatorIndex + 1]); auxDataAmount = Integer.parseInt(data[separatorIndex + 2]); auxMinCurrentSlices = Integer.parseInt(data[separatorIndex + 3]); auxMaxCurrentSlices = Integer.parseInt(data[separatorIndex + 4]); auxCurrentMaxTime = Integer.parseInt(data[separatorIndex + 5]); auxTransfer = new Transfer(auxNodeOrigin, auxNodeDestination, auxTimeCompletion, auxDataAmount); auxTransfer.setCurrentAllocation(auxMinCurrentSlices, auxMaxCurrentSlices, auxCurrentMaxTime); auxTransfer.setPath(new Path(transmissionPath, 0)); transferCollections.add_transfer(auxTransfer); } else if (lineIdentifier.substring(0, 1).equals("R")) { String[] requestedTransferInfo = line.split(" "); requestedTransfer = new RequestedTransfer(graph.getNodeIdentifier(requestedTransferInfo[0]), graph.getNodeIdentifier(requestedTransferInfo[1]), Integer.parseInt(requestedTransferInfo[2]), Integer.parseInt(requestedTransferInfo[3])); } } }
package com.example.PollingApplication.dto; import java.util.Collection; public class VoteResult { private int totalVotes; private Collection<ChoiceCount> results; public int getTotalVotes() { return totalVotes; } public void setTotalVotes(int totalVotes) { this.totalVotes = totalVotes; } public Collection<ChoiceCount> getResults() { return results; } public void setResults(Collection<ChoiceCount> results) { this.results = results; } }
package com.icanit.app_v2.ui; import android.app.Dialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ResolveInfo; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.CheckedTextView; import android.widget.GridView; import android.widget.TextView; import com.icanit.app_v2.R; import com.icanit.app_v2.util.AppUtil; public class CustomizedDialog extends Dialog { public TextView title,message; public Button positiveButton,negativeButton; public CheckedTextView checkedText; public GridView gv; public static int resId=R.layout.dialog_customized; public static int shareResId=R.layout.dialog_sharelist; public CustomizedDialog(Context context) { super(context); } CustomizedDialog(Context context, boolean cancelable, OnCancelListener cancelListener) { super(context, cancelable, cancelListener); } public boolean getCheckedTextStatus() { return checkedText.isChecked(); } public CustomizedDialog setPositiveButton(String name,final DialogInterface.OnClickListener listener){ positiveButton.setVisibility(View.VISIBLE); positiveButton.setText(name); positiveButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(listener!=null) listener.onClick(CustomizedDialog.this, DialogInterface.BUTTON_POSITIVE); dismiss(); } }); return this; } public CustomizedDialog setNegativeButton(String name,final DialogInterface.OnClickListener listener){ negativeButton.setVisibility(View.VISIBLE); negativeButton.setText(name); negativeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(listener!=null) listener.onClick(CustomizedDialog.this, DialogInterface.BUTTON_NEGATIVE); dismiss(); } }); return this; } public CustomizedDialog(Context context, int theme) { super(context, theme); } public static CustomizedDialog initDialog(String title,String message,String checkedText,float fontSize,Context context){ CustomizedDialog dialog= new CustomizedDialog(context,R.style.dialogStyle); View contentView=LayoutInflater.from(context).inflate(resId, null,false); dialog.setContentView(contentView); dialog.title=((TextView)contentView.findViewById(R.id.title)); dialog.message=((TextView)contentView.findViewById(R.id.message)); dialog.positiveButton= ((Button)contentView.findViewById(R.id.positiveButton)); dialog.negativeButton=(Button)contentView.findViewById(R.id.negativeButton); dialog.checkedText=(CheckedTextView)contentView.findViewById(R.id.checkedTextView1); dialog.title.setText(title); if(fontSize!=0) dialog.message.setTextSize(fontSize); dialog.message.setText(message); if(checkedText!=null){ dialog.checkedText.setText(checkedText); AppUtil.setOnClickListenerForCheckedTextView(dialog.checkedText); }else{dialog.checkedText.setVisibility(View.GONE);} dialog.positiveButton.setVisibility(View.GONE); dialog.negativeButton.setVisibility(View.GONE); return dialog; } public static CustomizedDialog initShareDialog(String title,final Context context){ final CustomizedDialog dialog= new CustomizedDialog(context,R.style.dialogStyle); View contentView=LayoutInflater.from(context).inflate(shareResId, null,false); dialog.setContentView(contentView); dialog.title=((TextView)contentView.findViewById(R.id.title)); dialog.gv=(GridView)contentView.findViewById(R.id.gridView1); dialog.title.setText(title); return dialog; } public static class Builder{ Context context; String title,message,positiveButton,negativeButton,checkedText; float fontSize; DialogInterface.OnClickListener positiveButtonListener,negativeButtonListener; public Builder(Context context){ this.context=context; } public Builder setTitle(String title){ this.title=title;return this; } public Builder setMessage(String message){ this.message=message; return this; } public Builder setCheckedText(String text){ this.checkedText=text; return this; } public Builder setContentFontSize(float size){ this.fontSize=size; return this; } public Builder setPositiveButton(String name,DialogInterface.OnClickListener listener){ this.positiveButton=name; this.positiveButtonListener=listener;return this; } public Builder setNegativeButton(String name,DialogInterface.OnClickListener listener){ this.negativeButton=name; this.negativeButtonListener=listener;return this; } public CustomizedDialog create(){ final CustomizedDialog dialog=initDialog(title,message,checkedText,fontSize,context); if(positiveButton!=null){ dialog.positiveButton.setVisibility(View.VISIBLE); dialog.positiveButton.setText(positiveButton); dialog.positiveButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(positiveButtonListener!=null) positiveButtonListener.onClick(dialog, DialogInterface.BUTTON_POSITIVE); dialog.dismiss(); } }); }else{dialog.positiveButton.setVisibility(View.GONE);} if(negativeButton!=null){ dialog.negativeButton.setVisibility(View.VISIBLE); dialog.negativeButton.setText(negativeButton); dialog.negativeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(negativeButtonListener!=null) negativeButtonListener.onClick(dialog, DialogInterface.BUTTON_NEGATIVE); dialog.dismiss(); } }); }else{dialog.negativeButton.setVisibility(View.GONE);} LayoutParams lp=dialog.getWindow().getAttributes(); System.out.println("height="+lp.height+",width="+lp.width+" @CustomizedDialog"); return dialog; } } }
package Lector13.Task5; import com.sun.org.apache.xpath.internal.objects.XBoolean; public class WordCount { public static void wordCount (String str){ int count = 0; String[] strArr = str.split(" +"); for (int i = 0; i < strArr.length; i ++){ count++; } System.out.println("Слов в тексте: " + count); } }
package diplomski.autoceste.services; import diplomski.autoceste.forms.VehicleDto; import diplomski.autoceste.forms.VehicleParameterDto; import diplomski.autoceste.models.PrivateUser; import diplomski.autoceste.models.Vehicle; import diplomski.autoceste.models.VehicleCategory; import diplomski.autoceste.repositories.PrivateUserRepository; import diplomski.autoceste.repositories.VehicleRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.data.util.Pair; import org.springframework.stereotype.Service; import java.util.List; import java.util.stream.Collectors; @Service public class VehicleServiceImpl implements VehicleService { private VehicleRepository repository; private PrivateUserRepository privateUserRepository; @Autowired public VehicleServiceImpl(VehicleRepository repository, PrivateUserRepository privateUserRepository) { this.repository = repository; this.privateUserRepository = privateUserRepository; } @Override public boolean addVehicle(VehicleDto dto) { Vehicle v = new Vehicle(); v.setCategory(VehicleCategory.valueOf(dto.getCategory())); v.setColor(dto.getColor()); v.setType(dto.getType()); v.setHeight(dto.getHeight()); v.setManufacturer(dto.getManufacturer()); v.setMaxWeightWithCargo(dto.getMaxWeight()); v.setPlate(dto.getPlate()); v.setPrivateUser(privateUserRepository.findById(dto.getUserId()).get()); v.setHasGreenCertificate(dto.getCertificate()); try { repository.save(v); } catch (DataIntegrityViolationException e) { return false; } return true; } @Override public List<Vehicle> getVehiclesForPrivateUser(PrivateUser privateUser) { List<Vehicle> vehicles = repository.findAllByPrivateUser(privateUser); return vehicles; } public List<VehicleParameterDto> getVehicleParams() { List<Object[]> result = repository.getColumnsWithTypes(); return result.stream() .map(e -> Pair.of((String) e[0], (String) e[1])) .filter(e -> !e.getFirst().equals("id")) .filter(e -> !e.getFirst().equals("private_user_id")) .map(VehicleParameterDto::new) .collect(Collectors.toList()); } @Override public Vehicle findByPlate(String plate) { Vehicle v = repository.findByPlate(plate); if (v == null) { throw new NullPointerException("Automobil nije registriran"); } return v; } }
package com.gfkl.adventofcode; import org.junit.jupiter.api.Test; import java.io.IOException; import static org.junit.jupiter.api.Assertions.*; public class PasswordCheckerTest { @Test public void shouldFindTwoValidPasswords() throws IOException { assertEquals(2, PasswordChecker.checkRangePasswords("src/test/resources/input")); } @Test public void shouldFindOneValidPasswords() throws IOException { assertEquals(1, PasswordChecker.checkPositionsPasswords("src/test/resources/input")); } }
package chapter7; public class Employee { private String firstName; private String lastName; private static int minWage; private Date birthDate; private Date hireDate; public Employee() { this(null,null); } public Employee(String fName, String lName) { firstName = fName; lastName = lName; } public Employee(String fName, String lName, Date birthDate, Date hireDate) { firstName = fName; lastName = lName; this.birthDate = birthDate; this.hireDate = hireDate; } public static int getMinWage() { return minWage; } public static void setMinWage(int minWage) { Employee.minWage = minWage; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public Date getHireDate() { return hireDate; } public void setHireDate(Date hireDate) { this.hireDate = hireDate; } public void setFirstName(String fName) { firstName = fName; } public String getFirstName() { // TODO Auto-generated method stub return firstName; } public String toString() { return String.format("%s %s hired: %s birthDay: %s", firstName,lastName, hireDate, birthDate); } public void setLastName(String lName) { lastName = lName; } public String getLastName() { // TODO Auto-generated method stub return lastName; } }
package com.sh.offer.tree; import com.sh.leetcode.structure.TreeNode; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; /** * @Auther: bjshaohang * @Date: 2019/2/2 */ public class PrintFromTopToButtom { public static void main(String[] args) { int[] array = {0,1,2,3,4,5,6,7,8,9,10}; TreeNode root= TreeNode.makeBinaryTreeByArray(array,1); ArrayList<Integer> list = new PrintFromTopToButtom().printFromTopToBottom(root); list.forEach(k->{ System.out.println(k); }); } public ArrayList<Integer> printFromTopToBottom(TreeNode root) { if(root == null){ return new ArrayList<Integer>(); } ArrayList<Integer> result = new ArrayList<>(); Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()){ TreeNode node = queue.remove(); if(node.left != null){ queue.add(node.left); } if(node.right!= null){ queue.add(node.right); } result.add(node.val); } return result; } public ArrayList<Integer> printFromTopToBottom2(TreeNode root) { if (root == null){ return new ArrayList<Integer>(); } ArrayList<Integer> result = new ArrayList<>(); result.add(root.val); while (root.left != null){ doMethod(root.left,result); } while (root.right != null){ doMethod(root.right,result); } return result; } public void doMethod(TreeNode node, ArrayList<Integer> list){ if (node == null){ return; } list.add(node.val); } }
package com.tsuro.tile; import com.tsuro.board.Token; import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.plaf.LayerUI; import lombok.NonNull; /** * A {@link LayerUI} for {@link TileComponent}s, where this Layer draws the token on a Tile. */ public class TokenLayer extends LayerUI<JComponent> { private final Location loc; private final int index; private final Token token; private final double RADIUS = .1; private final double INDEX_PERCENT = .1; /** * Construct with a preset index */ public TokenLayer(@NonNull Token token, @NonNull Location loc) { this(token, loc, 0); } /** * Normal constructor that calls super() for convention. * * @param index Draws the token INDEX_PERCENT% smaller for each index so that tokens can overlap */ public TokenLayer(@NonNull Token token, @NonNull Location loc, int index) { super(); this.token = token; this.loc = loc; this.index = index; } @Override public void paint(@NonNull Graphics g, @NonNull JComponent comp) { super.paint(g, comp); g.setColor(token.getColor()); double radiusToUse = RADIUS * Math.pow(1 - INDEX_PERCENT, index); final int W = comp.getWidth(); final int H = comp.getHeight(); final int xLocation = (int) (loc.renderX * W); final int yLocation = (int) (loc.renderY * H); final int ovalXRadius = (int) (W * radiusToUse); final int ovalYRadius = (int) (H * radiusToUse); g.fillOval(xLocation - ovalXRadius, yLocation - ovalYRadius, ovalXRadius * 2, ovalYRadius * 2); } }
package msip.go.kr.memo.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import msip.go.kr.common.entity.Item; @SuppressWarnings("serial") @Entity @Table(name="memo") public class Memo extends Item { @Column(name="content", columnDefinition="VARCHAR") private String content; public Memo() { } public Memo(Long id) { this.setId(id); } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
/* * Copyright (C) 2015 Adrien Guille <adrien.guille@univ-lyon2.fr> * * 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 main.java.fr.ericlab.sondy.algo.influenceanalysis; import java.util.HashMap; import main.java.fr.ericlab.sondy.core.app.AppParameters; import org.graphstream.graph.Node; /** * * @author Adrien GUILLE, ERIC Lab, University of Lyon 2 * @email adrien.guille@univ-lyon2.fr */ public class BetweennessCentrality extends InfluenceAnalysisMethod { public BetweennessCentrality(){ super(); } @Override public String getName() { return "Betweenness Centrality"; } @Override public String getCitation() { return "<li><b>Betweenness centrality:</b> L. Freeman (1977) A set of measures of centrality based on betweenness. Sociometry, vol. 40 pp. 35-41</li>"; } @Override public String getDescription() { return "Computes the number of shortest paths from all users to all others that pass through each user"; } @Override public void apply() { org.graphstream.algorithm.BetweennessCentrality bcb = new org.graphstream.algorithm.BetweennessCentrality(); bcb.init(AppParameters.authorNetwork); bcb.compute(); for (Node node : AppParameters.authorNetwork) { double rank = node.getAttribute("Cb"); rankedUsers.add(node.getId(),(int)(rank)); } } }
package br.com.rafagonc.tjdata.models; import br.com.rafagonc.tjdata.repositories.CookieRepository; import br.com.rafagonc.tjdata.repositories.ESAJCaptchaRepository; public class ESAJCaptchaRepositoryKit { private ESAJCaptchaRepository captchaRepository; private CookieRepository cookieRepository; public ESAJCaptchaRepositoryKit(ESAJCaptchaRepository captchaRepository, CookieRepository cookieRepository) { this.captchaRepository = captchaRepository; this.cookieRepository = cookieRepository; } public ESAJCaptchaRepository getCaptchaRepository() { return captchaRepository; } public void setCaptchaRepository(ESAJCaptchaRepository captchaRepository) { this.captchaRepository = captchaRepository; } public CookieRepository getCookieRepository() { return cookieRepository; } public void setCookieRepository(CookieRepository cookieRepository) { this.cookieRepository = cookieRepository; } }
package info.datacluster.crawler.mapper; import info.datacluster.crawler.entity.CrawlerTask; public interface CrawlerTaskMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table crawler_task * * @mbg.generated Sun Aug 25 22:01:54 CST 2019 */ int deleteByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table crawler_task * * @mbg.generated Sun Aug 25 22:01:54 CST 2019 */ int insert(CrawlerTask record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table crawler_task * * @mbg.generated Sun Aug 25 22:01:54 CST 2019 */ int insertSelective(CrawlerTask record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table crawler_task * * @mbg.generated Sun Aug 25 22:01:54 CST 2019 */ CrawlerTask selectByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table crawler_task * * @mbg.generated Sun Aug 25 22:01:54 CST 2019 */ int updateByPrimaryKeySelective(CrawlerTask record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table crawler_task * * @mbg.generated Sun Aug 25 22:01:54 CST 2019 */ int updateByPrimaryKey(CrawlerTask record); }
/*----------------------------------------------------------------------------- CS 211 01/20/2015 Kathryn Brusewitz Class: ItemOrder Super Class: Object Implements: None ItemOrder represents a shoppers order for a given Item in a given quantity. Public Interface ------------------------------------------------------------ ItemOrder(Item, int) Initializing Constructor: item, quantity boolean equals(Object) Test this with other class object for equality String toString() RETurns "String" description of this order double getPrice() RETurns the cost for this order Item getItem() RETurns a reference to the item in this order int getQuantity() RETurns the quantity of this order Private Methods ------------------------------------------------------------- non-static Item item The Item object this order is for non-static int quantity Quantity ordered of the Item ------------------------------------------------------------------------------*/ public class ItemOrder { public ItemOrder(Item item, int quantity) { if (quantity < 0) throw new IllegalArgumentException(); this.item = item; this.quantity = quantity; } @Override public boolean equals(Object object) { if (object instanceof ItemOrder) { ItemOrder other = (ItemOrder) object; return item == other.item && quantity == other.quantity && this.getPrice() == other.getPrice(); } else return false; } @Override public String toString() { return String.format(" %s%n Quantity: %d%n Final Price: %.2f%n%n", item, quantity, this.getPrice()); } public double getPrice() { return item.priceFor(quantity); } public Item getItem() { return item; } public int getQuantity() { return quantity; } private Item item; private int quantity; }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.config.annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import org.springframework.core.task.AsyncTaskExecutor; import org.springframework.lang.Nullable; import org.springframework.web.context.request.async.CallableProcessingInterceptor; import org.springframework.web.context.request.async.DeferredResult; import org.springframework.web.context.request.async.DeferredResultProcessingInterceptor; /** * Helps with configuring options for asynchronous request processing. * * @author Rossen Stoyanchev * @since 3.2 */ public class AsyncSupportConfigurer { @Nullable private AsyncTaskExecutor taskExecutor; @Nullable private Long timeout; private final List<CallableProcessingInterceptor> callableInterceptors = new ArrayList<>(); private final List<DeferredResultProcessingInterceptor> deferredResultInterceptors = new ArrayList<>(); /** * The provided task executor is used for the following: * <ol> * <li>Handle {@link Callable} controller method return values. * <li>Perform blocking writes when streaming to the response * through a reactive (e.g. Reactor, RxJava) controller method return value. * </ol> * <p>If your application has controllers with such return types, please * configure an {@link AsyncTaskExecutor} as the one used by default is not * suitable for production under load. * @param taskExecutor the task executor instance to use by default */ public AsyncSupportConfigurer setTaskExecutor(AsyncTaskExecutor taskExecutor) { this.taskExecutor = taskExecutor; return this; } /** * Specify the amount of time, in milliseconds, before asynchronous request * handling times out. In Servlet 3, the timeout begins after the main request * processing thread has exited and ends when the request is dispatched again * for further processing of the concurrently produced result. * <p>If this value is not set, the default timeout of the underlying * implementation is used. * @param timeout the timeout value in milliseconds */ public AsyncSupportConfigurer setDefaultTimeout(long timeout) { this.timeout = timeout; return this; } /** * Configure lifecycle interceptors with callbacks around concurrent request * execution that starts when a controller returns a * {@link java.util.concurrent.Callable}. * @param interceptors the interceptors to register */ public AsyncSupportConfigurer registerCallableInterceptors(CallableProcessingInterceptor... interceptors) { this.callableInterceptors.addAll(Arrays.asList(interceptors)); return this; } /** * Configure lifecycle interceptors with callbacks around concurrent request * execution that starts when a controller returns a {@link DeferredResult}. * @param interceptors the interceptors to register */ public AsyncSupportConfigurer registerDeferredResultInterceptors( DeferredResultProcessingInterceptor... interceptors) { this.deferredResultInterceptors.addAll(Arrays.asList(interceptors)); return this; } @Nullable protected AsyncTaskExecutor getTaskExecutor() { return this.taskExecutor; } @Nullable protected Long getTimeout() { return this.timeout; } protected List<CallableProcessingInterceptor> getCallableInterceptors() { return this.callableInterceptors; } protected List<DeferredResultProcessingInterceptor> getDeferredResultInterceptors() { return this.deferredResultInterceptors; } }
package com.citibank.ods.entity.pl.valueobject; import java.math.BigInteger; import java.util.Date; import com.citibank.ods.common.entity.valueobject.BaseEntityVO; /** * @author m.nakamura * * Representação da tabela de Memória de Risco. */ public class BaseTplMrDocPrvtEntityVO extends BaseEntityVO { // Data e Hora da Ultima Atualizacao Efetuada pelo Usuario. private Date m_lastUpdDate = null; // Codigo do Usuario que Efetuou a Ultima Atualizacao no Registro. private String m_lastUpdUserId = ""; // Descricao do Instrucao Permanente private String m_mrDocText = ""; // Indicador de Utilizacao de Conta CCI: 'S' (Sim), 'N' (Nao) private String m_mrInvstCurAcctInd = ""; // Codigo da Conta Produto private BigInteger m_prodAcctCode = null; // Codigo da Sub-conta Produto private BigInteger m_prodUnderAcctCode = null; /** * Recupera a Data e Hora da Ultima Atualizacao Efetuada pelo Usuario. * * @return Retorna a Data e Hora da Ultima Atualizacao Efetuada pelo Usuario. */ public Date getLastUpdDate() { return m_lastUpdDate; } /** * Seta a Data e Hora da Ultima Atualizacao Efetuada pelo Usuario. * * @param lastUpdDate_ - A Data e Hora da Ultima Atualizacao Efetuada pelo * Usuario. */ public void setLastUpdDate( Date lastUpdDate_ ) { m_lastUpdDate = lastUpdDate_; } /** * Recupera o Codigo do Usuario que Efetuou a Ultima Atualizacao no Registro. * * @return Retorna o Codigo do Usuario que Efetuou a Ultima Atualizacao no * Registro. */ public String getLastUpdUserId() { return m_lastUpdUserId; } /** * Seta o Codigo do Usuario que Efetuou a Ultima Atualizacao no Registro. * * @param lastUpdUserId_ - O Codigo do Usuario que Efetuou a Ultima * Atualizacao no Registro. */ public void setLastUpdUserId( String lastUpdUserId_ ) { m_lastUpdUserId = lastUpdUserId_; } /** * Recupera a Descricao do Instrucao Permanente * * @return Retorna a Descricao do Instrucao Permanente */ public String getMrDocText() { return m_mrDocText; } /** * Seta a Descricao do Instrucao Permanente * * @param mrDocText_ - A Descricao do Instrucao Permanente */ public void setMrDocText( String mrDocText_ ) { m_mrDocText = mrDocText_; } /** * Recupera o Indicador de Utilizacao de Conta CCI * * @return Retorna o Indicador de Utilizacao de Conta CCI */ public String getMrInvstCurAcctInd() { return m_mrInvstCurAcctInd; } /** * Seta o Indicador de Utilizacao de Conta CCI * * @param mrInvstCurAcctInd_ - O Indicador de Utilizacao de Conta CCI */ public void setMrInvstCurAcctInd( String mrInvstCurAcctInd_ ) { m_mrInvstCurAcctInd = mrInvstCurAcctInd_; } /** * Retorna o Codigo da Conta Produto * * @return Retorna o Codigo da Conta Produto */ public BigInteger getProdAcctCode() { return m_prodAcctCode; } /** * Seta o Codigo da Conta Produto * * @param prodAcctCode_ - o Codigo da Conta Produto */ public void setProdAcctCode( BigInteger prodAcctCode_ ) { m_prodAcctCode = prodAcctCode_; } /** * Recupera o Codigo da Sub-conta Produto * * @return Retorna o Codigo da Sub-conta Produto */ public BigInteger getProdUnderAcctCode() { return m_prodUnderAcctCode; } /** * Seta o Codigo da Sub-conta Produto * * @param prodUnderAcctCode_ - O Codigo da Sub-conta Produto */ public void setProdUnderAcctCode( BigInteger prodUnderAcctCode_ ) { m_prodUnderAcctCode = prodUnderAcctCode_; } }
package si.vei.pedram.builditbigger; import android.test.AndroidTestCase; import java.util.concurrent.TimeUnit; /** * Created by pedram on 20/12/15. */ public class EndpointsAsyncTaskTest extends AndroidTestCase { public void testJokeIsReturned() { try { EndpointsAsyncTask jokeTask = new EndpointsAsyncTask(mContext, false); jokeTask.execute(); String joke = jokeTask.get(30, TimeUnit.SECONDS); assertFalse(joke.isEmpty()); } catch (Exception e) { fail(e.toString()); } } }
package com.nematjon.edd_client_season_two.services; import android.Manifest; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Color; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.TrafficStats; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.core.app.ActivityCompat; import androidx.core.app.NotificationCompat; import com.google.android.gms.location.ActivityRecognition; import com.google.android.gms.location.ActivityRecognitionClient; import com.google.android.gms.location.ActivityTransition; import com.google.android.gms.location.ActivityTransitionRequest; import com.google.android.gms.location.DetectedActivity; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.nematjon.edd_client_season_two.AppUseDb; import com.nematjon.edd_client_season_two.AuthActivity; import com.nematjon.edd_client_season_two.DbMgr; import com.nematjon.edd_client_season_two.EMAActivity; import com.nematjon.edd_client_season_two.MainActivity; import com.nematjon.edd_client_season_two.R; import com.nematjon.edd_client_season_two.Tools; import com.nematjon.edd_client_season_two.receivers.ActivityTransRcvr; import com.nematjon.edd_client_season_two.receivers.CallRcvr; import com.nematjon.edd_client_season_two.receivers.ScreenAndUnlockRcvr; import com.nematjon.edd_client_season_two.receivers.SignificantMotionDetector; import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.List; import java.util.Locale; import inha.nsl.easytrack.ETServiceGrpc; import inha.nsl.easytrack.EtService; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.StatusRuntimeException; public class MainService extends Service implements SensorEventListener, LocationListener { private static final String TAG = MainService.class.getSimpleName(); //region Constants private static final int ID_SERVICE = 101; public static final int EMA_NOTIFICATION_ID = 1234; //in sec public static final int PERMISSION_REQUEST_NOTIFICATION_ID = 1111; //in sec public static final long EMA_RESPONSE_EXPIRE_TIME = 3600; //in sec public static final int SERVICE_START_X_MIN_BEFORE_EMA = 3 * 60; //min public static final short HEARTBEAT_PERIOD = 30; //in sec public static final short DATA_SUBMIT_PERIOD = 1; //in min private static final short AUDIO_RECORDING_PERIOD = 5 * 60; //in sec private static final short LIGHT_SENSOR_PERIOD = 30; //in sec private static final short AUDIO_RECORDING_DURATION = 5; //in sec private static final int APP_USAGE_SEND_PERIOD = 3; //in sec private static final int LOCATION_UPDATE_MIN_INTERVAL = 5 * 60 * 1000; //milliseconds private static final int LOCATION_UPDATE_MIN_DISTANCE = 0; // meters public static final String LOCATIONS_TXT = "locations.txt"; //endregion private SensorManager sensorManager; private Sensor sensorStepDetect; private Sensor sensorPressure; private Sensor sensorLight; private Sensor sensorSM; private SignificantMotionDetector SMListener; static SharedPreferences loginPrefs; static SharedPreferences confPrefs; static int stepDetectorDataSrcId; static int pressureDataSrcId; static int lightDataSrcId; private static long prevLightStartTime = 0; private static long prevAudioRecordStartTime = 0; static NotificationManager mNotificationManager; static Boolean permissionNotificationPosted; private ScreenAndUnlockRcvr mPhoneUnlockedReceiver; private CallRcvr mCallReceiver; private AudioFeatureRecorder audioFeatureRecorder; private LocationManager locationManager; private ActivityRecognitionClient activityTransitionClient; private PendingIntent activityTransPendingIntent; //private static boolean canSendNotif = true; private Handler mainHandler = new Handler(); private Runnable mainRunnable = new Runnable() { @Override public void run() { //check if all permissions are set then dismiss notification for request if (Tools.hasPermissions(getApplicationContext(), Tools.PERMISSIONS)) { mNotificationManager.cancel(PERMISSION_REQUEST_NOTIFICATION_ID); permissionNotificationPosted = false; } long nowTime = System.currentTimeMillis(); //region Registering Audio recorder periodically boolean canStartAudioRecord = (nowTime > prevAudioRecordStartTime + AUDIO_RECORDING_PERIOD * 1000) || CallRcvr.AudioRunningForCall; boolean stopAudioRecord = (nowTime > prevAudioRecordStartTime + AUDIO_RECORDING_DURATION * 1000); if (canStartAudioRecord) { if (audioFeatureRecorder == null) audioFeatureRecorder = new AudioFeatureRecorder(MainService.this); audioFeatureRecorder.start(); prevAudioRecordStartTime = nowTime; } else if (stopAudioRecord) { if (audioFeatureRecorder != null) { audioFeatureRecorder.stop(); audioFeatureRecorder = null; } } //endregion mainHandler.postDelayed(this, 5 * 1000); } }; private Handler dataSubmissionHandler = new Handler(); private Runnable dataSubmitRunnable = new Runnable() { @Override public void run() { new Thread(new Runnable() { @Override public void run() { if (Tools.isNetworkAvailable()) { Cursor cursor = DbMgr.getSensorData(); if (cursor.moveToFirst()) { ManagedChannel channel = ManagedChannelBuilder.forAddress( getString(R.string.grpc_host), Integer.parseInt(getString(R.string.grpc_port)) ).usePlaintext().build(); ETServiceGrpc.ETServiceBlockingStub stub = ETServiceGrpc.newBlockingStub(channel); loginPrefs = getSharedPreferences("UserLogin", MODE_PRIVATE); int userId = loginPrefs.getInt(AuthActivity.user_id, -1); String email = loginPrefs.getString(AuthActivity.usrEmail, null); try { do { EtService.SubmitDataRecordRequestMessage submitDataRecordRequestMessage = EtService.SubmitDataRecordRequestMessage.newBuilder() .setUserId(userId) .setEmail(email) .setDataSource(cursor.getInt(cursor.getColumnIndex("dataSourceId"))) .setTimestamp(cursor.getLong(cursor.getColumnIndex("timestamp"))) .setValues(cursor.getString(cursor.getColumnIndex("data"))) .build(); EtService.DefaultResponseMessage responseMessage = stub.submitDataRecord(submitDataRecordRequestMessage); if (responseMessage.getDoneSuccessfully()) { DbMgr.deleteRecord(cursor.getInt(cursor.getColumnIndex("id"))); } } while (cursor.moveToNext()); } catch (StatusRuntimeException e) { Log.e(TAG, "DataCollectorService.setUpDataSubmissionThread() exception: " + e.getMessage()); e.printStackTrace(); } finally { channel.shutdown(); } } cursor.close(); } } }).start(); dataSubmissionHandler.postDelayed(dataSubmitRunnable, DATA_SUBMIT_PERIOD * 60 * 1000); } }; private Handler appUsageSaveHandler = new Handler(); private Runnable appUsageSaveRunnable = new Runnable() { public void run() { Tools.checkAndSaveUsageAccessStats(getApplicationContext()); appUsageSaveHandler.postDelayed(this, APP_USAGE_SEND_PERIOD * 1000); } }; private Handler heartBeatHandler = new Handler(); private Runnable heartBeatSendRunnable = new Runnable() { public void run() { //before sending heart-beat check permissions granted or not. If not grant first if (!Tools.hasPermissions(getApplicationContext(), Tools.PERMISSIONS) && !permissionNotificationPosted) { permissionNotificationPosted = true; sendNotificationForPermissionSetting(); // send notification if any permission is disabled } Tools.sendHeartbeat(MainService.this); heartBeatHandler.postDelayed(this, HEARTBEAT_PERIOD * 1000); } }; @Override public void onCreate() { super.onCreate(); loginPrefs = getSharedPreferences("UserLogin", MODE_PRIVATE); confPrefs = getSharedPreferences("Configurations", Context.MODE_PRIVATE); stepDetectorDataSrcId = confPrefs.getInt("ANDROID_STEP_DETECTOR", -1); pressureDataSrcId = confPrefs.getInt("ANDROID_PRESSURE", -1); lightDataSrcId = confPrefs.getInt("ANDROID_LIGHT", -1); sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); if (sensorManager != null) { sensorPressure = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE); sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); sensorStepDetect = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR); sensorManager.registerListener(this, sensorStepDetect, SensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(this, sensorPressure, SensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(this, sensorLight, SensorManager.SENSOR_DELAY_NORMAL); SMListener = new SignificantMotionDetector(this); sensorSM = sensorManager.getDefaultSensor(Sensor.TYPE_SIGNIFICANT_MOTION); if (sensorSM != null) { sensorManager.requestTriggerSensor(SMListener, sensorSM); } else { Log.e(TAG, "Significant motion sensor is NOT available"); } } locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_UPDATE_MIN_INTERVAL, LOCATION_UPDATE_MIN_DISTANCE, this); } activityTransitionClient = ActivityRecognition.getClient(getApplicationContext()); activityTransPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(getApplicationContext(), ActivityTransRcvr.class), PendingIntent.FLAG_UPDATE_CURRENT); activityTransitionClient.requestActivityTransitionUpdates(new ActivityTransitionRequest(getActivityTransitions()), activityTransPendingIntent) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.d(TAG, "Registered: Activity Transition"); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.e(TAG, "Failed: Activity Transition " + e.toString()); } }); //region Register Phone unlock & Screen On state receiver mPhoneUnlockedReceiver = new ScreenAndUnlockRcvr(); IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_USER_PRESENT); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_SCREEN_ON); registerReceiver(mPhoneUnlockedReceiver, filter); //endregion //region Register Phone call logs receiver mCallReceiver = new CallRcvr(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_NEW_OUTGOING_CALL); intentFilter.addAction(Intent.EXTRA_PHONE_NUMBER); registerReceiver(mCallReceiver, intentFilter); //endregion //region Posting Foreground notification when service is started mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); String channel_id = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createNotificationChannel() : ""; NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channel_id) .setOngoing(true) .setSubText(getString(R.string.noti_service_running)) .setPriority(NotificationCompat.PRIORITY_LOW) .setSmallIcon(R.mipmap.ic_launcher_no_bg) .setCategory(NotificationCompat.CATEGORY_SERVICE); Notification notification = builder.build(); startForeground(ID_SERVICE, notification); //endregion mainHandler.post(mainRunnable); heartBeatHandler.post(heartBeatSendRunnable); appUsageSaveHandler.post(appUsageSaveRunnable); dataSubmissionHandler.post(dataSubmitRunnable); permissionNotificationPosted = false; } @RequiresApi(Build.VERSION_CODES.O) public String createNotificationChannel() { String id = "YouNoOne_channel_id"; String name = "You no one channel id"; String description = "This is description"; NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_LOW); mChannel.setDescription(description); mChannel.enableLights(true); mChannel.setLightColor(Color.RED); mChannel.enableVibration(true); NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); if (mNotificationManager != null) { mNotificationManager.createNotificationChannel(mChannel); } return id; } @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } @Override public void onDestroy() { //region Unregister listeners sensorManager.unregisterListener(this, sensorPressure); sensorManager.unregisterListener(this, sensorLight); sensorManager.unregisterListener(this, sensorStepDetect); sensorManager.cancelTriggerSensor(SMListener, sensorSM); // activityRecognitionClient.removeActivityUpdates(activityRecPendingIntent); activityTransitionClient.removeActivityTransitionUpdates(activityTransPendingIntent); if (audioFeatureRecorder != null) audioFeatureRecorder.stop(); //stopService(stationaryDetector); unregisterReceiver(mPhoneUnlockedReceiver); unregisterReceiver(mCallReceiver); mainHandler.removeCallbacks(mainRunnable); heartBeatHandler.removeCallbacks(heartBeatSendRunnable); appUsageSaveHandler.removeCallbacks(appUsageSaveRunnable); dataSubmissionHandler.removeCallbacks(dataSubmitRunnable); locationManager.removeUpdates(this); //remove location listener //endregion //region Stop foreground service stopForeground(false); mNotificationManager.cancel(ID_SERVICE); mNotificationManager.cancel(PERMISSION_REQUEST_NOTIFICATION_ID); //endregion Tools.sleep(1000); super.onDestroy(); } private List<ActivityTransition> getActivityTransitions() { List<ActivityTransition> transitionList = new ArrayList<>(); ArrayList<Integer> activities = new ArrayList<>(Arrays.asList( DetectedActivity.STILL, DetectedActivity.WALKING, DetectedActivity.RUNNING, DetectedActivity.ON_BICYCLE, DetectedActivity.IN_VEHICLE)); for (int activity : activities) { transitionList.add(new ActivityTransition.Builder() .setActivityType(activity) .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER).build()); transitionList.add(new ActivityTransition.Builder() .setActivityType(activity) .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT).build()); } return transitionList; } //function to save some stats when the EMA button submit it clicked private void saveSomeStats() { // saving app usage data final long app_usage_time_end = System.currentTimeMillis(); final long app_usage_time_start = (app_usage_time_end - SERVICE_START_X_MIN_BEFORE_EMA * 60 * 1000) + 1000; // add one second to start time new Thread(new Runnable() { @Override public void run() { SharedPreferences configPrefs = getSharedPreferences("Configurations", Context.MODE_PRIVATE); int dataSourceId = configPrefs.getInt("APPLICATION_USAGE", -1); assert dataSourceId != -1; Cursor cursor = AppUseDb.getAppUsage(); if (cursor.moveToFirst()) { do { String package_name = cursor.getString(1); long start_time = cursor.getLong(2); long end_time = cursor.getLong(3); if (Tools.inRange(start_time, app_usage_time_start, app_usage_time_end) && Tools.inRange(end_time, app_usage_time_start, app_usage_time_end)) if (start_time < end_time) { //Log.e(TAG, "Inserting -> package: " + package_name + "; start: " + start_time + "; end: " + end_time); DbMgr.saveMixedData(dataSourceId, start_time, 1.0f, start_time, end_time, package_name); } } while (cursor.moveToNext()); } cursor.close(); } }).start(); // saving transmitted & received network data new Thread(new Runnable() { @Override public void run() { long nowTime = System.currentTimeMillis(); String usage_tx_type = "TX"; String usage_rx_type = "RX"; SharedPreferences networkPrefs = getSharedPreferences("NetworkVariables", MODE_PRIVATE); SharedPreferences configPrefs = getSharedPreferences("Configurations", Context.MODE_PRIVATE); long prevRx = networkPrefs.getLong("prev_rx_network_data", 0); long prevTx = networkPrefs.getLong("prev_tx_network_data", 0); long rxBytes = TrafficStats.getTotalRxBytes() - prevRx; long txBytes = TrafficStats.getTotalTxBytes() - prevTx; final long time_start = (nowTime - SERVICE_START_X_MIN_BEFORE_EMA * 60 * 1000) + 1000; // add one second to start time int dataSourceId = configPrefs.getInt("NETWORK_USAGE", -1); assert dataSourceId != -1; DbMgr.saveMixedData(dataSourceId, nowTime, 1.0f, time_start, nowTime, rxBytes, usage_tx_type); DbMgr.saveMixedData(dataSourceId, nowTime, 1.0f, time_start, nowTime, txBytes, usage_rx_type); SharedPreferences.Editor editor = networkPrefs.edit(); editor.putLong("prev_rx_network_data", rxBytes); editor.putLong("prev_tx_network_data", txBytes); editor.apply(); } }).start(); } @Override public IBinder onBind(Intent intent) { return null; } private void sendNotification(int ema_order) { final NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); Intent notificationIntent = new Intent(MainService.this, EMAActivity.class); notificationIntent.putExtra("ema_order", ema_order); //PendingIntent pendingIntent = PendingIntent.getActivities(CustomSensorsService.this, 0, new Intent[]{notificationIntent}, 0); PendingIntent pendingIntent = PendingIntent.getActivity(MainService.this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); String channelId = this.getString(R.string.notif_channel_id); NotificationCompat.Builder builder = new NotificationCompat.Builder(this.getApplicationContext(), channelId); builder.setContentTitle(this.getString(R.string.app_name)) .setTimeoutAfter(1000 * EMA_RESPONSE_EXPIRE_TIME) .setContentText(this.getString(R.string.daily_notif_text)) .setTicker("New Message Alert!") .setAutoCancel(true) .setContentIntent(pendingIntent) .setSmallIcon(R.mipmap.ic_launcher_no_bg) .setPriority(NotificationCompat.PRIORITY_HIGH) .setDefaults(Notification.DEFAULT_ALL); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel(channelId, this.getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT); if (notificationManager != null) { notificationManager.createNotificationChannel(channel); } } final Notification notification = builder.build(); if (notificationManager != null) { notificationManager.notify(EMA_NOTIFICATION_ID, notification); } } private void sendNotificationForPermissionSetting() { final NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); Intent notificationIntent = new Intent(MainService.this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(MainService.this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); String channelId = "YouNoOne_permission_notif"; NotificationCompat.Builder builder = new NotificationCompat.Builder(this.getApplicationContext(), channelId); builder.setContentTitle(this.getString(R.string.app_name)) .setContentText(this.getString(R.string.grant_permissions)) .setTicker("New Message Alert!") .setOngoing(true) .setContentIntent(pendingIntent) .setSmallIcon(R.mipmap.ic_launcher_no_bg) .setPriority(NotificationCompat.PRIORITY_HIGH) .setDefaults(Notification.DEFAULT_ALL); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel(channelId, this.getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH); if (notificationManager != null) { notificationManager.createNotificationChannel(channel); } } final Notification notification = builder.build(); if (notificationManager != null) { notificationManager.notify(PERMISSION_REQUEST_NOTIFICATION_ID, notification); } } @Override public void onSensorChanged(SensorEvent event) { long timestamp = System.currentTimeMillis(); if (event.sensor.getType() == Sensor.TYPE_STEP_DETECTOR) { DbMgr.saveMixedData(stepDetectorDataSrcId, timestamp, event.accuracy, timestamp); } else if (event.sensor.getType() == Sensor.TYPE_PRESSURE) { //Sampling rate is 5~6 samples per second for SENSOR_DELAY_NORMAL DbMgr.saveMixedData(pressureDataSrcId, timestamp, event.accuracy, timestamp, event.values[0]); } else if (event.sensor.getType() == Sensor.TYPE_LIGHT) { long nowTime = System.currentTimeMillis(); boolean canLightSense = (nowTime > prevLightStartTime + LIGHT_SENSOR_PERIOD * 1000); if (canLightSense) { DbMgr.saveMixedData(lightDataSrcId, timestamp, event.accuracy, timestamp, event.values[0]); prevLightStartTime = nowTime; } } } @Override public void onAccuracyChanged(Sensor sensor, int i) { } @Override public void onLocationChanged(Location location) { Log.e(TAG, "Reporting location"); long nowTime = System.currentTimeMillis(); String timeStamp = new SimpleDateFormat("yyyyMMdd_HH:mm:ss", Locale.KOREA).format(Calendar.getInstance().getTime()); String resultString = timeStamp + "," + location.getLatitude() + "," + location.getLongitude() + "\n"; try { SharedPreferences prefs = getSharedPreferences("Configurations", Context.MODE_PRIVATE); int dataSourceId = prefs.getInt("LOCATION_GPS", -1); assert dataSourceId != -1; DbMgr.saveMixedData(dataSourceId, nowTime, location.getAccuracy(), nowTime, location.getLatitude(), location.getLongitude(), location.getSpeed(), location.getAccuracy(), location.getAltitude()); FileOutputStream fileOutputStream = openFileOutput(LOCATIONS_TXT, Context.MODE_APPEND); fileOutputStream.write(resultString.getBytes()); fileOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }
package net.lshift.lee.jaxb.xml; import javax.xml.bind.annotation.XmlAttribute; public class GrandchildElement { @XmlAttribute(name = "grandchild-name") private String grandchildName; public GrandchildElement() {} public String getGrandchildName() { return grandchildName; } }
package behavioral.visitor; /** * @author Renat Kaitmazov */ public final class Phone implements Visitable { /*--------------------------------------------------------*/ /* Instance variables /*--------------------------------------------------------*/ private double price; /*--------------------------------------------------------*/ /* Constructors /*--------------------------------------------------------*/ public Phone(double price) { this.price = price; } /*--------------------------------------------------------*/ /* Getters and setters /*--------------------------------------------------------*/ public final double getPrice() { return price; } public final void setPrice(double price) { this.price = price; } /*--------------------------------------------------------*/ /* Visitable implementation /*--------------------------------------------------------*/ @Override public final void accept(Visitor visitor) { visitor.visit(this); } }
package Eventos; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import Interfce_Grafica.Menu; public class EventoAlteraResposta implements ActionListener{ private Menu menu; public EventoAlteraResposta(Menu menu){ this.menu = menu; } public void actionPerformed(ActionEvent e) { this.menu.setMenu(this.menu.getTelaAlteraResposta()); } }
package com.lxj.leaf; import java.awt.Point; import java.awt.geom.Line2D; import java.util.Vector; import javax.media.j3d.Appearance; import javax.media.j3d.LineAttributes; import javax.media.j3d.Material; import javax.media.j3d.PolygonAttributes; import javax.media.j3d.Shape3D; import javax.media.j3d.Transform3D; import javax.media.j3d.TransformGroup; import javax.vecmath.AxisAngle4d; import javax.vecmath.Point3d; import javax.vecmath.Point3f; import javax.vecmath.Vector3f; import com.sun.j3d.utils.geometry.GeometryInfo; import com.sun.j3d.utils.geometry.NormalGenerator; class BaseOfLeaf { private DataCollector dc; private static int n = 30;// 三角面片数目 private Vector<Point3d> points; public BaseOfLeaf(DataCollector dc) { this.dc = dc; points = new Vector<Point3d>(); pointToPoint3d(); } public TransformGroup getBF(Line2D topLine, Line2D bottomLine) { // 要计算的端点数目 int vCount = (n + 1) * 2; // 得到叶茎横截面圆心 float tmpx = (float) ((topLine.getX1() + topLine.getX2()) / 2); float tmpy = (float) ((topLine.getY1() + topLine.getY2()) / 2); Point3f topcenterP = new Point3f(tmpx, tmpy, 0); tmpx = (float) ((bottomLine.getX1() + bottomLine.getX2()) / 2); tmpy = (float) ((bottomLine.getY1() + bottomLine.getY2()) / 2); Point3f bottomcenterP = new Point3f(tmpx, tmpy, 0); double angle = Math.atan((topcenterP.x - bottomcenterP.x) / (topcenterP.y - bottomcenterP.y)); if (topcenterP.y < bottomcenterP.y) angle += Math.PI; float length = (float) Math.sqrt((topcenterP.x - bottomcenterP.x) * (topcenterP.x - bottomcenterP.x) + (topcenterP.y - bottomcenterP.y) * (topcenterP.y - bottomcenterP.y)); // 得到叶茎横截面半径 float topr = (float) Math.sqrt((topcenterP.x - (float) topLine.getP1() .getX()) * (topcenterP.x - (float) topLine.getP1().getX()) + (topcenterP.y - (float) topLine.getP1().getY()) * (topcenterP.y - (float) topLine.getP1().getY())); float bottomr = (float) Math.sqrt((bottomcenterP.x - (float) bottomLine .getP1().getX()) * (bottomcenterP.x - (float) bottomLine.getP1().getX()) + (bottomcenterP.y - (float) bottomLine.getP1().getY()) * (bottomcenterP.y - (float) bottomLine.getP1().getY())); Point3d[] p = new Point3d[vCount]; int count = 0; // 计算叶茎端点坐标 for (int i = 0; i <= n; ++i) { float x1 = topr * (float) Math.cos(i * 2 * Math.PI / n); float z1 = topr * (float) Math.sin(i * 2 * Math.PI / n); float x2 = bottomr * (float) Math.cos(i * 2 * Math.PI / n); float z2 = bottomr * (float) Math.sin(i * 2 * Math.PI / n); p[count++] = new Point3d(x1, length, z1); p[count++] = new Point3d(x2, 0, z2); } int[] indices = new int[vCount]; for (int i = 0; i < vCount; ++i) indices[i] = i; int[] stripCounts = { vCount }; GeometryInfo gi = new GeometryInfo(GeometryInfo.TRIANGLE_STRIP_ARRAY); gi.setCoordinates(p); gi.setCoordinateIndices(indices); gi.setStripCounts(stripCounts); NormalGenerator ng = new NormalGenerator(); ng.generateNormals(gi); Appearance ap = new Appearance(); ap.setMaterial(new Material()); PolygonAttributes polyAttrbutes = new PolygonAttributes(); polyAttrbutes.setCullFace(PolygonAttributes.CULL_NONE); // polyAttrbutes.setCullFace( PolygonAttributes.POLYGON_LINE) ; ap.setPolygonAttributes(polyAttrbutes); Shape3D shape = new Shape3D(gi.getGeometryArray(), ap); Transform3D transform = new Transform3D(); transform.setTranslation(new Vector3f(bottomcenterP.x, bottomcenterP.y, bottomcenterP.z)); transform.setRotation(new AxisAngle4d(0, 0, 1, -angle)); TransformGroup tg = new TransformGroup(transform); tg.addChild(shape); return tg; } public TransformGroup getLeaf() { Transform3D transform = new Transform3D(); transform.setScale(0.005); TransformGroup tg = new TransformGroup(transform); Vector<Integer> vCount = dc.getVCount(); Vector<Line2D> vLines = dc.getLine(); int jCount; int count = 0; for (int i = 0; i < dc.getCount(); ++i) { jCount = (int) vCount.get(i); for (int j = 0; j < jCount - 1; ++j) { Line2D l1 = vLines.get(count + j); Line2D l2 = vLines.get(count + j + 1); tg.addChild(getBF(l1, l2)); } count += jCount; } return tg; } public TransformGroup getLeafOutline() { Point3d p0 = null; Point3d p1 = null; Point3d p2 = null; Point3d p3 = null; Transform3D transform = new Transform3D(); transform.setScale(0.005); TransformGroup tg = new TransformGroup(transform); double x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4; int n = points.size(); if (n == 0) return tg; p0 = (Point3d) points.get(0); p1 = (Point3d) points.get(1); p2 = (Point3d) points.get(2); p3 = (Point3d) points.get(3); x1 = p1.x; y1 = p1.y; z1 = p1.z; x2 = (p1.x + p2.x) / 2.0f; y2 = (p1.y + p2.y) / 2.0f; z2 = (p1.z + p2.z) / 2.0f; x4 = (2.0f * p2.x + p3.x) / 3.0f; y4 = (2.0f * p2.y + p3.y) / 3.0f; z4 = (2.0f * p2.z + p3.z) / 3.0f; x3 = (x2 + x4) / 2.0f; y3 = (y2 + y4) / 2.0f; z3 = (z2 + z4) / 2.0f; BezierCurve la = new BezierCurve(p0, new Point3d(x1, y1, z1), new Point3d(x2, y2, z2), new Point3d(x3, y3, z3)); float colors[]={ 1.0f,0.0f,0.0f, 1.0f,0.0f,0.0f, 1.0f,0.0f,0.0f, 1.0f,0.0f,0.0f, 1.0f,0.0f,0.0f, 1.0f,0.0f,0.0f, 1.0f,0.0f,0.0f, 1.0f,0.0f,0.0f, 1.0f,0.0f,0.0f, 1.0f,0.0f,0.0f, 1.0f,0.0f,0.0f, 1.0f,0.0f,0.0f, 1.0f,0.0f,0.0f, 1.0f,0.0f,0.0f, 1.0f,0.0f,0.0f, 1.0f,0.0f,0.0f, 1.0f,0.0f,0.0f }; la.setColor(0, colors); LineAttributes lineattributes = new LineAttributes(); lineattributes.setLineWidth(2.0f); lineattributes.setLineAntialiasingEnable(true); lineattributes.setLinePattern(0); Appearance ap = new Appearance(); ap.setLineAttributes(lineattributes); //ap.setMaterial(new Material()); Shape3D shape = new Shape3D(la, ap); tg.addChild(shape); for (int i = 2; i < n - 4; ++i) { p0 = new Point3d(x3, y3, z3); p1 = p2; p2 = p3; p3 = (Point3d) points.get(i + 2); x1 = x4; y1 = y4; z1 = z4; x2 = (p1.x + 2.0f * p2.x) / 3.0f; y2 = (p1.y + 2.0f * p2.y) / 3.0f; z2 = (p1.z + 2.0f * p2.z) / 3.0f; x4 = (2.0f * p2.x + p3.x) / 3.0f; y4 = (2.0f * p2.y + p3.y) / 3.0f; z4 = (2.0f * p2.z + p3.z) / 3.0f; x3 = (x2 + x4) / 2.0f; y3 = (y2 + y4) / 2.0f; z3 = (z2 + z4) / 2.0f; la = new BezierCurve(p0, new Point3d(x1, y1, z1), new Point3d(x2, y2, z2), new Point3d(x3, y3, z3)); ap = new Appearance(); ap.setLineAttributes(lineattributes); //ap.setMaterial(new Material()); shape = new Shape3D(la, ap); tg.addChild(shape); } p0 = new Point3d(x3, y3, z3); p1 = p2; p2 = p3; p3 = (Point3d) points.get(n - 2); x1 = x4; y1 = y4; z1 = z4; x2 = (p1.x + 2.0f * p2.x) / 3.0f; y2 = (p1.y + 2.0f * p2.y) / 3.0f; z2 = (p1.z + 2.0f * p2.z) / 3.0f; x4 = (p2.x + p3.x) / 2.0f; y4 = (p2.y + p3.y) / 2.0f; z4 = (p2.z + p3.z) / 2.0f; x3 = (x2 + x4) / 2.0f; y3 = (y2 + y4) / 2.0f; z3 = (z2 + z4) / 2.0f; la = new BezierCurve(p0, new Point3d(x1, y1, z1), new Point3d(x2, y2, z2), new Point3d(x3, y3, z3)); ap = new Appearance(); ap.setLineAttributes(lineattributes); //ap.setMaterial(new Material()); shape = new Shape3D(la, ap); tg.addChild(shape); p0 = new Point3d(x3, y3, z3); p2 = p3; p3 = (Point3d) points.get(n - 1); x1 = x4; y1 = y4; z1 = z4; x2 = p2.x; y2 = p2.y; z2 = p2.z; x3 = p3.x; y3 = p3.y; z3 = p3.z; la = new BezierCurve(p0, new Point3d(x1, y1, z1), new Point3d(x2, y2, z2), new Point3d(x3, y3, z3)); ap = new Appearance(); ap.setLineAttributes(lineattributes); //ap.setMaterial(new Material()); shape = new Shape3D(la, ap); tg.addChild(shape); return tg; } private void pointToPoint3d() { for (Point p : dc.getPoint()) { // System.out.println(p.x + "," + p.y); points.add(new Point3d((float) p.x, (float) p.y, 0.0f)); } } }
package com.intel.realsense.librealsense; public class Pipeline extends LrsClass{ public Pipeline(){ RsContext ctx = new RsContext(); mHandle = nCreate(ctx.getHandle()); } public void start() throws Exception{ PipelineProfile rv = new PipelineProfile(nStart(mHandle)); rv.close();//TODO: enable when PipelineProfile is implemented } public void start(Config config) throws Exception { long h = nStartWithConfig(mHandle, config.getHandle()); PipelineProfile rv = new PipelineProfile(h); rv.close();//TODO: enable when PipelineProfile is implemented } public void stop() { nStop(mHandle); } public FrameSet waitForFrames() throws Exception { return waitForFrames(5000); } public FrameSet waitForFrames (int timeoutMilliseconds) throws Exception{ long frameHandle = nWaitForFrames(mHandle, timeoutMilliseconds); return new FrameSet(frameHandle); } @Override public void close(){ nDelete(mHandle); } private static native long nCreate(long context); private static native void nDelete(long handle); private static native long nStart(long handle); private static native long nStartWithConfig(long handle, long configHandle); private static native void nStop(long handle); private static native long nWaitForFrames(long handle, int timeout); }
package mx.com.otss.c3.acceso; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.Toast; import mx.com.otss.c3.R; public class PortadaaActivity extends AppCompatActivity { private Button btnacceder,btnsalir; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_portadaa); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_portada); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.flotante_portada); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { String[] TO = {"hc@otss.com.mx"}; //aquí pon tu correo String[] CC = {"asanchez@otss.com.mx"}; Intent emailIntent = new Intent(Intent.ACTION_SEND); emailIntent.setData(Uri.parse("mailto:")); emailIntent.setType("text/plain"); emailIntent.putExtra(Intent.EXTRA_EMAIL, TO); emailIntent.putExtra(Intent.EXTRA_CC, CC); // Esto podrás modificarlo si quieres, el asunto y el cuerpo del mensaje emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Apoyo con lector de leyes"); emailIntent.putExtra(Intent.EXTRA_TEXT, "Escribe aquí tu mensaje"); try { startActivity(Intent.createChooser(emailIntent, "Enviar email...")); finish(); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(getApplication(),"No tienes clientes de email instalados.", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { } } }); btnacceder=(Button)findViewById(R.id.boton_acceder); btnacceder.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intentt=new Intent(getApplication(),LoginnActivity.class); startActivity(intentt); } }); btnsalir=(Button)findViewById(R.id.boton_inicio_salir); btnsalir.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } }
package com.miyatu.tianshixiaobai.http.service; import com.miyatu.tianshixiaobai.http.api.BaseInformationApi; import com.miyatu.tianshixiaobai.http.api.ServiceApi; import java.util.Map; import retrofit2.http.FieldMap; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; import rx.Observable; public interface BaseInformationService { @FormUrlEncoded @POST(BaseInformationApi.BASE_INFORMATION) Observable<String> baseInformation(@FieldMap Map<String,Object> params); }
package it.polito.tdp.metrodeparis; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import it.polito.tdp.metrodeparis.model.*; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.TextArea; public class MetroDeParisController { Model m; List<Fermata> fermate; @FXML // ResourceBundle that was given to the FXMLLoader private ResourceBundle resources; @FXML // URL location of the FXML file that was given to the FXMLLoader private URL location; @FXML // fx:id="cmbPartenza" private ComboBox<Fermata> cmbPartenza; // Value injected by FXMLLoader @FXML // fx:id="cmbArrivo" private ComboBox<Fermata> cmbArrivo; // Value injected by FXMLLoader @FXML // fx:id="btnPercorso" private Button btnPercorso; // Value injected by FXMLLoader @FXML // fx:id="txtResult" private TextArea txtResult; // Value injected by FXMLLoader @FXML void doCalcolaPercorso(ActionEvent event) { Fermata partenza = cmbPartenza.getValue(); Fermata arrivo = cmbArrivo.getValue(); if(partenza!=null && arrivo!=null){ List<Fermata> result = m.calcolaCamminoMinimo(partenza, arrivo); txtResult.appendText("Percorso: "+ result.toString()+"\n La durata e: "+(m.getDurata()/60)); } else{ txtResult.appendText("Errore inserire una stazione di partenza e una di arrivo!"); } } public void setModel(Model m){ this.m = m; m.creaGrafo(); fermate = new ArrayList<Fermata>(m.getFermate()); cmbPartenza.getItems().addAll(fermate); cmbArrivo.getItems().addAll(fermate); } @FXML // This method is called by the FXMLLoader when initialization is complete void initialize() { assert cmbPartenza != null : "fx:id=\"cmbPartenza\" was not injected: check your FXML file 'MetroDeParis.fxml'."; assert cmbArrivo != null : "fx:id=\"cmbArrivo\" was not injected: check your FXML file 'MetroDeParis.fxml'."; assert btnPercorso != null : "fx:id=\"btnPercorso\" was not injected: check your FXML file 'MetroDeParis.fxml'."; assert txtResult != null : "fx:id=\"txtResult\" was not injected: check your FXML file 'MetroDeParis.fxml'."; } }
package com.orsegrups.splingvendas.dao; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import com.orsegrups.splingvendas.model.Cliente; import com.orsegrups.splingvendas.model.Pedido; import com.orsegrups.splingvendas.model.PedidoProduto; import com.orsegrups.splingvendas.model.Produto; import com.orsegrups.splingvendas.model.TipoUsuario; import com.orsegrups.splingvendas.model.Usuario; import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.TableUtils; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class DatabaseHelper<E> extends OrmLiteSqliteOpenHelper { private static final String databaseName = "o99 .db"; private static final int databaseVersion = 12; public DatabaseHelper(Context context) { super(context, databaseName, null, databaseVersion); } @Override public void onCreate(SQLiteDatabase sd, ConnectionSource cs) { try { TableUtils.createTable(cs, TipoUsuario.class); TableUtils.createTable(cs, Usuario.class); TableUtils.createTable(cs, Cliente.class); TableUtils.createTable(cs, Produto.class); TableUtils.createTable(cs, Pedido.class); TableUtils.createTable(cs, PedidoProduto.class); List<String> allSql = new ArrayList<String>(); allSql.add("insert into tipo_usuario ( descricao) values ( 'Admin');"); allSql.add("insert into tipo_usuario ( descricao) values ( 'Compras');"); allSql.add("insert into tipo_usuario ( descricao)values('Faturamento');"); allSql.add("insert into tipo_usuario ( descricao) values ( 'Vendedor');"); //allSql.add("insert into usuario(id, nome, email, senha, idtipousuario)values(1, 'admin', 'admin@orsegups.com.br', 'admin', 1);"); allSql.add("insert into cliente (nome, cpfcnpj, endereco) values ('Dilmo Berger', '71667717804', 'R getulio Vargas 123');"); allSql.add("insert into cliente (nome, cpfcnpj, endereco) values ('Joao Nargs', '50072113111', 'AV Morro da Fumaça');"); allSql.add("insert into cliente (nome, cpfcnpj, endereco) values ('Danilo da Silvs', '71458790932', 'R dos testes');"); allSql.add("insert into produto (descricao, valor) values ('HD 1T SSD', 1980.99);"); allSql.add("insert into produto (descricao, valor) values ('Processador Intel Core i7', 890.99);"); allSql.add("insert into produto (descricao, valor) values ('HD 1T Sata', 450.00);"); allSql.add("insert into produto (descricao, valor) values ('Memória Kingston 2G', 250.56);"); allSql.add("insert into produto (descricao, valor) values ('Fonte ATX 400W reais', 500.00);"); allSql.add("insert into produto (descricao, valor) values ('Processador Intel Core i5', 510.00);"); allSql.add("insert into produto (descricao, valor) values ('Pendrive 8G SanDisk', 20.50);"); allSql.add("insert into produto (descricao, valor) values ('Gabinete ATX PowerCOOL Extreme', 689.50);"); allSql.add("insert into produto (descricao, valor) values ('Teclado Wifi ABNT2 C/ Mouse', 80.00);"); for (String sql : allSql) { sd.execSQL(sql); } } catch(SQLException e) { e.printStackTrace(); } } @Override public void onUpgrade(SQLiteDatabase sd, ConnectionSource cs, int oldVersion, int newVersion) { try { TableUtils.dropTable(cs, TipoUsuario.class, true); TableUtils.dropTable(cs, Usuario.class, true); TableUtils.dropTable(cs, Cliente.class, true); TableUtils.dropTable(cs, Produto.class, true); TableUtils.dropTable(cs, Pedido.class, true); TableUtils.dropTable(cs, PedidoProduto.class, true); onCreate(sd, cs); } catch(SQLException e) { e.printStackTrace(); } } @Override public void close(){ super.close(); } }
package com.qst.chapter02; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; public class MainActivity extends AppCompatActivity { private MyApplication app; @Override protected void onStart() { super.onStart(); } @Override protected void onRestart() { super.onRestart(); } @Override protected void onPause() { super.onPause(); } @Override protected void onStop() { super.onStop(); } @Override protected void onDestroy() { super.onDestroy(); } @Override protected void onResume() { super.onResume(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); app = (MyApplication) getApplication(); Log.d("应用程序Name原来的值为:", app.getName()); app.setName("青岛"); Log.d("应用程序Name,修改后的值为:", app.getName()); } }
package com.myvodafone.android.model.service.fixed; import com.myvodafone.android.model.service.CommonFAQ; import java.util.ArrayList; import java.util.List; /** * Created by kakaso on 8/7/2015. */ public class FixedFAQCategory { private int orderId; private String greekName; private String englishName; private List<CommonFAQ> fixedFaqs; public FixedFAQCategory() { fixedFaqs = new ArrayList<CommonFAQ>(); } public int getOrderId() { return orderId; } public void setOrderId(int orderId) { this.orderId = orderId; } public String getGreekName() { return greekName; } public void setGreekName(String greekName) { this.greekName = greekName; } public String getEnglishName() { return englishName; } public void setEnglishName(String englishName) { this.englishName = englishName; } public List<CommonFAQ> getFixedFaqs() { return fixedFaqs; } public void setFixedFaqs(List<CommonFAQ> fixedFaqs) { this.fixedFaqs = fixedFaqs; } }
package ir.madreseplus.ui.view.practice; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import java.util.List; import ir.madreseplus.data.DataManager; import ir.madreseplus.data.model.req.Practice; import ir.madreseplus.data.model.req.Task; import ir.madreseplus.ui.base.BaseViewModel; import ir.madreseplus.utilities.rx.SchedulerProvider; public class PracticeViewModel extends BaseViewModel<PracticeActivityNavigator> { private MutableLiveData<Task> practicesLiveData; public PracticeViewModel(DataManager mDataManager, SchedulerProvider mSchedulerProvider) { super(mDataManager, mSchedulerProvider); practicesLiveData = new MutableLiveData<>(); } public LiveData<Task> getTasks() { return practicesLiveData; } public void getPracticeById(int id) { setIsLoading(true); getCompositeDisposable().add( getDataManager().getTaskById(id) .subscribeOn(getSchedulerProvider().io()) .observeOn(getSchedulerProvider().ui()) .subscribe(task -> { setIsLoading(false); practicesLiveData.postValue(task); }, throwable -> { setIsLoading(false); getNavigator().error(throwable); }) ); } public void setPracticeResult(int id, int correct, int wrong, int noAnswered) { setIsLoading(true); getCompositeDisposable().add( getDataManager().setTaskResult( id, correct, wrong, noAnswered) .subscribeOn(getSchedulerProvider().io()) .observeOn(getSchedulerProvider().ui()) .subscribe(setTaskRes -> { setIsLoading(false); getNavigator().practiceDone(); }, throwable -> { setIsLoading(false); getNavigator().error(throwable); }) ); } }
package com.news.demo.Utils; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; public class OrderCodeFactoryUtils { private static final String ORDER_CODE = "A";//置顶新闻类 private static final String RETURN_ORDER = "B";//推荐新闻类 private static final String CANCEL_ORDER = "C";//普通新闻类 /** 随即编码 */ private static final int[] r = new int[]{7, 9, 6, 2, 8 , 1, 3, 0, 5, 4}; /** 用户id和随机数总长度 */ private static final int maxLength = 14; private static String toCode(int id) { String idStr = String.valueOf(id); StringBuilder idsbs = new StringBuilder(); for (int i = idStr.length() - 1 ; i >= 0; i--) { idsbs.append(r[idStr.charAt(i)-'0']); } return idsbs.append(getRandom(maxLength - idStr.length())).toString(); } /** * 生成固定长度随机码 * @param n 长度 */ private static long getRandom(long n) { long min = 1,max = 9; for (int i = 1; i < n; i++) { min *= 10; max *= 10; } long rangeLong = (((long) (new Random().nextDouble() * (max - min)))) + min ; return rangeLong; } /** * 生成时间戳 */ private static String getDateTime(){ DateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); return sdf.format(new Date()); } /** * 得到新闻单独编号 * @param id * @return */ public static String getCommonCode(int id,String level){ String code = ""; switch (level) { case ORDER_CODE: code = ORDER_CODE + getDateTime() + toCode(id); break; case RETURN_ORDER: code = RETURN_ORDER + getDateTime() + toCode(id); break; default : code = CANCEL_ORDER + getDateTime() + toCode(id); break; } return ORDER_CODE+getDateTime()+toCode(id); } }
public class Office extends MeetingPlace { private final Manager manager; public Office(int numberOfAttendees, Manager manager) { super(numberOfAttendees); this.manager = manager; } @Override public void conductMeeting() { System.out.println("Manager's office meeting has begun."); try { Thread.sleep(150L); } catch (InterruptedException e) { } } @Override public void onLeaveRoom() { System.out.println(Thread.currentThread().getName()+" left the Manager's office."); } @Override public void onEnterRoom() { System.out.println(Thread.currentThread().getName()+" entered the Manager's office."); } }
package com.fiume.billingmechine.activity; import android.app.Activity; import android.content.DialogInterface; import android.database.Cursor; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.WindowManager; import android.widget.ListView; import android.widget.TextView; import com.fiume.billingmechine.R; import com.fiume.billingmechine.adapter.BillReportAdapter; import com.fiume.billingmechine.db.DatabaseHelper; /** * Created by Razi on 12/31/2015. */ public class BillReportActivity extends AppCompatActivity { private static Activity activity; private ListView lvItems; private BillReportAdapter billAdapter; private DatabaseHelper dbHelper; private Cursor cursorItemData; private TextView tvTotalAmnt; private TextView tvTotalQty; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.bill_report_activity); activity = this; dbHelper = new DatabaseHelper(this); cursorItemData = dbHelper.getBillHeaderData(); billAdapter = new BillReportAdapter(getApplicationContext(), cursorItemData); lvItems = (ListView) findViewById(R.id.lv_items); lvItems.setAdapter(billAdapter); tvTotalAmnt = (TextView) findViewById(R.id.tv_total); tvTotalAmnt.setText(String.valueOf(dbHelper.getTotalBIllAmnt())); tvTotalQty = (TextView) findViewById(R.id.tv_tot_qty); tvTotalQty.setText(String.valueOf(dbHelper.getTotalBIllQty())); } public void deletItem(final String id) { String Id; if (id.length() == 1) Id = "00" + id; else if (id.length() == 2) Id = "0" + id; else Id = id; final AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyAlertDialogStyle); AlertDialog dialog = builder.setMessage("Do you want to delete Bill - " + Id). setPositiveButton(" YES ", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dbHelper.deleteBillHeaderData(id); dbHelper.deleteBillDetailData(id); cursorItemData = dbHelper.getBillHeaderData(); billAdapter = new BillReportAdapter(getApplicationContext(), cursorItemData); lvItems.setAdapter(billAdapter); } }).setNegativeButton(" NO ", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).create(); dialog.getWindow().setLayout(400, 150); dialog.show(); } }
/* * Copyright © 2020-2022 ForgeRock AS (obst@forgerock.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.org.openbanking.datamodel.account; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import uk.org.openbanking.datamodel.common.OBBranchAndFinancialInstitutionIdentification2; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import java.util.Objects; /** * Account */ @ApiModel(description = "Account") @javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen") public class OBAccount1 { @JsonProperty("AccountId") private String accountId = null; @JsonProperty("Currency") private String currency = null; @JsonProperty("Nickname") private String nickname = null; @JsonProperty("Account") private OBCashAccount1 account = null; @JsonProperty("Servicer") private OBBranchAndFinancialInstitutionIdentification2 servicer = null; public OBAccount1 accountId(String accountId) { this.accountId = accountId; return this; } /** * A unique and immutable identifier used to identify the account resource. This identifier has no meaning to the account owner. * * @return accountId **/ @ApiModelProperty(required = true, value = "A unique and immutable identifier used to identify the account resource. This identifier has no meaning to the account owner.") @NotNull @Size(min = 1, max = 40) public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } public OBAccount1 currency(String currency) { this.currency = currency; return this; } /** * Identification of the currency in which the account is held. Usage: Currency should only be used in case one and the same account number covers several currencies and the initiating party needs to identify which currency needs to be used for settlement on the account. * * @return currency **/ @ApiModelProperty(required = true, value = "Identification of the currency in which the account is held. Usage: Currency should only be used in case one and the same account number covers several currencies and the initiating party needs to identify which currency needs to be used for settlement on the account.") @NotNull @Pattern(regexp = "^[A-Z]{3,3}$") public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } public OBAccount1 nickname(String nickname) { this.nickname = nickname; return this; } /** * The nickname of the account, assigned by the account owner in order to provide an additional means of identification of the account. * * @return nickname **/ @ApiModelProperty(value = "The nickname of the account, assigned by the account owner in order to provide an additional means of identification of the account.") @Size(min = 1, max = 70) public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public OBAccount1 account(OBCashAccount1 account) { this.account = account; return this; } /** * Get account * * @return account **/ @ApiModelProperty(value = "") @Valid public OBCashAccount1 getAccount() { return account; } public void setAccount(OBCashAccount1 account) { this.account = account; } public OBAccount1 servicer(OBBranchAndFinancialInstitutionIdentification2 servicer) { this.servicer = servicer; return this; } /** * Get servicer * * @return servicer **/ @ApiModelProperty(value = "") @Valid public OBBranchAndFinancialInstitutionIdentification2 getServicer() { return servicer; } public void setServicer(OBBranchAndFinancialInstitutionIdentification2 servicer) { this.servicer = servicer; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OBAccount1 account = (OBAccount1) o; return Objects.equals(this.accountId, account.accountId) && Objects.equals(this.currency, account.currency) && Objects.equals(this.nickname, account.nickname) && Objects.equals(this.account, account.account) && Objects.equals(this.servicer, account.servicer); } @Override public int hashCode() { return Objects.hash(accountId, currency, nickname, account, servicer); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Account {\n"); sb.append(" accountId: ").append(toIndentedString(accountId)).append("\n"); sb.append(" currency: ").append(toIndentedString(currency)).append("\n"); sb.append(" nickname: ").append(toIndentedString(nickname)).append("\n"); sb.append(" account: ").append(toIndentedString(account)).append("\n"); sb.append(" servicer: ").append(toIndentedString(servicer)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
package org.vincent.taskexecutor; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; /** * @author PengRong * @package org.vincent.taskexecutor * @ClassName MainTaskExecutor.java * @date 2019/6/16 - 17:50 * @ProjectName JavaAopLearning * @Description: Spring 异步任务测试类 */ public class MainTaskExecutor { public static void main(String[] args) throws ExecutionException, InterruptedException { AnnotationConfigApplicationContext configApplicationContext =new AnnotationConfigApplicationContext(TaskExecutorConfig.class); AsyncTaskExecutorService asyncTaskExecutorService = configApplicationContext.getBean(AsyncTaskExecutorService.class); AsyncTaskExecutorService2 asyncTaskExecutorService2 = configApplicationContext.getBean(AsyncTaskExecutorService2.class); for (int i=0;i<=20;i++){ asyncTaskExecutorService.execute(i); asyncTaskExecutorService2.execute(i); } /** 提交一个异步任务并获取异步任务执行结果 * */ Future<String> execute = asyncTaskExecutorService2.execute(500); while (!execute.isDone()){ } System.out.println(execute.get().toString()); configApplicationContext.close(); } }
package com.esum.web.ims.ebms.vo; public class EbmsInfo { // primary key private String interfaceId; // fields private String inboundCpaId; private String inboundFromPartyId; private String inboundService; private String inboundAction; private String outboundAuthInfoId; private String outboundCpaId; private String outboundFromPartyId; private String outboundFromPartyType; private String outboundFromRole; private String outboundToPartyId; private String outboundToPartyType; private String outboundToRole; private String outboundService; private String outboundServiceType; private String outboundAction; private String outboundDescription; private String useXmlEnc; private String xmlEncInfoId; private String parsingRule; private String regDate; // "yyyyMMddHHmmss" private String modDate; // "yyyyMMddHHmmss" public String getInterfaceId() { return interfaceId; } public void setInterfaceId(String interfaceId) { this.interfaceId = interfaceId; } public String getInboundCpaId() { return inboundCpaId; } public void setInboundCpaId(String inboundCpaId) { this.inboundCpaId = inboundCpaId; } public String getInboundFromPartyId() { return inboundFromPartyId; } public void setInboundFromPartyId(String inboundFromPartyId) { this.inboundFromPartyId = inboundFromPartyId; } public String getInboundService() { return inboundService; } public void setInboundService(String inboundService) { this.inboundService = inboundService; } public String getInboundAction() { return inboundAction; } public void setInboundAction(String inboundAction) { this.inboundAction = inboundAction; } public String getOutboundAuthInfoId() { return outboundAuthInfoId; } public void setOutboundAuthInfoId(String outboundAuthInfoId) { this.outboundAuthInfoId = outboundAuthInfoId; } public String getOutboundCpaId() { return outboundCpaId; } public void setOutboundCpaId(String outboundCpaId) { this.outboundCpaId = outboundCpaId; } public String getOutboundFromPartyId() { return outboundFromPartyId; } public void setOutboundFromPartyId(String outboundFromPartyId) { this.outboundFromPartyId = outboundFromPartyId; } public String getOutboundFromPartyType() { return outboundFromPartyType; } public void setOutboundFromPartyType(String outboundFromPartyType) { this.outboundFromPartyType = outboundFromPartyType; } public String getOutboundFromRole() { return outboundFromRole; } public void setOutboundFromRole(String outboundFromRole) { this.outboundFromRole = outboundFromRole; } public String getOutboundToPartyId() { return outboundToPartyId; } public void setOutboundToPartyId(String outboundToPartyId) { this.outboundToPartyId = outboundToPartyId; } public String getOutboundToPartyType() { return outboundToPartyType; } public void setOutboundToPartyType(String outboundToPartyType) { this.outboundToPartyType = outboundToPartyType; } public String getOutboundToRole() { return outboundToRole; } public void setOutboundToRole(String outboundToRole) { this.outboundToRole = outboundToRole; } public String getOutboundService() { return outboundService; } public void setOutboundService(String outboundService) { this.outboundService = outboundService; } public String getOutboundServiceType() { return outboundServiceType; } public void setOutboundServiceType(String outboundServiceType) { this.outboundServiceType = outboundServiceType; } public String getOutboundAction() { return outboundAction; } public void setOutboundAction(String outboundAction) { this.outboundAction = outboundAction; } public String getOutboundDescription() { return outboundDescription; } public void setOutboundDescription(String outboundDescription) { this.outboundDescription = outboundDescription; } public String getUseXmlEnc() { return useXmlEnc; } public void setUseXmlEnc(String useXmlEnc) { this.useXmlEnc = useXmlEnc; } public String getXmlEncInfoId() { return xmlEncInfoId; } public void setXmlEncInfoId(String xmlEncInfoId) { this.xmlEncInfoId = xmlEncInfoId; } public String getParsingRule() { return parsingRule; } public void setParsingRule(String parsingRule) { this.parsingRule = parsingRule; } public String getRegDate() { return regDate; } public void setRegDate(String regDate) { this.regDate = regDate; } public String getModDate() { return modDate; } public void setModDate(String modDate) { this.modDate = modDate; } }
package com.revolut.moneytransfer.dao.impl; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.commons.dbutils.DbUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.revolut.moneytransfer.dao.TransactionDao; import com.revolut.moneytransfer.entity.Transaction; import com.revolut.moneytransfer.exception.TechnicalException; import com.revolut.moneytransfer.factory.ConnectionFactory; public class TransactionDaoImpl implements TransactionDao { private static Logger logger = LoggerFactory.getLogger(TransactionDaoImpl.class); private final String SQL_INSERT_TRANSACTION = "INSERT INTO transaction (start_date,end_date,amount,sender_account,receiver_account,sender_currency_code,receiver_currency_code,statu,is_reverse,transaction_token) VALUES (?,?,?,?,?,?,?,?,?,?)"; private final String SQL_GET_TRANSACTION_BY_SENDER_ACCOUNT = "SELECT * FROM transaction WHERE sender_account = ? "; private final String SQL_GET_ALL_TRANSACTION = "SELECT * FROM transaction"; private final String SQL_GET_TRANSACTION_BY_RECEIVER_ACCOUNT = "SELECT * FROM transaction WHERE receiver_account = ? "; private final String SQL_GET_NOT_COMPLETED_TRANSACTION = "SELECT * FROM transaction WHERE statu ='W' or statu = 'T'"; private final String SQL_UPDATE_TRANSACTION = "UPDATE transaction SET end_date = ?, statu = ? , is_reverse = ? WHERE transaction_token = ? "; private final String SQL_IS_TOKEN_USED_BEFORE = "SELECT * FROM transaction where transaction_token= ? "; private final String SQL_GET_TRANSACTION_WITH_TOKEN_ = "SELECT * FROM transaction WHERE transaction_token = ? "; @Override public int insertTransaction(Transaction transaction) { Connection conn = null; PreparedStatement preStmt = null; try { conn = ConnectionFactory.getDBConnection(); preStmt = conn.prepareStatement(SQL_INSERT_TRANSACTION); preStmt.setDate(1, new Date(transaction.getStartDate().getTime())); preStmt.setDate(2, new Date(transaction.getStartDate().getTime())); preStmt.setBigDecimal(3, transaction.getAmount()); preStmt.setLong(4, transaction.getSenderAccount()); preStmt.setLong(5, transaction.getReceiverAccount()); preStmt.setString(6, transaction.getSenderCurrencyCode()); preStmt.setString(7, transaction.getReceiverCurrencyCode()); preStmt.setString(8, transaction.getStatu()); preStmt.setInt(9, transaction.getIsReverse()); preStmt.setString(10, transaction.getTransactionToken()); int isCreated = preStmt.executeUpdate(); conn.commit(); if (isCreated == 0) { logger.error("Error in insertTransaction dao , transaction is not created"); throw new TechnicalException("Error in insertTransaction dao , transaction is not created"); } return isCreated; } catch (SQLException e) { logger.error("Error in insertTransaction dao", e); throw new TechnicalException("Error in insertTransaction dao ", e); } finally { DbUtils.closeQuietly(conn); DbUtils.closeQuietly(preStmt); } } @Override public List<Transaction> getTransactionBySenderAccount(long senderAccount) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; List<Transaction> transactions = new ArrayList<Transaction>(); try { conn = ConnectionFactory.getDBConnection(); stmt = conn.prepareStatement(SQL_GET_TRANSACTION_BY_SENDER_ACCOUNT); stmt.setLong(1, senderAccount); rs = stmt.executeQuery(); while (rs.next()) { Transaction transaction = new Transaction(rs.getLong("transaction_no"), rs.getLong("sender_account"), rs.getLong("receiver_account"), rs.getDate("start_date"), rs.getDate("end_date"), rs.getBigDecimal("amount"), rs.getString("sender_currency_code"), rs.getString("receiver_currency_code"), rs.getString("statu"), rs.getInt("is_reverse"), rs.getString("transaction_token")); transactions.add(transaction); } if (logger.isDebugEnabled()) { logger.debug("Transaction lists : " + transactions); } } catch (SQLException e) { logger.error("Error in getTransactionBySenderAccount dao", e); throw new TechnicalException("Error in getTransactionBySenderAccount dao ", e); } finally { DbUtils.closeQuietly(conn, stmt, rs); } return transactions; } @Override public List<Transaction> getAllTransaction() { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; List<Transaction> transactions = new ArrayList<Transaction>(); try { conn = ConnectionFactory.getDBConnection(); stmt = conn.prepareStatement(SQL_GET_ALL_TRANSACTION); rs = stmt.executeQuery(); while (rs.next()) { Transaction transaction = new Transaction(rs.getLong("transaction_no"), rs.getLong("sender_account"), rs.getLong("receiver_account"), rs.getDate("start_date"), rs.getDate("end_date"), rs.getBigDecimal("amount"), rs.getString("sender_currency_code"), rs.getString("receiver_currency_code"), rs.getString("statu"), rs.getInt("is_reverse"), rs.getString("transaction_token")); transactions.add(transaction); } if (logger.isDebugEnabled()) { logger.debug("Transaction lists : " + transactions); } } catch (SQLException e) { logger.error("Error in getAllTransaction dao", e); throw new TechnicalException("Error in getAllTransaction dao ", e); } finally { DbUtils.closeQuietly(conn, stmt, rs); } return transactions; } @Override public List<Transaction> getTransactionByReceiverAccount(long receiverAccount) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; List<Transaction> transactions = new ArrayList<Transaction>(); try { conn = ConnectionFactory.getDBConnection(); stmt = conn.prepareStatement(SQL_GET_TRANSACTION_BY_RECEIVER_ACCOUNT); stmt.setLong(1, receiverAccount); rs = stmt.executeQuery(); while (rs.next()) { Transaction transaction = new Transaction(rs.getLong("transaction_no"), rs.getLong("sender_account"), rs.getLong("receiver_account"), rs.getDate("start_date"), rs.getDate("end_date"), rs.getBigDecimal("amount"), rs.getString("sender_currency_code"), rs.getString("receiver_currency_code"), rs.getString("statu"), rs.getInt("is_reverse"), rs.getString("transaction_token")); transactions.add(transaction); } if (logger.isDebugEnabled()) { logger.debug("Transaction lists : " + transactions); } } catch (SQLException e) { logger.error("Error in getTransactionByReceiverAccount dao", e); throw new TechnicalException("Error in getTransactionByReceiverAccount dao ", e); } finally { DbUtils.closeQuietly(conn, stmt, rs); } return transactions; } @Override public List<Transaction> getNotCompletedTransaction() { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; List<Transaction> transactions = new ArrayList<Transaction>(); try { conn = ConnectionFactory.getDBConnection(); stmt = conn.prepareStatement(SQL_GET_NOT_COMPLETED_TRANSACTION); rs = stmt.executeQuery(); while (rs.next()) { Transaction transaction = new Transaction(rs.getLong("transaction_no"), rs.getLong("sender_account"), rs.getLong("receiver_account"), rs.getDate("start_date"), rs.getDate("end_date"), rs.getBigDecimal("amount"), rs.getString("sender_currency_code"), rs.getString("receiver_currency_code"), rs.getString("statu"), rs.getInt("is_reverse"), rs.getString("transaction_token")); transactions.add(transaction); } if (logger.isDebugEnabled()) { logger.debug("Transaction lists : " + transactions); } } catch (SQLException e) { logger.error("Error in getNotCompletedTransaction dao", e); throw new TechnicalException("Error in getNotCompletedTransaction dao ", e); } finally { DbUtils.closeQuietly(conn, stmt, rs); } return transactions; } @Override public int updateTransaction(Transaction transaction) { Connection conn = null; PreparedStatement preStmt = null; try { conn = ConnectionFactory.getDBConnection(); conn.setAutoCommit(false); preStmt = conn.prepareStatement(SQL_UPDATE_TRANSACTION); preStmt.setDate(1, new Date(transaction.getEndDate().getTime())); preStmt.setString(2, transaction.getStatu()); preStmt.setInt(3, transaction.getIsReverse()); preStmt.setString(4, transaction.getTransactionToken()); int isUpdated = preStmt.executeUpdate(); if (isUpdated == 0) { logger.error("Error in updateTransaction dao , transaction has not been updated"); throw new TechnicalException("Error in updateTransaction dao , transaction has not been updated"); } conn.commit(); return isUpdated; } catch (SQLException e) { logger.error("Error in updateTransaction dao", e); throw new TechnicalException("Error in updateTransaction dao ", e); } finally { DbUtils.closeQuietly(conn); DbUtils.closeQuietly(preStmt); } } @Override public List<Transaction> isTokenUsedBefore(String token) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; List<Transaction> transactions = new ArrayList<Transaction>(); try { conn = ConnectionFactory.getDBConnection(); stmt = conn.prepareStatement(SQL_IS_TOKEN_USED_BEFORE); stmt.setString(1, token); rs = stmt.executeQuery(); while (rs.next()) { Transaction transaction = new Transaction(rs.getLong("transaction_no"), rs.getLong("sender_account"), rs.getLong("receiver_account"), rs.getDate("start_date"), rs.getDate("end_date"), rs.getBigDecimal("amount"), rs.getString("sender_currency_code"), rs.getString("receiver_currency_code"), rs.getString("statu"), rs.getInt("is_reverse"), rs.getString("transaction_token")); transactions.add(transaction); } if (logger.isDebugEnabled()) { logger.debug("Transaction lists : " + transactions); } } catch (SQLException e) { logger.error("Error in isTokenUsedBefore dao", e); throw new TechnicalException("Error in isTokenUsedBefore dao ", e); } finally { DbUtils.closeQuietly(conn, stmt, rs); } return transactions; } @Override public Transaction getTransactionWithToken(String token) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; Transaction transaction = null; try { conn = ConnectionFactory.getDBConnection(); stmt = conn.prepareStatement(SQL_GET_TRANSACTION_WITH_TOKEN_); stmt.setString(1, token); rs = stmt.executeQuery(); while (rs.next()) { transaction = new Transaction(rs.getLong("transaction_no"), rs.getLong("sender_account"), rs.getLong("receiver_account"), rs.getDate("start_date"), rs.getDate("end_date"), rs.getBigDecimal("amount"), rs.getString("sender_currency_code"), rs.getString("receiver_currency_code"), rs.getString("statu"), rs.getInt("is_reverse"), rs.getString("transaction_token")); } if (logger.isDebugEnabled()) { logger.debug("Transaction lists : " + transaction); } } catch (SQLException e) { logger.error("Error in getTransactionWithToken dao", e); throw new TechnicalException("Error in getTransactionWithToken dao ", e); } finally { DbUtils.closeQuietly(conn, stmt, rs); } return transaction; } }
package ChessGame; /** * The NullSpot class extends the ChessPiece class. * * Created by Brandon on 11/29/2016. */ public class NullSpot extends ChessPiece { /** * constructor: Null Spot "piece" * * @param name * @param c * @param pic */ public NullSpot(String name, int c, String pic) { super(name, c, pic); } public boolean isValid(Board board, int fromX, int fromY, int toX, int toY){return false;} }
public class FibonacciSeries { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int n1=1; int n2 =1; int n3; // int temp = 1; // System.out.print(n1 + " "); // System.out.print(n2 + " "); // for(int i = 1; i <15-2; i++){ // n2 = temp+n2; // System.out.print(n2 + " "); // temp = n1; // n1 = n2; // // } System.out.print(n1 + " "); System.out.print(n2 + " "); for(int i = 1; i <15-2; i++){ n3 = n1+n2; n1=n2; n2=n3; System.out.print(n3 + " "); } } }
import java.io.*; import java.util.Scanner; public class GridAreaCounter { public static void read(String fileName, char[][] grid) { int i = 0; try { Scanner read = new Scanner(new File(fileName)); do { String line = read.nextLine(); for (int j = 0; j < 8; j++) { grid[i + 1][j + 1] = line.charAt(j); } i++; } while (read.hasNext()); read.close(); } catch (FileNotFoundException fnf) { System.out.println("File was not found"); } } public static void printGrid(char[][] grid) { for (int i = 1; i < grid.length - 1; i++) { for (int j = 1; j < grid[0].length - 1; j++) { System.out.print(grid[i][j]); } System.out.println(); } } public static void fillGrid(char[][] grid) { for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { grid[i][j] = '#'; } } } public static int countArea(char[][] grid, int x, int y, int count) { if (grid[x][y] != 'o') { return count; } grid[x][y] = '-'; return countArea(grid, x + 1, y, count) + countArea(grid, x - 1, y, count) + countArea(grid, x, y + 1, count) + countArea(grid, x, y - 1, count) + 1; } public static void checkGrid(char[][]grid) { int area = 1; for (int i = 1; i < grid.length - 1; i++) { for (int j = 1; j < grid[0].length - 1; j++) { if (grid[i][j] == 'o') { System.out.println("Area " + area + " = " + countArea(grid, i, j, 0)); area++; } } } } public static void main(String[] args) { char[][] grid = new char[10][10]; fillGrid(grid); read("grid1.txt", grid); printGrid(grid); checkGrid(grid); printGrid(grid); } }
package com.camila.web.dominio.models; public enum StatusVenda { ANDAMENTO,CANCELADA,CONCLUIDA }
/* * How to transfer a method as argument * * */ package TransferAMethod; /** * * @author YNZ */ interface Perform { public void driving(); } class Sporter implements Perform { @Override public void driving() { System.out.println("Im an engineer driving on the track!"); } } class Engineer implements Perform{ @Override public void driving() { System.out.println("Im an engineer driving on the track!"); } } class Coach { public void doCoaching(Perform perform) { perform.driving(); } } public class TransferAMethodAsArgument { public static void main(String[] args) { Coach c = new Coach(); c.doCoaching(new Sporter()); c.doCoaching(new Engineer()); } }
package com.nps.hellow; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.PagerTitleStrip; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class Accueil extends Fragment { public static final String TAG = Accueil.class.getSimpleName(); private ItemOnePagerAdapter mPagerAdapter; private ViewPager mViewPager; public static Accueil newInstance() { return new Accueil(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(com.nps.hellow.R.layout.activity_accueil, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); PagerTitleStrip tabs = (PagerTitleStrip) view.findViewById(com.nps.hellow.R.id.pager_title_strip); ViewPager pager = (ViewPager) view.findViewById(com.nps.hellow.R.id.pager); pager.setAdapter(mPagerAdapter); } public class ItemOnePagerAdapter extends FragmentPagerAdapter { private final String[] TAB_TITLES = { "Today", "This Week", "This Month" }; public ItemOnePagerAdapter(FragmentManager fm) { super(fm); } @Override public CharSequence getPageTitle(int position) { return TAB_TITLES[position]; } @Override public Fragment getItem(int position) { return AccueilContentFragment.newInstance(position); } @Override public int getCount() { return 4; } } }
// Definitions for sprite sheet menu.png // Created with TexturePacker www.codeandweb.com/texturepacker // $TexturePacker:SmartUpdate:44b697823d8a7f1f9ccc00bc8feff79e:1/1$ package com.karachevtsevuu.mayaghosts; public interface tp_menu { public static final int MENU_QUIT_ID = 0; public static final int MENU_RESET_ID = 1; }
package com.admin.flink.day09; import com.admin.flink.bean.WaterSensor; import org.apache.flink.api.common.functions.MapFunction; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.streaming.api.datastream.DataStreamSource; import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.table.api.Table; import org.apache.flink.table.api.bridge.java.StreamTableEnvironment; import org.apache.flink.table.functions.TableAggregateFunction; import org.apache.flink.util.Collector; import static org.apache.flink.table.api.Expressions.$; import static org.apache.flink.table.api.Expressions.call; public class Flink09_UDF_TableAggFun { public static void main(String[] args) { //1.获取流的执行环境 StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setParallelism(1); DataStreamSource<String> streamSource = env.socketTextStream("hadoop102", 9999); //将数据转为JavaBean SingleOutputStreamOperator<WaterSensor> waterSensorStream = streamSource.map(new MapFunction<String, WaterSensor>() { @Override public WaterSensor map(String value) throws Exception { String[] split = value.split(","); return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2])); } }); //2.获取表的执行环境 StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env); //3.将流转为动态表 Table table = tableEnv.fromDataStream(waterSensorStream); //TODO 4.不注册函数直接使用 TableAPI // table // .groupBy($("id")) // .flatAggregate(call(MyTop2Fun.class,$("vc")).as("value","top")) // .select($("id"),$("value"),$("top")).execute().print(); // table // .groupBy($("id")) // .flatAggregate(call(MyTop2Fun.class,$("vc"))) // .select($("id"),$("f0"),$("f1")).execute().print(); // table // .groupBy($("id")) // .flatAggregate(call(MyTop2Fun.class, $("vc")).as("value", "top")) // .select($("id"),$("value"),$("top")).execute().print(); //TODO 4.先注册再使用 TableAPI tableEnv.createTemporaryFunction("top2",MyTop2Fun.class); table .groupBy($("id")) .flatAggregate(call("top2", $("vc")).as("value", "top")) .select($("id"), $("value"), $("top")).execute().print(); } //自定义一个累加器 public static class MyTop2Accumulat { public Integer first; public Integer second; } //自定义表函数,求Top2 public static class MyTop2Fun extends TableAggregateFunction<Tuple2<Integer, String>, MyTop2Accumulat> { @Override public MyTop2Accumulat createAccumulator() { MyTop2Accumulat myTop2Accumulat = new MyTop2Accumulat(); myTop2Accumulat.first = Integer.MIN_VALUE; myTop2Accumulat.second = Integer.MIN_VALUE; return myTop2Accumulat; } public void accumulate(MyTop2Accumulat acc, Integer value) { if (value > acc.first) { acc.second = acc.first; acc.first = value; } else if (value > acc.second) { acc.second = value; } } public void emitValue(MyTop2Accumulat acc, Collector<Tuple2<Integer,String>> out){ // emit the value and rank if (acc.first != Integer.MIN_VALUE) { out.collect(Tuple2.of(acc.first, "1")); } if (acc.second != Integer.MIN_VALUE) { out.collect(Tuple2.of(acc.second, "2")); } } } }
package com.cs.administration.bonus; import javax.annotation.Nonnull; import javax.validation.Valid; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.math.BigDecimal; import static javax.xml.bind.annotation.XmlAccessType.FIELD; /** * @author Hadi Movaghar */ @XmlRootElement @XmlAccessorType(FIELD) public class UpdatePlayerBonusDto { @XmlElement @Nonnull @Valid private BigDecimal amount; public UpdatePlayerBonusDto() { } @Nonnull public BigDecimal getAmount() { return amount; } }
package view; import app.Principal; import entidades.Fornecedor; import entidades.Periodo; import entidades.Produto; import entidades.Promocao; import java.util.List; import javax.persistence.EntityManager; import javax.swing.table.AbstractTableModel; public class FrmListaPromocao extends AbstractTableModel { private String colunas[] = {"Produto","Fornecedor","Periodo","Valor"}; private Class classeColunas[] = {Produto.class, Fornecedor.class, Periodo.class, Double.class}; private List<Promocao> lista; private EntityManager em; public FrmListaPromocao() { lista = Principal.emf.createEntityManager().createQuery("from " + Promocao.class.getSimpleName()).getResultList(); } public List<Promocao> getLista() { return lista; } public int getRowCount() { return lista.size(); } public int getColumnCount() { return 4; } public Object getValueAt(int rowIndex, int columnIndex) { Promocao pro = lista.get(rowIndex); switch (columnIndex) { case 0: return pro.getProduto(); case 1: return pro.getProduto().getFornecedor(); case 2: return pro.getPeriodo(); case 3: return pro.getValor(); } return null; } @Override public Class<?> getColumnClass(int columnIndex) { return classeColunas[columnIndex]; } @Override public String getColumnName(int column) { return colunas[column]; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } }
/* * Copyright 2017 Goldman Sachs. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.gs.tablasco; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import java.io.IOException; public class HtmlFormattingTest { @Rule public final TableVerifier tableVerifier = new TableVerifier() .withFilePerMethod() .withMavenDirectoryStrategy(); @Test public void nonNumericBreak() throws IOException { final VerifiableTable table1 = TableTestUtils.createTable(2, "Col 1", "Col 2", "A1", "A2", "B1", "B2"); final VerifiableTable table2 = TableTestUtils.createTable(2, "Col 1", "Col 2", "A1", "A9", "B1", "B9"); TableTestUtils.assertAssertionError(() -> tableVerifier.verify("name", table1, table2)); Assert.assertEquals( "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"pass\">Col 1</th>\n" + "<th class=\"pass\">Col 2</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"pass\">A1</td>\n" + "<td class=\"fail\">A2<p>Expected</p>\n" + "<hr/>A9<p>Actual</p>\n" + "</td>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"pass\">B1</td>\n" + "<td class=\"fail\">B2<p>Expected</p>\n" + "<hr/>B9<p>Actual</p>\n" + "</td>\n" + "</tr>\n" + "</table>", TableTestUtils.getHtml(this.tableVerifier, "table")); } @Test public void numericBreak() throws IOException { final VerifiableTable table1 = TableTestUtils.createTable(2, "Col 1", "Col 2", "A", 10.123); final VerifiableTable table2 = TableTestUtils.createTable(2, "Col 1", "Col 2", "A", 20.456); TableTestUtils.assertAssertionError(() -> tableVerifier.withTolerance(0.01d).verify("name", table1, table2)); Assert.assertEquals( "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"pass\">Col 1</th>\n" + "<th class=\"pass\">Col 2</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"pass\">A</td>\n" + "<td class=\"fail number\">10.12<p>Expected</p>\n" + "<hr/>20.46<p>Actual</p>\n" + "<hr/>-10.33 / 102.07%<p>Difference / Variance</p>\n" + "</td>\n" + "</tr>\n" + "</table>", TableTestUtils.getHtml(this.tableVerifier, "table")); } @Test public void nonNumericActualNumericExpectedBreak() throws IOException { final VerifiableTable table1 = TableTestUtils.createTable(2, "Col 1", "Col 2", "A", 390.0); final VerifiableTable table2 = TableTestUtils.createTable(2, "Col 1", "Col 2", "A", "A2"); TableTestUtils.assertAssertionError(() -> tableVerifier.withVarianceThreshold(5.0d).verify("name", table1, table2)); Assert.assertEquals( "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"pass\">Col 1</th>\n" + "<th class=\"pass\">Col 2</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"pass\">A</td>\n" + "<td class=\"fail\">390<p>Expected</p>\n" + "<hr/>A2<p>Actual</p>\n" + "</td>\n" + "</tr>\n" + "</table>", TableTestUtils.getHtml(this.tableVerifier, "table")); } @Test public void numericActualNonNumericExpectedBreak() throws IOException { final VerifiableTable table1 = TableTestUtils.createTable(2, "Col 1", "Col 2", "A", "A1"); final VerifiableTable table2 = TableTestUtils.createTable(2, "Col 1", "Col 2", "A", 48.0); TableTestUtils.assertAssertionError(() -> tableVerifier.withTolerance(0.1d).verify("name", table1, table2)); Assert.assertEquals( "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"pass\">Col 1</th>\n" + "<th class=\"pass\">Col 2</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"pass\">A</td>\n" + "<td class=\"fail\">A1<p>Expected</p>\n" + "<hr/>48<p>Actual</p>\n" + "</td>\n" + "</tr>\n" + "</table>", TableTestUtils.getHtml(this.tableVerifier, "table")); } @Test public void outOfOrderColumnPassedCellNonNumeric() throws IOException { final VerifiableTable table1 = TableTestUtils.createTable(2, "Col 1", "Col 2", "A1", "A2"); final VerifiableTable table2 = TableTestUtils.createTable(2, "Col 2", "Col 1", "A2", "A1"); TableTestUtils.assertAssertionError(() -> tableVerifier.verify("name", table1, table2)); Assert.assertEquals( "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"outoforder\">Col 2<p>Out of order</p>\n" + "</th>\n" + "<th class=\"pass\">Col 1</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"outoforder\">A2<p>Out of order</p>\n" + "</td>\n" + "<td class=\"pass\">A1</td>\n" + "</tr>\n" + "</table>", TableTestUtils.getHtml(this.tableVerifier, "table")); } @Test public void outOfOrderColumnFailedCellNonNumeric() throws IOException { final VerifiableTable table1 = TableTestUtils.createTable(2, "Col 1", "Col 2", "A1", "A2"); final VerifiableTable table2 = TableTestUtils.createTable(2, "Col 2", "Col 1", "A3", "A1"); TableTestUtils.assertAssertionError(() -> tableVerifier.verify("name", table1, table2)); Assert.assertEquals( "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"outoforder\">Col 2<p>Out of order</p>\n" + "</th>\n" + "<th class=\"pass\">Col 1</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"fail\">A2<p>Expected</p>\n" + "<hr/>A3<p>Actual</p>\n" + "</td>\n" + "<td class=\"pass\">A1</td>\n" + "</tr>\n" + "</table>", TableTestUtils.getHtml(this.tableVerifier, "table")); } @Test public void outOfOrderColumnPassedCellNumeric() throws IOException { final VerifiableTable table1 = TableTestUtils.createTable(2, "Col 1", "Col 2", 30.78, 25); final VerifiableTable table2 = TableTestUtils.createTable(2, "Col 2", "Col 1", 25, 30.78); TableTestUtils.assertAssertionError(() -> tableVerifier.withTolerance(0.01d).verify("name", table1, table2)); Assert.assertEquals( "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"outoforder\">Col 2<p>Out of order</p>\n" + "</th>\n" + "<th class=\"pass\">Col 1</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"outoforder number\">25<p>Out of order</p>\n" + "</td>\n" + "<td class=\"pass number\">30.78</td>\n" + "</tr>\n" + "</table>", TableTestUtils.getHtml(this.tableVerifier, "table")); } @Test public void outOfOrderColumnFailedCellNumeric() throws IOException { final VerifiableTable table1 = TableTestUtils.createTable(2, "Col 1", "Col 2", 30.78, 25); final VerifiableTable table2 = TableTestUtils.createTable(2, "Col 2", "Col 1", 25.3, 30.78); TableTestUtils.assertAssertionError(() -> tableVerifier.withTolerance(0.01d).verify("name", table1, table2)); Assert.assertEquals( "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"outoforder\">Col 2<p>Out of order</p>\n" + "</th>\n" + "<th class=\"pass\">Col 1</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"fail number\">25<p>Expected</p>\n" + "<hr/>25.3<p>Actual</p>\n" + "<hr/>-0.3 / 1.2%<p>Difference / Variance</p>\n" + "</td>\n" + "<td class=\"pass number\">30.78</td>\n" + "</tr>\n" + "</table>", TableTestUtils.getHtml(this.tableVerifier, "table")); } @Test public void missingSurplusColumnsNonNumeric() throws IOException { final VerifiableTable table1 = TableTestUtils.createTable(2, "Col 1", "Col 2", "A1", "A2"); final VerifiableTable table2 = TableTestUtils.createTable(2, "Col 4", "Col 1", "A2", "A1"); TableTestUtils.assertAssertionError(() -> tableVerifier.verify("name", table1, table2)); Assert.assertEquals( "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"surplus\">Col 4<p>Surplus</p>\n" + "</th>\n" + "<th class=\"pass\">Col 1</th>\n" + "<th class=\"missing\">Col 2<p>Missing</p>\n" + "</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"surplus\">A2<p>Surplus</p>\n" + "</td>\n" + "<td class=\"pass\">A1</td>\n" + "<td class=\"missing\">A2<p>Missing</p>\n" + "</td>\n" + "</tr>\n" + "</table>", TableTestUtils.getHtml(this.tableVerifier, "table")); } @Test public void missingSurplusColumnsNumeric() throws IOException { final VerifiableTable table1 = TableTestUtils.createTable(2, "Col 1", "Col 2", 30.78, 25); final VerifiableTable table2 = TableTestUtils.createTable(2, "Col 4", "Col 1", 26, 30.78); TableTestUtils.assertAssertionError(() -> tableVerifier.withTolerance(0.01d).verify("name", table1, table2)); Assert.assertEquals( "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"surplus\">Col 4<p>Surplus</p>\n" + "</th>\n" + "<th class=\"pass\">Col 1</th>\n" + "<th class=\"missing\">Col 2<p>Missing</p>\n" + "</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"surplus number\">26<p>Surplus</p>\n" + "</td>\n" + "<td class=\"pass number\">30.78</td>\n" + "<td class=\"missing number\">25<p>Missing</p>\n" + "</td>\n" + "</tr>\n" + "</table>", TableTestUtils.getHtml(this.tableVerifier, "table")); } @Test public void missingSurplusRowsNonNumeric() throws IOException { final VerifiableTable table1 = TableTestUtils.createTable(2, "Col 1", "Col 2", "A1", "A2"); final VerifiableTable table2 = TableTestUtils.createTable(2, "Col 1", "Col 2", "C1", "C2"); TableTestUtils.assertAssertionError(() -> tableVerifier.verify("name", table1, table2)); Assert.assertEquals( "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"pass\">Col 1</th>\n" + "<th class=\"pass\">Col 2</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"surplus\">C1<p>Surplus</p>\n" + "</td>\n" + "<td class=\"surplus\">C2<p>Surplus</p>\n" + "</td>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"missing\">A1<p>Missing</p>\n" + "</td>\n" + "<td class=\"missing\">A2<p>Missing</p>\n" + "</td>\n" + "</tr>\n" + "</table>", TableTestUtils.getHtml(this.tableVerifier, "table")); } @Test public void missingSurplusRowsNumeric() throws IOException { final VerifiableTable table1 = TableTestUtils.createTable(2, "Col 1", "Col 2", 345.66, 13.0, 56.44, 45.01); final VerifiableTable table2 = TableTestUtils.createTable(2, "Col 1", "Col 2", 345.63, 12.8, 56.65, 45.31); TableTestUtils.assertAssertionError(() -> tableVerifier.withTolerance(0.1d).verify("name", table1, table2)); Assert.assertEquals( "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"pass\">Col 1</th>\n" + "<th class=\"pass\">Col 2</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"pass number\">345.6</td>\n" + "<td class=\"fail number\">13<p>Expected</p>\n" + "<hr/>12.8<p>Actual</p>\n" + "<hr/>0.2 / -1.5%<p>Difference / Variance</p>\n" + "</td>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"surplus number\">56.6<p>Surplus</p>\n" + "</td>\n" + "<td class=\"surplus number\">45.3<p>Surplus</p>\n" + "</td>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"missing number\">56.4<p>Missing</p>\n" + "</td>\n" + "<td class=\"missing number\">45<p>Missing</p>\n" + "</td>\n" + "</tr>\n" + "</table>", TableTestUtils.getHtml(this.tableVerifier, "table")); } @Test public void assertionSummaryWithSuccess() throws IOException { VerifiableTable table = TableTestUtils.createTable(1, "Col 1", "A1"); this.tableVerifier.withAssertionSummary(true).verify("name", table, table); Assert.assertEquals( "<body>\n" + "<div class=\"metadata\"/>\n" + "<h1>assertionSummaryWithSuccess</h1>\n" + "<div>\n" + "<h2>Assertions</h2>\n" + "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"pass\">2 right, 0 wrong, 100.0% correct</th>\n" + "</tr>\n" + "</table>\n" + "</div>\n" + "<div id=\"assertionSummaryWithSuccess.name\">\n" + "<h2>name</h2>\n" + "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"pass\">Col 1</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"pass\">A1</td>\n" + "</tr>\n" + "</table>\n" + "</div>\n" + "</body>", TableTestUtils.getHtml(this.tableVerifier, "body")); } @Test public void assertionSummaryWithFailure() throws IOException { final VerifiableTable table1 = TableTestUtils.createTable(2, "Col 1", "Col 2", "A1", "A2", "B1", "B2"); final VerifiableTable table2 = TableTestUtils.createTable(2, "Col 1", "Col 2", "A1", "A9", "B1", "B9"); TableTestUtils.assertAssertionError(() -> tableVerifier.withAssertionSummary(true).verify("name", table1, table2)); Assert.assertEquals( "<body>\n" + "<div class=\"metadata\"/>\n" + "<h1>assertionSummaryWithFailure</h1>\n" + "<div>\n" + "<h2>Assertions</h2>\n" + "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"fail\">4 right, 2 wrong, 66.6% correct</th>\n" + "</tr>\n" + "</table>\n" + "</div>\n" + "<div id=\"assertionSummaryWithFailure.name\">\n" + "<h2>name</h2>\n" + "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"pass\">Col 1</th>\n" + "<th class=\"pass\">Col 2</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"pass\">A1</td>\n" + "<td class=\"fail\">A2<p>Expected</p>\n" + "<hr/>A9<p>Actual</p>\n" + "</td>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"pass\">B1</td>\n" + "<td class=\"fail\">B2<p>Expected</p>\n" + "<hr/>B9<p>Actual</p>\n" + "</td>\n" + "</tr>\n" + "</table>\n" + "</div>\n" + "</body>", TableTestUtils.getHtml(this.tableVerifier, "body")); } @Test public void assertionSummaryWithMultipleVerify() throws IOException { final VerifiableTable table1 = TableTestUtils.createTable(1, "Col 1", "A1"); final VerifiableTable table2 = TableTestUtils.createTable(1, "Col 1", "A2"); this.tableVerifier.withAssertionSummary(true).verify("name1", table1, table1); TableTestUtils.assertAssertionError(() -> tableVerifier.withAssertionSummary(true).verify("name2", table1, table2)); Assert.assertEquals( "<body>\n" + "<div class=\"metadata\"/>\n" + "<h1>assertionSummaryWithMultipleVerify</h1>\n" + "<div>\n" + "<h2>Assertions</h2>\n" + "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"pass\">2 right, 0 wrong, 100.0% correct</th>\n" + "</tr>\n" + "</table>\n" + "</div>\n" + "<div id=\"assertionSummaryWithMultipleVerify.name1\">\n" + "<h2>name1</h2>\n" + "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"pass\">Col 1</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"pass\">A1</td>\n" + "</tr>\n" + "</table>\n" + "</div>\n" + "<div>\n" + "<h2>Assertions</h2>\n" + "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"fail\">1 right, 2 wrong, 33.3% correct</th>\n" + "</tr>\n" + "</table>\n" + "</div>\n" + "<div id=\"assertionSummaryWithMultipleVerify.name2\">\n" + "<h2>name2</h2>\n" + "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"pass\">Col 1</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"surplus\">A2<p>Surplus</p>\n" + "</td>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"missing\">A1<p>Missing</p>\n" + "</td>\n" + "</tr>\n" + "</table>\n" + "</div>\n" + "</body>", TableTestUtils.getHtml(this.tableVerifier, "body")); } @Test public void assertionSummaryWithMissingSurplusTables() throws IOException { final VerifiableTable table = TableTestUtils.createTable(1, "Col 1", "A1"); TableTestUtils.assertAssertionError(() -> tableVerifier.withAssertionSummary(true).verify( TableTestUtils.toNamedTables("name", table, "name2", table), TableTestUtils.toNamedTables("name", table, "name3", table))); Assert.assertEquals( "<body>\n" + "<div class=\"metadata\"/>\n" + "<h1>assertionSummaryWithMissingSurplusTables</h1>\n" + "<div>\n" + "<h2>Assertions</h2>\n" + "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"fail\">2 right, 4 wrong, 33.3% correct</th>\n" + "</tr>\n" + "</table>\n" + "</div>\n" + "<div id=\"assertionSummaryWithMissingSurplusTables.name\">\n" + "<h2>name</h2>\n" + "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"pass\">Col 1</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"pass\">A1</td>\n" + "</tr>\n" + "</table>\n" + "</div>\n" + "<div id=\"assertionSummaryWithMissingSurplusTables.name2\">\n" + "<h2>name2</h2>\n" + "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"missing\">Col 1<p>Missing</p>\n" + "</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"missing\">A1<p>Missing</p>\n" + "</td>\n" + "</tr>\n" + "</table>\n" + "</div>\n" + "<div id=\"assertionSummaryWithMissingSurplusTables.name3\">\n" + "<h2>name3</h2>\n" + "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"surplus\">Col 1<p>Surplus</p>\n" + "</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"surplus\">A1<p>Surplus</p>\n" + "</td>\n" + "</tr>\n" + "</table>\n" + "</div>\n" + "</body>", TableTestUtils.getHtml(this.tableVerifier, "body")); } @Test public void assertionSummaryWithHideMatchedRows() throws IOException { final VerifiableTable table1 = TableTestUtils.createTable(2, "Col 1", "Col 2", "A1", "A2", "B1", "B2", "C1", "C2"); final VerifiableTable table2 = TableTestUtils.createTable(2, "Col 1", "Col 2", "A1", "A2", "B1", "B2", "C1", "C9"); TableTestUtils.assertAssertionError(() -> tableVerifier .withAssertionSummary(true) .withHideMatchedRows(true) .verify("name", table1, table2)); Assert.assertEquals( "<body>\n" + "<div class=\"metadata\"/>\n" + "<h1>assertionSummaryWithHideMatchedRows</h1>\n" + "<div>\n" + "<h2>Assertions</h2>\n" + "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"fail\">7 right, 1 wrong, 87.5% correct</th>\n" + "</tr>\n" + "</table>\n" + "</div>\n" + "<div id=\"assertionSummaryWithHideMatchedRows.name\">\n" + "<h2>name</h2>\n" + "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"pass\">Col 1</th>\n" + "<th class=\"pass\">Col 2</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"pass multi\" colspan=\"2\">2 matched rows...</td>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"pass\">C1</td>\n" + "<td class=\"fail\">C2<p>Expected</p>\n" + "<hr/>C9<p>Actual</p>\n" + "</td>\n" + "</tr>\n" + "</table>\n" + "</div>\n" + "</body>", TableTestUtils.getHtml(this.tableVerifier, "body")); } }
package com.proquest.interview.phonebook; public class Person { public String name; public String phoneNumber; public String address; @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("\nFirst name: ").append(name); stringBuilder.append("\nPhone number: ").append(phoneNumber); stringBuilder.append("\nAddress: ").append(address); return stringBuilder.toString(); } }
package com.penglai.haima.utils; import android.text.TextUtils; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 作者:flyjiang * 说明: 用于字符串的处理 */ public class StringUtil { /** * 转换全角到半角 * * @param s 需要转换的字符串 * @return 转换后的字符串 */ public static String full2Half(final String s) { if (TextUtils.isEmpty(s)) { return ""; } char[] c = s.toCharArray(); for (int i = 0; i < c.length; i++) { if (c[i] >= 65281 && c[i] <= 65374) { c[i] = (char) (c[i] - 65248); } else if (c[i] == 12288) { // 空格 c[i] = (char) 32; } } return new String(c); } /** * 转换半角到全角 * * @param s 需要转换的字符串 * @return 转换后的字符串 */ public static String half2Full(String s) { if (TextUtils.isEmpty(s)) { return s; } char[] c = s.toCharArray(); for (int i = 0; i < c.length; i++) { if (c[i] == 32) { c[i] = (char) 12288; } else if (c[i] >= 33 && c[i] <= 126) { c[i] = (char) (c[i] + 65248); } } return new String(c); } /** * 提取字符串中的数字为数字数组 * * @param s 需要提取的字符串 * @return 提取后的数字数组 */ public static Long[] fetchNumber(String s) { if (TextUtils.isEmpty(s)) { return new Long[0]; } List<Long> longNumbers = new ArrayList<Long>(); char[] chs = s.toCharArray(); long number = -1; boolean isNumber = false; for (int i = 0; i < chs.length; i++) { if (chs[i] >= 48 && chs[i] <= 57) { if (number < 0) { number = 0; } number = number * 10 + chs[i] - 0x30; isNumber = true; } else { if (number >= 0 && isNumber) { longNumbers.add(number); number = -1; isNumber = false; } } } if (number >= 0) { longNumbers.add(number); } return (Long[]) longNumbers.toArray(new Long[longNumbers.size()]); } /** * 过滤掉回车和换行 * * @param oldString 需要过滤的字符串 * @return 过滤后字符串 */ public static String replaceEnter(String oldString) { if (TextUtils.isEmpty(oldString)) { return ""; } Pattern pattern = Pattern.compile("(\r\n|\r|\n|\n\r)"); //正则表达式的匹配一定要是这样,单个替换\r|\n的时候会错误 Matcher matcher = pattern.matcher(oldString); String newString = matcher.replaceAll("<br>"); return newString; } /** * 转成分段时间 * * @param str 8:30-15:30 * @param spaceTime 30min * @return */ public static ArrayList<String> getShowTimeArray(String str, int spaceTime, boolean flag) { ArrayList<String> tmp = new ArrayList<String>(); String[] tmpStr1 = str.trim().split("-"); String[] tmpStr2 = tmpStr1[0].trim().split(":"); String[] tmpStr3 = tmpStr1[1].trim().split(":"); int start = 0; int end = 0; try { start = Integer.parseInt(tmpStr2[0].trim()) * 60 + Integer.parseInt(tmpStr2[1].trim()); end = Integer.parseInt(tmpStr3[0].trim()) * 60 + Integer.parseInt(tmpStr3[1].trim()); } catch (Exception e) { e.printStackTrace(); } if (start > end) { end += 24 * 60; int zstart = 0; int zend = end; if (flag) { // 每半个小小时添加一次 for (int i = 0; i <= (zend - zstart) / spaceTime; i++) { tmp.add(String.format("%1$02d", (start + i * spaceTime) / 60 % 24) + ":" + String.format("%1$02d", (start + i * spaceTime) % 60)); } } for (int i = 0; i <= (24 - start) / spaceTime; i++) { tmp.add(String.format("%1$02d", (start + i * spaceTime) / 60 % 24) + ":" + String.format("%1$02d", (start + i * spaceTime) % 60)); } } else { // if(end == 24 * 60){ // end = 23*60+30; // // 每半个小小时添加一次 // for (int i = 0; i <= (end - start) / spaceTime; i++) { // tmp.add(String.format("%1$02d", (start + i * spaceTime) / 60 % // 24) + ":" + String.format("%1$02d", (start + i * spaceTime) % // 60)); // } // }else { // 每半个小小时添加一次 for (int i = 0; i <= (end - start) / spaceTime; i++) { int time = start + i * spaceTime; if (time < end) { tmp.add(String.format("%1$02d", (start + i * spaceTime) / 60 % 24) + ":" + String.format("%1$02d", (start + i * spaceTime) % 60)); } } // } } return tmp; } /** * 验证手机号码手机号是否合法 * 只验证1抬头且11位数字 * * @param str * @return */ public static boolean isMobile(String str) { // Pattern pattern = Pattern.compile("^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(17[0-3,5-8])|(18[0-9]))(\\d){8}$"); Pattern pattern = Pattern.compile("^(1)(\\d){10}$"); Matcher matcher = pattern.matcher(str); if (matcher.matches()) { return true; } else { return false; } } public static void filtNull(TextView textView, String s) { if (s != null) { textView.setText(s); } else { textView.setText(filtNull(s)); } } //判断过滤单个string为null public static String filtNull(String s) { if (s != null) { return s; } else { s = "null"; } return s; } }
package controller.registrar.curriculum; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; 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 org.json.simple.JSONObject; import configuration.EncryptandDecrypt; import connection.DBConfiguration; /** * Servlet implementation class CurriculumItemController */ @WebServlet("/Registrar/Controller/Registrar/Curriculum/PrintCurriculum") public class PrintCurriculum extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public PrintCurriculum() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("plain/text"); String course = request.getParameter("course"); String curyear = request.getParameter("curyear"); EncryptandDecrypt ec = new EncryptandDecrypt(); DBConfiguration db = new DBConfiguration(); Connection conn = db.getConnection(); Statement stmnt = null; try { stmnt = conn.createStatement(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } String sql = ""; try { PrintWriter out = response.getWriter(); sql = " SELECT * FROM `r_curriculum` where "; out.print(sql); stmnt.execute(sql); ResultSet rs = stmnt.executeQuery(sql); while(rs.next()){ } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package ceui.lisa.adapters; import android.content.Context; import android.graphics.Bitmap; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.target.SimpleTarget; import com.bumptech.glide.request.transition.Transition; import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import ceui.lisa.R; import ceui.lisa.activities.Shaft; import ceui.lisa.download.FileCreator; import ceui.lisa.http.ErrorCtrl; import ceui.lisa.interfaces.OnItemClickListener; import ceui.lisa.model.IllustsBean; import ceui.lisa.utils.Common; import ceui.lisa.utils.GlideUtil; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; /** * 作品详情页竖向多P列表 */ public class IllustDetailAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context mContext; private OnItemClickListener mOnItemClickListener; private IllustsBean allIllust; private int imageSize = 0; private TagHolder gifHolder; private boolean playGif = false; public IllustDetailAdapter(IllustsBean list, Context context) { mContext = context; allIllust = list; imageSize = (mContext.getResources().getDisplayMetrics().widthPixels - 2 * mContext.getResources().getDimensionPixelSize(R.dimen.twelve_dp)); } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new TagHolder( LayoutInflater.from(mContext).inflate( R.layout.recy_illust_grid, parent, false) ); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { final TagHolder currentOne = (TagHolder) holder; if (position == 0) { ViewGroup.LayoutParams params = currentOne.illust.getLayoutParams(); params.height = imageSize * allIllust.getHeight() / allIllust.getWidth(); params.width = imageSize; currentOne.illust.setLayoutParams(params); if (Shaft.sSettings.isFirstImageSize()) { Glide.with(mContext) .load(GlideUtil.getOriginal(allIllust, position)) .into(currentOne.illust); } else { Glide.with(mContext) .load(GlideUtil.getLargeImage(allIllust, position)) .into(currentOne.illust); } Common.showLog("height " + params.height + "width " + params.width); if (allIllust.getType().equals("ugoira")) { gifHolder = currentOne; startGif(); } else { currentOne.playGif.setVisibility(View.GONE); } } else { Glide.with(mContext) .asBitmap() .load(Shaft.sSettings.isFirstImageSize() ? GlideUtil.getOriginal(allIllust, position) : GlideUtil.getLargeImage(allIllust, position)) .into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) { ViewGroup.LayoutParams params = currentOne.illust.getLayoutParams(); params.width = imageSize; params.height = imageSize * resource.getHeight() / resource.getWidth(); currentOne.illust.setLayoutParams(params); currentOne.illust.setImageBitmap(resource); } }); } if (mOnItemClickListener != null) { currentOne.itemView.setOnClickListener(v -> mOnItemClickListener.onItemClick(v, position, 0)); currentOne.playGif.setOnClickListener(v -> { currentOne.mProgressBar.setVisibility(View.VISIBLE); currentOne.playGif.setVisibility(View.GONE); mOnItemClickListener.onItemClick(v, position, 1); }); } } @Override public int getItemCount() { return allIllust.getPage_count(); } public void setOnItemClickListener(OnItemClickListener itemClickListener) { mOnItemClickListener = itemClickListener; } public boolean isPlayGif() { return playGif; } public void setPlayGif(boolean playGif) { Common.showLog("IllustDetailAdapter 停止播放gif图"); this.playGif = playGif; } public void startGif() { Common.showLog("IllustDetailAdapter 开始播放gif图"); playGif = true; File parentFile = FileCreator.createGifParentFile(allIllust); if (parentFile.exists()) { gifHolder.mProgressBar.setVisibility(View.GONE); gifHolder.playGif.setVisibility(View.GONE); final File[] listfile = parentFile.listFiles(); Observable.create(new ObservableOnSubscribe<File>() { @Override public void subscribe(ObservableEmitter<File> emitter) throws Exception { List<File> allFiles = Arrays.asList(listfile); Collections.sort(allFiles, new Comparator<File>() { @Override public int compare(File o1, File o2) { if (Integer.valueOf(o1.getName().substring(0, o1.getName().length() - 4)) > Integer.valueOf(o2.getName().substring(0, o2.getName().length() - 4))) { return 1; } else { return -1; } } }); int xyz = 0; int count = allFiles.size(); while (true) { if (playGif) { emitter.onNext(allFiles.get(xyz % count)); Thread.sleep(85); xyz++; } else { break; } } } }).subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new ErrorCtrl<File>() { @Override public void onNext(File s) { Glide.with(mContext) .load(s) .placeholder(gifHolder.illust.getDrawable()) .into(gifHolder.illust); } }); } else { gifHolder.playGif.setVisibility(View.VISIBLE); } } public static class TagHolder extends RecyclerView.ViewHolder { ImageView illust, playGif; ProgressBar mProgressBar; TagHolder(View itemView) { super(itemView); illust = itemView.findViewById(R.id.illust_image); playGif = itemView.findViewById(R.id.play_gif); mProgressBar = itemView.findViewById(R.id.gif_progress); } } }
package com.psing.professional_streaming.service.serviceimpl; import com.psing.professional_streaming.dataobject.User; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest @Slf4j public class LoginServiceImplTest { @Autowired private LoginServiceImpl loginService; private final String USERNAME = "111111"; private final String PASSWORD = "111111"; @Test public void loginTest() throws Exception{ User result = loginService.login(USERNAME, PASSWORD); log.info("【用户登录】 result={}", result); Assert.assertNotNull(result); } }
package gm; /** * * @author Angelos Trigkas * * Class Board implements the board that the game is played on. */ public class Board { private final static int PLAYER_ONE = 1; private final static int PLAYER_TWO = -1; private final static int EMPTY = 0; private Point[][] board; // The game board private int[] columnHeight; // Number of pieces added to each column as the game progresses private int cols; // Number of columns of the game board private int rows; // Number of rows of the game board private int[] movesMade; // movesMade history, stores the movesMade made by each player as the game progresses private int moveCounter; // movesMade counter private int currentPlayer; // Current player private Point[][] cl; /** * Constructor. Creates a Board object. * * @param columns number of columns of the board * @param inrows number of rows of the board */ public Board(int columns, int inrows) { cols = columns; rows = inrows; board = new Point[cols][rows]; columnHeight = new int[cols]; movesMade = new int[cols*rows]; moveCounter = -1; /* Set columnHeight to zero and initialise all points to EMPTY. */ for(int x=0; x<cols;x++) { columnHeight[x]=0; for(int y=0;y<rows;y++) board[x][y]=new Point(x,y,EMPTY); } generateCL(); currentPlayer=PLAYER_ONE; } public void generateCL() { cl=new Point[69][4]; int count=0; // horz segs for(int y=0;y<rows;y++) { for(int x=0;x<cols-3;x++) { Point[] temp = new Point[4]; for(int i=x;i<x+4;i++) temp[i-x]=board[i][y]; cl[count]=temp; count++; } } // vert segs for(int x=0;x<cols;x++) { for(int y=0;y<rows-3;y++) { Point[] temp = new Point[4]; for(int i=y;i<y+4;i++) temp[i-y]=board[x][i]; cl[count]=temp; count++; } } // diag segs for(int x=0;x<cols-3;x++) { for(int y=0;y<rows-3;y++) { Point[] temp = new Point[4]; for(int t=x,i=y;t<x+4 && i<y+4;t++,i++) temp[i-y]=board[t][i]; cl[count]=temp; count++; } } for(int x=0;x<cols-3;x++) { for(int y=rows-1;y>rows-4;y--) { Point[] temp = new Point[4]; for(int t=x,i=y;t<x+4 && i>-1;t++,i--) temp[t-x]=board[t][i]; cl[count]=temp; count++; } } } /** * A move is valid if there are less than 6 pieces * in the particular column. * * @param column the column attempted to be inserted a piece * @return TRUE if the move is valid, FALSE otherwise */ public boolean validMove(int column) { return columnHeight[column]<rows; } /** * Executes a move: * - Sets the state of the point the piece is placed in, * depending on the player making the move * - Adjusts the height of the column that the piece is * dropped in * - Increments the number of movesMade * - Stores the column in which the piece is added * - changes the current player * * @param column the column in which the piece will be dropped */ public void makeMove(int column) { board[column][columnHeight[column]].setState(currentPlayer); columnHeight[column]++; moveCounter++; movesMade[moveCounter]=column; currentPlayer=-currentPlayer; } /** * Executes the opposite actions from makeMove() method. * Used by the computer player to decide the best move. */ public void undoMove() { board[movesMade[moveCounter]][columnHeight[movesMade[moveCounter]]-1].setState(EMPTY); columnHeight[movesMade[moveCounter]]--; moveCounter--; currentPlayer=-currentPlayer; } /** * * @return TRUE if there are valid movesMade left, FALSE otherwise */ public boolean validMovesLeft() { return moveCounter<movesMade.length-1; } /** * * @return 1 if the user is the winner * 2 if the computer is the winner * 0 if there is no winner yet */ public int winnerIs() { for (int i = 0; i < cl.length; i++) { if (getScore(cl[i])==4) { return PLAYER_ONE; } else if(getScore(cl[i])==-4) return PLAYER_TWO; } return 0; } private int getScore(Point[] points) { int playerone = 0; int playertwo = 0; for (int i = 0; i < points.length; i++) { if (points[i].getState() == Board.PLAYER_ONE) { playerone++; } else if (points[i].getState() == Board.PLAYER_TWO) { playertwo++; } } if ( (playerone+playertwo > 0) && (!(playerone > 0 && playertwo > 0)) ) { return (playerone != 0) ? playerone : playertwo; } else { return 0; } } public int getStrength() { int sum = 0; int[] weights = {0,1,10,50,600}; for (int i = 0; i < cl.length; i++) { sum += (getScore(cl[i]) > 0) ? weights[Math.abs(getScore(cl[i]))] : -weights[Math.abs(getScore(cl[i]))]; } return sum + (currentPlayer == PLAYER_ONE ? 16 : -16); } /** * Prints the Board to the screen. * @return */ public String toString() { String temp = ""; for (int y = rows-1; y > -1; y--) { for (int x = 0; x < cols; x++) { if (board[x][y].getState() == EMPTY) { temp = temp + "-"; } else if (board[x][y].getState() == PLAYER_ONE) { temp = temp + "O"; } else { temp = temp + "X"; } } temp += "\n"; } return temp; } /** * Sets current player. * @param currentPlayer player to be set */ void setCP(int cp) { this.currentPlayer = cp; } /** * Returns the current player. * @return 1 for the user * -1 for the computer */ int getCP() { return currentPlayer; } /** * Returns the height of a column. * * @param col the requested columns height * @return height of column col */ public int getHeight(int col) { return this.columnHeight[col]; } /** * Return a move from history. * @param moveCounter move to be returned * @return the corresponding column */ public int getMove(int lm) { return this.movesMade[lm]; } /** * * @return moveCounter */ public int getLm() { return this.moveCounter; } }
package pl.coderslab.service; public class TransferService { private String text; public TransferService(String text) { this.text = text; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
/* * 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 DAO; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import PO.cashback; import PO.estabelecimento; import PO.franquia; import PO.pedido; import PO.produto; import PO.usuario; /** * * @author QueroDelivery */ public class DAOCashback extends DAOBase { private Connection connection; public DAOCashback() throws Exception { if (connection == null) { connection = new ConnectionFactory().getConnection(); } } public DAOCashback(Connection con) { connection = con; } public List getAllCashback() throws Exception { try { stmt = connection.prepareStatement("use web select * from cashback"); rs = stmt.executeQuery(); return rsToList(rs); } catch (Exception e) { throw e; } finally { close(connection, stmt, rs); } } public List getCashbackPorUsuarioId(int id) throws Exception { try { stmt = connection.prepareStatement("use web select * from cashback where usu_bene=?"); stmt.setObject(1, id); rs = stmt.executeQuery(); return rsToList(rs); } catch (Exception e) { throw e; } finally { close(connection, stmt, rs); } } public List selectCashbackUsuario(usuario usu) throws Exception { return getCashbackPorUsuarioId(usu.getCod_usu()); } public void insertCashback(cashback cashback) throws SQLException { System.out.println("Inserindo cashback"); PreparedStatement stmt = null; try { stmt = connection.prepareStatement("insert into cashback values ( ?,?,? )"); stmt.setObject(1, cashback.getCod_ped()); stmt.setObject(2, cashback.getUsu_bene()); stmt.setObject(3, cashback.getValor()); stmt.execute(); } catch (SQLException ex) { System.err.println("Erro :" + ex); } finally { close(connection, stmt, rs); } } private List<cashback> rsToList(ResultSet rs) throws Exception { List<cashback> listaResult = new ArrayList<>(); while (rs.next()) { cashback cash = new cashback(); cash.setCod_cash(rs.getInt("cod_cash")); cash.setCod_ped(rs.getInt("pedido")); cash.setUsu_bene(rs.getInt("usu_bene")); cash.setValor(rs.getFloat("valor")); listaResult.add(cash); } return listaResult; } }
package CircleOverlap; public class Circle { // Fields public double[] Center; public double radius; public Circle(double[] center, double radius) { Center = center; this.radius = radius; } // Getters, x, y, and radius public double getX() { return this.Center[0]; } public double getY() { return this.Center[1]; } public double getradius() { return this.radius; } // Circle contains point? public boolean contains(double[] Punkt) { if (Math.sqrt(Math.pow(this.getX() - Punkt[0], 2) + Math.pow(this.getY() - Punkt[1], 2)) <= this.getradius ()) { return true; } else return false; } // Circle overlaps with other circle? public boolean overlaps(Circle cirkel2) { if (Math.sqrt(Math.pow(this.getX() - cirkel2.getX(), 2) + Math.pow(this.getY() - cirkel2.getY(), 2)) <= this .getradius() + cirkel2.getradius()) { return true; } else return false; } }
package com.acewill.ordermachine.adapter; import android.content.Context; import android.support.v4.app.FragmentManager; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.acewill.ordermachine.R; import com.acewill.ordermachine.model.OrderReq; import com.acewill.ordermachine.util_new.TimeUtil; import com.acewill.paylibrary.PayReqModel; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; /** * Author:Anch * Date:2017/11/20 16:27 * Desc: */ public class DingDanItemAdapter<T> extends MyAdapter { private List<OrderReq> dataList; private FragmentManager manager; public DingDanItemAdapter(Context context, List<T> data, FragmentManager ft) { super(context, data); this.mContext = context; dataList = (List<OrderReq>) data; manager = ft; } @Override protected View getItemView(int position, View convertView, ViewGroup parent) { MyHolder holder; if (convertView == null) { convertView = View.inflate(mContext, R.layout.item_dingdantongji, null); holder = new MyHolder(); holder.item_caozuo_img = (ImageView) convertView.findViewById(R.id.item_caozuo_img); holder.item_dingdanhao_tv = (TextView) convertView .findViewById(R.id.item_dingdanhao_tv); holder.item_xiadanshijian_tv = (TextView) convertView .findViewById(R.id.item_xiadanshijian_tv); holder.item_shishoujine_tv = (TextView) convertView .findViewById(R.id.item_shishoujine_tv); holder.item_youhuijine_tv = (TextView) convertView .findViewById(R.id.item_youhuijine_tv); holder.item_dingdanzhuangtai_tv = (TextView) convertView .findViewById(R.id.item_dingdanzhuangtai_tv); holder.item_tuikuanjine_tv = (TextView) convertView .findViewById(R.id.item_tuikuanjine_tv); holder.item_tuikuanshijian_tv = (TextView) convertView .findViewById(R.id.item_tuikuanshijian_tv); holder.item_zhifufangshi_tv = (TextView) convertView .findViewById(R.id.item_zhifufangshi_tv); holder.shanghuzhifupingtaidingdanhao_tv = (TextView) convertView .findViewById(R.id.item_shanghuzhifupingtaidingdanhao_tv); holder.item_zhongduandanhao_tv = (TextView) convertView .findViewById(R.id.item_zhongduandanhao_tv); holder.item_shouyinyuan_tv = (TextView) convertView .findViewById(R.id.item_shouyinyuan_tv); holder.item_huiyuanxinxi_tv = (TextView) convertView .findViewById(R.id.item_huiyuanxinxi_tv); convertView.setTag(holder); } else { holder = (MyHolder) convertView.getTag(); } final OrderReq recorder = dataList.get(position); holder.item_dingdanhao_tv.setText(recorder.getOid() + "");//如果已经上传了的话就会变成订单号,如果没有上传就会变成 id holder.item_shishoujine_tv.setText(recorder.getCost()); holder.item_xiadanshijian_tv .setText(format.format(new Date(Long.parseLong(recorder.getCreatedAt())))); holder.item_zhifufangshi_tv.setText(recorder.getPaymentTypeName()); holder.item_youhuijine_tv.setText("0"); holder.item_shouyinyuan_tv.setText(recorder.getRealname()); if (recorder.getPaymentStatus().equals("PAYED")) { holder.item_dingdanzhuangtai_tv.setText("已支付"); holder.item_dingdanzhuangtai_tv .setTextColor(mContext.getResources().getColor(R.color.gray_search_text)); } else if (recorder.getPaymentStatus().equals("REFUND")) { holder.item_dingdanzhuangtai_tv.setText("已退单"); holder.item_dingdanzhuangtai_tv .setTextColor(mContext.getResources().getColor(R.color.red1)); } if (PayReqModel.PTID_SSS_MEMBER_CHUZHISTR .equals(recorder.getPaymentTypeName()) || PayReqModel.PTID_SSS_MEMBER_YOUHUIQUANSTR .equals(recorder.getPaymentTypeName())) { if (!TextUtils.isEmpty(recorder.getMemberPhoneNumber())) holder.item_huiyuanxinxi_tv .setText(recorder.getMemberName() + "|\n" + recorder .getMemberPhoneNumber()); else holder.item_huiyuanxinxi_tv .setText(recorder.getMemberName() + "|\n" + recorder .getuActualNo()); } else { holder.item_huiyuanxinxi_tv .setText(""); } if (!TextUtils.isEmpty(recorder.getRefundMoney()) && Float .parseFloat(recorder.getRefundMoney()) != 0) { holder.item_tuikuanjine_tv.setText("-" + recorder.getRefundMoney()); holder.item_tuikuanjine_tv .setTextColor(mContext.getResources().getColor(R.color.green1)); } else { holder.item_tuikuanjine_tv.setText(""); holder.item_tuikuanjine_tv .setTextColor(mContext.getResources().getColor(R.color.gray_search_text)); } if (recorder.getRefundTime() != 0) { holder.item_tuikuanshijian_tv .setText(format.format(new Date(recorder.getRefundTime()))); } else { holder.item_tuikuanshijian_tv .setText(""); } holder.shanghuzhifupingtaidingdanhao_tv.setText(recorder.getBis_id()); holder.item_zhongduandanhao_tv.setText(recorder.getTerminalOrderId() + ""); //1、获取当前时间和下单时间,如果是一天前的就设置成灰,不能点击 //2、获取订单状态,如果还没有退款的就设置成绿色,可以退款,如果已经退款,设置成红色不能点击 try { boolean moreThanOneDay = TimeUtil .moreThanOneDay(new Date(Long.parseLong(recorder.getCreatedAt())), new Date()); if (moreThanOneDay) {//大于一天或者不为已支付状态不能退款 convertView.setEnabled(false); holder.item_caozuo_img.setImageResource(R.drawable.cannot_refund);//不能退款的 } else if (recorder.getPaymentStatus().equals("REFUND")) { convertView.setEnabled(false); holder.item_caozuo_img.setImageResource(R.drawable.refund_success);//已经退款的 } else { convertView.setEnabled(true); holder.item_caozuo_img.setImageResource(R.drawable.refund);//退款成功 } } catch (ParseException e) { e.printStackTrace(); } return convertView; } SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private class MyHolder { ImageView item_caozuo_img; TextView item_dingdanhao_tv; TextView item_xiadanshijian_tv; TextView item_shishoujine_tv; TextView item_youhuijine_tv; TextView item_dingdanzhuangtai_tv; TextView item_tuikuanjine_tv; TextView item_tuikuanshijian_tv; TextView item_zhifufangshi_tv; TextView shanghuzhifupingtaidingdanhao_tv; TextView item_zhongduandanhao_tv; TextView item_shouyinyuan_tv; TextView item_huiyuanxinxi_tv; } }
/* Ara - capture species and specimen data * * Copyright (C) 2009 INBio (Instituto Naciona de Biodiversidad) * * 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.inbio.ara.persistence.taxonomy; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.persistence.Basic; 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.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.inbio.ara.persistence.LogGenericEntity; /** * * @author esmata */ @Entity @Table(name = "reference") public class Reference extends LogGenericEntity implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "reference_id") private Long referenceId; @Basic(optional = false) @Column(name = "title") private String title; @Column(name = "description") private String description; @Column(name = "publication_date") @Temporal(TemporalType.DATE) private Date publicationDate; @Column(name = "identifier") private String identifier; @OneToMany(cascade = CascadeType.ALL, mappedBy = "reference", fetch = FetchType.LAZY) private List<TaxonDescriptionRecordReference> taxonDescriptionRecordReferenceCollection; @JoinColumn(name = "language_id", referencedColumnName = "language_id") @ManyToOne(optional = false, fetch = FetchType.LAZY) private Language languageId; @JoinColumn(name = "reference_type_id", referencedColumnName = "reference_type_id") @ManyToOne(optional = false, fetch = FetchType.LAZY) private ReferenceType referenceTypeId; public Reference() { } public Reference(Long referenceId) { this.referenceId = referenceId; } public Reference(Long referenceId, String createdBy, Calendar creationDate, String lastModificationBy, Calendar lastModificationDate, String title) { this.referenceId = referenceId; this.setCreatedBy(createdBy); this.setCreationDate(creationDate); this.setLastModificationBy(lastModificationBy); this.setLastModificationDate(lastModificationDate); this.title = title; } public Long getReferenceId() { return referenceId; } public void setReferenceId(Long referenceId) { this.referenceId = referenceId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Date getPublicationDate() { return publicationDate; } public void setPublicationDate(Date publicationDate) { this.publicationDate = publicationDate; } public String getIdentifier() { return identifier; } public void setIdentifier(String identifier) { this.identifier = identifier; } public List<TaxonDescriptionRecordReference> getTaxonDescriptionRecordReferenceCollection() { return taxonDescriptionRecordReferenceCollection; } public void setTaxonDescriptionRecordReferenceCollection(List<TaxonDescriptionRecordReference> taxonDescriptionRecordReferenceCollection) { this.taxonDescriptionRecordReferenceCollection = taxonDescriptionRecordReferenceCollection; } public Language getLanguageId() { return languageId; } public void setLanguageId(Language languageId) { this.languageId = languageId; } public ReferenceType getReferenceTypeId() { return referenceTypeId; } public void setReferenceTypeId(ReferenceType referenceTypeId) { this.referenceTypeId = referenceTypeId; } @Override public int hashCode() { int hash = 0; hash += (referenceId != null ? referenceId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Reference)) { return false; } Reference other = (Reference) object; if ((this.referenceId == null && other.referenceId != null) || (this.referenceId != null && !this.referenceId.equals(other.referenceId))) { return false; } return true; } @Override public String toString() { return "org.inbio.ara.persistence.taxonomy.Reference[referenceId=" + referenceId + "]"; } }
import java.util.Scanner; public class sumarray { public static void main(String[] args) { int n;int m;int max=0;int min=0; Scanner sc=new Scanner(System.in); m=sc.nextInt();n=sc.nextInt(); int arr[]=new int[m]; for(int i=0;i<m;i++) { arr[i]=sc.nextInt(); } int brr[]=new int[n]; for(int i=0;i<n;i++) { brr[i]=sc.nextInt(); } if(m>n) { max=m; } else { max=n; } if(m<n) { min=m; } else { min=n; } int c[]=new int[max]; if(max==m) { sum(arr,brr,c,max,min,0,arr); } else if(max==n) { sum(arr,brr,c,max,min,0,brr); } for(int i=0;i<max;i++) { System.out.print(c[i]+" "); } } public static int[] sum(int arr[],int brr[],int c[],int max,int min,int i,int d[]) { if(i<min) { c[i]=arr[i]+brr[i]; return sum(arr,brr,c,max,min,++i,d); } else if(i>=min&&i<max) { c[i]=d[i]; return sum(arr,brr,c,max,min,++i,d); } else if(i==max) { return c; } return c; } }
package dao.mapper; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import logic.SNSFile; public interface FileMapper { @Select("select ifnull(max(fno), 0)+1 fno from file") SNSFile maxfno(); @Insert("insert into file (fno, wno, wno2, wno3, fwhere, name, filename, fileurl, regdate) values(#{fno},#{wno},#{wno2},#{wno3},#{fwhere},#{name},#{filename},#{fileurl},now())") void insert_file(SNSFile f); }
package testingData; public class TestData { public static String HomeTitle="JCPenny"; public static int numberOfElement=1; public static String zipCode="11373"; public static String productname="shoe"; public static String numberOfProductinTheCart="2"; public static String ViewCartandCheckOutButtonName="View Cart and Checkout"; public static String CheckOutButtonName="Checkout"; }
package com.cg.demo; import java.util.Scanner; public class CheckNumber { public static void main(String[] args) { System.out.println("Check if a number is an increasing number "); boolean flag = false; Scanner sc = new Scanner (System.in); System.out.println("Enter a number:"); int num = sc.nextInt(); int current_num= num%10; num = num/10; while(num>0) { if(current_num <= num % 10) { flag = true; break; } current_num = num % 10; num = num / 10; } if(flag) { System.out.println("false");} else { System.out.println("true"); } } }
/* * Welcome to use the TableGo Tools. * * http://vipbooks.iteye.com * http://blog.csdn.net/vipbooks * http://www.cnblogs.com/vipbooks * * Author:bianj * Email:edinsker@163.com * Version:5.8.0 */ package com.lenovohit.hwe.mobile.core.model; import javax.persistence.Entity; import javax.persistence.Table; import com.lenovohit.hwe.base.model.AuditableModel; /** * Emergency 急救 * * @author redstar * @version 1.0.0 2017-12-14 */ @Entity @Table(name = "APP_EMERGENCY") public class Emergency extends AuditableModel implements java.io.Serializable { /** 版本号 */ private static final long serialVersionUID = 5123120272341522921L; private String fakId; private String classificationId; private String fakName; private String sort; private String fakDetails; public String getFakId() { return fakId; } public void setFakId(String fakId) { this.fakId = fakId; } public String getClassificationId() { return classificationId; } public void setClassificationId(String classificationId) { this.classificationId = classificationId; } public String getFakName() { return fakName; } public void setFakName(String fakName) { this.fakName = fakName; } public String getSort() { return sort; } public void setSort(String sort) { this.sort = sort; } public String getFakDetails() { return fakDetails; } public void setFakDetails(String fakDetails) { this.fakDetails = fakDetails; } }
import java.io.IOException; /** * Created by fur1k on 26.05.2017. */ public class Main { public static void main(String[] args) throws IOException, CloneNotSupportedException { Worker worker1, worker2, worker3; Detail detailLol; detailLol = new Detail("China", "Bolt"); worker1 = new Worker("Egor", 9 ); System.out.println("worker1: "); System.out.println(worker1); System.out.println("1-------------"); try{ worker3 = worker1.clone(); // worker3.setSkill(new Worker()); System.out.println("worker1: "); System.out.println(worker1); System.out.println("worker3: "); System.out.println(worker3); if (worker1.equals(worker3)) System.out.println("worker1 equals worker3"); if (worker1.equals(worker3)) System.out.println("worker1 equals worker3"); if (worker1.getSkill() == worker3.getSkill()); System.out.println("worker1.Detail equals worker3.Detail"); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } }
package com.xinbang.bwacl.api; import moxie.cloud.service.client.ClientFactory; import moxie.cloud.service.client.auth.AuthorizationProvider; /** * Created by sxm on 17/2/10. */ public class BWaclCenterClientFactory extends ClientFactory { protected BWaclCenterClientFactory(Builder builder) { super(builder); } public BWaclCenterClient newClient() { return new BWaclCenterClient(this); } public BWaclCenterClient newClient(String authorization) { BWaclCenterClient client = new BWaclCenterClient(this); client.setAuthorization(authorization); return client; } public BWaclCenterClient newClient(AuthorizationProvider provider) { BWaclCenterClient client = new BWaclCenterClient(this); client.setAuthorizationProvider(provider); return client; } public static Builder builder(ClientFactory.Options options) { return new Builder(options); } public static class Builder extends ClientFactory.Builder<Builder> { public Builder(ClientFactory.Options options) { super(options); } public BWaclCenterClientFactory build() { return new BWaclCenterClientFactory(this); } } }
package com.state.light; /** * Created by Valentine on 2018/5/10. */ public class LightManager { public LightState state; public LightManager(LightState state){ this.state = state; } public void pressButton(){ state.switchs(this); } }
package lab6; public abstract class BreakFastTemplate { public final void MakeBreakFast(int numOfEggs) { crackingEggs(numOfEggs); prepareEggs(); cook(); serve(); if(hook()) System.out.println("ajouter du sel et du poivre");; } abstract public void crackingEggs(int numOfEggs); abstract public void prepareEggs() ; abstract public void cook() ; abstract public void serve() ; boolean hook() { return true; } }
package com.psing.professional_streaming.repository; import com.psing.professional_streaming.dataobject.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends JpaRepository<User,String> { User findByUsername(String username); }
package com.scripbox.service; import java.util.List; import com.scripbox.model.Challenge; import com.scripbox.model.Employee; import com.scripbox.model.GenericResponse; public interface EmployeeChallengeService { GenericResponse saveChallenges(List<Challenge> challenges, String userName); GenericResponse upVoteChallenge(String id, String userName); GenericResponse collaborateChallenge(String id, String userName); List<Employee> getChallengeColaborations(String id, String userName); List<Challenge> getChallenges(boolean creationDateSort, boolean voteCountSort); }
package com.example.submissionempat.ui.detail; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.media.Image; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.ContextCompat; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import com.bumptech.glide.Glide; import com.example.submissionempat.R; import com.example.submissionempat.db.DatabaseContract; import com.example.submissionempat.db.DatabaseHelper; import com.example.submissionempat.db.FavoriteHelper; import com.example.submissionempat.model.MovieData; import com.example.submissionempat.model.TvData; import com.example.submissionempat.viewmodel.MainViewModel; import static com.example.submissionempat.db.DatabaseContract.*; import de.hdodenhof.circleimageview.CircleImageView; public class DetailActivity extends AppCompatActivity implements View.OnClickListener { CircleImageView imgFilm; private TextView titleFilm, descOfFilm; ImageView imgFavorite; private String imgUrl; private int id; public static final String EXTRA_DATA = "extra_data"; public static final String EXTRA_FAVORITES = "extra_favorites"; public static final String EXTRA_POSITION = "extra_position"; public static final int REQUEST_ADD = 100; public static final int RESULT_ADD = 101; private final int ALERT_DIALOG_DELETE = 20; public static final int RESULT_DELETE = 301; private MovieData movieData; private FavoriteHelper favoriteHelper; private DatabaseHelper databaseHelper; private MainViewModel mainViewModel; private int position; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); ActionBar actionBar = getSupportActionBar(); actionBar.setTitle("Film Detail"); // mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class); // mainViewModel.getCheckFavorite(this, movieData.getId() ).observe(this,getCheckMovie); imgFilm = (CircleImageView) findViewById(R.id.img_circle); titleFilm = (TextView) findViewById(R.id.tv_title_film); descOfFilm = (TextView) findViewById(R.id.tv_desc_film); imgFavorite = (ImageView) findViewById(R.id.img_favorite); // if(FavoriteHelper.getInstance(this).isFavorite(id)) { // // } movieData = getIntent().getParcelableExtra(EXTRA_DATA); titleFilm.setText(movieData.getTitle()); descOfFilm.setText(movieData.getOverview()); imgUrl = movieData.getPoster_path(); id = movieData.getId(); Glide.with(this) .load(movieData.getPoster_path()) .into(imgFilm); imgFavorite.setOnClickListener(this); favoriteHelper = FavoriteHelper.getInstance(getApplicationContext()); MovieFavorite(); } private Observer<? super MovieData> getCheckMovie = new Observer<MovieData>() { @Override public void onChanged(MovieData movieData) { } }; private void MovieFavorite() { movieData = getIntent().getParcelableExtra(EXTRA_FAVORITES); if(movieData != null){ position = getIntent().getIntExtra(EXTRA_POSITION,0); // isFavorite = true; } else { movieData = new MovieData(); } // if (isFavorite){ // imgFilm.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.ic_favorite_black_24dp)); // if(movieData != null){ // titleFilm.setText(movieData.getTitle()); // descOfFilm.setText(movieData.getOverview()); // // Glide.with(this) // .load(movieData.getPoster_path()) // .into(imgFilm); // } // } else { // imgFilm.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.ic_favorite_border_black_24dp)); // } } @Override public void onClick(View view) { if(view.getId() == R.id.img_favorite){ if(FavoriteHelper.getInstance(this).isFavorite(id)) { showAlertDialog(ALERT_DIALOG_DELETE); } else { String title = titleFilm.getText().toString().trim(); String desc = descOfFilm.getText().toString().trim(); movieData.setTitle(title); movieData.setOverview(desc); movieData.setPoster_path(imgUrl); movieData.setId(id); Intent intent = new Intent(); intent.putExtra(EXTRA_FAVORITES,movieData); intent.putExtra(EXTRA_POSITION,0); long result = favoriteHelper.insertNote(movieData); if (result > 0 ){ movieData.setId((int)result); setResult(RESULT_ADD, intent); finish(); } else { Toast.makeText(DetailActivity.this, "Gagal menambahkan ke favorite", Toast.LENGTH_SHORT).show(); } } // if(isFavorite){ // showAlertDialog(ALERT_DIALOG_DELETE); // } else { // long result = favoriteHelper.insertNote(movieData); // // if (result > 0 ){ // movieData.setId((int)result); // setResult(RESULT_ADD, intent); // finish(); // } else { // Toast.makeText(DetailActivity.this, "Gagal menambahkan ke favorite", Toast.LENGTH_SHORT).show(); // } // } } } private void showAlertDialog(int type) { String dialogTitle, dialogMessage; dialogMessage = "Apakah anda yakin ingin menghapus item ini dari favorite?"; dialogTitle = "Hapus Note"; AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setTitle(dialogTitle); alertDialogBuilder .setMessage(dialogMessage) .setCancelable(false) .setPositiveButton("Ya", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { long result = favoriteHelper.deleteNote(movieData.getId()); if (result > 0) { Intent intent = new Intent(); intent.putExtra(EXTRA_POSITION, position); setResult(RESULT_DELETE, intent); finish(); } else { Toast.makeText(DetailActivity.this, "Gagal menghapus data", Toast.LENGTH_SHORT).show(); } } }) .setNegativeButton("Tidak", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } }
package sop.reports.vo; /** * @Author: LCF * @Date: 2020/1/9 10:20 * @Package: sop.reports.vo */ public class OffListItem { private String off_sh_no_pfix; private String off_sh_no; private String it_no; private String off2_it_name; private String off2_curr_code; private String of_fob; private String of_cnf; public String getOff_sh_no_pfix() { return off_sh_no_pfix; } public void setOff_sh_no_pfix(String off_sh_no_pfix) { this.off_sh_no_pfix = off_sh_no_pfix; } public String getOff_sh_no() { return off_sh_no; } public void setOff_sh_no(String off_sh_no) { this.off_sh_no = off_sh_no; } public String getIt_no() { return it_no; } public void setIt_no(String it_no) { this.it_no = it_no; } public String getOff2_it_name() { return off2_it_name; } public void setOff2_it_name(String off2_it_name) { this.off2_it_name = off2_it_name; } public String getOff2_curr_code() { return off2_curr_code; } public void setOff2_curr_code(String off2_curr_code) { this.off2_curr_code = off2_curr_code; } public String getOf_fob() { return of_fob; } public void setOf_fob(String of_fob) { this.of_fob = of_fob; } public String getOf_cnf() { return of_cnf; } public void setOf_cnf(String of_cnf) { this.of_cnf = of_cnf; } }