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
d1a3c3ca2b74ffad86c6f5ed552d0ba5b2cfb4ca
Java
rturquetti/TrabFinal
/app/src/main/java/com/example/rafael/trabfinal/ManagerPecaOrcAdapter.java
UTF-8
2,342
2.28125
2
[]
no_license
package com.example.rafael.trabfinal; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; /** * Created by rafael on 05/12/2016. */ public class ManagerPecaOrcAdapter extends AppCompatActivity { private ListView listPecasOrc; private Peca pecaClicada; ArrayList<Peca> pecas = new ArrayList<Peca>(); protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_orcamento); listPecasOrc = (ListView) findViewById(R.id.listPecasOrc); //informar à listview para abrir o menu quando clicar registerForContextMenu(listPecasOrc); listPecasOrc.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View view, int posicao, long id) { pecaClicada = (Peca) adapter.getItemAtPosition(posicao); Toast.makeText(getApplicationContext(), "clicando", Toast.LENGTH_LONG).show(); } }); listPecasOrc.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapter, View view, int posicao, long id) { pecaClicada = (Peca) adapter.getItemAtPosition(posicao); return false; } }); } protected void onResume() { super.onResume(); atualizaLista(); } public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { MenuItem deletar = menu.add("Remover"); deletar.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { pecas.remove(pecaClicada); return false; } }); } public void atualizaLista(){ pecas.add(pecaClicada); ListaPecaOrcAdapter adapter = new ListaPecaOrcAdapter(pecas,this); listPecasOrc.setAdapter(adapter); } }
true
8d277cc8813b7112575066266315cbebaba90a43
Java
ksereda/Spring_Cloud_Netflix_Microservices
/feign-client/src/main/java/com/example/feignclient/example_1/ServiceFeignClient.java
UTF-8
437
1.8125
2
[]
no_license
package com.example.feignclient.example_1; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import java.util.List; @FeignClient(name = "service_statistics") public interface ServiceFeignClient { @GetMapping("/users/{id}/statistics") public List<UserModel> getStatistics(@PathVariable String id); }
true
678f4f5bbb8a6fee30c1e05496b34d6e9761744f
Java
ericchangzmm/apollo
/core/plugin-framework/src/main/java/com/jijesoft/boh/core/plugin/servlet/PluginHttpRequestWrapper.java
UTF-8
3,467
2.828125
3
[]
no_license
package com.jijesoft.boh.core.plugin.servlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import com.jijesoft.boh.core.plugin.servlet.descriptors.BaseServletModuleDescriptor; /** * A request wrapper for requests bound for servlets declared in plugins. Does the necessary path * munging for requests so that they look like they are */ public class PluginHttpRequestWrapper extends HttpServletRequestWrapper { private final String basePath; public PluginHttpRequestWrapper(HttpServletRequest request, BaseServletModuleDescriptor<?> descriptor) { super(request); this.basePath = findBasePath(descriptor); } public String getServletPath() { String servletPath = super.getServletPath(); if (basePath != null) { servletPath += basePath; } return servletPath; } public String getPathInfo() { String pathInfo = super.getPathInfo(); if (pathInfo != null && basePath != null) { if (basePath.equals(pathInfo)) { return null; } else { return pathInfo.substring(basePath.length()); } } return pathInfo; } /** * A <a href="http://bluxte.net/blog/2006-03/29-40-33.html">commenter</a> based on the * <a href="http://java.sun.com/products/servlet/2.1/html/introduction.fm.html#1499">servlet mapping spec</a> * defined the mapping processing as: * * <ol> * <li>A string beginning with a '/' character and ending with a '/*' postfix is used for path mapping.</li> * <li>A string beginning with a'*.' prefix is used as an extension mapping.</li> * <li>A string containing only the '/' character indicates the "default" servlet of the application. In this * case the servlet path is the request URI minus the context path and the path info is null.</li> * <li>All other strings are used for exact matches only.</li> * </ol> * * To find the base path we're really only interested in the first and last case. Everything else will just get a * null base path. So we'll iterate through the list of paths specified and for the ones that match (1) above, * check if the path info returned by the super class matches. If it does, we return that base path, otherwise we * move onto the next one. */ private String findBasePath(BaseServletModuleDescriptor<?> descriptor) { String pathInfo = super.getPathInfo(); if (pathInfo != null) { for (String basePath : descriptor.getPaths()) { if (isPathMapping(basePath)) { if (pathInfo.startsWith(getMappingRootPath(basePath))) { return getMappingRootPath(basePath); } } else if (basePath.equals(pathInfo)) { // Exact match return basePath; } } } return null; } private boolean isPathMapping(String path) { return path.startsWith("/") && path.endsWith("/*"); } private String getMappingRootPath(String pathMapping) { return pathMapping.substring(0, pathMapping.length() - 2); } }
true
eb565037b248b400205512f70e3ba67d4b269fd8
Java
moutainhigh/cfamily
/familyhas/src/main/java/com/cmall/familyhas/api/result/APiForExpressCompanyResult.java
UTF-8
603
1.9375
2
[]
no_license
package com.cmall.familyhas.api.result; import java.util.ArrayList; import java.util.List; import com.cmall.familyhas.api.model.LogisticseInfo; import com.srnpr.zapcom.baseannotation.ZapcomApi; import com.srnpr.zapcom.topapi.RootResult; public class APiForExpressCompanyResult extends RootResult{ @ZapcomApi(value = "公司列表", require = 1) private List<LogisticseInfo> companyList=new ArrayList<LogisticseInfo>(); public List<LogisticseInfo> getCompanyList() { return companyList; } public void setCompanyList(List<LogisticseInfo> companyList) { this.companyList = companyList; } }
true
cab59c2a60781dbc9d37a0e7fd8fe035e07af93b
Java
hcomb/test
/test-workflow-engine-simple/src/test/java/test/TestJsonMarshaller03.java
UTF-8
2,480
2.5625
3
[]
no_license
package test; import hcomb.eu.workflow.engine.EasyFlow; import hcomb.eu.workflow.engine.StatefulContext; import hcomb.eu.workflow.engine.call.ContextHandler; import hcomb.eu.workflow.engine.call.StateHandler; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TestJsonMarshaller03 { public static void main(String[] args) throws Exception { EasyFlow<StatefulContext> flow = TestParser.parseWorkflow("test03.json"); ContextHandler<StatefulContext> enterCtx = new ContextHandler<StatefulContext>() { public void call(StatefulContext context) throws Exception { System.out.println(" * entering "+context.getState()); } }; ContextHandler<StatefulContext> leaveCtx = new ContextHandler<StatefulContext>() { public void call(StatefulContext context) throws Exception { System.out.println(" * leaving "+context.getState()); } }; final ExecutorService service = Executors.newSingleThreadExecutor(); flow.executor(service); flow.whenEnter("NEW_POLICY_SIGNED", enterCtx); flow.whenLeave("NEW_POLICY_SIGNED", leaveCtx); flow.whenEnter("CREATE_PDF_DOCUMENT", enterCtx); flow.whenLeave("CREATE_PDF_DOCUMENT", leaveCtx); flow.whenEnter("SAVE_DOCUMENT", enterCtx); flow.whenLeave("SAVE_DOCUMENT", leaveCtx); flow.whenEnter("SEND_EMAIL", enterCtx); flow.whenLeave("SEND_EMAIL", leaveCtx); flow.whenEnter("END", enterCtx); flow.whenLeave("END", leaveCtx); flow.whenFinalState(new StateHandler<StatefulContext>() { public void call(String stateEnum, StatefulContext statefulContext) throws Exception { System.out.println("finished."); service.shutdown(); } }); StatefulContext ctx = new StatefulContext(); //ctx.setState(States.SAVE_DOCUMENT); flow.trace().start(ctx); Thread.sleep(1000); ctx.trigger("onPolicySigned"); Thread.sleep(1000); ctx.trigger("onDocumentCreated"); Thread.sleep(1000); ctx.trigger("testBack"); Thread.sleep(1000); ctx.trigger("onDocumentCreated"); Thread.sleep(1000); ctx.trigger("onDocumentSaved"); Thread.sleep(1000); ctx.trigger("onEmailSent"); Thread.sleep(1000); System.out.println("terminated? " + ctx.isTerminated()); } }
true
0e35938171e33bde6612841bfd44b74d37002860
Java
kailash9820/RemoveDuplicatewsSprinBootProject
/src/main/java/com/project/dao/UserService.java
UTF-8
1,096
2.515625
3
[]
no_license
package com.project.dao; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import com.project.SpringAppProjectApplication; @Service public class UserService { public String getFinalData(String data) { data = data.replaceAll("\\s", ""); String output=removeDuplicate(data); return output; } static String removeDuplicate(String data) { char[] chars = data.toCharArray(); char previous = chars[0]; int k = 0; int i = 1; int Count=0; while (i < chars.length) { if (previous != chars[i]) { chars[++k] = chars[i++]; previous = chars[k]; } else { while (i < chars.length && previous == chars[i]) { i++; } Count++; if(k>1) previous = chars[--k]; else k=-1; } } String output=new String(chars).substring(0, k + 1); return output+"-"+Count; } }
true
33c65332715dac2452281f25946f37ec0824897d
Java
nathan-phan/Portfolio-Optimizer
/src/main/java/com/cs490/dao/PortfolioDAO.java
UTF-8
36,725
2
2
[]
no_license
package com.cs490.dao; import java.io.IOException; import java.math.BigDecimal; import java.math.RoundingMode; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.IOUtils; import org.apache.log4j.net.SyslogAppender; import com.cs490.database.MySqlConnector; import com.cs490.servlet.MainServlet; import com.cs490.vo.GoogleStock; import com.cs490.vo.PortfolioVO; import com.cs490.vo.RecordVO; import com.cs490.vo.StockPriceComparator; import com.cs490.vo.StockSnapshotVO; import com.cs490.vo.StockVO; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.google.gson.JsonParser; import yahoofinance.Stock; import yahoofinance.YahooFinance; import yahoofinance.histquotes.HistoricalQuote; public class PortfolioDAO { public static boolean checkDuplicatePortfolioName(String portName, String userName) throws SQLException { Connection connection = null; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); } PreparedStatement prepStmt = null; try { String query = "SELECT portfolio_name FROM portfolios WHERE user_id=? AND portfolio_name=? and flag=0"; prepStmt = connection.prepareStatement(query); prepStmt.setString(1, userName); prepStmt.setString(2, portName); ResultSet rs = prepStmt.executeQuery(); if(!rs.next()){ prepStmt.close(); return false; } prepStmt.close(); return true; } catch(Exception e){ e.printStackTrace(); return false; } finally { connection.close(); } } public static boolean addPortfolio(String portName, String userName) throws SQLException { Connection connection = null; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); } PreparedStatement prepStmt = null; try { String query = "INSERT INTO portfolios (user_id, portfolio_name, current_balance) " + "VALUES(?,?,?)"; prepStmt = connection.prepareStatement(query); prepStmt.setString(1, userName); prepStmt.setString(2, portName); prepStmt.setBigDecimal(3, new BigDecimal(0)); prepStmt.executeUpdate(); prepStmt.close(); return true; } catch(Exception e){ e.printStackTrace(); return false; } finally { connection.close(); } } public static LinkedHashMap<StockVO, Integer> findCurrentStocksByPortfolioId(int portId) throws SQLException { Connection connection = null; LinkedHashMap<StockVO, Integer> stocks = new LinkedHashMap<StockVO, Integer>(); try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); } PreparedStatement prepStmt = null; try { String query = "SELECT stock_symbol, shares FROM portfolio_stocks WHERE portfolio_id=? and shares <> 0"; prepStmt = connection.prepareStatement(query); prepStmt.setInt(1, portId); ResultSet rs = prepStmt.executeQuery(); while(rs.next()){ StockVO stock = new StockVO(rs.getString(1)); stocks.put(stock, rs.getInt(2)); } prepStmt.close(); return stocks; } catch(Exception e){ e.printStackTrace(); return stocks; } finally { connection.close(); } } public static LinkedHashMap<StockVO, Integer> findAllStocksByPortfolioId(int portId) throws SQLException { Connection connection = null; LinkedHashMap<StockVO, Integer> stocks = new LinkedHashMap<StockVO, Integer>(); try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); } PreparedStatement prepStmt = null; try { String query = "SELECT stock_symbol, shares FROM portfolio_stocks WHERE portfolio_id=?"; prepStmt = connection.prepareStatement(query); prepStmt.setInt(1, portId); ResultSet rs = prepStmt.executeQuery(); while(rs.next()){ StockVO stock = new StockVO(rs.getString(1)); stocks.put(stock, rs.getInt(2)); } prepStmt.close(); return stocks; } catch(Exception e){ e.printStackTrace(); return stocks; } finally { connection.close(); } } public static int findStockShares(String symbol, int id) throws SQLException { Connection connection = null; int result = -1; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); } PreparedStatement prepStmt = null; try { String query = "SELECT shares FROM portfolio_stocks WHERE portfolio_id=? and stock_symbol=?"; prepStmt = connection.prepareStatement(query); prepStmt.setInt(1, id); prepStmt.setString(2, symbol); ResultSet rs = prepStmt.executeQuery(); if(rs.next()){ result = rs.getInt(1); } prepStmt.close(); return result; } catch(Exception e){ e.printStackTrace(); return result; } finally { connection.close(); } } public static PortfolioVO getPortfolioById(int portfolioId) throws SQLException { Connection connection = null; PortfolioVO port = new PortfolioVO(); try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); } PreparedStatement prepStmt = null; try { String query = "SELECT portfolio_name, current_balance FROM portfolios WHERE portfolio_id=?"; prepStmt = connection.prepareStatement(query); prepStmt.setInt(1, portfolioId); ResultSet rs = prepStmt.executeQuery(); while(rs.next()){ port.setName(rs.getString(1)); port.setBalance(rs.getBigDecimal(2)); port.setId(portfolioId); LinkedHashMap<StockVO, Integer> stocks = findCurrentStocksByPortfolioId(portfolioId); port.setStocks(stocks); } prepStmt.close(); return port; } catch(Exception e){ e.printStackTrace(); return port; } finally { connection.close(); } } public static PortfolioVO getPortfolioByIdForReport(int portfolioId) throws SQLException { Connection connection = null; PortfolioVO port = new PortfolioVO(); try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); } PreparedStatement prepStmt = null; try { String query = "SELECT portfolio_name, current_balance FROM portfolios WHERE portfolio_id=?"; prepStmt = connection.prepareStatement(query); prepStmt.setInt(1, portfolioId); ResultSet rs = prepStmt.executeQuery(); while(rs.next()){ port.setName(rs.getString(1)); port.setBalance(rs.getBigDecimal(2)); port.setId(portfolioId); LinkedHashMap<StockVO, Integer> stocks = findAllStocksByPortfolioId(portfolioId); port.setStocks(stocks); } prepStmt.close(); return port; } catch(Exception e){ e.printStackTrace(); return port; } finally { connection.close(); } } public static boolean insertStockToPortfolio(int id, String symbol, int shares, boolean firstTime) throws SQLException { boolean result = false; Connection connection = null; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); return false; } PreparedStatement prepStmt = null; try { if(firstTime){ String query = "INSERT INTO portfolio_stocks(portfolio_id, stock_symbol, shares) VALUES(?,?,?)"; prepStmt = connection.prepareStatement(query); prepStmt.setInt(1, id); prepStmt.setString(2, symbol); prepStmt.setInt(3, shares); prepStmt.executeUpdate(); prepStmt.close(); } else { String query = "UPDATE portfolio_stocks SET shares = (shares + ?) WHERE portfolio_id = ? AND stock_symbol = ?"; prepStmt = connection.prepareStatement(query); prepStmt.setInt(1, shares); prepStmt.setInt(2, id); prepStmt.setString(3, symbol); prepStmt.executeUpdate(); prepStmt.close(); } result = true; } catch(Exception e){ e.printStackTrace(); return result; } finally { connection.close(); } return result; } public static boolean removeStocksFromPortfolio(int id, String symbol, int shares) throws SQLException { boolean result = false; Connection connection = null; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); return false; } PreparedStatement prepStmt = null; try { String query = "UPDATE portfolio_stocks SET shares = (shares - ?) WHERE portfolio_id = ? AND stock_symbol = ?"; prepStmt = connection.prepareStatement(query); prepStmt.setInt(1, shares); prepStmt.setInt(2, id); prepStmt.setString(3, symbol); prepStmt.executeUpdate(); prepStmt.close(); result = true; } catch(Exception e){ e.printStackTrace(); return result; } finally { connection.close(); } return result; } public static boolean addMoneyToPortfolio(int id, BigDecimal amount) throws SQLException{ boolean result = false; Connection connection = null; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); return false; } PreparedStatement prepStmt = null; try { String query = "UPDATE portfolios SET current_balance = (current_balance + ?) WHERE portfolio_id = ?"; prepStmt = connection.prepareStatement(query); prepStmt.setBigDecimal(1, amount); prepStmt.setInt(2, id); prepStmt.executeUpdate(); prepStmt.close(); result = true; } catch(Exception e){ e.printStackTrace(); return result; } finally { connection.close(); } return result; } public static boolean removeMoneyFromPortfolio(int id, BigDecimal amount) throws SQLException{ boolean result = false; Connection connection = null; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); return false; } PreparedStatement prepStmt = null; try { //amount is negative here. Probably shouldnt have made this method String query = "UPDATE portfolios SET current_balance = (current_balance + ?) WHERE portfolio_id = ?"; prepStmt = connection.prepareStatement(query); prepStmt.setBigDecimal(1, amount); prepStmt.setInt(2, id); prepStmt.executeUpdate(); prepStmt.close(); result = true; } catch(Exception e) { e.printStackTrace(); return result; } finally { connection.close(); } return result; } public static BigDecimal findPortfolioBalance(int id) throws SQLException { Connection connection = null; BigDecimal result = new BigDecimal(-1); try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); } PreparedStatement prepStmt = null; try { String query = "SELECT current_balance FROM portfolios WHERE portfolio_id=?"; prepStmt = connection.prepareStatement(query); prepStmt.setInt(1, id); ResultSet rs = prepStmt.executeQuery(); if(rs.next()){ result = rs.getBigDecimal(1); } prepStmt.close(); return result; } catch(Exception e){ e.printStackTrace(); return result; } finally { connection.close(); } } public static BigDecimal findInitialStockPrice(String symbol) throws SQLException { String[] niftyArray = MainServlet.NIFTY_STOCKS.split(","); if(Arrays.asList(niftyArray).contains(symbol)){ Connection connection = null; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); } PreparedStatement prepStmt = null; BigDecimal result = new BigDecimal(-1); try { String query = "SELECT price FROM nifty_initial WHERE symbol=?"; prepStmt = connection.prepareStatement(query); prepStmt.setString(1, symbol); ResultSet rs = prepStmt.executeQuery(); if(rs.next()){ result = rs.getBigDecimal(1); } prepStmt.close(); return result; } catch(Exception e){ e.printStackTrace(); return result; } finally { connection.close(); } } else { Calendar calendar = new GregorianCalendar(); calendar.set(Calendar.YEAR, 2016); calendar.set(Calendar.MONTH, Calendar.SEPTEMBER); calendar.set(Calendar.DAY_OF_MONTH, 12); Stock stock = YahooFinance.get(symbol); List<HistoricalQuote> history = stock.getHistory(calendar,calendar); return history.get(0).getClose(); } } public static BigDecimal findCurrentStockPrice(String symbol) throws SQLException, JsonParseException, JsonMappingException, IOException { String[] niftyArray = MainServlet.NIFTY_STOCKS.split(","); if(Arrays.asList(niftyArray).contains(symbol)){ GoogleStock stock = new GoogleStock(symbol); return stock.getPrice(); } else { Stock stock = YahooFinance.get(symbol); return stock.getQuote().getPrice(); } } public static boolean recordDeposit(int id, BigDecimal amount) throws SQLException{ boolean result = false; Connection connection = null; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); return false; } PreparedStatement prepStmt = null; try { String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); BigDecimal currentBalance = findPortfolioBalance(id); String query = "INSERT INTO history (transaction_type, money_amount, balance, time, portfolio_id) VALUES (?,?,?,?,?)"; prepStmt = connection.prepareStatement(query); prepStmt.setString(1, "Deposit"); prepStmt.setBigDecimal(2, amount); prepStmt.setBigDecimal(3, currentBalance); prepStmt.setString(4, timeStamp); prepStmt.setInt(5, id); prepStmt.executeUpdate(); prepStmt.close(); result = true; } catch(Exception e) { e.printStackTrace(); return result; } finally { connection.close(); } return result; } public static boolean recordWithdraw(int id, BigDecimal amount) throws SQLException{ boolean result = false; Connection connection = null; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); return false; } PreparedStatement prepStmt = null; try { String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); BigDecimal currentBalance = findPortfolioBalance(id); String query = "INSERT INTO history (transaction_type, money_amount, balance, time, portfolio_id) VALUES (?,?,?,?,?)"; prepStmt = connection.prepareStatement(query); prepStmt.setString(1, "Withdraw"); prepStmt.setBigDecimal(2, amount); prepStmt.setBigDecimal(3, currentBalance); prepStmt.setString(4, timeStamp); prepStmt.setInt(5, id); prepStmt.executeUpdate(); prepStmt.close(); result = true; } catch(Exception e) { e.printStackTrace(); return result; } finally { connection.close(); } return result; } public static ArrayList<RecordVO> getPortfolioRecord(int id) throws SQLException { Connection connection = null; ArrayList<RecordVO> records = new ArrayList<RecordVO>(); try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); } PreparedStatement prepStmt = null; try { String query = "SELECT transaction_type, money_amount, stock_symbol, shares, share_price, balance, time FROM history WHERE portfolio_id=?"; prepStmt = connection.prepareStatement(query); prepStmt.setInt(1, id); ResultSet rs = prepStmt.executeQuery(); while(rs.next()){ RecordVO record = new RecordVO(); record.setType(rs.getString(1)); record.setAmount(rs.getBigDecimal(2)); record.setSymbol(rs.getString(3)); record.setShares(rs.getInt(4)); record.setPrice(rs.getBigDecimal(5)); record.setBalance(rs.getBigDecimal(6)); record.setTime(rs.getString(7)); records.add(record); } prepStmt.close(); return records; } catch(Exception e){ e.printStackTrace(); return records; } finally { connection.close(); } } public static ArrayList<RecordVO> getMoneyRecord(int id) throws SQLException { Connection connection = null; ArrayList<RecordVO> records = new ArrayList<RecordVO>(); try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); } PreparedStatement prepStmt = null; try { String query = "SELECT transaction_type, money_amount, balance, time " + "FROM history WHERE portfolio_id=? " + "AND transaction_type IN ('Deposit', 'Withdraw') "; prepStmt = connection.prepareStatement(query); prepStmt.setInt(1, id); ResultSet rs = prepStmt.executeQuery(); while(rs.next()){ RecordVO record = new RecordVO(); record.setType(rs.getString(1)); record.setAmount(rs.getBigDecimal(2)); record.setBalance(rs.getBigDecimal(3)); record.setTime(rs.getString(4)); records.add(record); } prepStmt.close(); return records; } catch(Exception e){ e.printStackTrace(); return records; } finally { connection.close(); } } public static boolean deletePortfolio(int id) throws SQLException { Connection connection = null; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); return false; } PreparedStatement prepStmt = null; try { String query = "UPDATE portfolios SET flag=1 WHERE portfolio_id=?"; prepStmt = connection.prepareStatement(query); prepStmt.setInt(1, id); prepStmt.executeUpdate(); prepStmt.close(); return true; } catch(Exception e){ e.printStackTrace(); return false; } finally { connection.close(); } } public static boolean recordStockPurchase(String symbol, int shares, BigDecimal price, int id, boolean firstTime) throws SQLException{ boolean result = false; Connection connection = null; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); return false; } PreparedStatement prepStmt = null; try { String timeStamp = firstTime? "2016-09-12 00:00:00" : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); BigDecimal currentBalance = findPortfolioBalance(id); String query = "INSERT INTO history (transaction_type, stock_symbol, shares, share_price, balance, time, portfolio_id) VALUES (?,?,?,?,?,?,?)"; prepStmt = connection.prepareStatement(query); prepStmt.setString(1, "Buy"); prepStmt.setString(2, symbol); prepStmt.setInt(3, shares); prepStmt.setBigDecimal(4, price); prepStmt.setBigDecimal(5, currentBalance); prepStmt.setString(6, timeStamp); prepStmt.setInt(7, id); prepStmt.executeUpdate(); prepStmt.close(); result = true; } catch(Exception e) { e.printStackTrace(); return result; } finally { connection.close(); } return result; } public static boolean recordStockRemoval(String symbol, int shares, BigDecimal price, int id) throws SQLException{ boolean result = false; Connection connection = null; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); return false; } PreparedStatement prepStmt = null; try { String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); BigDecimal currentBalance = findPortfolioBalance(id); String query = "INSERT INTO history (transaction_type, stock_symbol, shares, share_price, balance, time, portfolio_id) VALUES (?,?,?,?,?,?,?)"; prepStmt = connection.prepareStatement(query); prepStmt.setString(1, "Sell"); prepStmt.setString(2, symbol); prepStmt.setInt(3, shares); prepStmt.setBigDecimal(4, price); prepStmt.setBigDecimal(5, currentBalance); prepStmt.setString(6, timeStamp); prepStmt.setInt(7, id); prepStmt.executeUpdate(); prepStmt.close(); result = true; } catch(Exception e) { e.printStackTrace(); return result; } finally { connection.close(); } return result; } public static void insertNifty() throws SQLException{ HashMap<String, Double> x = new HashMap<String, Double>(); x.put("NSE:ACC", 1584.0); x.put("NSE:ADANIPORTS", 259.75); x.put("NSE:AMBUJACEM", 260.0); x.put("NSE:ASIANPAINT", 1155.0); x.put("NSE:AXISBANK", 594.5); x.put("NSE:BAJAJ-AUTO", 2953.0); x.put("NSE:BANKBARODA", 162.1); x.put("NSE:BHARTIARTL", 317.8); x.put("NSE:BHEL", 147.6); x.put("NSE:BOSCHLTD", 23400.1); x.put("NSE:BPCL", 566.0); x.put("NSE:CAIRN", 191.25); x.put("NSE:CIPLA", 570.5); x.put("NSE:COALINDIA", 330.3); x.put("NSE:DRREDDY", 3140.0); x.put("NSE:GAIL", 386.25); x.put("NSE:GRASIM", 4642.0); x.put("NSE:HCLTECH", 780.2); x.put("NSE:HDFC", 1398.0); x.put("NSE:HDFCBANK", 1279.6); x.put("NSE:HEROMOTOCO", 3537.0); x.put("NSE:HINDALCO", 141.2); x.put("NSE:HINDUNILVR", 919.0); x.put("NSE:ICICIBANK", 267.85); x.put("NSE:IDEA", 82.7); x.put("NSE:INDUSINDBK", 1195.35); x.put("NSE:INFY", 1055.0); x.put("NSE:ITC", 251.85); x.put("NSE:KOTAKBANK", 814.0); x.put("NSE:LT", 1463.0); x.put("NSE:LUPIN", 1533.2); x.put("NSE:M&M", 1424.9); x.put("NSE:MARUTI", 5330.0); x.put("NSE:NTPC", 153.0); x.put("NSE:ONGC", 250.8); x.put("NSE:PNB" ,137.0); x.put("NSE:POWERGRID", 180.05); x.put("NSE:RELIANCE", 1046.95); x.put("NSE:SBIN", 253.65); x.put("NSE:SUNPHARMA", 786.0); x.put("NSE:TATAMOTORS", 553.75); x.put("NSE:TATAPOWER", 74.15); x.put("NSE:TATASTEEL", 371.95); x.put("NSE:TCS", 2358.0); x.put("NSE:TECHM" ,464.1); x.put("NSE:ULTRACEMCO", 3869.05); x.put("NSE:VEDL", 163.0); x.put("NSE:WIPRO", 482.0); x.put("NSE:YESBANK", 1199.5); x.put("NSE:ZEEL", 517.35); Connection connection = null; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); } PreparedStatement prepStmt = null; try { String query = "INSERT INTO nifty_initial (symbol, price) VALUES (?,?)"; prepStmt = connection.prepareStatement(query); for(String a:x.keySet()){ BigDecimal b = new BigDecimal(x.get(a)); prepStmt.setString(1, a); prepStmt.setBigDecimal(2, b); prepStmt.executeUpdate(); } prepStmt.close(); } catch(Exception e) { e.printStackTrace(); } finally { connection.close(); } } public static BigDecimal initialCurrencyConvert (String symbol, BigDecimal price) { String[] niftyArray = MainServlet.NIFTY_STOCKS.split(","); String[] straitArray = MainServlet.STRAIT_STOCKS.split(","); if(Arrays.asList(niftyArray).contains(symbol)){ return price.divide(new BigDecimal(MainServlet.INITIAL_USD_INR),4, RoundingMode.HALF_UP); } if(Arrays.asList(straitArray).contains(symbol)){ return price.divide(new BigDecimal(MainServlet.INITIAL_USD_SGD),4, RoundingMode.HALF_UP); } return price; } public static LinkedHashMap<String, Double> getExchangeRates() throws MalformedURLException, IOException{ String jsonContent = IOUtils.toString(new URL("http://www.apilayer.net/api/live?access_key=" + MainServlet.CURRENCY_API_KEY + "&format=1"), Charset.forName("UTF-8")); JsonParser jsonParser = new JsonParser(); String inrRate = jsonParser.parse(jsonContent).getAsJsonObject().get("quotes").getAsJsonObject().get("USDINR").getAsString(); String sgdRate = jsonParser.parse(jsonContent).getAsJsonObject().get("quotes").getAsJsonObject().get("USDSGD").getAsString(); LinkedHashMap<String, Double> rates = new LinkedHashMap<String, Double>(); rates.put("USDINR", Double.valueOf(inrRate)); rates.put("USDSGD", Double.valueOf(sgdRate)); return rates; } public static BigDecimal liveCurrencyConvert(String symbol, BigDecimal price) throws MalformedURLException, IOException { String jsonContent = IOUtils.toString(new URL("http://www.apilayer.net/api/live?access_key=" + MainServlet.CURRENCY_API_KEY + "&format=1"), Charset.forName("UTF-8")); JsonParser jsonParser = new JsonParser(); String inrRate = jsonParser.parse(jsonContent).getAsJsonObject().get("quotes").getAsJsonObject().get("USDINR").getAsString(); String sgdRate = jsonParser.parse(jsonContent).getAsJsonObject().get("quotes").getAsJsonObject().get("USDSGD").getAsString(); String[] niftyArray = MainServlet.NIFTY_STOCKS.split(","); String[] straitArray = MainServlet.STRAIT_STOCKS.split(","); if(Arrays.asList(niftyArray).contains(symbol)){ return price.divide(new BigDecimal(inrRate), 4, RoundingMode.HALF_UP); } if(Arrays.asList(straitArray).contains(symbol)){ return price.divide(new BigDecimal(sgdRate),4, RoundingMode.HALF_UP); } return price; } public static boolean checkForInitialPurchase(int id, String symbol) throws SQLException{ Connection connection = null; boolean result = true; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); } PreparedStatement prepStmt = null; try { String query = "SELECT 1 FROM portfolio_stocks WHERE portfolio_id=? AND stock_symbol=?"; prepStmt = connection.prepareStatement(query); prepStmt.setInt(1, id); prepStmt.setString(2, symbol); ResultSet rs = prepStmt.executeQuery(); if(rs.next()){ result = false; } prepStmt.close(); return result; } catch(Exception e){ e.printStackTrace(); return result; } finally { connection.close(); } } public static boolean checkForEditDupe(int id, String name, String user) throws SQLException{ Connection connection = null; boolean result = false; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); } PreparedStatement prepStmt = null; try { String query = "SELECT 1 FROM portfolios WHERE portfolio_name=? AND user_id = ? AND portfolio_id <> ?"; prepStmt = connection.prepareStatement(query); prepStmt.setString(1, name); prepStmt.setString(2, user); prepStmt.setInt(3, id); ResultSet rs = prepStmt.executeQuery(); if(rs.next()){ result = true; } prepStmt.close(); return result; } catch(Exception e){ e.printStackTrace(); return result; } finally { connection.close(); } } public static boolean updatePortfolioName(int id, String name) throws SQLException { Connection connection = null; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); return false; } PreparedStatement prepStmt = null; try { String query = "UPDATE portfolios SET portfolio_name=? WHERE portfolio_id=?"; prepStmt = connection.prepareStatement(query); prepStmt.setString(1, name); prepStmt.setInt(2, id); prepStmt.executeUpdate(); prepStmt.close(); return true; } catch(Exception e){ e.printStackTrace(); return false; } finally { connection.close(); } } public static ArrayList<StockSnapshotVO> findStockPurchaseHistory(String symbol, int id) throws SQLException { ArrayList<StockSnapshotVO> history = new ArrayList<StockSnapshotVO>(); Connection connection = null; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); } PreparedStatement prepStmt = null; try { String query = "SELECT shares, share_price, time FROM history WHERE portfolio_id=? AND transaction_type='Buy' AND stock_symbol=?"; prepStmt = connection.prepareStatement(query); prepStmt.setInt(1, id); prepStmt.setString(2, symbol); ResultSet rs = prepStmt.executeQuery(); while(rs.next()){ StockSnapshotVO snapshot = new StockSnapshotVO(); snapshot.setShares(rs.getInt(1)); snapshot.setDate(rs.getString(3)); snapshot.setPrice(rs.getBigDecimal(2)); snapshot.setSymbol(symbol); history.add(snapshot); } prepStmt.close(); rs.close(); } catch(Exception e){ e.printStackTrace(); } finally { connection.close(); } return history; } public static ArrayList<StockSnapshotVO> findStockSellHistory(String symbol, int id) throws SQLException { ArrayList<StockSnapshotVO> history = new ArrayList<StockSnapshotVO>(); Connection connection = null; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); } PreparedStatement prepStmt = null; try { String query = "SELECT shares, share_price, time FROM history WHERE portfolio_id=? AND transaction_type='Sell' AND stock_symbol=?"; prepStmt = connection.prepareStatement(query); prepStmt.setInt(1, id); prepStmt.setString(2, symbol); ResultSet rs = prepStmt.executeQuery(); while(rs.next()){ StockSnapshotVO snapshot = new StockSnapshotVO(); snapshot.setShares(rs.getInt(1)); snapshot.setDate(rs.getString(3)); snapshot.setPrice(rs.getBigDecimal(2)); snapshot.setSymbol(symbol); history.add(snapshot); } prepStmt.close(); rs.close(); } catch(Exception e){ e.printStackTrace(); } finally { connection.close(); } return history; } public static ArrayList<StockSnapshotVO> findStockTransactionHistory(String symbol, int id) throws SQLException { ArrayList<StockSnapshotVO> history = new ArrayList<StockSnapshotVO>(); Connection connection = null; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); } PreparedStatement prepStmt = null; try { String query = "SELECT shares, share_price, time, transaction_type FROM history WHERE portfolio_id=? AND transaction_type IN ('Sell','Buy') AND stock_symbol=?"; prepStmt = connection.prepareStatement(query); prepStmt.setInt(1, id); prepStmt.setString(2, symbol); ResultSet rs = prepStmt.executeQuery(); while(rs.next()){ StockSnapshotVO snapshot = new StockSnapshotVO(); snapshot.setShares(rs.getInt(1)); snapshot.setDate(rs.getString(3)); snapshot.setPrice(rs.getBigDecimal(2)); snapshot.setSymbol(symbol); snapshot.setType(rs.getString(4)); history.add(snapshot); } prepStmt.close(); rs.close(); } catch(Exception e){ e.printStackTrace(); } finally { connection.close(); } return history; } public static ArrayList<BigDecimal> findNetGain(ArrayList<StockSnapshotVO> buyHistory, ArrayList<StockSnapshotVO> sellHistory) throws CloneNotSupportedException { ArrayList<StockSnapshotVO> sortedBuy = new ArrayList<StockSnapshotVO>(buyHistory.size()); ArrayList<BigDecimal> profit = new ArrayList<BigDecimal>(); for (StockSnapshotVO x: buyHistory) { sortedBuy.add((StockSnapshotVO)x.clone()); } Collections.sort(sortedBuy, new StockPriceComparator()); for(StockSnapshotVO s : sellHistory) { if(sortedBuy.isEmpty()) return profit; BigDecimal tempNet = new BigDecimal(0); BigDecimal sellPrice = s.getPrice(); int sellShares = s.getShares(); for(int i=0; i<sortedBuy.size();i++) { StockSnapshotVO b = sortedBuy.get(i); int buyShares = b.getShares(); if(buyShares <= sellShares) { sellShares -= buyShares; BigDecimal buyPrice = b.getPrice(); BigDecimal currDiff = sellPrice.subtract(buyPrice); tempNet = tempNet.add(currDiff.multiply(new BigDecimal(buyShares))); sortedBuy.remove(i); i--; continue; } else { buyShares -= sellShares; b.setShares(buyShares); BigDecimal buyPrice = b.getPrice(); BigDecimal currDiff = sellPrice.subtract(buyPrice); tempNet = tempNet.add(currDiff.multiply(new BigDecimal(sellShares))); } break; } profit.add(tempNet); } return profit; } //This is not an elegant method at all but since user will probably have fewer than 10 stocks //and each stock has fewer than 10 transactions, this method is probably acceptable public static ArrayList<BigDecimal> findNetGain(ArrayList<StockSnapshotVO> history) throws CloneNotSupportedException { ArrayList<BigDecimal> profit = new ArrayList<BigDecimal>(); for(int i=0; i<history.size(); i++) { if(history.get(i).getType().equals("Sell")) { ArrayList<StockSnapshotVO> previousTransactions = new ArrayList<StockSnapshotVO>( history.subList(0, i)); ArrayList<StockSnapshotVO> previousPurchases = new ArrayList<StockSnapshotVO>(); for(StockSnapshotVO ss: previousTransactions){ if(ss.getType().equals("Buy")){ previousPurchases.add(ss); } } ArrayList<StockSnapshotVO> sortedBuy = new ArrayList<StockSnapshotVO>(previousPurchases.size()); for (StockSnapshotVO x: previousPurchases) { sortedBuy.add((StockSnapshotVO)x.clone()); } Collections.sort(sortedBuy, new StockPriceComparator()); if(sortedBuy.isEmpty()) return profit; BigDecimal tempNet = new BigDecimal(0); BigDecimal sellPrice = history.get(i).getPrice(); int sellShares = history.get(i).getShares(); for(int j=0; j<sortedBuy.size();j++) { StockSnapshotVO originalB = new StockSnapshotVO(); StockSnapshotVO b = sortedBuy.get(j); for(StockSnapshotVO x:history){ if(x.getType().equals("Buy") && x.getDate().equals(b.getDate())){ originalB = x; break; } } int buyShares = b.getShares(); if(buyShares <= sellShares) { sellShares -= buyShares; BigDecimal buyPrice = b.getPrice(); BigDecimal currDiff = sellPrice.subtract(buyPrice); tempNet = tempNet.add(currDiff.multiply(new BigDecimal(buyShares))); sortedBuy.remove(j); history.remove(originalB); i--; j--; continue; } else { buyShares -= sellShares; b.setShares(buyShares); originalB.setShares(buyShares); BigDecimal buyPrice = b.getPrice(); BigDecimal currDiff = sellPrice.subtract(buyPrice); tempNet = tempNet.add(currDiff.multiply(new BigDecimal(sellShares))); } break; } profit.add(tempNet); } } return profit; } public static boolean insertExpectedReturns(String symbol, double returnVal) throws SQLException { boolean result = false; Connection connection = null; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); return false; } PreparedStatement prepStmt = null; try { String query = "INSERT INTO stock_returns(symbol,expected_return) VALUES(?,?)"; prepStmt = connection.prepareStatement(query); prepStmt.setString(1,symbol); prepStmt.setDouble(2, returnVal); prepStmt.executeUpdate(); prepStmt.close(); result = true; } catch(Exception e){ e.printStackTrace(); return result; } finally { connection.close(); } return result; } public static boolean insertCovariances(LinkedHashMap<String, Double> map) throws SQLException { boolean result = false; Connection connection = null; try { connection = new MySqlConnector().getConnection(); } catch (Exception e) { e.printStackTrace(); return false; } PreparedStatement prepStmt = null; try { String query = "INSERT IGNORE INTO stock_covariances(symbol_pair,covariance) VALUES(?,?)"; prepStmt = connection.prepareStatement(query); int count=0; for(String x: map.keySet()){ prepStmt.setString(1, x); prepStmt.setDouble(2, map.get(x)); prepStmt.executeUpdate(); System.out.println("Inserted " + x); count++; System.out.println(count + " entries"); Thread.sleep(100); } prepStmt.close(); result = true; System.out.println("Done"); } catch(Exception e){ e.printStackTrace(); return result; } finally { connection.close(); } return result; } }
true
93bcb87465841fa1f80f664193e58074a4ae17c9
Java
anuj39680/Assignment-Submission-Demo
/Day2.java
UTF-8
343
3.859375
4
[]
no_license
//Take 2 values from command line argument and print sum of the two values. import java.util.*; class Sum{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter two value"); int i=sc.nextInt(); int i1=sc.nextInt(); System.out.println("Sum of two no. is = "+(i+i1)); } }
true
33bf1f25bb28e87d5b3bb1e81e58f0ba15a0980d
Java
CryptoSingh1337/spring-recipe-app
/src/test/java/com/saransh/springrecipeapp/converters/IngredientCommandToIngredientTest.java
UTF-8
2,548
2.640625
3
[]
no_license
package com.saransh.springrecipeapp.converters; import com.saransh.springrecipeapp.commands.IngredientCommand; import com.saransh.springrecipeapp.commands.UnitOfMeasureCommand; import com.saransh.springrecipeapp.domain.Ingredient; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.math.BigDecimal; import static org.junit.jupiter.api.Assertions.*; class IngredientCommandToIngredientTest { private IngredientCommandToIngredient commandToIngredient; private final Long ID = 1L; private final String DESCRIPTION = "description"; private final BigDecimal AMOUNT = BigDecimal.ONE; private final Long UOM_ID = 2L; private final String UOM_DESCRIPTION = "uom_description"; @BeforeEach void setUp() { commandToIngredient = new IngredientCommandToIngredient(new UnitOfMeasureCommandToUnitOfMeasure()); } @Test void testNullObject() { assertNull(commandToIngredient.convert(null)); } @Test void testEmptyObject() { assertNotNull(commandToIngredient.convert(new IngredientCommand())); } @Test void testWithNullUOM() { // given IngredientCommand command = new IngredientCommand(); command.setId(ID); command.setDescription(DESCRIPTION); command.setAmount(AMOUNT); // when Ingredient ingredient = commandToIngredient.convert(command); // then assertNotNull(ingredient); assertEquals(ID, ingredient.getId()); assertEquals(DESCRIPTION, ingredient.getDescription()); assertEquals(AMOUNT, ingredient.getAmount()); assertNull(ingredient.getUom()); } @Test void convert() { // given UnitOfMeasureCommand uomCommand = new UnitOfMeasureCommand(); uomCommand.setId(UOM_ID); uomCommand.setDescription(UOM_DESCRIPTION); IngredientCommand command = new IngredientCommand(); command.setId(ID); command.setDescription(DESCRIPTION); command.setAmount(AMOUNT); command.setUnitOfMeasure(uomCommand); // when Ingredient ingredient = commandToIngredient.convert(command); // then assertNotNull(ingredient); assertEquals(ID, ingredient.getId()); assertEquals(DESCRIPTION, ingredient.getDescription()); assertEquals(AMOUNT, ingredient.getAmount()); assertEquals(UOM_ID, ingredient.getUom().getId()); assertEquals(UOM_DESCRIPTION, ingredient.getUom().getDescription()); } }
true
b91bbf37379c2aaa85966e792505e390d89bf643
Java
mfaella/Java-practice
/JFC/GreenPass/GreenPass.java
UTF-8
892
2.890625
3
[]
no_license
public class GreenPass { private static final int VALIDITA_PRIMA_DOSE = 180; private static final int VALIDITA = 270; private String soggetto; private int data_somministrazione; private boolean isFirst; public GreenPass(String soggetto, int data_somministrazione, boolean isFirst) { this.soggetto = soggetto; this.data_somministrazione = data_somministrazione; this.isFirst = isFirst; } public boolean isValidOn(int data) { if(isFirst){ return (VALIDITA_PRIMA_DOSE > (data + data_somministrazione))? true : false; } return (VALIDITA > (data + data_somministrazione))? true : false; } public boolean belongsTo(Persona p) { return p.equals(new Persona(soggetto)); } @Override public int hashCode() { return soggetto.hashCode() ^ data_somministrazione; } }
true
4a0d906a9c658730dd90c07c4439870d344b0454
Java
lvjie2426/store-system
/store-system-common/src/main/java/com/store/system/model/LoginUserPool.java
UTF-8
1,358
1.8125
2
[]
no_license
package com.store.system.model; import com.quakoo.baseFramework.model.pagination.PagerCursor; import com.quakoo.space.annotation.domain.CombinationKey; import com.quakoo.space.annotation.domain.HyperspaceDomain; import com.quakoo.space.annotation.domain.ShardingKey; import com.quakoo.space.annotation.domain.SortKey; import com.quakoo.space.enums.HyperspaceDomainType; import lombok.Data; import java.io.Serializable; @HyperspaceDomain(domainType= HyperspaceDomainType.listDataStructure) @Data public class LoginUserPool implements Serializable { private static final long serialVersionUID = -1L; public static int loginType_phone = 1; // 手机号登陆 public static int loginType_userName = 2; // 账号名密码登录 public static int loginType_weixin = 3; // 微信 public static int loginType_qq = 4; // QQ public static int loginType_weibo = 5; // 微博 public static int loginType_alipay = 6; // 支付宝登录 @ShardingKey @CombinationKey private int loginType; @CombinationKey private int userType;//用户类型(一般分为普通用户、后台用户) @CombinationKey private String account;//手机号登陆的时候 对应phone. 账号名密码登录的时候对应userName 微信登录的时候对应weixinId private long uid; @SortKey @PagerCursor private long ctime; private long utime; }
true
517095503e05baa45628646700a0725ef92ca61a
Java
vikash011/spring_codes
/IOCProj6-StrategyDP-corejava/src/com/nit/comps/Vechicle.java
UTF-8
442
2.625
3
[]
no_license
//Vehicle.java(target class) package com.nit.comps; public class Vechicle { private IEngine engg; public void setEngg(IEngine engg) { this.engg = engg; } public void journey(String source, String destination) { engg.start(); System.out.println("journey started at " + source); System.out.println("journey is going on...."); engg.stop(); System.out.println("journey ended at " + destination); } }
true
9ea75129c3713c014429213ce007fc5e65ee67c4
Java
vasusheoran/coding
/graph/cycle/UndirectedGraph.java
UTF-8
2,326
3.53125
4
[]
no_license
// { Driver Code Starts import java.util.*; import java.lang.*; import java.io.*; class UndirectedGraph { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { String[] s = br.readLine().trim().split(" "); int V = Integer.parseInt(s[0]); int E = Integer.parseInt(s[1]); ArrayList<ArrayList<Integer>>adj = new ArrayList<>(); for(int i = 0; i < V; i++) adj.add(i, new ArrayList<Integer>()); for(int i = 0; i < E; i++){ String[] S = br.readLine().trim().split(" "); int u = Integer.parseInt(S[0]); int v = Integer.parseInt(S[1]); adj.get(u).add(v); adj.get(v).add(u); } Solution obj = new Solution(); boolean ans = obj.isCycle(V, adj); if(ans) System.out.println("1"); else System.out.println("0"); } } }// } Driver Code Ends class Solution { public boolean util(int v, ArrayList<ArrayList<Integer>> adj, boolean visited[], int parent){ visited[v] = true; ListIterator<Integer> iter = adj.get(v).listIterator(); while(iter.hasNext()){ int i = iter.next(); // System.out.println("v: " + v + ", i: " + i + ", visited: " + visited[i] + ", parent: " + parent); if(!visited[i]){ if (util(i, adj, visited, v)){ return true; } } else if(i != parent){ return true; } } return false; } //Function to detect cycle in an undirected graph. public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj) { // Code here boolean visited[] = new boolean[adj.size()]; for(int i = 0; i<V; i++){ visited[i] = false; } for(int i = 0; i<V; i++){ if(!visited[i]){ if(util(i, adj, visited, -1)){ return true; } } } return false; } }
true
af6c5239b7af9e9ab392669ad06f16b281e0aca4
Java
pedrohff/Projeto-Final-MLP2
/src/escola/gui/MenuListarAlunos.java
UTF-8
985
2.421875
2
[]
no_license
package escola.gui; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import escola.model.Aluno; public class MenuListarAlunos extends JFrame{ public MenuListarAlunos(){ super("MenuListarAlunos"); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(600, 600); montar(); } File arquivo = new File("matriculas.txt"); void montar() throws Exception{ ObjectInputStream in= new ObjectInputStream( new BufferedInputStream( new FileInputStream("alunos.txt"))); } }
true
bff993ffca8bc23b94abc4fd162470fe22af71b6
Java
2856754968/travel
/src/cn/tjx/entity/pageBean.java
UTF-8
1,468
2.40625
2
[]
no_license
package cn.tjx.entity; import java.util.List; /** * 分页实体 * @author tjx * @version 2020/01/02 * */ public class pageBean<T> { private int pageSize;//每页显示数 private int pageCode;//当前页 private int totalSize;//总页数 private List<Route> beanList; private String url; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getPageCode() { return pageCode; } public void setPageCode(int pageCode) { this.pageCode = pageCode; } public int getTotalSize() { return totalSize; } public void setTotalSize(int totalSize) { this.totalSize = totalSize; } public List<Route> getBeanList() { return beanList; } public void setBeanList(List<Route> beanList) { this.beanList = beanList; } public pageBean() { } public pageBean(int pageSize, int pageCode, int totalSize, List<Route> beanList) { this.pageSize = pageSize; this.pageCode = pageCode; this.totalSize = totalSize; this.beanList = beanList; } //总页数=总记录数/每页显示数 public int totalPage(){ return totalSize%pageSize==0?totalSize/pageSize:(totalSize/pageSize)+1; } @Override public String toString() { return "pageBean [pageSize=" + pageSize + ", pageCode=" + pageCode + ", totalSize=" + totalSize + ", beanList=" + beanList + "]"; } }
true
2634a1d7d3513e267382e59fb6a39e5922a93bf8
Java
jkcuk/Dr-TIM
/src/optics/raytrace/sceneObjects/SparseRectangularLensletArray.java
UTF-8
8,710
2.546875
3
[]
no_license
package optics.raytrace.sceneObjects; import java.io.Serializable; import math.Vector3D; import optics.raytrace.core.SceneObject; import optics.raytrace.core.Studio; import optics.raytrace.core.SurfacePropertyPrimitive; import optics.raytrace.exceptions.SceneException; import optics.raytrace.surfaces.ColourFilter; import optics.raytrace.surfaces.PhaseHologramOfSparseRectangularLensletArray; import optics.raytrace.surfaces.SurfacePropertyLayerStack; /** * A rectangle whose surface area is a phase hologram of a rectangular lenslet array * @author johannes */ public class SparseRectangularLensletArray extends SceneObjectWithHoles implements Serializable { private static final long serialVersionUID = 1939712790553898120L; /** * the parallelogram (normally a rectangle) that is then "wrapped" by the "SceneObjectWithHoles" */ private ScaledParametrisedParallelogram parallelogram; private PhaseHologramOfSparseRectangularLensletArray sparseLensArray; public SparseRectangularLensletArray( String description, Vector3D corner, Vector3D spanVector1, Vector3D spanVector2, double focalLength, double xPeriod, double yPeriod, double xOffset, double yOffset, int nx, int ny, boolean simulateDiffractiveBlur, double lambda, boolean colouredLenses, double throughputCoefficient, boolean reflective, boolean shadowThrowing, SceneObject parent, Studio studio ) { super(description); // create the wrapped SceneObject parallelogram = new ScaledParametrisedParallelogram( description, corner, spanVector1, spanVector2, 0, spanVector1.getLength(), // suMin, suMax 0, spanVector2.getLength(), // svMin, svMax null, // surfaceProperty, null for the moment parent, studio ); sparseLensArray = new PhaseHologramOfSparseRectangularLensletArray( focalLength, xPeriod, yPeriod, xOffset, yOffset, nx, ny, simulateDiffractiveBlur, lambda, parallelogram, // sceneObject throughputCoefficient, reflective, shadowThrowing ); if(colouredLenses) parallelogram.setSurfaceProperty( new SurfacePropertyLayerStack(sparseLensArray, ColourFilter.LIGHT_CYAN_GLASS) ); else parallelogram.setSurfaceProperty(sparseLensArray); try { setWrappedSceneObject(parallelogram); } catch (SceneException e) { // this shouldn't happen e.printStackTrace(); } setHoleySurface(sparseLensArray); } public SparseRectangularLensletArray( SceneObject parent, Studio studio ) { this( "Sparse rectangular lenslet-array", // description new Vector3D(-0.5, -0.5, 10), // corner new Vector3D(1, 0, 0), // spanVector1 new Vector3D(0, 1, 0), // spanVector2 1, // focalLength 0.1, // xPeriod 0.1, // yPeriod 0, // xOffset 0, // yOffset 1, // nx 1, // ny true, // simulateDiffractiveBlur 632.8e-9, // lambda true, // colouredLenses SurfacePropertyPrimitive.DEFAULT_TRANSMISSION_COEFFICIENT, // throughputCoefficient false, // reflective true, // shadowThrowing parent, studio ); } public SparseRectangularLensletArray(SparseRectangularLensletArray original) throws SceneException { super(original); sparseLensArray = (PhaseHologramOfSparseRectangularLensletArray)original.getHoleySurface(); parallelogram = (ScaledParametrisedParallelogram)original.getWrappedSceneObject(); sparseLensArray.setSceneObject(parallelogram); parallelogram.setSurfaceProperty(sparseLensArray); } /* (non-Javadoc) * @see optics.raytrace.sceneObjects.ParametrisedPlane#clone() */ @Override public SparseRectangularLensletArray clone() { try { return new SparseRectangularLensletArray(this); } catch (SceneException e) { // this should never happen e.printStackTrace(); return null; } } // // setters & getters // public void setCorner(Vector3D corner) { parallelogram.setCorner(corner); } public Vector3D getCorner() { return parallelogram.getCorner(); } public void setSpanVectors(Vector3D spanVector1, Vector3D spanVector2) { parallelogram.setSpanVectors(spanVector1, spanVector2); } public Vector3D getSpanVector1() { return parallelogram.getSpanVector1(); } public Vector3D getSpanVector2() { return parallelogram.getSpanVector2(); } // /** // * // * Editable-interface stuff // * // */ // // /** // * variables // */ // private JPanel editPanel; // private LabelledStringPanel descriptionPanel; // private LabelledVector3DPanel centrePanel, widthVectorPanel, heightVectorPanel; // private LabelledDoublePanel lensletArrayFocalLengthPanel, lensletArrayTransmissionCoefficientPanel; // private LabelledVector2DPanel lensletArrayPeriodPanel, lensletArrayOffsetPanel; // // // /** // * initialise the edit panel // */ // @Override // public void createEditPanel(IPanel iPanel) // { // editPanel = new JPanel(); // editPanel.setLayout(new MigLayout("insets 0")); // editPanel.setBorder(GUIBitsAndBobs.getTitledBorder("Lenslet array")); // // // // // the basic-parameters panel // // // // // a text field containing the description // descriptionPanel = new LabelledStringPanel("Description"); // editPanel.add(descriptionPanel, "wrap"); // // centrePanel = new LabelledVector3DPanel("Centre"); // editPanel.add(centrePanel, "wrap"); // // widthVectorPanel = new LabelledVector3DPanel("Vector along width"); // editPanel.add(widthVectorPanel, "wrap"); // // heightVectorPanel = new LabelledVector3DPanel("Vector along height"); // editPanel.add(heightVectorPanel, "wrap"); // // // // // the lenslet-array parameters // // // // lensletArrayFocalLengthPanel = new LabelledDoublePanel("Focal length"); // lensletArrayFocalLengthPanel.setNumber(1); // editPanel.add(lensletArrayFocalLengthPanel, "span"); // // lensletArrayPeriodPanel = new LabelledVector2DPanel("Period in (x,y)"); // lensletArrayPeriodPanel.setVector2D(0.1, 0.1); // editPanel.add(lensletArrayPeriodPanel, "span"); // // lensletArrayOffsetPanel = new LabelledVector2DPanel("Offset in (x,y)"); // lensletArrayOffsetPanel.setVector2D(0, 0); // editPanel.add(lensletArrayOffsetPanel, "span"); // // lensletArrayTransmissionCoefficientPanel = new LabelledDoublePanel("Transmission coefficient"); // lensletArrayTransmissionCoefficientPanel.setNumber(SurfacePropertyPrimitive.DEFAULT_TRANSMISSION_COEFFICIENT); // editPanel.add(lensletArrayTransmissionCoefficientPanel, "span");; // // editPanel.validate(); // } // // @Override // public void discardEditPanel() // { // editPanel = null; // } // // /* (non-Javadoc) // * @see optics.raytrace.GUI.Editable#getEditPanel() // */ // @Override // public JPanel getEditPanel() // { // return editPanel; // } // // // /* (non-Javadoc) // * @see optics.raytrace.GUI.Editable#setValuesInEditPanel() // */ // @Override // public void setValuesInEditPanel() // { // descriptionPanel.setString(getDescription()); // centrePanel.setVector3D(getCentre()); // widthVectorPanel.setVector3D(getSpanVector1()); // heightVectorPanel.setVector3D(getSpanVector2()); // // // initialize any fields // lensletArrayFocalLengthPanel.setNumber(sparseLensArray.getFocalLength()); // lensletArrayTransmissionCoefficientPanel.setNumber(sparseLensArray.getTransmissionCoefficient()); // lensletArrayPeriodPanel.setVector2D(sparseLensArray.getxPeriod(), sparseLensArray.getyPeriod()); // lensletArrayOffsetPanel.setVector2D(sparseLensArray.getxOffset(), sparseLensArray.getyOffset()); // } // // /* (non-Javadoc) // * @see optics.raytrace.GUI.Editable#acceptValuesInEditPanel() // */ // @Override // public SparseRectangularLensletArray acceptValuesInEditPanel() // { // // don't use super.acceptValuesInEditPanel(); as this sets the surface property and the scaling; // // instead, copy the relevant code from it // setDescription(descriptionPanel.getString()); // // setCentreAndSpanVectors( // centrePanel.getVector3D(), // widthVectorPanel.getVector3D(), // heightVectorPanel.getVector3D() // ); // // sparseLensArray.setFocalLength(lensletArrayFocalLengthPanel.getNumber()); // sparseLensArray.setxPeriod(lensletArrayPeriodPanel.getVector2D().x); // sparseLensArray.setyPeriod(lensletArrayPeriodPanel.getVector2D().y); // sparseLensArray.setxOffset(lensletArrayOffsetPanel.getVector2D().x); // sparseLensArray.setyOffset(lensletArrayOffsetPanel.getVector2D().y); // sparseLensArray.setTransmissionCoefficient(lensletArrayTransmissionCoefficientPanel.getNumber()); // // return this; // } // // @Override // public void backToFront(IPanelComponent edited) {} }
true
bb56ed45d866d3b1d9083f7bb0815846a5bb10ab
Java
PlayersCommittee/gemp-swccg-public
/gemp-swccg-logic/src/main/java/com/gempukku/swccgo/logic/effects/choose/ChooseCardsToMoveAwayOrBeLostEffect.java
UTF-8
6,433
2.59375
3
[ "MIT" ]
permissive
package com.gempukku.swccgo.logic.effects.choose; import com.gempukku.swccgo.common.Filterable; import com.gempukku.swccgo.filters.Filters; import com.gempukku.swccgo.game.PhysicalCard; import com.gempukku.swccgo.game.SwccgGame; import com.gempukku.swccgo.logic.GameUtils; import com.gempukku.swccgo.logic.actions.SubAction; import com.gempukku.swccgo.logic.effects.ChooseToMoveAwayOrBeLostEffect; import com.gempukku.swccgo.logic.effects.TargetCardsOnTableEffect; import com.gempukku.swccgo.logic.effects.UnrespondableEffect; import com.gempukku.swccgo.logic.timing.AbstractSubActionEffect; import com.gempukku.swccgo.logic.timing.Action; import com.gempukku.swccgo.logic.timing.PassthruEffect; import java.util.Collection; /** * An effect that causes the specified player to choose cards on table to move away (for free) or be lost. */ public class ChooseCardsToMoveAwayOrBeLostEffect extends AbstractSubActionEffect { private String _performingPlayerId; private int _maximum; private Filterable _cardFilter; /** * Creates an effect that causes the specified player to choose cards on table to move away (for free) or be lost. * @param action the action performing this effect * @param playerId the player * @param numCards the number of cards * @param cardFilter the card filter */ public ChooseCardsToMoveAwayOrBeLostEffect(Action action, String playerId, int numCards, Filterable cardFilter) { super(action); _performingPlayerId = playerId; _maximum = numCards; _cardFilter = cardFilter; } @Override public boolean isPlayableInFull(SwccgGame game) { return true; } @Override protected SubAction getSubAction(SwccgGame game) { final SubAction subAction = new SubAction(_action, _performingPlayerId); subAction.appendTargeting( new PassthruEffect(subAction) { @Override protected void doPlayEffect(final SwccgGame game) { int minimum = Math.min(_maximum, Filters.countActive(game, subAction.getActionSource(), _cardFilter)); subAction.appendTargeting( new TargetCardsOnTableEffect(subAction, _performingPlayerId, "Choose card" + GameUtils.s(minimum) + " to move away (for free) or be lost", minimum, _maximum, _cardFilter) { @Override protected void cardsTargeted(final int targetGroupId, final Collection<PhysicalCard> targetedCards) { subAction.addAnimationGroup(targetedCards); // Allow response(s) subAction.allowResponses("Make " + GameUtils.getAppendedNames(targetedCards) + " move away (for free) or be lost", new UnrespondableEffect(subAction) { @Override protected void performActionResults(Action targetingAction) { subAction.appendEffect( new ChooseNextCardToMoveAwayOrBeLost(subAction, game, targetedCards)); } } ); } } ); } } ); return subAction; } @Override protected boolean wasActionCarriedOut() { return true; } /** * A private effect for choosing the next card. */ private class ChooseNextCardToMoveAwayOrBeLost extends ChooseCardsOnTableEffect { private SubAction _subAction; private SwccgGame _game; private Collection<PhysicalCard> _remainingCards; /** * Creates an effect for choosing the next card. * @param subAction the action * @param remainingCards the remaining cards */ public ChooseNextCardToMoveAwayOrBeLost(SubAction subAction, SwccgGame game, Collection<PhysicalCard> remainingCards) { super(subAction, subAction.getPerformingPlayer(), "Choose next card to move away (for free) or be lost", 1, 1, remainingCards); _subAction = subAction; _game = game; _remainingCards = remainingCards; } @Override protected boolean getUseShortcut() { return true; } @Override protected void cardsSelected(Collection<PhysicalCard> selectedCards) { for (PhysicalCard selectedCard : selectedCards) { _game.getGameState().cardAffectsCard(_performingPlayerId, _action.getActionSource(), selectedCard); // SubAction to carry out losing card from table SubAction moveAwayOrBeLostSubAction = new SubAction(_subAction); moveAwayOrBeLostSubAction.appendEffect( new ChooseToMoveAwayOrBeLostEffect(moveAwayOrBeLostSubAction, selectedCard.getOwner(), selectedCard, true)); // Stack sub-action _subAction.stackSubAction(moveAwayOrBeLostSubAction); _remainingCards.remove(selectedCard); if (!_remainingCards.isEmpty()) { _subAction.appendEffect( new PassthruEffect(_subAction) { @Override protected void doPlayEffect(SwccgGame game) { // Filter for cards that are still on the table _remainingCards = Filters.filter(_remainingCards, game, _cardFilter); if (!_remainingCards.isEmpty()) { _subAction.appendEffect( new ChooseCardsToMoveAwayOrBeLostEffect.ChooseNextCardToMoveAwayOrBeLost(_subAction, _game, _remainingCards)); } } } ); } } } } }
true
1a5b68713ccf42662c05c2f21592f7c9060e3fe5
Java
MTamPham/OCA-Java8-1Z0--808
/src/ch03/methods/Phone3.java
UTF-8
833
4.15625
4
[]
no_license
package ch03.methods; /* * A return statement is used to exit from a method, with or without a value. For methods that define a return type, the * return statement must be immediately followed by a return value. For methods that don't return a value, the return * statement can be used without a return value to exit a method. * The return statement must be the last statement to execute in a method, if present. */ public class Phone3 { double weight; void setWeight(double val) { if (val < -1) { return; //control exits the method if this condition is true } this.weight = val; } // this code won't compile, the return statement must be the last statement to execute in a method // void setWeight(double val) { // return; // this.weight = val; // } }
true
eafd22e0ca80453d6f1bdf345783e92e683fe9eb
Java
geeklx/MakeJarAAR
/myshininglibrary/src/main/java/com/example/myshininglibrary/glin/cache/ICacheProvider.java
UTF-8
980
2.34375
2
[]
no_license
package com.example.myshininglibrary.glin.cache; import com.example.myshininglibrary.glin.NetResult; import com.example.myshininglibrary.glin.Result; public interface ICacheProvider { /** * get cache by key of {@link #getKey(String, String)} * @param key * @param klass * @param isList * @param <T> * @return */ <T> Result<T> get(String key, Class<T> klass, boolean isList); /** * cache data * @param key see {@link #getKey(String, String)} * @param netResult the origin result * @param result parsed result */ <T> void put(String key, NetResult netResult, Result<T> result); /** * provide the key * @param url the request url * @param params the request params, maybe key1=value1&key2=value2 while your request is POST, maybe null while your request is GET, maybe json string while your request is POST Json * @return */ String getKey(String url, String params); }
true
0396a0d8180727276071746eda81d831100281b8
Java
duanxq1994/springboot-mybatis-demo
/src/main/java/com/xinge/demo/common/util/Md5Util.java
UTF-8
1,274
2.796875
3
[]
no_license
package com.xinge.demo.common.util; import lombok.extern.slf4j.Slf4j; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * md5加密 * * @author duanxq * @date 2018/01/23 */ @Slf4j public class Md5Util { private Md5Util() { } private static MessageDigest messagedigest = null; static { try { messagedigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { log.error("初始化失败,MessageDigest不支持MD5Util:", e); } } /** * 对字符串进行md5加密 * @param s 输入字符串 * @return md5加密结果 */ public static String getMD5String(String s) { return getMD5String(s.getBytes(StandardCharsets.UTF_8)); } public static String getMD5String(byte[] bytes) { messagedigest.update(bytes); byte[] md = messagedigest.digest(); StringBuilder sb = new StringBuilder(); for (byte aMd : md) { int val = ((int) aMd) & 0xff; if (val < 16) { sb.append("0"); } sb.append(Integer.toHexString(val)); } return sb.toString(); } }
true
fb9d50c2dcc322e72af39cc166045a35adf92668
Java
Salojd/SemesterCardProject
/src/playingcards24/Cards.java
UTF-8
2,851
3.78125
4
[]
no_license
/** * This is the entire Playing Cards 24 package including the game and its tests */ package playingcards24; import javafx.scene.image.Image; /** * * BCS 345 Semester Project * * Prof. Alrajab * * @author Peter Schellhorn, Brett Silver, Jonathan Saloman, Aayushma Pal * * @version 1.0 * * Description: This application randomly generates four different cards from a deck. * The deck contains four suits which includes clubs, diamonds, hearts, and spades. * Each card contains a numbered value. For example, the value of Ace no matter which suit is picked is 1, * the value of two of whichever suit is 2, Queen is 12, King is 13, etc. The objective of this game is to use these four randomly * generated cards to implement them into a math equation that results in the value of 24. You can either add, subtract, * multiply, or divide when creating a math equation. * * This class has all the attributes of each card object */ public class Cards { // Variables for Card Object private String number, type; private Image image; private int value; public Cards() { } // Constructor for Card Object /** * * @param n the number of the card based upon what the user inputs * @param t the type of card * @param v the total value of the 4 cards */ public Cards(String n, String t, int v) { this.number = n; this.type = t; this.value = v; image = new Image("/CardImages/" + this.number + "_of_" + this.type + ".png"); } // Getters for Card Object /** * * @return returns the number of the card */ public String getNumber() { return this.number; } /** * * @return returns the type of card */ public String getType() { return this.type; } /** * * @return returns an image of a card */ public Image getImage() { return this.image; } /** * * @return returns the total value for all 4 cards */ public int getValue() { return this.value; } // Setters for Card object /** * * @param n sets the number of the card based on user input */ public void setNumber(String n) { this.number = n; } /** * * @param t sets the type of card to be displayed on screen */ public void setType(String t) { this.type = t; } /** * * @param image sets the image to be displayed on screen */ public void setImage(Image image) { this.image = image; } /** * * @param value sets the value of all 4 cards displayed on screen */ public void setValue(int value) { this.value = value; } /** * * @return returns a string representation for the card number and type */ // ToString for Card Object public String toString() { return this.number + "_of_" + this.type; } }
true
c6583527e4bd36d76ab6f42bb919c13298c93089
Java
cckmit/meJreLibs
/io/io-store/io-store-opc/src/test/me/java/library/io/store/opc/ShowOpcClients.java
UTF-8
1,377
2.359375
2
[]
no_license
package me.java.library.io.store.opc; import org.jinterop.dcom.common.JIException; import org.openscada.opc.dcom.list.ClassDetails; import org.openscada.opc.lib.list.Categories; import org.openscada.opc.lib.list.Category; import org.openscada.opc.lib.list.ServerList; import java.net.UnknownHostException; import java.util.Collection; /** * @author : sylar * @fullName : me.java.library.io.store.opc.DemoTest * @createDate : 2020/7/24 * @description : * @copyRight : COPYRIGHT(c) me.iot.com All Rights Reserved * ******************************************************************************************* */ public class ShowOpcClients { /** * 列举某Server下的所有OPC连接 * * @throws JIException * @throws UnknownHostException */ public static void main(String[] args) throws JIException, UnknownHostException { ServerList serverList = new ServerList("10.1.5.123", "freud", "password", ""); Collection<ClassDetails> classDetails = serverList .listServersWithDetails(new Category[]{ Categories.OPCDAServer10, Categories.OPCDAServer20, Categories.OPCDAServer30}, new Category[]{}); for (ClassDetails cds : classDetails) { System.out.println(cds.getProgId() + "=" + cds.getDescription()); } } }
true
764dd71fb2c050f7391c04559b02825ce9977c97
Java
clouddriver/aliyun-api-java-wrapper
/src/main/java/com/fit2cloud/aliyun/ecs/ECSRequest.java
UTF-8
437
1.867188
2
[ "MIT" ]
permissive
package com.fit2cloud.aliyun.ecs; import com.fit2cloud.aliyun.AliyunCredentials; import com.fit2cloud.aliyun.BaseModuleRequest; public class ECSRequest extends BaseModuleRequest { private static final String API_VERSION = "2014-05-26"; private static final String ENDPOINT = "http://ecs.aliyuncs.com/"; public ECSRequest(AliyunCredentials credentials) { super(credentials, ENDPOINT, API_VERSION); } }
true
95bcc7b9a761bc0022e7b176c702665783993c32
Java
stephanof/legend-engine
/legend-engine-language-pure-store-relational-grammar-api/src/main/java/org/finos/legend/engine/language/pure/grammar/api/relationalOperationElement/RelationalOperationElementJsonToGrammarInput.java
UTF-8
1,580
1.695313
2
[ "Apache-2.0", "CC0-1.0" ]
permissive
// Copyright 2020 Goldman Sachs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.finos.legend.engine.language.pure.grammar.api.relationalOperationElement; import org.finos.legend.engine.language.pure.grammar.from.ParserError; import org.finos.legend.engine.language.pure.grammar.to.PureGrammarComposerContext; import org.finos.legend.engine.protocol.pure.v1.model.packageableElement.store.relational.model.operation.RelationalOperationElement; import java.util.Map; public class RelationalOperationElementJsonToGrammarInput { public PureGrammarComposerContext.RenderStyle renderStyle = PureGrammarComposerContext.RenderStyle.STANDARD; public Map<String, RelationalOperationElement> operations; public Map<String, ParserError> operationErrors; public RelationalOperationElementJsonToGrammarInput() { // DO NOT DELETE: this resets the default constructor for Jackson } public RelationalOperationElementJsonToGrammarInput(Map<String, RelationalOperationElement> operations) { this.operations = operations; } }
true
b9b724e6197e00ab0c2f2e008980f2b3706b093a
Java
QQsilhonette/mid
/symphony-auditflow-parent/symphony-auditflow-starter/src/main/java/com/tuya/hardware/symphony/auditflow/model/dto/ShelfAudStatusDTO.java
UTF-8
883
2
2
[]
no_license
package com.tuya.hardware.symphony.auditflow.model.dto; import com.tuya.hardware.symphony.auditflow.enums.audit.AuditStateEnum; import com.tuya.hardware.symphony.auditflow.enums.shelf.ShelfStateEnum; import lombok.Data; import lombok.ToString; import lombok.experimental.Accessors; import java.io.Serializable; @Data @Accessors(chain = true) @ToString(callSuper = true) public class ShelfAudStatusDTO implements Serializable { private static final long serialVersionUID = 1L; /** * 上架状态 * @see ShelfStateEnum */ private Integer shelfStatus; /** * 审核状态 * @see AuditStateEnum */ private String auditStatus; /** * 审核人 */ private String auditUsername; /** * 下架时间 */ private Long stopUsingTime; /** * 审批实例id */ private String traceId; }
true
efd3c268932d4635180912a13274ac26f675ad11
Java
GangsOfCoder/FoodOrderingCustomeApp
/app/src/main/java/com/imakancustomer/ui/basket/BasketContract.java
UTF-8
802
1.945313
2
[ "Apache-2.0" ]
permissive
package com.imakancustomer.ui.basket; import com.imakancustomer.model.AddressListPojo; import com.imakancustomer.model.ProviderListPojo; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Header; public class BasketContract { public interface View { void showLoader(); void hideLoader(); void showMessage(String msg); void setDataToAdapter(List<AddressListPojo.Datum> categoryList); } public interface Action { void getPrimaryAddress(); } public interface Service { @GET("customer/address/list") Call<AddressListPojo> getPrimaryAddressAPI(@Header("authorization") String authorization, @Header("api_key") String api_key); } }
true
e5330a0ed565781e620217da91eb14eb06b34a4a
Java
stokito/AdvancedExpressionFolding
/src/com/intellij/advancedExpressionFolding/Pow.java
UTF-8
2,740
2.421875
2
[]
no_license
package com.intellij.advancedExpressionFolding; import com.intellij.lang.folding.FoldingDescriptor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.FoldingGroup; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Pow extends Function implements ArithmeticExpression { public Pow(@NotNull PsiElement element, @NotNull TextRange textRange, @NotNull List<Expression> operands) { super(element, textRange, "pow", operands); } @Override public boolean supportsFoldRegions(@NotNull Document document, @Nullable Expression parent) { return operands.get(0).getTextRange().getEndOffset() < getTextRange().getEndOffset() && superscript(operands.get(1).getElement().getText()) != null; // TODO no-format: Forbid non-literal/non-variable operands.get(1) } @Override public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement element, @NotNull Document document, @Nullable Expression parent) { ArrayList<FoldingDescriptor> descriptors = new ArrayList<>(); FoldingGroup group = FoldingGroup.newGroup(Pow.class.getName()); if (getTextRange().getStartOffset() < operands.get(0).getTextRange().getStartOffset()) { descriptors.add(new FoldingDescriptor(element.getNode(), TextRange.create(getTextRange().getStartOffset(), operands.get(0).getTextRange().getStartOffset()), group) { @NotNull @Override public String getPlaceholderText() { return operands.get(0) instanceof Operation ? "(" : ""; } }); } if (operands.get(0).supportsFoldRegions(document, this)) { Collections.addAll(descriptors, operands.get(0).buildFoldRegions(operands.get(0).getElement(), document, this)); } descriptors.add(new FoldingDescriptor(element.getNode(), TextRange.create(operands.get(0).getTextRange().getEndOffset(), getTextRange().getEndOffset()), group) { @Nullable @Override public String getPlaceholderText() { String b = operands.get(1).getElement().getText(); return operands.get(0) instanceof Operation ? ")" + superscript(b) : superscript(b); } }); return descriptors.toArray(FoldingDescriptor.EMPTY); } }
true
735d179a1bc66a6d8d044e891e8d4c5fdb42aa9a
Java
dzograf/SearchSERAPIS
/src/arg/tech/argql/translator/sparql/SymbolTable.java
UTF-8
3,405
2.984375
3
[]
no_license
package arg.tech.argql.translator.sparql; /* import java.util.*; import java.util.stream.Collectors; import gr.forth.ics.argql.models.Argument; import gr.forth.ics.argql.models.Proposition; import gr.forth.ics.argql.models.PropositionSet; import gr.forth.ics.argql.models.Variable; import gr.forth.ics.argql.models.VariableValue; import gr.forth.ics.argql.patterns.*; public class SymbolTable { public HashMap<Variable, ArrayList<VariableValue>> variables; public SymbolTable(){ variables = new HashMap<Variable, ArrayList<VariableValue>>(); } /*public int positionOf(String varName) { for (int i = 0; i < variableList.size(); i++) { if (variableList.get(i).name.equals(varName)) return i; } return -1; }*/ /* public void clear(){ variables.clear(); } private boolean varExists(String name) { for(Map.Entry<Variable, ArrayList<VariableValue>> entry : variables.entrySet()){ Variable key = entry.getKey(); if(name.equals(key.name)) return true; } return false; } public boolean addVar(String varName, Variable.Type type) { if(!varExists(varName)){ Variable node = new Variable(varName, type); variables.put(node, new ArrayList<VariableValue>()); return true; } else { return false; } } public void addValue(Variable var, VariableValue value) { for(Map.Entry<Variable, ArrayList<VariableValue>> entry : variables.entrySet()){ Variable key = entry.getKey(); if(var.name.equals(key.name)){ ArrayList<VariableValue> values = entry.getValue(); values.add(value); variables.put(key, values); } } } public void setValues(Variable var, ArrayList<VariableValue> values) { for(Map.Entry<Variable, ArrayList<VariableValue>> entry : variables.entrySet()){ Variable key = entry.getKey(); if(var.name.equals(key.name)){ variables.put(key, values); } } } public ArrayList<VariableValue> getVariableValues(String var){ for(Map.Entry<Variable, ArrayList<VariableValue>> entry: variables.entrySet()){ Variable key = entry.getKey(); if(var.equals(key.name)){ return entry.getValue(); } } return null; } public Variable.Type getType(String var){ for(Map.Entry<Variable, ArrayList<VariableValue>> entry: variables.entrySet()){ Variable v = entry.getKey(); if(v.name.equals(var)) return v.type; } return null; } public void updateValue(Variable variable, VariableValue value) { VariableValue val = valueExists(value.getId(), variable.name); if(val == null) { addValue(variable, value); } else { ArrayList<VariableValue> values = getVariableValues(variable.name); values.remove(val); values.add(value); setValues(variable, values); } } public VariableValue valueExists(String id, String var) { ArrayList<VariableValue> values = getVariableValues(var); for(VariableValue v : values) { if(v.getId().compareTo(id) == 0) { return v; } } return null; } public String toString() { StringBuilder str = new StringBuilder(); for(Map.Entry<Variable, ArrayList<VariableValue>> entry: variables.entrySet()){ Variable v = entry.getKey(); str.append("Variable: " + v.name + "\nValues: \n"); ArrayList<VariableValue> values = getVariableValues(v.name); for(VariableValue value : values) { str.append(value.toString()); str.append("\n"); } } return str.toString(); } }*/
true
f914a3c0e743fe1e1c36d87a00a28cc92b1aa0d6
Java
grzszy/SEP4
/SEP4Android-master/app/src/main/java/com/example/mainactivity/Model/Current.java
UTF-8
2,418
2.90625
3
[]
no_license
package com.example.mainactivity.Model; public class Current { /** * @author Jakob Hansen */ private int CO2_value; private double Temp_value; private double Humidity_value; private int Passenger_value; private int shaftStatus; /** * Constructor for Current class. * @param CO2_value * @param Temp_value * @param Humidity_value * @param Passenger_value * @param shaftStatus */ public Current(int CO2_value, double Temp_value, double Humidity_value, int Passenger_value, int shaftStatus){ this.CO2_value = CO2_value; this.Temp_value = Temp_value; this.Humidity_value = Humidity_value; this.Passenger_value = Passenger_value; this.shaftStatus = shaftStatus; } /** * Getter for CO2 value. * @return CO value. */ public int getCO2_value() { return CO2_value; } /** * Setter for CO2 value. * @param CO2_value */ public void setCO2_value(int CO2_value) { this.CO2_value = CO2_value; } /** * Getter for temperature value. * @return Temperature value. */ public double getTemp_value() { return Temp_value; } /** * Setter for temperature value. * @param temp_value */ public void setTemp_value(double temp_value) { Temp_value = temp_value; } /** * Getter for humidity value. * @return Humidity value. */ public double getHumidity_value() { return Humidity_value; } /** * Setter for humidity value. * @param humidity_value */ public void setHumidity_value(double humidity_value) { Humidity_value = humidity_value; } /** * Getter for passenger value. * @return Passenger value. */ public int getPassenger_value() { return Passenger_value; } /** * Setter for passenger value. * @param passenger_value */ public void setPassenger_value(int passenger_value) { Passenger_value = passenger_value; } /** * Getter for shaft status. * @return Shaft status. */ public int getShaftStatus() { return shaftStatus; } /** * Setter for shaft status. * @param shaftStatus */ public void setShaftStatus(int shaftStatus) { this.shaftStatus = shaftStatus; } }
true
374810ce326b409b0458a474b95f860053304186
Java
ee08b397/AlgoSolutions
/ctci/8_5.java
UTF-8
600
4
4
[]
no_license
/* * Implement an algorithm to print all valid (e.g., properly opened and closed) * combinations of n-pairs of parentheses. * EXAMPLE: * input: 3 (e.g., 3 pairs of parentheses) * output: ()()(), ()(()), (())(), ((())) */ public class Solution { public void printParentheses(int n) { helper("", n, n); } public void helper(String s, int left, int right) { if(left == 0 && right == 0) System.out.println(s); if(left > 0) helper(s + "(", left - 1, right); if(left < right) helper(s + ")", left, right - 1); } }
true
795fedb47ddb7978cf1088422c5392f378ccf197
Java
seblm/code-samples
/all/src/test/java/bundles/BundlesTest.java
UTF-8
2,336
2.609375
3
[]
no_license
package bundles; import org.junit.jupiter.api.Test; import java.util.Locale; import java.util.ResourceBundle; import static org.assertj.core.api.Assertions.assertThat; public class BundlesTest { @Test public void should_display_value_with_language() { ResourceBundle frBundle = ResourceBundle.getBundle("bundles.BundlesTest", Locale.FRENCH); String translatedValue = frBundle.getString("value"); assertThat(translatedValue).isEqualTo("francais"); } @Test public void should_display_value_with_language_and_country() { ResourceBundle fr_FRBundle = ResourceBundle.getBundle("bundles.BundlesTest", Locale.FRANCE); String translatedValue = fr_FRBundle.getString("value"); assertThat(translatedValue).isEqualTo("francais de France"); } @Test public void should_display_value_with_default_Locale() { Locale defaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.ENGLISH); ResourceBundle enBundle = ResourceBundle.getBundle("bundles.BundlesTest"); String translatedValue = enBundle.getString("value"); assertThat(translatedValue).isEqualTo("english"); } finally { Locale.setDefault(defaultLocale); } } @Test public void should_display_value_without_Locale_when_no_file_given() { Locale defaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.CHINA); ResourceBundle defaultBundle = ResourceBundle.getBundle("bundles.BundlesTest", Locale.GERMANY); String translatedValue = defaultBundle.getString("value"); assertThat(translatedValue).isEqualTo("esperanto"); } finally { Locale.setDefault(defaultLocale); } } @Test public void should_use_fallbackLocale_from_Control() { ResourceBundle defaultBundle = ResourceBundle.getBundle("bundles.BundlesTest", Locale.GERMANY, new ResourceBundle.Control() { @Override public Locale getFallbackLocale(String baseName, Locale locale) { return Locale.FRANCE; } }); String translatedValue = defaultBundle.getString("value"); assertThat(translatedValue).isEqualTo("francais de France"); } }
true
fbe8c98913886f752bf35632439b56e2b3c1cea8
Java
abhishek-yadav-cse/netflix-prototype-spring
/src/main/java/com/sjsu/cmpe275/netflix/controller/UserActivityController.java
UTF-8
9,860
2.53125
3
[]
no_license
package com.sjsu.cmpe275.netflix.controller; import java.sql.Date; import java.time.LocalDate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.*; import com.sjsu.cmpe275.netflix.repository.UserActivityRepository; @RestController @CrossOrigin(origins = "*", allowCredentials = "true") @RequestMapping(value = "/user") public class UserActivityController { @Autowired UserActivityRepository repository; // get particular data based on title of movie // API 8: to get customer details based on title of movie @RequestMapping(value = "/{title}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> getDatabyTitle(@PathVariable("title") String title) { return getInformation(title); } private ResponseEntity<?> getInformation(String title) { ResponseEntity responseEntity = new ResponseEntity(null, HttpStatus.NOT_FOUND); try { List questionOptional = repository.findAllActiveUsers(title); System.out.println(questionOptional); if(questionOptional.isEmpty()) { return new ResponseEntity<>( "No Data found for this Title", HttpStatus.NOT_FOUND); } else { HttpHeaders httpHeaders = new HttpHeaders(); List<HashMap<String,String>> lst = new ArrayList<HashMap<String,String>>(); for (Object i: questionOptional) { Map<String, String> map = new HashMap<String, String>(); map.put("email", i.toString()); lst.add((HashMap<String, String>) map); //System.out.printf("I am here",i); } return new ResponseEntity<>(lst, httpHeaders, HttpStatus.OK); } } catch(Exception e) {e.printStackTrace();} return responseEntity; } //API getnumber 10:5a of plays: input: moviename, period // @SuppressWarnings(value = { "" }) @RequestMapping(value = "/{title}/{date}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> getDatabymovienamedate(@PathVariable("title") String title, @PathVariable("date") String date) { return getInformationbynamedate(date, title); } private ResponseEntity<?> getInformationbynamedate(String time, String title) { ResponseEntity responseEntity = new ResponseEntity(null, HttpStatus.NOT_FOUND); LocalDate date; try { if(time.equals("day")){date = LocalDate.now().minusDays(1); } else if(time.equals("week")) {date = LocalDate.now().minusDays(7); } else if (time.equals("month")){ date = LocalDate.now().minusDays(30); } else {return new ResponseEntity<>( "Please choose between 24 hours, 1 week or 1 month", HttpStatus.NOT_FOUND);} String data = ""; Date new_date = java.sql.Date.valueOf(date); System.out.printf("date is", new_date); int questionOptional = repository.getDatabyNameAndPeriod(new_date, title); //System.out.printf("Value of date", questionOptional); if(questionOptional != 0) { HttpHeaders httpHeaders = new HttpHeaders(); Map<String, Integer> map = new HashMap<String, Integer>(); map.put("NoOfPlay", questionOptional); //System.out.printf("I am here",i); return new ResponseEntity(map ,httpHeaders, HttpStatus.OK); } else { return new ResponseEntity<>( "No Data found for this Title within given period", HttpStatus.NOT_FOUND); } } catch(Exception e) {e.printStackTrace();} return responseEntity; } //API 4c: to get top 10 users @RequestMapping(value = "/topTenUser/{date}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> getTopTen(@PathVariable("date") String date) { return getInformationbydate(date); } private ResponseEntity<?> getInformationbydate(String time) { ResponseEntity responseEntity = new ResponseEntity(null, HttpStatus.NOT_FOUND); LocalDate date; try { if(time.equals("day")){date = LocalDate.now().minusDays(1); } else if(time.equals("week")) {date = LocalDate.now().minusDays(7); } else if (time.equals("month")){ date = LocalDate.now().minusDays(30); } else {return new ResponseEntity<>( "Please choose between 24 hours, 1 week or 1 month", HttpStatus.NOT_FOUND);} HttpHeaders httpHeaders = new HttpHeaders(); System.out.printf("date is",date); Date new_date = java.sql.Date.valueOf(date); List questionOptional = repository.getTopTenUsers(new_date); if(questionOptional.isEmpty()) { return new ResponseEntity<>( "No Data found in this TimeFrame", HttpStatus.NOT_FOUND); } else { List<HashMap<String,String>> lst = new ArrayList<HashMap<String,String>>(); for (Object i: questionOptional) { Map<String, String> map = new HashMap<String, String>(); map.put("User", i.toString()); lst.add((HashMap<String, String>) map); //System.out.printf("I am here",i); } return new ResponseEntity<>(lst, httpHeaders, HttpStatus.OK); } } catch(Exception e) {e.printStackTrace();} return responseEntity; } //API 11:5b get top ten movies based on no of plays in a given period of time @RequestMapping(value = "/topTenMovies/{date}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> getTopTenMoviesbyDate(@PathVariable("date") String date) { return getTopTenMovieInformationbydate(date); } private ResponseEntity<?> getTopTenMovieInformationbydate(String time) { ResponseEntity responseEntity = new ResponseEntity(null, HttpStatus.NOT_FOUND); LocalDate date; HttpHeaders httpHeaders = new HttpHeaders(); try { if(time.equals("day")){date = LocalDate.now().minusDays(1); } else if(time.equals("week")) {date = LocalDate.now().minusDays(7); } else if (time.equals("month")){ date = LocalDate.now().minusDays(30); } else {return new ResponseEntity<>( "Please choose between 24 hours, 1 week or 1 month", HttpStatus.NOT_FOUND);} Date new_date = java.sql.Date.valueOf(date); List questionOptional = repository.getTopTenMovies(new_date); if(questionOptional.isEmpty()) { return new ResponseEntity<>( "No Data found in this TimeFrame", HttpStatus.NOT_FOUND); } else { List<HashMap<String,String>> lst = new ArrayList<HashMap<String,String>>(); for (Object i: questionOptional) { Map<String, String> map = new HashMap<String, String>(); map.put("moviename", i.toString()); lst.add((HashMap<String, String>) map); //System.out.printf("I am here",i); } return new ResponseEntity<>(lst, httpHeaders, HttpStatus.OK); } } catch(Exception e) {e.printStackTrace();} return responseEntity; } //API 4b: An admin must be able to view the movie playing history (in reverse chronological order) of any customer. @RequestMapping(value = "/movieHistorys/{userName}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> getHitory(@PathVariable("userName") String userName) { return getMovieHistory(userName); } private ResponseEntity<?> getMovieHistory(String userName) { ResponseEntity responseEntity = new ResponseEntity(null, HttpStatus.NOT_FOUND); HttpHeaders httpHeaders = new HttpHeaders(); try { List questionOptional = repository.getMoviesHistoryByUser(userName); if(questionOptional.isEmpty()) { return new ResponseEntity<>( "No Data found in this TimeFrame", HttpStatus.NOT_FOUND); } else { List<HashMap<String,String>> lst = new ArrayList<HashMap<String,String>>(); for (Object i: questionOptional) { Map<String, String> map = new HashMap<String, String>(); map.put("moviename", i.toString()); lst.add((HashMap<String, String>) map); //System.out.printf("I am here",i); } return new ResponseEntity<>(lst, httpHeaders, HttpStatus.OK); } } catch(Exception e) {e.printStackTrace();} return responseEntity; } @RequestMapping(value = "/userHistory/{email}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> getUserHistory(@PathVariable("email") String email) { HttpStatus status = HttpStatus.OK; List<Map<String, String>> responseList = new ArrayList<>(); List<String> userHistory = repository.getUserHistory(email); System.out.println(userHistory.size()); for(String eachMovie: userHistory) { Map<String, String> eachMovieMap = new HashMap<>(); eachMovieMap.put("name", eachMovie); responseList.add(eachMovieMap); } return new ResponseEntity(responseList, null, status); } }
true
2b11d850070a5ddbb1938e524d8d7b4c660bec15
Java
javaandselenium/java6-30
/src/inhertances/Child.java
UTF-8
243
2.78125
3
[]
no_license
package inhertances; public class Child extends Parent{ public void cycle() { System.out.println("cycle"); } public static void main(String[] args) { Child c=new Child(); c.cycle(); c.car(); c.house(); } }
true
14d70796e2fc2124093c97bf943a3ba38cc7b389
Java
nikkil331/AIMProject
/src/tools/syncBlockStats/SyncBlocksStats.java
UTF-8
17,018
2.125
2
[ "BSD-3-Clause", "SMLNJ" ]
permissive
package tools.syncBlockStats; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.RandomAccessFile; import java.util.HashSet; import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.Stack; import java.util.concurrent.ConcurrentHashMap; import java.util.Iterator; import rr.meta.ClassInfo; import rr.meta.FieldInfo; import rr.meta.SourceLocation; import acme.util.decorations.Decoration; import acme.util.decorations.DecorationFactory; import acme.util.decorations.DefaultValue; import acme.util.option.CommandLine; import acme.util.option.CommandLineOption; import rr.tool.TaggedValue.Type; import rr.tool.Tool; import rr.event.AccessEvent; import rr.event.AcquireEvent; import rr.event.ArrayAccessEvent; import rr.event.InterruptEvent; import rr.event.JoinEvent; import rr.event.MethodEvent; import rr.event.ReleaseEvent; import rr.event.SleepEvent; import rr.event.VolatileAccessEvent; import rr.event.WaitEvent; import rr.state.ShadowThread; import rr.state.ShadowVar; import rr.event.FieldAccessEvent; import org.jgrapht.DirectedGraph; import org.jgrapht.alg.CycleDetector; import org.jgrapht.alg.DijkstraShortestPath; import org.jgrapht.alg.JohnsonsCycleFinder; import org.jgrapht.graph.*; public class SyncBlocksStats extends Tool { /*----------------------------CLASS VARIABLES-----------------------*/ private static boolean testOutput = false; //mapping from thread to thread local information (locks, accessed fields) private static DecorationFactory<ShadowThread> fac = new DecorationFactory<ShadowThread>(); private static Decoration<ShadowThread, ThreadData> tdata =fac.make("tdata", DecorationFactory.Type.SINGLE, new DefaultValue<ShadowThread, ThreadData>(){ public ThreadData get(ShadowThread t) { return new ThreadData();} }); //mapping from program location to access counts and depths private static ConcurrentHashMap<SourceLocation, Counter> pcMap = new ConcurrentHashMap<SourceLocation, Counter>(); //mapping from static fields to shadow var instances private static ConcurrentHashMap<FieldInfo, List<Field>> fieldMap = new ConcurrentHashMap<FieldInfo, List<Field>>(); //state for recording partial order of accesses private static DefaultDirectedGraph<Field, BlockEdge> globalGraph = new DefaultDirectedGraph<Field, BlockEdge>(BlockEdge.class); static int LOCKS_GRABBED = 1; //commandline options to specify analysis CommandLineOption<Boolean> trackOrder; CommandLineOption<Boolean> trackCounts; CommandLineOption<Boolean> mergeGraph; CommandLineOption<String> outputName; /*-----------------------------INNER CLASSES---------------------*/ private class AccessTracker{ Object o; boolean r = false; boolean w = false; SourceLocation loc; int currDepth = 0; int firstRDepth = -1; int firstWDepth = -1; public AccessTracker(AcquireEvent ae){ this.o = ae.getLock().getLock(); synchronized(ae.getInfo()){ this.loc = ae.getInfo().getLoc(); } } } private static class ThreadData{ private final Stack<AccessTracker> locks = new Stack<AccessTracker>(); private DefaultDirectedGraph<Field, BlockEdge> graph = new DefaultDirectedGraph<Field, BlockEdge>(BlockEdge.class); private Field lastAccessed = null; private HashSet<Field> seen = new HashSet<Field>(); public int locksGrabbed; public Stack<AccessTracker> getLocks(){ return locks; } public Field getLastAccessed(){ return lastAccessed; } public void setLastAccessed(Field f){ lastAccessed = f; } public HashSet<Field> getSeen(){ return seen; } public void setSeen(HashSet<Field> seen){ this.seen = seen; } } private static class Counter{ int Total = 0; int Read = 0; int Write = 0; int None = 0; List<Integer> depths = new ArrayList<Integer>(); } /*----------------------------TOOL IMPLEMENTATION----------------------------*/ public SyncBlocksStats(String name, Tool next, CommandLine commandLine) { super(name, next, commandLine); trackOrder = CommandLine.makeBoolean( "noOrder", true, CommandLineOption.Kind.EXPERIMENTAL, "Enable tracking of order of accesses. Default value is true"); mergeGraph = CommandLine.makeBoolean( "mergeGraph", false, CommandLineOption.Kind.EXPERIMENTAL, "Merge certain nodes to shrink graph size. Default value is false"); trackCounts = CommandLine.makeBoolean( "noCounts", true, CommandLineOption.Kind.EXPERIMENTAL, "Enable tracking of read, write, neither counts per static synchronized block." + "Default value is true"); outputName = CommandLine.makeString( "output", "", CommandLineOption.Kind.EXPERIMENTAL, "Name modifier for order analysis output. -output=avrora will output the files " + "avrora_graph.ser and avrora_roots.ser if the trackOrder option is set to true." ); commandLine.add(trackOrder); commandLine.add(mergeGraph); commandLine.add(trackCounts); commandLine.add(outputName); } @Override public void stop(ShadowThread st){ ThreadData td = tdata.get(st); if(td.graph.vertexSet().size() != 0){ unionGraph(td); } } @Override public void preSleep(SleepEvent se){ ThreadData td = tdata.get(se.getThread()); if(td.graph.vertexSet().size() != 0){ unionGraph(td); } } @Override public void preJoin(JoinEvent je){ ThreadData td = tdata.get(je.getThread()); if(td.graph.vertexSet().size() != 0){ unionGraph(td); } } @Override public void preInterrupt(InterruptEvent ie){ ThreadData td = tdata.get(ie.getThread()); if(td.graph.vertexSet().size() != 0){ unionGraph(td); } } @Override public void preWait(WaitEvent we){ ThreadData td = tdata.get(we.getThread()); if(td.graph.vertexSet().size() != 0){ unionGraph(td); } } @Override public void acquire(AcquireEvent ae){ if(testOutput){ System.out.println("thread " + ae.getThread().getTid() + " acquired " + ae.getLock().getLock().toString()); } Stack<AccessTracker> localLocks = tdata.get(ae.getThread()).getLocks(); AccessTracker at = new AccessTracker(ae); if(trackCounts.get()){ updateBlockTotal(at); } localLocks.push(at); tdata.get(ae.getThread()).locksGrabbed++; } private void updateBlockTotal(AccessTracker at){ Counter newCount = new Counter(); newCount.Total++; if(pcMap.putIfAbsent(at.loc, newCount) != null){ Counter prevCount = pcMap.get(at.loc); synchronized(prevCount){ prevCount.Total++; } } } @Override public void release(ReleaseEvent re){ if(testOutput){ System.out.println("thread " + re.getThread().getTid() + " released " + re.getLock().getLock().toString()); } ThreadData td = tdata.get(re.getThread()); Stack<AccessTracker> localLocks = td.getLocks(); AccessTracker at = localLocks.pop(); if(trackCounts.get()){ updateBlockCategory(at); } if(trackOrder.get()){ if(td.locksGrabbed % LOCKS_GRABBED == 0){ unionGraph(td); } //reset variable tracking when finished with sync block if(localLocks.size() == 0){ td.setLastAccessed(null); td.setSeen(new HashSet<Field>()); } } } private void updateBlockCategory(AccessTracker at){ Counter count = pcMap.get(at.loc); synchronized(count){ if(at.w){ count.Write++; if(!count.depths.contains(at.firstWDepth)) count.depths.add(at.firstWDepth); } else if(at.r){ count.Read++; if(!count.depths.contains(at.firstRDepth)) count.depths.add(at.firstRDepth); } else{ count.None++; } } } public void unionGraph(ThreadData td){ synchronized(globalGraph){ globalGraph.union(td.graph); } td.graph = new DefaultDirectedGraph<Field, BlockEdge>(BlockEdge.class); } @Override public void access(AccessEvent ae){ ThreadData td = tdata.get(ae.getThread()); Stack<AccessTracker> localLocks = td.getLocks(); if(trackOrder.get()){ //do only when in sync block if(localLocks.size() > 0){ //get current field accessed Field curr = null; if(ae.getOriginalShadow() instanceof Field){ curr = (Field)ae.getOriginalShadow(); } else{ curr = (Field)makeShadowVar(ae); } curr.loc = localLocks.peek().loc; //if access is a field type, add it to map if(ae.getKind() == AccessEvent.Kind.FIELD || ae.getKind() == AccessEvent.Kind.VOLATILE){ FieldInfo field = curr.statField; List<Field> vList = new ArrayList<Field>(); vList.add(curr); if(fieldMap.putIfAbsent(field, vList) != null){ List<Field> vertices = fieldMap.get(field); synchronized(vertices){ if(!vertices.contains(curr)) vertices.add(curr); } } } if(!td.getSeen().contains(curr)){ //get last field accessed in the sync block Field prev = td.getLastAccessed(); //if the current field is the first field accessed in sync block if(prev == null){ td.setLastAccessed(curr); td.graph.addVertex(curr); } else{ addEdgeAccessToGraph(td, prev, curr); td.setLastAccessed(curr); } td.getSeen().add(curr); } } } if(trackCounts.get()){ categorizeAccess(ae, localLocks); } } private void addEdgeAccessToGraph(ThreadData td, Field prev, Field curr){ td.graph.addVertex(prev); td.graph.addVertex(curr); if(DijkstraShortestPath.<Field, BlockEdge>findPathBetween(td.graph, prev, curr) == null){ BlockEdge e = td.graph.addEdge(prev, curr); e.loc = prev.loc; } } private void categorizeAccess(AccessEvent ae, Stack<AccessTracker>localLocks){ Object target = ae.getTarget(); Object self = ae.getAccessed(); for(AccessTracker at : localLocks){ if (at.o == self){ if(ae.isWrite()){ setFirstDepth(at, false); at.w = true; } else{ setFirstDepth(at, true); at.r = true; } } else if(at.o == target){ setFirstDepth(at, true); at.r = true; } else if(at.o instanceof Class){ Class<?> heldClass = (Class<?>)at.o; ClassInfo cinfo = ae.getAccessInfo().getEnclosing().getOwner(); if(heldClass.getName().equals(cinfo.getName().replace('/', '.'))) { setFirstDepth(at, true); at.r = true; } } } } private void setFirstDepth(AccessTracker at, boolean isRead){ if(isRead){ if(!at.r){ at.firstRDepth = at.currDepth; } } else{ if(!at.w){ at.firstWDepth = at.currDepth; } } } @Override public void volatileAccess(VolatileAccessEvent e){ access(e); } @Override public ShadowVar makeShadowVar(AccessEvent ae){ Stack<AccessTracker> localLocks = tdata.get(ae.getThread()).locks; if(trackOrder.get()){ Field f = new Field(); if(ae.getKind() == AccessEvent.Kind.FIELD || ae.getKind() == AccessEvent.Kind.VOLATILE){ FieldAccessEvent fae = (FieldAccessEvent)ae; f.isField = true; f.name = fae.getInfo().getField().getName(); f.statField = fae.getInfo().getField(); } else{ ArrayAccessEvent aae = (ArrayAccessEvent)ae; f.isField = false; f.name = aae.getTarget().toString() + "[" + aae.getIndex() + "]"; } return f; } return new ShadowVar(){}; } @Override public void enter(MethodEvent me){ if(testOutput){ System.out.println(me.toString()); } if(trackCounts.get()){ Stack<AccessTracker> localLocks = tdata.get(me.getThread()).getLocks(); for(AccessTracker at : localLocks){ at.currDepth++; } } } @Override public void exit(MethodEvent me){ if(testOutput){ System.out.println(me.toString()); } if(trackCounts.get()){ Stack<AccessTracker> localLocks = tdata.get(me.getThread()).getLocks(); for(AccessTracker at : localLocks){ at.currDepth--; } } } @Override public void fini(){ if(trackOrder.get()) try { synchronized(globalGraph){ saveOrderAnalysis(); } } catch (IOException e) { e.printStackTrace(); } if(trackCounts.get()) printCountsAnalysis(); } private void saveOrderAnalysis() throws IOException{ System.out.println("Number of nodes = " + globalGraph.vertexSet().size()); System.out.println("Number of edges = " + globalGraph.edgeSet().size()); if(mergeGraph.get()){ mergeGraph(); System.out.println("Number of nodes after merge = " + globalGraph.vertexSet().size()); System.out.println("Number of edges after merge = " + globalGraph.edgeSet().size()); } //get vertices in cycle CycleDetector<Field, BlockEdge> cd = new CycleDetector<Field, BlockEdge>(globalGraph); Set<Field> cycles = cd.findCycles(); //get edges in cycle subgraph Set<BlockEdge> edges = new HashSet<BlockEdge>(); for(Field f : cycles){ Set<BlockEdge> outEs = globalGraph.outgoingEdgesOf(f); for(BlockEdge e : outEs){ if(cycles.contains(globalGraph.getEdgeTarget(e))) edges.add(e); } } DirectedGraph<Field, BlockEdge> cycleGraph = new DirectedSubgraph<Field, BlockEdge>( globalGraph, cycles, edges ); //find number of simple cycles in cycle graph JohnsonsCycleFinder<Field,BlockEdge> johnsons = new JohnsonsCycleFinder<Field,BlockEdge>(cycleGraph); int numCycles = johnsons.getCycleCount(); System.out.println("Number of simple cycles = " + numCycles); //save cycle graph String output = outputName.get(); String graphName; if(!output.isEmpty()){ graphName = output + "_graph.ser"; } else{ graphName = "graph.ser"; } RandomAccessFile raf = new RandomAccessFile(graphName, "rw"); FileOutputStream gout = new FileOutputStream(raf.getFD()); ObjectOutputStream graph_oos = new ObjectOutputStream(gout); graph_oos.writeObject(globalGraph); graph_oos.close(); } private void printCountsAnalysis(){ synchronized(pcMap){ System.out.println("Number of Static Synchronized Blocks = " + pcMap.size()); Set<SourceLocation> keys = pcMap.keySet(); for(SourceLocation loc : keys){ Counter count = pcMap.get(loc); synchronized(count){ StringBuilder sb = new StringBuilder(); sb.append("["); for(Integer i : count.depths){ sb.append(i + ","); } if(sb.length() > 1) sb.replace(sb.length() - 1, sb.length(), "]"); else sb.append("]"); System.out.printf("result['%s line %d'] = {\"total\" : %d , \"read\" : %d, " + "\"write\" : %d, \"neither\" : %d, \"depths\" : %s}\n", loc.getFile().replace('/', '.'), loc.getLine(), count.Total, count.Read, count.Write, count.None, sb.toString()); } } } } private void mergeGraph(){ Set<FieldInfo> fields = fieldMap.keySet(); for(FieldInfo f : fields){ List<Field> vertices = fieldMap.get(f); int i = 0; while(i < vertices.size()){ int j = i + 1; while(j < vertices.size()){ if(globalGraph.containsVertex(vertices.get(i)) && globalGraph.containsVertex(vertices.get(j))){ if(!mergeVertices(vertices.get(i), vertices.get(j), i, j)){ j++; } } else{ j++; } } } } } //pass in vertex index in list to speed up deletion private boolean mergeVertices(Field v0, Field v1, int ind0, int ind1){ //outgoing-edge sets if(globalGraph.containsEdge(v0, v1) || globalGraph.containsEdge(v1, v0)) return false; Set<BlockEdge> outEdges0 = globalGraph.outgoingEdgesOf(v0); Set<BlockEdge> outEdges1 = globalGraph.outgoingEdgesOf(v1); if(outEdges0.size() != outEdges1.size()){ return false; } //incoming-edge sets Set<BlockEdge> inEdges0 = globalGraph.incomingEdgesOf(v0); Set<BlockEdge> inEdges1 = globalGraph.incomingEdgesOf(v1); if(inEdges0.size() != inEdges1.size()){ return false; } for(BlockEdge e0 : outEdges0){ Field target0 = globalGraph.getEdgeTarget(e0); boolean match = false; for(BlockEdge e1 : outEdges1){ Field target1 = globalGraph.getEdgeTarget(e1); if(target0.isField && target1.isField){ if(target0.statField.equals(target1.statField) && e0.loc.equals(e1.loc)) { match = true; } } } if(!match){ return false; } } for(BlockEdge e0 : inEdges0){ Field source0 = globalGraph.getEdgeSource(e0); boolean match = false; for(BlockEdge e1 : inEdges1){ Field source1 = globalGraph.getEdgeSource(e1); if(source0.isField && source1.isField){ if(source0.statField.equals(source1.statField) && e0.loc.equals(e1.loc)){ match = true; } } } if(!match) { return false; } } v0.merged = true; for(BlockEdge e : outEdges1){ BlockEdge newE = globalGraph.addEdge(v0, globalGraph.getEdgeTarget(e)); if(newE != null) newE.loc = e.loc; } for(BlockEdge e : inEdges1){ BlockEdge newE = globalGraph.addEdge(globalGraph.getEdgeSource(e), v0); if(newE != null) newE.loc = e.loc; } globalGraph.removeVertex(v1); fieldMap.get(v1.statField).remove(ind1); return true; } }
true
dc47981327853b6e1bf74865e84cb79acb0725b3
Java
shubham/Rx-learning
/app/src/main/java/com/babapanda/rxoperators/customoperator/MyOperator.java
UTF-8
843
2.390625
2
[]
no_license
package com.babapanda.rxoperators.customoperator; import org.jetbrains.annotations.NotNull; import io.reactivex.SingleObserver; import io.reactivex.SingleOperator; import io.reactivex.disposables.Disposable; public class MyOperator<T> implements SingleOperator<T,T> { @NotNull @Override public SingleObserver<? super T> apply(@NotNull SingleObserver<? super T> singleObserver) throws Exception { return new SingleObserver<T>() { @Override public void onSubscribe(@NotNull Disposable d) { singleObserver.onSubscribe(d); } @Override public void onSuccess(@NotNull T t) { singleObserver.onSuccess(t); } @Override public void onError(@NotNull Throwable e) { } }; } }
true
73c3167659b0e5346a9a7c338dc92c50b3e15bb3
Java
janebabra/speedment
/src/main/java/com/speedment/core/config/view/ColumnView.java
UTF-8
1,404
1.953125
2
[ "Apache-2.0" ]
permissive
/** * * Copyright (c) 2006-2015, Speedment, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); You may not * use this file except in compliance with the License. You may obtain a copy of * the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.speedment.core.config.view; import static com.speedment.codegen.util.Formatting.*; import com.speedment.codegen.base.Generator; import com.speedment.codegen.base.Transform; import com.speedment.core.config.model.Column; import com.speedment.core.config.model.impl.utils.MethodsParser; import java.util.Optional; import java.util.stream.Collectors; /** * * @author Emil Forslund */ public class ColumnView /*implements Transform<Column, String>*/ { // @Override // public Optional<String> render(Generator cg, Column model) { // return Optional.of("column " + block( // MethodsParser.streamOfExternal(Column.class) // .map(m -> m.getName() + " = " + "\"" + "\"") // .collect(Collectors.joining(nl())), // )); // } // }
true
6573b01e765a4f0141f54e3154792bc74985392c
Java
VazkiiMods/Botania
/Xplat/src/main/java/vazkii/botania/common/block/BotaniaFlowerBlocks.java
UTF-8
47,864
1.71875
2
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * This class is distributed as part of the Botania Mod. * Get the Source Code in github: * https://github.com/Vazkii/Botania * * Botania is Open Source and distributed under the * Botania License: http://botaniamod.net/license.php */ package vazkii.botania.common.block; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.FlowerBlock; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockBehaviour; import vazkii.botania.api.block.WandHUD; import vazkii.botania.api.block_entity.BindableSpecialFlowerBlockEntity; import vazkii.botania.api.block_entity.FunctionalFlowerBlockEntity; import vazkii.botania.api.block_entity.GeneratingFlowerBlockEntity; import vazkii.botania.api.block_entity.SpecialFlowerBlockEntity; import vazkii.botania.common.block.block_entity.BotaniaBlockEntities; import vazkii.botania.common.block.flower.ManastarBlockEntity; import vazkii.botania.common.block.flower.PureDaisyBlockEntity; import vazkii.botania.common.block.flower.functional.*; import vazkii.botania.common.block.flower.generating.*; import vazkii.botania.common.brew.BotaniaMobEffects; import vazkii.botania.common.item.BotaniaItems; import vazkii.botania.common.item.block.SpecialFlowerBlockItem; import vazkii.botania.common.lib.LibBlockNames; import vazkii.botania.xplat.XplatAbstractions; import java.util.function.BiConsumer; import java.util.function.Supplier; public class BotaniaFlowerBlocks { private static final BlockBehaviour.Properties FLOWER_PROPS = BlockBehaviour.Properties.copy(Blocks.POPPY); private static final BlockBehaviour.Properties FLOATING_PROPS = BotaniaBlocks.FLOATING_PROPS; public static final Block pureDaisy = createSpecialFlowerBlock(BotaniaMobEffects.clear, 1, FLOWER_PROPS, () -> BotaniaFlowerBlocks.PURE_DAISY); public static final Block pureDaisyFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.PURE_DAISY); public static final Block manastar = createSpecialFlowerBlock(MobEffects.GLOWING, 10, FLOWER_PROPS, () -> BotaniaFlowerBlocks.MANASTAR); public static final Block manastarFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.MANASTAR); public static final Block hydroangeas = createSpecialFlowerBlock(MobEffects.UNLUCK, 10, FLOWER_PROPS, () -> BotaniaFlowerBlocks.HYDROANGEAS); public static final Block hydroangeasFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.HYDROANGEAS); public static final Block endoflame = createSpecialFlowerBlock(MobEffects.MOVEMENT_SLOWDOWN, 10, FLOWER_PROPS, () -> BotaniaFlowerBlocks.ENDOFLAME); public static final Block endoflameFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.ENDOFLAME); public static final Block thermalily = createSpecialFlowerBlock(MobEffects.FIRE_RESISTANCE, 120, FLOWER_PROPS, () -> BotaniaFlowerBlocks.THERMALILY); public static final Block thermalilyFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.THERMALILY); public static final Block rosaArcana = createSpecialFlowerBlock(MobEffects.LUCK, 64, FLOWER_PROPS, () -> BotaniaFlowerBlocks.ROSA_ARCANA); public static final Block rosaArcanaFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.ROSA_ARCANA); public static final Block munchdew = createSpecialFlowerBlock(MobEffects.SLOW_FALLING, 300, FLOWER_PROPS, () -> BotaniaFlowerBlocks.MUNCHDEW); public static final Block munchdewFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.MUNCHDEW); public static final Block entropinnyum = createSpecialFlowerBlock(MobEffects.DAMAGE_RESISTANCE, 72, FLOWER_PROPS, () -> BotaniaFlowerBlocks.ENTROPINNYUM); public static final Block entropinnyumFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.ENTROPINNYUM); public static final Block kekimurus = createSpecialFlowerBlock(MobEffects.SATURATION, 15, FLOWER_PROPS, () -> BotaniaFlowerBlocks.KEKIMURUS); public static final Block kekimurusFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.KEKIMURUS); public static final Block gourmaryllis = createSpecialFlowerBlock(MobEffects.HUNGER, 180, FLOWER_PROPS, () -> BotaniaFlowerBlocks.GOURMARYLLIS); public static final Block gourmaryllisFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.GOURMARYLLIS); public static final Block narslimmus = createSpecialFlowerBlock(BotaniaMobEffects.featherfeet, 240, FLOWER_PROPS, () -> BotaniaFlowerBlocks.NARSLIMMUS); public static final Block narslimmusFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.NARSLIMMUS); public static final Block spectrolus = createSpecialFlowerBlock(MobEffects.BLINDNESS, 240, FLOWER_PROPS, () -> BotaniaFlowerBlocks.SPECTROLUS); public static final Block spectrolusFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.SPECTROLUS); public static final Block dandelifeon = createSpecialFlowerBlock(MobEffects.CONFUSION, 240, FLOWER_PROPS, () -> BotaniaFlowerBlocks.DANDELIFEON); public static final Block dandelifeonFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.DANDELIFEON); public static final Block rafflowsia = createSpecialFlowerBlock(MobEffects.HEALTH_BOOST, 18, FLOWER_PROPS, () -> BotaniaFlowerBlocks.RAFFLOWSIA); public static final Block rafflowsiaFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.RAFFLOWSIA); public static final Block shulkMeNot = createSpecialFlowerBlock(MobEffects.LEVITATION, 72, FLOWER_PROPS, () -> BotaniaFlowerBlocks.SHULK_ME_NOT); public static final Block shulkMeNotFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.SHULK_ME_NOT); public static final Block bellethorn = createSpecialFlowerBlock(MobEffects.WITHER, 10, FLOWER_PROPS, () -> BotaniaFlowerBlocks.BELLETHORNE); public static final Block bellethornChibi = createSpecialFlowerBlock(MobEffects.WITHER, 10, FLOWER_PROPS, () -> BotaniaFlowerBlocks.BELLETHORNE_CHIBI); public static final Block bellethornFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.BELLETHORNE); public static final Block bellethornChibiFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.BELLETHORNE_CHIBI); public static final Block bergamute = createSpecialFlowerBlock(MobEffects.BLINDNESS, 10, FLOWER_PROPS, () -> BotaniaFlowerBlocks.BERGAMUTE); public static final Block bergamuteFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.BERGAMUTE); public static final Block dreadthorn = createSpecialFlowerBlock(MobEffects.WITHER, 10, FLOWER_PROPS, () -> BotaniaFlowerBlocks.DREADTHORN); public static final Block dreadthornFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.DREADTHORN); public static final Block heiseiDream = createSpecialFlowerBlock(BotaniaMobEffects.soulCross, 300, FLOWER_PROPS, () -> BotaniaFlowerBlocks.HEISEI_DREAM); public static final Block heiseiDreamFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.HEISEI_DREAM); public static final Block tigerseye = createSpecialFlowerBlock(MobEffects.DAMAGE_BOOST, 90, FLOWER_PROPS, () -> BotaniaFlowerBlocks.TIGERSEYE); public static final Block tigerseyeFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.TIGERSEYE); public static final Block jadedAmaranthus = createSpecialFlowerBlock(MobEffects.HEAL, 1, FLOWER_PROPS, () -> BotaniaFlowerBlocks.JADED_AMARANTHUS); public static final Block jadedAmaranthusFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.JADED_AMARANTHUS); public static final Block orechid = createSpecialFlowerBlock(MobEffects.DIG_SPEED, 10, FLOWER_PROPS, () -> BotaniaFlowerBlocks.ORECHID); public static final Block orechidFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.ORECHID); public static final Block fallenKanade = createSpecialFlowerBlock(MobEffects.REGENERATION, 90, FLOWER_PROPS, () -> BotaniaFlowerBlocks.FALLEN_KANADE); public static final Block fallenKanadeFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.FALLEN_KANADE); public static final Block exoflame = createSpecialFlowerBlock(MobEffects.MOVEMENT_SPEED, 240, FLOWER_PROPS, () -> BotaniaFlowerBlocks.EXOFLAME); public static final Block exoflameFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.EXOFLAME); public static final Block agricarnation = createSpecialFlowerBlock(MobEffects.ABSORPTION, 48, FLOWER_PROPS, () -> BotaniaFlowerBlocks.AGRICARNATION); public static final Block agricarnationChibi = createSpecialFlowerBlock(MobEffects.ABSORPTION, 48, FLOWER_PROPS, () -> BotaniaFlowerBlocks.AGRICARNATION_CHIBI); public static final Block agricarnationFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.AGRICARNATION); public static final Block agricarnationChibiFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.AGRICARNATION_CHIBI); public static final Block hopperhock = createSpecialFlowerBlock(MobEffects.MOVEMENT_SPEED, 30, FLOWER_PROPS, () -> BotaniaFlowerBlocks.HOPPERHOCK); public static final Block hopperhockChibi = createSpecialFlowerBlock(MobEffects.MOVEMENT_SPEED, 30, FLOWER_PROPS, () -> BotaniaFlowerBlocks.HOPPERHOCK_CHIBI); public static final Block hopperhockFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.HOPPERHOCK); public static final Block hopperhockChibiFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.HOPPERHOCK_CHIBI); public static final Block tangleberrie = createSpecialFlowerBlock(BotaniaMobEffects.bloodthrst, 120, FLOWER_PROPS, () -> BotaniaFlowerBlocks.TANGLEBERRIE); public static final Block tangleberrieChibi = createSpecialFlowerBlock(BotaniaMobEffects.bloodthrst, 120, FLOWER_PROPS, () -> BotaniaFlowerBlocks.TANGLEBERRIE_CHIBI); public static final Block tangleberrieFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.TANGLEBERRIE); public static final Block tangleberrieChibiFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.TANGLEBERRIE_CHIBI); public static final Block jiyuulia = createSpecialFlowerBlock(BotaniaMobEffects.emptiness, 120, FLOWER_PROPS, () -> BotaniaFlowerBlocks.JIYUULIA); public static final Block jiyuuliaChibi = createSpecialFlowerBlock(BotaniaMobEffects.emptiness, 120, FLOWER_PROPS, () -> BotaniaFlowerBlocks.JIYUULIA_CHIBI); public static final Block jiyuuliaFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.JIYUULIA); public static final Block jiyuuliaChibiFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.JIYUULIA_CHIBI); public static final Block rannuncarpus = createSpecialFlowerBlock(MobEffects.JUMP, 30, FLOWER_PROPS, () -> BotaniaFlowerBlocks.RANNUNCARPUS); public static final Block rannuncarpusChibi = createSpecialFlowerBlock(MobEffects.JUMP, 30, FLOWER_PROPS, () -> BotaniaFlowerBlocks.RANNUNCARPUS_CHIBI); public static final Block rannuncarpusFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.RANNUNCARPUS); public static final Block rannuncarpusChibiFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.RANNUNCARPUS_CHIBI); public static final Block hyacidus = createSpecialFlowerBlock(MobEffects.POISON, 48, FLOWER_PROPS, () -> BotaniaFlowerBlocks.HYACIDUS); public static final Block hyacidusFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.HYACIDUS); public static final Block pollidisiac = createSpecialFlowerBlock(MobEffects.DIG_SPEED, 369, FLOWER_PROPS, () -> BotaniaFlowerBlocks.POLLIDISIAC); public static final Block pollidisiacFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.POLLIDISIAC); public static final Block clayconia = createSpecialFlowerBlock(MobEffects.WEAKNESS, 30, FLOWER_PROPS, () -> BotaniaFlowerBlocks.CLAYCONIA); public static final Block clayconiaChibi = createSpecialFlowerBlock(MobEffects.WEAKNESS, 30, FLOWER_PROPS, () -> BotaniaFlowerBlocks.CLAYCONIA_CHIBI); public static final Block clayconiaFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.CLAYCONIA); public static final Block clayconiaChibiFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.CLAYCONIA_CHIBI); public static final Block loonium = createSpecialFlowerBlock(BotaniaMobEffects.allure, 900, FLOWER_PROPS, () -> BotaniaFlowerBlocks.LOONIUM); public static final Block looniumFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.LOONIUM); public static final Block daffomill = createSpecialFlowerBlock(MobEffects.LEVITATION, 6, FLOWER_PROPS, () -> BotaniaFlowerBlocks.DAFFOMILL); public static final Block daffomillFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.DAFFOMILL); public static final Block vinculotus = createSpecialFlowerBlock(MobEffects.NIGHT_VISION, 900, FLOWER_PROPS, () -> BotaniaFlowerBlocks.VINCULOTUS); public static final Block vinculotusFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.VINCULOTUS); public static final Block spectranthemum = createSpecialFlowerBlock(MobEffects.INVISIBILITY, 360, FLOWER_PROPS, () -> BotaniaFlowerBlocks.SPECTRANTHEMUM); public static final Block spectranthemumFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.SPECTRANTHEMUM); public static final Block medumone = createSpecialFlowerBlock(MobEffects.MOVEMENT_SLOWDOWN, 3600, FLOWER_PROPS, () -> BotaniaFlowerBlocks.MEDUMONE); public static final Block medumoneFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.MEDUMONE); public static final Block marimorphosis = createSpecialFlowerBlock(MobEffects.DIG_SLOWDOWN, 60, FLOWER_PROPS, () -> BotaniaFlowerBlocks.MARIMORPHOSIS); public static final Block marimorphosisChibi = createSpecialFlowerBlock(MobEffects.DIG_SLOWDOWN, 60, FLOWER_PROPS, () -> BotaniaFlowerBlocks.MARIMORPHOSIS_CHIBI); public static final Block marimorphosisFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.MARIMORPHOSIS); public static final Block marimorphosisChibiFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.MARIMORPHOSIS_CHIBI); public static final Block bubbell = createSpecialFlowerBlock(MobEffects.WATER_BREATHING, 240, FLOWER_PROPS, () -> BotaniaFlowerBlocks.BUBBELL); public static final Block bubbellChibi = createSpecialFlowerBlock(MobEffects.WATER_BREATHING, 240, FLOWER_PROPS, () -> BotaniaFlowerBlocks.BUBBELL_CHIBI); public static final Block bubbellFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.BUBBELL); public static final Block bubbellChibiFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.BUBBELL_CHIBI); public static final Block solegnolia = createSpecialFlowerBlock(MobEffects.HARM, 1, FLOWER_PROPS, () -> BotaniaFlowerBlocks.SOLEGNOLIA); public static final Block solegnoliaChibi = createSpecialFlowerBlock(MobEffects.HARM, 1, FLOWER_PROPS, () -> BotaniaFlowerBlocks.SOLEGNOLIA_CHIBI); public static final Block solegnoliaFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.SOLEGNOLIA); public static final Block solegnoliaChibiFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.SOLEGNOLIA_CHIBI); public static final Block orechidIgnem = createSpecialFlowerBlock(MobEffects.FIRE_RESISTANCE, 600, FLOWER_PROPS, () -> BotaniaFlowerBlocks.ORECHID_IGNEM); public static final Block orechidIgnemFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.ORECHID_IGNEM); public static final Block labellia = createSpecialFlowerBlock(MobEffects.FIRE_RESISTANCE, 600, FLOWER_PROPS, () -> BotaniaFlowerBlocks.LABELLIA); public static final Block labelliaFloating = new FloatingSpecialFlowerBlock(FLOATING_PROPS, () -> BotaniaFlowerBlocks.LABELLIA); public static final BlockEntityType<PureDaisyBlockEntity> PURE_DAISY = XplatAbstractions.INSTANCE.createBlockEntityType(PureDaisyBlockEntity::new, pureDaisy, pureDaisyFloating); public static final BlockEntityType<ManastarBlockEntity> MANASTAR = XplatAbstractions.INSTANCE.createBlockEntityType(ManastarBlockEntity::new, manastar, manastarFloating); public static final BlockEntityType<HydroangeasBlockEntity> HYDROANGEAS = XplatAbstractions.INSTANCE.createBlockEntityType(HydroangeasBlockEntity::new, hydroangeas, hydroangeasFloating); public static final BlockEntityType<EndoflameBlockEntity> ENDOFLAME = XplatAbstractions.INSTANCE.createBlockEntityType(EndoflameBlockEntity::new, endoflame, endoflameFloating); public static final BlockEntityType<ThermalilyBlockEntity> THERMALILY = XplatAbstractions.INSTANCE.createBlockEntityType(ThermalilyBlockEntity::new, thermalily, thermalilyFloating); public static final BlockEntityType<RosaArcanaBlockEntity> ROSA_ARCANA = XplatAbstractions.INSTANCE.createBlockEntityType(RosaArcanaBlockEntity::new, rosaArcana, rosaArcanaFloating); public static final BlockEntityType<MunchdewBlockEntity> MUNCHDEW = XplatAbstractions.INSTANCE.createBlockEntityType(MunchdewBlockEntity::new, munchdew, munchdewFloating); public static final BlockEntityType<EntropinnyumBlockEntity> ENTROPINNYUM = XplatAbstractions.INSTANCE.createBlockEntityType(EntropinnyumBlockEntity::new, entropinnyum, entropinnyumFloating); public static final BlockEntityType<KekimurusBlockEntity> KEKIMURUS = XplatAbstractions.INSTANCE.createBlockEntityType(KekimurusBlockEntity::new, kekimurus, kekimurusFloating); public static final BlockEntityType<GourmaryllisBlockEntity> GOURMARYLLIS = XplatAbstractions.INSTANCE.createBlockEntityType(GourmaryllisBlockEntity::new, gourmaryllis, gourmaryllisFloating); public static final BlockEntityType<NarslimmusBlockEntity> NARSLIMMUS = XplatAbstractions.INSTANCE.createBlockEntityType(NarslimmusBlockEntity::new, narslimmus, narslimmusFloating); public static final BlockEntityType<SpectrolusBlockEntity> SPECTROLUS = XplatAbstractions.INSTANCE.createBlockEntityType(SpectrolusBlockEntity::new, spectrolus, spectrolusFloating); public static final BlockEntityType<DandelifeonBlockEntity> DANDELIFEON = XplatAbstractions.INSTANCE.createBlockEntityType(DandelifeonBlockEntity::new, dandelifeon, dandelifeonFloating); public static final BlockEntityType<RafflowsiaBlockEntity> RAFFLOWSIA = XplatAbstractions.INSTANCE.createBlockEntityType(RafflowsiaBlockEntity::new, rafflowsia, rafflowsiaFloating); public static final BlockEntityType<ShulkMeNotBlockEntity> SHULK_ME_NOT = XplatAbstractions.INSTANCE.createBlockEntityType(ShulkMeNotBlockEntity::new, shulkMeNot, shulkMeNotFloating); public static final BlockEntityType<BellethornBlockEntity> BELLETHORNE = XplatAbstractions.INSTANCE.createBlockEntityType(BellethornBlockEntity::new, bellethorn, bellethornFloating); public static final BlockEntityType<BellethornBlockEntity.Mini> BELLETHORNE_CHIBI = XplatAbstractions.INSTANCE.createBlockEntityType(BellethornBlockEntity.Mini::new, bellethornChibi, bellethornChibiFloating); public static final BlockEntityType<BergamuteBlockEntity> BERGAMUTE = XplatAbstractions.INSTANCE.createBlockEntityType(BergamuteBlockEntity::new, bergamute, bergamuteFloating); public static final BlockEntityType<DreadthornBlockEntity> DREADTHORN = XplatAbstractions.INSTANCE.createBlockEntityType(DreadthornBlockEntity::new, dreadthorn, dreadthornFloating); public static final BlockEntityType<HeiseiDreamBlockEntity> HEISEI_DREAM = XplatAbstractions.INSTANCE.createBlockEntityType(HeiseiDreamBlockEntity::new, heiseiDream, heiseiDreamFloating); public static final BlockEntityType<TigerseyeBlockEntity> TIGERSEYE = XplatAbstractions.INSTANCE.createBlockEntityType(TigerseyeBlockEntity::new, tigerseye, tigerseyeFloating); public static final BlockEntityType<JadedAmaranthusBlockEntity> JADED_AMARANTHUS = XplatAbstractions.INSTANCE.createBlockEntityType(JadedAmaranthusBlockEntity::new, jadedAmaranthus, jadedAmaranthusFloating); public static final BlockEntityType<OrechidBlockEntity> ORECHID = XplatAbstractions.INSTANCE.createBlockEntityType(OrechidBlockEntity::new, orechid, orechidFloating); public static final BlockEntityType<FallenKanadeBlockEntity> FALLEN_KANADE = XplatAbstractions.INSTANCE.createBlockEntityType(FallenKanadeBlockEntity::new, fallenKanade, fallenKanadeFloating); public static final BlockEntityType<ExoflameBlockEntity> EXOFLAME = XplatAbstractions.INSTANCE.createBlockEntityType(ExoflameBlockEntity::new, exoflame, exoflameFloating); public static final BlockEntityType<AgricarnationBlockEntity> AGRICARNATION = XplatAbstractions.INSTANCE.createBlockEntityType(AgricarnationBlockEntity::new, agricarnation, agricarnationFloating); public static final BlockEntityType<AgricarnationBlockEntity.Mini> AGRICARNATION_CHIBI = XplatAbstractions.INSTANCE.createBlockEntityType(AgricarnationBlockEntity.Mini::new, agricarnationChibi, agricarnationChibiFloating); public static final BlockEntityType<HopperhockBlockEntity> HOPPERHOCK = XplatAbstractions.INSTANCE.createBlockEntityType(HopperhockBlockEntity::new, hopperhock, hopperhockFloating); public static final BlockEntityType<HopperhockBlockEntity.Mini> HOPPERHOCK_CHIBI = XplatAbstractions.INSTANCE.createBlockEntityType(HopperhockBlockEntity.Mini::new, hopperhockChibi, hopperhockChibiFloating); public static final BlockEntityType<TangleberrieBlockEntity> TANGLEBERRIE = XplatAbstractions.INSTANCE.createBlockEntityType(TangleberrieBlockEntity::new, tangleberrie, tangleberrieFloating); public static final BlockEntityType<TangleberrieBlockEntity.Mini> TANGLEBERRIE_CHIBI = XplatAbstractions.INSTANCE.createBlockEntityType(TangleberrieBlockEntity.Mini::new, tangleberrieChibi, tangleberrieChibiFloating); public static final BlockEntityType<JiyuuliaBlockEntity> JIYUULIA = XplatAbstractions.INSTANCE.createBlockEntityType(JiyuuliaBlockEntity::new, jiyuulia, jiyuuliaFloating); public static final BlockEntityType<JiyuuliaBlockEntity.Mini> JIYUULIA_CHIBI = XplatAbstractions.INSTANCE.createBlockEntityType(JiyuuliaBlockEntity.Mini::new, jiyuuliaChibi, jiyuuliaChibiFloating); public static final BlockEntityType<RannuncarpusBlockEntity> RANNUNCARPUS = XplatAbstractions.INSTANCE.createBlockEntityType(RannuncarpusBlockEntity::new, rannuncarpus, rannuncarpusFloating); public static final BlockEntityType<RannuncarpusBlockEntity.Mini> RANNUNCARPUS_CHIBI = XplatAbstractions.INSTANCE.createBlockEntityType(RannuncarpusBlockEntity.Mini::new, rannuncarpusChibi, rannuncarpusChibiFloating); public static final BlockEntityType<HyacidusBlockEntity> HYACIDUS = XplatAbstractions.INSTANCE.createBlockEntityType(HyacidusBlockEntity::new, hyacidus, hyacidusFloating); public static final BlockEntityType<LabelliaBlockEntity> LABELLIA = XplatAbstractions.INSTANCE.createBlockEntityType(LabelliaBlockEntity::new, labellia, labelliaFloating); public static final BlockEntityType<PollidisiacBlockEntity> POLLIDISIAC = XplatAbstractions.INSTANCE.createBlockEntityType(PollidisiacBlockEntity::new, pollidisiac, pollidisiacFloating); public static final BlockEntityType<ClayconiaBlockEntity> CLAYCONIA = XplatAbstractions.INSTANCE.createBlockEntityType(ClayconiaBlockEntity::new, clayconia, clayconiaFloating); public static final BlockEntityType<ClayconiaBlockEntity.Mini> CLAYCONIA_CHIBI = XplatAbstractions.INSTANCE.createBlockEntityType(ClayconiaBlockEntity.Mini::new, clayconiaChibi, clayconiaChibiFloating); public static final BlockEntityType<LooniumBlockEntity> LOONIUM = XplatAbstractions.INSTANCE.createBlockEntityType(LooniumBlockEntity::new, loonium, looniumFloating); public static final BlockEntityType<DaffomillBlockEntity> DAFFOMILL = XplatAbstractions.INSTANCE.createBlockEntityType(DaffomillBlockEntity::new, daffomill, daffomillFloating); public static final BlockEntityType<VinculotusBlockEntity> VINCULOTUS = XplatAbstractions.INSTANCE.createBlockEntityType(VinculotusBlockEntity::new, vinculotus, vinculotusFloating); public static final BlockEntityType<SpectranthemumBlockEntity> SPECTRANTHEMUM = XplatAbstractions.INSTANCE.createBlockEntityType(SpectranthemumBlockEntity::new, spectranthemum, spectranthemumFloating); public static final BlockEntityType<MedumoneBlockEntity> MEDUMONE = XplatAbstractions.INSTANCE.createBlockEntityType(MedumoneBlockEntity::new, medumone, medumoneFloating); public static final BlockEntityType<MarimorphosisBlockEntity> MARIMORPHOSIS = XplatAbstractions.INSTANCE.createBlockEntityType(MarimorphosisBlockEntity::new, marimorphosis, marimorphosisFloating); public static final BlockEntityType<MarimorphosisBlockEntity.Mini> MARIMORPHOSIS_CHIBI = XplatAbstractions.INSTANCE.createBlockEntityType(MarimorphosisBlockEntity.Mini::new, marimorphosisChibi, marimorphosisChibiFloating); public static final BlockEntityType<BubbellBlockEntity> BUBBELL = XplatAbstractions.INSTANCE.createBlockEntityType(BubbellBlockEntity::new, bubbell, bubbellFloating); public static final BlockEntityType<BubbellBlockEntity.Mini> BUBBELL_CHIBI = XplatAbstractions.INSTANCE.createBlockEntityType(BubbellBlockEntity.Mini::new, bubbellChibi, bubbellChibiFloating); public static final BlockEntityType<SolegnoliaBlockEntity> SOLEGNOLIA = XplatAbstractions.INSTANCE.createBlockEntityType(SolegnoliaBlockEntity::new, solegnolia, solegnoliaFloating); public static final BlockEntityType<SolegnoliaBlockEntity.Mini> SOLEGNOLIA_CHIBI = XplatAbstractions.INSTANCE.createBlockEntityType(SolegnoliaBlockEntity.Mini::new, solegnoliaChibi, solegnoliaChibiFloating); public static final BlockEntityType<OrechidIgnemBlockEntity> ORECHID_IGNEM = XplatAbstractions.INSTANCE.createBlockEntityType(OrechidIgnemBlockEntity::new, orechidIgnem, orechidIgnemFloating); private static ResourceLocation floating(ResourceLocation orig) { return new ResourceLocation(orig.getNamespace(), "floating_" + orig.getPath()); } private static ResourceLocation chibi(ResourceLocation orig) { return new ResourceLocation(orig.getNamespace(), orig.getPath() + "_chibi"); } private static ResourceLocation getId(Block b) { return BuiltInRegistries.BLOCK.getKey(b); } private static FlowerBlock createSpecialFlowerBlock( MobEffect effect, int effectDuration, BlockBehaviour.Properties props, Supplier<BlockEntityType<? extends SpecialFlowerBlockEntity>> beType) { return XplatAbstractions.INSTANCE.createSpecialFlowerBlock( effect, effectDuration, props, beType ); } public static void registerBlocks(BiConsumer<Block, ResourceLocation> r) { r.accept(pureDaisy, LibBlockNames.SUBTILE_PUREDAISY); r.accept(pureDaisyFloating, floating(LibBlockNames.SUBTILE_PUREDAISY)); r.accept(manastar, LibBlockNames.SUBTILE_MANASTAR); r.accept(manastarFloating, floating(LibBlockNames.SUBTILE_MANASTAR)); r.accept(hydroangeas, LibBlockNames.SUBTILE_HYDROANGEAS); r.accept(hydroangeasFloating, floating(LibBlockNames.SUBTILE_HYDROANGEAS)); r.accept(endoflame, LibBlockNames.SUBTILE_ENDOFLAME); r.accept(endoflameFloating, floating(LibBlockNames.SUBTILE_ENDOFLAME)); r.accept(thermalily, LibBlockNames.SUBTILE_THERMALILY); r.accept(thermalilyFloating, floating(LibBlockNames.SUBTILE_THERMALILY)); r.accept(rosaArcana, LibBlockNames.SUBTILE_ARCANE_ROSE); r.accept(rosaArcanaFloating, floating(LibBlockNames.SUBTILE_ARCANE_ROSE)); r.accept(munchdew, LibBlockNames.SUBTILE_MUNCHDEW); r.accept(munchdewFloating, floating(LibBlockNames.SUBTILE_MUNCHDEW)); r.accept(entropinnyum, LibBlockNames.SUBTILE_ENTROPINNYUM); r.accept(entropinnyumFloating, floating(LibBlockNames.SUBTILE_ENTROPINNYUM)); r.accept(kekimurus, LibBlockNames.SUBTILE_KEKIMURUS); r.accept(kekimurusFloating, floating(LibBlockNames.SUBTILE_KEKIMURUS)); r.accept(gourmaryllis, LibBlockNames.SUBTILE_GOURMARYLLIS); r.accept(gourmaryllisFloating, floating(LibBlockNames.SUBTILE_GOURMARYLLIS)); r.accept(narslimmus, LibBlockNames.SUBTILE_NARSLIMMUS); r.accept(narslimmusFloating, floating(LibBlockNames.SUBTILE_NARSLIMMUS)); r.accept(spectrolus, LibBlockNames.SUBTILE_SPECTROLUS); r.accept(spectrolusFloating, floating(LibBlockNames.SUBTILE_SPECTROLUS)); r.accept(dandelifeon, LibBlockNames.SUBTILE_DANDELIFEON); r.accept(dandelifeonFloating, floating(LibBlockNames.SUBTILE_DANDELIFEON)); r.accept(rafflowsia, LibBlockNames.SUBTILE_RAFFLOWSIA); r.accept(rafflowsiaFloating, floating(LibBlockNames.SUBTILE_RAFFLOWSIA)); r.accept(shulkMeNot, LibBlockNames.SUBTILE_SHULK_ME_NOT); r.accept(shulkMeNotFloating, floating(LibBlockNames.SUBTILE_SHULK_ME_NOT)); r.accept(bellethorn, LibBlockNames.SUBTILE_BELLETHORN); r.accept(bellethornChibi, chibi(LibBlockNames.SUBTILE_BELLETHORN)); r.accept(bellethornFloating, floating(LibBlockNames.SUBTILE_BELLETHORN)); r.accept(bellethornChibiFloating, chibi(floating(LibBlockNames.SUBTILE_BELLETHORN))); r.accept(bergamute, LibBlockNames.SUBTILE_BERGAMUTE); r.accept(bergamuteFloating, floating(LibBlockNames.SUBTILE_BERGAMUTE)); r.accept(dreadthorn, LibBlockNames.SUBTILE_DREADTHORN); r.accept(dreadthornFloating, floating(LibBlockNames.SUBTILE_DREADTHORN)); r.accept(heiseiDream, LibBlockNames.SUBTILE_HEISEI_DREAM); r.accept(heiseiDreamFloating, floating(LibBlockNames.SUBTILE_HEISEI_DREAM)); r.accept(tigerseye, LibBlockNames.SUBTILE_TIGERSEYE); r.accept(tigerseyeFloating, floating(LibBlockNames.SUBTILE_TIGERSEYE)); r.accept(jadedAmaranthus, LibBlockNames.SUBTILE_JADED_AMARANTHUS); r.accept(jadedAmaranthusFloating, floating(LibBlockNames.SUBTILE_JADED_AMARANTHUS)); r.accept(orechid, LibBlockNames.SUBTILE_ORECHID); r.accept(orechidFloating, floating(LibBlockNames.SUBTILE_ORECHID)); r.accept(fallenKanade, LibBlockNames.SUBTILE_FALLEN_KANADE); r.accept(fallenKanadeFloating, floating(LibBlockNames.SUBTILE_FALLEN_KANADE)); r.accept(exoflame, LibBlockNames.SUBTILE_EXOFLAME); r.accept(exoflameFloating, floating(LibBlockNames.SUBTILE_EXOFLAME)); r.accept(agricarnation, LibBlockNames.SUBTILE_AGRICARNATION); r.accept(agricarnationChibi, chibi(LibBlockNames.SUBTILE_AGRICARNATION)); r.accept(agricarnationFloating, floating(LibBlockNames.SUBTILE_AGRICARNATION)); r.accept(agricarnationChibiFloating, chibi(floating(LibBlockNames.SUBTILE_AGRICARNATION))); r.accept(hopperhock, LibBlockNames.SUBTILE_HOPPERHOCK); r.accept(hopperhockChibi, chibi(LibBlockNames.SUBTILE_HOPPERHOCK)); r.accept(hopperhockFloating, floating(LibBlockNames.SUBTILE_HOPPERHOCK)); r.accept(hopperhockChibiFloating, chibi(floating(LibBlockNames.SUBTILE_HOPPERHOCK))); r.accept(tangleberrie, LibBlockNames.SUBTILE_TANGLEBERRIE); r.accept(tangleberrieChibi, chibi(LibBlockNames.SUBTILE_TANGLEBERRIE)); r.accept(tangleberrieFloating, floating(LibBlockNames.SUBTILE_TANGLEBERRIE)); r.accept(tangleberrieChibiFloating, chibi(floating(LibBlockNames.SUBTILE_TANGLEBERRIE))); r.accept(jiyuulia, LibBlockNames.SUBTILE_JIYUULIA); r.accept(jiyuuliaChibi, chibi(LibBlockNames.SUBTILE_JIYUULIA)); r.accept(jiyuuliaFloating, floating(LibBlockNames.SUBTILE_JIYUULIA)); r.accept(jiyuuliaChibiFloating, chibi(floating(LibBlockNames.SUBTILE_JIYUULIA))); r.accept(rannuncarpus, LibBlockNames.SUBTILE_RANNUNCARPUS); r.accept(rannuncarpusChibi, chibi(LibBlockNames.SUBTILE_RANNUNCARPUS)); r.accept(rannuncarpusFloating, floating(LibBlockNames.SUBTILE_RANNUNCARPUS)); r.accept(rannuncarpusChibiFloating, chibi(floating(LibBlockNames.SUBTILE_RANNUNCARPUS))); r.accept(hyacidus, LibBlockNames.SUBTILE_HYACIDUS); r.accept(hyacidusFloating, floating(LibBlockNames.SUBTILE_HYACIDUS)); r.accept(pollidisiac, LibBlockNames.SUBTILE_POLLIDISIAC); r.accept(pollidisiacFloating, floating(LibBlockNames.SUBTILE_POLLIDISIAC)); r.accept(clayconia, LibBlockNames.SUBTILE_CLAYCONIA); r.accept(clayconiaChibi, chibi(LibBlockNames.SUBTILE_CLAYCONIA)); r.accept(clayconiaFloating, floating(LibBlockNames.SUBTILE_CLAYCONIA)); r.accept(clayconiaChibiFloating, chibi(floating(LibBlockNames.SUBTILE_CLAYCONIA))); r.accept(loonium, LibBlockNames.SUBTILE_LOONIUM); r.accept(looniumFloating, floating(LibBlockNames.SUBTILE_LOONIUM)); r.accept(daffomill, LibBlockNames.SUBTILE_DAFFOMILL); r.accept(daffomillFloating, floating(LibBlockNames.SUBTILE_DAFFOMILL)); r.accept(vinculotus, LibBlockNames.SUBTILE_VINCULOTUS); r.accept(vinculotusFloating, floating(LibBlockNames.SUBTILE_VINCULOTUS)); r.accept(spectranthemum, LibBlockNames.SUBTILE_SPECTRANTHEMUM); r.accept(spectranthemumFloating, floating(LibBlockNames.SUBTILE_SPECTRANTHEMUM)); r.accept(medumone, LibBlockNames.SUBTILE_MEDUMONE); r.accept(medumoneFloating, floating(LibBlockNames.SUBTILE_MEDUMONE)); r.accept(marimorphosis, LibBlockNames.SUBTILE_MARIMORPHOSIS); r.accept(marimorphosisChibi, chibi(LibBlockNames.SUBTILE_MARIMORPHOSIS)); r.accept(marimorphosisFloating, floating(LibBlockNames.SUBTILE_MARIMORPHOSIS)); r.accept(marimorphosisChibiFloating, chibi(floating(LibBlockNames.SUBTILE_MARIMORPHOSIS))); r.accept(bubbell, LibBlockNames.SUBTILE_BUBBELL); r.accept(bubbellChibi, chibi(LibBlockNames.SUBTILE_BUBBELL)); r.accept(bubbellFloating, floating(LibBlockNames.SUBTILE_BUBBELL)); r.accept(bubbellChibiFloating, chibi(floating(LibBlockNames.SUBTILE_BUBBELL))); r.accept(solegnolia, LibBlockNames.SUBTILE_SOLEGNOLIA); r.accept(solegnoliaChibi, chibi(LibBlockNames.SUBTILE_SOLEGNOLIA)); r.accept(solegnoliaFloating, floating(LibBlockNames.SUBTILE_SOLEGNOLIA)); r.accept(solegnoliaChibiFloating, chibi(floating(LibBlockNames.SUBTILE_SOLEGNOLIA))); r.accept(orechidIgnem, LibBlockNames.SUBTILE_ORECHID_IGNEM); r.accept(orechidIgnemFloating, floating(LibBlockNames.SUBTILE_ORECHID_IGNEM)); r.accept(labellia, LibBlockNames.SUBTILE_LABELLIA); r.accept(labelliaFloating, floating(LibBlockNames.SUBTILE_LABELLIA)); } public static void registerItemBlocks(BiConsumer<Item, ResourceLocation> r) { Item.Properties props = BotaniaItems.defaultBuilder(); r.accept(new SpecialFlowerBlockItem(pureDaisy, props), getId(pureDaisy)); r.accept(new SpecialFlowerBlockItem(pureDaisyFloating, props), getId(pureDaisyFloating)); r.accept(new SpecialFlowerBlockItem(manastar, props), getId(manastar)); r.accept(new SpecialFlowerBlockItem(manastarFloating, props), getId(manastarFloating)); r.accept(new SpecialFlowerBlockItem(hydroangeas, props), getId(hydroangeas)); r.accept(new SpecialFlowerBlockItem(hydroangeasFloating, props), getId(hydroangeasFloating)); r.accept(new SpecialFlowerBlockItem(endoflame, props), getId(endoflame)); r.accept(new SpecialFlowerBlockItem(endoflameFloating, props), getId(endoflameFloating)); r.accept(new SpecialFlowerBlockItem(thermalily, props), getId(thermalily)); r.accept(new SpecialFlowerBlockItem(thermalilyFloating, props), getId(thermalilyFloating)); r.accept(new SpecialFlowerBlockItem(rosaArcana, props), getId(rosaArcana)); r.accept(new SpecialFlowerBlockItem(rosaArcanaFloating, props), getId(rosaArcanaFloating)); r.accept(new SpecialFlowerBlockItem(munchdew, props), getId(munchdew)); r.accept(new SpecialFlowerBlockItem(munchdewFloating, props), getId(munchdewFloating)); r.accept(new SpecialFlowerBlockItem(entropinnyum, props), getId(entropinnyum)); r.accept(new SpecialFlowerBlockItem(entropinnyumFloating, props), getId(entropinnyumFloating)); r.accept(new SpecialFlowerBlockItem(kekimurus, props), getId(kekimurus)); r.accept(new SpecialFlowerBlockItem(kekimurusFloating, props), getId(kekimurusFloating)); r.accept(new SpecialFlowerBlockItem(gourmaryllis, props), getId(gourmaryllis)); r.accept(new SpecialFlowerBlockItem(gourmaryllisFloating, props), getId(gourmaryllisFloating)); r.accept(new SpecialFlowerBlockItem(narslimmus, props), getId(narslimmus)); r.accept(new SpecialFlowerBlockItem(narslimmusFloating, props), getId(narslimmusFloating)); r.accept(new SpecialFlowerBlockItem(spectrolus, props), getId(spectrolus)); r.accept(new SpecialFlowerBlockItem(spectrolusFloating, props), getId(spectrolusFloating)); r.accept(new SpecialFlowerBlockItem(dandelifeon, props), getId(dandelifeon)); r.accept(new SpecialFlowerBlockItem(dandelifeonFloating, props), getId(dandelifeonFloating)); r.accept(new SpecialFlowerBlockItem(rafflowsia, props), getId(rafflowsia)); r.accept(new SpecialFlowerBlockItem(rafflowsiaFloating, props), getId(rafflowsiaFloating)); r.accept(new SpecialFlowerBlockItem(shulkMeNot, props), getId(shulkMeNot)); r.accept(new SpecialFlowerBlockItem(shulkMeNotFloating, props), getId(shulkMeNotFloating)); r.accept(new SpecialFlowerBlockItem(bellethorn, props), getId(bellethorn)); r.accept(new SpecialFlowerBlockItem(bellethornChibi, props), getId(bellethornChibi)); r.accept(new SpecialFlowerBlockItem(bellethornFloating, props), getId(bellethornFloating)); r.accept(new SpecialFlowerBlockItem(bellethornChibiFloating, props), getId(bellethornChibiFloating)); r.accept(new SpecialFlowerBlockItem(bergamute, props), getId(bergamute)); r.accept(new SpecialFlowerBlockItem(bergamuteFloating, props), getId(bergamuteFloating)); r.accept(new SpecialFlowerBlockItem(dreadthorn, props), getId(dreadthorn)); r.accept(new SpecialFlowerBlockItem(dreadthornFloating, props), getId(dreadthornFloating)); r.accept(new SpecialFlowerBlockItem(heiseiDream, props), getId(heiseiDream)); r.accept(new SpecialFlowerBlockItem(heiseiDreamFloating, props), getId(heiseiDreamFloating)); r.accept(new SpecialFlowerBlockItem(tigerseye, props), getId(tigerseye)); r.accept(new SpecialFlowerBlockItem(tigerseyeFloating, props), getId(tigerseyeFloating)); r.accept(new SpecialFlowerBlockItem(jadedAmaranthus, props), getId(jadedAmaranthus)); r.accept(new SpecialFlowerBlockItem(jadedAmaranthusFloating, props), getId(jadedAmaranthusFloating)); r.accept(new SpecialFlowerBlockItem(orechid, props), getId(orechid)); r.accept(new SpecialFlowerBlockItem(orechidFloating, props), getId(orechidFloating)); r.accept(new SpecialFlowerBlockItem(fallenKanade, props), getId(fallenKanade)); r.accept(new SpecialFlowerBlockItem(fallenKanadeFloating, props), getId(fallenKanadeFloating)); r.accept(new SpecialFlowerBlockItem(exoflame, props), getId(exoflame)); r.accept(new SpecialFlowerBlockItem(exoflameFloating, props), getId(exoflameFloating)); r.accept(new SpecialFlowerBlockItem(agricarnation, props), getId(agricarnation)); r.accept(new SpecialFlowerBlockItem(agricarnationChibi, props), getId(agricarnationChibi)); r.accept(new SpecialFlowerBlockItem(agricarnationFloating, props), getId(agricarnationFloating)); r.accept(new SpecialFlowerBlockItem(agricarnationChibiFloating, props), getId(agricarnationChibiFloating)); r.accept(new SpecialFlowerBlockItem(hopperhock, props), getId(hopperhock)); r.accept(new SpecialFlowerBlockItem(hopperhockChibi, props), getId(hopperhockChibi)); r.accept(new SpecialFlowerBlockItem(hopperhockFloating, props), getId(hopperhockFloating)); r.accept(new SpecialFlowerBlockItem(hopperhockChibiFloating, props), getId(hopperhockChibiFloating)); r.accept(new SpecialFlowerBlockItem(tangleberrie, props), getId(tangleberrie)); r.accept(new SpecialFlowerBlockItem(tangleberrieChibi, props), getId(tangleberrieChibi)); r.accept(new SpecialFlowerBlockItem(tangleberrieFloating, props), getId(tangleberrieFloating)); r.accept(new SpecialFlowerBlockItem(tangleberrieChibiFloating, props), getId(tangleberrieChibiFloating)); r.accept(new SpecialFlowerBlockItem(jiyuulia, props), getId(jiyuulia)); r.accept(new SpecialFlowerBlockItem(jiyuuliaChibi, props), getId(jiyuuliaChibi)); r.accept(new SpecialFlowerBlockItem(jiyuuliaFloating, props), getId(jiyuuliaFloating)); r.accept(new SpecialFlowerBlockItem(jiyuuliaChibiFloating, props), getId(jiyuuliaChibiFloating)); r.accept(new SpecialFlowerBlockItem(rannuncarpus, props), getId(rannuncarpus)); r.accept(new SpecialFlowerBlockItem(rannuncarpusChibi, props), getId(rannuncarpusChibi)); r.accept(new SpecialFlowerBlockItem(rannuncarpusFloating, props), getId(rannuncarpusFloating)); r.accept(new SpecialFlowerBlockItem(rannuncarpusChibiFloating, props), getId(rannuncarpusChibiFloating)); r.accept(new SpecialFlowerBlockItem(hyacidus, props), getId(hyacidus)); r.accept(new SpecialFlowerBlockItem(hyacidusFloating, props), getId(hyacidusFloating)); r.accept(new SpecialFlowerBlockItem(pollidisiac, props), getId(pollidisiac)); r.accept(new SpecialFlowerBlockItem(pollidisiacFloating, props), getId(pollidisiacFloating)); r.accept(new SpecialFlowerBlockItem(clayconia, props), getId(clayconia)); r.accept(new SpecialFlowerBlockItem(clayconiaChibi, props), getId(clayconiaChibi)); r.accept(new SpecialFlowerBlockItem(clayconiaFloating, props), getId(clayconiaFloating)); r.accept(new SpecialFlowerBlockItem(clayconiaChibiFloating, props), getId(clayconiaChibiFloating)); r.accept(new SpecialFlowerBlockItem(loonium, props), getId(loonium)); r.accept(new SpecialFlowerBlockItem(looniumFloating, props), getId(looniumFloating)); r.accept(new SpecialFlowerBlockItem(daffomill, props), getId(daffomill)); r.accept(new SpecialFlowerBlockItem(daffomillFloating, props), getId(daffomillFloating)); r.accept(new SpecialFlowerBlockItem(vinculotus, props), getId(vinculotus)); r.accept(new SpecialFlowerBlockItem(vinculotusFloating, props), getId(vinculotusFloating)); r.accept(new SpecialFlowerBlockItem(spectranthemum, props), getId(spectranthemum)); r.accept(new SpecialFlowerBlockItem(spectranthemumFloating, props), getId(spectranthemumFloating)); r.accept(new SpecialFlowerBlockItem(medumone, props), getId(medumone)); r.accept(new SpecialFlowerBlockItem(medumoneFloating, props), getId(medumoneFloating)); r.accept(new SpecialFlowerBlockItem(marimorphosis, props), getId(marimorphosis)); r.accept(new SpecialFlowerBlockItem(marimorphosisChibi, props), getId(marimorphosisChibi)); r.accept(new SpecialFlowerBlockItem(marimorphosisFloating, props), getId(marimorphosisFloating)); r.accept(new SpecialFlowerBlockItem(marimorphosisChibiFloating, props), getId(marimorphosisChibiFloating)); r.accept(new SpecialFlowerBlockItem(bubbell, props), getId(bubbell)); r.accept(new SpecialFlowerBlockItem(bubbellChibi, props), getId(bubbellChibi)); r.accept(new SpecialFlowerBlockItem(bubbellFloating, props), getId(bubbellFloating)); r.accept(new SpecialFlowerBlockItem(bubbellChibiFloating, props), getId(bubbellChibiFloating)); r.accept(new SpecialFlowerBlockItem(solegnolia, props), getId(solegnolia)); r.accept(new SpecialFlowerBlockItem(solegnoliaChibi, props), getId(solegnoliaChibi)); r.accept(new SpecialFlowerBlockItem(solegnoliaFloating, props), getId(solegnoliaFloating)); r.accept(new SpecialFlowerBlockItem(solegnoliaChibiFloating, props), getId(solegnoliaChibiFloating)); r.accept(new SpecialFlowerBlockItem(orechidIgnem, props), getId(orechidIgnem)); r.accept(new SpecialFlowerBlockItem(orechidIgnemFloating, props), getId(orechidIgnemFloating)); r.accept(new SpecialFlowerBlockItem(labellia, props), getId(labellia)); r.accept(new SpecialFlowerBlockItem(labelliaFloating, props), getId(labelliaFloating)); } public static void registerTEs(BiConsumer<BlockEntityType<?>, ResourceLocation> r) { r.accept(PURE_DAISY, getId(pureDaisy)); r.accept(MANASTAR, getId(manastar)); r.accept(HYDROANGEAS, getId(hydroangeas)); r.accept(ENDOFLAME, getId(endoflame)); r.accept(THERMALILY, getId(thermalily)); r.accept(ROSA_ARCANA, getId(rosaArcana)); r.accept(MUNCHDEW, getId(munchdew)); r.accept(ENTROPINNYUM, getId(entropinnyum)); r.accept(KEKIMURUS, getId(kekimurus)); r.accept(GOURMARYLLIS, getId(gourmaryllis)); r.accept(NARSLIMMUS, getId(narslimmus)); r.accept(SPECTROLUS, getId(spectrolus)); r.accept(DANDELIFEON, getId(dandelifeon)); r.accept(RAFFLOWSIA, getId(rafflowsia)); r.accept(SHULK_ME_NOT, getId(shulkMeNot)); r.accept(BELLETHORNE, getId(bellethorn)); r.accept(BELLETHORNE_CHIBI, getId(bellethornChibi)); r.accept(BERGAMUTE, getId(bergamute)); r.accept(DREADTHORN, getId(dreadthorn)); r.accept(HEISEI_DREAM, getId(heiseiDream)); r.accept(TIGERSEYE, getId(tigerseye)); r.accept(JADED_AMARANTHUS, getId(jadedAmaranthus)); r.accept(ORECHID, getId(orechid)); r.accept(FALLEN_KANADE, getId(fallenKanade)); r.accept(EXOFLAME, getId(exoflame)); r.accept(AGRICARNATION, getId(agricarnation)); r.accept(AGRICARNATION_CHIBI, getId(agricarnationChibi)); r.accept(HOPPERHOCK, getId(hopperhock)); r.accept(HOPPERHOCK_CHIBI, getId(hopperhockChibi)); r.accept(TANGLEBERRIE, getId(tangleberrie)); r.accept(TANGLEBERRIE_CHIBI, getId(tangleberrieChibi)); r.accept(JIYUULIA, getId(jiyuulia)); r.accept(JIYUULIA_CHIBI, getId(jiyuuliaChibi)); r.accept(RANNUNCARPUS, getId(rannuncarpus)); r.accept(RANNUNCARPUS_CHIBI, getId(rannuncarpusChibi)); r.accept(HYACIDUS, getId(hyacidus)); r.accept(POLLIDISIAC, getId(pollidisiac)); r.accept(CLAYCONIA, getId(clayconia)); r.accept(CLAYCONIA_CHIBI, getId(clayconiaChibi)); r.accept(LOONIUM, getId(loonium)); r.accept(DAFFOMILL, getId(daffomill)); r.accept(VINCULOTUS, getId(vinculotus)); r.accept(SPECTRANTHEMUM, getId(spectranthemum)); r.accept(MEDUMONE, getId(medumone)); r.accept(MARIMORPHOSIS, getId(marimorphosis)); r.accept(MARIMORPHOSIS_CHIBI, getId(marimorphosisChibi)); r.accept(BUBBELL, getId(bubbell)); r.accept(BUBBELL_CHIBI, getId(bubbellChibi)); r.accept(SOLEGNOLIA, getId(solegnolia)); r.accept(SOLEGNOLIA_CHIBI, getId(solegnoliaChibi)); r.accept(ORECHID_IGNEM, getId(orechidIgnem)); r.accept(LABELLIA, getId(labellia)); } public static void registerWandHudCaps(BotaniaBlockEntities.BECapConsumer<WandHUD> consumer) { consumer.accept(be -> new SpectrolusBlockEntity.WandHud((SpectrolusBlockEntity) be), SPECTROLUS); consumer.accept(be -> new BindableSpecialFlowerBlockEntity.BindableFlowerWandHud<>((GeneratingFlowerBlockEntity) be), HYDROANGEAS, ENDOFLAME, THERMALILY, ROSA_ARCANA, MUNCHDEW, ENTROPINNYUM, KEKIMURUS, GOURMARYLLIS, NARSLIMMUS, DANDELIFEON, RAFFLOWSIA, SHULK_ME_NOT); consumer.accept(be -> new HopperhockBlockEntity.WandHud((HopperhockBlockEntity) be), HOPPERHOCK, HOPPERHOCK_CHIBI); consumer.accept(be -> new RannuncarpusBlockEntity.WandHud((RannuncarpusBlockEntity) be), RANNUNCARPUS, RANNUNCARPUS_CHIBI); consumer.accept(be -> new BindableSpecialFlowerBlockEntity.BindableFlowerWandHud<>((FunctionalFlowerBlockEntity) be), BELLETHORNE, BELLETHORNE_CHIBI, DREADTHORN, HEISEI_DREAM, TIGERSEYE, JADED_AMARANTHUS, ORECHID, FALLEN_KANADE, EXOFLAME, AGRICARNATION, AGRICARNATION_CHIBI, TANGLEBERRIE, TANGLEBERRIE_CHIBI, JIYUULIA, JIYUULIA_CHIBI, HYACIDUS, POLLIDISIAC, CLAYCONIA, CLAYCONIA_CHIBI, LOONIUM, DAFFOMILL, VINCULOTUS, SPECTRANTHEMUM, MEDUMONE, MARIMORPHOSIS, MARIMORPHOSIS_CHIBI, BUBBELL, BUBBELL_CHIBI, SOLEGNOLIA, SOLEGNOLIA_CHIBI, ORECHID_IGNEM, LABELLIA); } }
true
3e7a589ec9fc06e22eac01283ddf7b98045060d8
Java
PankhudiB/ddd-handson
/src/main/java/entities/Item.java
UTF-8
393
2.828125
3
[]
no_license
package entities; public class Item { Product product; Quantity quantity; public Item(Product product, Quantity quantity) { this.product = product; this.quantity = quantity; } @Override public String toString() { return "Item{" + "product=" + product + ", quantity=" + quantity + '}'; } }
true
012e2c8af927f0323e6986f12052f043c9ddb733
Java
avolar133/SWT
/u01/HelloLibrary.java
UTF-8
991
3.375
3
[]
no_license
/* * Lehrstuhl Softwaretechnologie, TU Dresden, Datei HelloLibrary.java * * HelloLibrary-Klasse implementiert eine Anwendung, * die die Aufnahme von Büchern simuliert */ public class HelloLibrary { // Simulation durch main() public static void main(String[] args) { // Erzeugung eines Library-Objektes Library myLibrary = new Library(); // Erzeugung von zwei Book-Objekten Book book1 = new Book("Harry Potter"); Book book2 = new Book("Charile"); // Nachricht an die Library, dass die Books aufgenommen werden sollen myLibrary.add(book1); myLibrary.add(book2); myLibrary.add(book1); myLibrary.add(book2); myLibrary.add(book1); myLibrary.add(book2); myLibrary.add(book1); myLibrary.add(book2); myLibrary.add(book1); myLibrary.add(book2); myLibrary.add(book1); myLibrary.add(book2); Book x = myLibrary.search("Harry Potter"); } }
true
19776ad3850afa382637576d7dc3f18b0494fd93
Java
athornburg/person-rest-api-example
/src/main/java/com/alex/thornburg/web/rest/repo/AddressRepository.java
UTF-8
378
1.992188
2
[ "MIT" ]
permissive
package com.alex.thornburg.web.rest.repo; import com.alex.thornburg.web.rest.model.Address; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.query.Param; /** * Created by alexthornburg on 9/3/15. */ public interface AddressRepository extends JpaRepository<Address, Long> { Address findById(@Param("id")long id); }
true
3e72428c477f42c92d8056bfaa2cc8c333f5d2f2
Java
ccutyang0569/xunwu
/src/main/java/com/founder/xunwu/service/ISmsService.java
UTF-8
572
2.125
2
[]
no_license
package com.founder.xunwu.service; /** * @program: xunwu * @description: 手机短信验证码服务 * @author: yangming * @create: 2018-03-26 18:09 **/ public interface ISmsService { /** * 向用户手机发送验证码 * @param telephone * @return */ ServiceResult<String> sendSms(String telephone); /** * 从缓存中获取验证码 * @param telephone * @return */ String getSmsCode(String telephone); /** * * @param telephone * @return */ void remove(String telephone); }
true
9f5e4db160ad9d298bf040f88e24f43538aa6902
Java
tempeste/WIA1002-Labs
/Lab4Q8/src/Q8/Music.java
UTF-8
1,545
2.703125
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 Q8; import java.nio.file.Paths; import javafx.embed.swing.JFXPanel; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; /** * * @author RAVEN */ public class Music { private String title; private String folder = "D:\\Education\\UM COURSES\\Year 1Sem 2\\Data Structure\\Labs\\Lab4Q8\\"; private String fileName; JFXPanel panel = new JFXPanel(); Media hit; static MediaPlayer mediaPlayer; public Music(String title, String fileName) { this.title = title; this.fileName = folder + fileName; hit = new Media(Paths.get(fileName).toUri().toString()); } public String getTitle() { return title; } public String getFileName() { return fileName; } public void setTitle(String title) { this.title = title; } public void setFileName(String fileName) { this.fileName = folder + fileName; hit = new Media(Paths.get(fileName).toUri().toString()); } public void play(){ mediaPlayer = new MediaPlayer(hit); mediaPlayer.play(); } public void stop(){ mediaPlayer.stop(); } public void exit(){ System.exit(0); } public String toString(){ return this.title; } }
true
d54b600fba535f98acf3b86fcee9aa6df53f16a4
Java
Flandre923/webpackStudy
/blog01/src/main/java/com/example/pojo/params/PageComment.java
UTF-8
650
1.679688
2
[]
no_license
package com.example.pojo.params; import java.util.ArrayList; import java.util.Date; import java.util.List; import lombok.Data; import lombok.NoArgsConstructor; /** * 页面评论 */ @NoArgsConstructor @Data public class PageComment { private Long id; private String nickname;//昵称 private String content;//评论内容 private String avatar;//头像(图片路径) private Date createTime;//评论时间 private String website;//个人网站 private String parentCommentId;//父评论id private String parentCommentNickname;//父评论昵称 private List<PageComment> replyComments = new ArrayList<>();//回复该评论的评论 }
true
66bb3ea5a32c58d752362a4c70c62724fdcdabee
Java
kostet802/lab2
/src/com/company/Phone.java
UTF-8
924
3.03125
3
[]
no_license
package com.company; public class Phone { private String number; private String fio; private String adres; public Phone(){ } public void setNumber(String number) { if(number.matches("^[0-9 ]*$")){ this.number = number; } else{ System.out.println("Wrong number"); } } public String getNumber(){ return number; } public void setFio(String fio){ if(fio.matches("^[a-zA-Z ]*$")){ this.fio = fio; } else{ System.out.println("Wrong fio"); } } public String getFio(){ return fio; } public void setAdres(String adres) { if(adres.matches("^[a-zA-Z0-9 ]*$")){ this.adres = adres; } else{ System.out.println("Wrong adres"); } } public String getAdres(){ return adres; } }
true
57a35826562ebcb401c75dbe17694f046b6bab57
Java
gnikkoch96/Super_The_Bird_Game
/Super Bird Game Prototype/android/src/com/procode/game/AndroidLauncher.java
UTF-8
891
1.882813
2
[]
no_license
package com.procode.game; import android.graphics.Point; import android.os.Bundle; import android.view.Display; import android.view.Window; import android.view.WindowManager; import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; import com.procode.game.SuperBirdGame; public class AndroidLauncher extends AndroidApplication { @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); Display screensize = getWindowManager().getDefaultDisplay(); Point size = new Point(); screensize.getSize(size); int width = size.x; int height = size.y; AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); //sp.ANDROID_HEIGHT = 100; //sp.setHeight(100); initialize(new SuperBirdGame(), config); //initialize(new Test()); } }
true
3dea858ac74407f71dc3549bda1138bb5c3da428
Java
xuhui-lu/Key-to-Exercises-in-LeetCode
/src/P14/src/Solution.java
UTF-8
680
3.046875
3
[]
no_license
import java.util.Arrays; class Solution { public String longestCommonPrefix(String[] strs) { if (strs.length == 0) return ""; int min_length = strs[0].length(); for (int i = 1;i < strs.length;i++) { min_length = Math.min(min_length, strs[i].length()); } if (min_length == 0) return ""; for (int i = 0;i < min_length;i++) { char c = strs[0].charAt(i); for (int j = 1;j < strs.length;j++) { if (c != strs[j].charAt(i)) { return strs[0].substring(0, i); } } } return strs[0].substring(0, min_length); } }
true
f3b611a5d9e20415de1f2ceda60cefe3544275fc
Java
carlbray/webservice-test
/src/com/carlbray/pojos/organisation/Query.java
UTF-8
3,076
2.390625
2
[]
no_license
package com.carlbray.pojos.organisation; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "offset", "count", "total" }) public class Query { @JsonProperty("offset") private int offset; @JsonProperty("count") private int count; @JsonProperty("total") private int total; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("offset") public int getOffset() { return offset; } @JsonProperty("offset") public void setOffset(int offset) { this.offset = offset; } public Query withOffset(int offset) { this.offset = offset; return this; } @JsonProperty("count") public int getCount() { return count; } @JsonProperty("count") public void setCount(int count) { this.count = count; } public Query withCount(int count) { this.count = count; return this; } @JsonProperty("total") public int getTotal() { return total; } @JsonProperty("total") public void setTotal(int total) { this.total = total; } public Query withTotal(int total) { this.total = total; return this; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } public Query withAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); return this; } @Override public String toString() { return new ToStringBuilder(this).append("offset", offset).append("count", count).append("total", total).append("additionalProperties", additionalProperties).toString(); } @Override public int hashCode() { return new HashCodeBuilder().append(count).append(total).append(additionalProperties).append(offset).toHashCode(); } @Override public boolean equals(Object other) { if (other == this) { return true; } if ((other instanceof Query) == false) { return false; } Query rhs = ((Query) other); return new EqualsBuilder().append(count, rhs.count).append(total, rhs.total).append(additionalProperties, rhs.additionalProperties).append(offset, rhs.offset).isEquals(); } }
true
229dff4cc7d2496ef11b4c0c3dc37d7eb744a2fe
Java
chromium/chromium
/chrome/android/java/src/org/chromium/chrome/browser/suggestions/mostvisited/MostVisitedSites.java
UTF-8
2,922
2.234375
2
[ "BSD-3-Clause" ]
permissive
// Copyright 2017 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.suggestions.mostvisited; import androidx.annotation.Nullable; import org.chromium.base.annotations.CalledByNative; import org.chromium.chrome.browser.suggestions.SiteSuggestion; import org.chromium.chrome.browser.suggestions.tile.Tile; import org.chromium.url.GURL; import java.util.List; /** * Methods to provide most recent urls, titles and thumbnails. */ public interface MostVisitedSites { /** * An interface for handling events in {@link MostVisitedSites}. */ interface Observer { /** This is called when the list of most visited URLs is initially available or updated. */ void onSiteSuggestionsAvailable(List<SiteSuggestion> siteSuggestions); /** * This is called when a previously uncached icon has been fetched. * Parameters guaranteed to be non-null. * * @param siteUrl URL of site with newly-cached icon. */ void onIconMadeAvailable(GURL siteUrl); } /** * An interface to provide {@link MostVisitedSites} with platform-specific home page data. */ interface HomepageClient { /** * @return True if homepage tile should be shown. */ @CalledByNative("HomepageClient") boolean isHomepageTileEnabled(); /** * @return The raw URL of the currently set home page. */ @CalledByNative("HomepageClient") @Nullable String getHomepageUrl(); } /** * This instance must not be used after calling destroy(). */ void destroy(); /** * Sets the recipient for events from {@link MostVisitedSites}. The observer may be notified * synchronously or asynchronously. * @param observer The observer to be notified. * @param numSites The maximum number of sites to return. */ void setObserver(Observer observer, int numSites); /** * Blocklists a URL from the most visited URLs list. */ void addBlocklistedUrl(GURL url); /** * Removes a URL from the most visited URLs blocklist. */ void removeBlocklistedUrl(GURL url); /** * Records metrics about an impression of the surface with tiles. * @param tilesCount Count of tiles available on the surface at the moment. */ void recordPageImpression(int tilesCount); /** * Records metrics about an impression of a tile including its source (local, server, ...) and * its visual type. * @param tile Object holding the details of a tile. */ void recordTileImpression(Tile tile); /** * Records the opening of a Most Visited Item. * @param tile Object holding the details of a tile. */ void recordOpenedMostVisitedItem(Tile tile); }
true
fcaaf5d14c27c90942d362a928f77044150f4c26
Java
kronar/OK
/app/src/main/java/ru/ok/android/ui/custom/loadmore/LoadMoreAdapter.java
UTF-8
5,327
1.929688
2
[]
no_license
package ru.ok.android.ui.custom.loadmore; import android.content.Context; import android.database.DataSetObserver; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import ru.ok.android.ui.custom.loadmore.LoadMoreController.LoadMoreStateChangedListener; public class LoadMoreAdapter extends BaseAdapter implements LoadMoreStateChangedListener { private final BaseAdapter baseAdapter; private final Context context; private final LoadMoreController controller; @NonNull private final LoadMoreViewProvider loadMoreViewProvider; /* renamed from: ru.ok.android.ui.custom.loadmore.LoadMoreAdapter.1 */ class C06671 implements LoadMoreConditionCallback { C06671() { } public boolean isTimeToLoadTop(int position, int count) { return position == 0; } public boolean isTimeToLoadBottom(int position, int count) { return position == count + -1; } } public LoadMoreAdapter(Context context, BaseAdapter baseAdapter, LoadMoreAdapterListener listener, LoadMoreMode mode, @Nullable LoadMoreViewProvider loadMoreViewProvider) { this.context = context; this.baseAdapter = baseAdapter; if (loadMoreViewProvider == null) { loadMoreViewProvider = new DefaultLoadMoreViewProvider(); } this.loadMoreViewProvider = loadMoreViewProvider; this.controller = new LoadMoreController(listener, mode, new C06671(), this); } public int getCount() { return this.baseAdapter.getCount() + this.controller.getLoadMoreAdditionalCount(); } public Object getItem(int position) { if (this.controller.isTopView(position)) { return this.controller.topViewData; } if (this.controller.isBottomView(position, getCount())) { return this.controller.bottomViewData; } return this.baseAdapter.getItem(this.controller.getDataPosition(position)); } public long getItemId(int position) { if (this.controller.isTopView(position)) { return (long) this.controller.topViewData.hashCode(); } if (this.controller.isBottomView(position, getCount())) { return (long) this.controller.bottomViewData.hashCode(); } return this.baseAdapter.getItemId(this.controller.getDataPosition(position)); } public View getView(int position, View convertView, ViewGroup parent) { int count = getCount(); this.controller.onBindViewHolder(position, count); if (!this.controller.isTopOrBottomView(position, count)) { return this.baseAdapter.getView(this.controller.getDataPosition(position), convertView, parent); } LoadMoreView loadMoreView; boolean isTop = this.controller.isTopView(position); if (convertView instanceof LoadMoreView) { loadMoreView = (LoadMoreView) convertView; } else { loadMoreView = this.loadMoreViewProvider.createLoadMoreView(this.context, isTop, parent); } loadMoreView.bind(isTop ? this.controller.topViewData : this.controller.bottomViewData); return loadMoreView; } public int getItemViewType(int position) { if (this.controller.isTopView(position)) { return 0; } if (this.controller.isBottomView(position, getCount())) { return 1; } return this.baseAdapter.getItemViewType(this.controller.getDataPosition(position)) + 2; } public int getViewTypeCount() { return this.baseAdapter.getViewTypeCount() + 2; } public void registerDataSetObserver(DataSetObserver observer) { super.registerDataSetObserver(observer); this.baseAdapter.registerDataSetObserver(observer); } public void unregisterDataSetObserver(DataSetObserver observer) { super.unregisterDataSetObserver(observer); this.baseAdapter.unregisterDataSetObserver(observer); } public boolean processItemClick(int position) { if (this.controller.isTopView(position)) { this.controller.startTopLoading(); return true; } else if (!this.controller.isBottomView(position, getCount())) { return false; } else { this.controller.startBottomLoading(); return true; } } public boolean isEmpty() { return this.controller.isEmpty(this.baseAdapter.getCount()); } public boolean isEnabled(int position) { int i = 0; if (this.controller.isTopOrBottomView(position, getCount())) { return false; } BaseAdapter baseAdapter = this.baseAdapter; if (this.controller.mode.hasTopAdditionalView) { i = 1; } return baseAdapter.isEnabled(position - i); } public boolean hasStableIds() { return this.baseAdapter.hasStableIds(); } public void onTopAutoLoadChanged() { notifyDataSetChanged(); } public void onBottomAutoLoadChanged() { notifyDataSetChanged(); } public LoadMoreController getController() { return this.controller; } }
true
1a4d203eff7f8c20bbead3f3384809c7268eb097
Java
dutraRafael13/spring-boot-ionic-backend
/src/main/java/com/dutra/cursomc/services/BoletoService.java
UTF-8
554
2.15625
2
[]
no_license
package com.dutra.cursomc.services; import java.util.Calendar; import java.util.Date; import org.springframework.stereotype.Service; import com.dutra.cursomc.domain.PagamentoComBoleto; @Service public class BoletoService { private static final int VENCIMENTO = 7; public void preenchePagamentoComBoleto(PagamentoComBoleto pagamento, Date instantePedido) { Calendar calendar = Calendar.getInstance(); calendar.setTime(instantePedido); calendar.add(Calendar.DAY_OF_MONTH, VENCIMENTO); pagamento.setDataVencimento(calendar.getTime()); } }
true
802cbfd10e369e778d1198dd9f1d3a7e2a02b6a9
Java
Akshit8/corify-app
/app-v1/app/src/main/java/com/ishaanohri/corify/UserDetails2.java
UTF-8
12,747
2.203125
2
[]
no_license
package com.ishaanohri.corify; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CompoundButton; import android.widget.TextView; import com.google.android.material.chip.Chip; import com.sasank.roundedhorizontalprogress.RoundedHorizontalProgressBar; public class UserDetails2 extends AppCompatActivity { private Chip cold, fever, bronchitis, breath, headache, aids, pneumonia, cough, heart, chronic; private RoundedHorizontalProgressBar healthProgress2; private Button nextButton; private TextView scoreTextView; public static float total, score; float value, oldValue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_details2); cold = findViewById(R.id.chip1); fever = findViewById(R.id.chip2); bronchitis = findViewById(R.id.chip3); breath = findViewById(R.id.chip4); headache = findViewById(R.id.chip5); aids = findViewById(R.id.chip6); pneumonia = findViewById(R.id.chip7); cough = findViewById(R.id.chip8); heart = findViewById(R.id.chip9); chronic = findViewById(R.id.chip10); healthProgress2 = findViewById(R.id.healthProgress2); nextButton = findViewById(R.id.nextButton2); scoreTextView = findViewById(R.id.scoreTextView2); total = 47; score = 47; value = score/total * 100; healthProgress2.animateProgress(1000, 0, Math.round(value)); // (animationDuration, oldProgress, newProgress) scoreTextView.setText(String.valueOf(Math.round(value)) + "%"); cold.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) { score = score - 2; oldValue = value; value = score/total * 100; healthProgress2.animateProgress(1000, Math.round(oldValue), Math.round(value)); // (animationDuration, oldProgress, newProgress) scoreTextView.setText(String.valueOf(Math.round(value)) + "%"); } else { score = score + 2; oldValue = value; value = score/total * 100; healthProgress2.animateProgress(1000, Math.round(oldValue), Math.round(value)); // (animationDuration, oldProgress, newProgress) scoreTextView.setText(String.valueOf(Math.round(value)) + "%"); } } }); fever.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) { score = score - 3; oldValue = value; value = score/total * 100; healthProgress2.animateProgress(1000, Math.round(oldValue), Math.round(value)); // (animationDuration, oldProgress, newProgress) scoreTextView.setText(String.valueOf(Math.round(value)) + "%"); } else { score = score + 3; oldValue = value; value = score/total * 100; healthProgress2.animateProgress(1000, Math.round(oldValue), Math.round(value)); // (animationDuration, oldProgress, newProgress) scoreTextView.setText(String.valueOf(Math.round(value)) + "%"); } } }); bronchitis.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) { score = score - 6; oldValue = value; value = score/total * 100; healthProgress2.animateProgress(1000, Math.round(oldValue), Math.round(value)); // (animationDuration, oldProgress, newProgress) scoreTextView.setText(String.valueOf(Math.round(value)) + "%"); } else { score = score + 6; oldValue = value; value = score/total * 100; healthProgress2.animateProgress(1000, Math.round(oldValue), Math.round(value)); // (animationDuration, oldProgress, newProgress) scoreTextView.setText(String.valueOf(Math.round(value)) + "%"); } } }); breath.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) { score = score - 5; oldValue = value; value = score/total * 100; healthProgress2.animateProgress(1000, Math.round(oldValue), Math.round(value)); // (animationDuration, oldProgress, newProgress) scoreTextView.setText(String.valueOf(Math.round(value)) + "%"); } else { score = score + 5; oldValue = value; value = score/total * 100; healthProgress2.animateProgress(1000, Math.round(oldValue), Math.round(value)); // (animationDuration, oldProgress, newProgress) scoreTextView.setText(String.valueOf(Math.round(value)) + "%"); } } }); headache.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) { score = score - 5; oldValue = value; value = score/total * 100; healthProgress2.animateProgress(1000, Math.round(oldValue), Math.round(value)); // (animationDuration, oldProgress, newProgress) scoreTextView.setText(String.valueOf(Math.round(value)) + "%"); } else { score = score + 5; oldValue = value; value = score/total * 100; healthProgress2.animateProgress(1000, Math.round(oldValue), Math.round(value)); // (animationDuration, oldProgress, newProgress) scoreTextView.setText(String.valueOf(Math.round(value)) + "%"); } } }); aids.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) { score = score - 8; oldValue = value; value = score/total * 100; healthProgress2.animateProgress(1000, Math.round(oldValue), Math.round(value)); // (animationDuration, oldProgress, newProgress) scoreTextView.setText(String.valueOf(Math.round(value)) + "%"); } else { score = score + 8; oldValue = value; value = score/total * 100; healthProgress2.animateProgress(1000, Math.round(oldValue), Math.round(value)); // (animationDuration, oldProgress, newProgress) scoreTextView.setText(String.valueOf(Math.round(value)) + "%"); } } }); cough.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) { score = score - 2; oldValue = value; value = score/total * 100; healthProgress2.animateProgress(1000, Math.round(oldValue), Math.round(value)); // (animationDuration, oldProgress, newProgress) scoreTextView.setText(String.valueOf(Math.round(value)) + "%"); } else { score = score + 2; oldValue = value; value = score/total * 100; healthProgress2.animateProgress(1000, Math.round(oldValue), Math.round(value)); // (animationDuration, oldProgress, newProgress) scoreTextView.setText(String.valueOf(Math.round(value)) + "%"); } } }); pneumonia.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) { score = score - 7; oldValue = value; value = score/total * 100; healthProgress2.animateProgress(1000, Math.round(oldValue), Math.round(value)); // (animationDuration, oldProgress, newProgress) scoreTextView.setText(String.valueOf(Math.round(value)) + "%"); } else { score = score + 7; oldValue = value; value = score/total * 100; healthProgress2.animateProgress(1000, Math.round(oldValue), Math.round(value)); // (animationDuration, oldProgress, newProgress) scoreTextView.setText(String.valueOf(Math.round(value)) + "%"); } } }); heart.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) { score = score - 4; oldValue = value; value = score/total * 100; healthProgress2.animateProgress(1000, Math.round(oldValue), Math.round(value)); // (animationDuration, oldProgress, newProgress) scoreTextView.setText(String.valueOf(Math.round(value)) + "%"); } else { score = score + 4; oldValue = value; value = score/total * 100; healthProgress2.animateProgress(1000, Math.round(oldValue), Math.round(value)); // (animationDuration, oldProgress, newProgress) scoreTextView.setText(String.valueOf(Math.round(value)) + "%"); } } }); chronic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) { score = score - 5; oldValue = value; value = score/total * 100; healthProgress2.animateProgress(1000, Math.round(oldValue), Math.round(value)); // (animationDuration, oldProgress, newProgress) scoreTextView.setText(String.valueOf(Math.round(value)) + "%"); } else { score = score + 5; oldValue = value; value = score/total * 100; healthProgress2.animateProgress(1000, Math.round(oldValue), Math.round(value)); // (animationDuration, oldProgress, newProgress) scoreTextView.setText(String.valueOf(Math.round(value)) + "%"); } } }); nextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(UserDetails2.this, UserDetails3.class); startActivity(intent); } }); } }
true
8b2615bfcbdf2f905db001889dbfe204b27c7bbb
Java
viper78/interview
/src/core/TicTac.java
UTF-8
3,604
3.828125
4
[]
no_license
package core; import java.util.Scanner; public class TicTac { static char[][] board = new char[3][3]; static char player = 'x'; public static void main(String[] args) { int row, col = -1; System.out.println("Board..."); initialize(board); Scanner in = new Scanner(System.in); while (!isBoardFull(board) && !isGameOver(board)) { System.out.println("Enter row:"); row = in.nextInt(); System.out.println("Enter col:"); col = in.nextInt(); if (applyValue(board, row, col, player)) { print(board); if (!isGameOver(board)) { switchPlayer(); } } } print(board); if (!isGameOver(board) && isBoardFull(board)) { System.out.println("Its a tie"); } else { System.out.println("Player " + player + " wins"); } } public static boolean applyValue(char[][] board, int row, int col, char player) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == row && j == col) { if (board[i][j] == '-') { board[i][j] = player; return true; } else { return false; } } } } return false; } public static void switchPlayer() { if (player == 'x') { player = 'o'; } else { player = 'x'; } } public static void initialize(char[][] board) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { board[i][j] = '-'; System.out.print(board[i][j] + " "); } System.out.println(); } } public static void print(char[][] board) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { System.out.print(board[i][j] + " "); } System.out.println(); } } public static boolean isBoardFull(char[][]board) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i][j] == '-') { return false; } } } return true; } public static boolean isGameOver(char[][] board) { if (isRowsMatch(board) || isColsMatch(board) || isDiagonalsMatch(board)) { System.out.println("Game Over"); return true; } return false; } public static boolean isRowsMatch(char[][] board) { for (int i = 0; i < 3; i++) { if (checkEquals(board[i][0], board[i][1], board[i][2])) { return true; } } return false; } public static boolean isColsMatch(char[][] board) { for (int i = 0; i < 3; i++) { if (checkEquals(board[0][i], board[1][i], board[2][i])) { return true; } } return false; } public static boolean isDiagonalsMatch(char[][] board) { if (checkEquals(board[0][0], board[1][1], board[2][2]) || checkEquals(board[0][2], board[1][1], board[2][0])) { return true; } return false; } public static boolean checkEquals(char a, char b, char c) { if (a != '-' && a == b && b == c) { return true; } return false; } }
true
a3de609275cbf883c1fc097d893e2a2464a1a264
Java
garrickyang/hello-world
/kata-practice/src/main/java/yanggui/kata/suppermarket/Product.java
UTF-8
906
2.34375
2
[]
no_license
package yanggui.kata.suppermarket; import java.math.BigDecimal; import java.util.Currency; public class Product { private String productName; private BigDecimal price; private String skuid; private Currency currency; private String unit; public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public String getSkuid() { return skuid; } public void setSkuid(String skuid) { this.skuid = skuid; } public Currency getCurrency() { return currency; } public void setCurrency(Currency currency) { this.currency = currency; } }
true
7094220031c76df6a1f1a64c616f703bdd895a34
Java
sunhonglong/common
/src/main/java/com/upyoo/cloud/common/entity/Alert.java
UTF-8
6,090
1.648438
2
[]
no_license
package com.upyoo.cloud.common.entity; import java.io.Serializable; public class Alert implements Serializable { private static final long serialVersionUID = 1L; protected Integer id; private Integer alarmId; private Long creationTime; private Long modifiedTime; private Integer version; private String alarmType; private String alarmName; private String entityName; private String hostIp; private String status; private Long autoResolve; private Integer parentAlarmId; private String host; private String service; private String tag; private String metric; private Integer activeCount; private String activeAlarm; private Integer alarmVersion; private String owner; private String assignments; private String users; private String alarmContent; private Integer priority; protected Long ackTime; protected String ackUser; private Long closeTime; private String closeUser; private String closeComments; private String entityId; private Integer alertDefId; private String policyId; private String source; private String user; private String app; private String eventId; private String sourceUrl; private Integer ext; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getAlarmId() { return alarmId; } public void setAlarmId(Integer alarmId) { this.alarmId = alarmId; } public Long getCreationTime() { return creationTime; } public void setCreationTime(Long creationTime) { this.creationTime = creationTime; } public Long getModifiedTime() { return modifiedTime; } public void setModifiedTime(Long modifiedTime) { this.modifiedTime = modifiedTime; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public String getAlarmType() { return alarmType; } public void setAlarmType(String alarmType) { this.alarmType = alarmType; } public String getAlarmName() { return alarmName; } public void setAlarmName(String alarmName) { this.alarmName = alarmName; } public String getEntityName() { return entityName; } public void setEntityName(String entityName) { this.entityName = entityName; } public String getHostIp() { return hostIp; } public void setHostIp(String hostIp) { this.hostIp = hostIp; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Long getAutoResolve() { return autoResolve; } public void setAutoResolve(Long autoResolve) { this.autoResolve = autoResolve; } public Integer getParentAlarmId() { return parentAlarmId; } public void setParentAlarmId(Integer parentAlarmId) { this.parentAlarmId = parentAlarmId; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getService() { return service; } public void setService(String service) { this.service = service; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public String getMetric() { return metric; } public void setMetric(String metric) { this.metric = metric; } public Integer getActiveCount() { return activeCount; } public void setActiveCount(Integer activeCount) { this.activeCount = activeCount; } public String getActiveAlarm() { return activeAlarm; } public void setActiveAlarm(String activeAlarm) { this.activeAlarm = activeAlarm; } public Integer getAlarmVersion() { return alarmVersion; } public void setAlarmVersion(Integer alarmVersion) { this.alarmVersion = alarmVersion; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getAssignments() { return assignments; } public void setAssignments(String assignments) { this.assignments = assignments; } public String getUsers() { return users; } public void setUsers(String users) { this.users = users; } public String getAlarmContent() { return alarmContent; } public void setAlarmContent(String alarmContent) { this.alarmContent = alarmContent; } public Integer getPriority() { return priority; } public void setPriority(Integer priority) { this.priority = priority; } public Long getAckTime() { return ackTime; } public void setAckTime(Long ackTime) { this.ackTime = ackTime; } public String getAckUser() { return ackUser; } public void setAckUser(String ackUser) { this.ackUser = ackUser; } public Long getCloseTime() { return closeTime; } public void setCloseTime(Long closeTime) { this.closeTime = closeTime; } public String getCloseUser() { return closeUser; } public void setCloseUser(String closeUser) { this.closeUser = closeUser; } public String getCloseComments() { return closeComments; } public void setCloseComments(String closeComments) { this.closeComments = closeComments; } public String getEntityId() { return entityId; } public void setEntityId(String entityId) { this.entityId = entityId; } public Integer getAlertDefId() { return alertDefId; } public void setAlertDefId(Integer alertDefId) { this.alertDefId = alertDefId; } public String getPolicyId() { return policyId; } public void setPolicyId(String policyId) { this.policyId = policyId; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getApp() { return app; } public void setApp(String app) { this.app = app; } public String getEventId() { return eventId; } public void setEventId(String eventId) { this.eventId = eventId; } public String getSourceUrl() { return sourceUrl; } public void setSourceUrl(String sourceUrl) { this.sourceUrl = sourceUrl; } public Integer getExt() { return ext; } public void setExt(Integer ext) { this.ext = ext; } }
true
a7e6e482ae2566b143577cd2061597af53cfcabf
Java
skok005/chattingProject
/Chatting/src/Chatting/Chatting_Client.java
UHC
1,137
2.8125
3
[]
no_license
package Chatting; import java.awt.Component; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import javax.swing.JOptionPane; public class Chatting_Client implements Runnable{ private static final String SERVER_IP = "127.0.0.1"; private static final int SERVER_PORT = 9090; public static void main(String[] args) throws IOException{ Socket socket = new Socket(SERVER_IP, SERVER_PORT); InputStream is=socket.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); OutputStream os=socket.getOutputStream(); PrintWriter out =new PrintWriter(new OutputStreamWriter(os)); String serverResponse = br.readLine(); JOptionPane.showMessageDialog(null, " !"); Chatting_Client cc = new Chatting_Client(); cc.run(); socket.close(); System.out.println(0); } @Override public void run() { Chatting_Login ca = new Chatting_Login(); ca.LoginScreen(); } }
true
cdd4758d056f4695d8f5d4ccd40ba48a9ebfe229
Java
huanglongf/enterprise_project
/service-interface-wms/src/main/java/com/jumbo/util/PropListCopyable.java
UTF-8
778
2.578125
3
[]
no_license
package com.jumbo.util; import java.io.Serializable; import java.util.HashSet; import java.util.Set; public class PropListCopyable implements CopyableInterface, Serializable { private static final long serialVersionUID = 4436474866531853581L; private Set<String> props; public PropListCopyable(String... propList) { props = new HashSet<String>(); if (propList != null) { for (String prop : propList){ props.add(prop); } } } @Override public boolean isCopyable(String propertyName, Object propertyValue, @SuppressWarnings("rawtypes") Class clazz) { if (props.contains(propertyName)){ return true; } else{ return false; } } }
true
8670c0b5a94ce8e474fc0e7ff5ed0f053f63d399
Java
jovanam96/TravelAgency
/TravelAgencyAPI/src/main/java/com/ta/controller/CityController.java
UTF-8
1,005
1.8125
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 com.ta.controller; import com.ta.controller.dto.CityDTO; import com.ta.entity.City; import com.ta.service.CityService; import java.util.List; import java.util.stream.Collectors; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * * @author Jovana Mitrovic */ @RestController @RequestMapping("/city") @CrossOrigin public class CityController { @Autowired private CityService cityService; @GetMapping("/all") public List<CityDTO> findAll() { return cityService.findAll(); } }
true
19881fb12ab2478021d6da91ca456f4471b77a28
Java
BGSU-RNA/JAR3D
/src/main/java/edu/bgsu/rna/jar3d/JAR3DMatlab.java
UTF-8
11,817
2.65625
3
[]
no_license
package edu.bgsu.rna.jar3d; import java.io.*; import java.util.*; /** * This is the Alignment class, it has methods that are used to facilitate aligning sequences * @author meg pirrung * */ public class JAR3DMatlab { /** * MotifCorrespondences parses a fasta file of sequences against a model * and collects together correspondences between sequence positions and * JAR3D model positions, returning them as a string * @param fastaFileName * @param modelFileName * @return */ public static String ModelCorrespondences(String fastaFileName, String modelPath, String modelName, int rotation) { List<Sequence> sequenceData = Alignment.loadFasta(fastaFileName); MotifGroup group = new MotifGroup(modelPath, modelName); String type = group.loopType; if (rotation > 0) sequenceData = Alignment.reverse(sequenceData); sequenceData = Alignment.doParse(sequenceData, group.Model, 999, true, true); double[] modelScores = new double[sequenceData.size()]; //Add up model scores for each sequence, find mean score, compare regular and reversed scores for(int m = 1; m < sequenceData.size(); m++) { double tempo = sequenceData.get(m).getMaxLogProbability(0); modelScores[m-1] = tempo; } double[] Deficits = Alignment.getDeficits(group.Best_Score, modelScores); int[] InteriorMinDist = Alignment.getMinEditDistance(group,sequenceData,type,rotation,true); int[] FullMinDist = Alignment.getMinEditDistance(group,sequenceData,type,rotation,false); boolean[] cutoffs = Alignment.getCutoffs(group,modelScores,InteriorMinDist); double[] cutoffscores = Alignment.getCutoffScores(group,modelScores,InteriorMinDist); // Alignment.displayAlignmentFASTA(sequenceData); String correspondences = ""; for (int i = 1; i < sequenceData.size(); i++) { sequenceData.get(i).correspondences += "Sequence_"+i+" has_alignment_score_deficit "+String.valueOf(Deficits[i-1])+"\n"; sequenceData.get(i).correspondences += "Sequence_"+i+" has_minimum_interior_edit_distance "+String.valueOf(InteriorMinDist[i-1])+"\n"; sequenceData.get(i).correspondences += "Sequence_"+i+" has_minimum_full_edit_distance "+String.valueOf(FullMinDist[i-1])+"\n"; sequenceData.get(i).correspondences += "Sequence_"+i+" has_cutoff_value "+String.valueOf(cutoffs[i-1])+"\n"; sequenceData.get(i).correspondences += "Sequence_"+i+" has_cutoff_score "+String.valueOf(cutoffscores[i-1])+"\n"; } for (int i = 1; i < sequenceData.size(); i++) { correspondences += ((Sequence)sequenceData.get(i)).correspondences; } correspondences = correspondences.replace("MMM",modelName); return correspondences; } public static List Align(String FastaFile, String ModelFile, int DNA, int range) { List sequenceData = Alignment.loadFastaColumnsDNA(FastaFile,0,0,DNA); sequenceData = Alignment.doParse(sequenceData, ModelFile, range); return sequenceData; } public static ParseData Align2(String UserDir, String FastaFile, String ModelFile, int DNA, int range) { System.setProperty("user.dir",UserDir); Vector sequenceData = Alignment.loadFastaColumnsDNA(FastaFile,0,0,DNA); ParseData PD = new ParseData(); PD = Alignment.doParse2(sequenceData, ModelFile, range); return PD; } public static double[][] MotifTest(String UserDir, String loopType) { String FASTAName = ""; Vector<Sequence> sData; System.setProperty("user.dir",UserDir); Vector<String> modelNames = Sequence.getModelNames(loopType); // read file listing model names System.out.println("Read " + modelNames.size() + " model names"); double S[][] = new double[modelNames.size()][3*modelNames.size()]; S[0][0] = 1; for (int m=0; m<modelNames.size();m++) // loop through sets of sequences { FASTAName = ((String)modelNames.get(m)).replace(".txt",".fasta"); System.out.println("Aligning sequences from "+FASTAName); sData = Alignment.loadFasta(FASTAName); double[] newscores = new double[2*modelNames.size()]; if (loopType.equals("IL")) { newscores = Alignment.getSortedILAlignment(sData, modelNames, 100); for (int g=0; g < 2*modelNames.size(); g++) S[m][g] = newscores[g]; } } return S; } /** * MotifTestGeneral reads a list of model names and sequence names separately * It looks in the folder Sequences for sequences * It looks in the folder Models for models * @param UserDir * @param loopType * @return */ public static double[][] MotifTestGeneral(String UserDir, String loopType, String sequenceNameFile, String modelNameFile) { String FASTAName = ""; Vector<Sequence> sData; System.setProperty("user.dir",UserDir); Vector<String> modelNames = Sequence.readTextFile("Models" + File.separator + modelNameFile); // read file listing model names System.out.println("Read " + modelNames.size() + " model names"); Vector<String> sequenceNames = Sequence.readTextFile("Sequences" + File.separator + sequenceNameFile); // read file listing model names System.out.println("Read " + sequenceNames.size() + " sequence names"); double[][] S; if(loopType.equals("IL")){ S = new double[sequenceNames.size()][2*modelNames.size()]; }else{ //assume hairpin S = new double[sequenceNames.size()][modelNames.size()]; } S[0][0] = 1; for (int m=0; m<sequenceNames.size();m++) // loop through sets of sequences { FASTAName = ((String)sequenceNames.get(m)); System.out.println("Aligning sequences from "+FASTAName); sData = Alignment.loadFasta(FASTAName); double[] newscores = new double[2*modelNames.size()]; if (loopType.equals("IL")) { newscores = Alignment.getSortedILAlignment(sData, modelNames, 100); for (int g=0; g < 2*modelNames.size(); g++) S[m][g] = newscores[g]; } else if (loopType.equals("HL")) newscores = Alignment.getSortedHLAlignment(sData, modelNames, 100); for (int g=0; g < modelNames.size(); g++) S[m][g] = newscores[g]; } return S; } public static Vector Display(Vector sData) { Vector<String> pData = new Vector<String>(); for (int i = 0; i < sData.size(); i++) { pData.add(((Sequence)sData.get(i)).parseData); System.out.println((String)pData.get(i)); } int[] mask = Alignment.stripDash(pData); String alnm = ""; Vector alignmentVect = new Vector(); for(int j = 0; j < pData.size(); j++) { alnm = ""; for(int i = 0; i < mask.length; i++) { if(mask[i] == 0) alnm += pData.get(j).charAt(i); } alnm += " "+((Sequence)sData.elementAt(j)).organism+" "; for(int x = 0; x < ((Sequence)sData.elementAt(j)).getMaxNodeLogProbabilitySize(); x++) alnm += ((Sequence)sData.elementAt(j)).getMaxNodeLogProbabilities(x).get(0); alignmentVect.add(alnm); } return alignmentVect; } // Parse the sequences in the fasta file seq file against all models in the model directory public static double[][] MotifParseAll(String UserDir, String SeqFile, String loopType) { Vector<Sequence> sData; System.setProperty("user.dir",UserDir); Vector<String> modelNames = Sequence.getModelNames(loopType); sData = Alignment.loadFasta(SeqFile); double S[][] = new double[sData.size()][2*modelNames.size()]; if (loopType.equals("IL")) { S = Alignment.getILScores(sData, modelNames, 100); } return S; } public static double[] MotifParseSingle(String UserDir, String SeqFile, String ModFile) { Vector<Sequence> sData; System.setProperty("user.dir",UserDir); sData = Alignment.loadFasta(SeqFile); double S[] = new double[sData.size()]; S = Alignment.getILScoresSingle(sData, ModFile, 100); // Please retain the following commented-out line for debugging purposes // Alignment.displayAlignmentFASTA(sData); return S; } public static void WriteModelDists(String UserDir, String loopType,int distSize) { Vector<String> tinyModNames = new Vector<String>(); Vector<String> modelNames = Sequence.getModelNames(loopType); for (int k=0; k< modelNames.size(); k++) { tinyModNames.add(modelNames.get(k).substring(0,5)); } for(int i=0; i<modelNames.size(); i++) { String nodeFileName = modelNames.get(i); Sequence S = new Sequence("",""); // blank sequence S.addNodeData(nodeFileName); // only add node data once } } public static int[][] DisplayEditDists(String UserDir, String seqFile1, String seqFile2, String loopType){ // TODO 2013-11-07 CLZ Below, the IL edit distances are called with rotation 0. That might not be appropriate. System.setProperty("user.dir",UserDir); Vector<Sequence> seqData1 = Alignment.loadFasta(seqFile1); Vector<Sequence> seqData2 = Alignment.loadFasta(seqFile1); int[][] EditDistances; if(loopType.equals("IL")){ EditDistances = SimpleAlign.calcILEditDistances(seqData1,seqData2,0,true); }else{ EditDistances = SimpleAlign.calcHLEditDistances(seqData1,seqData2,true); } return EditDistances; } public static double[] getQuantilesFromFile(double[] Scores, String quantileFileName) { File distFile = new File(quantileFileName); Vector modDist = new Vector(); Vector modVals = new Vector(); try { FileReader inStream = new FileReader(distFile); BufferedReader in = new BufferedReader(inStream); String lineS; String ValueS; String DistS; double Value; double Dist; int BreakP; while((lineS = in.readLine()) != null){ BreakP = lineS.indexOf(" "); ValueS = lineS.substring(0, BreakP); DistS = lineS.substring(BreakP+1); Dist = Double.parseDouble(DistS); modDist.add(Dist); Value = Double.parseDouble(ValueS); modVals.add(Value); } in.close(); } catch(Exception e) { System.out.println("webJAR3D.getQuantilesFromFile: Error reading file " + quantileFileName + "\n" + e); } int n = Scores.length; double[] quantiles = new double[n]; int DistLength = modVals.size(); for(int i = 0; i < n; i++){ int found = 0; int j = DistLength/2; int step = j; double current; double next; while(found==0){ if(j==DistLength-1) { quantiles[i] = 1; found = 1; } else if(j==0){ current = ((Double)modVals.get(j)).doubleValue(); if(Scores[i] == current || Scores[i] > current){ quantiles[i] = ((Double)modDist.get(j)).doubleValue(); found = 1; }else{ quantiles[i] = 0; found = 1; } }else{ current = ((Double)modVals.get(j)).doubleValue(); next = ((Double)modVals.get(j+1)).doubleValue(); if(Scores[i] == current || (Scores[i] > current && Scores[i] < next)){ quantiles[i] = ((Double)modDist.get(j)).doubleValue(); found = 1; }else if(Scores[i] <current){ step = Math.max(step/2,1); j = j - step; }else { step = Math.max(step/2,1); j = j + step; } } } } return quantiles; } public static double[] MotifTotalProbSingle(String UserDir, String SeqFile, String ModFile) { System.setProperty("user.dir",UserDir); List<Sequence> sData; sData = Alignment.loadFasta(SeqFile); sData = Alignment.calculateTotalProbability(sData, ModFile, 0, false); double[] scores = new double[sData.size()-1]; // all scores computed for(int m = 1; m < sData.size(); m++) { scores[m-1] = sData.get(m).totalProbability; } return scores; } }
true
9ff2c68494e35c162a26fecb674deb626f19283b
Java
abramovaE/xoConsole
/src/main/java/ru/kotpack/crestiki/MainClass.java
UTF-8
1,098
3.015625
3
[]
no_license
package ru.kotpack.crestiki; public class MainClass { public static Pole igrovoePole; public static void main(String[] args) { igrovoePole = new Pole(); igrovoePole.setPole(new Cletka[3][3]); igrovoePole.ustanovkaPola(); Computer computer = new Computer(); computer.setName("computer"); Chelovek chelovek = new Chelovek(); ConsoleHelper.writeMessage("hello, how you doing, what's your name??"); String name = ConsoleHelper.readString(); chelovek.setName(name); while (true) { mainCourse(chelovek); if(igrovoePole.getWinner()!=null){break;} if (igrovoePole.isGameEnd()) break; mainCourse(computer); if(igrovoePole.getWinner()!=null){break;} if (igrovoePole.isGameEnd()) break; igrovoePole.pechatPola(); } } public static void mainCourse(Igrok igrok){ igrok.hod(); igrovoePole.findHasWinner(); igrovoePole.checkTheWinner(igrok); igrovoePole.checkTheGameEnd(); } }
true
72fa6e8efd176c9d420cfac3f39680d6e0696f61
Java
ndlongit/longnd-projects
/fichesst/src/main/java/com/structis/fichesst/server/service/client/ClientDeductionServiceImpl.java
UTF-8
616
1.664063
2
[]
no_license
package com.structis.fichesst.server.service.client; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.structis.fichesst.client.service.ClientDeductionService; import com.structis.fichesst.server.core.DependencyInjectionRemoteServiceServlet; import com.structis.fichesst.server.service.domain.DeductionService; @Service("clientDeductionService") public class ClientDeductionServiceImpl extends DependencyInjectionRemoteServiceServlet implements ClientDeductionService { @Autowired private DeductionService deductionService; }
true
944a3aaa19459f579e2e64f8d395bbfa3ec743b8
Java
Lamilla19/REPOSITORIO_5
/PisFinal_1/src/pis/Datos.java
UTF-8
2,793
2.890625
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 pis; import java.util.Scanner; /** * * @author PC-01 */ public class Datos { private String cedula; private String nombre; private String apellido; private String Dia; private String Mes; private String Anio; private String Edad; private String telefono; private String direccion; private int nivel; public Datos(String cedula, String nombre, String apellido, String Dia, String Mes, String Anio, String Edad, String telefono, String direccion,int nivel) { this.cedula = cedula; this.nombre = nombre; this.apellido = apellido; this.Dia = Dia; this.Mes = Mes; this.Anio = Anio; this.Edad = Edad; this.telefono = telefono; this.direccion = direccion; this.nivel=nivel; } public static boolean isInt(String str){ boolean entero=true; char[] strch=str.toCharArray(); for(int i=0;i<strch.length;i++){ if(!Character.isDigit(strch[i])){ entero=false; } } return entero; } public static boolean dosPalabras(String strw){ Scanner sc=new Scanner(strw); sc.useDelimiter("\\s* \\s*"); sc.next(); if(sc.hasNext()){ sc.next();} return !sc.hasNext(); } public void setCedula(String cedula) { this.cedula = cedula; } public void setNombre(String nombre) { this.nombre = nombre; } public void setApellido(String apellido) { this.apellido = apellido; } public void setTelefono(String telefono) { this.telefono = telefono; } public void setDireccion(String direccion) { this.direccion = direccion; } public String getCedula(){ return cedula; } public String getNombre() { return nombre; } public String getApellido() { return apellido; } public String getTelefono() { return telefono; } public String getDireccion() { return direccion; } public String getDia() { return Dia; } public void setDia(String Dia) { this.Dia = Dia; } public String getMes() { return Mes; } public void setMes(String Mes) { this.Mes = Mes; } public String getAnio() { return Anio; } public void setAnio(String Anio) { this.Anio = Anio; } public String getEdad() { return Edad; } public void setEdad(String Edad) { this.Edad = Edad; } public int getNivel(){ return nivel; } public void setNivel(int nivel){ this.nivel=nivel; } }
true
3955689d5235d55053420b70518fe130117d2bc7
Java
asteriskm0nkey/SpawnBorder
/SpawnBorder/src/main/java/com/asteriskmonkey/spawnborder/BorderStrategies/Completion/SmoothingCompletionStrategy.java
UTF-8
1,599
2.9375
3
[]
no_license
package com.asteriskmonkey.spawnborder.BorderStrategies.Completion; import java.util.List; import org.bukkit.Location; public class SmoothingCompletionStrategy implements BorderCompletionStrategy { @Override public List<Location> getCompletedBorderLocations(List<Location> skeletonBorder) { // TODO Auto-generated method stub throw new UnsupportedOperationException("Not yet implemented"); } // TODO begin here... map out roughly what I want the border function to do, block by block /* * TODO link the last entry in the locations to the first entry? Would * potentially cause some breakages. Keep it as a soft constraint that * the end of the list joins to the start of the list May be useful * later with a smoothed border, but not so much right now. */ // More advanced strategies can add gradients or smooth the land surrounding the border using the Diamond-Square method /* BorderSmoothingCompletionStrategy * Start with a block. Look at the block surrounding this block and average them out? * 1 1B 1 1 * 1 1* 2 1 replace 2 with a 1 * 1 1B 1 1 * * 5 5B 3 * 5 5B 3 * 5 5B 3 * * Looking at the contours of the land, rather than the immediate surrounding blocks? The second example would just find air * * Lay a mesh down on the land that matches the shape of the border and several squares surrounding it, then contort the * mesh, pulling up low parts, flattening high parts? * Read article on terrain generation by Robert Martin - he discusses an algorithm for averaging by choosing points. * Diamond-square algorithm? */ }
true
f6bd25e1a81c39a89f4e5a5507237ba0386b5d76
Java
dasmanas/practice_ws
/src/main/java/com/practice/mediumalgo/Subset.java
UTF-8
816
3.296875
3
[]
no_license
package com.practice.mediumalgo; import java.util.ArrayList; import java.util.List; public class Subset { public static void main(String[] args){ Subset subset = new Subset(); subset.subsets(new int[]{1,2,3}); } public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> output = new ArrayList(); output.add(new ArrayList<Integer>()); for(int num: nums){ List<List<Integer>> newSubsets = new ArrayList(); for (List<Integer> curr : output){ List<Integer> a = new ArrayList<Integer>(curr); a.add(num); newSubsets.add(a); } for (List<Integer> curr : newSubsets) { output.add(curr); } } return output; } }
true
21f584b9c1d2a0220327c3d4d04470bb2a1657fe
Java
Alexilho/FactoresHumanos
/ModuloFacturacion/src/Vista/Herramientas/buttonMenuMaker.java
UTF-8
2,806
2.78125
3
[]
no_license
package Vista.Herramientas; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.Color; import java.awt.Font; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.SwingConstants; public class buttonMenuMaker extends JButton { private static final long serialVersionUID = 1L; Color colorSeleccion; public buttonMenuMaker(String buttonLabel, int posX, int posY, int width, int height, Color[] focusedColor, Color panelColor, Font normalFont,String rutaIcono) { colorMaker pincel = new colorMaker(); setHorizontalAlignment(SwingConstants.LEFT); setHorizontalTextPosition(SwingConstants.RIGHT); setText(" "+buttonLabel); setLayout(null); setBackground(pincel.obtainColor("invisible")); setForeground(focusedColor[1]); setFont(normalFont); setFocusable(false); setBounds(new Rectangle(posX, posY, width, height)); setIcon(new ImageIcon(getClass().getResource(rutaIcono))); setBorder(BorderFactory.createMatteBorder(0, 10, 0, 0, panelColor)); addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent e) { /**Aspecto del boton en un momento cualquiera */ /** Modificar propiedades de visibilidad en vez de color*/ colorSeleccion = panelColor; setBorder(BorderFactory.createMatteBorder(0, 10, 0, 0, colorSeleccion)); } @Override public void mouseEntered(MouseEvent e) { /**Aspecto del boton con el mouse encima */ colorSeleccion = focusedColor[0]; setBorder(BorderFactory.createMatteBorder(0, 10, 0, 0, colorSeleccion)); setBackground(panelColor); } @Override public void mouseClicked(MouseEvent e) { setBorder(BorderFactory.createMatteBorder(0, 10, 0, 0, colorSeleccion)); setBackground(panelColor); } @Override public void mousePressed(MouseEvent e) { setBorder(BorderFactory.createMatteBorder(0, 10, 0, 0, colorSeleccion)); setBackground(panelColor); } @Override public void mouseExited(MouseEvent e) { /**Aspecto del boton cuando el mouse ya no esta encima */ colorSeleccion = panelColor; setBorder(BorderFactory.createMatteBorder(0, 10, 0, 0, colorSeleccion)); setBackground(panelColor); } }); } }
true
6ace1e0dc7526e32d024124badde3ed898ade70d
Java
BackupTheBerlios/cachewolf-svn
/branches/bugfix_1.0/src/CacheWolf/DetailsPanel.java
UTF-8
27,085
2.015625
2
[]
no_license
package CacheWolf; import ewe.ui.*; import ewe.fx.*; import ewe.util.*; import ewe.sys.*; /** * Class to create the panel to show the cache details.<br> * Also allows for creation of a custom waypoint.<br> * * */ public class DetailsPanel extends CellPanel{ mInput inpWaypoint = new mInput(); mInput inpName = new mInput(); mButton btnWayLoc = new mButton(); mInput inpHidden = new mInput(); mInput inpOwner = new mInput(); mButton btnDelete,btnCenter, btnAddDateTime; mChoice chcType = new mChoice(new String[]{"Custom", "Traditional", "Multi", "Virtual", "Letterbox", "Event", "Mega Event", "Mystery", "Webcam", "Locationless", "CITO", "Earthcache", "wherIGo", "Addi: Parking", "Addi: Stage", "Addi: Question", "Addi: Final","Addi: Trailhead","Addi: Reference"},0); mChoice chcSize = new mChoice(new String[]{"", "Micro", "Small", "Regular", "Large","Other","Very Large","None"},0); mComboBox chcStatus = new mComboBox(new String[]{"", MyLocale.getMsg(313,"Flag 1"), MyLocale.getMsg(314,"Flag 2"), MyLocale.getMsg(315,"Flag 3"), MyLocale.getMsg(316,"Flag 4"), MyLocale.getMsg(317,"Search"), MyLocale.getMsg(318,"Found"), MyLocale.getMsg(319,"Not Found"), MyLocale.getMsg(320,"Owner")},0); mButton btnNewWpt, btnShowBug, btnShowMap, btnGoto, btnAddPicture, btnBlack, btnNotes, btnSave, btnCancel; mButton btnFoundDate,btnHiddenDate; Vector cacheDB; CacheHolder thisCache; int dbIndex = -1; CellPanel pnlTools = new CellPanel(); AttributesViewer attV; mTextPad mNotes; private boolean dirty_notes = false; private boolean dirty_details = false; private boolean blackStatus = false; private boolean blackStatusChanged=false; private boolean needsTableUpdate = false; private boolean isBigScreen = false; Preferences pref; // Test Profile profile; mImage imgBlack; mImage imgBlackNo; mImage imgShowBug, imgShowBugNo,imgNewWpt,imgGoto; mImage imgShowMaps,imgAddImages,imgNotes; mLabel lblDiff, lblTerr; public DetailsPanel(){ pref = Global.getPref(); profile=Global.getProfile(); cacheDB = profile.cacheDB; //////////////////// // Tools //////////////////// // Use larger Button-Icons on VGA-mobiles int sw = MyLocale.getScreenWidth(); String imagesize=""; if (Vm.isMobile() && sw >= 400) imagesize="_vga"; // Button 1: New Waypoint pnlTools.addNext(btnNewWpt = new mButton(imgNewWpt=new mImage("newwpt"+imagesize+".png"))); btnNewWpt.setToolTip(MyLocale.getMsg(311,"Create Waypoint")); PenEvent.wantPenMoved(btnNewWpt,PenEvent.WANT_PEN_MOVED_ONOFF,true); imgNewWpt.transparentColor=new Color(255,0,0); // Button 2: Goto pnlTools.addNext(btnGoto = new mButton(imgGoto=new mImage("goto"+imagesize+".png")));//Goto.gif funzt manchmal nicht imgGoto.transparentColor=Color.White; btnGoto.setToolTip(MyLocale.getMsg(345,"Goto these coordinates")); // Button 3: Travelbugs imgShowBug = new mImage("bug"+imagesize+".gif"); imgShowBugNo = new mImage("bug_no"+imagesize+".gif"); pnlTools.addNext(btnShowBug = new mButton(imgShowBugNo)); //btnShowBug.modify(Control.Disabled,0); btnShowBug.setToolTip(MyLocale.getMsg(346,"Show travelbugs")); // Button 4: Show Map pnlTools.addNext(btnShowMap = new mButton(imgShowMaps = new mImage("globe_small"+imagesize+".gif"))); btnShowMap.setToolTip(MyLocale.getMsg(347,"Show map")); // Button 5: Add images pnlTools.addNext(btnAddPicture = new mButton(imgAddImages = new mImage("images"+imagesize+".gif"))); btnAddPicture.setToolTip(MyLocale.getMsg(348,"Add user pictures")); // Button 6: Toggle blacklist status imgBlackNo = new mImage("no_black"+imagesize+".png"); imgBlackNo.transparentColor=Color.Black; imgBlack = new mImage("is_black"+imagesize+".png"); imgBlack.transparentColor=Color.White; pnlTools.addNext(btnBlack=new mButton(imgBlackNo)); btnBlack.setToolTip(MyLocale.getMsg(349,"Toggle Blacklist status")); // Button 7: Notes pnlTools.addNext(btnNotes=new mButton(imgNotes=new mImage("notes"+imagesize+".gif"))); imgNotes.transparentColor=Color.DarkBlue; btnNotes.setToolTip(MyLocale.getMsg(351,"Add/Edit notes")); // Button 8: Date/time stamp pnlTools.addLast(btnAddDateTime = new mButton(new mImage("date_time"+imagesize+".gif"))); btnAddDateTime.setToolTip(MyLocale.getMsg(350,"Add timestamp to notes")); //showMap.modify(Control.Disabled,0); pnlTools.stretchFirstRow=true; this.addLast(pnlTools,CellConstants.DONTSTRETCH, CellConstants.WEST).setTag(SPAN,new Dimension(3,1));; //////////////////// // Main body of screen //////////////////// this.addNext(new mLabel(MyLocale.getMsg(300,"Type:")),CellConstants.DONTSTRETCH, (CellConstants.DONTFILL|CellConstants.NORTHWEST)); CellPanel line1Panel = new CellPanel(); line1Panel.addNext(chcType,CellConstants.HSTRETCH, (CellConstants.HFILL|CellConstants.WEST)); line1Panel.addLast(lblDiff=new mLabel(MyLocale.getMsg(1000,"D")+": 5.5"),CellConstants.DONTSTRETCH,(CellConstants.DONTFILL|CellConstants.EAST)); this.addLast(line1Panel,DONTSTRETCH,HFILL).setTag(CellConstants.SPAN, new Dimension(2,1)); this.addNext(new mLabel(MyLocale.getMsg(301,"Size:")),CellConstants.DONTSTRETCH, (CellConstants.DONTFILL|CellConstants.WEST)); CellPanel line2Panel = new CellPanel(); line2Panel.addNext(chcSize,CellConstants.HSTRETCH, (CellConstants.HFILL|CellConstants.WEST)); line2Panel.addLast(lblTerr=new mLabel(MyLocale.getMsg(1001,"T")+": 5.5"),CellConstants.DONTSTRETCH,(CellConstants.DONTFILL|CellConstants.EAST)); this.addLast(line2Panel,DONTSTRETCH,HFILL).setTag(CellConstants.SPAN, new Dimension(2,1)); this.addNext(new mLabel(MyLocale.getMsg(302,"Waypoint:")),CellConstants.DONTSTRETCH, (CellConstants.DONTFILL|CellConstants.WEST)); this.addLast(inpWaypoint.setTag(CellConstants.SPAN, new Dimension(2,1)),CellConstants.DONTSTRETCH, (CellConstants.HFILL|CellConstants.WEST)); this.addNext(new mLabel(MyLocale.getMsg(303,"Name:")),CellConstants.DONTSTRETCH, (CellConstants.DONTFILL|CellConstants.WEST)); this.addLast(inpName.setTag(CellConstants.SPAN, new Dimension(2,1)),CellConstants.DONTSTRETCH, (CellConstants.HFILL|CellConstants.WEST)); this.addNext(new mLabel(MyLocale.getMsg(304,"Location:")),CellConstants.DONTSTRETCH, (CellConstants.DONTFILL|CellConstants.WEST)); this.addLast(btnWayLoc.setTag(CellConstants.SPAN, new Dimension(2,1)),CellConstants.HSTRETCH, (CellConstants.HFILL|CellConstants.WEST)); this.addNext(new mLabel(MyLocale.getMsg(307,"Status:")),CellConstants.DONTSTRETCH, (CellConstants.DONTFILL|CellConstants.WEST)); CellPanel cp=new CellPanel(); cp.addNext(chcStatus,CellConstants.HSTRETCH, (CellConstants.HFILL|CellConstants.WEST)); cp.addLast(btnFoundDate=new mButton(new mImage("calendar"+imagesize+".png")),DONTSTRETCH,DONTFILL); this.addLast(cp,DONTSTRETCH,HFILL).setTag(CellConstants.SPAN, new Dimension(2,1)); this.addNext(new mLabel(MyLocale.getMsg(306,"Owner:")),CellConstants.DONTSTRETCH, (CellConstants.DONTFILL|CellConstants.WEST)); this.addLast(inpOwner.setTag(CellConstants.SPAN, new Dimension(2,1)),CellConstants.DONTSTRETCH, (CellConstants.HFILL|CellConstants.WEST)); this.addNext(new mLabel(MyLocale.getMsg(305,"Hidden on:")),CellConstants.DONTSTRETCH, (CellConstants.DONTFILL|CellConstants.WEST)); CellPanel ip=new CellPanel(); ip.addNext(inpHidden,CellConstants.HSTRETCH, (CellConstants.HFILL|CellConstants.WEST)); ip.addLast(btnHiddenDate=new mButton(new mImage("calendar"+imagesize+".png")),DONTSTRETCH,DONTFILL); this.addLast(ip,DONTSTRETCH,HFILL).setTag(CellConstants.SPAN, new Dimension(2,1)); inpHidden.modifyAll(DisplayOnly,0); //btnNotes = new mButton("Notes"); //this.addLast(btnNotes.setTag(Control.SPAN, new Dimension(3,1)),CellConstants.DONTSTRETCH, (CellConstants.HFILL|CellConstants.WEST)); //this.addNext(new mLabel(MyLocale.getMsg(308,"Notes:")),CellConstants.DONTSTRETCH, (CellConstants.DONTFILL|CellConstants.WEST)); //this.addLast(btnCenter = new mButton(MyLocale.getMsg(309,"Make Centre")),CellConstants.DONTSTRETCH, (CellConstants.DONTFILL|CellConstants.WEST)); // this.addLast(btnDelete = new mButton(MyLocale.getMsg(310,"Delete")),CellConstants.DONTSTRETCH, (CellConstants.DONTFILL|CellConstants.WEST)); attV=new AttributesViewer(); this.addLast(attV); if ((MyLocale.getScreenWidth() >= 400) && (MyLocale.getScreenHeight() >= 600)){ isBigScreen = true; this.addLast(new mLabel(MyLocale.getMsg(308,"Notes:")),CellConstants.DONTSTRETCH, (CellConstants.DONTFILL|CellConstants.WEST)); mNotes = new mTextPad(); mNotes.modify(ControlConstants.NotEditable,0); this.addLast(new MyScrollBarPanel(mNotes)); } } public void clear() { attV.clear(); } public void setNeedsTableUpdate(boolean tableUpdate) { needsTableUpdate = tableUpdate; } public boolean needsTableUpdate() { return needsTableUpdate; } public boolean isDirty() { return dirty_notes || dirty_details || needsTableUpdate; } public boolean hasBlackStatusChanged() { return blackStatusChanged; } /** * @param chD details of the cache to display * @param dbindex index in cacheDB, in which changes will be saved */ public void setDetails(CacheHolder ch){ thisCache = ch; dirty_notes = false; dirty_details = false; inpWaypoint.setText(ch.wayPoint); inpName.setText(ch.CacheName); btnWayLoc.setText(ch.pos.toString()); inpHidden.setText(ch.DateHidden); inpOwner.setText(ch.CacheOwner); if (ch.CacheStatus.length()>=10 && ch.CacheStatus.charAt(4)=='-') chcStatus.setText(MyLocale.getMsg(318,"Found")+" "+ch.CacheStatus); else { chcStatus.setText(ch.CacheStatus); // If the cache status contains a date, do not overwrite it with 'found' message if(ch.is_found == true) chcStatus.setText(MyLocale.getMsg(318,"Found")); } chcType.setInt(transType(ch.type)); if(ch.is_black){ btnBlack.image = imgBlack; } else { btnBlack.image = imgBlackNo; } blackStatus=ch.is_black; blackStatusChanged=false; btnBlack.repaintNow(); if (inpWaypoint.getText().length() == 0) createWptName(); if(ch.has_bug == true) { //btnShowBug.modify(Control.Disabled,1); btnShowBug.image = imgShowBug; } else { //btnShowBug.modify(Control.Disabled,0); btnShowBug.image = imgShowBugNo; } btnShowBug.repaintNow(); if(ch.CacheSize.equals("Micro")) chcSize.setInt(1); if(ch.CacheSize.equals("Small")) chcSize.setInt(2); if(ch.CacheSize.equals("Regular")) chcSize.setInt(3); if(ch.CacheSize.equals("Large")) chcSize.setInt(4); if(ch.CacheSize.equals("Other")) chcSize.setInt(5); if(ch.CacheSize.equals("Very Large")) chcSize.setInt(6); if(ch.CacheSize.equals("None")) chcSize.setInt(7); if(ch.CacheSize.equals("Not chosen")) chcSize.setInt(7); attV.showImages(ch.getCacheDetails(true).attributes); lblTerr.setText((ch.terrain.length()>0) ? (MyLocale.getMsg(1001,"T")+": "+ch.terrain) : ""); lblDiff.setText((ch.hard.length()>0) ? (MyLocale.getMsg(1000,"D")+": "+ch.hard) : ""); if(isBigScreen) mNotes.setText(ch.details.CacheNotes); } /** * Translate the cache type to the value in the cache type dropdown * control. */ private int transType(String type){ int c_type = 0; int tt = 0; tt = Convert.parseInt(type); switch(tt){ case 0: c_type = 0; break; case 2: c_type = 1; break; case 3: c_type = 2; break; case 4: c_type = 3; break; case 5: c_type = 4; break; case 6: c_type = 5; break; case 453: c_type = 6;break; case 8: c_type = 7; break; case 11: c_type = 8; break; //Earth case 12: c_type = 9; break; case 13: c_type = 10; break; case 137: c_type = 11;break; case 1858: c_type = 12; break; case 50: c_type = 13;break; case 51: c_type = 14;break; case 52: c_type = 15;break; case 53: c_type = 16;break; case 54: c_type = 17;break; case 55: c_type = 18;break; default: Vm.debug("Unknown cachetype: " + type); break; } return c_type; } /** * Method to translate a selected cache type in the drop down control * to a "true" cache type.<br> * This transformation is required to ease the display of the cache type * icon in the table display. */ public String transSelect(int num){ String ret = new String(""); switch(num){ case 0: ret = "0"; break; case 1: ret = "2"; break; case 2: ret = "3"; break; case 3: ret = "4"; break; case 4: ret = "5"; break; case 5: ret = "6"; break; case 6: ret = "453"; break; case 7: ret = "8"; break; case 8: ret = "11"; break; case 9: ret = "12"; break; case 10: ret = "13";break; case 11: ret = "137";break; case 12: ret = "1858"; break; case 13: ret = "50";break; case 14: ret = "51";break; case 15: ret = "52";break; case 16: ret = "53";break; case 17: ret = "54";break; case 18: ret = "55";break; default: Vm.debug("Unknown cachetype: " + num); break; } //switch return ret; } /** * if is addi -> returns the respective AddiWpt * if is main -> returns the respective MainWpt * */ public void createWptName() { String wpt = inpWaypoint.getText().toUpperCase(); if (CacheType.isAddiWpt(transSelect(chcType.getInt())) && (Global.mainTab.mainCache.startsWith("GC")||Global.mainTab.mainCache.startsWith("OC")||Global.mainTab.mainCache.startsWith("CW")) && wpt.startsWith("CW")) { // for what was this?: Global.mainTab.lastselected=Global.mainTab.mainCache; //I don't know exactly, but it's needed for creating a series of Addis inpWaypoint.setText(Global.getProfile().getNewAddiWayPointName(Global.mainTab.mainCache)); } if (!CacheType.isAddiWpt(transSelect(chcType.getInt())) && !(wpt.startsWith("GC") || wpt.startsWith("OC") || wpt.startsWith("CW")) ) { inpWaypoint.setText(Global.getProfile().getNewWayPointName()); } } /** * Method to react to a user input. */ public void onEvent(Event ev){ if (ev instanceof DataChangeEvent ) { if (ev.target == inpWaypoint) { // If user used lower case -> convert directly to upper case inpWaypoint.setText(inpWaypoint.getText().toUpperCase()); } dirty_details = true; needsTableUpdate = true; profile.hasUnsavedChanges=true; if (ev.target==chcType) { createWptName(); } } if(ev instanceof ControlEvent && ev.type == ControlEvent.PRESSED){ if(ev.target == btnNotes){ dirty_notes=true; // TODO I think this is redundant, because the notes are saved seperately by the notes screen itself NotesScreen nsc = new NotesScreen(thisCache.getCacheDetails(true)); nsc.execute(this.getFrame(), Gui.CENTER_FRAME); if(isBigScreen) mNotes.setText(thisCache.getCacheDetails(true).CacheNotes); } else if(ev.target == btnShowMap){ Global.mainTab.SwitchToMovingMap(thisCache.pos, true); /* try { MapDetailForm mdf = new MapDetailForm(thisCache.wayPoint, pref, profile); mdf.execute(); } catch (IllegalArgumentException e) { MessageBox tmp = new MessageBox(MyLocale.getMsg(321,"Error"), MyLocale.getMsg(322,"Kann Bild/Karte nicht finden")+": "+e.getMessage(), MessageBox.OKB); tmp.exec(); } */ } else if(ev.target == btnShowBug){ //InfoScreen is = new InfoScreen(thisCache.Travelbugs.toHtml(), "Travelbugs", false, pref); //is.execute(); TravelbugInCacheScreen ts = new TravelbugInCacheScreen(thisCache.getCacheDetails(true).Travelbugs.toHtml(), "Travelbugs"); ts.execute(this.getFrame(), Gui.CENTER_FRAME); } else if (ev.target == btnCenter){ CWPoint cp=new CWPoint(thisCache.LatLon); if (!cp.isValid()){ MessageBox tmpMB = new MessageBox(MyLocale.getMsg(312,"Error"), MyLocale.getMsg(4111,"Coordinates must be entered in the format N DD MM.MMM E DDD MM.MMM"), FormBase.OKB); tmpMB.exec(); } else { pref.curCentrePt.set(cp); Global.mainTab.updateBearDist(); } } else if (ev.target == btnAddDateTime){ dirty_notes=true; String note = thisCache.getCacheDetails(true).CacheNotes; Time dtm = new Time(); dtm.getTime(); dtm.setFormat("E dd.MM.yyyy '/' HH:mm"); if(note.length() > 0) note = note + "\n" + dtm.toString(); else note = note + dtm.toString(); note = note + "\n"; thisCache.getCacheDetails(true).CacheNotes = note; thisCache.getCacheDetails(true).saveCacheDetails( Global.getProfile().dataDir); } else if (ev.target == btnAddPicture){ thisCache.getCacheDetails(true).addUserImage(profile); } else if(ev.target == btnBlack){ if(thisCache.is_black) { thisCache.is_black = false; btnBlack.image = imgBlackNo; } else { thisCache.is_black = true; btnBlack.image = imgBlack; } blackStatus = thisCache.is_black; thisCache.setAttributesToAddiWpts(); btnBlack.repaintNow(); dirty_details=true; blackStatusChanged=true; } else if (ev.target == btnNewWpt){ CacheHolder ch = new CacheHolder(); ch.LatLon = thisCache.LatLon; ch.pos = new CWPoint( thisCache.pos ); ch.type = "51"; Global.mainTab.newWaypoint(ch); } else if (ev.target == btnGoto){ // TODO if something changed saveWpt(); Global.mainTab.gotoPoint(thisCache.pos); } else if (ev.target == btnWayLoc){ CWPoint coords = new CWPoint(btnWayLoc.getText(),CWPoint.CW); CoordsScreen cs = new CoordsScreen(true); cs.setFields(coords, CWPoint.CW); if (cs.execute()== FormBase.IDOK){ dirty_details=true; coords = cs.getCoords(); thisCache.pos.set(coords); btnWayLoc.setText(coords.toString()); thisCache.LatLon=coords.toString(); // If the current centre is valid, calculate the distance and bearing to it CWPoint centre=Global.getPref().curCentrePt; if (centre.isValid()) thisCache.calcDistance(centre); } } else if (ev.target==btnFoundDate) { //DateChooser.dayFirst=true; DateTimeChooser dc=new DateTimeChooser(Vm.getLocale()); dc.title=MyLocale.getMsg(328,"Date found"); dc.setPreferredSize(240,240); String foundDate=chcStatus.getText(); if (foundDate.startsWith(MyLocale.getMsg(318,"Found")+" ")) foundDate=foundDate.substring(MyLocale.getMsg(318,"Found").length()+1); Time t=new Time(); try { t.parse(foundDate,"y-M-d H:m"); } catch(IllegalArgumentException e) { try { t.parse(foundDate,"y-M-d"); } catch(IllegalArgumentException e1) {} }; dc.reset(t); if (dc.execute()==ewe.ui.FormBase.IDOK) { chcStatus.setText(MyLocale.getMsg(318,"Found")+" "+Convert.toString(dc.year)+"-"+MyLocale.formatLong(dc.month,"00")+"-"+MyLocale.formatLong(dc.day,"00")+" "+dc.time); dirty_details=true; profile.hasUnsavedChanges=true; } } else if (ev.target==btnHiddenDate) { DateChooser.dayFirst=true; DateChooser dc=new DateChooser(Vm.getLocale()); dc.title=MyLocale.getMsg(329,"Hidden date"); dc.setPreferredSize(240,240); if (inpHidden.getText().length()==10) try { dc.setDate(new Time( Convert.parseInt(inpHidden.getText().substring(8)), Convert.parseInt(inpHidden.getText().substring(5,7)), Convert.parseInt(inpHidden.getText().substring(0,4)))); } catch (NumberFormatException e) { dc.reset(new Time()); } if (dc.execute()==ewe.ui.FormBase.IDOK) { inpHidden.setText(Convert.toString(dc.year)+"-"+MyLocale.formatLong(dc.month,"00")+"-"+MyLocale.formatLong(dc.day,"00")); dirty_details=true; profile.hasUnsavedChanges=true; } } ev.consumed=true; } } public void saveDirtyWaypoint() { // We have to update two objects: thisCache (a CacheHolderDetail) which contains // the full cache which will be written to the cache.xml file AND // the CacheHolder object which sits in cacheDB // Strip the found message if the status contains a date if (chcStatus.getText().startsWith(MyLocale.getMsg(318,"Found")) && chcStatus.getText().length()>=MyLocale.getMsg(318,"Found").length()+11) thisCache.CacheStatus = chcStatus.getText().substring(MyLocale.getMsg(318,"Found").length()+1); else thisCache.CacheStatus = chcStatus.getText(); thisCache.is_found = chcStatus.getText().startsWith(MyLocale.getMsg(318,"Found")); thisCache.CacheOwner = inpOwner.getText().trim(); thisCache.is_owned = thisCache.CacheStatus.equals(MyLocale.getMsg(320,"Owner")); // Avoid setting is_owned if alias is empty and username is empty if(thisCache.is_owned == false){ thisCache.is_owned = (!pref.myAlias.equals("") && pref.myAlias.equals(thisCache.CacheOwner)) || (!pref.myAlias2.equals("") && pref.myAlias2.equals(thisCache.CacheOwner)); } thisCache.is_black = blackStatus; String oldWaypoint=thisCache.wayPoint; thisCache.wayPoint = inpWaypoint.getText().toUpperCase().trim(); thisCache.CacheSize = chcSize.getText(); // If the waypoint does not have a name, give it one if (thisCache.wayPoint.equals("")) { thisCache.wayPoint=profile.getNewWayPointName(); } //Don't allow single letter names=> Problems in updateBearingDistance // This is a hack but faster than slowing down the loop in updateBearingDistance if (thisCache.wayPoint.length()<2) thisCache.wayPoint+=" "; thisCache.CacheName = inpName.getText().trim(); thisCache.LatLon = thisCache.pos.toString(); thisCache.DateHidden = inpHidden.getText().trim(); String oldType=thisCache.type; thisCache.type = transSelect(chcType.getInt()); // thisCache.saveCacheDetails(profile.dataDir); // this is redundant, because all changes affecting the details are immediately saved // Now update the table CacheHolder ch = thisCache; // TODO variable ch is redundant /* The references have to be rebuilt if: * - the cachetype changed from addi->normal or normal->addi * - the old cachetype or the new cachetype were 'addi' and * the waypointname has changed */ if (CacheType.isAddiWpt(ch.type)!=CacheType.isAddiWpt(oldType) || ((CacheType.isAddiWpt(ch.type) || CacheType.isAddiWpt(oldType)) && !thisCache.wayPoint.equals(oldWaypoint))) { // If we changed the type to addi, check that a parent exists if (CacheType.isAddiWpt(ch.type)) { int idx; if (ch.wayPoint.length()<5) idx=-1; else { idx=profile.getCacheIndex("GC"+ ch.wayPoint.substring(ch.wayPoint.length() == 5?1:2)); if (idx<0) idx=profile.getCacheIndex("OC"+ ch.wayPoint.substring(ch.wayPoint.length() == 5?1:2)); if (idx<0) idx=profile.getCacheIndex("CW"+ ch.wayPoint.substring(ch.wayPoint.length() == 5?1:2)); if (idx<0) (new MessageBox(MyLocale.getMsg(144,"Warning"), MyLocale.getMsg(734,"No main cache found for addi waypoint ")+" "+ch.wayPoint+ "\n"+MyLocale.getMsg(735,"Addi Waypoints must have the format xxYYYY, where xx are any 2 chars and YYYY are the main cache's chars after the GC"),FormBase.OKB)).execute(); } profile.buildReferences(); // TODO this takes quite long -> use profile.setAddiRef instead } else { profile.buildReferences(); // we have to do this to release the link between the two caches } } // set status also on addi wpts ch.setAttributesToAddiWpts(); dirty_notes=false; dirty_details=false; setNeedsTableUpdate(false); if (thisCache.details != null) thisCache.details.hasUnsavedChanges = false; thisCache.getCacheDetails(true).hasUnsavedChanges = true; // Global.mainTab.tbP.refreshTable(); this is done in mainTab.onLeavingPanel ////Vm.debug("New status updated!"); } private class TravelbugInCacheScreen extends Form { private DispPanel disp = new DispPanel(); private mButton btCancel; private TravelbugJourneyList tbjList; TravelbugInCacheScreen(String text, String title) { this.setTitle(title); this.setPreferredSize(pref.myAppWidth, pref.myAppHeight); disp.setHtml(text); ScrollBarPanel sbp = new MyScrollBarPanel(disp, ScrollablePanel.NeverShowHorizontalScrollers); this.addLast(sbp); this.addLast(btCancel = new mButton(MyLocale.getMsg(3000,"Close")),CellConstants.DONTSTRETCH, CellConstants.FILL); } public void onEvent(Event ev){ if(ev instanceof ControlEvent && ev.type == ControlEvent.PRESSED){ if (ev.target == btCancel){ this.close(0); } } } // Subclassed HtmlDisplay with Pop-up menu private class DispPanel extends HtmlDisplay { MenuItem mnuPickupTB, mnuDropTB; MenuItem[] TBMenuItems=new MenuItem[2]; Menu mnuPopup; DispPanel() { TBMenuItems[0]= mnuPickupTB = new MenuItem(MyLocale.getMsg(6016,"Pick up Travelbug")); TBMenuItems[1]= mnuDropTB = new MenuItem(MyLocale.getMsg(6017,"Drop Travelbug")); mnuPopup=new Menu(TBMenuItems,""); } public void penRightReleased(Point p){ setMenu(mnuPopup); doShowMenu(p); // direct call (not through doMenu) is neccesary because it will exclude the whole table } public void penHeld(Point p){ setMenu(mnuPopup); doShowMenu(p); } public void popupMenuEvent(Object selectedItem){ if (selectedItem==mnuPickupTB) { Travelbug tb=TravelbugPickup.pickupTravelbug(thisCache.getCacheDetails(true).Travelbugs); if (tb!=null) { dirty_details=true; // Get the list of my travelbugs tbjList=new TravelbugJourneyList(); tbjList.readTravelbugsFile(); // Add the tb to this list tbjList.addTbPickup(tb,Global.getProfile().name,thisCache.wayPoint); tbjList.saveTravelbugsFile(); tbjList=null; setHtml(thisCache.getCacheDetails(true).Travelbugs.toHtml()); repaint(); thisCache.has_bug=thisCache.getCacheDetails(true).Travelbugs.size()>0; } } else if (selectedItem==mnuDropTB) { tbjList=new TravelbugJourneyList(); tbjList.readTravelbugsFile(); TravelbugList tbl=tbjList.getMyTravelbugs(); TravelbugScreen tbs=new TravelbugScreen(tbl,MyLocale.getMsg(6017,"Drop a travelbug"),false); tbs.execute(); if (tbs.selectedItem>=0) { Travelbug tb=tbl.getTB(tbs.selectedItem); thisCache.getCacheDetails(true).Travelbugs.add(tb); tbjList.addTbDrop(tb,Global.getProfile().name,thisCache.wayPoint); } tbjList.saveTravelbugsFile(); tbjList=null; thisCache.has_bug=thisCache.getCacheDetails(true).Travelbugs.size()>0; setHtml(thisCache.getCacheDetails(true).Travelbugs.toHtml()); repaint(); dirty_details=true; } else super.popupMenuEvent(selectedItem); } } } }
true
9af32567c969cd68719c708531ab200e0e45b141
Java
OpenVnmrJ/OpenVnmrJ
/src/vnmrj/src/vnmr/util/Undo.java
UTF-8
3,621
2.4375
2
[ "Apache-2.0", "GPL-3.0-only" ]
permissive
/* * Copyright (C) 2015 University of Oregon * * You may distribute under the terms of either the GNU General Public * License or the Apache License, as specified in the LICENSE file. * * For more information, see the LICENSE file. */ package vnmr.util; import vnmr.bo.*; import java.awt.*; import java.util.*; import java.awt.event.*; import java.io.*; import javax.swing.*; import javax.swing.undo.*; import javax.swing.event.*; import java.awt.Toolkit; /** * Title: Undo * Description: Utilty class that processes global undo events. * Does not need to be instantiated and contains only static methods. */ public class Undo { static UndoableEditSupport support=new UndoableEditSupport(); static UndoManager current=null; static UndoManager last=null; static KeyAdapter ka = new KeyAdapter() { public void keyPressed(KeyEvent e) { int modifiers = e.getModifiers(); int code=e.getKeyCode(); if(code==KeyEvent.VK_UNDO || (code==KeyEvent.VK_Z && e.isControlDown())){ if(current !=null){ if(e.isShiftDown()){ if(current.canRedo()) current.redo(); } else{ if(current.canUndo()) current.undo(); } } } } }; /** called by UndoableEditListeners */ public static synchronized void addUndoListener(UndoableEditListener m){ support.addUndoableEditListener(m); } /** called by UndoableEditListeners */ public static synchronized void removeUndoListener(UndoableEditListener m){ support.removeUndoableEditListener(m); } /** called by Undoable when a Undoable event is generated */ public static void postEdit(UndoableEdit anEdit){ support.postEdit(anEdit); } /** called by Undoable component on gained focus*/ public static void setUndoMgr(UndoManager m,Component c){ c.addKeyListener(ka); setUndoMgr(m); } /** called by Undoable on gained context */ public static void setUndoMgr(UndoManager m){ current=m; postEdit(m); } /** called by Undoable component on lost focus*/ public static void removeUndoMgr(UndoManager m,Component c){ if(m!=null){ c.removeKeyListener(ka); removeUndoMgr(m); } } /** called by Undoable on lost context */ public static void removeUndoMgr(UndoManager m){ if(m!=null){ support.removeUndoableEditListener(m); if(m==current){ last=current; current=null; } support.postEdit(new UndoManager()); } } /** called by UndoableEditListeners on undoableEditHappened */ public static UndoManager getCurrentUndoMgr(){ return current; } /** called by UndoableEditListeners on actionPerformed */ public static UndoManager getLastUndoMgr(){ return last; } /** called by UndoableEditListeners on focusGained */ public static void restoreLastUndoMgr(){ // note: A focus a gain for the Listener (e.g. undobutton) results in // a focus lost for the current Undoable. // This routine restores the Undo context to the last Undoable. if(current==null && last !=null){ current=last; support.postEdit(current); } } }
true
31b3005eb2e313c62b6b7a91d043c4d3699c7e94
Java
claveroJuan/Workspace
/Guia10/src/ejercicio3/Imprimible.java
WINDOWS-1252
478
3.015625
3
[]
no_license
/** * */ package ejercicio3; /** * @author JuanClavero * */ public interface Imprimible { public static void main (String[]args) { Libro libro = new Libro("el alquimista", "Antartica"); Revista revista = new Revista(5, "el caamo", "el feo"); libro.imprimible(); System.out.println("---------------------"); revista.imprimible(); } public void imprimible(); } /* * El mtodo imprimir, imprimira todos los atributos de la clase por consola. */
true
e9793e654895f26d1d2c4e6d03a3575b09cba27e
Java
shbaek/Android_Study
/SharedPrefrences/app/src/main/java/com/example/shbaek/sharedprefrences/MainActivity.java
UTF-8
1,631
2.4375
2
[]
no_license
package com.example.shbaek.sharedprefrences; import android.content.Context; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import java.io.IOException; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.shbaek.sharedprefrences", Context.MODE_PRIVATE); ArrayList<String> myTeam = new ArrayList<>(); myTeam.add("step1"); myTeam.add("step2"); myTeam.add("step3"); try { sharedPreferences.edit().putString("myTeam", ObjectSerializer.serialize(myTeam)).apply(); Log.i("This is the myTeam : ", ObjectSerializer.serialize(myTeam)); } catch (IOException e) { e.printStackTrace(); } ArrayList<String> newTeam = new ArrayList<>(); try{ newTeam = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("myTeam", ObjectSerializer.serialize(new ArrayList<String>()))); } catch(Exception e){ e.printStackTrace(); } Log.i("This is the newTeam : ", newTeam.toString()); // sharedPreferences.edit().putString("username", "shbaek").apply(); // String username = sharedPreferences.getString("username",""); // Log.i("This is the username : ", username); } }
true
c2952124182307b2145ad2024f536abdf58f7a7a
Java
eleshkova/labs_epam
/lab_6/src/main/java/pages/HomePage.java
UTF-8
2,970
2.171875
2
[]
no_license
package pages; import driver.Driver; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.apache.logging.log4j.Logger; import org.openqa.selenium.support.FindBy; import org.apache.logging.log4j.LogManager; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; import java.util.List; import java.util.concurrent.TimeUnit; public class MainPage extends Page{ private final Logger logger = LogManager.getRootLogger(); private final String BASE_URL = "http://www.lot.com/by/ru/; public MainPage(WebDriver webDriver) { super(webDriver); PageFactory.initElements(this.webDriver, this); } @FindBy(id="language-options") WebElement changeLanguageBtn; @FindBy(id = "gblang-selector") WebElement languageToChoose; @FindBy(id = "accessibility-options") WebElement changeContrastBtn; @FindBy(id = "enableHighContrast") WebElement enableHighContrastBtn; @FindBy(id = "departureAirport") WebElement depatureSelector; @FindBy(id = "destinationAirport") WebElement destinationSelector; @FindBy(css = "option[value='VIE']") private WebElement departurePicker; @FindBy(css = "option[value='KEF']") private WebElement destinationPicker; @FindBy(className = "hasDatepicker") private List <WebElement> flightDate; @FindBy(id = "submit-booker") private WebElement scheduleSubmitBtn; @FindBy(css = "option[href='#3']") private WebElement changeSlideBtn; @Override public void open() { webDriver.navigate().to(BASE_URL); logger.info("Home page opened"); } public void search(String date) { depatureSelector.click(); departurePicker.click(); logger.info("Departure airport chosen"); destinationSelector.click(); destinationPicker.click(); logger.info("Destination airport chosen"); flightDate.get(1).sendKeys(date); scheduleSubmitBtn.submit(); } public void changeLanguage(){ changeLangeageBtn.click(); logger.info("click on dropdown to change language"); languageToChoose.click(); Driver.getDriver().manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS); logger.info("language was chosen"); } public void chooseContrast(){ changeContrastBtn.click(); logger.info("click on dropdown to change contrast"); enableHighContrastBtn.click(); Driver.getDriver().manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS); logger.info("contrast was chosen"); } public void changeSlide(){ changeSlideBtn.click(); logger.info("click on pagination to change slide"); Driver.getDriver().manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS); logger.info("slide was changed"); } }
true
4c79e0fbcd0c298ce30d4eaadab74bac188c9af4
Java
EsupPortail/esup-stage
/src/main/java/org/esup_portail/esup_stage/model/ReponseSupplementaire.java
UTF-8
1,827
2.015625
2
[]
permissive
package org.esup_portail.esup_stage.model; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; @Entity @Table(name = "ReponseSupplementaire") public class ReponseSupplementaire { @EmbeddedId private ReponseSupplementaireId id; @JsonIgnore @ManyToOne @MapsId("idQuestionSupplementaire") @JoinColumn(name="idQuestionSupplementaire", nullable = false) private QuestionSupplementaire questionSupplementaire; @JsonIgnore @ManyToOne @MapsId("idConvention") @JoinColumn(name="idConvention", nullable = false) private Convention convention; @Lob private String reponseTxt; private Integer reponseInt; private Boolean reponseBool; public ReponseSupplementaireId getId() { return id; } public void setId(ReponseSupplementaireId id) { this.id = id; } public QuestionSupplementaire getQuestionSupplementaire() { return questionSupplementaire; } public void setQuestionSupplementaire(QuestionSupplementaire questionSupplementaire) { this.questionSupplementaire = questionSupplementaire; } public Convention getConvention() { return convention; } public void setConvention(Convention convention) { this.convention = convention; } public String getReponseTxt() { return reponseTxt; } public void setReponseTxt(String reponseTxt) { this.reponseTxt = reponseTxt; } public Integer getReponseInt() { return reponseInt; } public void setReponseInt(Integer reponseInt) { this.reponseInt = reponseInt; } public Boolean getReponseBool() { return reponseBool; } public void setReponseBool(Boolean reponseBool) { this.reponseBool = reponseBool; } }
true
fb485b7e4fdbfce264be79730a98f1e4eabccc56
Java
shimotakatani/game
/src/main/java/game/engine/actions/Impl/GenericGoapActionImpl.java
UTF-8
1,086
2.703125
3
[]
no_license
package game.engine.actions.Impl; import game.engine.Game; import game.engine.actions.ActionPrecondition; import game.engine.actions.GenericAction; import game.engine.actions.GenericGoapAction; import game.engine.objects.units.GenericUnit; /** * Абстрактный класс для действий GOAP * * create time 07.04.2018 * * @author nponosov */ public abstract class GenericGoapActionImpl extends GenericActionImpl implements GenericGoapAction { private ActionPrecondition precondition; private Double cost; @Override public void doAction(Game game, GenericUnit actor) { //Писать выполняемые действия сюда } public Double calcCost(Game game, GenericUnit actor){ //Здесь писать функцию стоимости, которая может зависеть от состояния мира и состояния актора действия cost = 1.0; return cost; } public boolean isAvailable(Game game, GenericUnit actor){ return true; } }
true
1099d2992183dd68804190cbddbd6a0248610a6b
Java
WesleyMoraes10/VendaSTC
/src/dao/DAOCliente.java
UTF-8
8,370
2.84375
3
[]
no_license
package DAO; import model.ModelCliente; import conexoes.ConexaoMySql; import java.util.ArrayList; import javax.swing.JOptionPane; /** * * @author Wesley */ public class DAOCliente extends ConexaoMySql { /** * grava Cliente * * @param ModelCliente return int */ public int salvarClienteDAO(ModelCliente modelCliente) { try { this.conectar(); return this.insertSQL("INSERT INTO tblcliente (" + "cli_nome," + "cli_endereco," + "cli_bairro," + "cli_cidade," + "cli_uf," + "cli_cep," + "cli_telefone," + "cli_numero" + ")VALUES (" + "'" + modelCliente.getCli_nome() + "'," + "'" + modelCliente.getCli_endereco() + "'," + "'" + modelCliente.getCli_bairro() + "'," + "'" + modelCliente.getCli_cidade() + "'," + "'" + modelCliente.getCli_uf() + "'," + "'" + modelCliente.getCli_cep() + "'," + "'" + modelCliente.getCli_telefone() + "'," + "'" + modelCliente.getCli_numero() + "'" + ");" ); } catch (Exception e) { e.printStackTrace(); return 0; } finally { this.fecharConexao(); } } /** * recupera Cliente * * @param cli_cod return ModelCliente */ public ModelCliente retornarClienteNomeConsumidorDAO() { ModelCliente modelCliente = new ModelCliente(); try { this.conectar(); this.executarSQL("SELECT * FROM tblcliente c\n" + "where c.cli_nome like 'CONSUMIDOR%'"); while (this.getResultSet().next()) { modelCliente.setCli_cod(this.getResultSet().getInt(1)); modelCliente.setCli_nome(this.getResultSet().getString(2)); modelCliente.setCli_endereco(this.getResultSet().getString(3)); modelCliente.setCli_bairro(this.getResultSet().getString(4)); modelCliente.setCli_cidade(this.getResultSet().getString(5)); modelCliente.setCli_uf(this.getResultSet().getString(6)); modelCliente.setCli_cep(this.getResultSet().getString(7)); modelCliente.setCli_telefone(this.getResultSet().getString(8)); modelCliente.setCli_numero(this.getResultSet().getInt(9)); } } catch (Exception e) { e.printStackTrace(); } finally { this.fecharConexao(); } return modelCliente; } public ModelCliente retornarClienteDAO(int cli_cod) { ModelCliente modelCliente = new ModelCliente(); try { this.conectar(); this.executarSQL("SELECT * FROM tblcliente c where c.cli_cod = '"+cli_cod+"';"); while (this.getResultSet().next()) { modelCliente.setCli_cod(this.getResultSet().getInt(1)); modelCliente.setCli_nome(this.getResultSet().getString(2)); modelCliente.setCli_endereco(this.getResultSet().getString(3)); modelCliente.setCli_bairro(this.getResultSet().getString(4)); modelCliente.setCli_cidade(this.getResultSet().getString(5)); modelCliente.setCli_uf(this.getResultSet().getString(6)); modelCliente.setCli_cep(this.getResultSet().getString(7)); modelCliente.setCli_telefone(this.getResultSet().getString(8)); modelCliente.setCli_numero(this.getResultSet().getInt(9)); } } catch (Exception e) { e.printStackTrace(); } finally { this.fecharConexao(); } return modelCliente; } /** * recupera uma lista de Cliente return ArrayList */ public ArrayList<ModelCliente> retornaListaClienteDAO() { ArrayList<ModelCliente> listamodelCliente = new ArrayList(); ModelCliente modelCliente = new ModelCliente(); try { this.conectar(); this.executarSQL("SELECT * FROM tblcliente;"); while (this.getResultSet().next()) { modelCliente = new ModelCliente(); modelCliente.setCli_cod(this.getResultSet().getInt(1)); modelCliente.setCli_nome(this.getResultSet().getString(2)); modelCliente.setCli_endereco(this.getResultSet().getString(3)); modelCliente.setCli_bairro(this.getResultSet().getString(4)); modelCliente.setCli_cidade(this.getResultSet().getString(5)); modelCliente.setCli_uf(this.getResultSet().getString(6)); modelCliente.setCli_cep(this.getResultSet().getString(7)); modelCliente.setCli_telefone(this.getResultSet().getString(8)); modelCliente.setCli_numero(this.getResultSet().getInt(9)); listamodelCliente.add(modelCliente); } } catch (Exception e) { e.printStackTrace(); } finally { this.fecharConexao(); } return listamodelCliente; } /** * atualiza Cliente * * @param modelCliente return boolean */ public boolean alterarClienteDAO(ModelCliente modelCliente) { try { this.conectar(); return this.executarUpdateDeleteSQL("UPDATE tblcliente SET " + "cli_nome = '" + modelCliente.getCli_nome() + "'," + "cli_endereco = '" + modelCliente.getCli_endereco() + "'," + "cli_bairro = '" + modelCliente.getCli_bairro() + "'," + "cli_cidade = '" + modelCliente.getCli_cidade() + "'," + "cli_uf = '" + modelCliente.getCli_uf() + "'," + "cli_cep = '" + modelCliente.getCli_cep() + "'," + "cli_telefone = '" + modelCliente.getCli_telefone() + "'," + "cli_numero = '" + modelCliente.getCli_numero() + "'" + " WHERE " + "cli_cod = '" + modelCliente.getCli_cod() + "'" + ";" ); } catch (Exception e) { e.printStackTrace(); //JOptionPane.showMessageDialog(null, "Erro ao cadastrar cliente!", "ERRO DAO ", JOptionPane.ERROR_MESSAGE); return false; } finally { this.fecharConexao(); } } /** * exclui Cliente * * @param cli_cod return boolean */ public boolean excluirClienteDAO(int cli_cod) { try { this.conectar(); return this.executarUpdateDeleteSQL( "DELETE FROM tblcliente " + " WHERE " + "cli_cod = '" + cli_cod + "'" + ";" ); } catch (Exception e) { e.printStackTrace(); return false; } finally { this.fecharConexao(); } } public ModelCliente retornarClienteDAO(String cli_nome) { ModelCliente modelCliente = new ModelCliente(); try { this.conectar(); this.executarSQL("SELECT * FROM tblcliente WHERE cli_nome = '" + cli_nome + "';"); while (this.getResultSet().next()) { modelCliente.setCli_cod(this.getResultSet().getInt(1)); modelCliente.setCli_nome(this.getResultSet().getString(2)); modelCliente.setCli_endereco(this.getResultSet().getString(3)); modelCliente.setCli_bairro(this.getResultSet().getString(4)); modelCliente.setCli_cidade(this.getResultSet().getString(5)); modelCliente.setCli_uf(this.getResultSet().getString(6)); modelCliente.setCli_cep(this.getResultSet().getString(7)); modelCliente.setCli_telefone(this.getResultSet().getString(8)); modelCliente.setCli_numero(this.getResultSet().getInt(9)); } } catch (Exception e) { e.printStackTrace(); } finally { this.fecharConexao(); } return modelCliente; } }
true
b3286d8c1d4fc1f9998eba9a6825ab3c3ed8dc09
Java
cloudwebsoft/ywoa
/c-core/src/main/java/com/cloudweb/oa/mapper/UserSetupMapper.java
UTF-8
486
1.976563
2
[]
no_license
package com.cloudweb.oa.mapper; import com.cloudweb.oa.entity.UserSetup; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Select; import java.util.List; /** * <p> * Mapper 接口 * </p> * * @author fgf * @since 2020-02-10 */ public interface UserSetupMapper extends BaseMapper<UserSetup> { @Select("select user_name from user_setup where myleaders like '%${userName}%'") List<String> getMySubordinates(String userName); }
true
6113e8c33e304cd24f665eaa37a19711848da312
Java
vinhqd/Lession-2
/src/Exercise/Rectangle.java
UTF-8
954
3.265625
3
[]
no_license
package Exercise; public class Rectangle { private double pointX; private double pointY; private double length; private double width; public Rectangle() { } public Rectangle(double pointX, double pointY, double length, double width) { this.pointX = pointX; this.pointY = pointY; this.length = length; this.width = width; } public double getPointX() { return pointX; } public void setPointX(double pointX) { this.pointX = pointX; } public double getPointY() { return pointY; } public void setPointY(double pointY) { this.pointY = pointY; } public double getLength() { return length; } public void setLength(double length) { this.length = length; } public double getWidth() { return width; } public void setWidth(double width) { this.width = width; } }
true
afbde28ca968856fdd72d36dff2821bd254aadb5
Java
abdev2019/Projet-MVC-Spring-Similar-
/src/main/java/projet/jee/web/UserController.java
UTF-8
1,364
2.453125
2
[]
no_license
package projet.jee.web; import java.util.Map; import projet.jee.entities.User; import projet.jee.framework.mvc.Controller; import projet.jee.idao.IUserDAO; public class UserController extends Controller { private IUserDAO dao; public String profile(Map<String, Object> model) { if( this.getSession().getAttribute("user") == null ) return "login"; this.getRequest().setAttribute( "user",getSession().getAttribute("user") ); return "profile"; } public String login(Map<String, Object> model) { if( this.getSession().getAttribute("user") != null ) { this.getRequest().setAttribute( "user",model.get("user") ); return "profile"; } if(this.getRequest().getMethod().equals("POST")) { String username = model.get("username").toString(); String password = model.get("password").toString(); User user = dao.findByUsernameAndPassword(username,password); if(user != null) { this.getSession().setAttribute("user", user); this.getRequest().setAttribute( "user",user ); return "profile"; } else { this.getRequest().setAttribute("errorLogin", true); return "login"; } } return "login"; } public String deconnecter(Map<String, Object> model) { this.getSession().removeAttribute("user"); return "login"; } public void setDao(IUserDAO dao) { this.dao = dao; } }
true
583c12f2ca3da91c73df8d28ca3737c97f6eae1f
Java
zenikd/project
/service/src/main/java/org/ez/vk/task/impl/point/task/VkSearch.java
UTF-8
918
1.882813
2
[]
no_license
package org.ez.vk.task.impl.point.task; import org.ez.vk.entity.db.reservable.AccountVk; import com.vk.api.sdk.client.VkApiClient; import com.vk.api.sdk.exceptions.ApiException; import com.vk.api.sdk.exceptions.ClientException; import com.vk.api.sdk.httpclient.HttpTransportClient; public class VkSearch { protected final static VkApiClient vk = new VkApiClient(HttpTransportClient.getInstance()); public static void sleep(int count, AccountVk accountVk) { for (int i = 0; i < count; i++) { try { vk.wall().get(accountVk.getUserActor()).execute(); try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (ApiException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
true
86f490f973ffd947fae89bd56ddf8dcaac2de9fd
Java
zhaozhenghao1993/zh-admin
/zh-admin-server/src/main/java/com/zhenghao/admin/server/annotation/SysLog.java
UTF-8
2,481
2.875
3
[ "MIT" ]
permissive
package com.zhenghao.admin.server.annotation; import com.zhenghao.admin.common.enums.LogTypeEnum; import java.lang.annotation.*; /** * 系统日志注解 * * @SysLog("里面写内容,必须赋值到value属性中") author:zhaozhenghao * Email :736720794@qq.com * date :2017年11月20日 * SysLog.java */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface SysLog { String value() default ""; LogTypeEnum type() default LogTypeEnum.OPERATION; } /** * @Target说明了Annotation所修饰的对象范围: Annotation可被用于 packages、types(类、接口、枚举、Annotation类型) * 、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。 * 在Annotation类型的声明中使用了target可更加明晰其修饰的目标。 * 作用:用于描述注解的使用范围(即:被描述的注解可以用在什么地方) * 取值(ElementType)有: * <p> *     1.CONSTRUCTOR:用于描述构造器 *     2.FIELD:用于描述域 *     3.LOCAL_VARIABLE:用于描述局部变量 *     4.METHOD:用于描述方法 *     5.PACKAGE:用于描述包 *     6.PARAMETER:用于描述参数 *     7.TYPE:用于描述类、接口(包括注解类型) 或enum声明 * @Retention定义了该Annotation被保留的时间长短:某些Annotation仅出现在源代码中, 而被编译器丢弃;而另一些却被编译在class文件中;编译在class文件中的Annotation可能会被虚拟机忽略, * 而另一些在class被装载时将被读取(请注意并不影响class的执行,因为Annotation与class在使用上是被分离的)。 * 使用这个meta-Annotation可以对 Annotation的“生命周期”限制。 * <p> * 作用:表示需要在什么级别保存该注释信息,用于描述注解的生命周期(即:被描述的注解在什么范围内有效) *  取值(RetentionPoicy)有: * <p> *     1.SOURCE:在源文件中有效(即源文件保留) *     2.CLASS:在class文件中有效(即class保留) *     3.RUNTIME:在运行时有效(即运行时保留) * <p> * <p> *  @Documented用于描述其它类型的annotation应该被作为被标注的程序成员的公共API, * 因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。 */
true
891d78ed666e8f55417b26cafabe7602f123f0bd
Java
MrPopiette/CalculMental
/src/dal/UserDAO.java
UTF-8
1,338
2.6875
3
[]
no_license
package dal; import bo.User; import java.sql.*; import java.util.List; public class UserDAO extends DataAccessObjectJDBC<User>{ private static final String AUTHENT_QUERY = "SELECT * FROM user WHERE login = ? AND password = ?"; public User authenticate(String login, String password) throws SQLException{ User user = null; try (Connection connection = DriverManager.getConnection(dbUrl, dbLogin, dbPwd); PreparedStatement ps = connection.prepareStatement(AUTHENT_QUERY)){ ps.setString(1, login); ps.setString(2, password); try (ResultSet rs = ps.executeQuery()){ if(rs.next()){ user = new User(); user.setLogin(rs.getString("login")); user.setPassword(rs.getString("password")); user.setNbConnections(rs.getInt("connections") + 1); user.setId(rs.getInt("id")); } } } return user; } public UserDAO(String dbUrl, String dbLogin, String dbPwd) { super(dbUrl, dbLogin, dbPwd); } @Override public void create(User object) { } @Override public List<User> findAll() { return null; } @Override public User findById() { return null; } }
true
d7cd77deee3e8f86c4e117ee00368018f4013942
Java
aryanbansal499/BikeLock
/Bike3/app/src/main/java/e/aryan/bike3/MainActivity.java
UTF-8
4,530
2.21875
2
[]
no_license
package e.aryan.bike3; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.media.MediaPlayer; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; import com.firebase.client.Firebase; import static e.aryan.bike3.R.color.locked_green; public class MainActivity extends AppCompatActivity implements SensorEventListener { Button lockUnlockBtn; ImageButton lockImage; boolean flag = false; TextView tv; private Sensor mySensor; private SensorManager SM; View view; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Firebase.setAndroidContext(this); //Div awesomeness here on SM = (SensorManager) getSystemService(SENSOR_SERVICE); mySensor = SM.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); SM.registerListener(this, mySensor, SensorManager.SENSOR_DELAY_NORMAL); // bike = new BikeInfo(); lockUnlockBtn = findViewById(R.id.btn1); lockImage = findViewById(R.id.Ibtn); tv = findViewById(R.id.tv1); lockUnlockBtn.setVisibility(View.INVISIBLE); lockImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { BikeInfo info = new BikeInfo(); if (flag == false) { info.setLockStatus("LOCKED"); lockImage.setImageResource(R.drawable.l1); lockUnlockBtn.setVisibility(View.VISIBLE); tv.setText("Bike is Locked"); info.refreshInfo(); //v.setBackgroundColor(getResources().getColor(R.color.locked_green)); View pv = (View) v.getParent(); pv.setBackgroundColor(getResources().getColor(R.color.locked_green)); flag = true; } else{ info.setLockStatus("UN-LOCKED"); lockImage.setImageResource(R.drawable.l2); tv.setText("Bike is Unlocked"); View pv = (View) v.getParent(); pv.setBackgroundColor(getResources().getColor(R.color.unlocked)); // v.setBackgroundColor(getResources().getColor(R.color.unlocked)); lockUnlockBtn.setVisibility(View.INVISIBLE); flag = false; } } }); } @Override public void onSensorChanged(SensorEvent event) { BikeInfo info = new BikeInfo(); info.refreshInfo(); if(BikeInfo.alertStatus != null) { if (BikeInfo.alertStatus.equals("PANIC")) { setAlertStatus("PANIC"); } else if (BikeInfo.alertStatus.equals("OK")) { setAlertStatus("OK"); } } info.finalize(); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } public void setAlertStatus(String status) { Button stopSiren = findViewById(R.id.button4); MediaPlayer siren = MediaPlayer.create(this, R.raw.alarm); if(status.equals("PANIC")) { view = this.getWindow().getDecorView(); view.setBackgroundResource(R.color.colorAccent); if (BikeInfo.sironStatus.equals("ON")) { siren.start(); } stopSiren.setOnClickListener(new View.OnClickListener() { MediaPlayer siren = MediaPlayer.create(view.getContext(), R.raw.alarm); @Override public void onClick(View v) { siren.stop(); BikeInfo info = new BikeInfo(); info.setAlarm("OFF"); } }); } else if(status.equals("SUSP")) { view = this.getWindow().getDecorView(); //view.setBackgroundResource(R.color.yellow); siren.stop(); } else if(status.equals("OK")) { view = this.getWindow().getDecorView(); view.setBackgroundResource(R.color.unlocked); siren.stop(); } } }
true
bcd8fe605b40a28ec0c19d99e0894e9366113783
Java
AvinaAccount/Coupon-System-Stage_1
/src/data/ex/ReturnCouponsException.java
UTF-8
229
2.34375
2
[]
no_license
package data.ex; /** * Exception to throw message if Unable to return coupons. */ public class ReturnCouponsException extends Exception { public ReturnCouponsException(String msg) { super(msg); } }
true
da0338c288d385896bd9c43df5a6f273d1de037f
Java
jihoonx/9th_Assignment
/Scribble.java
UHC
1,127
3.40625
3
[]
no_license
package 9th_Assignment; import java.awt.*; import java.awt.event.*; import javax.swing.*; class MyPanel4 extends JPanel implements MouseMotionListener{ private int index = 0; Point[] array = new Point[1000]; public MyPanel4() { this.addMouseMotionListener(this); } public void mouseDragged(MouseEvent e){ //콺 Ŭ ϶ int x = e.getX(); int y = e.getY(); if(index > 1000) return; array[index] = new Point(); array[index].x = x; array[index].y = y; index++; repaint(); } public void mouseMoved(MouseEvent e){} //콺 ϶(Ŭx) public void paintComponent(Graphics g){ super.paintComponent(g); for(Point p : array){ if(p != null) g.drawRect(p.x, p.y, 1,1); //x,yġ 1*1 簢 ׸ } } } public class Scribble extends JFrame{ public Scribble() { setSize(300,300); setTitle("콺 ׸ ׸"); add(new MyPanel4()); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { new Scribble(); } }
true
00a4e5a12f2c956d2625f1ec52c0ba0ee220cc73
Java
bhavya5/StringCalculator
/src/com/string/StringCalculatorTest4.java
UTF-8
289
2.546875
3
[]
no_license
package com.string; import java.util.Scanner; import org.junit.Assert; import org.junit.Test; public class StringCalculatorTest4{ @Test public final void whenDelimiterIsSpecifiedThenItIsUsedToSeparateNumbers() { Assert.assertEquals(3+6+15, StringCalculator4.add("//;n3;6;15")); } }
true
ac9bec892bed47f6ffc4478ae71a6e33b2a7ae2a
Java
elascano/ESPE202105-OOP-TC-3730
/workshops/chiliquingab/unit3/WS28Strategy/SortingAlgoritms/src/ec/edu/espe/controller/QuickSort.java
UTF-8
1,715
3
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 ec.edu.espe.controller; import utils.SortingStrategy; /** * * @author Bryan Chiliquinga Beta_Software ESPE-DCCO */ public class QuickSort implements SortingStrategy { @Override public int[] sort(int[] data) { //TODO program the sort algorithm //sort the data and return //System.out.println("ordering " + data + "], using Quick sort"); int[] sortedData = data; //this is only here to complete quicksort(data, 0, 10); imprimeArreglo(data); return sortedData; } public static void quicksort(int[] data, int izq, int der) { int pivote = data[izq]; int i = izq; int j = der; int swap; while (i < j) { while (data[i] <= pivote && i < j) { i++; } while (data[j] > pivote) { j--; } if (i < j) { swap = data[i]; data[i] = data[j]; data[j] = swap; //imprimeArreglo(data); } } data[izq] = data[j]; data[j] = pivote; if (izq < j - 1) { quicksort(data, izq, j - 1); } if (j + 1 < der) { quicksort(data, j + 1, der); } } public void imprimeArreglo(int[] data) { System.out.print("Sorted using Quick sort["); for (int i = 0; i < data.length; i++) { System.out.print(data[i] + "-"); } System.out.println("] "); } }
true
608d6b2796573a099f1b58e1103da67c050cf691
Java
yeongwei/AndroidSpecialisation-course3-week4-assignment1
/app/src/androidTest/java/edu/vandy/mooc/aad_3_assg_3/All_IntegrationTests_Suites.java
UTF-8
687
1.695313
2
[]
no_license
package edu.vandy.mooc.aad_3_assg_3; import org.junit.runner.RunWith; import org.junit.runners.Suite; import edu.vandy.mooc.aad_3_assg_3.misc.SanityTest_InstrumentedTest; import edu.vandy.mooc.aad_3_assg_3.suites.Orm_IntegrationTests_Suite; import edu.vandy.mooc.aad_3_assg_3.suites.Provider_IntegrationTests_Suite; /** * */ // Runs all unit tests. @SuppressWarnings("unused") @RunWith(Suite.class) @Suite.SuiteClasses({ // just a sanity check to make sure integration tests running properly SanityTest_InstrumentedTest.class, Provider_IntegrationTests_Suite.class, Orm_IntegrationTests_Suite.class, }) public class All_IntegrationTests_Suites { }
true
9758388b2070e3174b2fdc34035dc215ec3b60aa
Java
Tomoki-0526/IMapp
/back-end/src/main/java/com/tsinghua/course/Base/CustomizedClass/MsgItem.java
UTF-8
2,753
2.265625
2
[]
no_license
package com.tsinghua.course.Base.CustomizedClass; import org.springframework.data.mongodb.core.mapping.Document; /** * @描述 消息项 */ @Document("MsgItem") public class MsgItem { // 消息id String msgId; // 发送人 String username; // 发送人昵称 String nickname; // 发送人备注 String remark; // 发送人头像 String avatar; // 发送时间 String sendTime; // 是不是由自己发出的 boolean fromMyself; // 消息类型 int type; // 文本内容 String text; // 图片 String image; // 音频 String audio; // 视频 String video; // 经度 double longitude; // 纬度 double latitude; public String getMsgId() { return msgId; } public void setMsgId(String msgId) { this.msgId = msgId; } public String getSendTime() { return sendTime; } public void setSendTime(String sendTime) { this.sendTime = sendTime; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public void setFromMyself(boolean fromMyself) { this.fromMyself = fromMyself; } public boolean isFromMyself() { return fromMyself; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getAudio() { return audio; } public void setAudio(String audio) { this.audio = audio; } public String getVideo() { return video; } public void setVideo(String video) { this.video = video; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } }
true
2bff80f28a437e8c52738ea048db1bde631fc3ee
Java
AndrewTseZhou/KFGit
/app/src/main/java/com/andrewtse/kfgit/presenter/StarredPresenter.java
UTF-8
3,372
2.140625
2
[]
no_license
package com.andrewtse.kfgit.presenter; import android.util.Log; import com.andrewtse.kfgit.contract.IStarredContract; import com.andrewtse.kfgit.data.api.RepoApi; import com.andrewtse.kfgit.model.StarredModel; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import io.reactivex.Observable; import io.reactivex.ObservableSource; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; /** * @author xk * @date 2019/2/19 */ public class StarredPresenter extends BaseRepoPresenter<IStarredContract.IStarredView> { private static final String TAG = "StarredPresenter"; @Inject public StarredPresenter(RepoApi starredApi) { super(starredApi); } public void loadMyStarred(String token, int page, int perPage) { mRepoApi.loadMyStarred(token, page, perPage) .retryWhen(throwableObservable -> throwableObservable.flatMap((Function<Throwable, ObservableSource<?>>) throwable -> { Log.d(TAG, "apply: throwable: " + throwable.toString()); if (throwable instanceof IOException) { if (mCurrentRetryCount < mMaxConnectCount) { mCurrentRetryCount++; mWaitRetryTime = 1000 + mCurrentRetryCount * 1000; Log.d(TAG, "apply: mCurrentRetryCount = " + mCurrentRetryCount + ", mWaitRetryTime = " + mWaitRetryTime); return Observable.just(1).delay(mWaitRetryTime, TimeUnit.MILLISECONDS); } else { Log.d(TAG, "apply: 重试次数已超过设置次数"); return Observable.error(new Throwable("开小差了")); } } else { Log.d(TAG, "apply: 发生了非IO异常"); return Observable.error(new Throwable("开小差了")); } })) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe(disposable -> getBaseView().showLoading()) .doOnTerminate(() -> getBaseView().dismissLoading()) .subscribe(new Observer<List<StarredModel>>() { @Override public void onSubscribe(Disposable d) { Log.d(TAG, "onSubscribe: " + d); mCompositeDisposable.add(d); } @Override public void onNext(List<StarredModel> starredModels) { Log.d(TAG, "onNext: " + starredModels); getBaseView().showContent(starredModels); } @Override public void onError(Throwable e) { Log.d(TAG, "onError: " + e.toString()); getBaseView().showError(e); } @Override public void onComplete() { Log.d(TAG, "onComplete: "); } }); } }
true
e375d99f641af51c79d47d86655ea2c0346cbeb8
Java
refresh6724/APS
/Jungol/Lv1_LanguageCoder/01 출력/Main_JO_101_형성평가1.java
UTF-8
159
2
2
[]
no_license
public class Main_JO_101_형성평가1 { // 제출일 2020-12-29 23:15 public static void main(String[] args) { System.out.println("My name is Hong"); } }
true
79cf28d4c2196b7077b764019f67a9e365ce2d87
Java
belajarkuy11/dbgenerate
/src/main/java/com/generate/dbgenerate/model/Matpel.java
UTF-8
1,151
2.28125
2
[]
no_license
package com.generate.dbgenerate.model; import java.io.Serializable; import javax.persistence.*; import java.util.List; /** * The persistent class for the matpel database table. * */ @Entity @NamedQuery(name="Matpel.findAll", query="SELECT m FROM Matpel m") public class Matpel implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; private String nama; //bi-directional many-to-one association to Guru @OneToMany(mappedBy="matpelBean") private List<Guru> gurus; public Matpel() { } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getNama() { return this.nama; } public void setNama(String nama) { this.nama = nama; } public List<Guru> getGurus() { return this.gurus; } public void setGurus(List<Guru> gurus) { this.gurus = gurus; } public Guru addGurus(Guru gurus) { getGurus().add(gurus); gurus.setMatpelBean(this); return gurus; } public Guru removeGurus(Guru gurus) { getGurus().remove(gurus); gurus.setMatpelBean(null); return gurus; } }
true
5994ebe5284d814221bd8ac7bb640ada7299ec7f
Java
NicholasMaestrello/treinamento-impacta
/DesenvolvimentoJava/Modulo04/01_SpringWeb/src/br/com/seniorsolution/jdbc/CursoMapper.java
UTF-8
895
2.296875
2
[]
no_license
package br.com.seniorsolution.jdbc; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.RowMapper; import br.com.seniorsolution.entidades.Curso; public class CursoMapper implements RowMapper<Curso> { @Override public Curso mapRow(ResultSet rs, int arg1) throws SQLException { Curso curso = new Curso(); curso.setId(rs.getInt("ID")); curso.setDescricao(rs.getString("DESCRICAO")); ApplicationContext ctx = new ClassPathXmlApplicationContext("beanJdbc.xml"); JdbcEscolaDao escolaDao = (JdbcEscolaDao) ctx.getBean("jdbcEscolaDao"); try { curso.setEscola(escolaDao.buscarEscola(rs.getInt("IDESCOLA"))); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return curso; } }
true
cffbb66e068a4dc3ab75f0fac9dab7d4a585c304
Java
thaond/nsscttdt
/src/ext-lltnxp/ext-impl/src/com/sgs/portlet/pmllevelsend/service/impl/PmlEdmLevelSendLocalServiceImpl.java
UTF-8
5,564
2.046875
2
[]
no_license
package com.sgs.portlet.pmllevelsend.service.impl; import java.util.ArrayList; import java.util.List; import com.liferay.portal.PortalException; import com.liferay.portal.SystemException; import com.liferay.portal.kernel.util.OrderByComparator; import com.sgs.portlet.document.receipt.model.PmlEdmDocumentReceipt; import com.sgs.portlet.document.receipt.model.PmlEdmDocumentType; import com.sgs.portlet.pmllevelsend.PmlEdmLevelSendCanNotDeleteException; import com.sgs.portlet.pmllevelsend.model.PmlEdmLevelSend; import com.sgs.portlet.document.receipt.model.PmlEdmLevelSendDetail; import com.sgs.portlet.pmllevelsend.service.impl.PmlEdmLevelSendLocalServiceImpl; import com.sgs.portlet.document.receipt.service.persistence.PmlEdmDocumentReceiptUtil; import com.sgs.portlet.document.receipt.service.persistence.PmlEdmDocumentTypeUtil; import com.sgs.portlet.document.receipt.service.persistence.PmlEdmLevelSendDetailUtil; import com.sgs.portlet.pmlissuingplace.model.PmlEdmIssuingPlace; import com.sgs.portlet.pmlissuingplace.service.persistence.PmlEdmIssuingPlaceUtil; import com.sgs.portlet.pmllevelsend.service.base.PmlEdmLevelSendLocalServiceBaseImpl; /** * @author lethanhtung * */ public class PmlEdmLevelSendLocalServiceImpl extends PmlEdmLevelSendLocalServiceBaseImpl { /** * get all issue place with concrete level send *@param levelSendId * @return List<PmlEdmIssuingPlace> * */ public List<PmlEdmIssuingPlace> getPmlEdmIssuingPlacesWithPmlEdmLevelSend(int levelSendId) { List<PmlEdmIssuingPlace> resultList = new ArrayList<PmlEdmIssuingPlace>(); try { List<PmlEdmLevelSendDetail> pmlEdmLevelSendDetailList = PmlEdmLevelSendDetailUtil.findByLevelSendId(levelSendId); if(pmlEdmLevelSendDetailList != null && pmlEdmLevelSendDetailList.size() > 0) { for (PmlEdmLevelSendDetail pmlEdmLevelSendDetail : pmlEdmLevelSendDetailList) { resultList.add(PmlEdmIssuingPlaceUtil.findByPrimaryKey(pmlEdmLevelSendDetail.getIssuingPlaceId())); } } } catch (Exception e) { System.out.println("ERROR: in method getPmlEdmIssuingPlacesWithPmlEdmLevelSend "+PmlEdmLevelSendLocalServiceImpl.class); System.out.println(e.getMessage()); e.printStackTrace(); } return resultList; } /** * get all document type with concrete documentRecordTo * @param documentRecordId * @return List<PmlEdmDocumentType> * */ public List<PmlEdmDocumentType> getPmlEdmDocumentTypesWithPmlEdmDocumentRecordTo() { List<PmlEdmDocumentType> resultList = new ArrayList<PmlEdmDocumentType>(); try { } catch (Exception e) { System.out.println("ERROR: in method getPmlEdmDocumentTypesWithPmlEdmDocumentRecordTo "+PmlEdmLevelSendLocalServiceImpl.class); System.out.println(e.getMessage()); e.printStackTrace(); } return resultList; } /** * get all document type with concrete document record type * @param documentRecordTypeId * @return List<PmlEdmDocumentType> * */ public List<PmlEdmDocumentType> getPmlEdmDocumentTypeWithPmlEdmDocumentRecordType(int documentRecordTypeId){ List<PmlEdmDocumentType> resultList = new ArrayList<PmlEdmDocumentType>(); try { resultList = PmlEdmDocumentTypeUtil.findByDocumentRecordTypeId(documentRecordTypeId); } catch (Exception e) { System.out.println("ERROR: in method getPmlEdmDocumentTypesWithPmlEdmDocumentRecordTo "+PmlEdmLevelSendLocalServiceImpl.class); System.out.println(e.getMessage()); e.printStackTrace(); } return resultList; } /** * get number document receipt * @param documentRecordId * @return String * */ public String getNumberDocumentReceipt(long documentRecordId) { String numberResult = null; try { } catch (Exception e) { e.printStackTrace(); } return numberResult; } /** * Lay tat ca level send * @return * @throws SystemException */ public List<PmlEdmLevelSend> getAll() throws SystemException { try { return pmlEdmLevelSendPersistence.findAll(); } catch (Exception ex) { return null; } } public List<PmlEdmLevelSend> findByLevelSendIds( List<Integer> levelSendIds) throws Exception { try { return pmlEdmLevelSendFinder.findByLevelSendIds(levelSendIds); } catch (Exception ex) { return null; } } // minh 20100206 public int searchCount(String keywords) throws SystemException{ return pmlEdmLevelSendFinder.countByKeywords(keywords); } public List<PmlEdmLevelSend> search(String keywords, int start, int end, OrderByComparator obc) throws SystemException{ return pmlEdmLevelSendFinder.findByKeywords(keywords, start, end, obc); } // end // yenlt update 23082010 protected void validatePmlEdmLevelSend(int documentReceiptSize, int levelSendDetailSize) throws PortalException, SystemException { if (documentReceiptSize != 0) { throw new PmlEdmLevelSendCanNotDeleteException(); } if (levelSendDetailSize != 0) { throw new PmlEdmLevelSendCanNotDeleteException(); } } public void removePmlEdmLevelSend(int levelSendId) throws SystemException, PortalException { List<PmlEdmDocumentReceipt> pmlEdmDocumentReceiptList = PmlEdmDocumentReceiptUtil.findByLevelSendId(levelSendId); List<PmlEdmLevelSendDetail> pmlEdmLevelSendDetailList = PmlEdmLevelSendDetailUtil.findByLevelSendId(levelSendId); int documentReceiptSize = pmlEdmDocumentReceiptList.size(); int levelSendDetailSize = pmlEdmLevelSendDetailList.size(); validatePmlEdmLevelSend(documentReceiptSize, levelSendDetailSize); pmlEdmLevelSendPersistence.remove(levelSendId); } // end yenlt }
true
1acf3bb4147fe107be13da74fc8b4b68baee8943
Java
srxctalia/mvcpenjualan
/src/main/java/com/mvc/dao/MstBarangDao.java
UTF-8
865
1.960938
2
[]
no_license
package com.mvc.dao; import java.util.List; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import com.mvc.entity.MstBarang; import com.mvc.entity.MstBarangPK; public interface MstBarangDao extends JpaRepository<MstBarang, MstBarangPK>{ @Query("select a,b.namaSupplier from MstBarang a, MstSupplier b " + "where a.kodeSupplier = b.kodeSupplier " + "AND (a.kodeBarang like %:cari% or a.namaBarang like %:cari% " + "or b.namaSupplier like %:cari%)") public List<Object[]> search(@Param("cari") String cari, Pageable pageable); @Query("select count(a.kodeBarang) from MstBarang a " + "where a.kodeBarang like %:cari%") public int countData(@Param("cari") String cari); }
true
a96ded6f2096afdf1d01e7fae8047a64ee6e3f5c
Java
honsontran/Blackjack-Project
/BlackjackGUI.java/Hand.java
UTF-8
1,835
3.8125
4
[]
no_license
// This class represents the set of cards held by one player (or the dealer). public class Hand { // define fields here public static int value = 0; public static int softhand = 0; public Card[] hand; // This constructor builds a hand (with no cards, initially). public Hand() { this.hand = new Card[20]; //Hand value is generously big enough to hold cards. for (int i = 0; i < hand.length; i++) { hand[i] = null; } } // This method retrieves the size of this hand. public int getNumberOfCards(){ int numCards = 0; for (int i = 0; i < this.hand.length; i++) { if (this.hand[i] != null) { numCards++; } } return numCards; } // This method retrieves a particular card in this hand. The card number is zero-based. public Card getCard(int index){ return this.hand[index]; } // This method takes a card and places it into this hand. public void addCard(Card newcard){ for(int i = 0; i < this.hand.length; i++){ if(this.hand[i] == null){ this.hand[i] = newcard; break; } } } // This method computes the score of this hand. public int getScore(){ int total = 0; //This adds the normal value without aces. for(int i = 0; i < this.hand.length; i++){ if(hand[i] != null){ total += hand[i].getValue(); } } //Find aces. If there is, set a boolean to use the next loop. boolean ace = false; for(int i = 0; i < hand.length;i++){ if(hand[i] != null){ if(hand[i].getFace() == 1){ ace = true; } } } //If ace is true, display this value instead of the one without aces. if(ace == true && total + 10 <= 21){ total += 10; } return total; }//end addScore() // This methods discards all cards in this hand. public void discardAll(){ for (int i = 0; i < hand.length; i++){ this.hand[i] = null; } } }
true
2a2e21ae243fbd7047105942aa0e8d4bd44c2407
Java
agjycxys/online-answering-system-ssm
/src/main/java/com/agjycxys/mapper/TiMuMapper.java
UTF-8
331
1.8125
2
[]
no_license
package com.agjycxys.mapper; import com.agjycxys.domain.TiMu; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface TiMuMapper { public List<TiMu> queryTiMuAll(); public void addTiMu(TiMu timu); public void editTiMu(TiMu timu); public void delTiMu(int tmid); }
true
99fe4e5697285c6cd0a9dadf4c39e4def78ce504
Java
BKJang/jobQ
/src/main/java/egovframework/example/admin/cmmn/jqgrid/JobqJqGridSearchTemplate.java
UTF-8
2,321
2.171875
2
[]
no_license
package egovframework.example.admin.cmmn.jqgrid; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.JsonObject; import egovframework.example.admin.cmmn.board.BoardSearch; import egovframework.example.admin.cmmn.board.BoardSelect; public abstract class JobqJqGridSearchTemplate { private static final Logger logger = LoggerFactory.getLogger(JobqJqGridSearchTemplate.class); private BoardSearch boardSearch; private BoardSelect boardSelect; private JobqJqGridConvertorTemplate jobqJqGridConvertorTemplate; public JobqJqGridSearchTemplate(BoardSearch boardSearch, BoardSelect boardSelect, JobqJqGridConvertorTemplate jobqJqGridConvertorTemplate) { super(); this.boardSearch = boardSearch; this.boardSelect = boardSelect; this.jobqJqGridConvertorTemplate = jobqJqGridConvertorTemplate; } public final JsonObject search(Map<String, Object> searchInfo) throws Exception{ int row = Integer.parseInt((String) searchInfo.get("rows")); int page = Integer.parseInt((String)searchInfo.get("page")); calculatePage(searchInfo); int allData = boardSelect.countAllList(); int countSearchedData = boardSearch.countSearchedData(searchInfo); int searchedPages = countSearchPage(countSearchedData, row); JsonObject object = jobqJqGridConvertorTemplate.convertDataToJqGridJson(page, boardSearch.search(searchInfo), row, allData, searchedPages); object.add("userData", makeTotalCountAndSearchedCount(allData, countSearchedData)); return object; } protected abstract JsonObject makeTotalCountAndSearchedCount(int allData, int countSearchedData); private int countSearchPage(int page, int row) { return page % row == 0 ? page / row : ( page / row ) + 1 ; } private void calculatePage(Map<String, Object> searchInfo){ int page = Integer.parseInt((String)searchInfo.get("page")); int row = Integer.parseInt((String)searchInfo.get("rows")); String startPage = String.valueOf(((page - 1) * row) + 1); String endPage = String.valueOf(page * row); searchInfo.put("startPage", startPage); searchInfo.put("endPage", endPage); } public void setJobqJqGridConvertorTemplate(JobqJqGridConvertorTemplate jobqJqGridConvertorTemplate) { this.jobqJqGridConvertorTemplate = jobqJqGridConvertorTemplate; } }
true
e0e4635ecea8039ee5adf0282948e1bc443da5c6
Java
dustyewer/design-pattern
/singleton/src/test/java/yewer/singleton/LoadBalancerTest.java
UTF-8
912
2.90625
3
[]
no_license
package yewer.singleton; import org.junit.Test; public class LoadBalancerTest { @Test public void test01() { LoadBalancer balancer01, balancer02, balancer03, balancer04; balancer01 = LoadBalancer.getLoadBalancer(); balancer02 = LoadBalancer.getLoadBalancer(); balancer03 = LoadBalancer.getLoadBalancer(); balancer04 = LoadBalancer.getLoadBalancer(); if (balancer01 == balancer02 && balancer02 == balancer03 && balancer03 == balancer04) { System.out.println("服务器负载均衡具有唯一性"); } balancer01.addServer("server 1"); balancer01.addServer("server 2"); balancer02.addServer("server 3"); balancer04.addServer("server 4"); for (int i = 0; i < 10; i++) { String server = balancer01.getServer(); System.out.println("分发到 "+server); } } }
true
fcecb43782ae5a88c95987875b4e1525df24945b
Java
Hai9527/emp
/EMP_CW/src/com/fmlditital/emp/music/MusicActivity.java
UTF-8
6,098
1.710938
2
[]
no_license
package com.fmlditital.emp.music; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.Html; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import com.fmlditital.emp.PageActivity; import com.fmlditital.emp.R; import com.fmlditital.emp.async.AsyncImage; import com.fmlditital.emp.async.AsyncJson; import com.fmlditital.emp.async.AsyncRefreshJson; import com.fmlditital.emp.base.AdapterViewActivity; import com.fmlditital.emp.base.DefaultActivity; import com.fmlditital.emp.config.Confi; import com.fmlditital.emp.dowmload.DownloadActivity; import com.fmlditital.emp.interf.ImageLoadCallback; import com.fmlditital.emp.model.MusicModel; import com.fmlditital.emp.preferences.SettingActivity; import com.fmlditital.emp.tool.Tools; import com.fmlditital.emp.tool.ViewFactory; import com.fmlditital.emp.tool.ViewFactory.AdapterSelect; public class MusicActivity extends AdapterViewActivity { private AsyncImage asyncImage = null; private ImageView imageView = null; private static final int REFRESH = Menu.FIRST; private static final int DOWNLOAD = Menu.FIRST + 1; private static final int SETTING = Menu.FIRST + 2; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); data = app.getDataMusic(); data.clear(); adapter = ViewFactory .getDataAdapter(this, AdapterSelect.musickey, data); adapterView = ViewFactory.getAdapterView(this, AdapterSelect.musickey); adapterView.setAdapter(adapter); imageView = new ImageView(this); imageView.setLayoutParams(new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, Tools.dip2px(this, 182))); imageView.setScaleType(ScaleType.FIT_XY); bodyLayout.addView(imageView); bodyLayout.addView(adapterView); dataUrl = Confi.getInstance().getMusicApiUrl(tid); // System.out.println("music url= =========== "+dataUrl); asyncJson = new AsyncJson(this); asyncJson.addInterFace(this); asyncJson.execute(dataUrl); adapterView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(MusicActivity.this, MusicDetailActivity.class); Bundle bundle = new Bundle(); bundle.putString("tabName", title); bundle.putInt("index", position); bundle.putString("tid", tid); intent.putExtras(bundle); MusicActivity.this.startActivity(intent); } }); } public void callJoinSuccess(String url, JSONObject json) { super.callJoinSuccess(url, json); if (url.equals(dataUrl)) { data.clear(); try { JSONArray jsonArray = json.getJSONArray("datas"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i); if (jsonObject2.getString("music_status").equals("1")) { MusicModel model = new MusicModel(); model.setId(jsonObject2.getString("music_id")); model.setTitle(jsonObject2.getString("music_title")); model.setThumb(jsonObject2.getString("music_thumb")); model.setUrl(jsonObject2.getString("music_url")); model.setAuthor(jsonObject2.getString("msinger")); model.setIsDownload(jsonObject2.getString("download")); model.setDescription(Html.fromHtml( jsonObject2.getString("music_caption")) .toString()); // System.out.println("music_caption ========== :"+Html.fromHtml( // jsonObject2.getString("music_caption")) // .toString()); data.add(model); adapter.notifyDataSetChanged(); } } if (data.size() > 0) { asyncImage = new AsyncImage(); asyncImage.addImageLoadCallback(this); asyncImage.execute(((MusicModel) data.get(0)).getThumb()); } } catch (JSONException e) { callJoinFailure(dataUrl, e.getMessage().toString()); } } } public void callImageSuccess(String url, Drawable drawable) { super.callImageSuccess(url, drawable); imageView.setBackgroundColor(this.getResources() .getColor(R.color.black)); if (data.size()>0 && url.equals(((MusicModel) data.get(0)).getThumb())) { if (drawable != null) imageView.setImageDrawable(drawable); else imageView.setImageResource(R.drawable.music_cover); } } public void callImageFailure(String url) { // TODO Auto-generated method stub } public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, REFRESH, 0, getResources().getString(R.string.refresh)) .setIcon(android.R.drawable.ic_popup_sync); menu.add(0, DOWNLOAD, 0, getResources().getString(R.string.download)) .setIcon(android.R.drawable.stat_sys_download_done); menu.add(0, SETTING, 0, getResources().getString(R.string.setting)) .setIcon(android.R.drawable.ic_menu_preferences); return true; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case REFRESH: { // asyncImage = new AsyncImage(); // asyncImage.addImageLoadCallback(this); // asyncImage.execute(((MusicModel) data.get(0)).getThumb()); asyncJson = new AsyncJson(this); asyncJson.addInterFace(this); asyncJson.execute(dataUrl); } break; case DOWNLOAD: { Intent intent = new Intent(MusicActivity.this, DownloadActivity.class); //intent.putExtra("tabName", "Download"); intent.putExtra("tabName", "下载"); MusicActivity.this.startActivity(intent); } break; case SETTING: { Intent intent = new Intent(MusicActivity.this, SettingActivity.class); intent.putExtra("tabName", "Setting"); MusicActivity.this.startActivity(intent); } break; } return true; } }
true
844416286aa232fcf8a59c0965defb18c3b50162
Java
aghasyedbilal/intellij-community
/platform/platform-impl/src/com/intellij/openapi/wm/impl/content/ContentLayout.java
UTF-8
2,597
1.976563
2
[ "Apache-2.0" ]
permissive
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.wm.impl.content; import com.intellij.openapi.ui.popup.ListPopup; import com.intellij.openapi.util.NlsActions.ActionText; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentManager; import com.intellij.ui.content.ContentManagerEvent; import com.intellij.util.ui.JBUI; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; abstract class ContentLayout { ToolWindowContentUi myUi; BaseLabel myIdLabel; ContentLayout(@NotNull ToolWindowContentUi ui) { myUi = ui; } public abstract void init(@NotNull ContentManager contentManager); public abstract void reset(); public abstract void layout(); public abstract void paintComponent(Graphics g); public abstract void update(); public abstract void rebuild(); public abstract int getMinimumWidth(); public abstract void contentAdded(ContentManagerEvent event); public abstract void contentRemoved(ContentManagerEvent event); protected void updateIdLabel(BaseLabel label) { String title = myUi.window.getStripeTitle(); String suffix = getTitleSuffix(); if (suffix != null) title += suffix; label.setText(title); label.setBorder(JBUI.Borders.empty(0, 2, 0, 7)); label.setVisible(shouldShowId()); } private String getTitleSuffix() { ContentManager manager = myUi.getContentManager(); switch (manager == null ? 0 : manager.getContentCount()) { case 0: return null; case 1: Content content = manager.getContent(0); if (content == null) return null; final String text = content.getDisplayName(); if (text != null && text.trim().length() > 0 && manager.canCloseContents()) { return ":"; } return null; default: return ":"; } } public abstract void showContentPopup(ListPopup listPopup); @ActionText public abstract String getCloseActionName(); @ActionText public abstract String getCloseAllButThisActionName(); @ActionText public abstract String getPreviousContentActionName(); @ActionText public abstract String getNextContentActionName(); protected boolean shouldShowId() { JComponent component = myUi.window.getComponentIfInitialized(); return component != null && !"true".equals(component.getClientProperty(ToolWindowContentUi.HIDE_ID_LABEL)); } boolean isIdVisible() { return myIdLabel.isVisible(); } }
true
3b636213fe05bd3ed659a904f2afa9ae8ebcc27c
Java
monikabiskup/topairplanes
/src/main/java/com/topairplanes/springboot/topairplanes/service/BiggestAircraftServiceImpl.java
UTF-8
804
2.15625
2
[]
no_license
package com.topairplanes.springboot.topairplanes.service; import com.topairplanes.springboot.topairplanes.dao.BiggestAircraftRepository; import com.topairplanes.springboot.topairplanes.entity.BiggestAircraft; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class BiggestAircraftServiceImpl implements BiggestAircraftService { private BiggestAircraftRepository biggestAircraftRepository; @Autowired public BiggestAircraftServiceImpl(BiggestAircraftRepository theBiggestAircraftRepository) { this.biggestAircraftRepository = theBiggestAircraftRepository; } @Override public List<BiggestAircraft> findAll() { return biggestAircraftRepository.findAll(); } }
true
a22b1d16fca27f93bcb5ac2211f7616507af7a93
Java
McClone/fashionj
/dubbo-example/src/main/java/com/example/service/DemoService.java
UTF-8
110
1.617188
2
[ "Apache-2.0" ]
permissive
package com.example.service; /** * @author zhengsd */ public interface DemoService { String test(); }
true
617f5f675ff3079daaf5083ee7d0303855d7b22d
Java
v-venes/FZL_Estrutura-de-Dados
/ED_Ex06_FilaEncadeada/src/collection/FilaEncadeada.java
UTF-8
1,269
3.09375
3
[]
no_license
package collection; import java.util.NoSuchElementException; import model.Pessoa; public class FilaEncadeada { private int tamanho; private No primeiro; private No ultimo; public FilaEncadeada() { this.tamanho = -1; this.primeiro = (No) null; this.ultimo = (No) null; } public void adicionar(Pessoa pessoa) { if (!estaVazia()) { No novoNo = new No(pessoa); ultimo.setAnterior(novoNo); ultimo = novoNo; } else { No novoNo = new No(pessoa); primeiro = novoNo; ultimo = novoNo; } tamanho++; } public Pessoa remover() { Pessoa primeiroFila = (Pessoa) null; try { primeiroFila = primeiro.getPessoa(); primeiro = primeiro.getAnterior(); tamanho--; } catch (NoSuchElementException e) { e.printStackTrace(); } return primeiroFila; } public Pessoa cortar() { Pessoa primeiroFila = (Pessoa) null; if (!estaVazia()) { if (tamanho > 0) { primeiroFila = primeiro.getPessoa(); primeiro = primeiro.getAnterior(); tamanho--; } } else { System.out.println("Fila vazia!!"); } return primeiroFila; } public Pessoa getPrimeiro() { return primeiro.getPessoa(); } public boolean estaVazia() { return (tamanho == -1); } public int getTamanho() { return (tamanho + 1); } }
true