blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
a675389888ee21754fc607219c608b4ae1f1eece
Java
jess426sophia/hw12
/week10/src/week10/Loan.java
UTF-8
1,664
3.234375
3
[]
no_license
package week10; public abstract class Loan implements LoanConstants { int loanNum; String customerLastName; double loanAmount; double interestRate; int term; /** * @param loanNum * @param customerLastName * @param loanAmount * @param term */ public Loan(int loanNum, String customerLastName, double loanAmount, int term) { if (loanAmount > maxLoanAmount) { loanAmount = maxLoanAmount; } this.loanNum = loanNum; this.customerLastName = customerLastName; this.loanAmount = loanAmount; if (term == mediumTerm || term == longTerm) { this.term = term; } else { this.term = shortTerm; } } public double calculateTotalAmountOwed() { double loanFee = loanAmount * 0.01; // Assumed, Loan fee is 1% of loan amount return loanAmount + loanFee; } @Override public String toString() { return getClass().getName() + "\n Loan Number=" + loanNum + ",\n Customer Last Name=" + customerLastName + ",\n Loan Amount=" + loanAmount + ",\n InterestRate=" + interestRate + ",\n Term=" + term + " years \n Total amount owed=" + String.format("%.2f", calculateTotalAmountOwed()); } public Object[] toArray() { return new Object[] {getClass().getName(),loanNum,customerLastName,loanAmount,interestRate,term, String.format("%.2f", calculateTotalAmountOwed())}; // //return getClass().getName() + "\n Loan Number=" + loanNum + ",\n Customer Last Name=" + customerLastName // + ",\n Loan Amount=" + loanAmount + ",\n InterestRate=" + interestRate + ",\n Term=" + term // + " years \n Total amount owed=" + String.format("%.2f", calculateTotalAmountOwed()); } }
true
a2d75faecd987abdc2cfd070a3505e4918c25f51
Java
pparkhyung/nenea
/nenea/src/nenea/Client.java
UTF-8
305
1.601563
2
[]
no_license
package nenea; import nenea.client.operation.UptimeClient; public class Client { public void start() throws Exception { System.out.println("nenea booting"); //new OperationClient().start(); UptimeClient.start(); //new FileClient().start(); //new TelnetClient().start(); } }
true
27e6cc645a3eef571c3790db48f9c76014d7cecb
Java
Carayav/rnc-ws
/src/main/java/cl/minsal/api/ws/Services/RncService.java
UTF-8
155
1.59375
2
[]
no_license
package cl.minsal.api.ws.Services; import java.util.Date; public interface RncService { void bookLeave(Date startDate, Date endDate, String name); }
true
9ad68c7776e75ba716b7149f98f8d3057f8d37ad
Java
TradewareSystems/tradewaresystemsPublicDevRepo
/src/main/java/com/tradeware/clouddatabase/entity/OptionLiveTradeChildEntity.java
UTF-8
8,110
1.859375
2
[]
no_license
package com.tradeware.clouddatabase.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.tradeware.clouddatabase.bean.OptionLiveTradeChildBean; /*@Entity @Table(name = "T_OPTION_TRADE_CHILD", uniqueConstraints = { @UniqueConstraint(name = "OPTION_TRADE_MAIN_CONSTRAINT", columnNames = { "OPTION_TRADE_MAIN_ID" }) }) */ @Entity/*(name = "T_OPTION_TRADE_CHILD")*/ @Table(name = "T_OPTION_TRADE_CHILD") public class OptionLiveTradeChildEntity extends AbstractEntity { private static final long serialVersionUID = -5660536719759828136L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "OPTION_TRADE_CHILD_ID", unique = true, nullable = false, columnDefinition = "serial") private Integer itemIdChild; @Column(name = "STRIKE_PRICE", precision=12) private Double strikePrice; @Column(name = "TRADE_TYPE", length=6) private String tradeType; @Column(name = "TRADE_POSITION", length=6) private String tradePosition; //OPEN/CLOSE @Column(name = "OPTION_TYPE", length=6) private String optionType; //Call/Put @Column(name = "KITE_OPTION_KEY", length=36) private String kiteFutureKey; @Column(name = "BUY_AT_VALUE", precision=7, scale=2) private Double buyAtValue;//buyerAt @Column(name = "SELL_AT_VALUE", precision=7, scale=2) private Double sellAtValue;//sellerAt @Column(name = "TRADED_AT_VAL", precision=7, scale=2) private Double tradedAtVal; @Column(name = "EXITED_AT_VAL", precision=7, scale=2) private Double exitedAtVal; @Column(name = "STOCK_PRICE_ENTRY", precision=7, scale=2) private Double stockPriceEntry; @Column(name = "FUTURE_PRICE_ENTRY", precision=7, scale=2) private Double futurePriceEntry; @Column(name = "STOCK_PRICE_EXIT", precision=7, scale=2) private Double stockPriceExit; @Column(name = "FUTURE_PRICE_EXIT", precision=7, scale=2) private Double futurePriceExit; @Column(name = "NUMBER_OF_LOTS", precision=6) private Integer numberOfLots; @Temporal(TemporalType.TIMESTAMP) @Column(name = "TRADED_AT_DT_TM") private Date tradedAtDtTm; @Temporal(TemporalType.TIMESTAMP) @Column(name = "EXITED_AT_DT_TM") private Date exitedAtDtTm; @Column(name = "PROF_LOS_AMT_VAL", precision=7, scale=2) private Double profitLossAmtVal; @Column(name = "POS_MOVE_VAL", precision=7, scale=2) private Double positiveMoveVal; @Column(name = "NEG_MOVE_VAL", precision=7, scale=2) private Double negativeMoveVal; @Column(name = "POS_MOVE_LTP", precision=7, scale=2) private Double positiveMoveLtp; @Column(name = "NEG_MOVE_LTP", precision=7, scale=2) private Double negativeMoveLtp; @Column(name = "DT_STAMP") @Temporal(TemporalType.DATE) private Date tradedDateStamp; @Column(name = "OI_TREND") private String optionChainTrend; @Column(name = "OI_PRICE_TREND") private String optionChainPriceTrend; @Column(name = "OPTION_CHAIN_ID") private Integer optionChainId; @Column(name = "OI_INFO", length=128) private String oiInfo; @Column(name = "BID_PRICE", precision=7, scale=2) private Double bidPrice;//buyerAt @Column(name = "ASK_PRICE", precision=7, scale=2) private Double askPrice;//sellerAt @Column(name = "LAST_PRICE", precision=7, scale=2) private Double lastPrice; @Column(name = "BID_QUANTTY", precision=32) private Long bidQuantity; @Column(name = "ASK_QUANTTY", precision=32) private Long askQuantity; @Column(name = "KITE_INSTRUMENT_TOKEN") private Long instrumentToken; @Column(name = "KITE_ORDER_ID") private String kiteOrderId; @Column(name = "KITE_ORDER_TYPE") private String kiteOrderType;//CO/BO/Regular @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "FK_OPTION_TRADE_MAIN_ID", referencedColumnName="OPTION_TRADE_MAIN_ID") private OptionLiveTradeMainEntity optionLiveTradeMainEntity; public OptionLiveTradeMainEntity getOptionLiveTradeMainEntity() { return optionLiveTradeMainEntity; } public void setOptionLiveTradeMainEntity(OptionLiveTradeMainEntity optionLiveTradeMainEntity) { this.optionLiveTradeMainEntity = optionLiveTradeMainEntity; } ///////// @Column(name = "STOP_LOSS_VAL", precision=7, scale=2) private Double stopLossVal; @Column(name = "TARGET_VAL", precision=7, scale=2) private Double targetVal; ///////// public void populateEntity(OptionLiveTradeChildBean bean) { this.itemIdChild = bean.getItemIdChild(); this.strikePrice = bean.getStrikePrice(); this.tradeType = bean.getTradeType(); this.tradePosition = bean.getTradePosition(); this.optionType = bean.getOptionType(); this.kiteFutureKey = bean.getKiteFutureKey(); this.buyAtValue = bean.getBuyAtValue(); this.sellAtValue = bean.getSellAtValue(); this.tradedAtVal = bean.getTradedAtVal(); this.exitedAtVal = bean.getExitedAtVal(); this.stockPriceEntry = bean.getStockPriceEntry(); this.futurePriceEntry = bean.getFuturePriceEntry(); this.stockPriceExit = bean.getStockPriceExit(); this.futurePriceExit = bean.getFuturePriceExit(); this.numberOfLots = bean.getNumberOfLots(); this.tradedAtDtTm = bean.getTradedAtDtTm(); this.exitedAtDtTm = bean.getExitedAtDtTm(); this.profitLossAmtVal = bean.getProfitLossAmtVal(); this.positiveMoveVal = bean.getPositiveMoveVal(); this.negativeMoveVal = bean.getNegativeMoveVal(); this.positiveMoveLtp = bean.getPositiveMoveLtp(); this.negativeMoveLtp = bean.getNegativeMoveLtp(); this.tradedDateStamp = bean.getTradedDateStamp(); this.optionChainTrend = bean.getOptionChainTrend(); this.optionChainPriceTrend = bean.getOptionChainPriceTrend(); this.optionChainId = bean.getOptionChainId(); this.oiInfo = bean.getOiInfo(); this.bidPrice = bean.getBidPrice(); this.askPrice = bean.getAskPrice(); this.lastPrice = bean.getLastPrice(); this.bidQuantity = bean.getBidQuantity(); this.askQuantity = bean.getAskQuantity(); this.instrumentToken = bean.getInstrumentToken(); this.kiteOrderId = bean.getKiteOrderId(); this.kiteOrderType = bean.getKiteOrderType(); this.stopLossVal = bean.getStopLossVal(); this.targetVal = bean.getTargetVal(); } public void populateBean(OptionLiveTradeChildBean bean) { bean.setItemIdChild(this.itemIdChild); bean.setStrikePrice(this.strikePrice); bean.setTradeType(this.tradeType); bean.setTradePosition(this.tradePosition); bean.setOptionType(this.optionType); bean.setKiteFutureKey(this.kiteFutureKey); bean.setBuyAtValue(this.buyAtValue); bean.setSellAtValue(this.sellAtValue); bean.setTradedAtVal(this.tradedAtVal); bean.setExitedAtVal(this.exitedAtVal); bean.setStockPriceEntry(this.stockPriceEntry); bean.setFuturePriceEntry(this.futurePriceEntry); bean.setStockPriceExit(this.stockPriceExit); bean.setFuturePriceExit(this.futurePriceExit); bean.setNumberOfLots(this.numberOfLots); bean.setTradedAtDtTm(this.tradedAtDtTm); bean.setExitedAtDtTm(this.exitedAtDtTm); bean.setProfitLossAmtVal(this.profitLossAmtVal); bean.setPositiveMoveVal(this.positiveMoveVal); bean.setNegativeMoveVal(this.negativeMoveVal); bean.setPositiveMoveLtp(this.positiveMoveLtp); bean.setNegativeMoveLtp(this.negativeMoveLtp); bean.setTradedDateStamp(this.tradedDateStamp); bean.setOptionChainTrend(this.optionChainTrend); bean.setOptionChainPriceTrend(this.optionChainPriceTrend); bean.setOptionChainId(this.optionChainId); bean.setOiInfo(this.oiInfo); bean.setBidPrice(this.bidPrice); bean.setAskPrice(this.askPrice); bean.setLastPrice(this.lastPrice); bean.setBidQuantity(this.bidQuantity); bean.setAskQuantity(this.askQuantity); bean.setInstrumentToken(this.instrumentToken); bean.setKiteOrderId(this.kiteOrderId); bean.setKiteOrderType(this.kiteOrderType); bean.setStopLossVal(this.stopLossVal); bean.setTargetVal(this.targetVal); } }
true
abb672e98762d5260391be8ee1e1800fe546aeba
Java
Tochi-kazi/ICS4U-Assignments
/Assignment2.java
UTF-8
1,933
4.03125
4
[]
no_license
/** * Name: Tochi Iroakazi * Class: ICS4U * Defintion: This program runs rock, paper Scissors against the computer. */ import java.util.Random; import java.util.Scanner; public class RockPaperScissors { public static void main(String[] args) { System.out.println("Pick a choice: Rock = 1, Papper = 2 and Scissors = 3 ? "); Scanner userinput = new Scanner (System.in); int userchoice = userinput.nextInt(); Random generatenumber = new Random(); int computerchoice = generatenumber.nextInt(3) + 1; switch(computerchoice) { case 1: //rock if (userchoice == 1) { // Rock vs Rock System.out.println("Draw, the computer chose(Rock) " + computerchoice); }else if (userchoice == 2) { // Rock vs Papper System.out.println("Win, the computer chose(Rock) " + computerchoice); }else if (userchoice == 3) { // Rock vs Scissors System.out.println("Lose, the computer chose(Rock) " + computerchoice); } break; case 2: //paper if (userchoice == 1) { // paper vs Rock System.out.println("Lose the computer chose(Paper) " + computerchoice); }else if (userchoice == 2) { // paper vs paper System.out.println("Draw, the computer chose(Paper) " + computerchoice); }else if ( userchoice == 3) { // paper vs Scissors System.out.println("Win, the computer chose(Paper) " + computerchoice); } break; case 3: // Scissors if (userchoice == 1) { // Scissors vs Rock System.out.println("Win,the computer chose(Scissors) " + computerchoice); }else if (userchoice == 2) { // Scissors vs paper System.out.println("Lose, the computer chose(Scissors) " + computerchoice); }else if ( userchoice == 3) { // Scissors vs Scissors System.out.println("Draw, the computer chose(Scissors) " + computerchoice); } break; } } }
true
b22e075b8d544b6db4ef5af8a40884a8f347c114
Java
ConnorDoane/Exercises
/Chapter15/Exercise2/Exercise2.java
UTF-8
385
3.28125
3
[]
no_license
import java.util.Scanner; public class Exercise2 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a word"); String input = scan.nextLine(); int counter = input.length(); System.out.println(" "); while (counter > 0) { System.out.println(input); counter = counter - 1; } } }
true
55b776e697250e66cf69a826619f211afbd626fb
Java
kanaida/LG-Esteem-Homeless-Kernel
/out/target/common/obj/JAVA_LIBRARIES/android_stubs_current_intermediates/src/android/appwidget/AppWidgetManager.java
UTF-8
2,236
1.726563
2
[]
no_license
package android.appwidget; public class AppWidgetManager { AppWidgetManager() { throw new RuntimeException("Stub!"); } public static android.appwidget.AppWidgetManager getInstance(android.content.Context context) { throw new RuntimeException("Stub!"); } public void updateAppWidget(int[] appWidgetIds, android.widget.RemoteViews views) { throw new RuntimeException("Stub!"); } public void updateAppWidget(int appWidgetId, android.widget.RemoteViews views) { throw new RuntimeException("Stub!"); } public void updateAppWidget(android.content.ComponentName provider, android.widget.RemoteViews views) { throw new RuntimeException("Stub!"); } public java.util.List<android.appwidget.AppWidgetProviderInfo> getInstalledProviders() { throw new RuntimeException("Stub!"); } public android.appwidget.AppWidgetProviderInfo getAppWidgetInfo(int appWidgetId) { throw new RuntimeException("Stub!"); } public void bindAppWidgetId(int appWidgetId, android.content.ComponentName provider) { throw new RuntimeException("Stub!"); } public int[] getAppWidgetIds(android.content.ComponentName provider) { throw new RuntimeException("Stub!"); } public static final java.lang.String ACTION_APPWIDGET_PICK = "android.appwidget.action.APPWIDGET_PICK"; public static final java.lang.String ACTION_APPWIDGET_CONFIGURE = "android.appwidget.action.APPWIDGET_CONFIGURE"; public static final java.lang.String EXTRA_APPWIDGET_ID = "appWidgetId"; public static final java.lang.String EXTRA_APPWIDGET_IDS = "appWidgetIds"; public static final java.lang.String EXTRA_CUSTOM_INFO = "customInfo"; public static final java.lang.String EXTRA_CUSTOM_EXTRAS = "customExtras"; public static final int INVALID_APPWIDGET_ID = 0; public static final java.lang.String ACTION_APPWIDGET_UPDATE = "android.appwidget.action.APPWIDGET_UPDATE"; public static final java.lang.String ACTION_APPWIDGET_DELETED = "android.appwidget.action.APPWIDGET_DELETED"; public static final java.lang.String ACTION_APPWIDGET_DISABLED = "android.appwidget.action.APPWIDGET_DISABLED"; public static final java.lang.String ACTION_APPWIDGET_ENABLED = "android.appwidget.action.APPWIDGET_ENABLED"; public static final java.lang.String META_DATA_APPWIDGET_PROVIDER = "android.appwidget.provider"; }
true
4ee8064fff7d7e5cec235eee19dd4acc4e4204cc
Java
BlackCellena/Codility
/Lesson_10_PrimeAndCompositeNumbers/MinPerimeterRectangle/src/Solution.java
UTF-8
761
3.703125
4
[]
no_license
public class Solution { //find the smallest perimeter of a rectangular with area N. public int solution(int N){ //find the divisors of N and check the perimeter int i = 1, minPer = Integer.MAX_VALUE; while (Math.pow(i,2) <N) { if (N % i == 0) { minPer = Math.min(minPer, 2*(N/i + i)); } // so we count its pair two i++; } if(Math.pow(i,2)==N) minPer = Math.min(minPer, 2*(N/i + i)); return minPer; } public static void main(String[] args) { Solution sol = new Solution(); int N = 30; int perimeter = sol.solution(N); System.out.println(perimeter); } }
true
6b2123b5bea4b414e98e68afae3e6997bda69ac9
Java
Rocher0724/AndroidPluginForUnity
/app/src/main/java/com/visualcamp/plugin/plugintest/PluginClass.java
UTF-8
213
1.976563
2
[]
no_license
package com.visualcamp.plugin.plugintest; /** * Created by visualcamp on 2018. 3. 9.. */ public class PluginClass { public static String GetTextPlugin(int number) { return "Number is " + number; } }
true
2cb234bf57a147989ad6fffc240ea7af04a2cde6
Java
LittleBelka/Java-University-Course
/Laba 4 with ServerSocket/src/MainServer.java
UTF-8
480
2.5
2
[]
no_license
import java.io.File; import java.io.IOException; public class MainServer { public static void main(String[] args) throws ClassNotFoundException, IOException { ConfigurationRead xPathCaller = new ConfigurationRead("configuration.xml"); File directory1 = new File(xPathCaller.getProperty("locationFolderOne")); int port = Integer.parseInt(xPathCaller.getProperty("port")); Thread s = new Server(directory1, port); s.start(); } }
true
74f18957e11c9b95d906b4c14acb310f89ee3c11
Java
digiprizma/gestion-commande
/src/main/java/com/digiprisma/product/infra/repositories/CategoryDpoRepository.java
UTF-8
391
1.59375
2
[]
no_license
package com.digiprisma.product.infra.repositories; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.digiprisma.product.persistence.model.CategoryDpo; @Repository public interface CategoryDpoRepository extends MongoRepository<CategoryDpo, Long> { }
true
7be10fc0fc98db309b575160b139af5698ab6311
Java
zhuxj/willow_mvn
/willow-endoor/src/main/java/com/willow/door/admin/doorslide/mapper/DoorSlideMapper.java
UTF-8
414
1.578125
2
[]
no_license
/** * 版权声明:贤俊工作室 版权所有 违者必究 * 日 期:2013-01-12 */ package com.willow.door.admin.doorslide.mapper; import com.willow.platform.core.base.mapper.BaseMapper; import com.willow.door.admin.doorslide.domain.DoorSlide; /** * <pre> * 幻灯片映射类 * </pre> * * @author 朱贤俊 * @version 1.0 */ public interface DoorSlideMapper extends BaseMapper<DoorSlide> { }
true
3d532a86ae7d67ebad335b83effa9a8fe4ea7ea9
Java
Yasaman1997/BattleShip
/Final Project/src/ir/aut/ceit/view/guest/Waiting_For_Connections_Guest.java
UTF-8
1,620
2.75
3
[]
no_license
package ir.aut.ceit.view.guest; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * Created by Admin on 6/17/2017. */ public class Waiting_For_Connections_Guest { public Waiting_For_Connections_Guest() { MainFrame mainFrame = new MainFrame(); } static class MainFrame extends JFrame implements ActionListener { MainFrame() { setLayout(new FlowLayout()); // set frame layout JMenuBar mainMenu; JLabel label; JLabel buttonLabel; JButton cancelButton; mainMenu = new JMenuBar(); setJMenuBar(mainMenu); setTitle("Waiting for connections ..."); setDefaultCloseOperation(EXIT_ON_CLOSE); setExtendedState(this.getExtendedState() | this.MAXIMIZED_BOTH); setVisible(true); setBounds(0, 0, 300, 200); label = new JLabel("Waiting for the host to join...", Label.LEFT); add(label, Label.LEFT); buttonLabel = new JLabel(); add(buttonLabel, RIGHT_ALIGNMENT); cancelButton = new JButton("Cancel"); add(cancelButton, RIGHT_ALIGNMENT); } /** * Invoked when an action occurs. * * @param e */ @Override public void actionPerformed(ActionEvent e) { } } public static void main(String[] args) { MainFrame mainFrame = new MainFrame(); } }
true
6ab27ab270d3354696419928f717464073517405
Java
guorongjuan/test
/wms-model/src/main/java/com/lsh/wms/model/stock/StockLot.java
UTF-8
2,535
2.234375
2
[ "Apache-2.0" ]
permissive
package com.lsh.wms.model.stock; import java.io.Serializable; import java.math.BigDecimal; import java.security.acl.LastOwnerException; import java.util.Date; public class StockLot implements Serializable { /** */ private Long id; /** 批次id */ private Long lotId; /** 商品id */ private Long skuId; /** 生产批次号 */ private String serialNo; /** 入库时间 */ private Long inDate; /** 生产时间 */ private Long productDate; /** 保质期失效时间 */ private Long expireDate; /** */ private Long createdAt; /** */ private Long updatedAt; private Long itemId; private Long poId; private Long receiptId; /** 包装单位*/ private BigDecimal packUnit= new BigDecimal(0); /** 包装名称 */ private String packName = ""; public Long getId(){ return this.id; } public void setId(Long id){ this.id = id; } public Long getLotId(){ return this.lotId; } public void setLotId(Long lotId){ this.lotId = lotId; } public Long getSkuId(){ return this.skuId; } public void setSkuId(Long skuId){ this.skuId = skuId; } public String getSerialNo(){ return this.serialNo; } public void setSerialNo(String serialNo){ this.serialNo = serialNo; } public Long getInDate(){ return this.inDate; } public void setInDate(Long inDate){ this.inDate = inDate; } public Long getProductDate(){ return this.productDate; } public void setProductDate(Long productDate){ this.productDate = productDate; } public Long getExpireDate(){ return this.expireDate; } public void setExpireDate(Long expireDate){ this.expireDate = expireDate; } public Long getCreatedAt(){ return this.createdAt; } public void setCreatedAt(Long createdAt){ this.createdAt = createdAt; } public Long getUpdatedAt(){ return this.updatedAt; } public void setUpdatedAt(Long updatedAt){ this.updatedAt = updatedAt; } public Long getPoId() { return poId; } public void setPoId(Long poId) { this.poId = poId; } public Long getReceiptId() { return receiptId; } public void setReceiptId(Long receiptId) { this.receiptId = receiptId; } public Long getItemId() { return itemId; } public void setItemId(Long itemId) { this.itemId = itemId; } public BigDecimal getPackUnit(){ return packUnit; } public void setPackUnit(BigDecimal packUnit){ this.packUnit = packUnit; } public String getPackName(){ return packName; } public void setPackName(String packName){ this.packName = packName; } }
true
0a5d91eb7e97e33c11147563b0ab2b980b6cfb31
Java
sgrinich/Droptoken-Android-RIBs
/tutorials/tutorial3-completed/build/generated/source/apt/debug/com/uber/rib/root/home/HomeBuilder_Module_RouterFactory.java
UTF-8
1,663
1.945313
2
[]
no_license
package com.uber.rib.root.home; import dagger.internal.Factory; import dagger.internal.Preconditions; import javax.annotation.Generated; import javax.inject.Provider; @Generated( value = "dagger.internal.codegen.ComponentProcessor", comments = "https://google.github.io/dagger" ) public final class HomeBuilder_Module_RouterFactory implements Factory<HomeRouter> { private final Provider<HomeBuilder.Component> componentProvider; private final Provider<HomeView> viewProvider; private final Provider<HomeInteractor> interactorProvider; public HomeBuilder_Module_RouterFactory( Provider<HomeBuilder.Component> componentProvider, Provider<HomeView> viewProvider, Provider<HomeInteractor> interactorProvider) { this.componentProvider = componentProvider; this.viewProvider = viewProvider; this.interactorProvider = interactorProvider; } @Override public HomeRouter get() { return Preconditions.checkNotNull( HomeBuilder.Module.router( componentProvider.get(), viewProvider.get(), interactorProvider.get()), "Cannot return null from a non-@Nullable @Provides method"); } public static Factory<HomeRouter> create( Provider<HomeBuilder.Component> componentProvider, Provider<HomeView> viewProvider, Provider<HomeInteractor> interactorProvider) { return new HomeBuilder_Module_RouterFactory( componentProvider, viewProvider, interactorProvider); } public static HomeRouter proxyRouter(Object component, HomeView view, HomeInteractor interactor) { return HomeBuilder.Module.router((HomeBuilder.Component) component, view, interactor); } }
true
c25c38b0747b54b5ace2398f10570270a96b3092
Java
mbamforth/6-S079-project
/6S079-final-project/src/weird/gears/Spline.java
UTF-8
960
3.015625
3
[]
no_license
package weird.gears; // spline object public class Spline { private double[][] points; public static final double[][] bSplineCoefficients = {{-1./6 , 3./6 , -3./6 , 1./6 }, { 3./6 , -6./6 , 3./6 , 0. }, {-3./6 , 0. , 3./6 , 0. }, { 1./6 , 4./6 , 1./6 , 0. }}; // creates b-spline public Spline(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { points = new double[4][2]; points[0][0] = x1; points[0][1] = y1; points[1][0] = x2; points[1][1] = y2; points[2][0] = x3; points[2][1] = y3; points[3][0] = x4; points[3][1] = y4; } // returns the points public double[][] getPoints() { return points; } }
true
f566aa12e812c586b39c2485dd72f4be35d26c3f
Java
Aashish-Anand/Practice
/src/CodeForces/C1359.java
UTF-8
1,099
2.9375
3
[]
no_license
package CodeForces; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class C1359 { public static void main(String[] args) throws IOException { new C1359().run(); } private void run() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(reader.readLine()); while(t-- > 0) { String s[] = reader.readLine().split(" "); int h = Integer.parseInt(s[0]); int c = Integer.parseInt(s[1]); int temp = Integer.parseInt(s[2]); int x = (int)Math.ceil((temp - c)/(2*temp - h- c)); System.out.println(x+(x-1)); } } } // ld sg(ll p,ll q,ll n){ // return ((ld)p*(n+1)+q*n)/(2*n+1); // } // // void solve(){ // cin>>p>>q>>h; // if(p+q>=2*h)cout<<2<<el; // else{ // z=(p-h)/(2*h-p-q); // if(abs(sg(p,q,z)-h)>abs(sg(p,q,z+1)-h))cout<<2*z+3<<el; // else cout<<2*z+1<<el; // } // }
true
119e2815f624366091a54f44c45af86fa7b1b7d1
Java
shinso1990/MLTP_Java_1
/src/main/java/Proxy/ErrorTracker.java
UTF-8
1,060
2.671875
3
[]
no_license
/* * 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 Proxy; /** * * @author alancastro */ public class ErrorTracker { public static void logError(Exception e ) { try { StringBuilder sb; sb = new StringBuilder(); sb.append("{ Mensaje: '"); sb.append(e.getMessage() ); sb.append("', StackTrace: '"); sb.append(e.getStackTrace()); sb.append("'}"); new ComunicadorRedis().guardarError(sb.toString()); } finally{} } public static void logError(String error ) { try { StringBuilder sb; sb = new StringBuilder(); sb.append("{ Mensaje: '"); sb.append(error); sb.append("' }"); new ComunicadorRedis().guardarError(sb.toString()); } finally{} } }
true
7f556d3532a60725bb19976a5c2fb5728a87c204
Java
avrhamo/GrouponProject
/src/main/java/com/jb/clients/LoginManager.java
UTF-8
1,645
2.5
2
[]
no_license
package com.jb.clients; import com.jb.exception.CustomCouponSystemException; import com.jb.exception.ExceptionsMap; import com.jb.facade.AdminFacade; import com.jb.facade.ClientFacade; import com.jb.facade.CompanyFacade; import com.jb.facade.CustomerFacade; import java.sql.SQLException; public class LoginManager { private static LoginManager loginManager = null; private LoginManager() { } public static LoginManager getInstance() { if (loginManager == null) { loginManager = new LoginManager(); } return loginManager; } public ClientFacade login(String email, String password, ClientType clientType) throws CustomCouponSystemException, SQLException { try { switch (clientType) { case ADMIN: AdminFacade adminFacade = new AdminFacade(); adminFacade.login(email, password); return adminFacade; case COMPANY: CompanyFacade companyFacade = new CompanyFacade(); companyFacade.login(email, password); return companyFacade; case CUSTOMER: CustomerFacade customerFacade = new CustomerFacade(); customerFacade.login(email, password); return customerFacade; default: throw new CustomCouponSystemException(ExceptionsMap.ERROR_LOGIN); } } catch(CustomCouponSystemException ex) { System.out.println(ex.getMessage()); return null; } } }
true
18a058e20831b86dd64dee7272f8e61f2e2a283a
Java
procukvs/RegulaExpr
/RegulExpr/src/regexpr/finite/Going.java
UTF-8
396
3.15625
3
[]
no_license
package regexpr.finite; public class Going implements Comparable<Going>{ //private class Going{ Integer state; Character ch; Going(Integer s, Character c){ state = s; ch = c; } public int compareTo(Going g){ int r = state-g.state; if (r==0) r = ch-g.ch; return r; } @Override public String toString() { return "Going (state=" + state + ", ch=" + (ch==0?"Eps":ch)+ ")"; } }
true
97ad1eb10af572a086899cb8943886df10441494
Java
history-purge/LeaveHomeSafe-source-code
/e/d/c/o/a0/i.java
UTF-8
17,265
2.296875
2
[]
no_license
package e.d.c.o.a0; import e.d.b.m; import e.d.c.j; public class i extends j<j> { public i(j paramj) { super(paramj); } private String x() { return b(0, 2); } public String a() { return a(4352, new String[] { "Off", "On", "No Flash & Flash" }); } public String b() { return a(4866, new String[] { "AE Good", "Over Exposed" }); } public String c() { return a(4864, new String[] { "No Blur Warning", "Blur warning" }); } public String c(int paramInt) { if (paramInt != 0) { if (paramInt != 4102) { if (paramInt != 4107) { if (paramInt != 4110) { if (paramInt != 4352) { if (paramInt != 4624) { if (paramInt != 4112) { if (paramInt != 4113) { if (paramInt != 4128) { if (paramInt != 4129) { if (paramInt != 4144) { if (paramInt != 4145) { if (paramInt != 4147) { if (paramInt != 4148) { switch (paramInt) { default: switch (paramInt) { default: switch (paramInt) { default: return super.c(paramInt); case 5122: return g(); case 5121: return j(); case 5120: break; } return f(); case 4866: return b(); case 4865: return o(); case 4864: break; } return c(); case 4100: return v(); case 4099: return d(); case 4098: return w(); case 4097: break; } return t(); } return i(); } return h(); } return s(); } return u(); } return n(); } return q(); } return l(); } return m(); } return k(); } return a(); } return p(); } return r(); } return e(); } return x(); } public String d() { Integer integer = ((j)this.a).k(4099); if (integer == null) return null; int k = integer.intValue(); if (k != 0) { if (k != 128) { if (k != 256) { if (k != 384) { if (k != 512) { if (k != 32768) { StringBuilder stringBuilder; switch (k) { default: stringBuilder = new StringBuilder(); stringBuilder.append("Unknown ("); stringBuilder.append(integer); stringBuilder.append(")"); return stringBuilder.toString(); case 772: return "B&W Sepia"; case 771: return "B&W Blue Filter"; case 770: return "B&W Yellow Filter"; case 769: return "B&W Green Filter"; case 768: break; } return "None (B&W)"; } return "Film Simulation"; } return "Low"; } return "Medium Low"; } return "High"; } return "Medium High"; } return "Normal"; } public String e() { Integer integer = ((j)this.a).k(4102); if (integer == null) return null; int k = integer.intValue(); if (k != 0) { if (k != 256) { if (k != 768) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Unknown ("); stringBuilder.append(integer); stringBuilder.append(")"); return stringBuilder.toString(); } return "Low"; } return "High"; } return "Normal"; } public String f() { return a(5120, 1, new String[] { "Standard", null, "Wide" }); } public String g() { Integer integer = ((j)this.a).k(5122); if (integer == null) return null; int k = integer.intValue(); if (k != 0) { if (k != 1) { if (k != 256) { if (k != 32768) { if (k != 512) { if (k != 513) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Unknown ("); stringBuilder.append(integer); stringBuilder.append(")"); return stringBuilder.toString(); } return "Wide 2 (400%)"; } return "Wide 1 (230%)"; } return "Film Simulation"; } return "Standard (100%)"; } return "Manual"; } return "Auto (100-400%)"; } public String h() { return a(4147, new String[] { "Auto", "Manual" }); } public String i() { Integer integer = ((j)this.a).k(4148); if (integer == null) return null; int k = integer.intValue(); if (k != 256) { if (k != 512) { if (k != 768) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Unknown ("); stringBuilder.append(integer); stringBuilder.append(")"); return stringBuilder.toString(); } return "DR (Dynamic Range Priority)"; } return "SN (Signal to Noise Priority)"; } return "HR (High Resolution)"; } public String j() { Integer integer = ((j)this.a).k(5121); if (integer == null) return null; int k = integer.intValue(); if (k != 0) { if (k != 256) { if (k != 272) { if (k != 288) { if (k != 304) { if (k != 512) { if (k != 768) { if (k != 1024) { if (k != 1280) { if (k != 1281) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Unknown ("); stringBuilder.append(integer); stringBuilder.append(")"); return stringBuilder.toString(); } return "Pro Neg. Hi"; } return "Pro Neg. Std"; } return "F4/Velvia"; } return "F3/Studio Portrait Ex"; } return "F2/Fujichrome (Velvia)"; } return "F1c/Studio Portrait Increased Sharpness"; } return "F1b/Studio Portrait Smooth Skin Tone (Astia)"; } return "F1a/Studio Portrait Enhanced Saturation"; } return "F1/Studio Portrait"; } return "F0/Standard (Provia) "; } public String k() { Integer integer = ((j)this.a).k(4624); if (integer == null) return null; int k = integer.intValue(); if (k != 0) { if (k != 16) { if (k != 48) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Unknown ("); stringBuilder.append(integer); stringBuilder.append(")"); return stringBuilder.toString(); } return "B&W"; } return "Chrome"; } return "Standard"; } public String l() { m m = ((j)this.a).n(4113); if (m == null) return null; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(m.a(false)); stringBuilder.append(" EV (Apex)"); return stringBuilder.toString(); } public String m() { return a(4112, new String[] { "Auto", "On", "Off", "Red-eye Reduction", "External" }); } public String n() { return a(4129, new String[] { "Auto Focus", "Manual Focus" }); } public String o() { return a(4865, new String[] { "Good Focus", "Out Of Focus" }); } public String p() { Integer integer = ((j)this.a).k(4110); if (integer == null) return null; int k = integer.intValue(); if (k != 0) { if (k != 256) { if (k != 512) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Unknown ("); stringBuilder.append(integer); stringBuilder.append(")"); return stringBuilder.toString(); } return "Weak"; } return "Strong"; } return "Normal"; } public String q() { return a(4128, new String[] { "Off", "On" }); } public String r() { Integer integer = ((j)this.a).k(4107); if (integer == null) return null; int k = integer.intValue(); if (k != 64) { if (k != 128) { if (k != 256) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Unknown ("); stringBuilder.append(integer); stringBuilder.append(")"); return stringBuilder.toString(); } return "N/A"; } return "Normal"; } return "Low"; } public String s() { Integer integer = ((j)this.a).k(4145); if (integer == null) return null; int k = integer.intValue(); if (k != 27) { if (k != 28) { if (k != 256) { if (k != 512) { if (k != 768) { StringBuilder stringBuilder; switch (k) { default: switch (k) { default: stringBuilder = new StringBuilder(); stringBuilder.append("Unknown ("); stringBuilder.append(integer); stringBuilder.append(")"); return stringBuilder.toString(); case 25: return "Pro Focus"; case 24: return "Pro Low-light"; case 23: return "Night (Tripod)"; case 22: break; } return "Panorama"; case 20: return "Portrait with Skin Correction"; case 19: return "Underwater"; case 18: return "Fireworks"; case 17: return "Snow"; case 16: return "Beach"; case 15: return "Natural Light & Flash"; case 14: return "Text"; case 13: return "Flower"; case 12: return "Party"; case 11: return "Museum"; case 10: return "Sunset"; case 9: return "Beach & Snow"; case 8: return "Anti-blur"; case 7: return "Natural Light"; case 6: return "Program AE"; case 5: return "Night scene"; case 4: return "Sports scene"; case 3: return "Macro"; case 2: return "Landscape scene"; case 1: return "Portrait scene"; case 0: break; } return "Auto"; } return "Manual exposure"; } return "Shutter priority AE"; } return "Aperture priority AE"; } return "Cat Face Detection"; } return "Dog Face Detection"; } public String t() { Integer integer = ((j)this.a).k(4097); if (integer == null) return null; int k = integer.intValue(); if (k != 1) { if (k != 2) { if (k != 3) { if (k != 4) { if (k != 5) { if (k != 130) { if (k != 132) { if (k != 32768) { if (k != 65535) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Unknown ("); stringBuilder.append(integer); stringBuilder.append(")"); return stringBuilder.toString(); } return "N/A"; } return "Film Simulation"; } return "Medium Hard"; } return "Medium Soft"; } return "Hardest"; } return "Hard"; } return "Normal"; } return "Soft"; } return "Softest"; } public String u() { return a(4144, new String[] { "Off", "On" }); } public String v() { Integer integer = ((j)this.a).k(4100); if (integer == null) return null; int k = integer.intValue(); if (k != 0) { if (k != 128) { if (k != 256) { if (k != 384) { if (k != 512) { if (k != 768) { if (k != 32768) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Unknown ("); stringBuilder.append(integer); stringBuilder.append(")"); return stringBuilder.toString(); } return "Film Simulation"; } return "None (B&W)"; } return "Low"; } return "Medium Low"; } return "High"; } return "Medium High"; } return "Normal"; } public String w() { Integer integer = ((j)this.a).k(4098); if (integer == null) return null; int k = integer.intValue(); if (k != 0) { if (k != 256) { if (k != 512) { if (k != 1024) { if (k != 1280) { if (k != 4080) { StringBuilder stringBuilder; switch (k) { default: switch (k) { default: stringBuilder = new StringBuilder(); stringBuilder.append("Unknown ("); stringBuilder.append(integer); stringBuilder.append(")"); return stringBuilder.toString(); case 3844: return "Custom White Balance 5"; case 3843: return "Custom White Balance 4"; case 3842: return "Custom White Balance 3"; case 3841: return "Custom White Balance 2"; case 3840: break; } return "Custom White Balance"; case 772: return "Living Room Warm White Fluorescent"; case 771: return "Warm White Fluorescent"; case 770: return "White Fluorescent"; case 769: return "Day White Fluorescent"; case 768: break; } return "Daylight Fluorescent"; } return "Kelvin"; } return "Flash"; } return "Incandescence"; } return "Cloudy"; } return "Daylight"; } return "Auto"; } } /* Location: /home/yc/Downloads/LeaveHomeSafe.jar!/e/d/c/o/a0/i.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
true
518a36490be61a969561425a865a379e0b74ebf7
Java
chaug2018/web
/com.yzj.ebs.report/src/com/yzj/ebs/report/pojo/EbillResult.java
UTF-8
3,082
2.359375
2
[]
no_license
package com.yzj.ebs.report.pojo; /** * *创建于:2012-11-13<br> *版权所有(C) 2012 深圳市银之杰科技股份有限公司<br> * 机构对账成功率统计结果类,保存统计数据 * @author chenzg * @version 1.0.0 */ public class EbillResult { private String idCenter; //分行 private String idBank; //机构号 private String bankName; //机构名称 private long sendCount; //对账单发出数,按账单 private long backCount; //回收数 private long checkSuccessCount; //余额相符数 private long checkFailCount; //余额不相符数 private long notCheckCount; //尚未核对数 private long ebillSuccessCount;//对账成功数 private String checkSuccessPercent;//对账成功率 private String backPercent; //回收率 public EbillResult(String idCenter, String idBank, String bankName, long sendCount, long backCount, long checkSuccessCount, long checkFailCount, long notCheckCount, long ebillSuccessCount, String checkSuccessPercent, String backPercent) { super(); this.idCenter = idCenter; this.idBank = idBank; this.bankName = bankName; this.sendCount = sendCount; this.backCount = backCount; this.checkSuccessCount = checkSuccessCount; this.checkFailCount = checkFailCount; this.notCheckCount = notCheckCount; this.ebillSuccessCount = ebillSuccessCount; this.checkSuccessPercent = checkSuccessPercent; this.backPercent = backPercent; } public String getIdCenter() { return idCenter; } public void setIdCenter(String idCenter) { this.idCenter = idCenter; } public String getIdBank() { return idBank; } public void setIdBank(String idBank) { this.idBank = idBank; } public String getBankName() { return bankName; } public void setBankName(String bankName) { this.bankName = bankName; } public long getSendCount() { return sendCount; } public void setSendCount(long sendCount) { this.sendCount = sendCount; } public long getBackCount() { return backCount; } public void setBackCount(long backCount) { this.backCount = backCount; } public long getCheckSuccessCount() { return checkSuccessCount; } public void setCheckSuccessCount(long checkSuccessCount) { this.checkSuccessCount = checkSuccessCount; } public long getCheckFailCount() { return checkFailCount; } public void setCheckFailCount(long checkFailCount) { this.checkFailCount = checkFailCount; } public long getNotCheckCount() { return notCheckCount; } public void setNotCheckCount(long notCheckCount) { this.notCheckCount = notCheckCount; } public long getEbillSuccessCount() { return ebillSuccessCount; } public void setEbillSuccessCount(long ebillSuccessCount) { this.ebillSuccessCount = ebillSuccessCount; } public String getCheckSuccessPercent() { return checkSuccessPercent; } public void setCheckSuccessPercent(String checkSuccessPercent) { this.checkSuccessPercent = checkSuccessPercent; } public String getBackPercent() { return backPercent; } public void setBackPercent(String backPercent) { this.backPercent = backPercent; } }
true
3472c1eebad93e9b1ed439af6a548cfc894febff
Java
Chibi-girl/Textreme
/SimpleTextEditor.java
UTF-8
21,060
2.53125
3
[]
no_license
package application; import java.io.*; import java.awt.*; import javax.swing.*; import java.util.*; import java.awt.event.*; import java.awt.font.TextAttribute; import javax.swing.text.DefaultEditorKit.*; import javax.swing.text.*; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.undo.*; import javax.swing.event.*; import javax.swing.plaf.metal.MetalLookAndFeel; import javax.swing.plaf.metal.OceanTheme; class SimpleTextEditor implements ActionListener { JFrame frame,ftable;JTextPane txtarea;JScrollPane scroll;JTable table; JMenuBar menu;JMenu file,edit,exit,view,preferences;Icon lefticon,righticon,centreicon,justifiedicon; JMenuItem newfile,openfile,savefile,undo,redo,saveas,toggle,font,shortcut,copy,cut,paste,view_panel,hide_panel,close,printfile; JPanel panel,controlPanel,buttonpanel;JButton bold,italics,underline,left,right,centre,justified,ok,ok2,cancel;JOptionPane dopen,dquit; JLabel sampleText;JDialog dialog;JComboBox fontComboBox,sizeComboBox;JCheckBox boldCheck, italCheck; String filename=null;String[] fonts;String column[]={"Action","Keyboard shortcut"}; String name; Integer size,b=0,i=0,u=0; String data[][]={ {"New File","Ctrl+N"},{"Open File","Ctrl+O"},{"Print File","Ctrl+P"},{"Save New File","Ctrl+Shift+S"}, {"Save File","Ctrl+S"},{"Cut","Ctrl+X"},{"Copy","Ctrl+C"},{"Paste","Ctrl+V"},{"Undo","Ctrl+Z"},{"Redo","Ctrl+Y"}, {"View Bottom Panel","Ctrl+Shift+V"},{"Hide Bottom Panel","Ctrl+Shift+H"},{"Toggle between light/dark mode","Ctrl+T"}, {"Change text style","Ctrl+F"},{"Exit","Ctrl+Q"},{"Bold","Ctrl+B"},{"Italics","Ctrl+I"},{"Underline","Ctrl+U"}}; Integer[] sizes = { 7, 8, 9, 10, 11, 12, 14, 18, 20, 22, 24, 36 }; UndoManager undomanager=new UndoManager();FontListener fl = new FontListener();Font f; SimpleAttributeSet attribs = new SimpleAttributeSet(); SimpleTextEditor() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { } frame= new JFrame("Untitled Document"); frame.setBounds(100,100,616,444); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ftable=new JFrame("List of Keyboard Shortcuts"); ftable.setBounds(100,100,530,395); ftable.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); txtarea= new JTextPane(); txtarea.setFont(new Font("Chilanka Regular", Font.PLAIN, 20)); txtarea.setBackground(Color.WHITE); txtarea.setForeground(Color.MAGENTA); txtarea.setBounds(200,100,200,100); frame.getContentPane().add(txtarea,BorderLayout.NORTH); scroll= new JScrollPane(txtarea); frame.getContentPane().add(scroll,BorderLayout.CENTER); panel=new JPanel(); panel.setBackground(Color.PINK); panel.setSize(100,100); frame.getContentPane().add(panel,BorderLayout.SOUTH); menu=new JMenuBar(); menu.setMargin(new Insets(5,10,5,10)); menu.setBackground(new java.awt.Color(120,180,255)); frame.getContentPane().add(menu,BorderLayout.NORTH); file=new JMenu("File");edit=new JMenu("Edit");view=new JMenu("Bottom Panel"); preferences=new JMenu("Preferences"); menu.add(file);menu.add(new JMenu("|")).setEnabled(false); menu.add(edit);menu.add(new JMenu("|")).setEnabled(false); menu.add(preferences);menu.add(new JMenu ("|")).setEnabled(false); newfile=new JMenuItem("New");openfile=new JMenuItem("Open");savefile=new JMenuItem("Save"); saveas=new JMenuItem("SaveAs");printfile=new JMenuItem("Print"); view_panel=new JMenuItem("View");hide_panel=new JMenuItem("Hide");shortcut=new JMenuItem("Keyboard Shortcuts"); copy=new JMenuItem("Copy");paste=new JMenuItem("Paste");close=new JMenuItem("Exit"); cut=new JMenuItem("Cut");toggle=new JMenuItem("Toggle view mode");font=new JMenuItem("Fonts"); undo=new JMenuItem("Undo");redo=new JMenuItem("Redo");ok= new JButton("Change selected"); cancel=new JButton ("Cancel");ok2=new JButton("Change entire document"); bold=new JButton("Bold");italics=new JButton("Italics");underline=new JButton("Underline"); righticon=new ImageIcon("right.png");right=new JButton(righticon); lefticon=new ImageIcon("left.png");left=new JButton(lefticon); centreicon=new ImageIcon("centre.png");centre=new JButton(centreicon);justified=new JButton("Justified"); bold.setFont(new Font("Serif", Font.BOLD, 18)); italics.setFont(new Font("Serif", Font.ITALIC, 18)); underline.setFont(new Font("Serif", Font.PLAIN, 18)); Font uf = underline.getFont(); Map attributes = uf.getAttributes(); attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); underline.setFont(uf.deriveFont(attributes)); newfile.addActionListener(this);openfile.addActionListener(this);printfile.addActionListener(this); savefile.addActionListener(this);saveas.addActionListener(this); copy.addActionListener(this);paste.addActionListener(this);cut.addActionListener(this); view_panel.addActionListener(this);hide_panel.addActionListener(this);shortcut.addActionListener(this); undo.addActionListener(this);redo.addActionListener(this); close.addActionListener(this);toggle.addActionListener(this);font.addActionListener(this); bold.addActionListener(new StyledEditorKit.BoldAction());italics.addActionListener(new StyledEditorKit.ItalicAction()); underline.addActionListener(new StyledEditorKit.UnderlineAction()); left.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { StyledDocument doc = txtarea.getStyledDocument(); StyleConstants.setAlignment(attribs , StyleConstants.ALIGN_LEFT); doc.setParagraphAttributes(0, doc.getLength(), attribs, false); } }); right.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { StyledDocument doc = txtarea.getStyledDocument(); StyleConstants.setAlignment(attribs , StyleConstants.ALIGN_RIGHT); doc.setParagraphAttributes(0, doc.getLength(), attribs, false); } }); centre.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { StyledDocument doc = txtarea.getStyledDocument(); StyleConstants.setAlignment(attribs , StyleConstants.ALIGN_CENTER); doc.setParagraphAttributes(0, doc.getLength(), attribs, false); } }); justified.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { StyledDocument doc = txtarea.getStyledDocument(); StyleConstants.setAlignment(attribs , StyleConstants.ALIGN_JUSTIFIED); doc.setParagraphAttributes(0, doc.getLength(), attribs, false); } }); menu.add(close); file.add(newfile);file.addSeparator();file.add(openfile); file.addSeparator();file.add(printfile);file.addSeparator();file.add(savefile); file.addSeparator();view.add(view_panel);view.addSeparator();view.add(hide_panel); preferences.add(view);preferences.addSeparator();file.add(saveas);edit.add(cut);edit.addSeparator(); edit.add(copy);edit.addSeparator();edit.add(paste);edit.addSeparator();edit.add(undo); edit.addSeparator();edit.add(redo);preferences.add(toggle);preferences.addSeparator(); preferences.add(font);preferences.addSeparator();preferences.add(shortcut); panel.add(bold);panel.add(italics);panel.add(underline); panel.add(left);panel.add(centre);panel.add(right); table=new JTable(data,column) { public boolean editCellAt(int row, int column, java.util.EventObject e) { return false; } }; table.setBounds(100,100,500,70); JScrollPane sp=new JScrollPane(table); ftable.add(sp); sampleText= new JLabel(" Sample Text"); dialog = new JDialog(frame,"Select Font"); dialog.add(sampleText, BorderLayout.CENTER); GraphicsEnvironment g = GraphicsEnvironment.getLocalGraphicsEnvironment(); fonts = g.getAvailableFontFamilyNames(); controlPanel = new JPanel(); buttonpanel=new JPanel(); fontComboBox = new JComboBox(fonts);sizeComboBox = new JComboBox(sizes); boldCheck = new JCheckBox("Bold");italCheck = new JCheckBox("Italics"); boldCheck.addActionListener(fl);fontComboBox.addActionListener(fl);ok.addActionListener(this);ok2.addActionListener(this); italCheck.addActionListener(fl);sizeComboBox.addActionListener(fl);cancel.addActionListener(this); controlPanel.add(new JLabel("Family: "));controlPanel.add(new JLabel("Size: ")); sizeComboBox.setSelectedIndex(5); controlPanel.add(fontComboBox);controlPanel.add(sizeComboBox);buttonpanel.add(ok);//buttonpanel.add(ok2); controlPanel.add(boldCheck);controlPanel.add(italCheck);buttonpanel.add(cancel); dialog.add(controlPanel, BorderLayout.SOUTH); dialog.add(buttonpanel,BorderLayout.NORTH); txtarea.getDocument().addUndoableEditListener(new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent e) { undomanager.addEdit(e.getEdit()); } }); txtarea.getActionMap().put("New",new AbstractAction("New") { public void actionPerformed(ActionEvent e) { newFile(); } }); txtarea.getActionMap().put("Open",new AbstractAction("Open") { public void actionPerformed(ActionEvent e) { openFile(); } }); txtarea.getActionMap().put("Print",new AbstractAction("Print") { public void actionPerformed(ActionEvent e) { print(); } }); txtarea.getActionMap().put("SaveAs",new AbstractAction("SaveAs") { public void actionPerformed(ActionEvent e) { saveFile(null); } }); txtarea.getActionMap().put("Save",new AbstractAction("Save") { public void actionPerformed(ActionEvent e) { saveFile(filename); } }); txtarea.getActionMap().put("Undo",new AbstractAction("Undo") { public void actionPerformed(ActionEvent e) { undo(); } }); txtarea.getActionMap().put("Redo",new AbstractAction("Redo") { public void actionPerformed(ActionEvent e) { redo(); } }); txtarea.getActionMap().put("View",new AbstractAction("View") { public void actionPerformed(ActionEvent e) { panel.setVisible(true); } }); txtarea.getActionMap().put("Hide",new AbstractAction("Hide") { public void actionPerformed(ActionEvent e) { panel.setVisible(false); } }); txtarea.getActionMap().put("Toggle",new AbstractAction("Toggle") { public void actionPerformed(ActionEvent e) { toggle(); } }); txtarea.getActionMap().put("Fonts",new AbstractAction("Fonts") { public void actionPerformed(ActionEvent e) { fonts(); } }); txtarea.getActionMap().put("Exit",new AbstractAction("Exit") { public void actionPerformed(ActionEvent e) { exit(); } }); txtarea.getActionMap().put("Bold", new StyledEditorKit.BoldAction()); txtarea.getActionMap().put("Italics", new StyledEditorKit.ItalicAction()); txtarea.getActionMap().put("Underline", new StyledEditorKit.UnderlineAction()); txtarea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control N"), "New"); txtarea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control O"), "Open"); txtarea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control P"), "Print"); txtarea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("shift control S"), "SaveAs"); txtarea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control S"), "Save"); //txtarea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control X"), "Cut"); //txtarea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control C"), "Copy"); //txtarea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control V"), "Paste"); txtarea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control Z"), "Undo"); txtarea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control Y"), "Redo"); txtarea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control shift V"), "View"); txtarea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control shift H"), "Hide"); txtarea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control T"), "Toggle"); txtarea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control F"), "Fonts"); txtarea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control Q"), "Exit"); txtarea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control B"), "Bold"); txtarea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control I"), "Italics"); txtarea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control U"), "Underline"); } public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals("Cut")) { txtarea.cut(); } else if (s.equals("Copy")) { txtarea.copy(); } else if (s.equals("Paste")) { txtarea.paste(); } else if (s.contentEquals("Undo")) { undo(); } else if (s.contentEquals("Redo")) { redo(); } else if (s.equals("Toggle view mode")) { toggle(); } else if (s.contentEquals("Fonts")) { fonts(); } else if (s.contentEquals("Change selected")) { new StyledEditorKit.FontSizeAction("Change",size).actionPerformed(e); new StyledEditorKit.FontFamilyAction("Change", name).actionPerformed(e); if(b==1) new StyledEditorKit.BoldAction().actionPerformed(e); if(i==1) new StyledEditorKit.ItalicAction().actionPerformed(e); dialog.setVisible(false); } /*else if (s.contentEquals("Change entire document")){ txtarea.setFont(f); dialog.setVisible(false); }*/ else if (s.contentEquals("Cancel")) { dialog.setVisible(false); } else if (s.equals(lefticon)) { } else if (s.equals(centreicon)) { StyledDocument doc = txtarea.getStyledDocument(); StyleConstants.setAlignment(attribs , StyleConstants.ALIGN_CENTER); doc.setParagraphAttributes(0, doc.getLength(), attribs, false); } else if (s.contentEquals("Right")) { StyledDocument doc = txtarea.getStyledDocument(); StyleConstants.setAlignment(attribs , StyleConstants.ALIGN_RIGHT); doc.setParagraphAttributes(0, doc.getLength(), attribs, false); } else if (s.contentEquals("Justified")) { StyledDocument doc = txtarea.getStyledDocument(); StyleConstants.setAlignment(attribs , StyleConstants.ALIGN_JUSTIFIED); doc.setParagraphAttributes(0, doc.getLength(), attribs, false); } else if (s.contentEquals("Keyboard Shortcuts")) { ftable.setVisible(true); } else if (s.equals("Exit")) { exit(); } else if (s.equals("New")) { newFile(); } else if (s.equals("View")) { panel.setVisible(true); } else if (s.equals("Hide")) { panel.setVisible(false); } else if (s.equals("Open")) { openFile(); } else if (s.equals("SaveAs")) { saveFile(null); } else if(s.equals("Save")) { saveFile(filename); } else if (s.equals("Print")) { print(); } } private void undo() { try { if (undomanager.canUndo()) { undomanager.undo(); } } catch (CannotUndoException ex) { } } private void redo() { try { if (undomanager.canRedo()) { undomanager.redo(); } } catch (CannotRedoException ex) { } } private void fonts() { dialog.setSize(620, 200); dialog.setLocationRelativeTo(null); dialog.setVisible(true); } private void toggle() { if(txtarea.getBackground()==Color.WHITE) { txtarea.setBackground(Color.DARK_GRAY); txtarea.setForeground(Color.CYAN); panel.setBackground(Color.LIGHT_GRAY); menu.setBackground(Color.LIGHT_GRAY); } else { txtarea.setBackground(Color.WHITE); txtarea.setForeground(Color.MAGENTA); panel.setBackground(Color.PINK); menu.setBackground(new java.awt.Color(120,180,255)); } } private void newFile() { Object stringArray[] = { "Sure", "No. I'd like to change/save" }; int response=JOptionPane.showOptionDialog(frame, "You're about to delete this text. Continue?", "Select an Option", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,null, stringArray,stringArray[0]); if (response == JOptionPane.YES_OPTION) { txtarea.setText(""); filename=null; frame.setTitle("Untitled Document"); } } private void openFile() { JFileChooser j = new JFileChooser("/home/aishwarya"); int r = j.showOpenDialog(null); // If the user selects a file if (r == JFileChooser.APPROVE_OPTION) { // Set the label to the path of the selected directory filename=j.getSelectedFile().getAbsolutePath(); String name=j.getSelectedFile().getName(); File fi = new File(filename); try { String s1 = "", sl = ""; BufferedReader br = new BufferedReader(new FileReader(fi)); sl = br.readLine(); while ((s1 = br.readLine()) != null) { sl = sl + "\n" + s1; } //StyledDocument doc1 = fi.getStyledDocument(); //StyleConstants.setAlignment(attribs , StyleConstants.ALIGN_JUSTIFIED); //doc.setParagraphAttributes(0, doc.getLength(), attribs, false); txtarea.setText(sl); frame.setTitle(name); } catch (Exception evt) { JOptionPane.showMessageDialog(frame, evt.getMessage()); } } } private void print() { try { txtarea.print(); } catch (Exception evt) { JOptionPane.showMessageDialog(frame, evt.getMessage()); } } private void saveFile(String name) { if (name == null) { // get filename from user JFileChooser fc = new JFileChooser(); if (fc.showSaveDialog(null) != JFileChooser.CANCEL_OPTION) name = fc.getSelectedFile().getAbsolutePath(); String setname=fc.getSelectedFile().getName(); frame.setTitle(setname); } if (name != null) { try { Formatter out = new Formatter(new File(name)); filename = name; out.format("%s", txtarea.getText()); out.close(); JOptionPane.showMessageDialog(null, "Saved to " + filename, "Save File", JOptionPane.PLAIN_MESSAGE); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, "Cannot write to file: " + name, "Error", JOptionPane.ERROR_MESSAGE); } } } private void exit() { Object stringArray[] = { "Sure", "No. I'd like to change/save" }; int response=JOptionPane.showOptionDialog(frame, "You're about to exit. Continue?", "Select an Option", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,null, stringArray,stringArray[0]); if (response == JOptionPane.YES_OPTION) { frame.setVisible(false); } } private class FontListener implements ActionListener { public void actionPerformed(ActionEvent e) { updateText(); } public void updateText() { name = (String) fontComboBox.getSelectedItem(); b=0;i=0;u=1; size = (Integer) sizeComboBox.getSelectedItem(); int style; if (boldCheck.isSelected() && italCheck.isSelected()) { style = Font.BOLD | Font.ITALIC; b=1; i=1; } else if (boldCheck.isSelected()) { style = Font.BOLD; b=1; } else if (italCheck.isSelected()) { style = Font.ITALIC; i=1; } else style = Font.PLAIN; f = new Font(name, style, size.intValue()); sampleText.setFont(f); } } public static void main(String[] args) { SimpleTextEditor window = new SimpleTextEditor(); window.frame.setLocationRelativeTo(null); window.ftable.setLocationRelativeTo(null); window.frame.setVisible(true); } }
true
55d5975664f0872c572daaff6c6c0d4747f268db
Java
dealexce/STARGYM
/src/UI/Controller/AllTrainersController.java
UTF-8
3,990
2.640625
3
[]
no_license
package UI.Controller; import Data.Course; import Data.Trainer; import Service.SearchService; import UI.Page; import UI.Path; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.Line; import javafx.scene.shape.TriangleMesh; import javafx.scene.text.Font; import javafx.scene.control.*; import java.io.File; import java.util.List; /** * @description: Controller of AllTrainersPage * @author: Haopu Chen **/ public class AllTrainersController extends Page { @FXML private VBox trainerBox; @FXML private TextField searchWord; @Override public String getLocalPath() { return Path.ALLTRAINERS; } @Override public void init() { genTrainerBox(this.stageManager.getDataService().getAllTrainer()); } @FXML void search(){ List<Trainer> trainers = SearchService.searchTrainer(searchWord.getText(),this.stageManager.getDataService().getAllTrainer()); genTrainerBox(trainers); } private void genTrainerBox(List<Trainer> trainers){ trainerBox.getChildren().clear(); for(Trainer trainer:trainers){ BorderPane bp = new BorderPane(); bp.setPrefSize(600,100); bp.setMinSize(600,100); bp.setStyle("-fx-border-color: lightgrey; -fx-background-color: FCFCFC;"); String url = Path.RESOURCE+ File.separator+"Trainers"+File.separator+"T1.png"; javafx.scene.image.Image img = new Image("file:"+url); ImageView imgv = new ImageView(img); imgv.setFitHeight(80); imgv.setFitWidth(80); imgv.setPreserveRatio(false); imgv.setPickOnBounds(true); bp.setLeft(imgv); BorderPane.setAlignment(imgv, Pos.CENTER); VBox vb = new VBox(); vb.setPrefSize(100,200); Label lbl = new Label(trainer.getUserName()); lbl.setFont(Font.font(23)); Line line = new Line(); line.setStartX(-100); line.setEndX(100); Label lbl2 = new Label("Level "+ trainer.getLevel()); lbl2.setTextFill(Color.BLUE); Label lbl3 = new Label(trainer.getIntroduction()); vb.getChildren().addAll(lbl,lbl2,lbl3); vb.setAlignment(Pos.CENTER_LEFT); BorderPane.setMargin(vb,new Insets(10)); BorderPane.setAlignment(vb, Pos.CENTER); bp.setCenter(vb); VBox vb2 = new VBox(); vb2.setPrefSize(100,200); vb2.setSpacing(5); Button btn = new Button("Book"); btn.setOnMouseClicked(e->book(trainer)); btn.setPrefWidth(70); Button btn2 = new Button("Like"); btn2.setOnMouseClicked(e->like(trainer)); btn2.setPrefWidth(70); vb2.getChildren().addAll(btn,btn2); vb2.setAlignment(Pos.CENTER_RIGHT); bp.setRight(vb2); bp.setPadding(new Insets(20)); trainerBox.getChildren().add(bp); } } private void like(Trainer trainer){ if(this.stageManager.getDataService().getTrainee()!=null){ this.stageManager.getDataService().traineeAddTrainer(trainer.getUserId()); notice("Success","You like this trainer! You can see this trainer in your personal page then.", Alert.AlertType.INFORMATION); }else{ notice("Fail","Only members can like a course. Please login as a member first.", Alert.AlertType.WARNING); } } public void goHome(){ this.stageManager.stageRedirect(getLocalPath(),Path.HOME); } public void book(Trainer trainer){ this.stageManager.openStage(Path.EXERCISEARRANGE,trainer); } }
true
7b790e7cd7a1c7fa93fe5d30930c22e7f38f21a6
Java
ishawagh19/CS680
/HW8/test/src/edu/umb/cs680/hw08/FileTest.java
UTF-8
2,699
2.71875
3
[]
no_license
package edu.umb.cs680.hw08; import static org.junit.jupiter.api.Assertions.*; import java.time.LocalDateTime; import java.util.Arrays; import org.junit.jupiter.api.Test; class FileTest { LocalDateTime date = LocalDateTime.now(); Directory root = new Directory( "root", 0, date,null); Directory home = new Directory( "home", 0, date,root); Directory code = new Directory( "code", 0, date,home); Directory applications = new Directory( "applications", 0, date,root); File a = new File( "a", 100, date,applications); File b = new File( "b", 200, date,applications); File c = new File( "c", 300, date,home); File d = new File( "d", 400, date,home); File e = new File( "e", 500, date,code); File f = new File( "f", 600, date,code); private String[] fileToString(File file) { String parentName = null; Directory parent = file.getParent(); if (parent != null) { parentName = parent.getName(); } String[] fileInfo = { file.getName(), Integer.toString(f.getSize()),Boolean.toString(file.isDirectory()), file.getCreationTime().toString(),parentName }; return fileInfo; } @Test void verify_FileF() { String[] expected = { "f", "600","false", date.toString(), "code" }; File actual = f; assertArrayEquals(expected, fileToString(actual)); } @Test void error_FileA() { String[] expected = { "a", "80","true", date.toString(), "applications" }; File actual = a; assertFalse(Arrays.deepEquals(expected, fileToString(actual)) ); } @Test void error_FileB() { String[] expected = { "i", "200", "false",date.toString(), "home" }; File actual = b; assertFalse(Arrays.deepEquals(expected, fileToString(actual)) ); } @Test void error_FileC() { String[] expected = { "w", "30","false", date.toString(), "home" }; File actual = c; assertFalse(Arrays.deepEquals(expected, fileToString(actual)) ); } @Test void error_FileD() { String[] expected = { "d", "40","false", date.toString(), "code" }; File actual = d; assertFalse(Arrays.deepEquals(expected, fileToString(actual)) ); } @Test void error_FileE() { String[] expected = { "y", "500","false", date.toString(), "code" }; File actual = e; assertFalse(Arrays.deepEquals(expected, fileToString(actual)) ); } @Test void error_FileF() { String[] expected = { "f", "600","true", date.toString(), "code" }; File actual = f; assertFalse(Arrays.deepEquals(expected, fileToString(actual)) ); } }
true
f89c3ebc0bd4116e77eddb0b1004630f453a0fbb
Java
DavidSembroiz/Knowledge-Manager
/src/building/Room.java
UTF-8
7,702
2.609375
3
[]
no_license
package building; import behaviour.Person; import data.Schedule; import data.SchedulesDB; import domain.Debugger; import entity.*; import iot.Manager; import iot.Sensor; import rule_headers.RuleManager; import java.util.ArrayList; import java.util.HashSet; public class Room { private String location; private String size; private Building.ROOM_TYPE type; private ArrayList<Sensor> sensors; private RuleManager ruleManager; private ArrayList<Person> peopleActing; private ArrayList<Person> peopleComing; private HashSet<Object> entities; private Schedule schedule; public Room(String location, String size, String type) { this.location = location; this.size = size; this.type = Building.ROOM_TYPE.valueOf(type.toUpperCase()); sensors = new ArrayList<>(); this.entities = new HashSet<>(); this.ruleManager = new RuleManager(this); this.peopleActing = new ArrayList<>(); this.peopleComing = new ArrayList<>(); this.schedule = new Schedule(location, new ArrayList<>()); } public void addTimeToSchedule(String elementId, int time, String st) { schedule.addTimeToSchedule(elementId, time, st); } Schedule getSchedule() { return schedule; } public String getLocation() { return location; } public ArrayList<Sensor> getSensors() { return sensors; } public Building.ROOM_TYPE getType() { return type; } public boolean sensorExists(String soID, String type) { for (Sensor s : sensors) { if (s.getSoID().equals(soID) && s.getType().equals(type)) return true; } return false; } public Sensor getSensor(String soID, String type) { for (Sensor s : sensors) { if (s.getSoID().equals(soID) && s.getType().toLowerCase().equals(type)) return s; } return null; } void fireRules() { ruleManager.fireRules(); } public void addSensor(ArrayList<Sensor> s) { for (Sensor sen : s) sensors.add(sen); } public String getSize() { return size; } public Sensor fetchSensor(String id, String type) { for (Sensor s : sensors) { /* * Currently comparing with type, but model needs to be compared * with id so multiple sensors of same type are compatible */ if (s.getId().toLowerCase().equals(id) && s.getType().toLowerCase().equals(type)) return s; } return null; } public void addEntity(String type, String qtt) { switch(type) { case "computer": for (int i = 0; i < Integer.parseInt(qtt); ++i) entities.add(new Computer(i)); break; case "lamp": for (int i = 0; i < Integer.parseInt(qtt); ++i) entities.add(new Lamp(i)); break; case "hvac": for (int i = 0; i < Integer.parseInt(qtt); ++i) entities.add(new HVAC(i)); break; case "door": for (int i = 0; i < Integer.parseInt(qtt); ++i) ruleManager.addDoorRule(new Door(i)); break; case "window": for (int i = 0; i < Integer.parseInt(qtt); ++i) entities.add(new Window(i)); break; default: break; } } public void addRules() { for (Object e : entities) { if (e instanceof HVAC) { Window w = findUnassignedWindow(); if (w != null) ruleManager.addHVACRule((HVAC) e, w); } else if (e instanceof Computer) ruleManager.addComputerRule((Computer) e); else if (e instanceof Lamp) ruleManager.addLampRule((Lamp) e); else if (e instanceof Window) ruleManager.addWindowRule((Window) e); else if (e instanceof Door) ruleManager.addDoorRule((Door) e); } } private Window findUnassignedWindow() { return (Window) entities.stream().filter(o -> o instanceof Window).filter(o -> !((Window) o).isAssigned()).findFirst().orElse(null); } HashSet<Object> getEntities() { return entities; } public ArrayList<Person> getPeopleActing() { return peopleActing; } void removePerson(Person p) { if (peopleActing.contains(p)) peopleActing.remove(p); else if (peopleComing.contains(p)) peopleComing.remove(p); } void addPerson(Person p) { peopleComing.add(p); } public boolean arePeopleComing(int threshold) { return peopleComing.stream().anyMatch(p -> p.getNextActionSteps() < threshold); } public boolean arePeopleInside() { return peopleActing.size() > 0; } public boolean isEmpty() { return peopleActing.size() == 0 && peopleComing.size() == 0; } public void shiftPerson(Person p) { if (peopleComing.contains(p)) { if (Debugger.isEnabled()) Debugger.log("Person " + p.getName() + " shifted to ACTING " + this.getLocation()); peopleComing.remove(p); peopleActing.add(p); } } public boolean isAvailable() { return peopleActing.size() + peopleComing.size() < type.getLimit(); } void saveSchedule() { SchedulesDB.getInstance().save(schedule); } void insertSchedule(Schedule s) { this.schedule = s; } void performActuation(String element, int index, String value) { if (element.toLowerCase().equals("computer")) { for (Object e : entities) { if (e instanceof Computer && ((Computer) e).getId() == index) { ((Computer) e).setCurrentState(Computer.State.valueOf(value)); ((Computer) e).setTimeChanged(Manager.CURRENT_STEP); return; } } } else if (element.toLowerCase().equals("hvac")) { for (Object e : entities) { if (e instanceof HVAC && ((HVAC) e).getId() == index) { ((HVAC) e).setCurrentState(HVAC.State.valueOf(value)); ((HVAC) e).setTimeChanged(Manager.CURRENT_STEP); return; } } } else if (element.toLowerCase().equals("lamp")) { for (Object e : entities) { if (e instanceof Lamp && ((Lamp) e).getId() == index) { ((Lamp) e).setCurrentState(Lamp.State.valueOf(value)); ((Lamp) e).setTimeChanged(Manager.CURRENT_STEP); return; } } } } public double getTemperature() { for (Sensor s : sensors) { if (s.getType().equals("temperature")) { double res = Double.parseDouble(s.getValue()); if (res > 0) return res; } } return 0; } public double getLuminosity() { for (Sensor s : sensors) { if (s.getType().equals("luminosity")) { double res = Double.parseDouble(s.getValue()); if (res > 0) return res; } } return 0; } public Computer.State getUsedComputer(String name) { for (Object o : entities) { if (o instanceof Computer) { Person p = ((Computer) o).getUsedBy(); if (p != null && p.getName().equals(name)) { return ((Computer) o).getCurrentState(); } } } return null; } public void adjustSchedule(int jump, Person p) { schedule.adjustSchedule(jump, p); } }
true
ec7eaecedf5eef0af7a2b724f974f077a5321b73
Java
Digits88/affiliateproducts
/affiliateproductsapp/app/models/Brand.java
UTF-8
1,395
2.34375
2
[]
no_license
package models; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; @Entity @Table(name = "AFFILIATE_BRAND") public class Brand extends VersionedEntity { private static final long serialVersionUID = 2L; public static final String CACHE_PREFIX = Brand.class.getSimpleName(); @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "name") private String name; @Column(name = "image_url") private String imageUrl; @Column(name = "local_image_url") private String localImageUrl; public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getLocalImageUrl() { return localImageUrl; } public void setLocalImageUrl(String localImageUrl) { this.localImageUrl = localImageUrl; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Brand(String name) { this.name = name; } @Override public String toString() { return "Brand [id=" + id + ", name=" + name + "]"; } }
true
2471426079b99718d3d757e68a91a80c5b3be74a
Java
snabu/cybersecurity-base
/src/main/java/sec/project/controller/SearchController.java
UTF-8
1,940
2.421875
2
[]
no_license
package sec.project.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import sec.project.domain.Message; import java.security.Principal; import java.sql.*; import java.util.ArrayList; @Controller public class SearchController { @RequestMapping(value = "/searchform", method = RequestMethod.GET) public String searchForm() { return "searchform"; } @RequestMapping(value = "/search", method = RequestMethod.GET) public String search(Principal principal, Model model, @RequestParam("searchterm") String searchString) { ArrayList msgList = new ArrayList(); try { Class.forName("org.h2.Driver"); Connection conn = DriverManager.getConnection("jdbc:h2:mem:testdb", "sa", ""); Statement stmnt = conn.createStatement(); //String sql = "SELECT subject,message FROM message WHERE subject='" + searchString + "'"; String sql = "SELECT subject,message FROM message WHERE (author= '" + principal.getName() + "' OR recipient= '" + principal.getName() + "') AND message LIKE '%" + searchString + "%'"; System.out.println(sql); ResultSet rs = stmnt.executeQuery(sql); while (rs.next()) { String subject = rs.getString("subject"); String message = rs.getString("message"); Message msg = new Message(); msg.setSubject(subject); msg.setMessage(message); msgList.add(msg); } conn.close(); } catch (Exception e) { e.printStackTrace(); } model.addAttribute("messages", msgList); return "searchresult"; } }
true
aaf5497fbefba0bff65a7a01a4560d0e6e017641
Java
king-code0212/LiBlog
/li_blog_xo/src/main/java/com/steel/li_blog_xo/mapper/SysDictDataMapper.java
UTF-8
324
1.625
2
[]
no_license
package com.steel.li_blog_xo.mapper; import com.steel.li_blog_base.mapper.SuperMapper; import com.steel.li_blog_common.entity.SysDictData; /** * <p> * 字典数据 Mapper 接口 * </p> * * @author 陌溪 * @since 2020年2月15日21:01:50 */ public interface SysDictDataMapper extends SuperMapper<SysDictData> { }
true
0ab7a34e02eb3af2a05b55735a623d7fe848eccd
Java
athakore/java-collections-presentation-assignment-athakore
/src/com/cooksys/ftd/assignments/objects/Pizza.java
UTF-8
1,606
3.46875
3
[]
no_license
package com.cooksys.ftd.assignments.objects; public class Pizza { private String[] toppings; private String sauce; private int cookTime; public Pizza() { this.toppings = new String[]{"O-Cheese!"}; this.sauce = "marinara"; this.cookTime = 0; } public Pizza(String[] toppings, String sauce) { this.toppings = toppings; this.sauce = sauce; this.cookTime = 0; } public String[] getToppings() { return toppings; } public void setToppings(String[] toppings) { this.toppings = toppings; } public String getSauce() { return sauce; } public void setSauce(String sauce) { this.sauce = sauce; } public int getCookTime() { return cookTime; } public void setCookTime(int cookTime) { this.cookTime = cookTime; } public void Cook() { this.cookTime++; } public String Cooked() { String result = ""; for(int i = 0; i < toppings.length; i++) { if( i < toppings.length - 1) result += toppings[i] + ", "; else if(i == toppings.length - 1 && toppings.length != 1) result += "and " + toppings[i]; else result += toppings[i]; } result += " pizza with " + sauce + " sauce is done cooking!"; return result; } public String toString() { String result = ""; for(int i = 0; i < toppings.length; i++) { if( i < toppings.length - 1) result += toppings[i] + ", "; else if(i == toppings.length - 1 && toppings.length != 1) result += "and " + toppings[i]; else result += toppings[i]; } result += " pizza with " + sauce + " sauce has been cooking for " + cookTime + " minutes."; return result; } }
true
24c24555e8cd2dec634f17d922f52c39759f8e41
Java
vtamas00/bme-sztech-alkesz
/src/control/GameState.java
UTF-8
1,313
3.109375
3
[]
no_license
/** * */ package control; import java.util.ArrayList; /** * @author chaah * * This Calss contains every data releated to the game. * */ public class GameState { public enum Game_Type{ eSinglePlayer, eMultiPlayer, eDeveloper } public enum Game_Control_Events{ } public ArrayList<Food_Drink> FallingObjects; /* List for the objects */ public Player Plato; /* The player who has to catch the objects */ public Game_Type eGameType; /* Gma type of the current game */ public Game_Control_Events eEvents; /* Every event that changes the course of the game */ public GameState( String myName, Game_Type eGameType ) { this.eGameType = eGameType; this.Plato = new Player( myName ); this.FallingObjects = new ArrayList<Food_Drink>(); } /** * @param fallingObjects * the fallingObjects to set */ public void addFallingObjects(final Food_Drink fallingObjects) { FallingObjects.add(fallingObjects); } /** * @return the fallingObjects */ public ArrayList<Food_Drink> getFallingObjects() { return FallingObjects; } /** * @return the plato */ public Player getPlato() { return Plato; } @Override public String toString() { return "GameState [FallingObjects=" + FallingObjects + ", Plato=" + Plato + ", eGameType=" + eGameType + "]"; } }
true
b697ca54fc99669934fdca77503bea9e0dbb9075
Java
Kminttech/UWL-Work
/Misc/Lab6/src/Main.java
UTF-8
2,026
3.84375
4
[]
no_license
import java.io.File; import java.io.IOException; import java.util.Scanner; /** * Lab Assignment 06: This file will load data from an input file into a * hash-table, then print out some results. * * @author M. Allen * @author Kevin Minter * */ public class Main { /** * Does some sample hashing on a few vehicles, then runs loadHash(). */ private void procVehicles() { Vehicle[] vhs = { new Vehicle( "Chevy", "Tahoe", 2001, 25000 ), new Vehicle( "Chevy", "Tahoe", 2001, 11000 ), new Vehicle( "Chevy", "Tahoe", 2002, 25000 ) }; System.out.println(); for ( int v1 = 0; v1 < vhs.length; v1++ ) for ( int v2 = 0; v2 < vhs.length; v2++ ) System.out.println( vhs[v1] + " equals " + vhs[v2] + " => " + vhs[v1].equals( vhs[v2] ) ); System.out.println(); for ( int v1 = 0; v1 < vhs.length; v1++ ) System.out.println( "Hashing: " + vhs[v1] + " => " + vhs[v1].hashCode() ); System.out.println(); loadHash( "database.txt" ); } /** * Method to be filled in later. * * @param fileInput Text-file to read data from. */ private void loadHash( String fileInput ) { SeparateChainingHashTable<Vehicle> table = new SeparateChainingHashTable(); try{ File input = new File(fileInput); Scanner parcer = new Scanner(input); while(parcer.hasNextLine()){ table.insert(new Vehicle(parcer.next(),parcer.next(),parcer.nextInt(),parcer.nextInt())); } parcer.close(); }catch(IOException ex){ System.out.println("Error with File"); } System.out.println(table.size()); table.printTable(); } /** * Simple initiating method. * * @param args Not used. */ public static void main( String[] args ) { final Main m = new Main(); m.procVehicles(); } }
true
cd4c45ce773777b26137f1b3af682ea63cc71aad
Java
palmurugan/loki-invoice
/way2invoice/src/main/java/com/way2invoice/bms/config/TenantStore.java
UTF-8
583
2.34375
2
[]
no_license
package com.way2invoice.bms.config; /** * @author palmuruganc * <p> * The store to keep the tenant information based on each request */ public class TenantStore { private static final Long DEFAULT_TENANT_ID = 1L; private static final ThreadLocal<Long> TENANT_CONTEXT = new ThreadLocal<>(); public static void clear() { TENANT_CONTEXT.remove(); } public static Long getTenantId() { return TENANT_CONTEXT.get() == null ? DEFAULT_TENANT_ID : TENANT_CONTEXT.get(); } public static void setTenantId(Long tenantId) { TENANT_CONTEXT.set(tenantId); } }
true
7092e14ee615e2a566b75a356310a28674b554b6
Java
mountsdigital/delivery_userapp
/app/src/main/java/com/mounts/lenovo/delivery3/response/RegisterResponse.java
UTF-8
367
1.640625
2
[]
no_license
package com.mounts.lenovo.delivery3.response; import com.google.gson.annotations.SerializedName; public class RegisterResponse { @SerializedName("isSuccess") public Boolean isSuccess; @SerializedName("user_id") public int id; @SerializedName("sessionId") public String sessionId; @SerializedName("errors") public String errors; }
true
e6d51744e7bd405f2083d888d152ce98ba9005c8
Java
ravitejasrt/mytest
/HibernatePaginationExample/src/com/nareshit/util/PaginationConstants.java
UTF-8
116
1.5625
2
[]
no_license
package com.nareshit.util; public class PaginationConstants { public static final Integer CONST_MAX_ROWS=4; }
true
92d353e92498fdd9ac879495df5b4982ab523ea0
Java
anszhao/online-test-platform
/agent/src/main/java/com/taobao/qa/ruleengine/statical/IStatic.java
UTF-8
453
1.796875
2
[ "Apache-2.0" ]
permissive
package com.taobao.qa.ruleengine.statical; import com.taobao.qa.ruleengine.core.RedisConfig; import redis.clients.jedis.Jedis; import java.util.LinkedHashMap; import java.util.LinkedList; public interface IStatic { // 更新redis数据 //public void updateRedis(Jedis jedis, String prefix_key,LinkedList<LinkedHashMap<String,String>> adlist); public void updateRedis(RedisConfig redisConfig, String prefix_key, Object obj, String url); }
true
ff05c19dabf08420a1f5895103d604c7acb8d5c0
Java
StylesTrip/word-search
/src/main/java/com/ryan/kata/parser/InputParser.java
UTF-8
504
2.671875
3
[]
no_license
package com.ryan.kata.parser; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class InputParser { public List<String> parseHeader(String filePath) throws IOException { List<String> headerWords = new ArrayList<>(); String header = Files.lines(Paths.get(filePath)) .findFirst() .get(); headerWords.add(header); return headerWords; } }
true
fc7356c1097632f707361d7613daf37fae3f868e
Java
wenjiangit/ArtInterview
/app/src/main/java/com/wenjian/artinterview/activity/LifecycleComponent.java
UTF-8
759
2.078125
2
[]
no_license
package com.wenjian.artinterview.activity; import android.arch.lifecycle.Lifecycle; import android.arch.lifecycle.LifecycleObserver; import android.arch.lifecycle.OnLifecycleEvent; /** * Description LifecycleComponent * <p> * Date 2019-07-01 * * @author wenjianes@163.com */ public interface LifecycleComponent extends LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) void onCreate(); @OnLifecycleEvent(Lifecycle.Event.ON_START) void onStart(); @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) void onResume(); @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) void onPause(); @OnLifecycleEvent(Lifecycle.Event.ON_STOP) void onStop(); @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) void onDestroy(); }
true
04c994cc96bb8c4a32e87adbc150c6ecb27630d7
Java
CShiru/retrofit
/retrofit/src/test/java/retrofit2/StringConverterTest.java
UTF-8
3,538
2.140625
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package retrofit2; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static junit.framework.TestCase.assertTrue; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.core.StringContains.containsString; import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.lang.reflect.Type; import java.util.concurrent.atomic.AtomicReference; import okhttp3.ResponseBody; import okhttp3.mockwebserver.MockWebServer; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import retrofit2.http.GET; import retrofit2.http.Query; public final class StringConverterTest { @Rule public final MockWebServer server = new MockWebServer(); @Rule public ExpectedException exception = ExpectedException.none(); interface Annotated { @GET("/") Call<ResponseBody> queryString(@Query("word") String word); @GET("/") Call<ResponseBody> queryObject(@Foo @Query("foo") Object foo); @Target({PARAMETER, METHOD}) @Retention(RUNTIME) @interface Foo {} } @Test public void queryObjectWithStringConverter() { final AtomicReference<Annotation[]> annotationsRef = new AtomicReference<>(); class MyConverterFactory extends Converter.Factory { @Override public Converter<?, String> stringConverter( Type type, Annotation[] annotations, Retrofit retrofit) { annotationsRef.set(annotations); return (Converter<Object, String>) String::valueOf; } } Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .addConverterFactory(new MyConverterFactory()) .build(); Annotated annotated = retrofit.create(Annotated.class); annotated.queryObject(null); // Trigger internal setup. Annotation[] annotations = annotationsRef.get(); assertThat(annotations).hasAtLeastOneElementOfType(Annotated.Foo.class); } @Test public void queryObjectWithoutStringConverter() { exception.expect(IllegalArgumentException.class); exception.expectMessage( containsString( "Unable to create @Query converter for class java.lang.Object (parameter #1)")); Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build(); Annotated annotated = retrofit.create(Annotated.class); annotated.queryObject(null); // Trigger internal setup. } @Test public void queryStringWithoutStringConverter() { Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build(); Annotated annotated = retrofit.create(Annotated.class); try { annotated.queryString(null); // Trigger internal setup. assertTrue(true); } catch (Exception e) { assertTrue(false); } } }
true
49bc4ce296a5998181c80c1e811392a3dcba05a2
Java
X4TKC/PatronesDeDiseno
/src/main/java/TercerParcialClase/Ejercicios/Adapter/Celular.java
UTF-8
475
3.09375
3
[]
no_license
package TercerParcialClase.Ejercicios.Adapter; public class Celular implements IArtefactosEA { private int precio; private int tiempo; public Celular(int precio, int tiempo){ this.precio=precio; this.tiempo=tiempo; } @Override public void precio() { System.out.println("El precio es "+precio+"$ "); } @Override public void tiempoDeVida() { System.out.println("Tiempo de vida de "+tiempo+" anos "); } }
true
68861684d57fc4eb582080a041bc93ad5077f830
Java
vuthaihoa123/KLTN_Face
/app/src/main/java/uet/kltn/hoavt_58/crazyexface/interfaces/OnGroupingListener.java
UTF-8
345
1.609375
2
[]
no_license
package uet.kltn.hoavt_58.crazyexface.interfaces; import android.graphics.Bitmap; import com.microsoft.projectoxford.face.contract.GroupResult; import java.util.ArrayList; /** * Created by vutha on 4/14/2017. */ public interface OnGroupingListener { void onGroupingDone(GroupResult result, ArrayList<Bitmap> thumbs); }
true
473b5cba3290d3e8aeb2b955b0fdee35394c2afb
Java
soni112/planting-profits-private
/src/main/java/com/decipher/agriculture/farmreport/ReportTemplate.java
UTF-8
9,558
2.53125
3
[]
no_license
package com.decipher.agriculture.farmreport; import com.itextpdf.text.*; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; /** * Created by Satan on 11/29/2015. */ public class ReportTemplate { public static final Font[] FONT = new Font[7]; public static final Font TIMESROMAN_14_BOLD = new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.BOLD); public static final Font TIMESROMAN_14_BOLD_RED = new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.BOLD, BaseColor.RED); public static final Font TIMESROMAN_14_NORMAL = new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.NORMAL); public static final Font TIMESROMAN_12_NORMAL = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL); public static final Font TIMESROMAN_10_NORMAL = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.NORMAL); public static final Font TIMESROMAN_10_BOLD = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.BOLD); public static final Font TIMESROMAN_12_BOLD = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD); public static final Font TIMESROMAN_8_NORMAL = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.NORMAL); public static final Font TIMESROMAN_8_BOLD = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.BOLD); static { FONT[0] = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL); FONT[1] = new Font(Font.FontFamily.HELVETICA, 20, Font.BOLD); FONT[2] = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.BOLD); FONT[3] = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.BOLD); FONT[4] = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.NORMAL); FONT[5] = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.NORMAL); FONT[6] = new Font(Font.FontFamily.HELVETICA, 9, Font.ITALIC); } public static class CellBuilder { public static PdfPCell getTableCell() { PdfPCell cell = new PdfPCell(); return cell; } public static PdfPCell setBorder(PdfPCell cell, int border, float borderWidth, float left, float right, float top, float bottom, boolean useBorderPadding) { setBorder(cell, border, borderWidth, left, right, top, bottom); cell.setUseBorderPadding(useBorderPadding); return cell; } public static PdfPCell setBorder(PdfPCell cell, int border, float borderWidth, float left, float right, float top, float bottom) { setBorder(cell, border, borderWidth, left, right, top); cell.setBorderWidthBottom(bottom); return cell; } public static PdfPCell setBorder(PdfPCell cell, int border, float borderWidth, float left, float right, float top) { setBorder(cell, border, borderWidth, left, right); cell.setBorderWidthTop(top); return cell; } public static PdfPCell setBorder(PdfPCell cell, int border, float borderWidth, float left, float right) { setBorder(cell, border, borderWidth, left); cell.setBorderWidthRight(right); return cell; } public static PdfPCell setBorder(PdfPCell cell, int border, float borderWidth, float left) { setBorder(cell, border, borderWidth); cell.setBorderWidthLeft(left); return cell; } public static PdfPCell setBorder(PdfPCell cell, int border, float borderWidth) { setBorder(cell, border); cell.setBorderWidth(borderWidth); return cell; } public static PdfPCell setBorder(PdfPCell cell, int border) { cell.setBorder(border); return cell; } } public static class NoBorderNoHeaderTable { public static PdfPCell getDataCell(String text){ PdfPCell cell = new PdfPCell(new Phrase(text, ReportTemplate.TIMESROMAN_8_NORMAL)); cell.setUseBorderPadding(false); cell.setBorderWidth(0); return cell; } public static PdfPCell getEmptyCell(){ PdfPCell cell = new PdfPCell(); cell.setUseBorderPadding(false); cell.setBorderWidth(0); return cell; } } public static class BoldHeaderBottomBorderTable { public static PdfPCell getHeaderCell(String text){ PdfPCell cell = new PdfPCell(new Phrase(text, ReportTemplate.TIMESROMAN_8_BOLD)); cell.setUseBorderPadding(true); cell.setBorderWidth(0); cell.setBorderWidthBottom(1); return cell; } public static PdfPCell getDataCell(String text){ PdfPCell cell = new PdfPCell(new Phrase(text, ReportTemplate.TIMESROMAN_8_NORMAL)); cell.setUseBorderPadding(true); cell.setBorderWidth(0); return cell; } } public static class BoldHeaderBoxBorderTable{ public static PdfPCell getHeaderCell(String text){ PdfPCell cell = new PdfPCell(new Phrase(text, ReportTemplate.TIMESROMAN_8_BOLD)); cell.setUseBorderPadding(true); cell.setBorderWidth(1); cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); cell.setVerticalAlignment(PdfPCell.ALIGN_CENTER); cell.setBorder(Rectangle.BOX); return cell; } public static PdfPCell getDataCell(String text){ PdfPCell cell = new PdfPCell(new Phrase(text, ReportTemplate.TIMESROMAN_8_NORMAL)); cell.setUseBorderPadding(true); cell.setBorderWidth(1); cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); cell.setVerticalAlignment(PdfPCell.ALIGN_CENTER); cell.setBorder(Rectangle.BOX); return cell; } /** * @Added - Abhishek * @date - 12-1-2016 * @desc - Blank cell for table */ public static PdfPCell getBlankCell(){ PdfPCell cell = new PdfPCell(new Phrase("", ReportTemplate.TIMESROMAN_8_NORMAL)); cell.setUseBorderPadding(true); cell.setBorderWidth(1); cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); cell.setVerticalAlignment(PdfPCell.ALIGN_CENTER); cell.setBorder(Rectangle.BOX); cell.setBackgroundColor(BaseColor.LIGHT_GRAY); return cell; } } public static PdfPCell getFooterCellSmallNoBorder(String text){ PdfPCell cell = new PdfPCell(new Phrase(text, TIMESROMAN_8_NORMAL)); cell.setPaddingTop(5); cell.setPaddingBottom(5); cell.setUseBorderPadding(true); cell.setBorderWidth(0); cell.setBorder(Rectangle.NO_BORDER); return cell; } public static PdfPTable getFullWidthTable(int column){ PdfPTable table = new PdfPTable(column); table.setWidthPercentage(100); return table; } public static PdfPCell getSectionHeaderCell(String text){ Phrase sectionHeaderPara = new Phrase(text, ReportTemplate.TIMESROMAN_14_BOLD); PdfPCell sectionHeaderCell = new PdfPCell(sectionHeaderPara); sectionHeaderCell.setVerticalAlignment(PdfPCell.ALIGN_CENTER); sectionHeaderCell.setUseBorderPadding(true); sectionHeaderCell.setBorderWidth(1); sectionHeaderCell.setBorder(Rectangle.BOX); sectionHeaderCell.setBackgroundColor(new BaseColor(193, 183, 157)); return sectionHeaderCell; } public static PdfPCell getBoxBorderCell(){ PdfPCell cell = getBoxBorderWithoutLeftPaddingCell(); cell.setUseBorderPadding(true); return cell; } public static PdfPCell getBoxBorderWithoutLeftPaddingCell(){ PdfPCell cell = new PdfPCell(); cell.setUseBorderPadding(true); cell.setBorderWidth(1); cell.setBorder(Rectangle.BOX); return cell; } public static PdfPCell getSectionSubHeaderCellWithBoxBorder(String text){ Phrase sectionSubHeaderPara = new Phrase(text, ReportTemplate.TIMESROMAN_14_BOLD); PdfPCell sectionSubHeaderCell = new PdfPCell(sectionSubHeaderPara); sectionSubHeaderCell.setVerticalAlignment(PdfPCell.ALIGN_CENTER); sectionSubHeaderCell.setUseBorderPadding(true); sectionSubHeaderCell.setBorderWidth(1); sectionSubHeaderCell.setBorder(Rectangle.BOX); return sectionSubHeaderCell; } public static PdfPCell getSectionSubHeaderCellWithoutBorder(String text){ Phrase sectionSubHeaderPara = new Phrase(text, ReportTemplate.TIMESROMAN_14_BOLD); PdfPCell sectionSubHeaderCell = new PdfPCell(sectionSubHeaderPara); sectionSubHeaderCell.setVerticalAlignment(PdfPCell.ALIGN_CENTER); sectionSubHeaderCell.setUseBorderPadding(true); sectionSubHeaderCell.setBorderWidth(0); sectionSubHeaderCell.setBorder(Rectangle.NO_BORDER); return sectionSubHeaderCell; } public static PdfPCell getSectionSubHeaderCellWithoutBorderSmall(String text){ Phrase sectionSubHeaderPara = new Phrase(text, ReportTemplate.TIMESROMAN_10_BOLD); PdfPCell sectionSubHeaderCell = new PdfPCell(sectionSubHeaderPara); sectionSubHeaderCell.setVerticalAlignment(PdfPCell.ALIGN_CENTER); sectionSubHeaderCell.setUseBorderPadding(true); sectionSubHeaderCell.setBorderWidth(0); sectionSubHeaderCell.setBorder(Rectangle.NO_BORDER); return sectionSubHeaderCell; } public static Chunk getNewLineChunk() { return new Chunk("\n"); } }
true
d1b1111ba7ac9cca52ab0f86689e13cbeabbea11
Java
vinzlac/hexagonalExample
/src/main/java/com/vinzlac/hexagonal/domain/IObtainPoems.java
UTF-8
93
1.84375
2
[]
no_license
package com.vinzlac.hexagonal.domain; public interface IObtainPoems { String GetAPoem(); }
true
a2817b01ee87789c26a41875568f400f54690baf
Java
emmanueliv/sicabis
/sicabis/sicabis-ejb-modelo/src/main/java/com/issste/sicabis/ejb/DAO/ClasificacionImportanciaDAO.java
UTF-8
447
1.851563
2
[]
no_license
package com.issste.sicabis.ejb.DAO; import com.issste.sicabis.ejb.modelo.ClasificacionImportancia; import java.util.List; import javax.ejb.Local; @Local public interface ClasificacionImportanciaDAO { void guardarClasificacionImportancia(ClasificacionImportancia clasificacionImportancia); List<ClasificacionImportancia> obtenerByClasificacion(ClasificacionImportancia clasificacionImportancia); Integer obtenerUltimoRegistro(); }
true
be87bbddea23a546ee9caafe3849b36f2a3a45f7
Java
vinuthasr/Ehaenterprise
/src/main/java/com/elephant/controller/payment/PaymentController1.java
UTF-8
3,772
2.203125
2
[]
no_license
package com.elephant.controller.payment; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.elephant.constant.*; import com.elephant.config.PayPalResult; import com.elephant.config.PayPalSucess; import com.elephant.dao.customer.CustomerRepository; import com.elephant.domain.cartitem.CartItemDomain; import com.elephant.domain.customer.CustomerDomain; import com.elephant.domain.uploadproduct.ProductDomain; import com.elephant.model.payment.PaymentModel; import com.elephant.model.payment.Product; import com.elephant.service.order.OrderService; import com.elephant.service.payment.PayPalService1; @Controller @RequestMapping("/v1/cart") @CrossOrigin(origins= {"http://13.235.82.62","http://localhost:4200"}) public class PaymentController1 { /*static String email="null"; static long addressid=0;*/ @Autowired private PayPalService1 payPalService1; @Autowired CustomerRepository customerRepository; @Autowired OrderService orderService; PaymentModel paymentModel=new PaymentModel(); @RequestMapping(value="/paypal",method=RequestMethod.GET, produces="application/json") public String cartpage(ModelMap modelMap) { //paymentModel.setEmail(Email); //paymentModel.setAddressId(addressId); List<Product> products=new ArrayList<Product>(); /*------------------Get Total Price from Cart-------------------------------*/ //CustomerDomain customerDomain=customerRepository.findByEmail(Email); //List<CartItemDomain> listCartItemDomain=customerDomain.getCartItemDomain(); double grandtotal=0; //for(CartItemDomain cartItemDomain:listCartItemDomain) { //ProductDomain productDomain=cartItemDomain.getProduct(); //grandtotal+= (productDomain.getPrice()-((productDomain.getPrice()*productDomain.getDiscount()/100)))*cartItemDomain.getQuantity(); //} products.add(new Product("Total products", 20)); /*--------------------------------------------------------------------------*/ modelMap.put("products", products); modelMap.put("payPalConfig",payPalService1.getPayPalConfig() ); return "paypal"; } @RequestMapping(value = "success", method=RequestMethod.GET) public String success(HttpServletRequest request) { try { PayPalSucess payPalSucess = new PayPalSucess(); PayPalResult payPalResult = payPalSucess.getPayPal(request, payPalService1.getPayPalConfig()); /*---------------------Set Payment to PayPal Mode and Get transactionId through PayPalResult Class--------*/ paymentModel.setPaymentMode(Constants.PAYPAL); paymentModel.setTransactionId(payPalResult.getTxn_id()); /*---------------------------------------------------------------------------------------------------------*/ orderService.createOrder(paymentModel); System.out.println("Order Info"); System.out.println("First Name: " + payPalResult.getFirst_name()); System.out.println("Last Name" + payPalResult.getLast_name() ); System.out.println("Country" + payPalResult.getAddress_country()); System.out.println("Email" + payPalResult.getPayer_email()); System.out.println("Country" + payPalResult.getMc_gross()); }catch(Exception ex) { System.out.println("Exception in success"+ex); } return "cart/success"; } }
true
2fbcc60cb698daf1fd53b199cdaecb9bc4ae4ecf
Java
muhammed122/FaceRegonation
/app/src/main/java/com/example/faceregonatio/ui/activity/login/Login.java
UTF-8
1,932
1.984375
2
[]
no_license
package com.example.faceregonatio.ui.activity.login; import androidx.appcompat.app.AppCompatActivity; import androidx.databinding.DataBindingUtil; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import android.content.Intent; import android.os.Bundle; import android.widget.Toast; import com.example.faceregonatio.R; import com.example.faceregonatio.databinding.ActivityLoginBinding; import com.example.faceregonatio.ui.activity.MainActivity; import com.example.faceregonatio.ui.activity.signup.SignUp; public class Login extends AppCompatActivity { ActivityLoginBinding binding; LoginViewModel loginViewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_login); binding.setLifecycleOwner(this); loginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class); binding.setViewModel(loginViewModel); loginViewModel.message.observe(this, new Observer<String>() { @Override public void onChanged(String s) { Toast.makeText(Login.this, ""+s, Toast.LENGTH_SHORT).show(); } }); loginViewModel.intent.observe(this, new Observer<Boolean>() { @Override public void onChanged(Boolean intent) { if (intent){ startActivity(new Intent(Login.this,MainActivity.class)); finish(); } } }); loginViewModel.signUpIntent.observe(this, new Observer<Boolean>() { @Override public void onChanged(Boolean intent) { if (intent){ startActivity(new Intent(Login.this, SignUp.class)); finish(); } } }); } }
true
278dfe795fc3b95272ccd1523ddff0c56dda4cbb
Java
qqxliufeng/zwlogistics
/安卓/src/main/java/com/android/ql/lf/carapp/data/NewOrderMessageBean.java
UTF-8
354
1.960938
2
[]
no_license
package com.android.ql.lf.carapp.data; /** * Created by lf on 18.2.28. * * @author lf on 18.2.28 */ public class NewOrderMessageBean { private String orderMessage; public NewOrderMessageBean(String orderMessage) { this.orderMessage = orderMessage; } public String getOrderMessage() { return orderMessage; } }
true
caeceb3a468bce3409be24cc73aae4d8e01033f8
Java
EmbryoAI/EmbryoAI-aCloud
/code/EmbryoAI-aCloud/src/main/java/com/embryoai/acloud/entity/SystemFeedback.java
UTF-8
2,078
1.914063
2
[]
no_license
package com.embryoai.acloud.entity; import java.util.Date; public class SystemFeedback { private String procedureId; private String orgId; private Integer biochemPregnancy; private Integer clinicalPregnancy; private Integer fetusCount; private String userId; private Date createTime; private Date updateTime; private Integer delFlag; public String getProcedureId() { return procedureId; } public void setProcedureId(String procedureId) { this.procedureId = procedureId == null ? null : procedureId.trim(); } public String getOrgId() { return orgId; } public void setOrgId(String orgId) { this.orgId = orgId == null ? null : orgId.trim(); } public Integer getBiochemPregnancy() { return biochemPregnancy; } public void setBiochemPregnancy(Integer biochemPregnancy) { this.biochemPregnancy = biochemPregnancy; } public Integer getClinicalPregnancy() { return clinicalPregnancy; } public void setClinicalPregnancy(Integer clinicalPregnancy) { this.clinicalPregnancy = clinicalPregnancy; } public Integer getFetusCount() { return fetusCount; } public void setFetusCount(Integer fetusCount) { this.fetusCount = fetusCount; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId == null ? null : userId.trim(); } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Integer getDelFlag() { return delFlag; } public void setDelFlag(Integer delFlag) { this.delFlag = delFlag; } }
true
37c56dd0d1c6d3de567901861617ff36b94f58a7
Java
PaulEdwards0712/taskTrackerAppForNoveClass
/src/main/java/com/oosdclass/taskTrackerApp2/service/impl/UserServiceImpl.java
UTF-8
1,243
2.53125
3
[]
no_license
package com.oosdclass.taskTrackerApp2.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.oosdclass.taskTrackerApp2.dao.UserDAO; import com.oosdclass.taskTrackerApp2.model.User; import com.oosdclass.taskTrackerApp2.service.UserService; //Spring Framework: this class is the Service Layer @Service public class UserServiceImpl implements UserService { @Autowired UserDAO userDAO; @Override public boolean isUserValid(User user) { User userFromDb = userDAO.retrieveByUserName(user.getUsername()); if(user.getUsername().equals(userFromDb.getUsername()) && user.getPassword().equals(userFromDb.getPassword())) { return true; } else { return false; } } @Override public boolean doesUserExist(User user) { User userFromDb = userDAO.retrieveByUserName(user.getUsername()); if(userFromDb == null) { return false; } else { return true; } } @Override public boolean isUserAdmin(User user) { User userFromDb = userDAO.retrieveByUserName(user.getUsername()); if(userFromDb.getUsername().equals("admin")){ return true; } else { return false; } } }
true
220d04b2b6f8a38e05ad97a150b2e4e75e92e9cf
Java
SuzyWu2014/coprhd-controller
/controllersvc/src/main/java/com/emc/storageos/volumecontroller/impl/plugins/discovery/smis/processor/StorageProtocolEndPointProcessor.java
UTF-8
10,588
1.53125
2
[]
no_license
/* * Copyright (c) 2008-2011 EMC Corporation * All Rights Reserved */ package com.emc.storageos.volumecontroller.impl.plugins.discovery.smis.processor; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.cim.CIMInstance; import javax.cim.CIMObjectPath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.emc.storageos.coordinator.client.service.CoordinatorClient; import com.emc.storageos.db.client.DbClient; import com.emc.storageos.db.client.URIUtil; import com.emc.storageos.db.client.model.StoragePool; import com.emc.storageos.db.client.model.StoragePort; import com.emc.storageos.db.client.model.StorageSystem; import com.emc.storageos.db.client.model.StoragePort.OperationalStatus; import com.emc.storageos.plugins.AccessProfile; import com.emc.storageos.plugins.BaseCollectionException; import com.emc.storageos.plugins.common.Constants; import com.emc.storageos.plugins.common.domainmodel.Operation; import com.emc.storageos.volumecontroller.impl.NativeGUIDGenerator; import com.emc.storageos.volumecontroller.impl.StoragePoolAssociationHelper; import com.google.common.base.Joiner; public class StorageProtocolEndPointProcessor extends StorageEndPointProcessor { private Logger _logger = LoggerFactory .getLogger(StorageProtocolEndPointProcessor.class); private List<Object> args; private DbClient _dbClient; private static final String NAME = "Name"; private static final String SYSTEMNAME = "SystemName"; private static final String DEVICEID = "DeviceID"; private static final String COMMA_STR = ","; @Override public void processResult( Operation operation, Object resultObj, Map<String, Object> keyMap) throws BaseCollectionException { try { @SuppressWarnings("unchecked") final Iterator<CIMInstance> it = (Iterator<CIMInstance>) resultObj; _dbClient = (DbClient) keyMap.get(Constants.dbClient); CoordinatorClient coordinator = (CoordinatorClient) keyMap.get(Constants.COORDINATOR_CLIENT); AccessProfile profile = (AccessProfile) keyMap.get(Constants.ACCESSPROFILE); Map<URI, StoragePool> poolsToMatchWithVpool = (Map<URI, StoragePool>) keyMap.get(Constants.MODIFIED_STORAGEPOOLS); StorageSystem device = _dbClient.queryObject(StorageSystem.class, profile.getSystemId()); List<StoragePort> newPorts = new ArrayList<StoragePort>(); List<StoragePort> existingPorts = new ArrayList<StoragePort>(); while (it.hasNext()) { CIMInstance endPointInstance = null; StoragePort port = null; try { endPointInstance = it.next(); String portInstanceID = endPointInstance.getObjectPath() .getKey(SYSTEMNAME).getValue().toString(); if (device.checkIfVmax3()) { CIMObjectPath logicalPortPath = getObjectPathfromCIMArgument(args); // We need the portInstanceID to not constitute the Virtual information. // i.e Instead of SYMMETRIX-+-<<SERIAL>>-+-115-+-0 it should be SYMMETRIX-+-<<SERIAL>>-+-SE-1G-+-0 StringBuffer newPortInstanceID = new StringBuffer(logicalPortPath.getKey(SYSTEMNAME).getValue().toString()); newPortInstanceID.append(Constants._plusDelimiter) .append(logicalPortPath.getKey(DEVICEID).getValue().toString()); portInstanceID = (newPortInstanceID.toString()).replaceAll(Constants.SMIS_PLUS_REGEX, Constants.SMIS80_DELIMITER_REGEX); } String iScsiPortName = getCIMPropertyValue(endPointInstance, NAME); // Skip the iSCSI ports without name or without a valid name. if (null == iScsiPortName || iScsiPortName.split(COMMA_STR)[0].length() <= 0) { _logger.warn("Invalid port Name found for {} Skipping", portInstanceID); continue; } port = checkEthernetStoragePortExistsInDB( iScsiPortName.split(COMMA_STR)[0].toLowerCase(), _dbClient, device); createEthernetStoragePort(keyMap, port, endPointInstance, portInstanceID, coordinator, newPorts, existingPorts); addPath(keyMap, operation.getResult(), endPointInstance.getObjectPath()); } catch (Exception e) { _logger.warn("SCSI End Point Discovery failed for {}-->{}", "", getMessage(e)); } } @SuppressWarnings("unchecked") List<List<StoragePort>> portsUsedToRunNetworkConnectivity = (List<List<StoragePort>>) keyMap.get(Constants.STORAGE_PORTS); portsUsedToRunNetworkConnectivity.add(newPorts); // discovered ports used later to check for not visible ports List<StoragePort> discoveredPorts = (List<StoragePort>) keyMap.get(Constants.DISCOVERED_PORTS); discoveredPorts.addAll(newPorts); discoveredPorts.addAll(existingPorts); List<StoragePool> modifiedPools = StoragePoolAssociationHelper.getStoragePoolsFromPorts(_dbClient, newPorts, null); for (StoragePool pool : modifiedPools) { // pool matcher will be invoked on this pool if (!poolsToMatchWithVpool.containsKey(pool.getId())) { poolsToMatchWithVpool.put(pool.getId(), pool); } } _logger.debug("# Pools used in invoking PoolMatcher during StorageProtoclEndPoint {}", Joiner.on("\t").join(poolsToMatchWithVpool.keySet())); } catch (Exception e) { _logger.error("SCSI End Point Discovery failed -->{}", getMessage(e)); } } /** * create Ethernet Storage Port. * StoragePorts would have been created in SToragePorts Processor, but for ethernet those * will not get updated to DB, as to get SCSIAddress ,we need a different SMI Class ProtocolEndPoint * Algo : * 1. Check if StorageEthernet Port available in DB. * 2. If not, then get already created StoragePort, update SCSI Address and persist. * 3. If yes, then just update the properties alone. * * @param keyMap * @param port * @param endPointInstance * @param portInstanceID * @throws IOException */ private void createEthernetStoragePort( Map<String, Object> keyMap, StoragePort port, CIMInstance endPointInstance, String portInstanceID, CoordinatorClient coordinator, List<StoragePort> newPorts, List<StoragePort> existingPorts) throws IOException { StoragePort portinMemory = (StoragePort) keyMap.get(portInstanceID); String endPointInstanceId = endPointInstance.getObjectPath().getKey(NAME) .getValue().toString().split(COMMA_STR)[0].toLowerCase(); if (null == port) { if ((portinMemory != null) && (portinMemory.getPortNetworkId() != null) && !(portinMemory.getPortNetworkId().equals(endPointInstanceId))) { // Since this is a new protocol endpoint and for V3, a single physical port can have multiple // virtualiSCSIProtocolEndpoints, we will need to create new port object StoragePort newPortinMemory = portinMemory.clone(); newPortinMemory.setId(URIUtil.createId(StoragePort.class)); newPortinMemory.setPortNetworkId(endPointInstanceId); newPortinMemory.setPortEndPointID(endPointInstance.getObjectPath().getKey(NAME) .getValue().toString()); String portNativeGuid = NativeGUIDGenerator.generateNativeGuid(_dbClient, newPortinMemory); newPortinMemory.setNativeGuid(portNativeGuid); newPortinMemory.setLabel(portNativeGuid); _logger.info("Creating port - {}:{}", newPortinMemory.getLabel(), newPortinMemory.getNativeGuid()); _dbClient.createObject(newPortinMemory); newPorts.add(newPortinMemory); } else { // Name Property's value --> iqn.23.....,t,0x0001 portinMemory.setPortNetworkId(endPointInstanceId); portinMemory.setPortEndPointID(endPointInstance.getObjectPath().getKey(NAME) .getValue().toString()); String portNativeGuid = NativeGUIDGenerator.generateNativeGuid(_dbClient, portinMemory); portinMemory.setNativeGuid(portNativeGuid); portinMemory.setLabel(portNativeGuid); _logger.info("Creating port - {}:{}", portinMemory.getLabel(), portinMemory.getNativeGuid()); _dbClient.createObject(portinMemory); newPorts.add(portinMemory); } } else { String currentPortName = port.getPortName(); if (!currentPortName.contains(portinMemory.getPortName())) { // A single VirtualiSCSIProtocolEndpoint is associated to multiple physical GIGE ports StringBuffer appendedPortName = new StringBuffer(currentPortName); appendedPortName.append(COMMA_STR).append(portinMemory.getPortName()); port.setPortName(appendedPortName.toString()); } port.setPortSpeed(portinMemory.getPortSpeed()); port.setPortEndPointID(endPointInstance.getObjectPath().getKey(NAME) .getValue().toString()); port.setCompatibilityStatus(portinMemory.getCompatibilityStatus()); port.setDiscoveryStatus(portinMemory.getDiscoveryStatus()); if (!OperationalStatus.OK.name().equals(port.getOperationalStatus())) { port.setOperationalStatus(portinMemory.getOperationalStatus()); } _logger.info("Updating port - {} : {}", port.getLabel(), port.getNativeGuid()); _dbClient.persistObject(port); existingPorts.add(port); } } @Override protected void setPrerequisiteObjects(List<Object> inputArgs) throws BaseCollectionException { args = inputArgs; } }
true
b1b7061d44e89a9e16d92c795e1dfee72ab00e76
Java
Ebaa-Alnazer/EvaluationOrchestrator
/src/main/java/com/ebaa/alnazer/algorithm/evaluation/scenarios/BasicProblemEvaluationScenario.java
UTF-8
3,336
2.4375
2
[ "Apache-2.0" ]
permissive
package com.ebaa.alnazer.algorithm.evaluation.scenarios; import com.ebaa.alnazer.algorithm.algorithms.PlanningAlgorithm; import com.ebaa.alnazer.algorithm.algorithms.RiskAttitude; import com.ebaa.alnazer.algorithm.algorithms.UAShop; import lombok.Builder; import lombok.Data; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; @Data public class BasicProblemEvaluationScenario extends EvaluationScenario{ protected static final Logger log = LoggerFactory.getLogger(DiagonalScenario.class); protected int startSize; protected int endSize; protected int step; protected boolean hasShortcuts; protected PlanningAlgorithm algorithm; public BasicProblemEvaluationScenario(int startSize, int endSize, int step, boolean hasShortcuts, PlanningAlgorithm algorithm,File outputDirectory) { super(outputDirectory); this.startSize = startSize; this.endSize = endSize; this.step = step; this.hasShortcuts = hasShortcuts; this.algorithm = algorithm; } @Override public void run() { } @Override public void verifyInputs() throws IllegalArgumentException { super.verifyInputs(); if (algorithm == null) { throw new IllegalArgumentException("Planning algorithm is not set!"); } if (startSize < 4) { throw new IllegalArgumentException("startSize MUST be > 4!"); } if (endSize < startSize || step <= 0 || step > endSize - startSize) { throw new IllegalArgumentException("Evaluation scenario arguments are invalid!"); } } @Override public File retrieveResults() { return new File(outputDirectory, String.format("d-%s-%s-%s-%s.csv", algorithm.getName(), startSize, endSize, step)); } @Override public int getIndexOfDurationColumnInOutput() { if (algorithm instanceof UAShop) return 2; return 1; } protected void enhanceOutput(File original, File target) throws IOException { try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(target, false))) { try (BufferedReader bufferedReader = new BufferedReader(new FileReader(original))) { bufferedWriter.write("sep=,\n"); // insert header if (algorithm instanceof UAShop) { bufferedWriter.write("grid size,phase1 duration, phase 2 duration, cost,plan length\n"); } else { bufferedWriter.write("grid size,duration, cost,plan length\n"); } String current = bufferedReader.readLine(); int currentSize = this.startSize; while (current != null) { bufferedWriter.write(String.format("%s,%s\n", currentSize, current)); current = bufferedReader.readLine(); currentSize += step; } } } catch (IOException e) { log.error("An error occurred while injecting problem sizes in the output file..", e); throw new RuntimeException(e); } FileUtils.forceDelete(original); } @Override public String toString() { return null; } }
true
ea1aab7375a232f142e1c4f9b009c1c956fdea2b
Java
hawallen/MoodPath
/app/src/main/java/com/hawallen/moodpath/bean/Article.java
UTF-8
1,163
2.234375
2
[]
no_license
package com.hawallen.moodpath.bean; import java.io.Serializable; @SuppressWarnings("serial") public class Article implements Serializable { private String aId = ""; private String calendar = ""; private String title = ""; private String content = ""; private String picPath = ""; private int value = -1; // private boolean isRead = false; public String getaId() { return aId; } public void setaId(String aId) { this.aId = aId; } public String getCalendar() { return calendar; } public void setCalendar(String calendar) { this.calendar = calendar; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getPicPath() { return picPath; } public void setPicPath(String picPath) { this.picPath = picPath; } // public boolean isRead() { // return isRead; // } // public void setRead(boolean isRead) { // this.isRead = isRead; // } public int getValue() { return value; } public void setValue(int value) { this.value = value; } }
true
ae73a07dfb96c7307a5b6a0cc1374e0358cce84c
Java
ChristianQian/JavaConcurrence
/Exo8/TestTransport.java
UTF-8
321
2.609375
3
[]
no_license
public class TestTransport { public static void main(String [] args) { AleaStock s= new AleaStock(4); for(int i = 0; i <4 ; i++) s.ajout(new AleaObjet(1,1)); Chariot c= new Chariot(2,2); Thread tc= new Thread(new Chargeur(c,s)); Thread td= new Thread(new Dechargeur(c,s)); tc.start(); td.start(); } }
true
bc93be7d5bf477a61e06cab11b9d3f2abf34b0b4
Java
butwhole1994/1Dimension_Array
/1Dimension_Array/Average_Score_Students.java
UHC
1,385
3.421875
3
[]
no_license
import java.util.*; import java.io.*; public class Average_Score_Students { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int T = Integer.parseInt(br.readLine()); double average = 0; double sum = 0; double cnt = 0; for(int i=0; i<T; ++i) { StringTokenizer st = new StringTokenizer(br.readLine()); int students = Integer.parseInt(st.nextToken()); double[] score = new double[students]; for(int j=0; j<students; ++j) { score[j] = Double.parseDouble(st.nextToken()); sum += score[j]; } average = sum/students; for(int k=0; k<students; ++k) { if(score[k]>average) { cnt++;//double ̶ ++ ָ 1.0 ٴ ˾Ҵ. } } double percentage = cnt/students*100; String value = String.format("%.3f", percentage); //String.format("%.?f", objects) //Ʈ ϱ ؼ, ͸ Բ ؾ߸ Ѵ. // : https://micropai.tistory.com/48 // Ҽ ǥÿ : https://coding-factory.tistory.com/250 sb.append(value+"%").append("\n"); average = 0; sum=0; cnt=0; } System.out.println(sb); br.close(); } }
true
661f6f1f5003dc6e135354d498bb5a1c10f27d11
Java
dalalsunil1986/jvm_workshop
/contact-web-app/src/main/java/com/jvmworkshop/contactwebapp/controller/ContactController.java
UTF-8
1,791
2.265625
2
[]
no_license
package com.jvmworkshop.contactwebapp.controller; import com.jvmworkshop.contactwebapp.entity.Contact; import com.jvmworkshop.contactwebapp.repository.ContactRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; /** * Created by IntelliJ IDEA. * Project : contact-web-app * User: hendisantika * Email: hendisantika@gmail.com * Telegram : @hendisantika34 * Date: 09/12/17 * Time: 09.56 * To change this template use File | Settings | File Templates. */ @RestController @RequestMapping("/api/contacts") public class ContactController { @Autowired ContactRepo repo; @GetMapping("") Page<Contact> getAllContacts(Pageable page){ return repo.findAll(page); } @PostMapping("") ResponseEntity<Object> saveCandidate(@RequestBody Contact contact){ if (contact != null) { return new ResponseEntity<>(repo.save(contact), HttpStatus.OK); }else { return new ResponseEntity<>("Data Null", HttpStatus.OK); } } @GetMapping("/findById") Contact findContactById(@RequestParam(value = "id") String id){ return repo.findOne(Long.parseLong(id)); } @GetMapping("/{id}/find") Contact findById(@PathVariable(value = "id") String id){ return repo.findOne(Long.parseLong(id)); } @DeleteMapping("/{id}/delete") void deleteContact(@PathVariable(value = "id") String id){ Contact hasil = repo.findOne(Long.parseLong(id)); if (hasil != null) { repo.delete(Long.parseLong(id)); } } }
true
4dc74e656c25d3e8710be7dfa267a04e47a908f0
Java
rajbahadurpesit/VTU-1st-year
/app/src/main/java/simple/raj/com/vtuqpaper/Result.java
UTF-8
2,776
2.1875
2
[]
no_license
package simple.raj.com.vtuqpaper; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.webkit.WebView; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class Result extends ActionBarActivity { private Context context; public String s; WebView wv1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_result); getSupportActionBar().setDisplayHomeAsUpEnabled(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); getWindow().setStatusBarColor(getResources().getColor(R.color.ColorPrimaryDark)); } final EditText phone = (EditText) findViewById(R.id.editPhone); context = this.getApplicationContext(); phone.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast msg = Toast.makeText(getBaseContext(), "Only 10 Character", Toast.LENGTH_LONG); msg.show(); } }); Button next = (Button) findViewById(R.id.nextBtn); next.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { // Intent intent=new Intent(getApplicationContext(),Displayresult.class); s = phone.getText().toString(); Intent intent = new Intent(Result.this, Displayresult.class); intent.putExtra("s",s); startActivity(intent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_result, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // app icon in action bar clicked; goto parent activity. this.finish(); return true; default: return super.onOptionsItemSelected(item); case R.id.about: Intent inte=new Intent(getApplicationContext(),About.class); startActivity(inte); return true; } } }
true
df7000e01ba9e3718b01948cc309211e490f51ce
Java
mahogano/mahogano
/src/main/java/com/mahogano/core/presta/entity/Employee.java
UTF-8
6,059
1.875
2
[ "MIT" ]
permissive
package com.mahogano.core.presta.entity; import java.time.LocalDateTime; public class Employee { private Integer idEmployee; private Integer idProfile; private Integer idLang; private String lastname; private String firstname; private String email; private String passwd; private LocalDateTime lastPasswdGen; private LocalDateTime statsDateFrom; private LocalDateTime statsDateTo; private LocalDateTime statsCompareFrom; private LocalDateTime statsCompareTo; private Integer statsCompareOption; private String preselectDateRange; private String boColor; private String boTheme; private String boCss; private Integer defaultTab; private Integer boWidth; private Integer boMenu; private Integer active; private Integer optin; private Integer idLastOrder; private Integer idLastCustomerMessage; private Integer idLastCustomer; private LocalDateTime lastConnectionDate; private String resetPasswordToken; private LocalDateTime resetPasswordValidity; public Integer getIdEmployee() { return idEmployee; } public void setIdEmployee(Integer idEmployee) { this.idEmployee = idEmployee; } public Integer getIdProfile() { return idProfile; } public void setIdProfile(Integer idProfile) { this.idProfile = idProfile; } public Integer getIdLang() { return idLang; } public void setIdLang(Integer idLang) { this.idLang = idLang; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; } public LocalDateTime getLastPasswdGen() { return lastPasswdGen; } public void setLastPasswdGen(LocalDateTime lastPasswdGen) { this.lastPasswdGen = lastPasswdGen; } public LocalDateTime getStatsDateFrom() { return statsDateFrom; } public void setStatsDateFrom(LocalDateTime statsDateFrom) { this.statsDateFrom = statsDateFrom; } public LocalDateTime getStatsDateTo() { return statsDateTo; } public void setStatsDateTo(LocalDateTime statsDateTo) { this.statsDateTo = statsDateTo; } public LocalDateTime getStatsCompareFrom() { return statsCompareFrom; } public void setStatsCompareFrom(LocalDateTime statsCompareFrom) { this.statsCompareFrom = statsCompareFrom; } public LocalDateTime getStatsCompareTo() { return statsCompareTo; } public void setStatsCompareTo(LocalDateTime statsCompareTo) { this.statsCompareTo = statsCompareTo; } public Integer getStatsCompareOption() { return statsCompareOption; } public void setStatsCompareOption(Integer statsCompareOption) { this.statsCompareOption = statsCompareOption; } public String getPreselectDateRange() { return preselectDateRange; } public void setPreselectDateRange(String preselectDateRange) { this.preselectDateRange = preselectDateRange; } public String getBoColor() { return boColor; } public void setBoColor(String boColor) { this.boColor = boColor; } public String getBoTheme() { return boTheme; } public void setBoTheme(String boTheme) { this.boTheme = boTheme; } public String getBoCss() { return boCss; } public void setBoCss(String boCss) { this.boCss = boCss; } public Integer getDefaultTab() { return defaultTab; } public void setDefaultTab(Integer defaultTab) { this.defaultTab = defaultTab; } public Integer getBoWidth() { return boWidth; } public void setBoWidth(Integer boWidth) { this.boWidth = boWidth; } public Integer getBoMenu() { return boMenu; } public void setBoMenu(Integer boMenu) { this.boMenu = boMenu; } public Integer getActive() { return active; } public void setActive(Integer active) { this.active = active; } public Integer getOptin() { return optin; } public void setOptin(Integer optin) { this.optin = optin; } public Integer getIdLastOrder() { return idLastOrder; } public void setIdLastOrder(Integer idLastOrder) { this.idLastOrder = idLastOrder; } public Integer getIdLastCustomerMessage() { return idLastCustomerMessage; } public void setIdLastCustomerMessage(Integer idLastCustomerMessage) { this.idLastCustomerMessage = idLastCustomerMessage; } public Integer getIdLastCustomer() { return idLastCustomer; } public void setIdLastCustomer(Integer idLastCustomer) { this.idLastCustomer = idLastCustomer; } public LocalDateTime getLastConnectionDate() { return lastConnectionDate; } public void setLastConnectionDate(LocalDateTime lastConnectionDate) { this.lastConnectionDate = lastConnectionDate; } public String getResetPasswordToken() { return resetPasswordToken; } public void setResetPasswordToken(String resetPasswordToken) { this.resetPasswordToken = resetPasswordToken; } public LocalDateTime getResetPasswordValidity() { return resetPasswordValidity; } public void setResetPasswordValidity(LocalDateTime resetPasswordValidity) { this.resetPasswordValidity = resetPasswordValidity; } }
true
d31f2999d1032c549c8ba05b35f6027b1c11ba6a
Java
shawn2you/MySW
/src/pretest4/Solution_TA0037.java
UTF-8
2,284
2.921875
3
[]
no_license
package pretest4; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; /* * (중) [기출A-0037] 핵심도시1 */ public class Solution_TA0037 { static int T, V, E, Sum, Seq, RootTree; static int[] SearchOrder; static int[] CoreCity; static ArrayList<Integer>[] City; public static void main(String[] args) throws Exception { FileInputStream fi = new FileInputStream(new File(Solution_TA0037.class.getResource("").getPath() + "Solution_TA0037.txt")); System.setIn(fi); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); T = Integer.parseInt(br.readLine()); for (int t=1; t<=T; t++) { // 초기화 Sum = 0; Seq = 0; RootTree = 0; // 정점의 총 수 V 와 간선의 총 수 E StringTokenizer st = new StringTokenizer(br.readLine()); V = Integer.parseInt(st.nextToken()); E = Integer.parseInt(st.nextToken()); City = new ArrayList[V + 1]; SearchOrder = new int[V + 1]; for(int i=0; i<=V; i++) { City[i] = new ArrayList<Integer>(); } CoreCity = new int[V + 1]; // 단절 도시 for(int i=0; i<E; i++) { st = new StringTokenizer(br.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); City[A].add(B); } dfs(1); StringBuilder sb = new StringBuilder(); for(int i=1; i<=V; i++) { if(CoreCity[i] == 1) { sb.append(" " + i); Sum++; } } System.out.println("#"+t + " " + Sum + " " + sb.toString()); } // end test case } // end main public static int dfs(int start) { Seq++; SearchOrder[start] = Seq; int low = Seq; for(int c : City[start]) { if(SearchOrder[c] != 0) { low = Math.min(low, SearchOrder[c]); }else { int nextLow = dfs(c); if(start !=1 && SearchOrder[c] <= nextLow) { CoreCity[c] = 1; } low = Math.min(low, nextLow); // 점점노드 처리 if(start == 1) { RootTree++; if(RootTree > 1) { CoreCity[start] = 1; } } } } // System.out.println(start + " "+SearchOrder[start] + " " + low); return low; } }
true
1a33b8e94a2aae10faf8867b84c50653001aabeb
Java
endeavourhealth/Transforms
/src/main/java/org/endeavourhealth/transform/common/TransformConfig.java
UTF-8
12,910
1.960938
2
[ "Apache-2.0" ]
permissive
package org.endeavourhealth.transform.common; import com.fasterxml.jackson.databind.JsonNode; import org.endeavourhealth.common.config.ConfigManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.regex.Pattern; public class TransformConfig { private static final Logger LOG = LoggerFactory.getLogger(TransformConfig.class); private String sharedStoragePath; private int attemptsPermmitedPerExchange; private String killFileLocation; private Set<String> emisDisabledOdsCodesAllowed; private boolean emisAllowMissingCodes; private boolean emisAllowUnmappedRegistrationTypes; //private boolean emisSkipAdminData; private Set<String> softwareFormatsToDrainQueueOnFailure; private String cernerPatientIdFile; private boolean cernerCDSEncountersOnly; private String bhrutPatientIdFile; private int maxTransformErrorsBeforeAbort; private List<Pattern> warningsToFailOn; private boolean disableSavingResources; private boolean validateResourcesOnSaving; private int resourceCacheMaxSizeInMemory; private boolean isLive; private int resourceSaveBatchSize; private boolean allowMissingConceptIdsInSubscriberTransform; private Map<String, Set<String>> hmFileTypeFilters; private int rabbitMessagePerSecondThrottle; private Map<String, String> emisOdsCodesAndStartDates; private int adminBatchMaxSize; //singleton private static TransformConfig instance; private static Object sync = new Object(); public static TransformConfig instance() { if (instance == null) { synchronized (sync) { if (instance == null) { instance = new TransformConfig(); } } } return instance; } private TransformConfig() { //set some defaults //this.sharedStoragePath = null; //can't really default this this.attemptsPermmitedPerExchange = 5; //this.killFileLocation = null; //no default this.emisDisabledOdsCodesAllowed = new HashSet<>(); this.emisAllowMissingCodes = false; this.emisAllowUnmappedRegistrationTypes = false; //this.emisSkipAdminData = false; this.softwareFormatsToDrainQueueOnFailure = new HashSet<>(); this.cernerPatientIdFile = null; this.cernerCDSEncountersOnly = false; this.bhrutPatientIdFile = null; this.maxTransformErrorsBeforeAbort = 50; this.warningsToFailOn = new ArrayList<>(); this.disableSavingResources = false; this.validateResourcesOnSaving = true; this.resourceCacheMaxSizeInMemory = 100000; this.isLive = false; this.resourceSaveBatchSize = 50; this.hmFileTypeFilters = new HashMap<>(); this.rabbitMessagePerSecondThrottle = 5000; this.emisOdsCodesAndStartDates = new HashMap<>(); this.adminBatchMaxSize = 30000; //largest known patient has 14k resources, so cap at double try { JsonNode json = ConfigManager.getConfigurationAsJson("common_config", "queuereader"); loadCommonConfig(json); json = ConfigManager.getConfigurationAsJson("emis_config", "queuereader"); loadEmisConfig(json); json = ConfigManager.getConfigurationAsJson("cerner_config", "queuereader"); loadCernerConfig(json); json = ConfigManager.getConfigurationAsJson("bhrut_config", "queuereader"); loadBhrutConfig(json); } catch (Exception ex) { //if the config record is there, just log it out rather than throw an exception LOG.error("", ex); } //LOG.debug("resourceSaveBatchSize = " + resourceSaveBatchSize); } private void loadCernerConfig(JsonNode json) { if (json == null) { return; } JsonNode node = json.get("patient_id_file"); if (node != null) { this.cernerPatientIdFile = node.asText(); } node = json.get("cds_encounters_only"); if (node != null) { this.cernerCDSEncountersOnly = node.asBoolean(); } } private void loadBhrutConfig(JsonNode json) { if (json == null) { return; } JsonNode node = json.get("patient_id_file"); if (node != null) { this.bhrutPatientIdFile = node.asText(); } } private void loadCommonConfig(JsonNode json) throws Exception { if (json == null) { LOG.warn("No common queuereader config found in config DB with app_id queuereader and config_id common_config"); return; } JsonNode node = json.get("shared_storage_path"); if (node != null) { this.sharedStoragePath = node.asText(); } node = json.get("disable_saving_resources"); if (node != null) { this.disableSavingResources = node.asBoolean(); } node = json.get("validate_resources_on_save"); if (node != null) { this.validateResourcesOnSaving = node.asBoolean(); } node = json.get("attempts_permmitted_per_exchange"); if (node != null) { this.attemptsPermmitedPerExchange = node.asInt(); } node = json.get("kill_file_location"); if (node != null) { this.killFileLocation = node.asText(); } node = json.get("shared_storage_path"); if (node != null) { this.sharedStoragePath = node.asText(); } node = json.get("transform_errors_before_abort"); if (node != null) { this.maxTransformErrorsBeforeAbort = node.asInt(); } node = json.get("resource_cache_max_size_in_memory"); if (node != null) { this.resourceCacheMaxSizeInMemory = node.asInt(); } node = json.get("is_live"); if (node != null) { this.isLive = node.asBoolean(); } node = json.get("resource_save_batch_size"); if (node != null) { this.resourceSaveBatchSize = node.asInt(); } node = json.get("rabbit_message_per_second_throttle"); if (node != null) { this.rabbitMessagePerSecondThrottle = node.asInt(); } node = json.get("emis"); if (node != null) { //the emis config should now be in a separate config record, but still apply it if it's still found as part of the common config loadEmisConfig(node); } node = json.get("cerner"); if (node != null) { //the cerner config should now be in a separate config record, but still apply it if it's still found as part of the common config loadCernerConfig(node); } node = json.get("bhrut"); if (node != null) { //the cerner config should now be in a separate config record, but still apply it if it's still found as part of the common config loadBhrutConfig(node); } node = json.get("subscriber"); if (node != null) { JsonNode subNode = node.get("allow_missing_concepts"); if (subNode != null) { this.allowMissingConceptIdsInSubscriberTransform = subNode.asBoolean(); } } node = json.get("drain_queue_on_failure"); if (node != null) { for (int i=0; i<node.size(); i++) { String software = node.get(i).asText(); this.softwareFormatsToDrainQueueOnFailure.add(software); } } node = json.get("warnings_to_fail_on"); if (node != null) { for (int i=0; i<node.size(); i++) { String s = node.get(i).asText(); Pattern pattern = Pattern.compile(s); this.warningsToFailOn.add(pattern); } } node = json.get("file_type_filters"); if (node != null) { for (int i=0; i<node.size(); i++) { JsonNode orgNode = node.get(i); JsonNode odsNode = orgNode.get("ods_code"); JsonNode typesNode = orgNode.get("file_types"); if (odsNode == null || typesNode == null) { LOG.error("Missing ods_code or file_types node under file_type_filters node"); continue; } String odsCode = odsNode.asText(); Set<String> fileTypes = new HashSet<>(); for (int j=0; j<typesNode.size(); j++) { String fileType = typesNode.get(j).asText(); fileTypes.add(fileType); } hmFileTypeFilters.put(odsCode, fileTypes); } } node = json.get("admin_batch_max_size"); if (node != null) { this.adminBatchMaxSize = node.asInt(); } } private void loadEmisConfig(JsonNode json) throws Exception { if (json == null) { return; } JsonNode subNode = json.get("disabled_ods_codes_allowed"); if (subNode != null) { for (int i=0; i<subNode.size(); i++) { String s = subNode.get(i).asText(); this.emisDisabledOdsCodesAllowed.add(s); } } subNode = json.get("allow_missing_codes"); if (subNode != null) { this.emisAllowMissingCodes = subNode.asBoolean(); } subNode = json.get("allow_unmapped_registration_types"); if (subNode != null) { this.emisAllowUnmappedRegistrationTypes = subNode.asBoolean(); } /*subNode = json.get("skip_admin_data"); if (subNode != null) { this.emisSkipAdminData = subNode.asBoolean(); }*/ subNode = json.get("start_dates"); if (subNode != null) { for (int i=0; i<subNode.size(); i++) { JsonNode orgNode = subNode.get(i); JsonNode odsNode = orgNode.get("ods_code"); JsonNode startDateNode = orgNode.get("start_date"); if (odsNode == null || startDateNode == null) { LOG.error("Missing ods_code or start_date node under emis start_dates node"); continue; } String odsCode = odsNode.asText(); String startDate = startDateNode.asText(); emisOdsCodesAndStartDates.put(odsCode, startDate); } } } public String getSharedStoragePath() { return sharedStoragePath; } public int getAttemptsPermmitedPerExchange() { return attemptsPermmitedPerExchange; } public String getKillFileLocation() { return killFileLocation; } public Set<String> getEmisDisabledOdsCodesAllowed() { return emisDisabledOdsCodesAllowed; } public boolean isEmisAllowMissingCodes() { return emisAllowMissingCodes; } public boolean isEmisAllowUnmappedRegistrationTypes() { return emisAllowUnmappedRegistrationTypes; } public Set<String> getSoftwareFormatsToDrainQueueOnFailure() { return softwareFormatsToDrainQueueOnFailure; } public int getResourceCacheMaxSizeInMemory() { return resourceCacheMaxSizeInMemory; } public int getMaxTransformErrorsBeforeAbort() { return maxTransformErrorsBeforeAbort; } public List<Pattern> getWarningsToFailOn() { return warningsToFailOn; } public boolean isDisableSavingResources() { return disableSavingResources; } public boolean isValidateResourcesOnSaving() { return validateResourcesOnSaving; } public boolean isLive() { return isLive; } public int getResourceSaveBatchSize() { return resourceSaveBatchSize; } public String getCernerPatientIdFile() { return cernerPatientIdFile; } public boolean isCernerCDSEncountersOnly() { return cernerCDSEncountersOnly; } public String getBhrutPatientIdFile() { return bhrutPatientIdFile; } public boolean isAllowMissingConceptIdsInSubscriberTransform() { return allowMissingConceptIdsInSubscriberTransform; } public Set<String> getFilteredFileTypes(String odsCode) { return hmFileTypeFilters.get(odsCode); } public int getRabbitMessagePerSecondThrottle() { return rabbitMessagePerSecondThrottle; } public String getEmisStartDate(String odsCode) { return emisOdsCodesAndStartDates.get(odsCode); } public int getAdminBatchMaxSize() { return adminBatchMaxSize; } /*public boolean isEmisSkipAdminData() { return emisSkipAdminData; }*/ }
true
170b8d5e76d0502d07ddd79a9b2915be93043d9d
Java
1ci/vigenere-cipher
/src/cryptography/Caesar.java
UTF-8
3,651
3.59375
4
[]
no_license
/** * Package to encapsulate cryptography exercises */ package cryptography; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import cryptography.Util; /** * The Caesar cipher, also known as a shift cipher, is one of the simplest forms * of encryption. It is a substitution cipher where each letter in the original * message (called the plaintext) is replaced with a letter corresponding to a * certain number of letters up or down in the alphabet. * * @author Hristo Hristov */ class Caesar { /** * Attempts a monoalphabetic cipher-attack based on a statistical frequency analysis. * Used to find the shift value of a Caesar cipher. * * @param sample A big chunk of English text * @param cipher The encrypted string of text * @return The most congruent shift value for the cipher based on the stats */ static int cryptAnalyse(Text sample, Text cipher) { System.out.println("Cryptanalysing monoalphabetical cipher..."); float[] deviation = new float[Util.ALPHABET_SIZE]; // Used to sort deviation values Map<Integer, Float> deviationMap = new LinkedHashMap<Integer, Float>(); // s means shift, l means letter for (int s = 0; s < Util.ALPHABET_SIZE; s++) { for (int l = 0; l < Util.ALPHABET_SIZE; l++) { deviation[s] += Math.abs( Util.getFrequency(sample.getLetterCount(l), sample.getTotalLetters()) - Util.getFrequency(cipher.getLetterCount((l + s) % Util.ALPHABET_SIZE), cipher.getTotalLetters())); } System.out.printf("Shifting the cipher by %2d deviates it from the norm by %6.2f %%\n", s, deviation[s]); // Used to sort deviation values deviationMap.put(s, deviation[s]); } System.out.println("\nSorting shift values by deviation..."); deviationMap = Util.sortMap(deviationMap, true, true); for (Entry<Integer, Float> entry : deviationMap.entrySet()) { System.out.printf("Shift: %2d | Deviation: %4.2f %%\n", entry.getKey(), entry.getValue()); } System.out.println(); return (Integer) deviationMap.keySet().toArray()[0]; } /** * Decrypts a a monoalphabetic caesar cipher given a shift value * * @param encryptedFile File to decrypt * @param decryptedFile File to store the decrypted version at * @param shift Shift value to use */ static void decrypt(File encryptedFile, File decryptedFile, int shift) { try { System.out.printf("Opening \"%s\" for decryption... ", encryptedFile.getPath()); // Open cipher for decryption FileReader reader = new FileReader(encryptedFile); // Create a file to store the decrypted version FileWriter writer = new FileWriter(decryptedFile); // Go through every letter of the cipher text int ch; while ((ch = reader.read()) != -1) { // Not sure if lowercasing is necessary, but I'll keep it ch = Character.toLowerCase(ch); // Keep numbers, spaces, punc. intact // assuming they're not encrypted if (ch < 'a' || ch > 'z') { writer.write(ch); continue; } // Perform the shift and write to the new file int decryptedch = ch - shift; decryptedch = Util.normalizeLetter(decryptedch); writer.write(decryptedch); } System.out.println("finished decrypting file."); System.out.printf("Decrypted version stored at: \"%s\"\n", decryptedFile.getPath()); reader.close(); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
true
5658b0f8c606a00dbf6c8b35a232b201cdf5df68
Java
KC007-007/Data_Structure
/Stack/StackArray.java
UTF-8
1,376
4
4
[]
no_license
package stack; import java.util.*; public class StackArray { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc =new Scanner(System.in); Stack st=new Stack(); System.out.println("How many values u want to enter the stack"); int n=sc.nextInt(); System.out.println("push the "+n+" value in stack "); for(int i=0;i<n;i++) st.push(sc.nextInt()); int x=st.peek(); System.out.println("peek value is = "+x); int p=st.pop(); System.out.println("pop value is = "+p); x=st.peek(); System.out.println("peek value is = "+x); boolean b=st.isEmpty(); System.out.println("empty?? = " + b); st.print(); } } class Stack { int size=1000; int top; int[] s=new int[size]; Stack() { top=-1; } boolean push(int x) { if(top>=size-1) { System.out.println("Stack OverFlow"); return false; } else { s[++top]=x; return true; } } int pop() { if(top<0) { System.out.println("Stack Underflow"); return 0; } else { int x=s[top--]; return x; } } int peek() { if(top<0) { System.out.println("Stack underflow"); return 0; } else { int x=s[top]; return x; } } boolean isEmpty() { return (top<0); } void print() { for(int i=top;i>-1;i--) System.out.println(s[top--]); } }
true
a51fccd5d68dc8a83574bab3a6a34d230227321b
Java
cahya12/blauweJpa
/src/main/java/com/mini/ejb/MiniProjectFeedback.java
UTF-8
5,197
2.296875
2
[]
no_license
package com.mini.ejb; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.enterprise.context.ApplicationScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Named; import javax.persistence.*; import org.primefaces.event.CellEditEvent; import org.primefaces.event.RowEditEvent; import com.mini.entity.Feedback; import com.verdin.jsf.domain.Car; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; @Named @ApplicationScoped public class MiniProjectFeedback { private static final Logger LOGGER = Logger.getLogger("JPA"); static EntityManagerFactory factory = null; static EntityManager entityManager = null; static int counter = 1000; Feedback _c = new Feedback(); List<Feedback> data = new ArrayList<Feedback>(); @SuppressWarnings("unchecked") @PostConstruct public void initiate() { try { System.out.println("running .... "); factory = Persistence.createEntityManagerFactory("TrainingUnit"); entityManager = factory.createEntityManager(); System.out.println("running .... 1"); System.out.println("running .... 2"); Query query = entityManager.createQuery("Select e " + "from Feedback e "); data = (List<Feedback>) query.getResultList(); /* viewTable(); */ } catch (Exception e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); e.printStackTrace(); } finally { } } public void testing() { try { System.out.println("running .... persistCourse 1"); persistCourse(entityManager); System.out.println("running .... persistCourse 2"); } catch (Exception e) { // LOGGER.log(Level.SEVERE, e.getMessage(), e); System.out.println(e.getMessage()); e.printStackTrace(); } } @PreDestroy public void destroyrun() { if (entityManager != null) { entityManager.close(); } if (factory != null) { factory.close(); } } private void persistCourse(EntityManager entityManager) { EntityTransaction transaction = entityManager.getTransaction(); try { transaction.begin(); Feedback c = new Feedback(); c.setFeedback_id(counter++); c.setUser_name("aaaa"); c.setEmail_id("ajeng@mail.com"); c.setSubject("mate"); c.setDescription("lala"); entityManager.persist(c); transaction.commit(); } catch (Exception e) { e.printStackTrace(); if (transaction.isActive()) { System.out.println("running .... persistCourse transaction.isActive()"); transaction.rollback(); } } } public void saveCourse() { EntityTransaction transaction = entityManager.getTransaction(); try { transaction.begin(); entityManager.persist(_c); transaction.commit(); initiate(); } catch (Exception e) { e.printStackTrace(); if (transaction.isActive()) { System.out.println("running .... persistCourse transaction.isActive()"); transaction.rollback(); } } } public void deleteTopic(int feedback_id) { EntityManager c = factory.createEntityManager(); c.getTransaction().begin(); c.flush(); c.clear(); // query // setParameter Query query = c.createQuery("DELETE Feedback e WHERE feedback_id = :feedback_id"); query.setParameter("feedback_id", feedback_id); query.executeUpdate(); c.getTransaction().commit(); c.close(); initiate(); } /** * @param id * * @return number of affected columns . */ public int deleteTopicById(int id) { Query query = entityManager.createNativeQuery("Delete from Feedback where ID=?"); query.setParameter(1, id); return query.executeUpdate(); } public void updateData(int feedback_id, String user_name, String email_id, String subject, String description) { EntityManager em = factory.createEntityManager(); em.getTransaction().begin(); Query query = em.createQuery( "update Feedback set user_name = :user_name, email_id = :email_id, subject = :subject, description = :description where feedback_id= :feedback_id"); query.setParameter("feedback_id", feedback_id).setParameter("user_name", user_name) .setParameter("email_id", email_id).setParameter("subject", subject) .setParameter("description", description); query.executeUpdate(); em.getTransaction().commit(); initiate(); } public void onRowEdit(RowEditEvent event) { FacesMessage msg = new FacesMessage("Feedback Edited"); FacesContext.getCurrentInstance().addMessage(null, msg); } public void onRowCancel(RowEditEvent event) { FacesMessage msg = new FacesMessage("Edit Cancelled"); FacesContext.getCurrentInstance().addMessage(null, msg); } public void onCellEdit(CellEditEvent event) { Object oldValue = event.getOldValue(); Object newValue = event.getNewValue(); if (newValue != null && !newValue.equals(oldValue)) { FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Cell Changed", "Old: " + oldValue + ", New:" + newValue); FacesContext.getCurrentInstance().addMessage(null, msg); } } public void setCourse(Feedback e) { this._c = e; } public Feedback getFeedback() { return _c; } public List<Feedback> getData() { return data; } }
true
91e3c2405b0ea36a09669df9cef2a6bb617d029c
Java
GSIL-Monitor/hotel-1
/dlt-server/src/main/java/com/travel/common/exception/ParameterException.java
UTF-8
733
2.28125
2
[ "Apache-2.0" ]
permissive
package com.travel.common.exception; /** * @Description 参数异常类 * @author Zhiping Sun <szp_9830@163.com> * @date 2017年12月31日 下午10:07:53 */ public class ParameterException extends RuntimeException { private static final long serialVersionUID = 6291174592480851243L; public ParameterException() { super(); } public ParameterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public ParameterException(String message, Throwable cause) { super(message, cause); } public ParameterException(String message) { super(message); } public ParameterException(Throwable cause) { super(cause); } }
true
4824cb9f1f6bb452208ca4a8e064d1633edc723c
Java
tarunreddy1018/Smart_Interviews
/TimeOfTheYear_11.java
UTF-8
587
3.140625
3
[]
no_license
import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; public class TimeOfTheYear_11 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int p=0;p<t;p++) { long s=sc.nextLong(); s=s*1000; Date d=new Date(s); SimpleDateFormat df=new SimpleDateFormat("dd-MMM-yyyy"); SimpleDateFormat df2=new SimpleDateFormat("EEEE"); System.out.println(df.format(d).toUpperCase()+" "+df2.format(d)); } } }
true
99a2467306fe8f1cea08d656ecbd1dbab55632eb
Java
Ice-K/ssyccjxy
/src/main/java/com/ssyccjxy/entity/system/dto/SysUserInfo.java
UTF-8
3,619
2.015625
2
[]
no_license
package com.ssyccjxy.entity.system.dto; import com.ssyccjxy.common.base.BaseEntity; import com.ssyccjxy.common.enums.IsLookEnum; import com.ssyccjxy.common.enums.OnJobEnum; import com.ssyccjxy.entity.system.SysMenu; import java.util.List; /** * Description: * Cteated by wangpeng * 2018/4/7 9:12 */ public class SysUserInfo extends BaseEntity { private static final long serialVersionUID = -27910734544075749L; /**用户id*/ private Integer id; /** 上级领导id. */ private Integer pid; /** 部门id. */ private Integer deptId; /** 部门名称. */ private String deptName; /** 登录名. */ private String username; /** 密码. */ private String password; /** 真实姓名. */ private String realName; /** 手机号. */ private String phone; /** 最后一次登录时间. */ private String lastLoginTime; /** 最后一次登录ip. */ private String lastLoginIp; /** 最后一次登录地址. */ private String lastLoginAdd; /** 是否为领导. */ private Integer head; /** 账号是否为锁定 0-否,1-是. */ private Integer isLook = IsLookEnum.NO_LOOK.getCode(); /** 状态:0-在职,1-离职. 2-复职. */ private Integer onJob = OnJobEnum.ON_JOB.getCode(); /** 用户所拥有的菜单. */ private List<SysMenu> Menus; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public Integer getDeptId() { return deptId; } public void setDeptId(Integer deptId) { this.deptId = deptId; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getLastLoginTime() { return lastLoginTime; } public void setLastLoginTime(String lastLoginTime) { this.lastLoginTime = lastLoginTime; } public String getLastLoginIp() { return lastLoginIp; } public void setLastLoginIp(String lastLoginIp) { this.lastLoginIp = lastLoginIp; } public String getLastLoginAdd() { return lastLoginAdd; } public void setLastLoginAdd(String lastLoginAdd) { this.lastLoginAdd = lastLoginAdd; } public Integer getHead() { return head; } public void setHead(Integer head) { this.head = head; } public Integer getIsLook() { return isLook; } public void setIsLook(Integer isLook) { this.isLook = isLook; } public Integer getOnJob() { return onJob; } public void setOnJob(Integer onJob) { this.onJob = onJob; } public List<SysMenu> getMenus() { return Menus; } public void setMenus(List<SysMenu> menus) { Menus = menus; } }
true
12c431aaa0a86086191d47f7e1bb65b6d986d7f3
Java
MohammedAbdo2344/Advanced-Calculator
/Calculetor.java
UTF-8
16,767
2.8125
3
[]
no_license
package calculetor; import java.lang.Math; import javafx.application.Application; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.StackPane; import javafx.stage.Stage; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; public class Calculetor extends Application { int base = 10; @Override public void start(Stage primaryStage) { //Boutons _ size // Button btn_add = new Button("+"); btn_add.setMinSize(35, 35); Button btn_sub = new Button("-"); btn_sub.setMinSize(35, 35); Button btn_multi = new Button("*"); btn_multi.setMinSize(35, 35); Button btn_div = new Button("/"); btn_div.setMinSize(35, 35); Button btn_int_div = new Button("//"); btn_int_div.setMinSize(35, 35); Button btn_modul = new Button("%"); btn_modul.setMinSize(35, 35); Button btn_power = new Button("^"); btn_power.setMinSize(35, 35); Button btn_log = new Button("log "); btn_log.setMinSize(35, 35); Button btn_fact = new Button("x!"); btn_fact.setMinSize(35, 35); Button btn_clear = new Button(" c "); btn_clear.setMinSize(150, 35); Button btn_Exit = new Button("Exit"); btn_Exit.setMinSize(150, 35); Button btn_check = new Button("Check"); btn_check.setMinSize(150, 35); //Text Field // TextField txt_x = new TextField(); txt_x.setMinSize(35, 35); TextField txt_y = new TextField(); txt_y.setMinSize(35, 35); //Label// Label lbl_res = new Label(); lbl_res.setMinSize(35,35); // size Label lbl_base = new Label("Base: "); lbl_base.setMinSize(35, 35); // ComboBox// ComboBox combo = new ComboBox(); combo.getItems().addAll("DEC", "HEX", "OCT", "BIN"); combo.setValue("DEC"); combo.setMinSize(110, 35);// size combo.valueProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue observable, String x, String y) { if (y.equals("DEC")) { base = 10; } else if (y.equals("HEX")) { base = 16; } else if (y.equals("OCT")) { base = 8; } else { base = 2; } } }); //actions // btn_add.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { double x = Double.parseDouble(txt_x.getText()); double y = Double.parseDouble(txt_y.getText()); lbl_res.setText(Double.toString(x + y)); EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { if (combo.getValue() == "HEX") { int a = (int) Double.parseDouble((Double.toString(x + y))); lbl_res.setText(Integer.toString(a, 16)); } else if (combo.getValue() == "OCT") { int a = (int) Double.parseDouble(Double.toString(x + y)); lbl_res.setText(Integer.toString(a, 8)); } else if (combo.getValue() == "BIN") { int a = (int) Double.parseDouble(Double.toString(x + y)); lbl_res.setText(Integer.toString(a, 2)); } else if (combo.getValue() == "DEC") { int a = (int) Double.parseDouble(Double.toString(x + y)); lbl_res.setText(Integer.toString(a, 10)); } } }; combo.setOnAction(event); } }); btn_sub.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { double x = Double.parseDouble(txt_x.getText()); double y = Double.parseDouble(txt_y.getText()); lbl_res.setText(Double.toString(x - y)); EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { if (combo.getValue() == "HEX") { int a = (int) Double.parseDouble((Double.toString(x - y))); lbl_res.setText(Integer.toString(a, 16)); } else if (combo.getValue() == "OCT") { int a = (int) Double.parseDouble(Double.toString(x - y)); lbl_res.setText(Integer.toString(a, 8)); } else if (combo.getValue() == "BIN") { int a = (int) Double.parseDouble(Double.toString(x - y)); lbl_res.setText(Integer.toString(a, 2)); } else if (combo.getValue() == "DEC") { int a = (int) Double.parseDouble(Double.toString(x - y)); lbl_res.setText(Integer.toString(a, 10)); } } }; combo.setOnAction(event); } }); btn_multi.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { double x = Double.parseDouble(txt_x.getText()); double y = Double.parseDouble(txt_y.getText()); lbl_res.setText(Double.toString(x * y)); EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { if (combo.getValue() == "HEX") { int a = (int) Double.parseDouble((Double.toString(x * y))); lbl_res.setText(Integer.toString(a, 16)); } else if (combo.getValue() == "OCT") { int a = (int) Double.parseDouble(Double.toString(x * y)); lbl_res.setText(Integer.toString(a, 8)); } else if (combo.getValue() == "BIN") { int a = (int) Double.parseDouble(Double.toString(x * y)); lbl_res.setText(Integer.toString(a, 2)); } else if (combo.getValue() == "DEC") { int a = (int) Double.parseDouble(Double.toString(x * y)); lbl_res.setText(Integer.toString(a, 10)); } } }; combo.setOnAction(event); } }); btn_div.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { double x = Double.parseDouble(txt_x.getText()); double y = Double.parseDouble(txt_y.getText()); try { double sum = x / y; } catch (ArithmeticException eee) { lbl_res.setText("Invalid operation: " + eee.getMessage()); } lbl_res.setText(Double.toString(x / y)); EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { if (combo.getValue() == "HEX") { int a = (int) Double.parseDouble((Double.toString(x / y))); lbl_res.setText(Integer.toString(a, 16)); } else if (combo.getValue() == "OCT") { int a = (int) Double.parseDouble(Double.toString(x / y)); lbl_res.setText(Integer.toString(a, 8)); } else if (combo.getValue() == "BIN") { int a = (int) Double.parseDouble(Double.toString(x / y)); lbl_res.setText(Integer.toString(a, 2)); } else if (combo.getValue() == "DEC") { int a = (int) Double.parseDouble(Double.toString(x / y)); lbl_res.setText(Integer.toString(a, 10)); } } }; combo.setOnAction(event); } }); btn_int_div.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { int x = (int) Double.parseDouble(txt_x.getText()); int y = (int) Double.parseDouble(txt_y.getText()); lbl_res.setText(Integer.toString(x / y)); EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { if (combo.getValue() == "HEX") { int a = (int) Double.parseDouble((Double.toString(x / y))); lbl_res.setText(Integer.toString(a, 16)); } else if (combo.getValue() == "OCT") { int a = (int) Double.parseDouble(Double.toString(x / y)); lbl_res.setText(Integer.toString(a, 8)); } else if (combo.getValue() == "BIN") { int a = (int) Double.parseDouble(Double.toString(x / y)); lbl_res.setText(Integer.toString(a, 2)); } else if (combo.getValue() == "DEC") { int a = (int) Double.parseDouble(Double.toString(x / y)); lbl_res.setText(Integer.toString(a, 10)); } } }; combo.setOnAction(event); } }); btn_modul.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { double x = Double.parseDouble(txt_x.getText()); double y = Double.parseDouble(txt_y.getText()); lbl_res.setText(Double.toString(x % y)); EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { if (combo.getValue() == "HEX") { int a = (int) Double.parseDouble((Double.toString(x % y))); lbl_res.setText(Integer.toString(a, 16)); } else if (combo.getValue() == "OCT") { int a = (int) Double.parseDouble(Double.toString(x % y)); lbl_res.setText(Integer.toString(a, 8)); } else if (combo.getValue() == "BIN") { int a = (int) Double.parseDouble(Double.toString(x % y)); lbl_res.setText(Integer.toString(a, 2)); } else if (combo.getValue() == "DEC") { int a = (int) Double.parseDouble(Double.toString(x % y)); lbl_res.setText(Integer.toString(a, 10)); } } }; combo.setOnAction(event); } }); btn_power.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { double x = Double.parseDouble(txt_x.getText()); double y = Double.parseDouble(txt_y.getText()); lbl_res.setText(Double.toString(Math.pow(x, y))); EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { if (combo.getValue() == "HEX") { int a = (int) Double.parseDouble((Double.toString(Math.pow(x, y)))); lbl_res.setText(Integer.toString(a, 16)); } else if (combo.getValue() == "OCT") { int a = (int) Double.parseDouble(Double.toString(Math.pow(x, y))); lbl_res.setText(Integer.toString(a, 8)); } else if (combo.getValue() == "BIN") { int a = (int) Double.parseDouble(Double.toString(Math.pow(x, y))); lbl_res.setText(Integer.toString(a, 2)); } else if (combo.getValue() == "DEC") { int a = (int) Double.parseDouble(Double.toString(Math.pow(x, y))); lbl_res.setText(Integer.toString(a, 10)); } } }; combo.setOnAction(event); } }); btn_log.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { double x = Double.parseDouble(txt_x.getText()); double y = Double.parseDouble(txt_y.getText()); lbl_res.setText(Double.toString(Math.log(x) / Math.log(y))); } }); btn_fact.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { int i, fact = 1; double x = Double.parseDouble(txt_x.getText()); double number = x; for (i = 1; i <= number; i++) { fact = fact * i; } lbl_res.setText(Double.toString(fact)); } }); btn_clear.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { double x = Double.parseDouble(txt_x.getText()); double y = Double.parseDouble(txt_y.getText()); lbl_res.setText(""); } }); btn_Exit.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { System.exit(0); } }); btn_check.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { try { int x = Integer.parseInt(txt_x.getText(), base); int y = Integer.parseInt(txt_x.getText(), base); } catch (NumberFormatException ex) { lbl_res.setText("invalid input "); } } }); // place in scene // HBox box = new HBox(); box.getChildren().addAll(lbl_base, combo); GridPane grid = new GridPane(); grid.setVgap(10); grid.add(box, 0, 4); grid.add(txt_x, 0, 0); grid.add(txt_y, 0, 1); grid.add(lbl_res, 0, 2); grid.add(btn_clear, 0, 3); grid.add(btn_add, 1, 2); grid.add(btn_sub, 1, 3); grid.add(btn_multi, 1, 4); grid.add(btn_div, 1, 5); grid.add(btn_int_div, 2, 2); grid.add(btn_modul, 2, 3); grid.add(btn_power, 2, 4); grid.add(btn_log, 2, 5); grid.add(btn_fact, 1, 6); grid.add(btn_Exit, 0, 6); grid.add(btn_check, 0, 5); // scene Scene scene = new Scene(grid, 275, 350); primaryStage.setTitle("Calc"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
true
79d8ef7cd6de1b421d88bd681fae2c4ca9fbe3c9
Java
huangzhaohuii/demo
/src/main/java/com/example/demo/utils/SignUtil.java
UTF-8
2,730
3.03125
3
[]
no_license
package com.example.demo.utils; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; /** * 签名工具类 * */ public class SignUtil { public static String getSortParams(Map<String, String> params) { params.remove("sign"); String contnt = ""; Set<String> keySet = params.keySet(); List<String> keyList = new ArrayList<String>(); // 这个接口做sign签名时,值为空的参数也传 for (String key : keySet) { String value = params.get(key); // 将值为空的参数排除 /* * if (!StringUtil.isNull(value)) { keyList.add(key); } */ keyList.add(key); } Collections.sort(keyList, new Comparator<String>() { @Override public int compare(String o1, String o2) { int length = Math.min(o1.length(), o2.length()); for (int i = 0; i < length; i++) { char c1 = o1.charAt(i); char c2 = o2.charAt(i); int r = c1 - c2; if (r != 0) { // char值小的排前边 return r; } } // 2个字符串关系是str1.startsWith(str2)==true // 取str2排前边 return o1.length() - o2.length(); } }); // 将参数和参数值按照排序顺序拼装成字符串 for (int i = 0; i < keyList.size(); i++) { String key = keyList.get(i); contnt += key + params.get(key); } return contnt; } public static String toKey(Map<String, String> params){ String content = ""; Set<String> keySet = params.keySet(); List<String> keyList = new ArrayList<String>(); //这个接口做sign签名时,值为空的参数也传 for (String key : keySet) { String value = params.get(key); // 将值为空的参数排除 /*if (!StringUtil.isNull(value)) { keyList.add(key); }*/ keyList.add(key); } //将参数和参数值按照排序顺序拼装成字符串 for (int i = 0; i < keyList.size(); i++) { String key = keyList.get(i); if (i == keyList.size() - 1) { content += key + "=" + params.get(key); return content; } content += key + "=" + params.get(key) + "&"; } return content; } public static String sign(String content, String charset) { if (charset == null || "".equals(charset)) { charset = "UTF-8"; } String sign = ""; try { content = new String(content.getBytes(), charset); System.out.println(">>>>>>>>>>>>>"+content); MessageDigest md5 = MessageDigest.getInstance("SHA-256");//MD5 sign = BASE64Encoder.encode(md5.digest(content.getBytes(charset))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return sign; } }
true
b5e64dab5fedc954ed85cb5d3604892b2443011b
Java
tzieba1/JavaProjects
/SearchingAlgorithms_LOTR/src/com/tzieba/BookCharacter.java
UTF-8
1,008
3.296875
3
[]
no_license
package com.tzieba; import java.util.ArrayList; public class BookCharacter implements Positions { private final String name; private int appearanceCount; private int closenessCount; private double closenessFactor; private ArrayList<Integer> positions = new ArrayList<>(); public BookCharacter(String name) { this.name = name; this.appearanceCount = 0; this.closenessCount = 0; } public String getName() { return this.name; } public void incrementClosenessCount() { closenessCount++; closenessFactor = (double) closenessCount / appearanceCount; } @Override public String toString() { return String.format("[%-10s, %d] is close to the Ring %d times with a closeness factor of %5.4f", name, appearanceCount, closenessCount, closenessFactor); } @Override public void addPosition(int position) { positions.add(position); appearanceCount++; } @Override public ArrayList<Integer> getPositions() { return positions; } }
true
1b17bcd0db002e4fe977230fb186dabd907ed3f2
Java
xiehp/AnimeShotSite
/AnimeShotSite-core/src/main/java/xie/common/utils/aware/AuditorAwareImpl.java
UTF-8
1,052
2.34375
2
[]
no_license
package xie.common.utils.aware; import org.apache.shiro.SecurityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.AuditorAware; import xie.sys.auth.service.realm.ShiroRDbRealm.ShiroUser; /** * JPA AuditorAware实现 * 实现获取当前系统操作的用户 名称 * * */ public class AuditorAwareImpl implements AuditorAware<String>{ private Logger _log = LoggerFactory.getLogger(AuditorAwareImpl.class); /** * 返回当前登陆用户的ID * @return * @see org.springframework.data.domain.AuditorAware#getCurrentAuditor() */ public String getCurrentAuditor() { String userId = null; try{ if(SecurityUtils.getSubject() == null || SecurityUtils.getSubject().getPrincipal() == null){ // userId = "未登录用户"; userId = null; }else{ ShiroUser user = (ShiroUser)SecurityUtils.getSubject().getPrincipal(); userId = user.id; } }catch(Exception e){ userId = null; _log.debug("获取当前用户id失败!"); } return userId; } }
true
8e11afca4a148c3eec7f8c16f3271e71402c8b57
Java
nightwolf93/Wakxy-Core-Decompiled
/1_39_120042/com/ankamagames/wakfu/client/core/game/interactiveElement/StorageBox.java
UTF-8
7,180
1.914063
2
[]
no_license
package com.ankamagames.wakfu.client.core.game.interactiveElement; import org.apache.log4j.*; import com.ankamagames.wakfu.common.game.storageBox.*; import com.ankamagames.framework.kernel.core.common.serialization.*; import java.nio.*; import com.ankamagames.baseImpl.common.clientAndServer.game.interactiveElement.*; import com.ankamagames.wakfu.client.core.game.characterInfo.occupation.*; import com.ankamagames.wakfu.client.ui.protocol.frame.*; import com.ankamagames.framework.kernel.events.*; import com.ankamagames.wakfu.common.game.characterInfo.*; import com.ankamagames.wakfu.common.game.interactiveElements.param.*; import com.ankamagames.wakfu.common.game.interactiveElements.param.type.*; import com.ankamagames.wakfu.client.ui.mru.MRUActions.*; import com.ankamagames.wakfu.common.game.skill.*; import com.ankamagames.wakfu.client.core.*; import com.ankamagames.baseImpl.client.proxyclient.base.game.interactiveElement.*; import com.ankamagames.framework.kernel.core.common.*; import org.apache.commons.pool.*; public class StorageBox extends WakfuClientMapInteractiveElement { private static final Logger m_logger; private IEStorageBoxParameter m_info; private StorageBoxInventory m_inventory; private final BinarSerialPart SYNCHRO_PART; public StorageBox() { super(); this.SYNCHRO_PART = new BinarSerialPart() { @Override public void serialize(final ByteBuffer buffer) { throw new UnsupportedOperationException("Pas de serialization dans le client"); } @Override public void unserialize(final ByteBuffer buffer, final int version) { for (int numTabUnlocked = buffer.getInt(), i = 0; i < numTabUnlocked; ++i) { StorageBox.this.m_inventory.createCompartment(StorageBox.this.m_info.getFromId(buffer.getInt())); } } @Override public int expectedSize() { return 4 + StorageBox.this.m_inventory.size() * 4; } }; } @Override public boolean onAction(final InteractiveElementAction action, final InteractiveElementUser user) { switch (action) { case START_BROWSING: { this.runScript(action); final BasicOccupation occupation = new BrowseStorageBoxOccupation(this); if (!occupation.isAllowed()) { StorageBox.m_logger.error((Object)"[STORAGE_BOX] Impossible de d\u00e9marrer le browsing"); return false; } occupation.begin(); this.sendActionMessage(action); UIStorageBoxFrame.getInstance().setStorageBox(this); WakfuGameEntity.getInstance().pushFrame(UIStorageBoxFrame.getInstance()); return true; } case STOP_BROWSING: { this.runScript(action); if (WakfuGameEntity.getInstance().hasFrame(UIStorageBoxFrame.getInstance())) { WakfuGameEntity.getInstance().removeFrame(UIStorageBoxFrame.getInstance()); } this.sendActionMessage(action); WakfuGameEntity.getInstance().getLocalPlayer().finishCurrentOccupation(); return true; } default: { StorageBox.m_logger.error((Object)("Impossible d'effectuer l'action " + action), (Throwable)new IllegalArgumentException()); return false; } } } @Override protected BinarSerialPart getSynchronizationSpecificPart() { return this.SYNCHRO_PART; } public InteractiveElementAction getInteractiveDefaultAction() { return InteractiveElementAction.START_BROWSING; } @Override public InteractiveElementAction[] getInteractiveUsableActions() { return new InteractiveElementAction[] { InteractiveElementAction.START_BROWSING, InteractiveElementAction.STOP_BROWSING }; } @Override public void onCheckOut() { super.onCheckOut(); this.setBlockingLineOfSight(true); this.setBlockingMovements(true); this.setOverHeadable(true); this.setUseSpecificAnimTransition(true); assert this.m_info == null; assert this.m_inventory == null; } @Override public void onCheckIn() { super.onCheckIn(); this.setBlockingLineOfSight(false); this.setBlockingMovements(false); this.setOverHeadable(false); this.setUseSpecificAnimTransition(false); this.m_info = null; this.m_inventory = null; } @Override public void initializeWithParameter() { this.m_info = (IEStorageBoxParameter)IEParametersManager.INSTANCE.getParam(IETypes.STORAGE_BOX, Integer.parseInt(this.m_parameter)); if (this.m_info == null) { StorageBox.m_logger.error((Object)("Impossible de trouver le param\u00e8tre " + this.m_parameter)); return; } this.m_inventory = new StorageBoxInventory(this.m_info.size()); } @Override public AbstractMRUAction[] getInteractiveMRUActions() { final ActionVisual visual = ActionVisualManager.getInstance().get(this.m_info.getVisualId()); final MRUInteractifMachine action = MRUActions.INTERACTIF_ACTION.getMRUAction(); action.setGfxId(visual.getMruGfx()); action.setTextKey("desc.mru." + visual.getMruLabelKey()); return new AbstractMRUAction[] { action }; } @Override public String getName() { return WakfuTranslator.getInstance().getString(104, this.m_info.getId(), new Object[0]); } public StorageBoxInventory getInventory() { return this.m_inventory; } @Override public void onViewUpdated(final ClientInteractiveElementView view) { } public IEStorageBoxParameter getInfo() { return this.m_info; } @Override public String toString() { return "StorageBox{m_info=" + this.m_info + ", m_inventory=" + this.m_inventory + '}'; } static { m_logger = Logger.getLogger((Class)StorageBox.class); } public static class Factory extends ObjectFactory<WakfuClientMapInteractiveElement> { public static final MonitoredPool POOL; @Override public WakfuClientMapInteractiveElement makeObject() { StorageBox ie; try { ie = (StorageBox)Factory.POOL.borrowObject(); ie.setPool(Factory.POOL); } catch (Exception e) { StorageBox.m_logger.error((Object)"Erreur lors de l'extraction du pool", (Throwable)e); ie = new StorageBox(); } return ie; } static { POOL = new MonitoredPool(new ObjectFactory<StorageBox>() { @Override public StorageBox makeObject() { return new StorageBox(); } }); } } }
true
9ed51ef59ded7842b889ba999ee0cbd979eb6054
Java
moutainhigh/chdHRP
/src/com/chd/hrp/med/dao/requrie/dept/MedRequireConfirmMapper.java
UTF-8
1,255
1.664063
2
[]
no_license
/** * @Description: * @Copyright: Copyright (c) 2015-9-16 下午9:54:34 * @Company: 智慧云康(北京)数据科技有限公司 * @网站:www.s-chd.com */ package com.chd.hrp.med.dao.requrie.dept; import java.util.List; import java.util.Map; import org.apache.ibatis.session.RowBounds; import org.springframework.dao.DataAccessException; import com.chd.base.SqlMapper; import com.chd.hrp.med.entity.MedRequireDetail; import com.chd.hrp.med.entity.MedRequireMain; /** * * @Description: * 科室购置计划审核 * @Author: bell * @email: bell@s-chd.com * @Version: 1.0 */ public interface MedRequireConfirmMapper extends SqlMapper{ /** * 科室购置计划--审核 * @param listVo * @return * @throws DataAccessException */ public int updateAudit(List<Map<String, Object>> listVo) throws DataAccessException; /** * 科室购置计划--取消审核 * @param listVo * @return * @throws DataAccessException */ public int updateAuditCancle(List<Map<String, Object>> listVo) throws DataAccessException; /** * 科室购置计划--退回科室 * @param listVo * @return * @throws DataAccessException */ public int updateReturn(List<Map<String, Object>> listVo) throws DataAccessException; }
true
179ef380eb40d8cfb728b87534f73997a975d3f0
Java
charwliu/carbon-datasources
/components/org.wso2.carbon.datasource.core/src/main/java/org/wso2/carbon/datasource/rdbms/hikari/HikariConstants.java
UTF-8
592
2.15625
2
[ "Apache-2.0" ]
permissive
package org.wso2.carbon.datasource.rdbms.hikari; /** * Class holding the default values for Hikari configuration. */ public class HikariConstants { /** * Private constructor. */ private HikariConstants() { } public static final long CONNECTION_TIME_OUT = 30000; public static final long IDLE_TIME_OUT = 600000; public static final long MAX_LIFE_TIME = 1800000; public static final int MAXIMUM_POOL_SIZE = 10; /** * Default value for auto commit flag (for a connection). */ public static final boolean AUTO_COMMIT = true; }
true
8183400b258b477a0ac8cc41b160574414d3050a
Java
XHHuiL/JavaConcurrentPractice
/src/com/company/foo/ThreeWaysToUseThread.java
UTF-8
1,288
3.78125
4
[]
no_license
package com.company.foo; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; public class ThreeWaysToUseThread { // First Way: implements Callable interface private static class MyCallable implements Callable<String> { @Override public String call() throws InterruptedException { Thread.sleep(1000); System.out.println("Call MyCallable"); return "MyCallable"; } } // Second Way: implements Runnable interface private static class MyRunnable implements Runnable { @Override public void run() { System.out.println("Run MyRunnable"); } } // Third Way: extends Thread class private static class MyThread extends Thread { @Override public void run() { System.out.println("Run MyThread"); super.run(); } } public static void main(String[] args) { MyCallable myCallable = new MyCallable(); FutureTask<String> task = new FutureTask<>(myCallable); Thread thread = new Thread(task); thread.start(); thread = new Thread(new MyRunnable()); thread.start(); MyThread myThread = new MyThread(); myThread.start(); } }
true
9f91ef618cb17415b10632ab1238f77b5ae2c9a6
Java
Garnet0314/SAO-MOD
/sao/mods/client/renderer/RenderHPBarHelper.java
UTF-8
543
2.5
2
[]
no_license
package sao.mods.client.renderer; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; public class RenderHPBarHelper { private static final int FONT_HEIGHT = 12; public static final void renderStringWithBackGround(FontRenderer fontRenderer, String string, int x, int y, int font_color, int bg_color) { int string_w = fontRenderer.getStringWidth(string); Gui.drawRect(x, y, x + string_w, y + 12, bg_color); fontRenderer.drawString(string, x, y, font_color, false); } }
true
a703cdadf964b2d044ec74949b391d0ea73be2cf
Java
shilun/common
/src/main/java/com/common/util/StringUtils.java
UTF-8
1,629
2.65625
3
[]
no_license
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package com.common.util; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringUtils extends org.apache.commons.lang.StringUtils { public StringUtils() { } public boolean isNull(Object o) { return o == null; } public boolean isBlank(Object o) { return o == null; } public static boolean isMobileNO(String mobiles) { Pattern p = Pattern.compile("^1[34578]\\d{9}$"); Matcher m = p.matcher(mobiles); return m.matches(); } public static boolean isEmail(String email) { Pattern pattern = Pattern.compile("^\\w+([-.]\\w+)*@\\w+([-]\\w+)*\\.(\\w+([-]\\w+)*\\.)*[a-z]{2,3}$"); Matcher matcher = pattern.matcher(email); return matcher.matches(); } public static String getUUID() { return replace(UUID.randomUUID().toString(), "-", ""); } public static String getDomainName(String url) { url = url.toLowerCase(); Matcher m = Pattern.compile("^http://[^/]+").matcher(url); return m.find()?m.group():""; } public static String getSubTitleName(String title, Integer subSize) { return isNotBlank(title)?(title.length() > subSize.intValue()?title.substring(0, subSize.intValue()) + "....":title):""; } public static boolean isContains(String text, String subText) { return text.contains(subText); } public static void main(String[] args) { System.out.println(getUUID()); } }
true
ad54f99e396c78c5300eac06ca1bf94f1a4d0319
Java
SaraAmirsardari/CMMN-MODELS-HAND-DRAWN-SKETCH-RECOGNITION-SYSTEM
/CoordinatesOfLines.java
UTF-8
939
2.9375
3
[]
no_license
package CMMNElementsketchRecognitionSystem; /** * * @author * */ /** * This class gets and sets the coordinates of lines * @author SaraAmirsardari */ public class CoordinatesOfLines{ private double x1; private double y1; private double x2; private double y2; private int id; /** * This class defines the coordinate of each line inside the input image */ public CoordinatesOfLines(double x1, double y1, double x2, double y2,int id) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; this.id = id; } public double getX1() { return x1; } public double getY1() { return y1; } public double getX2() { return x2; } public double getY2() { return y2; } public int getid() { return id; } public String toString(){ return "start point: ("+this.x1+","+this.y1+"), end point: ("+this.x2+","+this.y2+")"; } }
true
3c17e3386e7a76df2935ca5f98a1d0b4e08c9522
Java
wangko27/nuls_2.0
/block/src/main/java/io/nuls/block/thread/BlockConsumer.java
UTF-8
2,312
2.21875
2
[ "MIT" ]
permissive
/* * MIT License * Copyright (c) 2017-2018 nuls.io * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.nuls.block.thread; import io.nuls.base.data.Block; import io.nuls.block.manager.ContextManager; import io.nuls.block.service.BlockService; import io.nuls.tools.log.Log; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; /** * 消费同步到的区块 * @author captain * @date 18-11-8 下午5:45 * @version 1.0 */ public class BlockConsumer implements Callable<Boolean> { private BlockingQueue<Block> blockQueue; private int chainId; private BlockService blockService = ContextManager.getServiceBean(BlockService.class); public BlockConsumer(int chainId, BlockingQueue<Block> blockQueue) { this.blockQueue = blockQueue; this.chainId = chainId; } @Override public Boolean call() { try { Block block; while ((block = blockQueue.take()) != null) { boolean saveBlock = blockService.saveBlock(chainId, block); if (!saveBlock) { return false; } } return true; } catch (InterruptedException e) { Log.error(e); return false; } } }
true
a7835b9ad27d2563a8c5a44f2c7be6a3ca5e2320
Java
andrei-aleksanian/Mashed
/Mashed/src/mashed/alertboxes/ReadyToQuitAlertBox.java
UTF-8
672
2.921875
3
[]
no_license
package mashed.alertboxes; import mashed.scenes.MainMenu; public class ReadyToQuitAlertBox extends ReadyAlertBox{ public ReadyToQuitAlertBox(String message, String buttonText) { super(message, buttonText); // What closeButton (the one that displays "Yes") does on action button(); // Display the alert box display(); } private void button() { // When you click on the button that displays "Yes!" closeButton.setOnAction(e -> { // It closes the alert box window window.close(); // Switch to main menu state MainMenu mainMenu = new MainMenu(); }); } }
true
17a363d3f5eba49b9669e197ed03dc1aafb029b3
Java
rahmanpq/mono-repo-parent-child
/projectB/src/main/java/com/example/projectB/UserKafkaProcessor.java
UTF-8
1,056
2.0625
2
[]
no_license
package com.example.projectB; import com.example.projectB.service.ConsumerService; import org.apache.kafka.streams.KeyValue; import org.apache.kafka.streams.kstream.KStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.cloud.stream.annotation.StreamListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.function.Function; import static java.lang.String.format; @Configuration("UserKafkaProcessor") public class UserKafkaProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(UserKafkaProcessor.class); @Bean public Function<KStream<String, com.example.projectB.models.Customer>, KStream<String, com.example.projectB.models.Customer>> userProcessor() { LOGGER.info(format("*****-> Consume Stream Message ---->")); return kstream -> kstream.map( (key, value) -> KeyValue.pair(key, value)); } }
true
01a5ceac9fc426190e0ae1c433716cdc0961399e
Java
sgholamian/log-aware-clone-detection
/LACCPlus/Camel/1929_1.java
UTF-8
1,611
2.296875
2
[ "MIT" ]
permissive
//,temp,HBaseConsumer.java,157,192,temp,MyBatisConsumer.java,105,158 //,3 public class xxx { @Override public int processBatch(Queue<Object> exchanges) throws Exception { int total = exchanges.size(); // limit if needed if (maxMessagesPerPoll > 0 && total > maxMessagesPerPoll) { LOG.debug("Limiting to maximum messages to poll {} as there were {} messages in this poll.", maxMessagesPerPoll, total); total = maxMessagesPerPoll; } for (int index = 0; index < total && isBatchAllowed(); index++) { // only loop if we are started (allowed to run) Exchange exchange = ObjectHelper.cast(Exchange.class, exchanges.poll()); // add current index and total as properties exchange.setProperty(ExchangePropertyKey.BATCH_INDEX, index); exchange.setProperty(ExchangePropertyKey.BATCH_SIZE, total); exchange.setProperty(ExchangePropertyKey.BATCH_COMPLETE, index == total - 1); // update pending number of exchanges pendingExchanges = total - index - 1; LOG.trace("Processing exchange [{}]...", exchange); getProcessor().process(exchange); if (exchange.getException() != null) { // if we failed then throw exception throw exchange.getException(); } if (endpoint.isRemove()) { remove((byte[]) exchange.getIn().getHeader(HBaseAttribute.HBASE_MARKED_ROW_ID.asHeader())); } } return total; } };
true
ca58ff93a101d84515f15818015ca20f8e6c2168
Java
alexandraback/datacollection
/solutions_5652388522229760_1/java/exoji2e/A.java
UTF-8
836
3.265625
3
[]
no_license
import java.util.Scanner; public class A { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); for(int i = 1; i<=n; i++) { int m = sc.nextInt(); if(m == 0) { System.out.println("Case #" + i + ": INSOMNIA"); continue; } boolean[] found = new boolean[10]; int now = m; int x = now; while(x>0) { found[x%10] = true; x = x/10; } boolean passed = true; for(int j = 0; j<10;j++) { if(!found[j]) { passed = false; break; } } while(!passed) { now += m; x = now; while(x>0) { found[x%10] = true; x = x/10; } passed = true; for(int j = 0; j<10;j++) { if(!found[j]) { passed = false; break; } } } System.out.println("Case #" + i + ": " + now); } } }
true
787a2e5a449115a78ea74d76fde260d9aabbcd73
Java
Vancheung/TestEngineering
/_3_Learning/_02_Algorithms/Week1/PercolationStats.java
UTF-8
2,242
3.328125
3
[]
no_license
import edu.princeton.cs.algs4.StdRandom; import edu.princeton.cs.algs4.StdStats; public class PercolationStats { public static final double ONE_POINT_96 = 1.96; private final double[] probability; private double mean = 0.0d; private double stddev = 0.0d; // perform independent trials on an n-by-n grid public PercolationStats(int n, int trials) { if (n <= 0 || trials <= 0) throw new IllegalArgumentException("Wrong Value! Please check your Input!"); probability = new double[trials]; for (int i = 0; i < trials; i++) { Percolation pc = new Percolation(n); while (!pc.percolates()) { pc.open(StdRandom.uniform(n) + 1, StdRandom.uniform(n) + 1); } probability[i] = (double) pc.numberOfOpenSites() / (n * n); } } // sample mean of percolation threshold public double mean() { if (Double.compare(0.0d, mean) == 0) mean = StdStats.mean(probability); return mean; } // sample standard deviation of percolation threshold public double stddev() { if (Double.compare(0.0d, stddev) == 0) stddev = StdStats.stddev(probability); return stddev; } // low endpoint of 95% confidence interval public double confidenceLo() { return mean - ONE_POINT_96 * stddev / Math.sqrt(probability.length); } // high endpoint of 95% confidence interval public double confidenceHi() { return mean + ONE_POINT_96 * stddev / Math.sqrt(probability.length); } // test client (see below) public static void main(String[] args) { int n = Integer.parseInt(args[0]); int times = Integer.parseInt(args[1]); PercolationStats stats = new PercolationStats(n, times); System.out.println("mean = " + stats.mean()); System.out.println("stddev = " + stats.stddev()); System.out.println("95% confidence interval = [" + stats.confidenceLo() + ", " + stats.confidenceHi() + "]"); } }
true
c642704c44cf836ae0d51f9260f10c8f13494498
Java
thundersilence/BigNews
/BigNews/src/com/model/filein.java
UTF-8
1,036
2.6875
3
[]
no_license
package com.model; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import javax.imageio.ImageIO; public class filein { public static void put(String dir, String url, BufferedImage bi) throws IOException { File file = new File(dir); if (!file.exists()) { file.mkdirs(); } FileOutputStream fos = new FileOutputStream(url); ImageIO.write(bi,"JPG", fos); fos.close(); } public static void putnew(String dir, String url, BufferedImage bi) throws IOException { File file = new File(dir); if (!file.exists()) { file.mkdirs(); }else { file.delete(); file.mkdirs(); System.out.println("ssssssssssssssssssss"); } System.out.println("=================================="); FileOutputStream fos = new FileOutputStream(url); ImageIO.write(bi,"JPG", fos); fos.close(); } }
true
7872936700b099c8acae34c15f8dacc01d6fb218
Java
saka1029/MiniSat-J
/src/jp/saka1029/minisatj/core/Dimacs.java
UTF-8
5,063
2.15625
2
[ "MIT" ]
permissive
package jp.saka1029.minisatj.core; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import jp.saka1029.minisatj.utils.Parser; ///****************************************************************************************[Dimacs.h] //Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson //Copyright (c) 2007-2010, Niklas Sorensson // //Permission is hereby granted, free of charge, to any person obtaining a copy of this software and //associated documentation files (the "Software"), to deal in the Software without restriction, //including without limitation the rights to use, copy, modify, merge, publish, distribute, //sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in all copies or //substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT //NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND //NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, //DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT //OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. //**************************************************************************************************/ // //#ifndef Minisat_Dimacs_h //#define Minisat_Dimacs_h // //#include <stdio.h> // //#include "utils/ParseUtils.h" //#include "core/SolverTypes.h" // //namespace Minisat { // ////================================================================================================= //// DIMACS Parser: public class Dimacs { // //template<class B, class Solver> //static void readClause(B& in, Solver& S, vec<Lit>& lits) { // int parsed_lit, var; // lits.clear(); // for (;;){ // parsed_lit = parseInt(in); // if (parsed_lit == 0) break; // var = abs(parsed_lit)-1; // while (var >= S.nVars()) S.newVar(); // lits.push( (parsed_lit > 0) ? mkLit(var) : ~mkLit(var) ); // } //} // // //template<class B, class Solver> //static void parse_DIMACS_main(B& in, Solver& S) { // vec<Lit> lits; // int vars = 0; // int clauses = 0; // int cnt = 0; // for (;;){ // skipWhitespace(in); // if (*in == EOF) break; // else if (*in == 'p'){ // if (eagerMatch(in, "p cnf")){ // vars = parseInt(in); // clauses = parseInt(in); // // SATRACE'06 hack // // if (clauses > 4000000) // // S.eliminate(true); // }else{ // printf("PARSE ERROR! Unexpected char: %c\n", *in), exit(3); // } // } else if (*in == 'c' || *in == 'p') // skipLine(in); // else{ // cnt++; // readClause(in, S, lits); // S.addClause_(lits); } // } // if (vars != S.nVars()) // fprintf(stderr, "WARNING! DIMACS header mismatch: wrong number of variables.\n"); // if (cnt != clauses) // fprintf(stderr, "WARNING! DIMACS header mismatch: wrong number of clauses.\n"); //} //template<class B, class Solver> public static void parse_DIMACS_main(Reader reader, Solver S) throws IOException { Parser in = new Parser(reader); VecLit lits = new VecLit(); int vars = 0; int clauses = 0; int cnt = 0; for (;;) { String token = in.read(); if (token == null) break; else if (token.equals("c")) in.skipLine(); else if (token.equals("p")) { token = in.read(); if (!token.equals("cnf")) throw new IOException("PARSE ERROR! 'cnf' expected after 'p'%n"); vars = in.readInt(); clauses = in.readInt(); } else { ++cnt; lits.clear(); for (;;){ int parsed_lit = Integer.parseInt(token); if (parsed_lit == 0) break; int var = Math.abs(parsed_lit) - 1; while (var >= S.nVars()) S.newVar(); lits.push(Lit.valueOf(var, parsed_lit < 0)); token = in.read(); } S.addClause_(lits); } } if (vars != S.nVars()) throw new IOException("WARNING! DIMACS header mismatch: wrong number of variables."); if (cnt != clauses) throw new IOException("WARNING! DIMACS header mismatch: wrong number of clauses."); } // //// Inserts problem into solver. //// //template<class Solver> //static void parse_DIMACS(gzFile input_stream, Solver& S) { // StreamBuffer in(input_stream); // parse_DIMACS_main(in, S); } public static void parse_DIMACS(Reader reader, Solver S) throws IOException { parse_DIMACS_main(new BufferedReader(reader), S); } // ////================================================================================================= //} // //#endif }
true
59ac1f4e00b419efcf95fdb90a4ba748ac5c9457
Java
hmarinoo/cursomc
/src/main/java/com/cursomc/CursomcApplication.java
UTF-8
4,764
2.234375
2
[]
no_license
package com.cursomc; import java.text.SimpleDateFormat; import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.cursomc.domain.Categoria; import com.cursomc.domain.Cidade; import com.cursomc.domain.Cliente; import com.cursomc.domain.Endereco; import com.cursomc.domain.Estado; import com.cursomc.domain.ItemPedido; import com.cursomc.domain.Pagamento; import com.cursomc.domain.PagamentoComBoleto; import com.cursomc.domain.PagamentoComCartao; import com.cursomc.domain.Pedido; import com.cursomc.domain.Product; import com.cursomc.domain.enums.EstadoPagamento; import com.cursomc.domain.enums.TipoCliente; import com.cursomc.repositories.CategoriaRepository; import com.cursomc.repositories.CidadeRepository; import com.cursomc.repositories.ClienteRepository; import com.cursomc.repositories.EnderecoRepository; import com.cursomc.repositories.EstadoRepository; import com.cursomc.repositories.ItemPedidoRepsitory; import com.cursomc.repositories.PagamentoRepository; import com.cursomc.repositories.PedidoRepository; import com.cursomc.repositories.ProductRepository; @SpringBootApplication public class CursomcApplication implements CommandLineRunner { @Autowired private CategoriaRepository catRepo; @Autowired private ProductRepository prodRepo; @Autowired private CidadeRepository cidRepo; @Autowired private EstadoRepository estRepo; @Autowired private ClienteRepository cliRepo; @Autowired private EnderecoRepository enderecoRepo; @Autowired private PedidoRepository pedidoRepo; @Autowired private PagamentoRepository pagamentoRepo; @Autowired private ItemPedidoRepsitory itemPedidoRepo; private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm"); public static void main(String[] args) { SpringApplication.run(CursomcApplication.class, args); } @Override public void run(String... args) throws Exception { Categoria cat1 = new Categoria(null, "Informática"); Categoria cat2 = new Categoria(null, "Escritorio"); Product p1 = new Product(null, "Computador", 2000.00); Product p2 = new Product(null, "Impressora", 800.00); Product p3 = new Product(null, "Mouse", 80.00); cat1.getProdutos().addAll(Arrays.asList(p1,p2,p3)); cat2.getProdutos().add(p2); p1.getCategorias().add(cat1); p2.getCategorias().addAll(Arrays.asList(cat1,cat2)); p3.getCategorias().add(cat1); catRepo.saveAll(Arrays.asList(cat1,cat2)); prodRepo.saveAll(Arrays.asList(p1,p2,p3)); Estado est1 = new Estado(null,"Minas Gerais"); Estado est2 = new Estado(null,"São Paulo"); Cidade c1 = new Cidade(null, "Uberlandia",est1); Cidade c2 = new Cidade(null, "São Paulo",est2); Cidade c3 = new Cidade(null, "Campinas",est2); est1.getCidades().addAll(Arrays.asList(c1)); est2.getCidades().addAll(Arrays.asList(c2,c3)); estRepo.saveAll(Arrays.asList(est1,est2)); cidRepo.saveAll(Arrays.asList(c1,c2,c3)); Cliente cli1 = new Cliente(null, "Maria Silva", "Maria@gmail.com", "36378912377", TipoCliente.PESSOAFISICA); cli1.getTelefones().addAll(Arrays.asList("27363323","9383893")); Endereco e1 = new Endereco(null, "Rua Flores", "300", "Apto 203", "Jardim", "38220834",cli1, c1); Endereco e2 = new Endereco(null, "Avenida Matoss", "105", "Sala 800", "Centro", "38777012",cli1, c2); cli1.getEnderecos().addAll(Arrays.asList(e1,e2)); cliRepo.saveAll(Arrays.asList(cli1)); enderecoRepo.saveAll(Arrays.asList(e1,e2)); Pedido ped1 = new Pedido(null, sdf.parse("30/09/2017 10:32"), cli1, e1); Pedido ped2 = new Pedido(null, sdf.parse("10/10/2017 10:32"), cli1, e1); cli1.getPedidos().addAll(Arrays.asList(ped1,ped2)); Pagamento pagto1 = new PagamentoComCartao(null,EstadoPagamento.QUITADO,ped1,6); ped1.setPagamento(pagto1); Pagamento pagto2 = new PagamentoComBoleto(null, EstadoPagamento.PENDENTE, ped2, sdf.parse("20/10/2017 00:00"), null); ped2.setPagamento(pagto2); enderecoRepo.saveAll(Arrays.asList(e1,e2)); pedidoRepo.saveAll(Arrays.asList(ped1,ped2)); pagamentoRepo.saveAll(Arrays.asList(pagto1,pagto2)); ItemPedido ip1 = new ItemPedido(ped1, p1, 0.00, 1, p1.getValue()); ItemPedido ip2 = new ItemPedido(ped1, p3, 0.00, 2, p3.getValue()); ItemPedido ip3 = new ItemPedido(ped2, p2, 100.00, 1, p2.getValue()); ped1.getItems().addAll(Arrays.asList(ip1,ip2)); ped2.getItems().addAll(Arrays.asList(ip3)); p1.getItems().addAll(Arrays.asList(ip1)); p2.getItems().addAll(Arrays.asList(ip3)); p3.getItems().addAll(Arrays.asList(ip2)); itemPedidoRepo.saveAll(Arrays.asList(ip1,ip2,ip3)); } }
true
edd02b959e594a1595c6df20eb712877cbccf3a5
Java
andrewPompa/smart-hotel
/src/main/java/com/dynamics/andrzej/smart/hotel/respositories/SeasonPriceRepository.java
UTF-8
778
2.046875
2
[]
no_license
package com.dynamics.andrzej.smart.hotel.respositories; import com.dynamics.andrzej.smart.hotel.entities.ChangedPricePeriod; import com.dynamics.andrzej.smart.hotel.entities.Receptionist; import com.dynamics.andrzej.smart.hotel.entities.SeasonPrice; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; @Repository public interface SeasonPriceRepository extends JpaRepository<SeasonPrice, Long> { @Query("select s from SeasonPrice s where s.fromDay <= ?1 and s.fromMonth <= ?2 and s.toDay >= ?3 and s.toMonth < ?4") List<SeasonPrice> findAllInDate(int fromDay, int fromMonth, int toDay, int toMonth); }
true
bb7c8c47e77b466f3f45f616f0a6e741e1be5f05
Java
pludov/ScopeExpress
/ScopeExpress/src/fr/pludov/scopeexpress/ui/utils/tiles/TileProducer.java
UTF-8
240
2.046875
2
[]
no_license
package fr.pludov.scopeexpress.ui.utils.tiles; import java.awt.image.BufferedImage; public interface TileProducer { BufferedImage produce(int offsetx, int offsety, BufferedImage area); @Override public boolean equals(Object obj); }
true
a088f919a9094d2392f49998da373d7fb0bb61ce
Java
autovalue/jdownloader-trunk
/src/org/jdownloader/statistics/AbstractTrackEntry.java
UTF-8
223
1.640625
2
[]
no_license
package org.jdownloader.statistics; import java.io.IOException; import jd.http.Browser; public interface AbstractTrackEntry extends StatsLogInterface { public void send(Browser br) throws IOException; }
true
90ae3d93203da0d635c24ae64c3d2ef8adfca466
Java
joej326/java-course
/test-project/src/com/company/Main.java
UTF-8
292
2.359375
2
[]
no_license
package com.company; public class Main { public static void main(String[] args) { System.out.println("hello world!"); System.out.println("That is it, everybody scout!"); } public static String joe(String[] stringArray){ return stringArray[0]; } }
true
7bf023e81abe791e5c90fc8a0f7c5be2989de2aa
Java
jorgeluis1997/SM1-PracticaCalificada8-Completable-y-HttpUrlConnection
/Autores/app/src/main/java/com/desarrollo/autores/Json/Conexion.java
UTF-8
685
2.484375
2
[]
no_license
package com.desarrollo.autores.Json; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public class Conexion { public static HttpURLConnection connect(String jsonURL) { try { URL url = new URL(jsonURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(15000); connection.setReadTimeout(15000); connection.setDoInput(true); return connection; } catch (IOException e) { e.printStackTrace(); return null; } } }
true
4e61d5037e49a2c789b4ffbedaf6e7e3da2b5061
Java
jam1987/digraphs
/codeBase/resources/Digraph.java
UTF-8
571
2.8125
3
[]
no_license
abstract public class Digraph { protected int num_nodes; protected int num_arcs; public Digraph(int n) { num_nodes = n; num_arcs = 0; } public int num_nodes() { return this.num_nodes; } public int num_arcs() { return this.num_arcs; } abstract public void clear(); abstract public void add_node(int n); abstract public void add_arc(int i, int j); abstract public void remove_arc(int i, int j); abstract public boolean is_arc(int i, int j); public abstract void RoyWarshall(Digraph digraph) ; }
true
ac23ae1aeafe6d8007f43081834199def4444c36
Java
CaioAndreucci95/Empresa
/src/empresa/Empresa.java
UTF-8
684
2.5
2
[]
no_license
/* * 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 empresa; /** * * @author 13.03349-2 */ public class Empresa { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Funcionario caio = new Gerente("Caio", "453.303.138-21",1000000); Funcionario tiago = new Funcionario( "Tiago" , "123456789" ,50000 ); if(caio instanceof Gerente){ ((Gerente)caio).demite(tiago); } } }
true
269770a0b05ac35c73ea943bce59b1e43a1aa4f8
Java
AyoubMoujane/SplitPay
/src/main/java/core/models/UserToBankAccount.java
UTF-8
1,389
3.0625
3
[]
no_license
package core.models; import java.util.Date; /** * Model of the UserToBankAccount which represents the transaction from a User's balance to a BankAccount. * * @author Julien Wiegandt * @version 1.0 * @since 2021-01-05 */ public class UserToBankAccount extends Transaction { private int sender_fk; private int receiver_fk; /** * UserToBankAccount's constructor. * * @param amount * @param dateCreated * @param sender_fk * @param receiver_fk */ public UserToBankAccount(Float amount, Date dateCreated, int sender_fk, int receiver_fk) { this.name = "UserToBankAccount"; this.amount = amount; this.dateCreated = dateCreated; this.sender_fk = sender_fk; this.receiver_fk = receiver_fk; } public int getSender_fk() { return sender_fk; } public void setSender_fk(int sender_fk) { this.sender_fk = sender_fk; } public int getReceiver_fk() { return receiver_fk; } public void setReceiver_fk(int receiver_fk) { this.receiver_fk = receiver_fk; } /** * Represents the transaction. * * @return the String representation of the transaction. */ public String toString() { return "To BankAccount " + this.getReceiver_fk() + ": -" + this.getAmount() + "€ on " + this.getDateCreated().toString(); } }
true
104d219d1c2f1444b9a9ec10e3ae0ef8eba6ee22
Java
aru21/Ajax-SpringBoot
/src/main/java/com/my/demo/Repository/StateRepository.java
UTF-8
280
1.5
2
[]
no_license
package com.my.demo.Repository; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.my.demo.Pojo.State; @Repository public interface StateRepository extends CrudRepository<State , Integer> { }
true
a1d40588184abff015512d612909e62e236c4e96
Java
pawandhamankar225/JavaSE
/JavaSE/Static_Block/src/myclass.java
UTF-8
370
3.03125
3
[]
no_license
class base { static { System.out.println("in base static"); } base() { System.out.println("base const"); } } class sub extends base { static { System.out.println("in sub static"); } } public class myclass { public static void main(String args[]) { base b=new base(); System.out.println("...................."); sub s=new sub(); } }
true
356c331d2a563aa795383838ba7dd09534aa7a5b
Java
achowdhury80/leetcode
/src/comp/prep2019/less1000/Prob503.java
UTF-8
1,072
3.5625
4
[]
no_license
package comp.prep2019.less1000; import java.util.*; public class Prob503 { /** * O(N) time and space * @param nums * @return */ public int[] nextGreaterElements(int[] nums) { int max = Integer.MIN_VALUE, n = nums.length; int[] result = new int[n]; if (n < 1) return result; int start = 0; for (int i = 0; i < n; i++) { if (nums[i] > max) { max = nums[i]; start = i; } } result[start] = -1; Stack<Integer> stack = new Stack<>(); stack.push(max); int idx = (start - 1 + n) % n; while (idx != start) { while(!stack.isEmpty() && stack.peek() <= nums[idx]) { stack.pop(); } if (stack.isEmpty()) result[idx] = -1; else result[idx] = stack.peek(); stack.push(nums[idx]); idx = (idx - 1 + n) % n; } return result; } public static void main(String[] args) { Prob503 prob = new Prob503(); System.out.println(prob.nextGreaterElements(new int[] {1, 2, 1})); } }
true
faf3ff8f22e6330962ede8b231731c9590a957db
Java
matheuslemke/mongoTeste
/src/main/java/model/Logradouro.java
UTF-8
2,512
2.59375
3
[]
no_license
package model; import java.io.Serializable; import org.bson.Document; import com.mongodb.BasicDBObject; @SuppressWarnings("serial") public class Logradouro extends BasicDBObject implements Serializable { private long idLogradouro; private long idCidade; private TipoLogradouro idTipoLogradouro; private String descricao; private long codigo; public Logradouro(long idLogradouro, long idCidade, TipoLogradouro idTipoLogradouro, String descricao, long codigo) { this.idLogradouro = idLogradouro; this.idCidade = idCidade; this.idTipoLogradouro = idTipoLogradouro; this.descricao = descricao; this.codigo = codigo; } public long getIdLogradouro() { return idLogradouro; } public void setIdLogradouro(long idLogradouro) { this.idLogradouro = idLogradouro; } public long getIdCidade() { return idCidade; } public void setIdCidade(long idCidade) { this.idCidade = idCidade; } public TipoLogradouro getIdTipoLogradouro() { return idTipoLogradouro; } public void setIdTipoLogradouro(TipoLogradouro idTipoLogradouro) { this.idTipoLogradouro = idTipoLogradouro; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public long getCodigo() { return codigo; } public void setCodigo(long codigo) { this.codigo = codigo; } @Override public String toJson() { BasicDBObject doc = new BasicDBObject(); doc.put("IDLOGRADOURO", (int) this.getIdLogradouro()); doc.put("IDCIDADE", (int) this.getIdCidade()); doc.put("IDTIPOLOGRADOURO", this.getIdTipoLogradouro().toJson()); doc.put("DESCRICAO", this.getDescricao()); doc.put("CODIGO", (int) this.getCodigo()); return doc.toString(); } public static Logradouro toObject(Document doc) { long idLogradouro = doc.getInteger("IDLOGRADOURO"); long idCidade = doc.getInteger("IDCIDADE"); Document db = (Document) doc.get("IDTIPOLOGRADOURO"); TipoLogradouro idTipoLogradouro = TipoLogradouro.toObject(db); String descricao = doc.getString("DESCRICAO"); long codigo = doc.getInteger("CODIGO"); Logradouro log = new Logradouro(idLogradouro, idCidade, idTipoLogradouro, descricao, codigo); return log; } @Override public String toString() { return "Logradouro [idLogradouro=" + idLogradouro + ", idCidade=" + idCidade + ", idTipoLogradouro=" + idTipoLogradouro + ", descricao=" + descricao + ", codigo=" + codigo + "]"; } }
true
e9735526c5933ef597e4cf02023ef87f8606b830
Java
yinzhiqiang007/spring-cloud
/ys-sharp/api/src/main/java/com/quinn/app/sharp/mapper/UserInfoMapper.java
UTF-8
379
1.601563
2
[]
no_license
package com.quinn.app.sharp.mapper; import com.baomidou.dynamic.datasource.annotation.DS; import com.quinn.app.sharp.entity.UserInfo; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * 客户用户信息 Mapper 接口 * </p> * * @author yinzhiqiang * @since 2019-11-11 */ @DS("slave_1") public interface UserInfoMapper extends BaseMapper<UserInfo> { }
true
79ff8220b0a3af8ce967bf997013e840cfab0994
Java
valoeghese/ShuttleGUI
/src/main/java/shuttlegui/system/TreeNode.java
UTF-8
92
2.140625
2
[]
no_license
package shuttlegui.system; interface TreeNode<T, S extends TreeNode<T, S>> { T build(); }
true
640b88698c9d58b34b6d0941800b84fc54e7e06e
Java
vikramramasahayam/JavaForBeginners
/src/com/main/inheritance/CarMain.java
UTF-8
244
2.359375
2
[]
no_license
package com.main.inheritance; import com.inheritance.ICar; public class CarMain { public static void main(String[] args) { ICar car = new Honda(); car.getCarName(); car.getTitle(); car.getMake(); ((Honda)car).getModel(); } }
true