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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
15ab1bf64d0f98a88b09ee56fbf835409e6bea3b | Java | Kutty39/WebApps | /SpringMvc/src/main/java/com/blbz/springmvc/controller/controller.java | UTF-8 | 4,434 | 2.359375 | 2 | [] | no_license | package com.blbz.springmvc.controller;
import com.blbz.springmvc.model.LoginDetail;
import com.blbz.springmvc.model.ProfileDetail;
import com.blbz.springmvc.model.RegDetail;
import com.blbz.springmvc.model.UserSession;
import com.blbz.springmvc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
@Controller
@SessionAttributes("UserSession")
public class controller {
@Autowired
RegDetail regDetail;
@Autowired
LoginDetail loginDetail;
@Autowired
UserService userService;
@Autowired
ProfileDetail profileDetail;
@Autowired
UserSession userSession;
ModelAndView mv = new ModelAndView();
/* @RequestMapping(method = RequestMethod.GET)
public String setupForm(Model model)
{
model.addAttribute("regForm", userInfo);
return "index";
}*/
@ModelAttribute("regForm")
public RegDetail createRegForm() {
return regDetail;
}
@ModelAttribute("lgnForm")
public LoginDetail createLgnForm() {
return loginDetail;
}
@ModelAttribute("prfForm")
public ProfileDetail createPfrForm() {
return profileDetail;
}
@ModelAttribute("UserSession")
public UserSession createSnForm() {
return userSession;
}
/* @InitBinder
public void initBinder(WebDataBinder dataBinder) {
StringTrimmerEditor stringTrimmerEditor = new StringTrimmerEditor(true);
dataBinder.registerCustomEditor(String.class, stringTrimmerEditor);
}
*/
/*
Another way to create Model attribute
@RequestMapping("/switchpage")
public String pageNav(@RequestParam String page, Model model) {
if(page.equals("register")){
model.addAttribute("regForm", userInfo);
}
return page;
}*/
@RequestMapping("/")
public ModelAndView index() {
mv.addObject("user", userSession.getUser());
mv.setViewName("index");
return mv;
}
@RequestMapping("/switchpage")
public ModelAndView pageNav(@RequestParam String page) {
mv.addObject("user", userSession.getUser());
if (page.equals("logout")) {
mv.clear();
userSession.setUser(null);
}
mv.setViewName(page);
return mv;
}
/*BindingResult is for form validation validation
@NotNull
@Size
@Min
@Max
@Email
@Pattern
@NotEmpty
above is the validation we can pass Error in the jsp for using Form:Error tag
*/
@PostMapping("/regestration")
public ModelAndView register(/*@Valid */@ModelAttribute("regForm") RegDetail regDetail/*, BindingResult theBindingResult*/) {
/* if (theBindingResult.hasErrors()) {
return "register";
}*/
/* System.out.println(userDetail);
System.out.println(userDetail.createUser());*/
if (userService.register(regDetail.createUser())) {
mv.addObject("regsucs", "success");
loginDetail.setEmail(regDetail.getEid());
mv.setViewName("login");
} else {
mv.setViewName("register");
}
regDetail.setPas("");
regDetail.setConpas("");
return mv;
}
@PostMapping("/login")
public ModelAndView login(@ModelAttribute("lgnForm") LoginDetail loginDetail) {
if (userService.login(loginDetail) != null) {
profileDetail = profileDetail.createProfile(userService.login(loginDetail));
userSession.setUser(loginDetail.getEmail());
mv.setViewName("userprof");
} else {
mv.addObject("regsucs", "error");
mv.setViewName("login");
}
loginDetail.setPas("");
return mv;
}
@RequestMapping("/validate")
@ResponseBody
public String emailvalidator(@RequestParam String email) {
return String.valueOf(userService.validater(email));
}
@RequestMapping("/update")
@ResponseBody
public String updateDetail(@ModelAttribute("prfForm") ProfileDetail profileDetail) {
if (userService.update(profileDetail.createUser())) {
profileDetail.setPas("");
return "Updated Successfully";
} else {
return "Somthing went wrong. Try to update again!!";
}
}
}
| true |
131d4e3c878102a05585962ea60bdfb53376480e | Java | williamsSoftwareLimited/MRSLMaintenanceV1.0 | /app/src/main/java/org/codebehind/mrslmaintenance/ReportNewActivity.java | UTF-8 | 2,359 | 2.171875 | 2 | [] | no_license | package org.codebehind.mrslmaintenance;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import org.codebehind.mrslmaintenance.Abstract.ActionBarActivityBase;
import org.codebehind.mrslmaintenance.Entities.Report;
import org.codebehind.mrslmaintenance.Models.ReportDbModel;
import org.codebehind.mrslmaintenance.Models.ReportEquipParamsDbModel;
public class ReportNewActivity extends ActionBarActivityBase {
public static final String REPORT_BUNDLE="REPORT_NEW_ACTIVITY_REPORT_BUNDLE",
NEW_REPORT="New Report",
EDIT_REPORT="Edit Report";
private Report _report;
@Override
protected void onCreate(Bundle savedInstanceState) {
FragmentTransaction fragmentTransaction;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report_new);
if (savedInstanceState != null) return; // if ths has been created before then don't recreate
_report = (Report)getIntent().getSerializableExtra(REPORT_BUNDLE);
if (_report.getId()<0) setTitle(NEW_REPORT);
else setTitle(EDIT_REPORT);
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.activity_report_new_container, ReportNewFragment.newInstance(_report));
fragmentTransaction.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_report_new, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id;
ReportDbModel model;
id = item.getItemId();
switch(id) {
case R.id.menu_report_new_save:
Toast.makeText(ReportNewActivity.this, "Report saved.", Toast.LENGTH_SHORT).show();
model=new ReportDbModel(this, new ReportEquipParamsDbModel(this));
if (_report.getId()<0) {
model.add(_report);
}else{
model.update(_report);
}
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
| true |
bdaec20d8ea1190fa028a5827c1f46fc8748da25 | Java | Realovka/Lesson_7_task_1 | /src/com/company/Ground.java | UTF-8 | 971 | 3.375 | 3 | [] | no_license | package com.company;
public class Ground extends Transport {
private int numberOfWheels;
private int fuelConsumption;
public Ground(int power, int maxSpeed, int weight, String model, int numberOfWheels, int fuelConsumption) {
super(power, maxSpeed, weight, model);
this.numberOfWheels = numberOfWheels;
this.fuelConsumption = fuelConsumption;
}
public int getNumberOfWheels() {
return numberOfWheels;
}
public void setNumberOfWheels(int numberOfWheels) {
this.numberOfWheels = numberOfWheels;
}
public int getFuelConsumption() {
return fuelConsumption;
}
public void setFuelConsumption(int fuelConsumption) {
this.fuelConsumption = fuelConsumption;
}
@Override
public void description() {
super.description();
System.out.print("кол-во колес: "+numberOfWheels+", расход топлива: "+fuelConsumption+", ");
}
}
| true |
c5a92021469abd4ac7d4bf0b4702c224a2cf26d0 | Java | cckmit/erp-4 | /Maven_Accounting_Libs/mavenAccCommonLibs/src/main/java/com/krawler/accounting/integration/common/IntegrationDAO.java | UTF-8 | 1,233 | 1.757813 | 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.krawler.accounting.integration.common;
import com.krawler.common.service.ServiceException;
import com.krawler.spring.common.KwlReturnObject;
import com.krawler.utils.json.base.JSONObject;
import java.util.List;
/**
*
* @author krawler
* DAO Interface for Third Party Service Integration.
* All common methods used in Integration should be put here.
* Methods from this interface can be used by all Integration services for example AvalaraIntegrationService, UpsIntegrationService.
*/
public interface IntegrationDAO {
public void saveOrUpdateIntegrationAccountDetails(JSONObject paramsJobj) throws ServiceException;
public KwlReturnObject getIntegrationAccountDetails(JSONObject paramsJobj) throws ServiceException;
public List getTransactionDetailTaxMapping(JSONObject paramsJobj) throws ServiceException;
public void saveTransactionDetailTaxMapping(JSONObject paramsJobj) throws ServiceException;
public void deleteTransactionDetailTaxMapping(JSONObject paramsJobj) throws ServiceException;
}
| true |
c651c1a02faaf43b959367f37cae6e227bdaa8be | Java | zzk2020/jianzixing-wechat | /src/main/java/com/jianzixing/webapp/template/JZXUrl.java | UTF-8 | 3,764 | 2.125 | 2 | [] | no_license | package com.jianzixing.webapp.template;
import org.mimosaframework.core.utils.RequestUtils;
import freemarker.ext.servlet.HttpRequestHashModel;
import freemarker.template.SimpleScalar;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import org.apache.commons.lang.StringUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@FreemarkerComponent("JZXUrl")
public class JZXUrl implements TemplateMethodModelEx {
@Override
public Object exec(List arguments) throws TemplateModelException {
if (arguments != null && arguments.size() > 0) {
Object arg0 = arguments.get(0);
if (arg0 instanceof HttpRequestHashModel) {
HttpRequestHashModel hashModel = (HttpRequestHashModel) arg0;
if (arguments.size() > 1) {
String url = arguments.get(1).toString();
if (url.equals("$")) {
return RequestUtils.getCurrentUrl(hashModel.getRequest());
} else if (url.equals("$$")) {
try {
return URLEncoder.encode(RequestUtils.getCurrentUrl(hashModel.getRequest()), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
if (url.startsWith("http://")) {
return url;
}
if (url.startsWith("local://")) {
return RequestUtils.getWebUrl(hashModel.getRequest()) + "/" + url.substring("local://".length());
}
return RequestUtils.getWebUrl(hashModel.getRequest()) + url;
}
} else {
return RequestUtils.getWebUrl(hashModel.getRequest());
}
}
if (arg0 instanceof SimpleScalar) {
String cmd = arg0.toString();
if (cmd.equals("&") || cmd.equals("&&")) {
if (arguments.size() > 1) {
String url = arguments.get(1).toString();
try {
url = URLDecoder.decode(url, "UTF-8");
url = url.trim();
if (arguments.size() > 3) {
String key = arguments.get(2).toString();
String value = arguments.get(3).toString();
if (StringUtils.isNotBlank(key)) {
if (url.indexOf("?") > 0) {
Map<String, String> map = RequestUtils.getUrlParams(url);
map.put(key.trim(), value.trim());
url = RequestUtils.replaceUrlParams(url, map);
} else {
url += "?" + key + "=" + value;
}
}
}
if (cmd.equals("&&")) {
return URLEncoder.encode(url, "UTF-8");
}
return url;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
}
return "";
}
}
| true |
82c56a83fc810a9b301f35887955aeae1cfb620a | Java | Spartak3/Final-OOP-Project | /fExam/src/service/ConeService.java | UTF-8 | 1,550 | 3.046875 | 3 | [] | no_license | package service;
import model.Cone;
import model.Cube;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ConeService {
public static List<Cone> createConesFromFile(List<String> list){
list.remove(0);
String sNums[];
List<Cone> coneList=new ArrayList<>();
for(String nums:list){
sNums=nums.split(",");
coneList.add(new Cone(Integer.parseInt(sNums[0]),Integer.parseInt(sNums[1])));
}
return coneList;
}
public static List<Cone> createConeManual(int shapeCount){
Scanner scanner=new Scanner(System.in);
List<Cone> listCone=new ArrayList<>();
int side,radius;
for (int i=0;i<shapeCount;i++){
System.out.printf("Type side and radius for %d Cone\n",i+1);
System.out.printf("Side-");
side=scanner.nextInt();
System.out.printf("Radius-");
radius=scanner.nextInt();
listCone.add(new Cone(side,radius));
}
return listCone;
}
public static void writeConesInFile(String path,List<Cone> cones) throws IOException {
StringBuilder stringBuilder=new StringBuilder("");
for (int i=0;i<cones.size();i++){
stringBuilder.append(cones.get(i).toString()).append("\n");
}
Files.write(Paths.get(path),stringBuilder.toString().getBytes());
}
}
| true |
4e47f2aad8a82b5f37e123903f209967558ebb9a | Java | dkbalachandar/grizzly-rest-custom-injection | /src/main/java/com/CustomerService.java | UTF-8 | 415 | 2.671875 | 3 | [] | no_license | package com;
public class CustomerService {
public Customer getCustomerById(String id) {
//This is a sample code to know how can we implement the custom injection so I am returning some default value
Customer customer = new Customer();
customer.setId(id);
customer.setFirstName("first name");
customer.setLastName("last name");
return customer;
}
}
| true |
c0aefb7a8defb91cccc8cc098d80c032b2a546e9 | Java | Dimitvp/Java-Fundamentals | /JavaSyntaxHomework/src/_10_ExtractWords.java | UTF-8 | 603 | 3.375 | 3 | [] | no_license | import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class _10_ExtractWords {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String text = input.nextLine();
Pattern pattern = Pattern.compile("([A-Za-z]+)");
Matcher matches = pattern.matcher(text);
ArrayList<String> lastWords = new ArrayList<>();
while(matches.find()){
lastWords.add(matches.group(1));
}
lastWords.forEach(w -> System.out.print(w + " "));
}
}
| true |
fe6526a85d9ba856a6c66d4da2fd7111b0461280 | Java | hongquang1799/OOP-111557 | /src/data/Agreement.java | UTF-8 | 238 | 2.09375 | 2 | [] | no_license | package data;
public class Agreement extends Entity {
public Agreement() {
}
public Agreement(String id, String name, String description) {
super(id, name, description);
}
public Agreement(Agreement copy) {
super(copy);
}
}
| true |
64464a4e1396cf84f3b110b89a35b4f0fd416914 | Java | Sushmithasmurthy/fun_with_algorithms | /src/test/java/com/ss/leetcode/easy/BinarySearchTest.java | UTF-8 | 1,588 | 2.859375 | 3 | [] | no_license | package com.ss.leetcode.easy;
import org.testng.annotations.Test;
public class BinarySearchTest {
BinarySearch bs;
public BinarySearchTest(){
bs = new BinarySearch();
}
@Test
public void testSingleNumberSameAsTarget(){
assert bs.search(new int[]{1}, 1) == 0;
}
@Test
public void testSingleNumberDifferentFromTarget(){
assert bs.search(new int[]{1}, -1) == -1;
}
@Test
public void testWhenThereArePositiveAndNegativeNumsAndTargetIsFound(){
assert bs.search(new int[]{-9999,-8988,-3434, 0, 1000,1001,2000,4000,8000,9000,9001,9002,9003,9004,9008}, -3434) == 2;
}
@Test
public void testWhenThereArePositiveAndNegativeNumsAndTargetIsNotFound(){
assert bs.search(new int[]{-9999,-8988,-3434, 0, 1000,1001,2000,4000,8000,9000,9001,9002,9003,9004,9099}, 9080) == -1;
}
@Test
public void testWhenThereAreOnlyPositiveNumsAndTargetIsFound(){
assert bs.search(new int[]{ 0, 1000,1001,2000,4000,8000,9000,9001,9002,9003,9004,9099}, 4000) == 4;
}
@Test
public void testWhenThereAreOnlyPositiveNumsAndTargetIsNotFound(){
assert bs.search(new int[]{ 0, 1000,1001,2000,4000,8000,9000,9001,9002,9003,9004,9099}, 22) == -1;
}
@Test
public void testWhenThereAreOnlyNegativeNumsAndTargetIsFound(){
assert bs.search(new int[]{-9999,-8988,-3434, -23,-10,-2}, -9999) == 0;
}
@Test
public void testWhenThereAreOnlyNegativeNumsAndTargetIsNotFound(){
assert bs.search(new int[]{-9999,-8988,-3434, -23,-10,-2}, -34) == -1;
}
}
| true |
cfa65ea30adb902882aa25eba4c7d5aba94c9808 | Java | mostafa0232/2018 | /src/org/usfirst/frc/team6417/robot/commands/LiftRobotUpTeleoperated.java | UTF-8 | 1,081 | 2.3125 | 2 | [] | no_license | package org.usfirst.frc.team6417.robot.commands;
import org.usfirst.frc.team6417.robot.OI;
import org.usfirst.frc.team6417.robot.Robot;
import org.usfirst.frc.team6417.robot.RobotMap;
import edu.wpi.first.wpilibj.command.Command;
public final class LiftRobotUpTeleoperated extends Command {
int interval = 100;
int counter = 0;
public LiftRobotUpTeleoperated() {
requires(Robot.liftingUnit);
}
@Override
protected void execute() {
System.out.println("LiftRobotUpTe-----leoperated.execute()");
double y = OI.getInstance().liftingUnitController.getY();
if(Math.abs(y) <= RobotMap.JOYSTICK.DEADZONES.JOYSTICK1_Y) {
y = 0.0;
}
y *= -1;
if(y > 0.0) {
Robot.liftingUnit.moveNoHoldPosition(y);
}else {
if(counter % interval == 0) {
System.out.println("LU not allowed go go up only down");
counter = 0;
}
counter++;
}
}
@Override
protected boolean isFinished() {
return false;
}
@Override
protected void end() {
System.out.println("LiftRobotUpTeleoperated.end()");
}
}
| true |
695895f5a70ff3ac22726db5936a202449b5dbd6 | Java | adiffpirate/estudos | /qa/testes-web-irts01/src/main/java/pages/HomePage.java | UTF-8 | 2,272 | 2.5 | 2 | [
"MIT"
] | permissive | package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.ArrayList;
import java.util.List;
public class HomePage {
List<WebElement> listaProdutos = new ArrayList();
private WebDriver driver;
private By produtos = By.className("product-description");
private By textoProdutosNoCarrinho = By.className("cart-products-count");
private By descricoesDosProdutos = By.cssSelector(".product-description a");
private By precoDosProdutos = By.className("price");
private By botaoSignIn = By.cssSelector("#_desktop_user_info span.hidden-sm-down");
private By usuarioLogado = By.cssSelector("#_desktop_user_info span.hidden-sm-down");
public HomePage(WebDriver driver) {
this.driver = driver;
}
public int contarProdutos(){
carregarListaProdutos();
return listaProdutos.size();
}
private void carregarListaProdutos(){
listaProdutos = driver.findElements(produtos);
}
public int obterQuantidadeProdutosNoCarrinho(){
String quantidadeProdutosNoCarrinho = driver.findElement(textoProdutosNoCarrinho).getText();
quantidadeProdutosNoCarrinho = quantidadeProdutosNoCarrinho.replace("(", "");
quantidadeProdutosNoCarrinho = quantidadeProdutosNoCarrinho.replace(")","");
int qtdProdutosNoCarrinho = Integer.parseInt(quantidadeProdutosNoCarrinho);
return qtdProdutosNoCarrinho;
}
public String obterNomeProduto(int indice){
return driver.findElements(descricoesDosProdutos).get(indice).getText().toLowerCase();
}
public String obterPrecoProduto(int indice){
return driver.findElements(precoDosProdutos).get(indice).getText();
}
public ProdutoPage clicarProduto(int indice){
driver.findElements(descricoesDosProdutos).get(indice).click();
return new ProdutoPage(driver);
}
public LoginPage clicarBotaoSignIn(){
driver.findElement(botaoSignIn).click();
return new LoginPage(driver);
}
public boolean estaLogado(String texto){
return texto.contentEquals(driver.findElement(usuarioLogado).getText());
}
}
| true |
051fed0735d29b6ad425936b3fa00fc3459d2388 | Java | IgorKonovalovAleks/Lotopo | /app/src/main/java/com/igorvenv/lotopo/GameField.java | UTF-8 | 4,810 | 2.3125 | 2 | [] | no_license | package com.igorvenv.lotopo;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.util.Random;
public class GameField extends SurfaceView implements SurfaceHolder.Callback {
public static final int FOG = 0;
public static final int PLAYER = 1;
public static final int HEDGEHOG = 2;
public static final int DRAGON = 3;
public static final int ITEM = 4;
public static final int VISIBLE_PLACE = 5;
public static final int ABLE_PLACE = 6;
public static final int CHUNK_SIZE = 100;
public static final int[] COLORS = {0xFFFFFFFF, 0xFFFF0000, 0xFFFF9D00, 0xFF00FF00, 0xFFFFFF00, 0xFFC1B83A, 0xFF77ABFF};
public static final int BORDER = 0xFF0000FF;
public boolean dragging;
public boolean thinking;
SurfaceHolder holder;
int[][] swamp;
int x;
int y;
int cursorX;
int cursorY;
int firstX, firstY;
GameLogicController controller;
public GameField(Context context) {
super(context);
getHolder().addCallback(this);
dragging = false;
thinking = false;
controller = new GameLogicController();
this.swamp = controller.generate(); //getting the same swamp for GameField and GameController
}
public int[] getScreenSwampPosition(int x, int y){
int[] ret = new int[2];
ret[0] = (int) Math.floor((x - this.x) / CHUNK_SIZE);
ret[1] = (int) Math.floor((y - this.y) / CHUNK_SIZE);
return ret;
}
public void render(){
if (holder == null) return;
Canvas canvas = holder.lockCanvas();
if (canvas != null) {
try {
clear(canvas);
paint(canvas);
} finally {
holder.unlockCanvasAndPost(canvas);
}
}
}
private void paint(Canvas canvas){
Paint p = new Paint();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 8; j++) {
p.setColor(COLORS[swamp[i][j]]);
drawChunk(canvas, i * CHUNK_SIZE, j * CHUNK_SIZE, p);
}
}
}
private void drawChunk(Canvas canvas, int x, int y, Paint p) { // drawing one piece of field
int x0 = x + this.x, y0 = y + this.y, x1 = x0 + CHUNK_SIZE, y1 = y0 + CHUNK_SIZE;
canvas.drawRect(x0, y0, x1, y1, p);
p.setColor(BORDER);
canvas.drawLine(x1, y0, x1, y1, p); // drawing border
canvas.drawLine(x1, y1, x0, y1, p);
canvas.drawLine(x0, y0, x0, y1, p);
canvas.drawLine(x1, y0, x0, y0, p);
}
private void clear(Canvas c){
c.drawColor(0xFFFFFFFF);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
this.x = 100;
this.y = 100;
this.holder = holder;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
@Override
public boolean onTouchEvent(MotionEvent e) {
switch (e.getAction()) {
// scrolling map
case MotionEvent.ACTION_DOWN:
dragging = true;
cursorX = (int)e.getX(); //remembering first finger's position
cursorY = (int)e.getY();
firstX = (int)e.getX(); //for handling touches
firstY = (int)e.getY();
break;
case MotionEvent.ACTION_UP:
dragging = false;
Log.d("ON_TOUCH_EVENT", "up");
//if finger moved less than 15 pixels
if (firstY - 15 < (int)e.getY() && firstY + 15 > (int)e.getY()
&& firstX - 15 < (int)e.getX() && firstX + 15 > (int)e.getX()
&& !thinking){
thinking = true; //time for unit's computing
Log.d("ON_TOUCH_EVENT", "click");
int[] touched = getScreenSwampPosition((int)e.getX(), (int)e.getY()); //what chunk was pressed
controller.handleTouch(touched[0], touched[1]);
thinking = false;
}
break;
case MotionEvent.ACTION_MOVE:
if (dragging) {
this.x += (int)e.getX() - cursorX;
this.y += (int)e.getY() - cursorY;
cursorX = (int)e.getX(); // updating finger's position
cursorY = (int)e.getY();
}
break;
}
return true;
}
}
| true |
b484cd41ff85bc61e54b0e1d3f9c454748051404 | Java | alldatacenter/alldata | /olap/kylin/src/common-server/src/main/java/org/apache/kylin/rest/advice/BaseExceptionHandler.java | UTF-8 | 2,612 | 1.945313 | 2 | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kylin.rest.advice;
import org.apache.kylin.rest.exception.ForbiddenException;
import org.apache.kylin.rest.exception.InternalErrorException;
import org.apache.kylin.rest.exception.NotFoundException;
import org.apache.kylin.rest.exception.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
@ControllerAdvice
public class BaseExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(BaseExceptionHandler.class);
@ExceptionHandler(ForbiddenException.class)
public final ResponseEntity<Void> handle(ForbiddenException ex, WebRequest request) {
logger.error("uncaught exception", ex);
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
@ExceptionHandler(InternalErrorException.class)
public final ResponseEntity<Void> handle(InternalErrorException ex, WebRequest request) {
logger.error("uncaught exception", ex);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(NotFoundException.class)
public final ResponseEntity<Void> handle(NotFoundException ex, WebRequest request) {
logger.error("uncaught exception", ex);
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
@ExceptionHandler(UnauthorizedException.class)
public final ResponseEntity<Void> handle(UnauthorizedException ex, WebRequest request) {
logger.error("uncaught exception", ex);
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
}
| true |
efb2482a110b91a72048870cf9762d8877a95a65 | Java | Ligerx/SSUI_Final | /app/src/main/java/com/example/admin/ssuifinalproject/BeatData.java | UTF-8 | 2,516 | 2.921875 | 3 | [] | no_license | package com.example.admin.ssuifinalproject;
import android.util.Log;
import java.util.ArrayList;
import java.util.Collections;
public class BeatData {
private final String TAG = "BeatData";
private final ArrayList<Double> beatTiming;
private final ArrayList<Double> beatIntervals;
// FIXME can I nudge the BPM towards the right #? Right now it sometimes is a multiple of the original.
public BeatData(ArrayList<Double> beatTiming) {
this.beatTiming = beatTiming;
this.beatIntervals = findBeatIntervals();
}
private ArrayList<Double> findBeatIntervals() {
// Calculate the difference between the beat times
ArrayList<Double> intervals = new ArrayList<>();
// skip the first value, it doesn't have an interval to compare
for(int i = 1; i < beatTiming.size(); i++) {
double previous = beatTiming.get(i - 1);
double current = beatTiming.get(i);
double difference = current - previous;
Log.d(TAG, String.valueOf(difference));
intervals.add(difference);
}
return intervals;
}
private double findMedianValue(ArrayList<Double> values) {
ArrayList<Double> sortedIntervals = new ArrayList<>(values); // copy because why not
Collections.sort(sortedIntervals); // in place sort
return median(sortedIntervals);
}
private double median(ArrayList<Double> m) {
if(m.size() == 0) { return -1; }
int middle = m.size()/2;
if (m.size()%2 == 1) {
return m.get(middle);
} else {
return (m.get(middle-1) + m.get(middle)) / 2.0;
}
}
public double getMedianBPM() {
return timeToBPM(findMedianValue(beatIntervals));
}
// TODO consider how to throw away extremely long intervals (bad data)
// and what about extremely short intervals too?
public ArrayList<Double> getBPMOverTime() {
ArrayList<Double> bpm = new ArrayList<>();
for(double interval : beatIntervals) {
bpm.add(timeToBPM(interval));
}
return bpm;
}
private double timeToBPM(double seconds) {
// x (bpm) = 1 (beat) / minute (60 seconds)
// x = 1 * 60sec / seconds
return 60.0 / seconds;
}
// Standard Getters and Setters
public ArrayList<Double> getBeatTiming() {
return beatTiming;
}
public ArrayList<Double> getBeatIntervals() {
return beatIntervals;
}
}
| true |
5b785265ca1aa78f4633df3fb16624ce836e18b4 | Java | yummykang/spring_dubbo | /provider/src/main/java/me/yummykang/SystemDetails.java | UTF-8 | 1,287 | 2.84375 | 3 | [] | no_license | package me.yummykang;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
/**
* desc the file.
*
* @author demon
* @Date 2016/11/28 15:29
*/
public class SystemDetails {
public static void printDetails() {
timeZone();
currentTime();
osInfo();
}
public static void timeZone() {
Calendar calendar = Calendar.getInstance();
TimeZone timeZone = calendar.getTimeZone();
System.out.println("系统时区:" + timeZone.getDisplayName());
}
public static void currentTime() {
String fromFormat = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat format = new SimpleDateFormat(fromFormat);
Date myDate = new Date();
System.out.println("系统时间:" + format.format(myDate));
}
public static void osInfo() {
String osName = System.getProperty("os.name"); //操作系统名称
System.out.println("当前系统:" + osName);
String osArch = System.getProperty("os.arch"); //操作系统构架
System.out.println("当前系统架构" + osArch);
String osVersion = System.getProperty("os.version"); //操作系统版本
System.out.println("当前系统版本:" + osVersion);
}
}
| true |
27b9485c5696ec59a02bc2fbd3947f98d277e143 | Java | karthickRajendran03/TravelOnline | /KarthickTravelOnline/src/main/java/com/travel/online/model/TravelSummaryResponse.java | UTF-8 | 1,927 | 2.15625 | 2 | [] | no_license | package com.travel.online.model;
import java.sql.Timestamp;
/*@Entity
@Table(name = "TravelSummary")*/
public class TravelSummaryResponse {
/*@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)*/
private Long id;
//@Column(name="USER_ID")
private String userId;
//@Column(name="FROM_PLACE")
private String fromPlace;
//@Column(name="TO_PLACE")
private String toPlace;
//@Column(name="TRAVEL_FROM_DATE")
private Timestamp travelFromDate;
//@Column(name="TRAVEL_TO_DATE")
private Timestamp travelToDate;
//@Column(name="CITY")
private String city;
//@Column(name="PAYMENT_MODE")
private String paymentMode;
//@Column(name="AMOUNT")
private double amount;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFromPlace() {
return fromPlace;
}
public void setFromPlace(String fromPlace) {
this.fromPlace = fromPlace;
}
public String getToPlace() {
return toPlace;
}
public void setToPlace(String toPlace) {
this.toPlace = toPlace;
}
public Timestamp getTravelFromDate() {
return travelFromDate;
}
public void setTravelFromDate(Timestamp travelFromDate) {
this.travelFromDate = travelFromDate;
}
public Timestamp getTravelToDate() {
return travelToDate;
}
public void setTravelToDate(Timestamp travelToDate) {
this.travelToDate = travelToDate;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPaymentMode() {
return paymentMode;
}
public void setPaymentMode(String paymentMode) {
this.paymentMode = paymentMode;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
}
| true |
4c2237fcd490063a0cea9a3ac7c820291d055e77 | Java | shwetakanchan89/rysecamp_android_shweta | /app/src/main/java/com/rysecamp/api/RetrofitConfig.java | UTF-8 | 2,546 | 2.109375 | 2 | [] | no_license | package com.rysecamp.api;
import com.rysecamp.utils.RxErrorHandlingCallAdapterFactory;
import com.rysecamp.BuildConfig;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by sahil on 10/10/18.
*/
public class RetrofitConfig {
// public static EgApi api;
//
// public static EgApi apiLoc;
//
// public static EgApi getInstance() {
// if (api == null) {
// HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// // set your desired log level
// logging.setLevel(HttpLoggingInterceptor.Level.BODY);
// OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
// // add your other interceptors …
//
// // add logging as last interceptor
// httpClient.addInterceptor(logging);
// Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
// .baseUrl(BuildConfig.HOST)
// .addCallAdapterFactory(RxErrorHandlingCallAdapterFactory.create())
// .addConverterFactory(GsonConverterFactory.create());
// if (BuildConfig.DEBUG)
// retrofitBuilder.client(httpClient.build());
// Retrofit retrofit = retrofitBuilder.build();
// api = retrofit.create(EgApi.class);
// }
// return api;
// }
//
// public static EgApi getGeoInstance() {
// if (apiLoc == null) {
// HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// // set your desired log level
// logging.setLevel(HttpLoggingInterceptor.Level.BODY);
// OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
// // add your other interceptors …
//
// // String BASE_URL = ApiUrls.BASEURL;
// // add logging as last interceptor
// httpClient.addInterceptor(logging);
// Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
// .baseUrl("https://api.rysecamp.com/")
// .addCallAdapterFactory(RxErrorHandlingCallAdapterFactory.create())
// .addConverterFactory(GsonConverterFactory.create());
// if (BuildConfig.DEBUG)
// retrofitBuilder.client(httpClient.build());
// Retrofit retrofit = retrofitBuilder.build();
// apiLoc = retrofit.create(EgApi.class);
// }
// return apiLoc;
// }
}
| true |
4cf6a036f1b333330f8913a74937ff9c3101e92a | Java | MobyRx/MobyRx-web | /src/main/java/com/MobyRx/java/service/wso/GenderWSO.java | UTF-8 | 234 | 1.679688 | 2 | [] | no_license | package com.MobyRx.java.service.wso;
/**
* Created by IntelliJ IDEA.
* User: ashqures
* Date: 9/6/16
* Time: 5:50 PM
* To change this template use File | Settings | File Templates.
*/
public enum GenderWSO {
MALE, FEMALE
}
| true |
b4af5a285d76fe49f4a000d3e8d14b7f7bdf9303 | Java | miseongshin/DRENGINEER_SPRING_PROJECT | /spring_web_step3/src/test/java/springtest/spring_web_step3/BookServiceTest.java | UTF-8 | 859 | 2.234375 | 2 | [
"MIT"
] | permissive | package springtest.spring_web_step3;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@RunWith(SpringRunner.class)
public class BookServiceTest {
@Mock
BookRepository bookRepository;
@Test
public void save() {
Book book = new Book();
when(bookRepository.save(book)).thenReturn(book);
//BookRepository bookRepository = new BookRepository();
BookService bookService = new BookService(bookRepository);
Book result =bookService.save(book);
assertThat(book.getCreate()).isNotNull();
assertThat(book.getBookStatus()).isEqualTo(BookStatus.DRAFT);
assertThat(result).isNotNull();
}
} | true |
5c17e08dfad542851669edf3ea28ef7b960dbaa3 | Java | Nandakumar-Kadavannoore/Dynamic-Programming | /entringerNumber.java | UTF-8 | 370 | 3.28125 | 3 | [] | no_license | class MainClass {
// Return Entringer Number E(n, k)
public static int Entringer(int n, int k)
{
// Base Case
if (n == 0 && k == 0)
return 1;
// Base Case
if (k == 0)
return 0;
// Recursive step
return Entringer(n, k - 1) +
Entringer(n - 1, n - k);
}
}
| true |
625783c6e4f0142e85363fb4f1c5ea688049cfc2 | Java | 4Lisandr/LiSQL | /src/main/java/ua/com/juja/lisql/view/View.java | UTF-8 | 257 | 1.585938 | 2 | [] | no_license | package ua.com.juja.lisql.view;
import java.util.List;
/*
* Lisandr 2017
* */
public interface View {
String read();
void write(String message);
void write(String... messages);
void write(List<List<?>> table);
boolean confirm();
}
| true |
9e915aa4244243e6e0979eec4da8f3b3850b2329 | Java | 13048694426/familiy-cook-menu | /src/com/example/familiycookmenu/base/BasePage.java | UTF-8 | 1,149 | 2.34375 | 2 | [
"Apache-2.0"
] | permissive | package com.example.familiycookmenu.base;
import java.io.Serializable;
import com.example.familiycookmenu.R;
import android.app.Activity;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
public class BasePage implements Serializable{
public View mRoot;
public Activity activity;
public TextView tvTitle;
public FrameLayout flContent;
public String result;
public BasePage (Activity activity) {
this.activity = activity;
mRoot = initView();
}
public View initView() {
View view = View.inflate(activity, R.layout.page_base, null);
tvTitle = (TextView) view.findViewById(R.id.tv_title);
flContent = (FrameLayout) view.findViewById(R.id.fl_content);
return view;
}
public void initData() {
TestData(result);
}
public void TestData(String data) {
tvTitle.setText(data);
TextView textView = new TextView(activity);
textView.setText(data);
textView.setTextColor(Color.BLUE);
textView.setTextSize(30);
textView.setGravity(Gravity.CENTER);
flContent.addView(textView);
}
}
| true |
9bd9d50cbfb74277ee5be03c1c3168f27dc37c20 | Java | IlyaHalsky/dkvs | /src/replica/Replica.java | UTF-8 | 7,299 | 2.046875 | 2 | [] | no_license | package replica;
import utility.Entry;
import java.net.InetSocketAddress;
import java.util.*;
/**
* Created by Ilya239 on 05.09.2016.
*/
public class Replica {
private InetSocketAddress[] configuration;
private int numberOfReplicas;
private int replicaNumber;
private int viewNumber;
private ReplicaStatus replicaStatus;
private int opNumber;
private int commitNumber;
private int clientTableNumber;
private int timeout;
private int leader;
private long lastMessageTime;
private ReplicaState replicaState;
private Map<Integer, Integer> opNumberToPrepareOk;
private int lastNormalViewNumber;
private int numberOfStartViewChangeMessages;
private Set<Integer> replicasStartViewChangeMessagesReceivedFrom;
private int numberOfDoViewChangeMessages;
private Set<Integer> replicasDoViewChangeMessagesReceivedFrom;
private int maxNormalViewNumber;
private int maxOpNumber;
private List<Entry> logInViewChange;
private int maxCommitNumber;
private Map<Integer, Integer> nonce;
private Map<Integer, List<Entry>> nonceToLog;
private Map<Integer, Integer> nonceToCommitNumber;
public Replica(InetSocketAddress[] configuration, int numberOfReplicas, int replicaNumber, int timeout) {
this.configuration = configuration;
this.numberOfReplicas = numberOfReplicas;
this.replicaNumber = replicaNumber;
viewNumber = 0;
replicaStatus = ReplicaStatus.NORMAL;
opNumber = 0;
commitNumber = 0;
clientTableNumber = 0;
this.timeout = timeout;
leader = -1;
opNumberToPrepareOk = new HashMap<>();
lastNormalViewNumber = 0;
numberOfStartViewChangeMessages = 0;
replicasStartViewChangeMessagesReceivedFrom = new HashSet<>();
numberOfDoViewChangeMessages = 0;
replicasDoViewChangeMessagesReceivedFrom = new HashSet<>();
maxNormalViewNumber = 0;
maxOpNumber = 0;
logInViewChange = new ArrayList<>();
maxCommitNumber = 0;
nonce = new HashMap<>();
nonceToLog = new HashMap<>();
nonceToCommitNumber = new HashMap<>();
}
public InetSocketAddress[] getConfiguration() {
return configuration;
}
public int getReplicaNumber() {
return replicaNumber;
}
public int getViewNumber() {
return viewNumber;
}
public void setViewNumber(int viewNumber) {
this.viewNumber = viewNumber;
}
public ReplicaStatus getReplicaStatus() {
return replicaStatus;
}
public void setReplicaStatus(ReplicaStatus replicaStatus) {
this.replicaStatus = replicaStatus;
}
public int getOpNumber() {
return opNumber;
}
public void setOpNumber(int opNumber) {
this.opNumber = opNumber;
}
public int getCommitNumber() {
return commitNumber;
}
public void setCommitNumber(int commitNumber) {
this.commitNumber = commitNumber;
}
public int getTimeout() {
return timeout;
}
public void setLeader(int leader) {
this.leader = leader;
}
public int getLeader() {
return leader;
}
public long getLastMessageTime() {
return lastMessageTime;
}
public void setLastMessageTime(long lastMessageTime) {
this.lastMessageTime = lastMessageTime;
}
public ReplicaState getReplicaState() {
return replicaState;
}
public void setReplicaState(ReplicaState replicaState) {
this.replicaState = replicaState;
}
public int getClientTableNumber() {
return clientTableNumber;
}
public void setClientTableNumber(int clientTableNumber) {
this.clientTableNumber = clientTableNumber;
}
public void addPrepareOk(Integer opNumber) {
if (!opNumberToPrepareOk.containsKey(opNumber)) {
opNumberToPrepareOk.put(opNumber, 1);
} else {
opNumberToPrepareOk.put(opNumber, opNumberToPrepareOk.get(opNumber) + 1);
}
}
public Integer getPrepareOk(Integer opNumber) {
return opNumberToPrepareOk.get(opNumber);
}
public int getLastNormalViewNumber() {
return lastNormalViewNumber;
}
public void setLastNormalViewNumber(int lastNormalViewNumber) {
this.lastNormalViewNumber = lastNormalViewNumber;
}
public int getNumberOfStartViewChangeMessages() {
return numberOfStartViewChangeMessages;
}
public void setNumberOfStartViewChangeMessages(int numberOfStartViewChangeMessages) {
this.numberOfStartViewChangeMessages = numberOfStartViewChangeMessages;
}
public int getNumberOfDoViewChangeMessages() {
return numberOfDoViewChangeMessages;
}
public void setNumberOfDoViewChangeMessages(int numberOfDoViewChangeMessages) {
this.numberOfDoViewChangeMessages = numberOfDoViewChangeMessages;
}
public int getMaxNormalViewNumber() {
return maxNormalViewNumber;
}
public void setMaxNormalViewNumber(int maxNormalViewNumber) {
this.maxNormalViewNumber = maxNormalViewNumber;
}
public int getMaxOpNumber() {
return maxOpNumber;
}
public void setMaxOpNumber(int maxOpNumber) {
this.maxOpNumber = maxOpNumber;
}
public List<Entry> getLogInViewChange() {
return logInViewChange;
}
public void setLogInViewChange(List<Entry> logInViewChange) {
this.logInViewChange = logInViewChange;
}
public int getMaxCommitNumber() {
return maxCommitNumber;
}
public void setMaxCommitNumber(int maxCommitNumber) {
this.maxCommitNumber = maxCommitNumber;
}
public Set<Integer> getReplicasStartViewChangeMessagesReceivedFrom() {
return replicasStartViewChangeMessagesReceivedFrom;
}
public void setReplicasStartViewChangeMessagesReceivedFrom(Set<Integer> replicasStartViewChangeMessagesReceivedFrom) {
this.replicasStartViewChangeMessagesReceivedFrom = replicasStartViewChangeMessagesReceivedFrom;
}
public Set<Integer> getReplicasDoViewChangeMessagesReceivedFrom() {
return replicasDoViewChangeMessagesReceivedFrom;
}
public void setReplicasDoViewChangeMessagesReceivedFrom(Set<Integer> replicasDoViewChangeMessagesReceivedFrom) {
this.replicasDoViewChangeMessagesReceivedFrom = replicasDoViewChangeMessagesReceivedFrom;
}
public int getNumberOfReplicas() {
return numberOfReplicas;
}
public void addVoiceForNonce(int curNonce, List<Entry> curLog, int commitNumber) {
nonce.putIfAbsent(curNonce, 0);
nonceToCommitNumber.putIfAbsent(curNonce, 0);
nonce.put(curNonce, nonce.get(curNonce) + 1);
nonceToLog.putIfAbsent(curNonce, null);
if (curLog != null) {
nonceToLog.put(curNonce, curLog);
nonceToCommitNumber.put(curNonce, commitNumber);
}
}
public int getVoiceForNonce(int curNonce) {
return nonce.get(curNonce);
}
public List<Entry> getLogForNonce(int curNonce) {
return nonceToLog.get(curNonce);
}
public int getCommitNumberForNonce(int curNonce) {
return nonceToCommitNumber.get(curNonce);
}
}
| true |
7276c074cfced3e59ec31af37643f8c92d22ea6e | Java | sselin-co/unicorn | /app/src/main/java/edu/tjrac/swant/douyin/widget/Selectedable.java | UTF-8 | 242 | 1.835938 | 2 | [] | no_license | package edu.tjrac.swant.douyin.widget;
/**
* Created by wpc on 2018/3/2 0002.
*/
public interface Selectedable {
boolean isSelected();
void select();
void unSelected();
void selectAnimate();
void unselectAnimate();
}
| true |
eb9c2c7f296693d5c65a22e876c94f139f3dd899 | Java | yangc22/UW_CSE373 | /HW3_TextAssociator/src/TextAssociator.java | UTF-8 | 6,670 | 3.625 | 4 | [] | no_license | import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/* Chaoyi Yang
* 02/10/17
* CSE373
* TA: Raquel Van Hofwegen
*
* TextAssociator represents a collection of associations between words.
* See write-up for implementation details and hints
*
*/
public class TextAssociator {
private WordInfoSeparateChain[] table;
private int size;
/* INNER CLASS
* Represents a separate chain in your implementation of your hashing
* A WordInfoSeparateChain is a list of WordInfo objects that have all
* been hashed to the same index of the TextAssociator
*/
private class WordInfoSeparateChain {
private List<WordInfo> chain;
/* Creates an empty WordInfoSeparateChain without any WordInfo
*/
public WordInfoSeparateChain() {
this.chain = new ArrayList<WordInfo>();
}
/* Adds a WordInfo object to the SeparateCahin
* Returns true if the WordInfo was successfully added, false otherwise
*/
public boolean add(WordInfo wi) {
if (chain.contains(wi)) {
return false;
} else {
chain.add(wi);
return true;
}
}
/* Removes the given WordInfo object from the separate chain
* Returns true if the WordInfo was successfully removed, false otherwise
*/
public boolean remove(WordInfo wi) {
if (!chain.contains(wi)) {
return false;
} else {
chain.remove(wi);
return true;
}
}
// Returns the size of this separate chain
public int size() {
return chain.size();
}
// Returns the String representation of this separate chain
public String toString() {
return chain.toString();
}
// Returns the list of WordInfo objects in this chain
public List<WordInfo> getElements() {
return chain;
}
}
/* Creates a new TextAssociator without any associations
*/
public TextAssociator() {
table = new WordInfoSeparateChain[11];
size = 0;
}
/* Adds a word with no associations to the TextAssociator
* Returns False if this word is already contained in your TextAssociator ,
* Returns True if this word is successfully added
*/
public boolean addNewWord(String word) {
if (contain(word)) {
return false;
} else {
addNewInfo(new WordInfo(word), table);
size++;
if (size == table.length) {
rehash();
}
return true;
}
}
/* Calculates the index in the table for the given string
*/
private int hashFunction(String word, int tableSize) {
int index = Math.abs(word.hashCode()) % tableSize;
return index;
}
/* Adds a WordInfo to the corresponding position in the hash table,
* Creates a new chain if the position is empty
*/
private void addNewInfo(WordInfo current, WordInfoSeparateChain[] table) {
int index = hashFunction(current.getWord(), table.length);
if (table[index] == null) {
table[index] = new WordInfoSeparateChain();
}
table[index].add(current);
}
/* Finds the corresponding WordInfo of the given string in the TextAssociator
* Returns the WordInfo object if it exits
* Returns null if it doesn't
*/
private WordInfo find(String word) {
int index = hashFunction(word, table.length);
if (table[index] != null) {
WordInfoSeparateChain bucket = table[index];
//For each separate chain, grab each individual WordInfo
for (WordInfo curr : bucket.getElements()) {
if (curr.getWord().equals(word)) {
return curr;
}
}
}
return null;
}
/* Checks whether the WordInfo of the given string exits in the TextAssociator
* return true if it exits
* return false if it doesn't
*/
private boolean contain(String word) {
if (size == 0) {
return false;
} else {
WordInfo newInfo = find(word);
if (newInfo != null) {
return true;
}
}
return false;
}
/* Rehash all the elements in the current table to a new table which is two times
* bigger than the current table.
*/
private void rehash() {
WordInfoSeparateChain[] newTable = new WordInfoSeparateChain[2 * table.length];
for (int i = 0; i < table.length; i++) {
if (table[i] != null) {
WordInfoSeparateChain bucket = table[i];
//For each separate chain, grab each individual WordInfo
for (WordInfo curr : bucket.getElements()) {
addNewInfo(curr, newTable);
}
}
}
this.table = newTable;
}
/* Adds an association between the given words. Returns true if association correctly added,
* returns false if first parameter does not already exist in the TextAssociator or if
* the association between the two words already exists
*/
public boolean addAssociation(String word, String association) {
if (!contain(word)) {
return false;
} else {
WordInfo newWord = find(word);
if (newWord.getAssociations().contains(association)) {
return false;
} else {
newWord.getAssociations().add(association);
}
}
return true;
}
/* Remove the given word from the TextAssociator, returns false if word
* was not contained, returns true if the word was successfully removed.
* Note that only a source word can be removed by this method, not an association.
*/
public boolean remove(String word) {
if (!contain(word)) {
return false;
} else {
int index = hashFunction(word, table.length);
WordInfoSeparateChain bucket = table[index];
WordInfo newWord = find(word);
bucket.remove(newWord);
size--;
}
return true;
}
/* Returns a set of all the words associated with the given String
* Returns null if the given String does not exist in the TextAssociator
*/
public Set<String> getAssociations(String word) {
if (!contain(word)) {
return null;
} else {
WordInfo newWord = find(word);
return newWord.getAssociations();
}
}
/* Prints the current associations between words being stored
* to System.out
*/
public void prettyPrint() {
System.out.println("Current number of elements : " + size);
System.out.println("Current table size: " + table.length);
//Walk through every possible index in the table
for (int i = 0; i < table.length; i++) {
if (table[i] != null) {
WordInfoSeparateChain bucket = table[i];
//For each separate chain, grab each individual WordInfo
for (WordInfo curr : bucket.getElements()) {
System.out.println("\tin table index, " + i + ": " + curr);
}
}
}
System.out.println();
}
/* Prints all the source word being stored to System.out
*/
public void wordPrint() {
System.out.print("[");
for (int i = 0; i < table.length; i++) {
if (table[i] != null) {
WordInfoSeparateChain bucket = table[i];
for (WordInfo curr : bucket.getElements()) {
System.out.print(curr.getWord() + " ");
}
}
}
System.out.println("]");
}
}
| true |
8864e4d7cc9f1b4a7ff1ac53aa5d55877f90f02a | Java | virgil-andreies/bookstore-backend | /src/main/java/com/bookstore/resource/ShippingResource.java | UTF-8 | 2,326 | 2.296875 | 2 | [] | no_license | package com.bookstore.resource;
import java.security.Principal;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.bookstore.domain.User;
import com.bookstore.domain.UserShipping;
import com.bookstore.service.UserService.IUserService;
import com.bookstore.service.UserShippingService.IUserShippingService;
@RestController
@RequestMapping("/shipping")
public class ShippingResource {
@Autowired
private IUserService userService;
@Autowired
private IUserShippingService userShippingService;
@RequestMapping(value="/add", method=RequestMethod.POST)
public ResponseEntity addNewUserShippingPost( @RequestBody UserShipping userShipping,
Principal principal ) {
User user = userService.findByUsername(principal.getName());
userService.updateUserShipping(userShipping, user);
return new ResponseEntity("Shipping Added(Updated) Successfully", HttpStatus.OK);
}
@RequestMapping("/getUserShippingList")
public List<UserShipping> getUserShippingList( Principal principal) {
User user = userService.findByUsername(principal.getName());
List<UserShipping> userShippingList = user.getUserShippingList();
return userShippingList;
}
@RequestMapping(value="/remove", method=RequestMethod.POST)
public ResponseEntity removeUserShippingList( @RequestBody String id,
Principal principal) {
userShippingService.removeById(Long.parseLong(id));
return new ResponseEntity("Shipping Removed Successfully", HttpStatus.OK);
}
@RequestMapping(value="/setDefault", method=RequestMethod.POST)
public ResponseEntity setDefaultUserShippingPost( @RequestBody String id, Principal principal) {
User user = userService.findByUsername(principal.getName());
userService.setUserDefaultPayment(Long.parseLong(id), user);
return new ResponseEntity("Shipping Default Shipping Successfully", HttpStatus.OK);
}
}
| true |
a3230864580636514209978b4164239b499ec640 | Java | orthocresol/ManageYourPasswords | /app/src/main/java/com/manageyourpassword/SettingsActivitySQL.java | UTF-8 | 3,413 | 1.9375 | 2 | [] | no_license | package com.manageyourpassword;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.switchmaterial.SwitchMaterial;
public class SettingsActivitySQL extends AppCompatActivity {
Button btn_logout;
SessionManagerSQL sessionManagerSQL;
BottomNavigationView bottomNavigationView;
SwitchCompat switchCompat;
MaterialButton tohide;
SwitchMaterial tohide2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_sql);
setTitle("Settings");
tohide = findViewById(R.id.changeFont_sql);
tohide.setVisibility(View.INVISIBLE);
tohide2 = findViewById(R.id.switch_mode_sql);
tohide2.setVisibility(View.INVISIBLE);
bottomNavigationView = findViewById(R.id.generatorNavigation);
btn_logout = findViewById(R.id.settingsLogout);
sessionManagerSQL = new SessionManagerSQL(getApplicationContext());
bottomNavigationView.setSelectedItemId(R.id.settings);
switchCompat = findViewById(R.id.settings_switch_logout);
switchCompat.setChecked(sessionManagerSQL.getAutoLogin());
switchCompat.setOnClickListener(v -> {
if(switchCompat.isChecked()) {
sessionManagerSQL.setAutoLogin(true);
}
else {
sessionManagerSQL.setAutoLogin(false);
}
});
btn_logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sessionManagerSQL.setUsername("");
sessionManagerSQL.setLogin(false);
Intent intent = new Intent(SettingsActivitySQL.this, SingleLoginActivity.class);
startActivity(intent);
finish();
}
});
setNavigationBar();
}
private void setNavigationBar() {
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Intent intent;
switch (item.getItemId()){
case R.id.settings:
return true;
case R.id.dashboard:
intent = new Intent(SettingsActivitySQL.this, DashboardActivitySQL.class);
startActivity(intent);
overridePendingTransition(0, 0);
finish();
return true;
case R.id.generator:
intent = new Intent(SettingsActivitySQL.this, GeneratorActivity.class);
startActivity(intent);
overridePendingTransition(0, 0);
finish();
return true;
}
return false;
}
});
}
} | true |
d61f069415e3ca67ae3b19ffa0dbd6226163c1a8 | Java | RahulRanjan-TPL/Mario | /package/gamemaster/src/com/lemi/controller/lemigameassistance/config/LotteryReturnValues.java | UTF-8 | 381 | 1.742188 | 2 | [] | no_license | package com.lemi.controller.lemigameassistance.config;
/**
* @author zhengjinguang@letv.com (shining).
*/
public class LotteryReturnValues {
public static final int LOTTERY_NOT_START = -12;
public static final int LOTTERY_STOP = -13;
public static final int LOTTERY_OVER_LIMIT = -14;
public static final int LOTTERY_NO_AWARD = -15;
public static final int LOTTERY_NOT_FOUND = -16;
}
| true |
6bd7896244cff639b3a63c7b121b77e139069724 | Java | zetingzhu/AppFrame | /app/src/main/java/frame/zzt/com/appframe/ui/login/LoginView.java | UTF-8 | 224 | 1.835938 | 2 | [] | no_license | package frame.zzt.com.appframe.ui.login;
import frame.zzt.com.appframe.mvp.mvpbase.BaseView;
public interface LoginView extends BaseView {
void onLoginSucc();
String getUserName();
String getPassword();
}
| true |
1e6c43cfe17680169c14c17e03c43dec15c2175d | Java | zhaolan2099/ccmanage2 | /src/main/java/com/cc/manage/utils/DateUtil.java | UTF-8 | 24,413 | 2.15625 | 2 | [] | no_license | package com.cc.manage.utils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
public class DateUtil {
public final static String DATE_FORMAT_DEFAULT_YEAR = "yyyy";
public final static String DATE_FORMAT_DEFAULT = "yyyy-MM-dd";
public final static String TIME_FORMAT_DEFAULT = "HH:mm:ss";
public final static String DATE_FORMAT_SOLIDUS = "yyyy/MM/dd";
public final static String DATE_FORMAT_COMPACT = "yyyyMMdd";
public final static String DATE_FORMAT_SHORT_COMPACT = "yyMMdd";
public final static String DATE_FORMAT_COMPACT_MONTH = "yyyyMM";
public final static String DATE_FORMAT_UTC_DEFAULT = "MM-dd-yyyy";
public final static String DATE_FORMAT_UTC_SOLIDUS = "MM/dd/yyyy";
public final static String DATE_FORMAT_TAODA_DIRECTORY = "yyyyMMdd HHmmss";
public final static String DATE_FORMAT_TAODA_DIRECTORY_T = "yyyyMMddHHmmss";
public final static String DATE_FORMAT_TAODA_DIRECTORY_Y = "yyyyMMddHHmm";
public final static String DATE_FORMAT_TAODA_DIRECTORY_S = "yyyyMMddHHmmssSSS";
public final static String DATE_FORMAT_CHINESE = "yyyy年MM月dd日";
public final static String DATE_TIME_FORMAT_COMPACT = "yyyyMMdd hhmmss";
public final static String DATE_TIME_FORMAT_CHINESE = "yyyy年MM月dd日 HH时mm分ss秒";
public final static String DATE_TIME_FORMAT_DEFAULT = "yyyy-MM-dd HH:mm:ss";
public final static String DATE_TIME_FORMAT_DEFAULT_MONET = "yyyy-MM-dd HH:mm";
public final static String DATE_TIME_FORMAT_DEFAULT_S = "yyyy-MM-dd HH:mm:ss.SSS";
public final static String DATE_TIME_FORMAT_TAODA_DIRECTORY = "HHmmss";
public final static String DATE_TIME_FORMAT_SOLIDUS = "yyyy/MM/dd HH:mm:ss";
public final static String DATE_TIME_FORMAT_UTC_DEFAULT = "MM-dd-yyyy HH:mm:ss";
public final static String DATE_TIME_FORMAT_UTC_SOLIDUS = "MM/dd/yyyy HH:mm:ss";
public final static String DATE_TIME_FORMAT_DEFAULT_3 = "yyyy-MM-dd'T'HH:mm:ss.SSS";
public final static String DATE_TIME_FORMAT_DEFAULT_4 = "HH:mm";
public final static String DATE_TIME_FORMAT_DEFAULT_5 = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
private static Map<String, String> dateFormatRegisterMap = new HashMap<String, String>();
private static Map<String, SimpleDateFormat> dateFormatMap = new HashMap<String, SimpleDateFormat>();
public final static String DATE_FORMAT_DEFAULT_MONTH = "yyyy-MM";
private static final String minDateStrTemp = "2020-04-14";
public static final String BANCK_TIME_SHOW = "yyyyMMdd HH:mm:ss";
private static String rexp = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";
static {
// 各种日期格式注册,有新需要请在此处添加 ,无需其它改动
dateFormatRegisterMap.put(DATE_FORMAT_COMPACT, "^\\d{8}$");
dateFormatRegisterMap.put(DATE_FORMAT_DEFAULT, "^\\d{4}-\\d{1,2}-\\d{1,2}$");
dateFormatRegisterMap.put(DATE_FORMAT_SOLIDUS, "^\\d{4}/\\d{1,2}/\\d{1,2}$");
dateFormatRegisterMap.put(DATE_FORMAT_UTC_DEFAULT, "^\\d{1,2}-\\d{1,2}-\\d{4}$");
dateFormatRegisterMap.put(DATE_FORMAT_UTC_SOLIDUS, "^\\d{1,2}/\\d{1,2}/\\d{4}$");
dateFormatRegisterMap.put(DATE_TIME_FORMAT_DEFAULT, "^\\d{4}-\\d{1,2}-\\d{1,2}\\s*\\d{1,2}:\\d{1,2}:\\d{1,2}$");
dateFormatRegisterMap.put(DATE_TIME_FORMAT_SOLIDUS, "^\\d{4}/\\d{1,2}/\\d{1,2}\\s*\\d{1,2}:\\d{1,2}:\\d{1,2}$");
dateFormatRegisterMap.put(DATE_TIME_FORMAT_UTC_DEFAULT, "^\\d{1,2}-\\d{1,2}-\\d{4}\\s*\\d{1,2}:\\d{1,2}:\\d{1,2}$");
dateFormatRegisterMap.put(DATE_TIME_FORMAT_UTC_SOLIDUS, "^\\d{1,2}/\\d{1,2}/\\d{4}\\s*\\d{1,2}:\\d{1,2}:\\d{1,2}$");
dateFormatMap.put(DATE_FORMAT_DEFAULT, new SimpleDateFormat(DATE_FORMAT_DEFAULT));
dateFormatMap.put(DATE_FORMAT_SOLIDUS, new SimpleDateFormat(DATE_FORMAT_SOLIDUS));
dateFormatMap.put(DATE_FORMAT_COMPACT, new SimpleDateFormat(DATE_FORMAT_COMPACT));
dateFormatMap.put(DATE_FORMAT_UTC_DEFAULT, new SimpleDateFormat(DATE_FORMAT_UTC_DEFAULT));
dateFormatMap.put(DATE_FORMAT_UTC_SOLIDUS, new SimpleDateFormat(DATE_FORMAT_UTC_SOLIDUS));
dateFormatMap.put(DATE_TIME_FORMAT_DEFAULT, new SimpleDateFormat(DATE_TIME_FORMAT_DEFAULT));
dateFormatMap.put(DATE_TIME_FORMAT_SOLIDUS, new SimpleDateFormat(DATE_TIME_FORMAT_SOLIDUS));
dateFormatMap.put(DATE_TIME_FORMAT_UTC_DEFAULT, new SimpleDateFormat(DATE_TIME_FORMAT_UTC_DEFAULT));
dateFormatMap.put(DATE_TIME_FORMAT_UTC_SOLIDUS, new SimpleDateFormat(DATE_TIME_FORMAT_UTC_SOLIDUS));
}
/**
* @param formatStr String
* @return String
* @Description: 获得当前日期的格式化表示
*/
public static String getCurrentDateStr(String formatStr) {
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
return sdf.format(new Date());
}
public static String getNowDate(String format) {
return formatDate(new Date(), format);
}
public static String formatDate(Date date, String format) {
SimpleDateFormat sf = new SimpleDateFormat(format);
return sf.format(date);
}
public static String format(String formatString, Date date) {
return new SimpleDateFormat(formatString).format(date);
}
public static Date parseStrToDate(String formatString, String dateString) {
try {
return new SimpleDateFormat(formatString).parse(dateString);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
public static long parseDateToLong(String date) {
date = date.replace("-", "");
Long result = Long.valueOf(date);
return result;
}
public static String formatDate(String date, String format, String newFormat) throws ParseException {
SimpleDateFormat sf = new SimpleDateFormat(format);
Date d = sf.parse(date);
sf = new SimpleDateFormat(newFormat);
return sf.format(d);
}
public static Date add(Date date, int n, int calendarField) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(calendarField, n);
return c.getTime();
}
public static String addDate(Date date, int n, String format) {
return DateUtil.formatDate(DateUtils.addDays(date, n), format);
}
public static String addMonths(Date date, int n, String format) {
return DateUtil.formatDate(DateUtils.addMonths(date, n), format);
}
public static String addMinutes(Date date, int n, String format) {
return DateUtil.formatDate(DateUtils.addMinutes(date, n), format);
}
public static String addYears(Date date, int n, String format) {
return DateUtil.formatDate(DateUtils.addYears(date, n), format);
}
/**
* 获取 是否是一般工作日(周一至周五)
* @return
*/
public static boolean isWorkingDate(Date date) {
final int dayNames[] = {7, 1, 2, 3, 4, 5, 6};
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"));// 获取中国的时区
calendar.setTime(date);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
if (dayOfWeek < 0){
dayOfWeek = 0;
}
int week = dayNames[dayOfWeek];
if (week > 5) {
return false;
}
return true;
}
/**
* 取得两个时间段的时间间隔
* @param t1 时间1
* @param t2 时间2
* @return t2 与t1的间隔天数
* @throws ParseException 如果输入的日期格式不是0000-00-00 格式抛出异常
* @author color
*/
public static int getBetweenDays(String t1, String t2, String dateFormat) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat(dateFormat);
int betweenDays = 0;
Date d1 = format.parse(t1);
Date d2 = format.parse(t2);
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(d1);
c2.setTime(d2);
// 保证第二个时间一定大于第一个时间
if (c1.after(c2)) {
c1 = c2;
c2.setTime(d1);
}
int betweenYears = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
betweenDays = c2.get(Calendar.DAY_OF_YEAR) - c1.get(Calendar.DAY_OF_YEAR);
for (int i = 0; i < betweenYears; i++) {
c1.set(Calendar.YEAR, c1.get(Calendar.YEAR) + 1);
betweenDays += c1.getMaximum(Calendar.DAY_OF_YEAR);
}
return betweenDays;
}
/**
* 获取当天日期的星期
* @return
*/
public static int getNowWeek() {
Date date = new Date();
final int dayNames[] = {7, 1, 2, 3, 4, 5, 6};
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"));// 获取中国的时区
calendar.setTime(date);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
if (dayOfWeek < 0){
dayOfWeek = 0;
}
return dayNames[dayOfWeek];
}
/**
* 获取几年的周一到周五的日期
* @return
*/
public static List<String> getWorkDs(int year) {
List<String> dates = new ArrayList<String>();
for (int j = 1; j <= 12; j++) {
getDates(dates, year, j);
}
return dates;
}
/**
* 计算两个日期之间相差的天数
* @param sdate 较小的时间
* @return 相差天数
* @throws Exception
*/
public static int daysBetween(Date sdate, Date edate) {
Calendar cal = Calendar.getInstance();
cal.setTime(sdate);
long time1 = cal.getTimeInMillis();
cal.setTime(edate);
long time2 = cal.getTimeInMillis();
long betweenDays = (time2 - time1) / (1000 * 3600 * 24);
return Integer.parseInt(String.valueOf(betweenDays));
}
/**
* 计算两个日期之间相差的秒数
* @param sdate 较小的时间
* @return 相差天数
* @throws Exception
*/
public static long secondsBetween(Date sdate, Date edate) {
Calendar cal = Calendar.getInstance();
cal.setTime(sdate);
long time1 = cal.getTimeInMillis();
cal.setTime(edate);
long time2 = cal.getTimeInMillis();
long betweenSeconds = time2 - time1;
return betweenSeconds;
}
public static Date calMonth(Date date, String format, int n) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, n);
return parseStrToDate(format, sdf.format(calendar.getTime()));
}
public static Date calWeek(Date date, String format, int n) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.WEDNESDAY, n);
return parseStrToDate(format, sdf.format(calendar.getTime()));
}
public static boolean dateMatcher(String date) {
return Pattern.matches(rexp, date);
}
private static List<String> getDates(List<String> dates, int year, int month) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1);
cal.set(Calendar.DATE, 1);
while (cal.get(Calendar.YEAR) == year && cal.get(Calendar.MONTH) < month) {
int day = cal.get(Calendar.DAY_OF_WEEK);
if (!(day == Calendar.SUNDAY || day == Calendar.SATURDAY)) {
Date date = (Date) cal.getTime().clone();
dates.add(DateUtil.format(DateUtil.DATE_FORMAT_DEFAULT, date));
}
cal.add(Calendar.DATE, 1);
}
return dates;
}
/**
* 字符串转日期
* @param date
* @return
* @throws ParseException
*/
public static Date fomatDate(String date) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat();
return sdf.parse(date);
}
/**
* 判断某一时间是否在一个区间内
* @param sourceTime 时间区间,半闭合,如[10:00-20:00)
* @param curTime 需要判断的时间 如10:00
* @return
* @throws IllegalArgumentException
*/
public static boolean isInTime(String sourceTime, String curTime) {
if (sourceTime == null || !sourceTime.contains("-") || !sourceTime.contains(":")) {
throw new IllegalArgumentException("Illegal Argument arg:" + sourceTime);
}
if (curTime == null || !curTime.contains(":")) {
throw new IllegalArgumentException("Illegal Argument arg:" + curTime);
}
String[] args = sourceTime.split("-");
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
try {
long now = sdf.parse(curTime).getTime();
long start = sdf.parse(args[0]).getTime();
long end = sdf.parse(args[1]).getTime();
if (args[1].equals("00:00")) {
args[1] = "24:00";
}
if (end < start) {
if (now >= end && now < start) {
return false;
} else {
return true;
}
} else {
if (now >= start && now < end) {
return true;
} else {
return false;
}
}
} catch (ParseException e) {
e.printStackTrace();
throw new IllegalArgumentException("Illegal Argument arg:" + sourceTime);
}
}
/**
* 计算两个日期之间相差的 秒差
* @param sdate 较小的时间
* @return 相差天数
* @throws Exception
*/
public static int secondBetween(Date sdate, Date edate) {
Calendar cal = Calendar.getInstance();
cal.setTime(sdate);
long time1 = cal.getTimeInMillis();
cal.setTime(edate);
long time2 = cal.getTimeInMillis();
long betweenDays = (time2 - time1) / 1000;
return Integer.parseInt(String.valueOf(betweenDays));
}
/**
* 获取当前日期字符串,格式"yyyyMMddHHmmss"
* @return
*/
public static String getNow2() {
Calendar today = Calendar.getInstance();
return DateFormatUtils.format(today.getTime(), DATE_FORMAT_TAODA_DIRECTORY_T);
}
/**
* 获取当前日期字符串,格式"yyyyMMddHHmmssSSS"
* @return
*/
public static String getNow3() {
Calendar today = Calendar.getInstance();
return DateFormatUtils.format(today.getTime(), DATE_FORMAT_TAODA_DIRECTORY_S);
}
/**
* 获取当前日期字符串,格式"yyyy-MM-dd"
* @return
*/
public static String getNow4() {
Calendar today = Calendar.getInstance();
return DateFormatUtils.format(today.getTime(), DATE_FORMAT_DEFAULT);
}
/**
* 获取当前时间的指定格式
*/
public static String getCurrDate(String format) {
return dateToString(new Date(), format);
}
/**
* 把日期转换为字符串
*/
public static String dateToString(Date date, String format) {
return DateFormatUtils.format(date, format);
}
/**
* Date日期转化为格林威治天文台标准台时间
* @return
*/
public static String getISO8601Timestamp(Date date) {
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
df.setTimeZone(tz);
String nowAsISO = df.format(date);
return nowAsISO;
}
/**
* 把符合日期格式的字符串转换为日期类型
*/
public static Date stringtoDate(String dateStr) {
Date date = null;
try {
date = DateUtils.parseDate(dateStr, new String[]{"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd", "yyyy/MM/dd", "yyyyMMdd", "yyyy-MM", "yyyy年MM月dd日"});
} catch (ParseException e) {
throw new RuntimeException(e.getMessage(), e);
}
return date;
}
/**
* 把符合日期格式的字符串转换为日期类型在转化为符合条件的日期格式字符串
*/
public static String stringToDateToString(String dateStr, String format) {
Date date = null;
try {
date = DateUtils.parseDate(dateStr, new String[]{"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd", "yyyy/MM/dd", "yyyyMMdd", "yyyy-MM", "yyyy年MM月dd日"});
} catch (ParseException e) {
return "长期";
}
return dateToString(date, format);
}
/**
* @param dateStr
* @param format
* @return
* @Title: dateMatcher
* @Description: 日期格式验证
*/
public static boolean dateMatcher(String dateStr, String format) {
SimpleDateFormat df = new SimpleDateFormat(format);
df.setLenient(false);
try {
df.parse(dateStr);
} catch (Exception e) {
return false;
}
return true;
}
/**
* 将日期转换为字符串
* @param source
* @param outfmt
* @return
*/
public static String getDateFmtStr(Date source, String outfmt) {
String result = "";
// 输出格式
DateFormat outfomater = new SimpleDateFormat(outfmt);
try {
result = outfomater.format(source);
} catch (Exception e) {
result = outfomater.format(new Date());
}
return result;
}
/**
* @return String 时间字符串
* @throws
* @Description: 获取当前系统时间戳 格式:yyyy-mm-dd HH:mm:ss
*/
public static String getCurrentTimeStamp() {
return getCurrentDate("yyyy-MM-dd HH:mm:ss");
}
/**
* @param format 日期格式
* @return String 日期字符串
* @throws
* @Description: 获取当前系统日期
*/
public static String getCurrentDate(String format) {
return getCurrentDateTimeStr(format);
}
/**
* @param format 日期时间格式
* @return String 日期时间字符串
* @throws
* @Description: 获取当前日期时间字符串
*/
public static String getCurrentDateTimeStr(String format) {
DateFormat formater = new SimpleDateFormat(format);
return formater.format(new Date());
}
/**
* @throws
* @Description: long转为date
*/
public static Date longToNowDate(long time) {
long t1 = System.currentTimeMillis();
time = t1 + time;
return new Date(time);
}
public static Date stringToDate(String date, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date thisDate = null;
try {
thisDate = sdf.parse(date);
} catch (ParseException e) {
e.printStackTrace();
} finally {
return thisDate;
}
}
/**
* 2个日期之间的天数
* @param date1
* @param date2
* @return
* @throws ParseException
*/
public static int getMonthSpace(Date date1, Date date2) {
int result = 0;
Calendar cal1 = new GregorianCalendar();
cal1.setTime(date1);
Calendar cal2 = new GregorianCalendar();
cal2.setTime(date2);
result = (cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR)) * 12 + cal1.get(Calendar.MONTH) - cal2.get(Calendar.MONTH);
return result == 0 ? 1 : Math.abs(result);
}
/**
* 获取两月之间所有的时间
* @param minDateStr
* @param maxDateStr
* @return
*/
public static List<String> showAllTime(String minDateStr, String maxDateStr) {
List<String> list = new ArrayList<String>();
Date thisDate = new Date();
Date minDateTemp = DateUtil.stringToDate(minDateStrTemp, DateUtil.DATE_FORMAT_DEFAULT_MONTH);
Date minDate = DateUtil.stringToDate(minDateStr, DateUtil.DATE_FORMAT_DEFAULT_MONTH);
if (minDate == null) {
minDate = minDateTemp;
} else {
if (minDateTemp.after(minDate)) {
minDate = minDateTemp;
}
}
Date maxDate = DateUtil.stringToDate(maxDateStr, DateUtil.DATE_FORMAT_DEFAULT_MONTH);
if (maxDate == null) {
maxDate = thisDate;
} else {
if (maxDate.after(thisDate)) {
maxDate = thisDate;
}
}
int month = getMonthSpace(minDate, maxDate);
for (int i = 0; i <= month; i++) {
Date dateTemp = DateUtils.addMonths(minDate, i);
if(thisDate.after(dateTemp)){
list.add(DateUtil.dateToString(dateTemp, DateUtil.DATE_FORMAT_COMPACT_MONTH));
}
}
if (list.isEmpty()) {
list.add(DateUtil.dateToString(thisDate, DateUtil.DATE_FORMAT_COMPACT_MONTH));
}
return list;
}
/**
* 将数据类型的时间字符串转换成格式字符串
* @param date
* @param beforeFormat
* @param afterFormat
* @return
*/
public static String formatConversion(String date, String beforeFormat, String afterFormat) {
return DateUtil.formatDate(DateUtil.parseStrToDate(beforeFormat, date), afterFormat);
}
/**
* 比较两个日期的大小
* @param startDate
* @param endDate
* @return
*/
public static boolean comparingDate(Date startDate, Date endDate) {
if (startDate.after(endDate)) {
return true;
}
return false;
}
/**
* 获取当前时间的前24小时
* @param nowDate
* @param beforeNum
* @return
*/
public static Date getBeforeDate(Date nowDate, int beforeNum){
Calendar calendar = Calendar.getInstance(); //得到日历
calendar.setTime(nowDate);//把当前时间赋给日历
calendar.add(Calendar.DAY_OF_MONTH, -beforeNum); //设置为前beforeNum天
return calendar.getTime(); //得到前beforeNum天的时间
}
/**
* 获取两个日期之间的所有日期
* @param startTime 开始日期
* @param endTime 结束日期
* @return
*/
public static List<String> getDays(String startTime, String endTime) {
// 返回的日期集合
List<String> days = new ArrayList<String>();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date start = dateFormat.parse(startTime);
Date end = dateFormat.parse(endTime);
Calendar tempStart = Calendar.getInstance();
tempStart.setTime(start);
Calendar tempEnd = Calendar.getInstance();
tempEnd.setTime(end);
tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
while (tempStart.before(tempEnd)) {
days.add(dateFormat.format(tempStart.getTime()));
tempStart.add(Calendar.DAY_OF_YEAR, 1);
}
} catch (ParseException e) {
e.printStackTrace();
}
return days;
}
/**
* 字符串转换成日期
* @param str
* @return date
*/
public static Date strToDate(String str) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = format.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
| true |
f6c33deb21227fdb6f13d2aa08605c1823eb231e | Java | yuexing89757/personal_account | /personal_account/src/com/zzy/biz/ISendMail.java | UTF-8 | 923 | 2.078125 | 2 | [] | no_license | /**
* Project name:ads-mail
*
* Copyright Pzoomtech.com 2011, All Rights Reserved.
*
*/
package com.zzy.biz;
import org.apache.commons.mail.EmailException;
/**
* @name ISendMail
*
* @description CLASS_DESCRIPTION
*
* MORE_INFORMATION
*
* @author lijing
*
* @since 2011-2-17
*
* @version 1.0
*/
public interface ISendMail
{
/**
* sendMail(This method is used to send e-mail)
*
* @param toMail
* @param title
* @param mailConent
* @param attachPath
* @param attachDescription
* @param attachName
* @param Cc
* @param Bcc
* @param mailType(TEXT,HTML)
* @return
* @throws EmailException
* @throws Exception
*/
public boolean sendMail(String[] toMail, String title, String mailConent, String attachPath[], String attachDescription[], String attachName[],String[] Cc,String[] Bcc,String mailType,String classify)
throws EmailException, Exception;
}
| true |
f8a62619f96a207f57ac5b836847c9a6b1823b16 | Java | google/j2objc | /jre_emul/android/platform/external/icu/android_icu4j/src/main/tests/android/icu/dev/test/format/MessagePatternUtilTest.java | UTF-8 | 25,031 | 2.140625 | 2 | [
"Apache-2.0",
"BSD-3-Clause",
"GPL-2.0-only",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"APSL-1.0",
"LGPL-2.0-or-later",
"LicenseRef-scancode-proprietary-license",
"GPL-1.0-or-later",
"LicenseRef-scancode-generic-exception",
"LicenseRef-scancode-red-hat-attribution",
"ICU",
"MIT",... | permissive | /* GENERATED SOURCE. DO NOT MODIFY. */
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
/*
*******************************************************************************
* Copyright (C) 2011-2012, International Business Machines
* Corporation and others. All Rights Reserved.
*******************************************************************************
* created on: 2011aug12
* created by: Markus W. Scherer
*/
package android.icu.dev.test.format;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import org.junit.Test;
import android.icu.text.MessagePattern;
import android.icu.text.MessagePatternUtil;
import android.icu.text.MessagePatternUtil.ArgNode;
import android.icu.text.MessagePatternUtil.ComplexArgStyleNode;
import android.icu.text.MessagePatternUtil.MessageContentsNode;
import android.icu.text.MessagePatternUtil.MessageNode;
import android.icu.text.MessagePatternUtil.TextNode;
import android.icu.text.MessagePatternUtil.VariantNode;
/**
* Test MessagePatternUtil (MessagePattern-as-tree-of-nodes API)
* by building parallel trees of nodes and verifying that they match.
*/
public final class MessagePatternUtilTest extends android.icu.dev.test.TestFmwk {
// The following nested "Expect..." classes are used to build
// a tree structure parallel to what the MessagePatternUtil class builds.
// These nested test classes are not static so that they have access to TestFmwk methods.
private class ExpectMessageNode {
private ExpectMessageNode expectTextThatContains(String s) {
contents.add(new ExpectTextNode(s));
return this;
}
private ExpectMessageNode expectReplaceNumber() {
contents.add(new ExpectMessageContentsNode());
return this;
}
private ExpectMessageNode expectNoneArg(Object name) {
contents.add(new ExpectArgNode(name));
return this;
}
private ExpectMessageNode expectSimpleArg(Object name, String type) {
contents.add(new ExpectArgNode(name, type));
return this;
}
private ExpectMessageNode expectSimpleArg(Object name, String type, String style) {
contents.add(new ExpectArgNode(name, type, style));
return this;
}
private ExpectComplexArgNode expectChoiceArg(Object name) {
return expectComplexArg(name, MessagePattern.ArgType.CHOICE);
}
private ExpectComplexArgNode expectPluralArg(Object name) {
return expectComplexArg(name, MessagePattern.ArgType.PLURAL);
}
private ExpectComplexArgNode expectSelectArg(Object name) {
return expectComplexArg(name, MessagePattern.ArgType.SELECT);
}
private ExpectComplexArgNode expectSelectOrdinalArg(Object name) {
return expectComplexArg(name, MessagePattern.ArgType.SELECTORDINAL);
}
private ExpectComplexArgNode expectComplexArg(Object name, MessagePattern.ArgType argType) {
ExpectComplexArgNode complexArg = new ExpectComplexArgNode(this, name, argType);
contents.add(complexArg);
return complexArg;
}
private ExpectComplexArgNode finishVariant() {
return parent;
}
private void checkMatches(MessageNode msg) {
// matches() prints all errors.
matches(msg);
}
private boolean matches(MessageNode msg) {
List<MessageContentsNode> msgContents = msg.getContents();
boolean ok = assertEquals("different numbers of MessageContentsNode",
contents.size(), msgContents.size());
if (ok) {
Iterator<MessageContentsNode> msgIter = msgContents.iterator();
for (ExpectMessageContentsNode ec : contents) {
ok &= ec.matches(msgIter.next());
}
}
if (!ok) {
errln("error in message: " + msg.toString());
}
return ok;
}
private ExpectComplexArgNode parent; // for finishVariant()
private List<ExpectMessageContentsNode> contents =
new ArrayList<ExpectMessageContentsNode>();
}
/**
* Base class for message contents nodes.
* Used directly for REPLACE_NUMBER nodes, subclassed for others.
*/
private class ExpectMessageContentsNode {
protected boolean matches(MessageContentsNode c) {
return assertEquals("not a REPLACE_NUMBER node",
MessageContentsNode.Type.REPLACE_NUMBER, c.getType());
}
}
private class ExpectTextNode extends ExpectMessageContentsNode {
private ExpectTextNode(String subString) {
this.subString = subString;
}
@Override
protected boolean matches(MessageContentsNode c) {
return
assertEquals("not a TextNode",
MessageContentsNode.Type.TEXT, c.getType()) &&
assertTrue("TextNode does not contain \"" + subString + "\"",
((TextNode)c).getText().contains(subString));
}
private String subString;
}
private class ExpectArgNode extends ExpectMessageContentsNode {
private ExpectArgNode(Object name) {
this(name, null, null);
}
private ExpectArgNode(Object name, String type) {
this(name, type, null);
}
private ExpectArgNode(Object name, String type, String style) {
if (name instanceof String) {
this.name = (String)name;
this.number = -1;
} else {
this.number = (Integer)name;
this.name = Integer.toString(this.number);
}
if (type == null) {
argType = MessagePattern.ArgType.NONE;
} else {
argType = MessagePattern.ArgType.SIMPLE;
}
this.type = type;
this.style = style;
}
@Override
protected boolean matches(MessageContentsNode c) {
boolean ok =
assertEquals("not an ArgNode",
MessageContentsNode.Type.ARG, c.getType());
if (!ok) {
return ok;
}
ArgNode arg = (ArgNode)c;
ok &= assertEquals("unexpected ArgNode argType",
argType, arg.getArgType());
ok &= assertEquals("unexpected ArgNode arg name",
name, arg.getName());
ok &= assertEquals("unexpected ArgNode arg number",
number, arg.getNumber());
ok &= assertEquals("unexpected ArgNode arg type name",
type, arg.getTypeName());
ok &= assertEquals("unexpected ArgNode arg style",
style, arg.getSimpleStyle());
if (argType == MessagePattern.ArgType.NONE || argType == MessagePattern.ArgType.SIMPLE) {
ok &= assertNull("unexpected non-null complex style", arg.getComplexStyle());
}
return ok;
}
private String name;
private int number;
protected MessagePattern.ArgType argType;
private String type;
private String style;
}
private class ExpectComplexArgNode extends ExpectArgNode {
private ExpectComplexArgNode(ExpectMessageNode parent,
Object name, MessagePattern.ArgType argType) {
super(name, argType.toString().toLowerCase(Locale.ENGLISH));
this.argType = argType;
this.parent = parent;
}
private ExpectComplexArgNode expectOffset(double offset) {
this.offset = offset;
explicitOffset = true;
return this;
}
private ExpectMessageNode expectVariant(String selector) {
ExpectVariantNode variant = new ExpectVariantNode(this, selector);
variants.add(variant);
return variant.msg;
}
private ExpectMessageNode expectVariant(String selector, double value) {
ExpectVariantNode variant = new ExpectVariantNode(this, selector, value);
variants.add(variant);
return variant.msg;
}
private ExpectMessageNode finishComplexArg() {
return parent;
}
@Override
protected boolean matches(MessageContentsNode c) {
boolean ok = super.matches(c);
if (!ok) {
return ok;
}
ArgNode arg = (ArgNode)c;
ComplexArgStyleNode complexStyle = arg.getComplexStyle();
ok &= assertNotNull("unexpected null complex style", complexStyle);
if (!ok) {
return ok;
}
ok &= assertEquals("unexpected complex-style argType",
argType, complexStyle.getArgType());
ok &= assertEquals("unexpected complex-style hasExplicitOffset()",
explicitOffset, complexStyle.hasExplicitOffset());
ok &= assertEquals("unexpected complex-style offset",
offset, complexStyle.getOffset());
List<VariantNode> complexVariants = complexStyle.getVariants();
ok &= assertEquals("different number of variants",
variants.size(), complexVariants.size());
if (!ok) {
return ok;
}
Iterator<VariantNode> complexIter = complexVariants.iterator();
for (ExpectVariantNode variant : variants) {
ok &= variant.matches(complexIter.next());
}
return ok;
}
private ExpectMessageNode parent; // for finishComplexArg()
private boolean explicitOffset;
private double offset;
private List<ExpectVariantNode> variants = new ArrayList<ExpectVariantNode>();
}
private class ExpectVariantNode {
private ExpectVariantNode(ExpectComplexArgNode parent, String selector) {
this(parent, selector, MessagePattern.NO_NUMERIC_VALUE);
}
private ExpectVariantNode(ExpectComplexArgNode parent, String selector, double value) {
this.selector = selector;
numericValue = value;
msg = new ExpectMessageNode();
msg.parent = parent;
}
private boolean matches(VariantNode v) {
boolean ok = assertEquals("different selector strings",
selector, v.getSelector());
ok &= assertEquals("different selector strings",
isSelectorNumeric(), v.isSelectorNumeric());
ok &= assertEquals("different selector strings",
numericValue, v.getSelectorValue());
return ok & msg.matches(v.getMessage());
}
private boolean isSelectorNumeric() {
return numericValue != MessagePattern.NO_NUMERIC_VALUE;
}
private String selector;
private double numericValue;
private ExpectMessageNode msg;
}
// The actual tests start here. ---------------------------------------- ***
// Sample message strings are mostly from the MessagePatternUtilDemo.
@Test
public void TestHello() {
// No syntax.
MessageNode msg = MessagePatternUtil.buildMessageNode("Hello!");
ExpectMessageNode expect = new ExpectMessageNode().expectTextThatContains("Hello");
expect.checkMatches(msg);
}
@Test
public void TestHelloWithApos() {
// Literal ASCII apostrophe.
MessageNode msg = MessagePatternUtil.buildMessageNode("Hel'lo!");
ExpectMessageNode expect = new ExpectMessageNode().expectTextThatContains("Hel'lo");
expect.checkMatches(msg);
}
@Test
public void TestHelloWithQuote() {
// Apostrophe starts quoted literal text.
MessageNode msg = MessagePatternUtil.buildMessageNode("Hel'{o!");
ExpectMessageNode expect = new ExpectMessageNode().expectTextThatContains("Hel{o");
expect.checkMatches(msg);
// Terminating the quote should yield the same result.
msg = MessagePatternUtil.buildMessageNode("Hel'{'o!");
expect.checkMatches(msg);
// Double apostrophe inside quoted literal text still encodes a single apostrophe.
msg = MessagePatternUtil.buildMessageNode("a'{bc''de'f");
expect = new ExpectMessageNode().expectTextThatContains("a{bc'def");
expect.checkMatches(msg);
}
@Test
public void TestNoneArg() {
// Numbered argument.
MessageNode msg = MessagePatternUtil.buildMessageNode("abc{0}def");
ExpectMessageNode expect = new ExpectMessageNode().
expectTextThatContains("abc").expectNoneArg(0).expectTextThatContains("def");
expect.checkMatches(msg);
// Named argument.
msg = MessagePatternUtil.buildMessageNode("abc{ arg }def");
expect = new ExpectMessageNode().
expectTextThatContains("abc").expectNoneArg("arg").expectTextThatContains("def");
expect.checkMatches(msg);
// Numbered and named arguments.
msg = MessagePatternUtil.buildMessageNode("abc{1}def{arg}ghi");
expect = new ExpectMessageNode().
expectTextThatContains("abc").expectNoneArg(1).expectTextThatContains("def").
expectNoneArg("arg").expectTextThatContains("ghi");
expect.checkMatches(msg);
}
@Test
public void TestSimpleArg() {
MessageNode msg = MessagePatternUtil.buildMessageNode("a'{bc''de'f{0,number,g'hi''jk'l#}");
ExpectMessageNode expect = new ExpectMessageNode().
expectTextThatContains("a{bc'def").expectSimpleArg(0, "number", "g'hi''jk'l#");
expect.checkMatches(msg);
}
@Test
public void TestSelectArg() {
MessageNode msg = MessagePatternUtil.buildMessageNode(
"abc{2, number}ghi{3, select, xx {xxx} other {ooo}} xyz");
ExpectMessageNode expect = new ExpectMessageNode().
expectTextThatContains("abc").expectSimpleArg(2, "number").
expectTextThatContains("ghi").
expectSelectArg(3).
expectVariant("xx").expectTextThatContains("xxx").finishVariant().
expectVariant("other").expectTextThatContains("ooo").finishVariant().
finishComplexArg().
expectTextThatContains(" xyz");
expect.checkMatches(msg);
}
@Test
public void TestPluralArg() {
// Plural with only keywords.
MessageNode msg = MessagePatternUtil.buildMessageNode(
"abc{num_people, plural, offset:17 few{fff} other {oooo}}xyz");
ExpectMessageNode expect = new ExpectMessageNode().
expectTextThatContains("abc").
expectPluralArg("num_people").
expectOffset(17).
expectVariant("few").expectTextThatContains("fff").finishVariant().
expectVariant("other").expectTextThatContains("oooo").finishVariant().
finishComplexArg().
expectTextThatContains("xyz");
expect.checkMatches(msg);
// Plural with explicit-value selectors.
msg = MessagePatternUtil.buildMessageNode(
"abc{ num , plural , offset: 2 =1 {1} =-1 {-1} =3.14 {3.14} other {oo} }xyz");
expect = new ExpectMessageNode().
expectTextThatContains("abc").
expectPluralArg("num").
expectOffset(2).
expectVariant("=1", 1).expectTextThatContains("1").finishVariant().
expectVariant("=-1", -1).expectTextThatContains("-1").finishVariant().
expectVariant("=3.14", 3.14).expectTextThatContains("3.14").finishVariant().
expectVariant("other").expectTextThatContains("oo").finishVariant().
finishComplexArg().
expectTextThatContains("xyz");
expect.checkMatches(msg);
// Plural with number replacement.
msg = MessagePatternUtil.buildMessageNode(
"a_{0,plural,other{num=#'#'=#'#'={1,number,##}!}}_z");
expect = new ExpectMessageNode().
expectTextThatContains("a_").
expectPluralArg(0).
expectVariant("other").
expectTextThatContains("num=").expectReplaceNumber().
expectTextThatContains("#=").expectReplaceNumber().
expectTextThatContains("#=").expectSimpleArg(1, "number", "##").
expectTextThatContains("!").finishVariant().
finishComplexArg().
expectTextThatContains("_z");
expect.checkMatches(msg);
// Plural with explicit offset:0.
msg = MessagePatternUtil.buildMessageNode(
"a_{0,plural,offset:0 other{num=#!}}_z");
expect = new ExpectMessageNode().
expectTextThatContains("a_").
expectPluralArg(0).
expectOffset(0).
expectVariant("other").
expectTextThatContains("num=").expectReplaceNumber().
expectTextThatContains("!").finishVariant().
finishComplexArg().
expectTextThatContains("_z");
expect.checkMatches(msg);
}
@Test
public void TestSelectOrdinalArg() {
MessageNode msg = MessagePatternUtil.buildMessageNode(
"abc{num, selectordinal, offset:17 =0{null} few{fff} other {oooo}}xyz");
ExpectMessageNode expect = new ExpectMessageNode().
expectTextThatContains("abc").
expectSelectOrdinalArg("num").
expectOffset(17).
expectVariant("=0", 0).expectTextThatContains("null").finishVariant().
expectVariant("few").expectTextThatContains("fff").finishVariant().
expectVariant("other").expectTextThatContains("oooo").finishVariant().
finishComplexArg().
expectTextThatContains("xyz");
expect.checkMatches(msg);
}
@Test
public void TestChoiceArg() {
MessageNode msg = MessagePatternUtil.buildMessageNode(
"a_{0,choice,-∞ #-inf| 5≤ five | 99 # ninety'|'nine }_z");
ExpectMessageNode expect = new ExpectMessageNode().
expectTextThatContains("a_").
expectChoiceArg(0).
expectVariant("#", Double.NEGATIVE_INFINITY).
expectTextThatContains("-inf").finishVariant().
expectVariant("≤", 5).expectTextThatContains(" five ").finishVariant().
expectVariant("#", 99).expectTextThatContains(" ninety|nine ").finishVariant().
finishComplexArg().
expectTextThatContains("_z");
expect.checkMatches(msg);
}
@Test
public void TestComplexArgs() {
MessageNode msg = MessagePatternUtil.buildMessageNode(
"I don't {a,plural,other{w'{'on't #'#'}} and "+
"{b,select,other{shan't'}'}} '{'''know'''}' and "+
"{c,choice,0#can't'|'}"+
"{z,number,#'#'###.00'}'}.");
ExpectMessageNode expect = new ExpectMessageNode().
expectTextThatContains("I don't ").
expectPluralArg("a").
expectVariant("other").
expectTextThatContains("w{on't ").expectReplaceNumber().
expectTextThatContains("#").finishVariant().
finishComplexArg().
expectTextThatContains(" and ").
expectSelectArg("b").
expectVariant("other").expectTextThatContains("shan't}").finishVariant().
finishComplexArg().
expectTextThatContains(" {'know'} and ").
expectChoiceArg("c").
expectVariant("#", 0).expectTextThatContains("can't|").finishVariant().
finishComplexArg().
expectSimpleArg("z", "number", "#'#'###.00'}'").
expectTextThatContains(".");
expect.checkMatches(msg);
}
/**
* @return the text string of the VariantNode's message;
* assumes that its message consists of only text
*/
private String variantText(VariantNode v) {
return ((TextNode)v.getMessage().getContents().get(0)).getText();
}
@Test
public void TestPluralVariantsByType() {
MessageNode msg = MessagePatternUtil.buildMessageNode(
"{p,plural,a{A}other{O}=4{iv}b{B}other{U}=2{ii}}");
ExpectMessageNode expect = new ExpectMessageNode().
expectPluralArg("p").
expectVariant("a").expectTextThatContains("A").finishVariant().
expectVariant("other").expectTextThatContains("O").finishVariant().
expectVariant("=4", 4).expectTextThatContains("iv").finishVariant().
expectVariant("b").expectTextThatContains("B").finishVariant().
expectVariant("other").expectTextThatContains("U").finishVariant().
expectVariant("=2", 2).expectTextThatContains("ii").finishVariant().
finishComplexArg();
if (!expect.matches(msg)) {
return;
}
List<VariantNode> numericVariants = new ArrayList<VariantNode>();
List<VariantNode> keywordVariants = new ArrayList<VariantNode>();
VariantNode other =
((ArgNode)msg.getContents().get(0)).getComplexStyle().
getVariantsByType(numericVariants, keywordVariants);
assertEquals("'other' selector", "other", other.getSelector());
assertEquals("message string of first 'other'", "O", variantText(other));
assertEquals("numericVariants.size()", 2, numericVariants.size());
VariantNode v = numericVariants.get(0);
assertEquals("numericVariants[0] selector", "=4", v.getSelector());
assertEquals("numericVariants[0] selector value", 4., v.getSelectorValue());
assertEquals("numericVariants[0] text", "iv", variantText(v));
v = numericVariants.get(1);
assertEquals("numericVariants[1] selector", "=2", v.getSelector());
assertEquals("numericVariants[1] selector value", 2., v.getSelectorValue());
assertEquals("numericVariants[1] text", "ii", variantText(v));
assertEquals("keywordVariants.size()", 2, keywordVariants.size());
v = keywordVariants.get(0);
assertEquals("keywordVariants[0] selector", "a", v.getSelector());
assertFalse("keywordVariants[0].isSelectorNumeric()", v.isSelectorNumeric());
assertEquals("keywordVariants[0] text", "A", variantText(v));
v = keywordVariants.get(1);
assertEquals("keywordVariants[1] selector", "b", v.getSelector());
assertFalse("keywordVariants[1].isSelectorNumeric()", v.isSelectorNumeric());
assertEquals("keywordVariants[1] text", "B", variantText(v));
}
@Test
public void TestSelectVariantsByType() {
MessageNode msg = MessagePatternUtil.buildMessageNode(
"{s,select,a{A}other{O}b{B}other{U}}");
ExpectMessageNode expect = new ExpectMessageNode().
expectSelectArg("s").
expectVariant("a").expectTextThatContains("A").finishVariant().
expectVariant("other").expectTextThatContains("O").finishVariant().
expectVariant("b").expectTextThatContains("B").finishVariant().
expectVariant("other").expectTextThatContains("U").finishVariant().
finishComplexArg();
if (!expect.matches(msg)) {
return;
}
// Check that we can use numericVariants = null.
List<VariantNode> keywordVariants = new ArrayList<VariantNode>();
VariantNode other =
((ArgNode)msg.getContents().get(0)).getComplexStyle().
getVariantsByType(null, keywordVariants);
assertEquals("'other' selector", "other", other.getSelector());
assertEquals("message string of first 'other'", "O", variantText(other));
assertEquals("keywordVariants.size()", 2, keywordVariants.size());
VariantNode v = keywordVariants.get(0);
assertEquals("keywordVariants[0] selector", "a", v.getSelector());
assertFalse("keywordVariants[0].isSelectorNumeric()", v.isSelectorNumeric());
assertEquals("keywordVariants[0] text", "A", variantText(v));
v = keywordVariants.get(1);
assertEquals("keywordVariants[1] selector", "b", v.getSelector());
assertFalse("keywordVariants[1].isSelectorNumeric()", v.isSelectorNumeric());
assertEquals("keywordVariants[1] text", "B", variantText(v));
}
}
| true |
73309383a8c7ae59d658fcc8e830b574753777fd | Java | r0g3r5/AdministracionVistasApringAngular | /CODIGO/VistaAdminAppBackEnd/VistaAdminRepositoryModule/src/main/java/com/myapps/vista_admin/repository/MenuRepository.java | UTF-8 | 610 | 1.898438 | 2 | [] | no_license | package com.myapps.vista_admin.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.myapps.vista_admin.model.VAMenuEntity;
@Repository
public interface MenuRepository extends JpaRepository<VAMenuEntity, Integer> {
@Query("SELECT a.formulario.menu FROM VAAccesoEntity a WHERE a.rol.nombre = :rol ORDER BY a.formulario.menu.orden")
List<VAMenuEntity> findByRol(@Param("rol") String rol);
}
| true |
262a06e2b58c63152a804e82413befac7848eb73 | Java | HaifaFeddaoui/CRM-JEE | /ProjetCRM/ProjetCRM/ProjetCRM-ejb/src/main/java/model/Competition.java | UTF-8 | 2,755 | 2.1875 | 2 | [] | no_license | package Entities;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
/**
* The persistent class for the Competitions database table.
*
*/
@Entity
@Table(name="Competitions")
@NamedQuery(name="Competition.findAll", query="SELECT c FROM Competition c")
public class Competition implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="CompetitionId")
private int competitionId;
@Column(name="CompetitionDesc")
private String competitionDesc;
@Column(name="CompetitionName")
private String competitionName;
@Column(name="ImageCompetition")
private String imageCompetition;
@Column(name="OfferId")
private int offerId;
@Column(name="ProductId")
private int productId;
private float solde;
//bi-directional many-to-one association to Participation
@OneToMany(mappedBy="competition")
private List<Participation> participations;
public Competition() {
}
public int getCompetitionId() {
return this.competitionId;
}
public void setCompetitionId(int competitionId) {
this.competitionId = competitionId;
}
public String getCompetitionDesc() {
return this.competitionDesc;
}
public void setCompetitionDesc(String competitionDesc) {
this.competitionDesc = competitionDesc;
}
public String getCompetitionName() {
return this.competitionName;
}
public void setCompetitionName(String competitionName) {
this.competitionName = competitionName;
}
public String getImageCompetition() {
return this.imageCompetition;
}
public void setImageCompetition(String imageCompetition) {
this.imageCompetition = imageCompetition;
}
public int getOfferId() {
return this.offerId;
}
public void setOfferId(int offerId) {
this.offerId = offerId;
}
public int getProductId() {
return this.productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public float getSolde() {
return this.solde;
}
public void setSolde(float solde) {
this.solde = solde;
}
public List<Participation> getParticipations() {
return this.participations;
}
public void setParticipations(List<Participation> participations) {
this.participations = participations;
}
public Participation addParticipation(Participation participation) {
getParticipations().add(participation);
participation.setCompetition(this);
return participation;
}
public Participation removeParticipation(Participation participation) {
getParticipations().remove(participation);
participation.setCompetition(null);
return participation;
}
} | true |
c50faf82a2065656b990dfc6a017c7eae7e2b49c | Java | luckyXingYan/MVPDemo | /app/src/main/java/com/example/mvpdemo/fragment/ProductPageFragment.java | UTF-8 | 1,271 | 2.171875 | 2 | [] | no_license | package com.example.mvpdemo.fragment;
import android.util.Log;
import android.view.View;
import com.example.mvpdemo.R;
import com.example.mvpdemo.base.mvp.BaseFragment;
import com.example.mvpdemo.bean.ProductDataBean;
import com.example.mvpdemo.iview.IProductPageView;
import com.example.mvpdemo.presenter.ProductPagePresenter;
import java.util.List;
/**
* @Author: xingyan
* @Date: 2019/8/2
* @Desc:
*/
public class ProductPageFragment extends BaseFragment<ProductPagePresenter> implements IProductPageView {
private static final String TAG = "ProductPageFragment";
public static ProductPageFragment newInstance() {
return new ProductPageFragment();
}
@Override
public int layoutId() {
return R.layout.fragment_product_page;
}
@Override
protected void initView(View view) {
}
@Override
protected void initData() {
if (presenter != null) {
presenter.getProductPageData("0", "1", getActivity());
}
}
@Override
public void updateProductData(List<ProductDataBean> data) {
Log.e(TAG, "updateProductData:" + data.toString());
}
@Override
public ProductPagePresenter createPresenter() {
return new ProductPagePresenter();
}
}
| true |
88c89a4afa2a684a9ee81dd9c8e054bb81b1b7b5 | Java | 1424234500/walker | /walker-core/src/main/java/com/walker/core/encode/RSAUtil.java | UTF-8 | 4,098 | 2.9375 | 3 | [] | no_license | package com.walker.core.encode;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.LoggerFactory;
import javax.crypto.Cipher;
import java.security.*;
/**
* RSA 工具类。提供加密,解密,生成密钥对等方法。
*
* <dependency>
* <groupId>org.bouncycastle</groupId>
* <artifactId>bcpkix-jdk15on</artifactId>
* <version>1.60</version>
* </dependency>
*/
public class RSAUtil {
static KeyPairGenerator keyPairGen;
static {
try {
keyPairGen = KeyPairGenerator.getInstance("RSA",
new BouncyCastleProvider());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
// 没什么好说的了,这个值关系到块加密的大小,可以更改,但是不要太大,否则效率会低
final int KEY_SIZE = 256;//1024;
keyPairGen.initialize(KEY_SIZE, new SecureRandom());
}
/**
* 生成密钥对 公钥 私钥
*/
public static KeyPair generateKeyPair() throws Exception {
try {
return keyPairGen.generateKeyPair();
} catch (Exception e) {
throw new Exception(e.getMessage(), e);
}
}
public static String encrypt(PublicKey pk, String str) throws Exception {
return new String(encrypt(pk, str.getBytes()));
}
/**
* 加密
*/
public static byte[] encrypt(PublicKey pk, byte[] data) throws Exception {
try {
Cipher cipher = Cipher.getInstance("RSA",
new BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, pk);
// 获得加密块大小,如:加密前数据为128个byte,而key_size=1024
int blockSize = cipher.getBlockSize();
// 加密块大小为127
// byte,加密后为128个byte;因此共有2个加密块,第一个127
// byte第二个为1个byte
// 获得加密块加密后块大小
byte[] raw = new byte[0];
if (blockSize > 0) {
int outputSize = cipher.getOutputSize(data.length);
int leavedSize = data.length % blockSize;
int blocksSize = leavedSize != 0 ? data.length / blockSize + 1
: data.length / blockSize;
raw = new byte[outputSize * blocksSize];
int i = 0;
while (data.length - i * blockSize > 0) {
if (data.length - i * blockSize > blockSize) {
cipher.doFinal(data, i * blockSize, blockSize, raw, i
* outputSize);
} else {
cipher.doFinal(data, i * blockSize, data.length - i
* blockSize, raw, i * outputSize);
}
// 这里面doUpdate方法不可用,查看源代码后发现每次doUpdate后并没有什么实际动作除了把byte[]放到
// ByteArrayOutputStream中,而最后doFinal的时候才将所有的byte[]进行加密,可是到了此时加密块大小很可能已经超出了
// OutputSize所以只好用dofinal方法。
i++;
}
} else {
LoggerFactory.getLogger(RSAUtil.class).info("block size is zero, please check.");
}
return raw;
} catch (Exception e) {
throw new Exception(e.getMessage(), e);
}
}
/**
* 解密
*/
public static byte[] decryptshort(PrivateKey pk, byte[] raw) throws Exception {
try {
Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
cipher.init(Cipher.DECRYPT_MODE, pk);
return cipher.doFinal(raw);
} catch (Exception e) {
throw new Exception(e.getMessage(), e);
}
}
} | true |
291b0c6155055a79abf54acbaa467a304fbe287b | Java | ArturoCercadillo/uam | /src/main/java/es/hazerta/uam/beans/Asignatura.java | UTF-8 | 828 | 2.515625 | 3 | [] | no_license | package es.hazerta.uam.beans;
public class Asignatura {
private String descripcion;
private String profesor;
private int id;
private double media;
public Asignatura(String descripcion, String profesor, int id, double media) {
super();
this.descripcion = descripcion;
this.profesor = profesor;
this.id = id;
this.media = media;
}
public double getMedia() {
return media;
}
public void setMedia(double media) {
this.media = media;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getProfesor() {
return profesor;
}
public void setProfesor(String profesor) {
this.profesor = profesor;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
| true |
a8266536a9511973e75f2c9292b22d259fd0454e | Java | 18482138228/Heima20200430_2 | /day3/src/Demo2/ForTest4.java | UTF-8 | 376 | 3.1875 | 3 | [] | no_license | package Demo2;
public class ForTest4 {
public static void main(String[] args) {
int count = 0;
for(int x=1;x<1000;x++){
int ge = x%10;
int shi = x/10%10;
int bai = x/100%10;
if(ge*ge*ge+shi*shi*shi+bai*bai*bai==x){
count++;
}
}
System.out.println(count);
}
}
| true |
e433b24aac5f0c891319bccde7dabf97d2e6f77c | Java | syanima/TCP-conversation | /TCPChitChat/src/CommunicatingServer.java | UTF-8 | 1,170 | 3.421875 | 3 | [] | no_license | import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class CommunicatingServer {
public static void main(String[] args) throws Exception {
String receiveMessage, sendMessage;
ServerSocket serverSocket = new ServerSocket(6789);
System.out.println("Server ready for chatting");
Socket socket = serverSocket.accept();
// reading from keyboard (inFromServer object)
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(System.in));
// sending to client (pwrite object)
OutputStream out = socket.getOutputStream();
PrintWriter pwrite = new PrintWriter(out, true);
// receiving from server ( inFromClient object)
InputStream in = socket.getInputStream();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(in));
while (true) {
if ((receiveMessage = inFromClient.readLine()) != null) {
System.out.println(receiveMessage);
}
sendMessage = inFromServer.readLine();
pwrite.println(sendMessage);
pwrite.flush();
}
}
}
| true |
ae6d645b98cc33a258a4942157c2cc7a2d76183f | Java | Sampathkonka/UserAdminServices | /src/main/java/com/okta/UserAdminServices/controller/AdminServiceController.java | UTF-8 | 2,020 | 2.046875 | 2 | [] | no_license | package com.okta.UserAdminServices.controller;
import java.io.IOException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.okta.UserAdminServices.UserAdminServicesApplication;
import com.okta.UserAdminServices.service.AssignOrRevokeUsersToApplication;
import com.okta.UserAdminServices.service.ReadOktaDataService;
@RestController
@RequestMapping("/okta")
public class AdminServiceController {
private static final Logger logger = LoggerFactory.getLogger(AdminServiceController.class);
@Autowired
private ReadOktaDataService listAppService;
@Autowired
private AssignOrRevokeUsersToApplication assignUsersToApplication;
@GetMapping("/getUsers")
public List<String> listUsers() throws IOException {
logger.info("Get Users API got triggered");
return listAppService.getUsers();
}
@GetMapping("/getApplications")
public List<String> listApplications() throws IOException {
logger.info("Get Applications API got triggered");
return listAppService.getApplictions();
}
@GetMapping("/assignUser")
public ResponseEntity<String> assignAppToUser(@RequestParam String userId, @RequestParam String appId) throws IOException {
logger.info("Assign the Application access to the User API triggered");
return assignUsersToApplication.assignUsersToApplication(userId, appId);
}
@GetMapping("/revokeUser")
public ResponseEntity<String> revokeUserFromApp(@RequestParam String userId, @RequestParam String appId) throws IOException {
logger.info("Revoke Application Access to the User API Triggered");
return assignUsersToApplication.revokeUserFromApplication(userId, appId);
}
} | true |
ee24566419f7c7a3d575aede5f861f3bc4bd367e | Java | VCOUTURIER-MADNOT/JavaProjet | /src/java/JavaRMI/Classes/Boutique.java | UTF-8 | 2,425 | 2.640625 | 3 | [] | no_license | package JavaRMI.Classes;
import JavaRMI.Gestionnaires.Gestionnaire;
import java.io.Serializable;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Objects;
public class Boutique implements Serializable{
private static final long serialVersionUID = 1L;
private String nom;
private int tcpPort;
private int udpPort;
private Inet4Address ip;
private Utilisateur admin;
public Boutique(String _loginAdmin, int _tcpPort, int _udpPort)
{
try {
this.nom = _loginAdmin + "'s Shop";
this.ip = (Inet4Address) Inet4Address.getAllByName("0.0.0.0")[0];
Gestionnaire ge = new Gestionnaire();
this.admin = ge.GU.getUtilisateur(_loginAdmin);
this.tcpPort = _tcpPort;
this.udpPort = _udpPort;
} catch (Exception ex) {
ex.printStackTrace();
}
}
public int getTcpPort() {
return tcpPort;
}
public void setTcpPort(int tcpPort) {
this.tcpPort = tcpPort;
}
public int getUdpPort() {
return udpPort;
}
public void setUdpPort(int udpPort) {
this.udpPort = udpPort;
}
public Inet4Address getIp() {
return this.ip;
}
public void setIp(Inet4Address _ip) {
this.ip = ip;
}
public String getNom() {
return nom;
}
public Utilisateur getAdmin() {
return admin;
}
public String ipToString()
{
return this.ip.getHostAddress();
}
public void setIpFromString(String _ipPort)
{
String[] split = _ipPort.split(":");
try {
this.ip = (Inet4Address) InetAddress.getAllByName(split[0])[0];
} catch (UnknownHostException ex) {
ex.printStackTrace();
}
}
@Override
public String toString() {
return "Boutique{" + "nom=" + nom + ", ip=" + ip.getHostAddress() + ", admin=" + admin + '}';
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Boutique other = (Boutique) obj;
if (!Objects.equals(this.admin, other.admin)) {
return false;
}
return true;
}
}
| true |
f04666221b497289d15192fdd89259bf8a55ae9a | Java | 12711/Exam-12711-20161229-1 | /src/main/java/com/lsm/App.java | UTF-8 | 1,168 | 2.71875 | 3 | [] | no_license | package com.lsm;
import java.util.Arrays;
import java.util.Scanner;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.lsm.dto.Film;
import com.lsm.service.FilmService;
/**
* Hello world!
*
*/
public class App {
public static void main(String[] args) {
ClassPathXmlApplicationContext application = new ClassPathXmlApplicationContext(
"classpath:ApplicationContext.xml");
Scanner in = new Scanner(System.in);
FilmService filmService = application.getBean("FilmService", FilmService.class);
while (true) {
System.out.println("请选择是否添加电影:\n--------1.添加--0.不添加------");
String flag = in.next();
if ("0".equals(flag)) {
//关闭application
application.close();
break;
}
Film film = new Film();
System.out.println("请输入电影名:");
String title = in.next();
film.setTitle(title);
System.out.println("请输入电影描述:");
film.setDescription(in.next());
System.out.println("请输入语言ID:");
film.setLanguageId(in.nextInt());
filmService.insertFilm(film);
}
}
}
| true |
19543bf3cb22d2b2dbbc92cf1a095100dd82c078 | Java | zbtmaker/LeetCode | /test/dp/StoneGameVII1690Test.java | UTF-8 | 372 | 2.203125 | 2 | [] | no_license | package dp;
import junit.framework.TestCase;
import org.junit.Assert;
/**
* @author Baitao Zou
* date 2020/12/25
*/
public class StoneGameVII1690Test extends TestCase {
private StoneGameVII1690 game = new StoneGameVII1690();
public void test1() {
int result = game.stoneGameVII(new int[]{5, 3, 1, 4, 2});
Assert.assertEquals(result, 6);
}
}
| true |
c5946d888103d8e707b7c12d38f06311a497c564 | Java | VicenTYC/LabSafety | /src/main/java/com/ssm/pojo/Question.java | UTF-8 | 1,388 | 1.921875 | 2 | [] | no_license | package com.ssm.pojo;
import org.springframework.stereotype.Component;
@Component
public class Question {
int question_id;
String question_content;
String question_item;
String question_answer;
int question_type;
int bank_id;
String question_analysis;
public String getQuestion_analysis() {
return question_analysis;
}
public void setQuestion_analysis(String question_analysis) {
this.question_analysis = question_analysis;
}
public int getQuestion_id() {
return question_id;
}
public void setQuestion_id(int question_id) {
this.question_id = question_id;
}
public String getQuestion_content() {
return question_content;
}
public void setQuestion_content(String question_content) {
this.question_content = question_content;
}
public String getQuestion_item() {
return question_item;
}
public void setQuestion_item(String question_item) {
this.question_item = question_item;
}
public String getQuestion_answer() {
return question_answer;
}
public void setQuestion_answer(String question_answer) {
this.question_answer = question_answer;
}
public int getQuestion_type() {
return question_type;
}
public void setQuestion_type(int question_type) {
this.question_type = question_type;
}
public int getBank_id() {
return bank_id;
}
public void setBank_id(int bank_id) {
this.bank_id = bank_id;
}
}
| true |
2b32750e8ec8795c73c0d618499818f3dd50da0b | Java | willenfoo/headfirst | /src/com/strategy/Cat.java | UTF-8 | 754 | 3.578125 | 4 | [] | no_license | package com.strategy;
public class Cat implements Comparable {
public Cat(Integer age) {
super();
this.age = age;
}
private Integer age;
private Comparator comparator = new CatAgeComparator();
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Comparator getComparator() {
return comparator;
}
public void setComparator(Comparator comparator) {
this.comparator = comparator;
}
@Override
public int compareTo(Object obj) {
/*Cat cat = (Cat)obj;
if (cat.getAge() > this.age) {
return 1;
} else if (cat.getAge() < this.age) {
return -1;
} else {
return 0;
}*/
return comparator.compare(this, obj);
}
}
| true |
8eb6f543f03d21e337c84ca4724eaf4134f2373f | Java | eevans/sstable-util | /metadata-json/src/main/java/org/wikimedia/cassandra/SSTableMetadataJson.java | UTF-8 | 1,157 | 2.53125 | 3 | [] | no_license | package org.wikimedia.cassandra;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class SSTableMetadataJson {
private static ObjectMapper mapper = new ObjectMapper();
static {
mapper.enable(SerializationFeature.INDENT_OUTPUT);
}
public static void main(String... args) throws IOException {
if (args.length == 0) {
System.err.printf("Usage: %s <file> [...]%n", SSTableMetadataJson.class.getSimpleName());
System.exit(1);
}
List<SSTableMetadata> objects = new ArrayList<>();
for (String fname : args) {
if (new File(fname).exists()) {
objects.add(SSTableMetadata.fromFile(fname));
}
else {
out("No such file: %s", fname);
}
}
out(mapper.writeValueAsString(objects));
}
private static void out(String format, String... args) {
System.out.printf(format + "%n", (Object[]) args);
}
}
| true |
ef0f5eb3647fb28dfb1973f4c3b3a0f5eaeff125 | Java | Partner-CN/demo4logback | /src/main/java/cn/partner/joe/demo/logback/HelloWorld.java | UTF-8 | 494 | 2.28125 | 2 | [] | no_license | package cn.partner.joe.demo.logback;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class HelloWorld {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
for (;;) {
log.info("why are you so busy ?aaasdfas");
try {
//TODO You Can Write Some Code Here aaabcsdf
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
| true |
a87a74877982e3d175a9201f18790da2e21fd164 | Java | marianblaj/angular | /fullstack-curs13-course-app/course-api-client/src/test/java/ro/fasttrackit/curs13/course/client/CourseApiClientIT.java | UTF-8 | 433 | 2 | 2 | [] | no_license | package ro.fasttrackit.curs13.course.client;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class CourseApiClientIT {
private CourseApiClient client;
@BeforeEach
void setup() {
this.client = new CourseApiClient("http://localhost:8001");
}
@Test
void addStudentToCourse() {
System.out.println(client.addStudentToCourse("60be720dbc270d075d89a7e3", 1));
}
}
| true |
19cfa33280bfe5c9fa29b4436dce3d66b32c5cda | Java | TeemoJUN/Rebuild-Java | /offer/Solution.java | WINDOWS-1252 | 636 | 3.078125 | 3 | [] | no_license | package test;
import java.util.Arrays;
//ȫ
public class Solution {
static int k=0;
public static void fullSort(int[] array,int lo,int hi){
if(lo==hi){
System.out.println(Arrays.toString(array));
k++;
}
else{
for(int i=lo;i<=hi;i++){
swap(array,i,lo);
fullSort(array,lo+1,hi);
swap(array,i,lo);
}
}
}
public static void swap(int[] array,int i,int j){
int temp=array[i];
array[i]=array[j];
array[j]=temp;
}
public static void main(String[] args){
int[] array={1,2,3};
fullSort(array,0,2);
System.out.println(k);
}
}
| true |
3d61e7b46633f93b15339b500ca3c6e06c1c486a | Java | zurl/OJ | /src/leetcode/p405.java | UTF-8 | 697 | 3.28125 | 3 | [] | no_license | package leetcode;
public class p405 {
public String toHex(int num) {
if( num == 0) return "0";
StringBuilder sb = new StringBuilder();
long val = num;
if( val < 0 ) val = Integer.MAX_VALUE + val + 0x80000001L;
while(val > 0){
if( val % 16 >= 10){
sb.append( (char)(val % 16 - 10 + 'a'));
}
else{
sb.append( (char)(val % 16 + '0'));
}
val /= 16;
}
return sb.reverse().toString();
}
public static void main(String[] args) {
p405 a = new p405();
System.out.println(a.toHex(-123) + "," + Integer.toString(-1, 16));
}
}
| true |
867f06a8aea83f2a630a695bc6d97784fd3c3adf | Java | Shikharini-Basu/BoardProject2020 | /polyProg.java | UTF-8 | 616 | 3 | 3 | [] | no_license | public class polyProg
{ int i,j;
void polygon(int n, char ch)
{ for(int i=1;i<=n;i++)
{ for(int j=1;j<=n;j++)
{ System.out.print(ch+" ");
}
System.out.println();
}
}
void polygon(int x, int y)
{ for(int i=1;i<=x;i++)
{ for(int j=1;j<=y;j++)
{ System.out.print('@'+" ");
}
System.out.println();
}
}
void polygon()
{ for(int i=1;i<=3;i++)
{ for(int j=1;j<=i;j++)
{ System.out.print('*'+" ");
}
System.out.println();
}
}
} | true |
3e73993d8f38406d0c7bf186c6c55c076a913017 | Java | fengzihub/Financial | /core/src/main/java/cn/fengzihub/p2p/base/mapper/LogininfoMapper.java | UTF-8 | 655 | 2.015625 | 2 | [] | no_license | package cn.fengzihub.p2p.base.mapper;
import cn.fengzihub.p2p.base.domain.Logininfo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface LogininfoMapper {
//登录用户只需要添加方法,删除...等等都不需要
int insert(Logininfo record);
int selectCountByUsername(String username);
Logininfo login(@Param("username") String username, @Param("password") String password, @Param("userType") int userType);
int queryCountByUserType(int usertypeManager);
List<Map<String,Object>> autocomplate(@Param("keyword") String keyword, @Param("usertype") int usertype);
} | true |
a5c935b3f72992ce6d63fd9c8516cfb939f5d770 | Java | GDBMedia/testApiAndroid | /app/src/main/java/com/example/guest/apitest/Church.java | UTF-8 | 536 | 2.6875 | 3 | [] | no_license | package com.example.guest.apitest;
/**
* Created by Guest on 6/29/16.
*/
public class Church {
private String mName;
private double mRating;
private String mVicinity;
public Church(String name, double rating, String vicinity){
this.mName = name;
this.mRating = rating;
this.mVicinity = vicinity;
}
public String getName() {
return mName;
}
public double getRating() {
return mRating;
}
public String getVicinity() {
return mVicinity;
}
}
| true |
fca529036e02ce3a614eee309cbdc0541f5dfa81 | Java | tasiomendez/middleware-akka | /src/main/java/it/polimi/middleware/akka/messages/storage/GetPartitionBackupResponseMessage.java | UTF-8 | 468 | 2 | 2 | [] | no_license | package it.polimi.middleware.akka.messages.storage;
import java.io.Serializable;
import java.util.Map;
public class GetPartitionBackupResponseMessage implements Serializable {
private static final long serialVersionUID = 1L;
private final Map<String, String> backup;
public GetPartitionBackupResponseMessage(Map<String, String> backup) {
this.backup = backup;
}
public Map<String, String> getBackup() {
return backup;
}
}
| true |
966c66e73d05f4588c5d0fc4acb4a37a374e033f | Java | encinas008/pokar-game | /src/com/company/ColorScale.java | UTF-8 | 842 | 3.296875 | 3 | [] | no_license | package com.company;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class ColorScale implements CheckDeckOfCard {
private static final int DIFFERENCE_OF_ONE = 1;
private static final int INDEX_FIRST_ELEMENT = 0;
@Override
public List<Card> execute(List<Card> cards) {
cards.sort(Comparator.naturalOrder());
Card card = cards.get(INDEX_FIRST_ELEMENT);
for (int index = 1; index < cards.size(); index++) {
Card currentCard = cards.get(index);
int difference = currentCard.getValue() - card.getValue();
if (difference != DIFFERENCE_OF_ONE || card.getSymbol() != currentCard.getSymbol()) {
return new ArrayList<>();
}
card = cards.get(index);
}
return cards;
}
}
| true |
233aeaf55ad0b0446cd48d3815ef967391d9767e | Java | sachinprajapati8604/DSA-Newton-School- | /Max_subArray_Kadane.java | UTF-8 | 1,332 | 3.609375 | 4 | [] | no_license | package com.company;
import java.util.Scanner;
public class Max_subArray_Kadane {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
System.out.println("Sum of sub array using Kadane Algorithm : " + Kadane_subarray(arr, n));
System.out.println("Sum of subarray using Dynamic Programming : " + byDynamic(arr, n));
}
private static int Kadane_subarray(int a[], int n) {
// time complexity is O(n)
int max_so_far = a[0];
int max_ending_here = 0;
for (int i = 0; i < n; i++) {
max_ending_here = max_ending_here + a[i];
if (max_ending_here < 0) {
max_ending_here = 0;
} else if (max_so_far < max_ending_here) {
max_so_far = max_ending_here;
}
}
return max_so_far;
}
public static int byDynamic(int arr[], int n) {
int max_so_far = arr[0];
int current_max = arr[0];
for (int i = 1; i < n; i++) {
current_max = Math.max(arr[i], arr[i] + current_max);
max_so_far = Math.max(max_so_far, current_max);
}
return max_so_far;
}
}
| true |
46645f3d6fef4ae21f8d1dac3fc302942be434e0 | Java | AayeshaFirdoz/Cisco_Training | /Demo1/src/test/java/test/NewTest.java | UTF-8 | 461 | 2.015625 | 2 | [] | no_license | package test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class NewTest {
WebDriver driver;
String url ="https://www.google.com/";
@Test
public void f() {
System.setProperty("webdriver.chrome.driver","C:\\Users\\aayeshafirdoz.f\\Downloads\\chromedriver_win32\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get(url);
driver.close();
}
}
| true |
a71fd1b6d9725c838e60937dbaeae687add2dfa1 | Java | rockie1004/SpringHotels | /src/main/java/dmacc/beans/Hotel.java | UTF-8 | 1,338 | 2.671875 | 3 | [] | no_license | package dmacc.beans;
import javax.persistence.Id;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import org.springframework.beans.factory.annotation.Autowired;
@Entity
public class Hotel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private String amenity;
@Autowired
private Address address;
public Hotel() {
super();
}
public Hotel(String name) {
super();
this.name = name;
}
public Hotel(String name, String amenity) {
super();
this.name = name;
this.amenity = amenity;
}
public Hotel(long id, String name, String amenity) {
super();
this.id = id;
this.name = name;
this.amenity = amenity;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return amenity;
}
public void setPhone(String amenity) {
this.amenity = amenity;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Hotel [id=" + id + ", name=" + name + ", amenity=" + amenity + ", address=" + address + "]";
}
}
| true |
2c787586bb68a28de12b69a80af1ecca9329365a | Java | u-kou/GAO | /FR/src/ndn/message/Interest.java | UTF-8 | 318 | 2.09375 | 2 | [] | no_license | package ndn.message;
/**
* NDN における Interest メッセージ
* @author taku
*
*/
public class Interest extends NDNMessage {
public Interest(String name) {
super(name, MessageType.INTEREST);
}
public Interest(String name, boolean cacheFlag) {
super(name, MessageType.INTEREST, cacheFlag);
}
}
| true |
46af0380949187db6ef6b2adaa7e3f78182c3905 | Java | jeffersonar/mobilidade | /src/main/java/br/com/dimed/mobilidade/repository/TaxiRepository.java | UTF-8 | 428 | 1.8125 | 2 | [] | no_license | package br.com.dimed.mobilidade.repository;
import java.math.BigInteger;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import br.com.dimed.mobilidade.entity.OnibusEntity;
import br.com.dimed.mobilidade.entity.TaxiEntity;
public interface TaxiRepository extends JpaRepository<TaxiEntity,BigInteger>{
public List<TaxiEntity> findByNomePontoContaining(String nome);
}
| true |
eae5bd0e8a13fb3ec4861928d2e336bb21b8b027 | Java | vZome/vzome | /core/src/main/java/com/vzome/core/math/symmetry/Symmetry.java | UTF-8 | 2,374 | 2.21875 | 2 | [
"Apache-2.0"
] | permissive |
package com.vzome.core.math.symmetry;
import java.util.Collection;
import com.vzome.core.algebra.AlgebraicField;
import com.vzome.core.algebra.AlgebraicMatrix;
import com.vzome.core.algebra.AlgebraicVector;
import com.vzome.core.math.RealVector;
/**
* @author Scott Vorthmann
*
*/
public interface Symmetry extends Embedding
{
int PLUS = 0 /*Axis.PLUS*/, MINUS = 1 /*Axis.MINUS*/; // Dumb workaround for the JSweet compiler glitch.
// JSweet fails under GitHub Actions (but not locally, using the exact same Eclipse Temurin OpenJDK 8!)
int NO_ROTATION = -1;
String TETRAHEDRAL = "tetrahedral", PYRITOHEDRAL = "pyritohedral";
int getChiralOrder();
String getName();
Axis getAxis( AlgebraicVector vector );
Axis getAxis( AlgebraicVector vector, OrbitSet orbits );
Axis getAxis( RealVector vector, Collection<Direction> filter );
int getMapping( int from, int to );
Permutation getPermutation( int i );
AlgebraicMatrix getMatrix( int i );
int inverse(int orientation);
String[] getDirectionNames();
Direction getDirection( String name );
AlgebraicField getField();
OrbitSet getOrbitSet();
/**
* Generate a subgroup, by taking the closure of some collection of Permutations
* @param perms an array of Permutations indices
* @return an array of Permutations indices
*/
int[] closure( int[] perms );
int[] subgroup( String name );
Direction createNewZoneOrbit( String name, int prototype, int rotatedPrototype, AlgebraicVector vector );
public abstract int[] getIncidentOrientations( int orientation );
public abstract Direction getSpecialOrbit( SpecialOrbit which );
Axis getPreferredAxis();
/**
* Get the transformation matrix that maps zone 7 to zone -7 (for example).
* If null, the matrix is implicitly a central inversion, negating vectors.
* @return {@link AlgebraicMatrix}
*/
public abstract AlgebraicMatrix getPrincipalReflection();
public AlgebraicVector[] getOrbitTriangle();
/**
* Compute the orbit triangle dots for all existing orbits,
* and leave behind an OrbitDotLocator for new ones.
* The result is just a VEF string, for debugging.
* @return
*/
public String computeOrbitDots();
public boolean reverseOrbitTriangle();
Iterable<Direction> getDirections();
}
| true |
eb62368d4911bc36da7973f026166261423c8ccc | Java | flame-stream/FlameStream | /examples/src/main/java/com/spbsu/flamestream/example/bl/index/ops/WikipediaPageToWordPositions.java | UTF-8 | 2,660 | 2.28125 | 2 | [
"Apache-2.0"
] | permissive | package com.spbsu.flamestream.example.bl.index.ops;
import com.expleague.commons.text.lexical.StemsTokenizer;
import com.expleague.commons.text.lexical.Tokenizer;
import com.expleague.commons.text.stem.Stemmer;
import com.spbsu.flamestream.core.graph.SerializableFunction;
import com.spbsu.flamestream.example.bl.index.model.WikipediaPage;
import com.spbsu.flamestream.example.bl.index.model.WordPagePositions;
import com.spbsu.flamestream.example.bl.index.utils.IndexItemInLong;
import com.spbsu.flamestream.runtime.utils.tracing.Tracing;
import gnu.trove.list.TLongList;
import gnu.trove.list.array.TLongArrayList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
/**
* User: Artem
* Date: 10.07.2017
*/
public class WikipediaPageToWordPositions implements SerializableFunction<WikipediaPage, Stream<WordPagePositions>> {
//private transient final Tracing.Tracer inputTracer;
//private transient final Tracing.Tracer outputTracer;
public WikipediaPageToWordPositions() {
//inputTracer = Tracing.TRACING.forEvent("flatmap-receive", 1000, 1);
//outputTracer = Tracing.TRACING.forEvent("flatmap-send");
}
public WikipediaPageToWordPositions(Tracing.Tracer inputTracer, Tracing.Tracer outputTracer) {
//this.inputTracer = inputTracer;
//this.outputTracer = outputTracer;
}
@Override
public Stream<WordPagePositions> apply(WikipediaPage wikipediaPage) {
//inputTracer.log(wikipediaPage.id());
//noinspection deprecation
final Tokenizer tokenizer = new StemsTokenizer(Stemmer.getInstance(), wikipediaPage.text());
final Map<String, TLongList> wordPositions = new HashMap<>();
int position = 0;
while (tokenizer.hasNext()) {
final String word = tokenizer.next().toString().toLowerCase();
final long pagePosition = IndexItemInLong.createPagePosition(
wikipediaPage.id(),
position,
wikipediaPage.version()
);
if (!wordPositions.containsKey(word)) {
final TLongList positions = new TLongArrayList();
positions.add(pagePosition);
wordPositions.put(word, positions);
} else {
wordPositions.get(word).add(pagePosition);
}
position++;
}
final List<WordPagePositions> wordPagePositions = new ArrayList<>();
wordPositions.forEach((word, list) -> wordPagePositions.add(new WordPagePositions(word, list.toArray())));
return wordPagePositions.stream()
.peek(positions -> {
//outputTracer.log(WordIndexAdd.hash(positions.word(), wikipediaPage.id()));
});
}
}
| true |
62a921fe6669cc0733afb9b763afb849f8d2fd06 | Java | arnorymir/FreeFlow | /app/src/main/java/com/example/flowflow/freeflow/Dot.java | UTF-8 | 509 | 2.890625 | 3 | [] | no_license | package com.example.flowflow.freeflow;
/**
* Created by bjornorri on 13/09/14.
*/
public class Dot {
private Coordinate mCell;
private int mColorID;
public Dot(Coordinate cell, int colorID) {
mCell = cell;
mColorID = colorID;
}
public Dot(int x, int y, int colorID) {
mCell = new Coordinate(x, y);
mColorID = colorID;
}
public Coordinate getCell() {
return mCell;
}
public int getColorID() {
return mColorID;
}
}
| true |
6b9c04e1dbb745ca56be6406ac24298b657aa6de | Java | chandratan03/Design-Pattern-Learning | /Observer/src/subjects/WeatherData.java | UTF-8 | 1,323 | 3.140625 | 3 | [] | no_license | package subjects;
import java.util.ArrayList;
import observers.Observer;
public class WeatherData implements Subject{
private ArrayList<Observer> observers = new ArrayList<Observer>();
private Float temperature, humidity, pressure;
@Override
public void registerObserver(Observer observer) {
observers.add(observer);
}
@Override
public void notifyObservers() {
for(int i=0; i<observers.size(); i++) {
observers.get(i).update(temperature, humidity, pressure);
}
}
@Override
public void removeObserver(Observer observer) {
Integer index = observers.indexOf(observer);
if(index >=0)
observers.remove(index);
}
public void setMeasurements(Float temperature, Float humidity, Float pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
notifyObservers(); // notify all
}
public Float getTemperature() {
return temperature;
}
public void setTemperature(Float temperature) {
this.temperature = temperature;
notifyObservers();
}
public Float getHumidity() {
return humidity;
}
public void setHumidity(Float humidity) {
this.humidity = humidity;
notifyObservers();
}
public Float getPressure() {
return pressure;
}
public void setPressure(Float pressure) {
this.pressure = pressure;
notifyObservers();
}
}
| true |
ecc3862e7fcc5c2ed009dfde8c967715610094d3 | Java | tyyx1228/study_all | /bd_hadoop/study-mr/src/main/java/com/ty/study/wordcount/WordCount.java | UTF-8 | 3,328 | 2.4375 | 2 | [] | no_license | package com.ty.study.wordcount;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.lib.CombineTextInputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class WordCount {
static class WordcountMapper extends Mapper<LongWritable, Text, Text, LongWritable>{
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
String[] words = line.split(" ");
for(String w:words){
context.write(new Text(w),new LongWritable(1));
}
}
@Override
protected void cleanup(Context context) throws IOException, InterruptedException {
// TODO Auto-generated method stub
System.out.println("haha");
}
}
static class WordcountReducer extends Reducer<Text, LongWritable, Text, LongWritable>{
@Override
protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
long count =0;
for(LongWritable v:values){
count += v.get();
}
context.write(key, new LongWritable(count));
}
}
static class WordcountCombiner extends Reducer<Text, LongWritable, Text, LongWritable>{
@Override
protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
long count =0;
for(LongWritable v:values){
count += v.get();
}
context.write(key, new LongWritable(count));
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
// conf.set("hadoop.tmp.dir", "d:/hadooptmp/");
// conf.set("mapred.map.output.compress.codec","true");
// conf.set("mapred.map.output.compress.codec", "org.apache.hadoop.io.compress.GzipCodec");
// conf.set("mapreduce.output.fileoutputformat.compress", "true");
// conf.set("mapreduce.output.fileoutputformat.compress.codec", "org.apache.hadoop.io.compress.GzipCodec");
Job job = Job.getInstance(conf);
job.setJarByClass(WordCount.class);
job.setMapperClass(WordcountMapper.class);
job.setReducerClass(WordcountReducer.class);
//job.setCombinerClass(WordcountCombiner.class);
//job.setUser("hadoop");
// job.setInputFormatClass(CombineTextInputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);
job.setNumReduceTasks(0);
// job.setOutputFormatClass(SequenceFileOutputFormat.class);
// FileInputFormat.setInputPaths(job, new Path(args[0]));
// FileOutputFormat.setOutputPath(job, new Path(args[1]));
// FileInputFormat.setInputPaths(job, new Path("F:/bigdata-material-data/2013072404-http-combinedBy-1373892200521-log-1"));
FileInputFormat.setInputPaths(job, new Path("x:/wordcount/srcdata"));
FileOutputFormat.setOutputPath(job, new Path("x:/wordcount/test"+new Random().nextInt(100)));
job.waitForCompletion(true);
}
}
| true |
6addd61741c037d012f59e88a23b428380b2f100 | Java | fishr/lightdj | /SoundExpressor/src/Signals/FFTEngine.java | UTF-8 | 4,362 | 3.625 | 4 | [] | no_license | package Signals;
/**
* Represents a faster Fast Fourier Transform (FFT) engine. Specific to a given FFT size.
* The size must range from 2 to 2^31, and be a power of 2.
*
* Trades away memory and pre-computation time, in favor of fast FFT computation time.
*
* Upon being initialized, the FFT does a bunch of pre-computations to prepare itself.
* This allows each FFT call to be run faster and more efficiently.
*
* @author Steve Levine
*
*/
public class FFTEngine {
// Some useful fields for this sized FFT
private int N; // The size of the FFT, i.e., 1024
private int v; // log2(N)
private double fs; // The sample rate
private int[] bitReversedIndices; // Map regular index to bit-reversed index
private double[][] WnPowers; // Wn = exp(-j*2 PI / N), to several powers
private int[][][] butterflyMappings; // Each of the v entries contains N/2 entries which are triples (p, q, k), such that the
// butterfly computation is executed on values with indices p and q,
// and the complex scale WnPowers[k] is used.
public FFTEngine(int fft_size, double fs) {
N = fft_size;
v = (int) Math.round(Math.log(N)/Math.log(2));
this.fs = fs;
// Precompute lots of stuff, so we can fly on each FFT
prepareEngine();
}
// Prepare the engine, by performing useful precomputations to save time.
// This doesn't need to be fast, since it is only run once at the beginning.
private void prepareEngine() {
// Set up the bit-reversed indices
bitReversedIndices = new int[N];
for(int i = 0; i < N; i++) {
int bitReverse = 0;
for(int j = 0; j < v; j++) {
bitReverse |= ( (i >> (v - j - 1)) & 0x01 ) << j;
}
bitReversedIndices[i] = bitReverse;
}
// Pre-compute Wn raised to the relevant powers
WnPowers = new double[N/2][2];
for(int k = 0; k < N/2; k++) {
double theta = - 2*Math.PI / N * k;
WnPowers[k][0] = Math.cos(theta);
WnPowers[k][1] = Math.sin(theta);
}
// Precompute the ordering and Wn usage for each butterfly computation to be performed,
// for each v levels of the FFT.
butterflyMappings = new int[v][N/2][3];
// Iterate over each of the v levels of FFT butterfly computations
for(int L = 1; L <= v; L++) {
int pairIndex = 0;
int WnIndex = 0;
int B = (1 << L); // The "block size" associated with this FFT level
int i = 0;
while(i < N) {
for(int j = 0; j < B/2; j++) {
butterflyMappings[L - 1][pairIndex][0] = i + j;
butterflyMappings[L - 1][pairIndex][1] = i + j + B/2;
butterflyMappings[L - 1][pairIndex][2] = WnIndex;
WnIndex = (WnIndex + (1 << (v - L))) % (N/2);
pairIndex++;
}
i += B;
}
}
// All done!
}
// Compute the FFT! This algorithm is optimized to use butterfly computations.
// Additionally, the main calculation consists solely of additions, multiplications,
// and array reads/writes. Computes in place. No Java class instantiations, memory allocations,
// function calls, etc. - this is to keep things as fast as possible.
//
public FFT computeFFT(double[] x) {
// Basic error checking
if (x.length != N) {
throw new RuntimeException("Error: Invalid length signal for the given sized FFT!");
}
// Start the list of complex registers
// Initialize with bit-reversed order input
double[][] X = new double[N][2];
for(int i = 0; i < N; i++) {
X[i][0] = x[bitReversedIndices[i]];
X[i][1] = 0;
}
// Start the v levels of FFT butterfly computations!
for(int m = 0; m < v; m++) {
// Execute the butterfly computations, using the pre-computed ordering
for(int butterflyIndex = 0; butterflyIndex < N / 2; butterflyIndex++) {
// Retrieve the two indices
int p = butterflyMappings[m][butterflyIndex][0];
int q = butterflyMappings[m][butterflyIndex][1];
int WnIndex = butterflyMappings[m][butterflyIndex][2];
double deltaR = WnPowers[WnIndex][0] * X[q][0] - WnPowers[WnIndex][1] * X[q][1];
double deltaI = WnPowers[WnIndex][0] * X[q][1] + WnPowers[WnIndex][1] * X[q][0];
X[q][0] = X[p][0] - deltaR;
X[q][1] = X[p][1] - deltaI;
X[p][0] = X[p][0] + deltaR;
X[p][1] = X[p][1] + deltaI;
}
}
// Done! Return a wrapper class holding the computed values with the sample rate.
return new FFT(X, fs);
}
}
| true |
27c601e32fc5abc0ee7bee07564f926a69242454 | Java | jimenabpose/TPE-POD | /src/main/java/ar/edu/itba/pod/signal/source/PredefinedSource.java | UTF-8 | 717 | 2.953125 | 3 | [] | no_license | package ar.edu.itba.pod.signal.source;
import java.util.List;
import ar.edu.itba.pod.api.Signal;
/**
* Source file that has a predefined number of signals.
* After all the signals are exhausted, the source will reset and
* start with the first one
*/
public class PredefinedSource implements Source {
public final List<Signal> signals;
public int index = 0;
public PredefinedSource(List<Signal> signals) {
super();
if (signals == null || signals.size() == 0) {
throw new IllegalArgumentException("List of signals must not be null or empty");
}
this.signals = signals;
}
@Override
public Signal next() {
index = (index == signals.size()) ? 0 : index+1;
return signals.get(index);
}
}
| true |
888500729a989aceb7ed1e855ff8fc3d8b1994ac | Java | wzhonggo/LiferayDemo | /Oauth2-portlet/docroot/WEB-INF/service/com/labimo/portlet/tincan/model/Oauth2TokenClp.java | UTF-8 | 11,713 | 1.75 | 2 | [] | no_license | /**
* Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.labimo.portlet.tincan.model;
import com.labimo.portlet.tincan.service.ClpSerializer;
import com.labimo.portlet.tincan.service.Oauth2TokenLocalServiceUtil;
import com.liferay.portal.kernel.bean.AutoEscapeBeanHandler;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.ProxyUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.model.BaseModel;
import com.liferay.portal.model.impl.BaseModelImpl;
import com.liferay.portal.util.PortalUtil;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* @author wzgong
*/
public class Oauth2TokenClp extends BaseModelImpl<Oauth2Token>
implements Oauth2Token {
public Oauth2TokenClp() {
}
@Override
public Class<?> getModelClass() {
return Oauth2Token.class;
}
@Override
public String getModelClassName() {
return Oauth2Token.class.getName();
}
@Override
public long getPrimaryKey() {
return _id;
}
@Override
public void setPrimaryKey(long primaryKey) {
setId(primaryKey);
}
@Override
public Serializable getPrimaryKeyObj() {
return _id;
}
@Override
public void setPrimaryKeyObj(Serializable primaryKeyObj) {
setPrimaryKey(((Long)primaryKeyObj).longValue());
}
@Override
public Map<String, Object> getModelAttributes() {
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("id", getId());
attributes.put("code", getCode());
attributes.put("token", getToken());
attributes.put("refreshToken", getRefreshToken());
attributes.put("clientId", getClientId());
attributes.put("expiredIn", getExpiredIn());
attributes.put("liferayUserId", getLiferayUserId());
return attributes;
}
@Override
public void setModelAttributes(Map<String, Object> attributes) {
Long id = (Long)attributes.get("id");
if (id != null) {
setId(id);
}
String code = (String)attributes.get("code");
if (code != null) {
setCode(code);
}
String token = (String)attributes.get("token");
if (token != null) {
setToken(token);
}
String refreshToken = (String)attributes.get("refreshToken");
if (refreshToken != null) {
setRefreshToken(refreshToken);
}
Long clientId = (Long)attributes.get("clientId");
if (clientId != null) {
setClientId(clientId);
}
Long expiredIn = (Long)attributes.get("expiredIn");
if (expiredIn != null) {
setExpiredIn(expiredIn);
}
Long liferayUserId = (Long)attributes.get("liferayUserId");
if (liferayUserId != null) {
setLiferayUserId(liferayUserId);
}
}
@Override
public long getId() {
return _id;
}
@Override
public void setId(long id) {
_id = id;
if (_oauth2TokenRemoteModel != null) {
try {
Class<?> clazz = _oauth2TokenRemoteModel.getClass();
Method method = clazz.getMethod("setId", long.class);
method.invoke(_oauth2TokenRemoteModel, id);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public String getCode() {
return _code;
}
@Override
public void setCode(String code) {
_code = code;
if (_oauth2TokenRemoteModel != null) {
try {
Class<?> clazz = _oauth2TokenRemoteModel.getClass();
Method method = clazz.getMethod("setCode", String.class);
method.invoke(_oauth2TokenRemoteModel, code);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public String getToken() {
return _token;
}
@Override
public void setToken(String token) {
_token = token;
if (_oauth2TokenRemoteModel != null) {
try {
Class<?> clazz = _oauth2TokenRemoteModel.getClass();
Method method = clazz.getMethod("setToken", String.class);
method.invoke(_oauth2TokenRemoteModel, token);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public String getRefreshToken() {
return _refreshToken;
}
@Override
public void setRefreshToken(String refreshToken) {
_refreshToken = refreshToken;
if (_oauth2TokenRemoteModel != null) {
try {
Class<?> clazz = _oauth2TokenRemoteModel.getClass();
Method method = clazz.getMethod("setRefreshToken", String.class);
method.invoke(_oauth2TokenRemoteModel, refreshToken);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public long getClientId() {
return _clientId;
}
@Override
public void setClientId(long clientId) {
_clientId = clientId;
if (_oauth2TokenRemoteModel != null) {
try {
Class<?> clazz = _oauth2TokenRemoteModel.getClass();
Method method = clazz.getMethod("setClientId", long.class);
method.invoke(_oauth2TokenRemoteModel, clientId);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public long getExpiredIn() {
return _expiredIn;
}
@Override
public void setExpiredIn(long expiredIn) {
_expiredIn = expiredIn;
if (_oauth2TokenRemoteModel != null) {
try {
Class<?> clazz = _oauth2TokenRemoteModel.getClass();
Method method = clazz.getMethod("setExpiredIn", long.class);
method.invoke(_oauth2TokenRemoteModel, expiredIn);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public long getLiferayUserId() {
return _liferayUserId;
}
@Override
public void setLiferayUserId(long liferayUserId) {
_liferayUserId = liferayUserId;
if (_oauth2TokenRemoteModel != null) {
try {
Class<?> clazz = _oauth2TokenRemoteModel.getClass();
Method method = clazz.getMethod("setLiferayUserId", long.class);
method.invoke(_oauth2TokenRemoteModel, liferayUserId);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public String getLiferayUserUuid() throws SystemException {
return PortalUtil.getUserValue(getLiferayUserId(), "uuid",
_liferayUserUuid);
}
@Override
public void setLiferayUserUuid(String liferayUserUuid) {
_liferayUserUuid = liferayUserUuid;
}
public BaseModel<?> getOauth2TokenRemoteModel() {
return _oauth2TokenRemoteModel;
}
public void setOauth2TokenRemoteModel(BaseModel<?> oauth2TokenRemoteModel) {
_oauth2TokenRemoteModel = oauth2TokenRemoteModel;
}
public Object invokeOnRemoteModel(String methodName,
Class<?>[] parameterTypes, Object[] parameterValues)
throws Exception {
Object[] remoteParameterValues = new Object[parameterValues.length];
for (int i = 0; i < parameterValues.length; i++) {
if (parameterValues[i] != null) {
remoteParameterValues[i] = ClpSerializer.translateInput(parameterValues[i]);
}
}
Class<?> remoteModelClass = _oauth2TokenRemoteModel.getClass();
ClassLoader remoteModelClassLoader = remoteModelClass.getClassLoader();
Class<?>[] remoteParameterTypes = new Class[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
if (parameterTypes[i].isPrimitive()) {
remoteParameterTypes[i] = parameterTypes[i];
}
else {
String parameterTypeName = parameterTypes[i].getName();
remoteParameterTypes[i] = remoteModelClassLoader.loadClass(parameterTypeName);
}
}
Method method = remoteModelClass.getMethod(methodName,
remoteParameterTypes);
Object returnValue = method.invoke(_oauth2TokenRemoteModel,
remoteParameterValues);
if (returnValue != null) {
returnValue = ClpSerializer.translateOutput(returnValue);
}
return returnValue;
}
@Override
public void persist() throws SystemException {
if (this.isNew()) {
Oauth2TokenLocalServiceUtil.addOauth2Token(this);
}
else {
Oauth2TokenLocalServiceUtil.updateOauth2Token(this);
}
}
@Override
public Oauth2Token toEscapedModel() {
return (Oauth2Token)ProxyUtil.newProxyInstance(Oauth2Token.class.getClassLoader(),
new Class[] { Oauth2Token.class }, new AutoEscapeBeanHandler(this));
}
@Override
public Object clone() {
Oauth2TokenClp clone = new Oauth2TokenClp();
clone.setId(getId());
clone.setCode(getCode());
clone.setToken(getToken());
clone.setRefreshToken(getRefreshToken());
clone.setClientId(getClientId());
clone.setExpiredIn(getExpiredIn());
clone.setLiferayUserId(getLiferayUserId());
return clone;
}
@Override
public int compareTo(Oauth2Token oauth2Token) {
long primaryKey = oauth2Token.getPrimaryKey();
if (getPrimaryKey() < primaryKey) {
return -1;
}
else if (getPrimaryKey() > primaryKey) {
return 1;
}
else {
return 0;
}
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Oauth2TokenClp)) {
return false;
}
Oauth2TokenClp oauth2Token = (Oauth2TokenClp)obj;
long primaryKey = oauth2Token.getPrimaryKey();
if (getPrimaryKey() == primaryKey) {
return true;
}
else {
return false;
}
}
@Override
public int hashCode() {
return (int)getPrimaryKey();
}
@Override
public String toString() {
StringBundler sb = new StringBundler(15);
sb.append("{id=");
sb.append(getId());
sb.append(", code=");
sb.append(getCode());
sb.append(", token=");
sb.append(getToken());
sb.append(", refreshToken=");
sb.append(getRefreshToken());
sb.append(", clientId=");
sb.append(getClientId());
sb.append(", expiredIn=");
sb.append(getExpiredIn());
sb.append(", liferayUserId=");
sb.append(getLiferayUserId());
sb.append("}");
return sb.toString();
}
@Override
public String toXmlString() {
StringBundler sb = new StringBundler(25);
sb.append("<model><model-name>");
sb.append("com.labimo.portlet.tincan.model.Oauth2Token");
sb.append("</model-name>");
sb.append(
"<column><column-name>id</column-name><column-value><![CDATA[");
sb.append(getId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>code</column-name><column-value><![CDATA[");
sb.append(getCode());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>token</column-name><column-value><![CDATA[");
sb.append(getToken());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>refreshToken</column-name><column-value><![CDATA[");
sb.append(getRefreshToken());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>clientId</column-name><column-value><![CDATA[");
sb.append(getClientId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>expiredIn</column-name><column-value><![CDATA[");
sb.append(getExpiredIn());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>liferayUserId</column-name><column-value><![CDATA[");
sb.append(getLiferayUserId());
sb.append("]]></column-value></column>");
sb.append("</model>");
return sb.toString();
}
private long _id;
private String _code;
private String _token;
private String _refreshToken;
private long _clientId;
private long _expiredIn;
private long _liferayUserId;
private String _liferayUserUuid;
private BaseModel<?> _oauth2TokenRemoteModel;
} | true |
0be643231c843e512b2aaa53cef3550362356d19 | Java | ndilworth/SuperClickStar | /SuperClickStar/src/com/ndilworth/superclickstar/Star.java | UTF-8 | 1,798 | 2.625 | 3 | [] | no_license | package com.ndilworth.superclickstar;
import java.util.Random;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
public class Star {
public float mX;
public float mY;
private int mSpeedX;
private int mSpeedY;
private int mType;
private int mClicks;
private Bitmap mBitmap;
public Star(Resources res, int x, int y, int type) {
Random rand = new Random();
mType = type;
switch (type) {
case 3:
mBitmap = BitmapFactory.decodeResource(res, R.drawable.mediumredstar);
break;
case 2:
mBitmap = BitmapFactory.decodeResource(res, R.drawable.mediumyellowstar);
break;
case 1:
mBitmap = BitmapFactory.decodeResource(res, R.drawable.mediumbluestar);
break;
default:
mBitmap = BitmapFactory.decodeResource(res, R.drawable.mediumbluestar);
break;
}
mX = x - mBitmap.getWidth() / 2;
mY = y - mBitmap.getHeight() / 2;
mSpeedX = rand.nextInt(7);
if (mSpeedX == 0)
mSpeedX = 1;
mSpeedY = rand.nextInt(7);
if (mSpeedY == 0)
mSpeedY = 1;
}
public void animate(long elapsedTime) {
mX += mSpeedX * (elapsedTime / 20f);
mY += mSpeedY * (elapsedTime / 20f);
checkBorders();
}
public void doDraw(Canvas canvas) {
canvas.drawBitmap(mBitmap, mX, mY, null);
}
private void checkBorders() {
if (mX <= 0) {
mSpeedX = -mSpeedX;
mX = 0;
} else if (mX + mBitmap.getWidth() >= Panel.mWidth) {
mSpeedX = -mSpeedX;
mX = Panel.mWidth - mBitmap.getWidth();
}
if (mY <= 0) {
mSpeedY = -mSpeedY;
mY = 0;
} else if (mY + mBitmap.getHeight() >= Panel.mHeight) {
mSpeedY = -mSpeedY;
mY = Panel.mHeight - mBitmap.getHeight();
}
}
}
| true |
eeddf759dc37d55658391ddcf27bead31d74d743 | Java | ysyha2/git2.javastudy | /src/quiz/A06_GuessAge.java | UTF-8 | 648 | 3.84375 | 4 | [] | no_license | package quiz;
import java.util.Scanner;
public class A06_GuessAge {
/*
사용자로부터 태어난 해와 올해의 년도를 입력받으면
그 사람의 한국 나이를 계산하여 몇 살인지 알려주는 프로그램을 만들어보세요
*/
public static void main(String[] agrs) {
Scanner sc = new Scanner(System.in);
System.out.print("당신이 태어난 해는 몇 년도입니까? ");
int birth = sc.nextInt();
System.out.print("올해는 몇년도입니까? ");
int now = sc.nextInt();
System.out.printf("당신의 나이는 %d입니다.\n", (now-birth+1));
}
}
| true |
379944ae71fca9ddeb74bb75cad25afbae958de7 | Java | ValeriiaPershakova/SpringbootLearning | /src/main/java/world/model/CountryUpdate.java | UTF-8 | 1,661 | 2.09375 | 2 | [] | no_license | package world.model;
import world.service.Updatable;
import javax.validation.constraints.Positive;
public class CountryUpdate implements Updatable {
private String name;
private Continent continent;
private String region;
@Positive
private Double surfacearea;
private String localname;
private String governmentform;
private Integer capital;
private String code2;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCapital() {
return capital;
}
public void setCapital(Integer capital) {
this.capital = capital;
}
public Continent getContinent() {
return continent;
}
public void setContinent(Continent continent) {
this.continent = continent;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public Double getSurfacearea() {
return surfacearea;
}
public void setSurfacearea(Double surfacearea) {
this.surfacearea = surfacearea;
}
public String getLocalname() {
return localname;
}
public void setLocalname(String localname) {
this.localname = localname;
}
public String getGovernmentform() {
return governmentform;
}
public void setGovernmentform(String governmentform) {
this.governmentform = governmentform;
}
public String getCode2() {
return code2;
}
public void setCode2(String code2) {
this.code2 = code2;
}
}
| true |
8bcb927bb7ecd6eeaa602c4afb83f217a51cafa9 | Java | rduarte25/primeros-pasos-java | /src/Uso_Tallas.java | UTF-8 | 277 | 2.25 | 2 | [] | no_license |
public class Uso_Tallas {
enum Talla {Pequena, Mediana, Grande, Muy_grade};
public static void main(String[] args) {
// TODO Auto-generated method stub
Talla s = Talla.Pequena;
Talla m = Talla.Mediana;
Talla l = Talla.Grande;
Talla xl = Talla.Muy_grade;
}
}
| true |
fc55b295873e9535690bd85be7d8acc0ce78c31e | Java | flywind2/joeis | /src/irvine/oeis/a094/A094002.java | UTF-8 | 348 | 2.5625 | 3 | [] | no_license | package irvine.oeis.a094;
import irvine.oeis.LinearRecurrence;
/**
* A094002 <code>a(n+3) = 3*a(n+2) - 2*a(n+1) + 1</code> with <code>a(0)=1, a(1)=5</code>.
* @author Sean A. Irvine
*/
public class A094002 extends LinearRecurrence {
/** Construct the sequence. */
public A094002() {
super(new long[] {2, -5, 4}, new long[] {1, 5, 14});
}
}
| true |
02cf97ab5062229ab75a9c334e44c59cffe7d5dd | Java | connectwithsagun/eMall | /app/src/main/java/com/savatechnology/emall/Fragments/DarkModeFragment.java | UTF-8 | 4,542 | 2.15625 | 2 | [] | no_license | package com.savatechnology.emall.Fragments;
import android.content.Context;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ToggleButton;
import com.savatechnology.emall.R;
/**
* A simple {@link Fragment} subclass.
* Use the {@link DarkModeFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class DarkModeFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
ToggleButton darkMode;
View view;
private Context mContext;
public DarkModeFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment DarkModeFragment.
*/
// TODO: Rename and change types and number of parameters
public static DarkModeFragment newInstance(String param1, String param2) {
DarkModeFragment fragment = new DarkModeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
// AppCompatDelegate
// .setDefaultNightMode(
// AppCompatDelegate
// .MODE_NIGHT_YES);
View view= inflater.inflate(R.layout.fragment_dark_mode, container, false);
init(view);
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
}
void init(View view) {
darkMode = view.findViewById(R.id.tbDarkMode);
darkMode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AppCompatDelegate
.setDefaultNightMode(
AppCompatDelegate
.MODE_NIGHT_YES);
//
// if (isDarkModeOn) {
//
// // if dark mode is on it
// // will turn it off
// AppCompatDelegate
// .setDefaultNightMode(
// AppCompatDelegate
// .MODE_NIGHT_NO);
// // it will set isDarkModeOn
// // boolean to false
// editor.putBoolean(
// "isDarkModeOn", false);
// editor.apply();
//
// // change text of Button
// btnToggleDark.setText(
// "Enable Dark Mode");
// }
// else {
//
// // if dark mode is off
// // it will turn it on
// AppCompatDelegate
// .setDefaultNightMode(
// AppCompatDelegate
// .MODE_NIGHT_YES);
//
// // it will set isDarkModeOn
// // boolean to true
// editor.putBoolean(
// "isDarkModeOn", true);
// editor.apply();
//
// // change text of Button
// btnToggleDark.setText(
// "Disable Dark Mode");
// }
}
});
}
}
| true |
6f9b1e833cd5576c00833bde1dd64cb605423557 | Java | ebrain-mirambeau/fullStackDevelopment | /FirstDemo/src/inheritanceExercise/MathTeacher.java | UTF-8 | 369 | 3.265625 | 3 | [] | no_license | package inheritanceExercise;
public class MathTeacher extends Person{
protected void teachesMath() {
System.out.println("Math teacher teaches");
}
@Override
protected void walk() {
System.out.println("Math teacher walks");
}
public static void main(String args[]) {
MathTeacher mt = new MathTeacher();
mt.teachesMath();
mt.walk();
}
}
| true |
242d8d647a473f0cc55c405bfb457d48fee09911 | Java | lanhuawei/LHWTest | /app/src/main/java/baifu/www/lhwtest/activity/ReplecePhoneNumber.java | UTF-8 | 12,314 | 2.03125 | 2 | [] | no_license | package baifu.www.lhwtest.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import net.sf.json.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
import java.util.List;
import baifu.www.lhwtest.BaseApplication;
import baifu.www.lhwtest.MyService;
import baifu.www.lhwtest.R;
import baifu.www.lhwtest.internet.ConnServerPost;
import baifu.www.lhwtest.internet.IpAddress;
import baifu.www.lhwtest.utils.ByteUtils;
import baifu.www.lhwtest.utils.CountdownAsyncTask;
import baifu.www.lhwtest.utils.Utility;
import baifu.www.lhwtest.utils.showDialogUtil;
/**
* Created by Ivan on 2017/7/30.
* 绑定新的手机号
*/
public class ReplecePhoneNumber extends BaseActivity implements View.OnClickListener{
private Context context = ReplecePhoneNumber.this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initView();
myHandler();
}
private Bundle bundle;
private ImageView phoneNumberIV, code_etIV;
private EditText phoneNumber;// 输入手机号edittext
private EditText code_et;// 输入验证码edittext
private TextView getCodeKey;//获取验证码
private void initView() {
bundle = getIntent().getExtras();
TextView replace_title = (TextView) findViewById(R.id.replace_title_tv);
replace_title.setText("绑定新手机号");
LinearLayout device_number_ll = (LinearLayout) findViewById(R.id.device_number_ll);
device_number_ll.setVisibility(View.GONE);
Button submit_binding = (Button) findViewById(R.id.submit_binding_btn);
submit_binding.setText("提交信息");
submit_binding.setOnClickListener(this);
phoneNumber = (EditText) findViewById(R.id.phone_number_et);
code_et = (EditText) findViewById(R.id.code_et);
phoneNumberIV = (ImageView) findViewById(R.id.phone_number_iv);//清空手机号
code_etIV = (ImageView) findViewById(R.id.code_iv);//清空验证码
ImageView back_iv = (ImageView) findViewById(R.id.back_iv);
getCodeKey = (TextView) findViewById(R.id.get_codeKey_tv);
phoneNumber.setFilters(new InputFilter[] { new InputFilter.LengthFilter(11) });
code_et.setFilters(new InputFilter[] { new InputFilter.LengthFilter(6) });
code_et.addTextChangedListener(new TextChanged(code_et));//验证码监听事件
phoneNumber.addTextChangedListener(new TextChanged(phoneNumber));
back_iv.setOnClickListener(this);
phoneNumberIV.setOnClickListener(this);
code_etIV.setOnClickListener(this);
getCodeKey.setOnClickListener(this);
}
@Override
protected int getContentViewId() {
return R.layout.activity_replace_phone_number;
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.phone_number_iv://清空电话号
phoneNumber.setText("");
phoneNumberIV.setVisibility(View.GONE);
break;
case R.id.code_iv://清空验证码
code_et.setText("");
code_etIV.setVisibility(View.GONE);
break;
case R.id.back_iv://返回
finish();//关闭
break;
case R.id.submit_binding_btn://提交换帮信息
String phoneNumberString =phoneNumber.getText().toString();
String codeStr = code_et.getText().toString();//获取验证码
if (TextUtils.isEmpty(phoneNumberString)) {//手机号是否为空
showDialogUtil.showDialog("请输入手机号", context);
} else {
if (!phoneNumberString.matches("^1[3|5|7|8|][0-9]{9}$")) {// 电话是否为空
Toast.makeText(context, "手机号格式错误", Toast.LENGTH_SHORT).show();
} else {
if (TextUtils.isEmpty(codeStr)) {//验证码是否为空
showDialogUtil.showDialog("请输入验证码", context);
} else {
showDialogUtil.startProgressDialog("", context);
submitBinding(phoneNumberString,codeStr);
}
}
}
break;
case R.id.get_codeKey_tv:// 获取验证码
String phoneNumberStr = phoneNumber.getText().toString();
if (TextUtils.isEmpty(phoneNumberStr)) {
showDialogUtil.showDialog("请输入手机号", context);
} else {
if (!phoneNumberStr.matches("^1[3|5|7|8|][0-9]{9}$")) {// 电话是否为空
Toast.makeText(context, "手机号格式错误", Toast.LENGTH_SHORT).show();
} else {
showDialogUtil.startProgressDialog("", context);
MessageAuthenticationCode(phoneNumberStr, "wsb_newphone");//新手机验证码wsb_newphone
}
}
break;
default:
break;
}
}
/**
* 提交绑定的信息
* @param phone
* @param captcha
*/
private void submitBinding(String phone, String captcha) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("old_captcha",bundle.getString("ordCode")));//原手机号验证码
if(!TextUtils.isEmpty(bundle.getString("deviceNumber"))){
params.add(new BasicNameValuePair("deviceUnique",bundle.getString("deviceNumber")));//设备号
}else if(!TextUtils.isEmpty(BaseApplication.getInstance().getNoDeviceSN())){
params.add(new BasicNameValuePair("deviceUnique",BaseApplication.getInstance().getNoDeviceSN()));//手机登入 设备号
}
// params.add(new BasicNameValuePair("deviceUnique",bundle.getString("deviceNumber")));//设备号
params.add(new BasicNameValuePair("old_phone",bundle.getString("phoneNumber")));//原手机号
params.add(new BasicNameValuePair("phone",phone));//与更换手机号
params.add(new BasicNameValuePair("captcha",captcha));//新手机号验证码
String sign = ByteUtils.JoiningTogether(params);//拼接
params.add(new BasicNameValuePair("sign", ByteUtils.MD5(ByteUtils.MD5(sign)+BaseApplication.getInstance().getCommand())));
String url = IpAddress.ChangePhone;//提交更换手机号地址
ConnServerPost csp = new ConnServerPost(url, myHandler, "ChangePhone",params);
new Thread(csp).start();
}
/**
* 短信验证码 注册wsb_reg 网页注册wsb_regweb 登录wsb_login
*/
private void MessageAuthenticationCode(String phone, String operation_type) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("phone", phone));//添加手机号
params.add(new BasicNameValuePair("operation_type", operation_type));
String sign = ByteUtils.JoiningTogether(params);//拼接
params.add(new BasicNameValuePair("sign", ByteUtils.MD5(ByteUtils.MD5(sign))));//验签
String url = IpAddress.getCaptcha;// 获取短信验证码
ConnServerPost csp = new ConnServerPost(url, myHandler, "getCaptcha",params);
new Thread(csp).start();
}
private Handler myHandler;
private void myHandler() {
myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
String data = msg.getData().getString("data");
if (msg.obj.equals("getCaptcha")) {
showDialogUtil.stopProgressDialog();
if (data.equals("Timeout")) {//超时
showDialogUtil.showDialog("获取验证码超时,请检查网络后重试", context);
} else {
JSONObject j = Utility.jsonObjectData(context,data);
String code = j.getString("code");
if ("1000".equals(code)) {
CountdownAsyncTask cdat = new CountdownAsyncTask(getCodeKey,context);
cdat.execute(1000);
} else {
showDialogUtil.showDialog(j.getString("info"), context);
Log.i("DeviceMobilePhoneBinding-179",j.getString("info"));
}
}
} else if (msg.obj.equals("ChangePhone")) {
if (data.equals("Timeout")) {//超时
showDialogUtil.stopProgressDialog();
showDialogUtil.showDialog("上传超时,请检查网络后重试", context);
} else {
showDialogUtil.stopProgressDialog();
JSONObject j = Utility.jsonObjectData(context,data);
String code = j.getString("code");
if ("1000".equals(code)) {
showDialogUtil.showDialog("更换手机号成功,请重新登录", context,new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// Intent intent = new Intent(context,VerificationOrdPhone.class);
// intent.putExtra("finish", "true");
// setResult(RESULT_OK,intent);
//返回登入页
Intent stopSer = new Intent(ReplecePhoneNumber.this, MyService.class);
Intent intent = new Intent(ReplecePhoneNumber.this, LoginActivity.class);
sendCmd("DeviceDisconnect", 0);
stopService(stopSer);// 停止服务
startActivity(intent);// 返回登录界面
finish();
}
});
} else {
showDialogUtil.showDialog(j.getString("info"), context);
}
}
}
}
};
}
public void sendCmd(String value, int i) {
Intent serviceIntent = new Intent();
serviceIntent.setAction("org.great.util.MyService");
serviceIntent.setAction("org.great.activity.All");
serviceIntent.putExtra("value", value);
serviceIntent.putExtra("num", i);
sendBroadcast(serviceIntent);
}
/**
* text状态监听
*/
private class TextChanged implements TextWatcher {
EditText e;
public TextChanged(EditText e) {
this.e = e;
}
@Override
public void afterTextChanged(Editable arg0) {
if (e == phoneNumber && TextUtils.isEmpty(phoneNumber.getText()))
phoneNumberIV.setVisibility(View.GONE);
else if (e == code_et && TextUtils.isEmpty(code_et.getText()))
code_etIV.setVisibility(View.GONE);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {}
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
if (e == phoneNumber)
phoneNumberIV.setVisibility(View.VISIBLE);
else if (e == code_et)
code_etIV.setVisibility(View.VISIBLE);
}
}
}
| true |
d9cee85bd58514382ca9af481831e8e10f8ccd8f | Java | MrSpock182/crypto4j | /src/main/java/io/github/mrspock182/encryption/EncryptionSymmetrical.java | UTF-8 | 3,198 | 2.765625 | 3 | [
"MIT"
] | permissive | package io.github.mrspock182.encryption;
import io.github.mrspock182.Encryption;
import io.github.mrspock182.exception.CryptographyException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import static javax.crypto.Cipher.ENCRYPT_MODE;
public class EncryptionSymmetrical implements Encryption {
private final String utf;
private final String type;
private final String cipher;
private final String cryptKey;
public EncryptionSymmetrical(String type, String utf, String cryptKey, String cipher) {
this.utf = utf;
this.type = type;
this.cipher = cipher;
this.cryptKey = cryptKey;
}
@Override
public String encrypt(Long value) throws CryptographyException {
if (value != null) {
return baseEncrypt(value.toString());
}
return null;
}
@Override
public String encrypt(String value) throws CryptographyException {
if (value != null) {
return baseEncrypt(value);
}
return null;
}
@Override
public String encrypt(Integer value) throws CryptographyException {
if (value != null) {
return baseEncrypt(value.toString());
}
return null;
}
@Override
public String encrypt(BigDecimal value) throws CryptographyException {
if (value != null) {
return baseEncrypt(value.toString());
}
return null;
}
@Override
public String encrypt(BigInteger value) throws CryptographyException {
if (value != null) {
return baseEncrypt(value.toString());
}
return null;
}
@Override
public String encrypt(LocalDate value, String dateFormatter) throws CryptographyException {
if (value != null) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormatter);
String data = value.format(formatter);
return baseEncrypt(data);
}
return null;
}
@Override
public String encrypt(LocalDateTime value, String dateFormatter) throws CryptographyException {
if (value != null) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormatter);
String data = value.format(formatter);
return baseEncrypt(data);
}
return null;
}
private String baseEncrypt(String value) throws CryptographyException {
try {
if (!value.isEmpty()) {
Cipher encrypt = Cipher.getInstance(this.cipher);
SecretKey key = new SecretKeySpec(cryptKey.getBytes(utf), this.type);
encrypt.init(ENCRYPT_MODE, key);
byte[] crypt = encrypt.doFinal(value.getBytes(utf));
return Base64.getUrlEncoder().encodeToString(crypt);
}
return "";
} catch (Exception ex) {
throw new CryptographyException(ex);
}
}
}
| true |
4fb5abe33fd066860c7852100aac0d06ab0fc593 | Java | stuckless/sagetv-sagex-api | /src/tools/java/org/jdna/url/CookieHandler.java | UTF-8 | 1,633 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | //
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.jdna.url;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import org.jdna.url.ICookieHandler;
import org.jdna.url.Url;
public class CookieHandler implements ICookieHandler {
private static final Logger log = Logger.getLogger(CookieHandler.class);
private Map<String, String> cookies = new HashMap();
private String cookieUrl = null;
private boolean lookingForCookies = true;
public CookieHandler(String cookieUrl) {
this.cookieUrl = cookieUrl;
}
public Map<String, String> getCookiesToSend(String url) {
log.debug("getCookies called on url: " + url);
if(this.cookies.size() == 0 && this.lookingForCookies) {
log.debug("We don\'t have a cookie, so we\'ll try and get them from: " + this.cookieUrl);
this.lookingForCookies = false;
Url u = new Url(this.cookieUrl);
try {
u.getInputStream(this);
} catch (IOException var4) {
;
}
}
return this.cookies;
}
public void handleSetCookie(String url, String cookie) {
log.debug(String.format("Handlin Cookies: Url: %s; Cookie: %s\n", new Object[]{url, cookie}));
Pattern p = Pattern.compile("([^ =:]+)=([^;]+)");
Matcher m = p.matcher(cookie);
if(m.find()) {
this.cookies.put(m.group(1), m.group(2));
}
}
}
| true |
bd9c82a7078fcbeea6e524b15a7c1c19493ff380 | Java | carolineGarcias/hbsales | /src/main/java/br/com/hbsis/fornecedor/FornecedorDTO.java | UTF-8 | 2,806 | 2.53125 | 3 | [] | no_license | package br.com.hbsis.fornecedor;
public class FornecedorDTO {
private Long idFornecedor;
private String razaoSocial;
private String cnpj;
private String nomeFantasia;
private String endereco;
private String telefone;
private String email;
public FornecedorDTO() {
}
public FornecedorDTO(Long idFornecedor, String razaoSocial,
String nomeFantasia, String endereco,
String email, String cnpj, String telefone) {
this.idFornecedor = idFornecedor;
this.razaoSocial = razaoSocial;
this.nomeFantasia = nomeFantasia;
this.endereco = endereco;
this.email = email;
this.cnpj = cnpj;
this.telefone = telefone;
}
public static FornecedorDTO of(Fornecedor fornecedor) {
return new FornecedorDTO(
fornecedor.getIdFornecedor(),
fornecedor.getRazaoSocial(),
fornecedor.getNomeFantasia(),
fornecedor.getEndereco(),
fornecedor.getEmail(),
fornecedor.getCnpj(),
fornecedor.getTelefone()
);
}
public Long getIdFornecedor() {
return idFornecedor;
}
public void setIdFornecedor(Long idFornecedor) {
this.idFornecedor = idFornecedor;
}
public String getRazaoSocial() {
return razaoSocial;
}
public void setRazaoSocial(String razaoSocial) {
this.razaoSocial = razaoSocial;
}
public String getNomeFantasia() {
return nomeFantasia;
}
public void setNomeFantasia(String nomeFantasia) {
this.nomeFantasia = nomeFantasia;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getCnpj() {
return cnpj;
}
public void setCnpj(String cnpj) {
this.cnpj = cnpj;
}
@Override
public String toString() {
return "Fornecedor{" +
"id= '" + idFornecedor +
", Razao Social= '" + razaoSocial + '\'' +
", CNPJ= '" + cnpj + '\'' +
", Nome Fantasia= '" + nomeFantasia + '\'' +
", Endereço= '" + endereco + '\'' +
", Telefone= '" + telefone + '\'' +
", E-mail= '" + email + '\'' +
'}';
}
} | true |
dd7ed32fbd0a9e71052b679c3ac61d4a54205059 | Java | nimingzhanghu/gmall0319 | /gmall-manage-service/src/main/java/com/atguigu/gmall/manage/mapper/BaseAttrInfoMapper.java | UTF-8 | 554 | 1.953125 | 2 | [] | no_license | package com.atguigu.gmall.manage.mapper;
import com.atguigu.gmall.bean.BaseAttrInfo;
import tk.mybatis.mapper.common.Mapper;
import java.util.List;
/**
* 平台属性表
*/
public interface BaseAttrInfoMapper extends Mapper<BaseAttrInfo> {
/**
* day05 平台属性功能动态加载
*/
//根据三级分类id查询属性表 -- 通用 Mapper只针对简单查询
// -- 凡是涉及到多表关联查询,通用Mapper不再使用
List<BaseAttrInfo> getBaseAttrInfoListByCatalog3Id(Long catalog3Id);
}
| true |
e82c8cdf0c6b59db105ba9f39490f2c67e5b241e | Java | Yaroslav97/cdp | /module4/hw13/src/main/java/com/epam/cdp/dao/impl/TicketDAO.java | UTF-8 | 2,099 | 2.265625 | 2 | [] | no_license | package com.epam.cdp.dao.impl;
import com.epam.cdp.dao.CrudRepository;
import com.epam.cdp.model.Event;
import com.epam.cdp.model.Ticket;
import com.epam.cdp.model.User;
import com.epam.cdp.storage.Storage;
import com.epam.cdp.storage.StorageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.stream.Collectors;
public class TicketDAO implements CrudRepository<Ticket, Long> {
private Storage<Ticket, Long> storage;
private StorageUtil<Ticket, Long> storageUtil;
public void initStorage() {
storage.patchUpdate(storageUtil.readCSV(StorageUtil.Model.TICKET));
}
@Autowired
public void setStorageUtil(StorageUtil<Ticket, Long> storageUtil) {
this.storageUtil = storageUtil;
}
@Autowired
public void setStorage(Storage<Ticket, Long> storage) {
this.storage = storage;
}
@Override
public Ticket save(Ticket ticket) {
return storage.update(ticket.getId(), ticket);
}
@Override
public Ticket update(Ticket ticket) {
return storage.update(ticket.getId(), ticket);
}
@Override
public Ticket findOne(Long id) {
return storage.findOne(id);
}
@Override
public void delete(Long id) {
storage.delete(id);
}
@Override
public Iterable<Ticket> findAll() {
return storage.findAll();
}
public List<Ticket> getBookedTickets(User user, int pageSize, int pageNum) {
List<Ticket> ticketList = (List<Ticket>) storage.findAll();
return ticketList.stream().filter(u -> u.getUserId() == user.getId())
.skip(pageNum)
.limit(pageSize)
.collect(Collectors.toList());
}
public List<Ticket> getBookedTickets(Event event, int pageSize, int pageNum) {
List<Ticket> ticketList = (List<Ticket>) storage.findAll();
return ticketList.stream().filter(e -> e.getEventId() == event.getId())
.skip(pageNum)
.limit(pageSize)
.collect(Collectors.toList());
}
}
| true |
09186729df6e9407cbba5528e342ad09c0d2d7eb | Java | nansyg21/AmusingMuseum | /app/src/main/java/com/Anaptixis/AmusingMuseum/OtherMuseumsSQLiteDB.java | UTF-8 | 2,958 | 2.640625 | 3 | [] | no_license | package com.Anaptixis.AmusingMuseum;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by panos on 18/10/2015.
*/
public class OtherMuseumsSQLiteDB extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Museums.db";
private static final String TABLE_NAME_MUSEUMS = "Museums";
public static final String COLUMN_MUSEUM_ID = "m_id";
public static final String COLUMN_USERNAME = "username";
public static final String COLUMN_MUSEUM_NAME = "museum_name";
public static final String COLUMN_NUMBER_OF_ROOMS = "number_of_rooms";
public static final String COLUMN_LOGO = "logo";
public static final String COLUMN_FLOOR_PLAN = "floor_plan";
public static final String SQL_DELETE_ENTRIES_FROM_MUSEUMS =
"DROP TABLE IF EXISTS " + OtherMuseumsSQLiteDB.TABLE_NAME_MUSEUMS;
public OtherMuseumsSQLiteDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.w("Warn", "DB Constructor!");
}
@Override
public void onCreate(SQLiteDatabase db) {
/** String CREATE_PRODUCTS_TABLE = "CREATE TABLE IF NOT EXISTS " +
TABLE_NAME_MUSEUMS + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY,"
+ COLUMN_PRODUCTNAME + " TEXT,"
+ COLUMN_QUANTITY + " INTEGER" + ")";
db.execSQL(CREATE_PRODUCTS_TABLE);
Log.w("Warn","DB Created!");
**/
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES_FROM_MUSEUMS);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
public void addData()
{
/** ContentValues values = new ContentValues();
values.put(COLUMN_PRODUCTNAME, "myname");//queue
values.put(COLUMN_QUANTITY, "myquantity");
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_NAME_MUSEUMS, null, values);
db.close();
Log.w("Warn", "Data Added");
**/
}
public void getData()
{
String query = "Select * FROM " + TABLE_NAME_MUSEUMS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null); //Printing data using cursor
while (cursor.moveToNext())
{
Log.w("Warn", cursor.getString(0));
Log.w("Warn", cursor.getString(1));
Log.w("Warn", cursor.getString(2));
}
Log.w("Warn","All data shown");
cursor.close();
db.close();
}
} | true |
ab22758007749e79300dc9f135511b00f6df1c9f | Java | AndreiLazarchik/FreeIT | /lesson_03/Task02.java | UTF-8 | 631 | 3.421875 | 3 | [] | no_license | package lesson_03;
public class Task02 {
public static void main(String[] args) {
int quantity = 1; // кол-во клеток в стартовый момент
for (int i = 0; i < 25; i=i+3) { // цикл до 24 часов включительно с шагом в 3 часа
System.out.println("Через " + i + " ч. будет " + quantity + " клет."); // выводим количество клеток на экран
quantity = quantity*2; // каждый цикл увеличиваем кол-во клеток вдвое
}
}
}
| true |
f5978a80c60f19c82bf9816d04f44128727d88c2 | Java | vampire-studios/VehiclesAndTheKitchenSink-Fabric | /src/main/java/io/github/vampirestudios/vks/entity/LandVehicleEntity.java | UTF-8 | 9,245 | 2.265625 | 2 | [
"CC0-1.0"
] | permissive | package io.github.vampirestudios.vks.entity;
import io.github.vampirestudios.vks.client.render.Wheel;
import io.github.vampirestudios.vks.common.entity.PartPosition;
import net.minecraft.client.MinecraftClient;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.data.DataTracker;
import net.minecraft.entity.data.TrackedData;
import net.minecraft.entity.data.TrackedDataHandlerRegistry;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
/**
* Author: MrCrayfish
*/
public abstract class LandVehicleEntity extends PoweredVehicleEntity
{
private static final TrackedData<Boolean> DRIFTING = DataTracker.registerData(LandVehicleEntity.class, TrackedDataHandlerRegistry.BOOLEAN);
public float drifting;
public float additionalYaw;
public float prevAdditionalYaw;
public float frontWheelRotation;
public float prevFrontWheelRotation;
public float rearWheelRotation;
public float prevRearWheelRotation;
public LandVehicleEntity(EntityType<?> entityType, World worldIn)
{
super(entityType, worldIn);
}
@Override
public void initDataTracker()
{
super.initDataTracker();
this.dataTracker.startTracking(DRIFTING, false);
}
@Override
public void onUpdateVehicle() {
super.onUpdateVehicle();
this.updateWheels();
}
@Override
public void updateVehicle()
{
this.prevAdditionalYaw = this.additionalYaw;
this.prevFrontWheelRotation = this.frontWheelRotation;
this.prevRearWheelRotation = this.rearWheelRotation;
this.updateDrifting();
}
@Override
public void onClientUpdate()
{
super.onClientUpdate();
LivingEntity entity = (LivingEntity) this.getControllingPassenger();
if(entity != null && entity.equals(MinecraftClient.getInstance().player))
{
/*boolean drifting = VehicleMod.PROXY.isDrifting();
if(this.isDrifting() != drifting)
{
this.setDrifting(drifting);
PacketHandler.instance.sendToServer(new MessageDrift(drifting));
}*/
}
}
@Override
public void updateVehicleMotion()
{
float currentSpeed = this.currentSpeed;
if(this.speedMultiplier > 1.0F)
{
this.speedMultiplier = 1.0F;
}
/* Applies the speed multiplier to the current speed */
currentSpeed = currentSpeed + (currentSpeed * this.speedMultiplier);
VehicleProperties properties = this.getProperties();
if(properties.getFrontAxelVec() != null && properties.getRearAxelVec() != null)
{
PartPosition bodyPosition = properties.getBodyPosition();
Vec3d nextFrontAxelVec = new Vec3d(0, 0, currentSpeed / 20F).rotateY(this.wheelAngle * 0.017453292F);
nextFrontAxelVec = nextFrontAxelVec.add(properties.getFrontAxelVec().multiply(0.0625));
Vec3d nextRearAxelVec = new Vec3d(0, 0, currentSpeed / 20F);
nextRearAxelVec = nextRearAxelVec.add(properties.getRearAxelVec().multiply(0.0625));
double deltaYaw = Math.toDegrees(Math.atan2(nextRearAxelVec.z - nextFrontAxelVec.z, nextRearAxelVec.x - nextFrontAxelVec.x)) + 90;
if(this.isRearWheelSteering())
{
deltaYaw -= 180;
}
this.yaw += deltaYaw;
this.deltaYaw = (float) -deltaYaw;
Vec3d nextVehicleVec = nextFrontAxelVec.add(nextRearAxelVec).multiply(0.5);
nextVehicleVec = nextVehicleVec.subtract(properties.getFrontAxelVec().add(properties.getRearAxelVec()).multiply(0.0625).multiply(0.5));
nextVehicleVec = nextVehicleVec.multiply(bodyPosition.getScale()).rotateY((-this.yaw + 90) * 0.017453292F);
float targetRotation = (float) Math.toDegrees(Math.atan2(nextVehicleVec.z, nextVehicleVec.x));
float f1 = MathHelper.sin(targetRotation * 0.017453292F) / 20F * (currentSpeed > 0 ? 1 : -1);
float f2 = MathHelper.cos(targetRotation * 0.017453292F) / 20F * (currentSpeed > 0 ? 1 : -1);
this.vehicleMotionX = (-currentSpeed * f1);
if(!launching)
{
this.setVelocity(this.getVelocity().add(0, -0.08, 0));
}
this.vehicleMotionZ = (currentSpeed * f2);
}
else
{
float f1 = MathHelper.sin(this.yaw * 0.017453292F) / 20F;
float f2 = MathHelper.cos(this.yaw * 0.017453292F) / 20F;
this.vehicleMotionX = (-currentSpeed * f1);
if(!launching)
{
this.setVelocity(this.getVelocity().add(0, -0.08, 0));
}
this.vehicleMotionZ = (currentSpeed * f2);
}
}
@Override
protected void updateTurning()
{
this.turnAngle = /*VehicleMod.PROXY.getTargetTurnAngle(this, this.isDrifting())*/0.0F;
this.wheelAngle = this.turnAngle * Math.max(0.1F, 1.0F - Math.abs(currentSpeed / this.getMaxSpeed()));
VehicleProperties properties = this.getProperties();
if(properties.getFrontAxelVec() == null || properties.getRearAxelVec() == null)
{
this.deltaYaw = this.wheelAngle * (currentSpeed / 30F) / 2F;
}
if(world.isClient)
{
this.targetWheelAngle = this.isDrifting() ? -35F * (this.turnAngle / (float) this.getMaxTurnAngle()) * this.getNormalSpeed() : this.wheelAngle - 35F * (this.turnAngle / (float) this.getMaxTurnAngle()) * drifting;
this.renderWheelAngle = this.renderWheelAngle + (this.targetWheelAngle - this.renderWheelAngle) * (this.isDrifting() ? 0.35F : 0.5F);
}
}
private void updateDrifting()
{
TurnDirection turnDirection = this.getTurnDirection();
if(this.getControllingPassenger() != null && this.isDrifting())
{
if(turnDirection != TurnDirection.FORWARD)
{
AccelerationDirection acceleration = this.getAcceleration();
if(acceleration == AccelerationDirection.FORWARD)
{
this.currentSpeed *= 0.975F;
}
this.drifting = Math.min(1.0F, this.drifting + 0.025F);
}
}
else
{
this.drifting *= 0.95F;
}
this.additionalYaw = 25F * this.drifting * (this.turnAngle / (float) this.getMaxTurnAngle()) * Math.min(this.getActualMaxSpeed(), this.getActualSpeed() * 2F);
//Updates the delta yaw to consider drifting
this.deltaYaw = this.wheelAngle * (this.currentSpeed / 30F) / (this.isDrifting() ? 1.5F : 2F);
}
public void updateWheels()
{
VehicleProperties properties = this.getProperties();
double wheelCircumference = 16.0;
double vehicleScale = properties.getBodyPosition().getScale();
double speed = this.getSpeed();
Wheel frontWheel = properties.getFirstFrontWheel();
if(frontWheel != null)
{
double frontWheelCircumference = wheelCircumference * vehicleScale * frontWheel.getScaleY();
double rotation = (speed * 16) / frontWheelCircumference;
this.frontWheelRotation -= rotation * 20F;
}
Wheel rearWheel = properties.getFirstRearWheel();
if(rearWheel != null)
{
double rearWheelCircumference = wheelCircumference * vehicleScale * rearWheel.getScaleY();
double rotation = (speed * 16) / rearWheelCircumference;
this.rearWheelRotation -= rotation * 20F;
}
}
@Override
public void createParticles()
{
if(this.canDrive())
{
super.createParticles();
}
}
@Override
protected void removePassenger(Entity passenger)
{
super.removePassenger(passenger);
if(this.getControllingPassenger() == null)
{
this.yaw -= this.additionalYaw;
this.additionalYaw = 0;
this.drifting = 0;
}
}
public void setDrifting(boolean drifting)
{
this.dataTracker.set(DRIFTING, drifting);
}
public boolean isDrifting()
{
return this.dataTracker.get(DRIFTING);
}
@Override
protected float getModifiedAccelerationSpeed()
{
if(trailer != null)
{
if(trailer.getPassengerList().size() > 0)
{
return super.getModifiedAccelerationSpeed() * 0.5F;
}
else
{
return super.getModifiedAccelerationSpeed() * 0.8F;
}
}
return super.getModifiedAccelerationSpeed();
}
@Override
public float getModifiedRotationYaw()
{
return this.yaw - this.additionalYaw;
}
public boolean isRearWheelSteering()
{
VehicleProperties properties = this.getProperties();
return properties.getFrontAxelVec() != null && properties.getRearAxelVec() != null && properties.getFrontAxelVec().z < properties.getRearAxelVec().z;
}
} | true |
6dda26be7874edc536ec5be2b37d45bc6b1971dc | Java | bilalcaliskan/postgres-demo | /src/main/java/com/bcaliskan/postgresdemo/persistence/repository/AnswerRepository.java | UTF-8 | 416 | 1.835938 | 2 | [] | no_license | package com.bcaliskan.postgresdemo.persistence.repository;
import com.bcaliskan.postgresdemo.persistence.entity.AnswerEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface AnswerRepository extends JpaRepository<AnswerEntity, Long> {
List<AnswerEntity> findByQuestionId(Long questionId);
} | true |
9ccd4fa9262805f3a3b493df081276df569df334 | Java | landcoder/DesignPattern | /src/com/mustang/factory/abs/Provider.java | UTF-8 | 142 | 1.875 | 2 | [] | no_license | package com.mustang.factory.abs;
/**
* 提供者
* Created by Mustang on 17/2/5.
*/
public interface Provider {
Sender produce();
}
| true |
f30c449da4bba21c05b6e9cb73a961a64c763183 | Java | Avokado-an/OwnProject | /OwnProject/src/main/java/com/example/OwnProject/service/Implementation/ContactsServiceImplementation.java | UTF-8 | 836 | 2.125 | 2 | [] | no_license | package com.example.OwnProject.service.Implementation;
import com.example.OwnProject.Entites.Contact;
import com.example.OwnProject.Entites.User;
import com.example.OwnProject.repos.ContactsRepo;
import com.example.OwnProject.service.ContactsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service
public class ContactsServiceImplementation implements ContactsService {
private ContactsRepo repo;
@Autowired
public void setContactsRepo(ContactsRepo repo){
this.repo = repo;
}
@Override
public void saveContact(Contact contact) {
repo.save(contact);
}
@Override
public Set<Contact> findByUser(User user) {
return repo.findAllByUser(user);
}
}
| true |
19b2719df84b32870d5852f9054485b67e9d6aa0 | Java | zeropay2019/ZeroPay_2019 | /src/server/src/main/java/com/seoul/zero/app/service/impl/BoardServiceImpl.java | UTF-8 | 1,645 | 2.359375 | 2 | [] | no_license | package com.seoul.zero.app.service.impl;
import com.seoul.zero.app.model.mapper.BoardMapper;
import com.seoul.zero.app.model.vo.Board;
import com.seoul.zero.app.model.wrapper.ResponseWrapper;
import com.seoul.zero.app.service.BoardService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class BoardServiceImpl implements BoardService {
@Resource
private BoardMapper boardMapper;
public ResponseWrapper createWrapper() {
ResponseWrapper response = new ResponseWrapper();
response.setResultCode(0);
response.setMessage("success");
return response;
}
// 공지사항 목록
@Override
public ResponseWrapper boardList() {
ResponseWrapper wrapper = createWrapper();
List<Board> bList = boardMapper.boardList();
if(bList.size()==0){
wrapper.setResultCode(109);
wrapper.setMessage("공지사항을 가져오는데 실패 했습니다.");
}else{
wrapper.setParam(bList);
}
return wrapper;
}
// 공지사항 상세 보기
@Override
public ResponseWrapper detailBoard(Board param) {
ResponseWrapper wrapper = createWrapper();
Board board = boardMapper.detailBoard(param);
if(board == null){
wrapper.setResultCode(110);
wrapper.setMessage("공지사항 글을 가져오는데 실패 했습니다.");
}else{
wrapper.setParam(board);
// 조회수 증가
boardMapper.plusCount(param);
}
return wrapper;
}
}
| true |
84b00cf4e2583c89de9735ab7a9790ea53aff7c7 | Java | DefNeoRoman/vk-chat-manager | /src/main/java/config/MyProperties.java | UTF-8 | 476 | 2.625 | 3 | [] | no_license | package config;
import java.util.*;
@SuppressWarnings("serial")
public class MyProperties extends Properties {
public Enumeration<Object> keys() {
Enumeration<Object> keysEnum = super.keys();
Vector<Object> keyList = new Vector<Object>();
while (keysEnum.hasMoreElements()) {
keyList.add(keysEnum.nextElement());
}
keyList.sort(Comparator.comparing(Object::toString));
return keyList.elements();
}
}
| true |
f6be2a40fbda855ca740290a0b8edf36d1fb892d | Java | EverGreen7112/PowerUp-2018 | /PowerUp-2018/src/com/spikes2212/robot/Commands/commandGroups/autonomousCommands/MiddleToSwitchAuto.java | UTF-8 | 3,327 | 2.375 | 2 | [] | no_license | package com.spikes2212.robot.Commands.commandGroups.autonomousCommands;
import java.util.function.Supplier;
import com.spikes2212.dashboard.ConstantHandler;
import com.spikes2212.genericsubsystems.commands.MoveBasicSubsystem;
import com.spikes2212.genericsubsystems.drivetrains.commands.DriveArcade;
import com.spikes2212.genericsubsystems.drivetrains.commands.DriveArcadeWithPID;
import com.spikes2212.robot.ImageProcessingConstants;
import com.spikes2212.robot.Robot;
import com.spikes2212.robot.SubsystemComponents;
import com.spikes2212.robot.SubsystemConstants;
import com.spikes2212.robot.Commands.commandGroups.MoveLiftToTarget;
import com.spikes2212.robot.Commands.commandGroups.PlaceCube;
import com.spikes2212.utils.PIDSettings;
import edu.wpi.first.wpilibj.command.CommandGroup;
/**
*
* This command group moves the robot from the middle to your side of the
* switch. First it moves forwards and turns to your side of the switch until it
* sees a light sensor and move to it.
*/
public class MiddleToSwitchAuto extends CommandGroup {
// initial turning constants
public static final Supplier<Double> FORWARD_SPEED = ConstantHandler
.addConstantDouble("switch from middle auto - forward speed", 0.4);
public static final Supplier<Double> ROTATION_SPEED = ConstantHandler
.addConstantDouble("switch from middle auto - rotation speed", 0.6);
public static final Supplier<Double> ROTATION_TIME = ConstantHandler
.addConstantDouble("switch from middle auto - rotation time", 0.5);
// orienting constants
public static final Supplier<Double> TOLERANCE = ConstantHandler
.addConstantDouble("switch from middle auto - orienting tolerance", 0);
public static final Supplier<Double> PID_WAIT_TIME = ConstantHandler
.addConstantDouble("switch from middle auto PID waitTime", 1);
public static final Supplier<Double> ORIENTATION_FORWARD_SPEED = ConstantHandler
.addConstantDouble("switch from middle auto - orientation forward speed", 0.45);
public static final Supplier<Double> ORIENTATION_TIME_OUT = ConstantHandler
.addConstantDouble("switch from middle auto - oriantation timeout", 3.8);
public MiddleToSwitchAuto(String gameData) {
addParallel(new DriveToSwitchFromMiddle(gameData));
// move lift
addSequential(new MoveLiftToTarget(SubsystemComponents.Lift.HallEffects.SWITCH));
addSequential(new MoveBasicSubsystem(Robot.liftLocker, SubsystemConstants.LiftLocker.LOCK_SPEED));
}
@Override
protected void end() {
super.end();
new PlaceCube().start();
}
public class DriveToSwitchFromMiddle extends CommandGroup {
public DriveToSwitchFromMiddle(String gameData) {
// turn to the correct direction
addSequential(
new DriveArcade(Robot.drivetrain, FORWARD_SPEED,
() -> gameData.charAt(0) == 'L' ? ROTATION_SPEED.get() : -ROTATION_SPEED.get()),
ROTATION_TIME.get());
// drive while orienting
addSequential(new DriveArcadeWithPID(Robot.drivetrain, ImageProcessingConstants.CENTER, () -> 0.0,
ORIENTATION_FORWARD_SPEED,
new PIDSettings(SubsystemConstants.Drivetrain.ORIENTATION_KP.get(),
SubsystemConstants.Drivetrain.ORIENTATION_KI.get(),
SubsystemConstants.Drivetrain.ORIENTATION_KD.get(), TOLERANCE.get(), PID_WAIT_TIME.get()),
ImageProcessingConstants.RANGE), ORIENTATION_TIME_OUT.get());
}
}
}
| true |
add277fc6b089436756631d986c95290687b4d69 | Java | axrkozlov/AmazingDay | /app/src/main/java/com/portfex/amazingday/presenters/trainings/TrainingEditDialog.java | UTF-8 | 8,134 | 2.15625 | 2 | [] | no_license | package com.portfex.amazingday.presenters.trainings;
import android.app.TimePickerDialog;
import android.support.v7.app.AlertDialog;
import android.app.Dialog;
import android.support.v4.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.portfex.amazingday.model.training.Training;
import com.portfex.amazingday.model.training.TrainingsManager;
import com.portfex.amazingday.R;
import com.portfex.amazingday.utilites.DateUtils;
import java.util.ArrayList;
import java.util.Calendar;
/**
* Created by alexanderkozlov on 11/29/17.
*/
public class TrainingEditDialog extends DialogFragment implements View.OnClickListener {
private TrainingsManager mTrainingsManager;
private Training mTrainingOld;
private View mTrainingCreateView;
private Boolean startTimeChanged;
private Button mEditCreate;
private Button mEditUpdate;
private Button mEditDuplicate;
private Button mEditDelete;
private Button mEditStartTime;
private EditText mEditName;
private EditText mEditDesc;
private ToggleButton mEditDay1;
private ToggleButton mEditDay2;
private ToggleButton mEditDay3;
private ToggleButton mEditDay4;
private ToggleButton mEditDay5;
private ToggleButton mEditDay6;
private ToggleButton mEditDay7;
private String trainingIdTag;
private long mId;
private AlertDialog mTrainingCreateDialog;
public static TrainingEditDialog newInstance() {
return new TrainingEditDialog();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
trainingIdTag = getResources().getString(R.string.training_id_tag);
Bundle bundle = this.getArguments();
if (bundle != null) {
mId = bundle.getLong(trainingIdTag, 0);
}
LayoutInflater inflater = LayoutInflater.from(getContext());
mTrainingCreateView = inflater.inflate(R.layout.activity_training_edit, null);
mTrainingsManager = TrainingsManager.getInstance(getContext().getApplicationContext());
startTimeChanged = false;
mEditCreate = mTrainingCreateView.findViewById(R.id.bt_training_create);
mEditUpdate = mTrainingCreateView.findViewById(R.id.bt_training_update);
mEditDuplicate = mTrainingCreateView.findViewById(R.id.bt_training_duplicate);
mEditDelete = mTrainingCreateView.findViewById(R.id.bt_training_delete);
mEditStartTime = mTrainingCreateView.findViewById(R.id.bt_training_create_start_time);
mEditName = mTrainingCreateView.findViewById(R.id.training_create_name);
mEditDesc = mTrainingCreateView.findViewById(R.id.training_create_desc);
mEditDay1 = mTrainingCreateView.findViewById(R.id.tb_day1);
mEditDay2 = mTrainingCreateView.findViewById(R.id.tb_day2);
mEditDay3 = mTrainingCreateView.findViewById(R.id.tb_day3);
mEditDay4 = mTrainingCreateView.findViewById(R.id.tb_day4);
mEditDay5 = mTrainingCreateView.findViewById(R.id.tb_day5);
mEditDay6 = mTrainingCreateView.findViewById(R.id.tb_day6);
mEditDay7 = mTrainingCreateView.findViewById(R.id.tb_day7);
if (mId > 0) {
mTrainingOld = mTrainingsManager.getTraining(mId);
if (mTrainingOld != null) {
mEditCreate.setVisibility(View.GONE);
mEditUpdate.setVisibility(View.VISIBLE);
mEditDuplicate.setVisibility(View.VISIBLE);
mEditDelete.setVisibility(View.VISIBLE);
bindTrainingToEdit();
}
}
AlertDialog.Builder mBuilder = new AlertDialog.Builder(getActivity());
mBuilder.setView(mTrainingCreateView);
mTrainingCreateDialog = mBuilder.create();
mTrainingCreateDialog.show();
mEditCreate.setOnClickListener(this);
mEditStartTime.setOnClickListener(this);
mEditUpdate.setOnClickListener(this);
mEditDuplicate.setOnClickListener(this);
mEditDelete.setOnClickListener(this);
return mTrainingCreateDialog;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_training_create:
createTraining();
break;
case R.id.bt_training_create_start_time:
showTimePickerDialog();
break;
case R.id.bt_training_update:
updateTraining();
break;
case R.id.bt_training_delete:
removeTraining();
break;
}
}
private void bindTrainingToEdit() {
if (mTrainingOld == null) {
return;
}
mEditName.setText(mTrainingOld.getName());
mEditDesc.setText(mTrainingOld.getDescription());
ArrayList<Boolean> weekDays = DateUtils.parseWeekDays(mTrainingOld.getWeekDaysComposed());
mEditDay1.setChecked(weekDays.get(0));
mEditDay2.setChecked(weekDays.get(1));
mEditDay3.setChecked(weekDays.get(2));
mEditDay4.setChecked(weekDays.get(3));
mEditDay5.setChecked(weekDays.get(4));
mEditDay6.setChecked(weekDays.get(5));
mEditDay7.setChecked(weekDays.get(6));
long startTimeLong = mTrainingOld.getStartTime();
if (startTimeLong > 0) {
mEditStartTime.setText(DateUtils.getTimeString(startTimeLong));
}
}
private void createTraining() {
if (mEditName.getText().length() == 0) {
Toast.makeText(getContext(), "Please, type Name of workout", Toast.LENGTH_SHORT).show();
return;
}
Training training = fill(new Training());
mTrainingsManager.insertTraining(training);
mTrainingCreateDialog.dismiss();
}
private void updateTraining() {
if (mId == 0) {
return;
}
if (mEditName.getText().length() == 0) {
Toast.makeText(getContext(), "Please, type Name of workout", Toast.LENGTH_SHORT).show();
return;
}
Training training = fill(new Training(mId));
mTrainingsManager.updateTraining(training);
mTrainingCreateDialog.dismiss();
}
private Training fill(Training training) {
if (training == null) {
return null;
}
training.setName(mEditName.getText().toString());
training.setDescription(mEditDesc.getText().toString());
ArrayList<Boolean> weekDays = new ArrayList<>();
weekDays.add(mEditDay1.isChecked());
weekDays.add(mEditDay2.isChecked());
weekDays.add(mEditDay3.isChecked());
weekDays.add(mEditDay4.isChecked());
weekDays.add(mEditDay5.isChecked());
weekDays.add(mEditDay6.isChecked());
weekDays.add(mEditDay7.isChecked());
training.setWeekDaysComposed(DateUtils.composeWeekDays(weekDays));
if (startTimeChanged) {
long startTimeLong = DateUtils.getTimeMillis(mEditStartTime.getText().toString());
training.setStartTime(startTimeLong);
}
return training;
}
private void removeTraining() {
mTrainingsManager.removeTraining(mId);
mTrainingCreateDialog.dismiss();
}
public void showTimePickerDialog() {
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(getContext(),
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mEditStartTime.setText(String.format("%02d:%02d", hourOfDay, minute));
startTimeChanged = true;
}
}, hour, minute, true);
timePickerDialog.show();
}
}
| true |
65aabb0f70b2f71383b924ebdcd9bed25d78c2db | Java | kucro3/Jam2 | /Jam2/src/org/kucro3/jam2/util/context/visitable/VisitableClassContextRestrictedModifiableCompound.java | UTF-8 | 1,893 | 2.265625 | 2 | [] | no_license | package org.kucro3.jam2.util.context.visitable;
import org.kucro3.jam2.util.ClassContext;
import org.objectweb.asm.ClassVisitor;
public class VisitableClassContextRestrictedModifiableCompound extends VisitableClassContextCompound
implements ClassContext.RestrictedModifiable {
public VisitableClassContextRestrictedModifiableCompound(ClassContext ref)
{
super(ref);
}
public VisitableClassContextRestrictedModifiableCompound(ClassContext ref, ClassVisitor cv)
{
super(ref, cv);
}
@Override
public void setSource(String source)
{
ref.setSource(source);
}
@Override
public void setDebug(String debug)
{
ref.setDebug(debug);
}
@Override
public void setSuperClass(String superClass)
{
ref.setSuperClass(superClass);
}
@Override
public void setInterfaces(String[] interfaces)
{
ref.setInterfaces(interfaces);
}
@Override
public void setEnclosingClass(String enclosingClass)
{
ref.setEnclosingClass(enclosingClass);
}
@Override
public void setEnclosingMethodName(String name)
{
ref.setEnclosingMethodName(name);
}
@Override
public void setEnclosingMethodDescriptor(String descriptor)
{
ref.setEnclosingMethodDescriptor(descriptor);
}
@Override
public void setVersion(int version)
{
ref.setVersion(version);
}
@Override
public void setModifier(int modifier)
{
ref.setModifier(modifier);
}
@Override
public void setSignature(String signature)
{
ref.setSignature(signature);
}
@Override
public void clearFields()
{
ref.clearFields();
}
@Override
public void removeField(String name)
{
ref.removeField(name);
}
@Override
public void clearMethods()
{
ref.clearMethods();
}
@Override
public void removeMethod(String fullDescriptor)
{
ref.removeMethod(fullDescriptor);
}
}
| true |
ae68dd5b805b3f3476e5ca027196a0a1a7de417e | Java | ZacharyMennona/Movie | /mennonaIMDB.java | UTF-8 | 4,866 | 3.25 | 3 | [] | no_license | import java.text.DecimalFormat;
class Movie
{
public String title;
public int year;
public String director;
public int duration;
public String actors;
public String genre;
public double rating;
Movie(String title, int year, String director,
int duration, String actors, String genre,
double rating) {
this.title = title;
this.year = year;
this.director = director;
this.duration = duration;
this.actors = actors;
this.genre = genre;
this.rating = rating;
}
}
public class mennonaIMDB extends Movie {
mennonaIMDB(String title, int year, String director, int duration, String actors, String genre, double rating) {
super(title, year, director, duration, actors, genre, rating);
}
public static void main(String[] args) {
Movie[] arr;
arr = new Movie[10];
arr[0] = new Movie("The Shawshank Redemption",
1994,
"Frank Darabont",
142,
"Timm Robbins, Morgan Freeman, and Bob Gunton",
"Drama",
Math.random()*10);
arr[1] = new Movie("The Godfather",
1972,
"Francis Coppola",
175,
"Marlon Brando, Al Pacino",
"Crime, Drama",
Math.random()*10);
arr[2] = new Movie("The Godfather: Part II",
1974,
"Francis Coppola",
202,
"Al Pacino, Robert De Niro, Robert Duvall",
"Crime, Drama",
Math.random()*10);
arr[3] = new Movie("The Dark Knight",
2008,
"Christopher Nolan",
152, "Christian Bale, Heath Ledger",
"Action, Crime, Drama",
Math.random()*10);
arr[4] = new Movie("12 Angry Men",
1957, "Sidney Lumet",
96, "Henry Fonda Lee, Lee J. Cobb, Martin Balsam",
"Crime, Drama",
Math.random()*10);
arr[5] = new Movie("Schindler's List",
1993,
"Steven Spielberg",
195,
"Liam Neeson, Ralph Fiennes",
"Biography, Drama",
Math.random()*10);
arr[6] = new Movie("The Lord of the Rings: The Return of the King",
2003,
"Peter Jackson",
201,
"Elijah Wood, Viggo Mortensen, Ian McKellen, Orlando Bloom",
"Adventure, Drama",
Math.random()*10);
arr[7] = new Movie("Pulp Fiction",
1994, "Guentin Taratino",
154,
"John Travolta, Uma Thurman, Samuel L. Jackson, Bruce Willis",
"Crime, Drama",
Math.random()*10);
arr[8] = new Movie("The Good, the Bad, and the Ugly",
191966,
"Sergio Leone",
178,
"Clint Eastwood",
"Western",
Math.random()*10);
arr[9] = new Movie("Fight Club",
1999,
"David Fincher",
175,
"Brad Pitt, Edward Norton",
"Drama",
Math.random()*10);
DecimalFormat df = new DecimalFormat("###.#");
for (Movie movie : arr) {
System.out.println("Title: '" + movie.title + "' || Rating: " + df.format(movie.rating));
}
double lowestRating = Math.min(Math.min(Math.min(Math.min(Math.min(Math.min(Math.min(Math.min(Math.min(arr[0].rating, arr[1].rating), arr[2].rating), arr[3].rating), arr[4].rating), arr[5].rating), arr[6].rating), arr[7].rating) , arr[8].rating), arr[9].rating);
double highestRating = Math.max(Math.max(Math.max(Math.max(Math.max(Math.max(Math.max(Math.max(Math.max(arr[0].rating, arr[1].rating), arr[2].rating), arr[3].rating), arr[4].rating), arr[5].rating), arr[6].rating), arr[7].rating) , arr[8].rating), arr[9].rating);
for (Movie movie : arr) {
if (movie.rating == (highestRating)) {
System.out.println("Highest Rated Movie: '" + movie.title + "' || Rating: " + df.format(movie.rating));
}
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
if (movie.rating == (lowestRating)) {
System.out.println("Lowest Rated Movie: '" + movie.title + "' || Rating: " + df.format(movie.rating));
}
}
}
}
| true |
6518e4ec92417c12dca47ece7a96809929f61a80 | Java | ZztPlus/teach_online_server | /src/com/zzt/servlet/adminner_operate_manager_delupdateServlet.java | UTF-8 | 3,872 | 2.53125 | 3 | [] | no_license | package com.zzt.servlet;
import com.zzt.jdbc.SqlConnection;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
/**
* @author 亲爱的子桐
*/
@WebServlet(name = "adminner_operate_manager_delupdateServlet",urlPatterns = "/adminner_operate_manager_delupdate")
public class adminner_operate_manager_delupdateServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置UTF-8格式,防止中文乱码
request.setCharacterEncoding("UTF-8");
response.setContentType("text/text;charset=utf-8");
response.setCharacterEncoding("UTF-8");
// 允许跨域请求
response.setHeader("Access-Control-Allow-Origin", "*");
PrintWriter writer = response.getWriter();
// 这是从前端获取的数据
String pname = request.getParameter("pname");
String ppassword = request.getParameter("ppw");
String plevel = request.getParameter("plevel");
String page = request.getParameter("page");
String psex = request.getParameter("psex");
String pphonenumber = request.getParameter("pphonenumber");
String pgonhao = request.getParameter("pgonhao");
System.out.println("pname:" + pname + " ppassward:" + ppassword + "plevel:" + plevel + "page" + page + " psex:" + psex + " pphonenumber:" + pphonenumber+ " pgonhao:" + pgonhao);
Connection connection = SqlConnection.getConnection();
try {
PreparedStatement preparedStatement = connection.prepareStatement("update manager set name=?,pw=?,level=?,age=?,sex=?,phonenumber=? where gonghao=?");
preparedStatement.setString(1, pname);
preparedStatement.setString(2, ppassword);
preparedStatement.setString(3, plevel);
preparedStatement.setString(4, page);
preparedStatement.setString(5, psex);
preparedStatement.setString(6, pphonenumber);
preparedStatement.setString(7, pgonhao);
preparedStatement.executeUpdate(); //插入用executeUpdate()
writer.print("教务员信息修改成功,请及时通知!");
return;
} catch (Exception e) {
e.printStackTrace();
}
writer.print("教务员信息修改失败!");
}
@Override
//删除教务员信息
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置UTF-8格式,防止中文乱码
request.setCharacterEncoding("UTF-8");
response.setContentType("text/text;charset=utf-8");
response.setCharacterEncoding("UTF-8");
// 允许跨域请求
response.setHeader("Access-Control-Allow-Origin", "*");
PrintWriter writer = response.getWriter();
// 这是从前端获取的数据
String pgonghao = request.getParameter("pgonghao");
System.out.println(" gonghao:" + pgonghao );
Connection connection = SqlConnection.getConnection();
try {
PreparedStatement preparedStatement = connection.prepareStatement("delete from manager where gonghao=? ");
preparedStatement.setString(1, pgonghao);
preparedStatement.executeUpdate(); //插入用executeUpdate()
writer.print("教务员已删除!");
return;
} catch (Exception e) {
e.printStackTrace();
}
writer.print("教务员教师失败!");
}
}
| true |
3eca20b038fc19f2d88b7ec7e9d0474ea01f194b | Java | firepho92/RandomNumbersIO | /src/randomnumersio/RandomNumbersOutput.java | UTF-8 | 1,543 | 3.28125 | 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 randomnumersio;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
/**
*
* @author alex
*/
public class RandomNumbersOutput {
int tamano;
public RandomNumbersOutput(){
}
public int getTamano() {
return tamano;
}
public void setTamano(int tamano) {
this.tamano = tamano;
}
public void generateRandomNumbersAndWrite(){
Random r = new Random();
int denominador = 0;
double result = 0.0;
try{
FileWriter fw = new FileWriter("NumerosAleatorios.txt");
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 0; i < this.tamano; i++){
try{
denominador = r.nextInt(10);
if(denominador == 0){
bw.write(0.0 + ",");
}else{
result = 8.0 / denominador;
bw.write(result + ",");
}
}catch(ArithmeticException e){
System.out.println("Error en la escritura");
}
}
bw.close();
}catch(IOException e){
System.out.println("Error no se puede dividir entre 0");
}
}
}
| true |
c705b13e296467d3fa6df2fdacc35b8186c26074 | Java | natiassefa/2048 | /2048/src/net/mygame/Tile.java | UTF-8 | 573 | 3.015625 | 3 | [] | no_license | package net.mygame;
public class Tile {
int value;
public Tile (){
value = 0;
}
public Tile (int val){
value = val;
}
public int getVal(){
return this.value;
}
public boolean isEmpty(){
if(this.getVal()==0){
return true;
}
else
return false;
}
public void setVal(int val){
this.value = val;
}
public String toString(){
if(this.getVal()==0){
return "_";
}
else
return Integer.toString(this.getVal());
}
public Tile clone(){
Tile tile = new Tile(this.getVal());
return tile;
}
}
| true |
fbbf0de60f554d43eeb689b62eab8ab2b6572db2 | Java | xp-zhao/learn-java | /learn-test/src/main/java/com/xp/thread/FutrueDemo/FutrueExample.java | UTF-8 | 1,696 | 2.984375 | 3 | [
"MIT"
] | permissive | package com.xp.thread.FutrueDemo;
import com.xp.utils.FileUtils;
import java.io.File;
import java.util.concurrent.*;
/**
* Created by xp-zhao on 2018/9/7.
*/
public class FutrueExample
{
public static void main(String[] args) throws InterruptedException, ExecutionException
{
deleteFile();
// long startTime = System.currentTimeMillis();
// ExecutorService service = Executors.newFixedThreadPool(1);
// // 第一步上传歌单文件
// Callable<Boolean> playlist = new PlayList();
// FutureTask<Boolean> task = new FutureTask<>(playlist);
// service.submit(task);
// service.shutdown();
//// new Thread(task).start();
// TimeUnit.SECONDS.sleep(2); // 模拟生成歌曲文件的时间
// System.out.println("第二步:歌曲文件生成成功");
// if(!task.isDone())
// {
// System.out.println("第二步:歌单文件未上传结束");
// }
// if(task.get())
// {
// System.out.println("第二步:上传歌曲文件");
// }
// long endTime = System.currentTimeMillis();
// System.out.println("总共耗时:"+(endTime - startTime) / 1000 + " s");
}
// 歌单文件处理线程
static class PlayList implements Callable<Boolean>{
private boolean isEnd = false;
@Override public Boolean call() throws Exception
{
System.out.println("第一步:开始上传歌单文件");
try
{
TimeUnit.SECONDS.sleep(5); // 模拟处理时间
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("第一步:上传歌单文件结束");
isEnd = true;
return isEnd;
}
}
public static void deleteFile(){
File file = new File("D:\\home\\liujf\\playlistinfo");
FileUtils.deleteFile(file);
}
}
| true |
dad8a6781e8388ccd15cd418b74ba24be410f7f7 | Java | zhuyu126/SortAlgorithm | /09-LSDSort/LSDSortMain.java | UTF-8 | 512 | 2.890625 | 3 | [
"MIT"
] | permissive | import java.util.Arrays;
public class LSDSortMain {
public static void main(String[] args) {
// int n = 100000, w = 200;
int n = 1000000, w = 2;
String[] arr = ArrayGenerator.generateRandomStringArray(n, w);
String[] arr2 = Arrays.copyOf(arr, arr.length);
String[] arr3 = Arrays.copyOf(arr, arr.length);
SortingHelper.sortTest("QuickSort", arr);
SortingHelper.sortTest("LSDSort", arr2);
SortingHelper.sortTest("QuickSort3Ways", arr3);
}
}
| true |
253cf621fe1db145f80da7661142950ab64c69a9 | Java | regwhitton/dynamator | /container-support/src/main/java/component/util/ComponentsImpl.java | UTF-8 | 1,847 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | package component.util;
import static util.Verify.argNotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import component.Components;
import provider.Commissioner;
import provider.Decommissioner;
import provider.Provider;
class ComponentsImpl implements Components {
private final Map<Class<?>, Component<?>> components = new HashMap<>();
private final List<Component<?>> initialised = new ArrayList<>();
@Override
public <T> T get(Class<T> type) {
@SuppressWarnings("unchecked")
Component<T> component = (Component<T>) components.get(type);
if (component == null) {
throw new IllegalStateException("no instance found for " + type.getClass().getName());
}
return component.instance;
}
@Override
public void commission() throws Exception {
for (Component<?> component : components.values()) {
component.commissioner.commission();
initialised.add(component);
}
}
@Override
public void decommission() {
for (Component<?> component : initialised) {
component.decommissioner.decommission();
}
}
<T> void add(Class<T> type, Provider<T> provider) {
argNotNull(type);
T instance = provider.get();
components.put(type,
new Component<T>(instance, provider.getCommissioner(instance), provider.getDecommissioner(instance)));
}
boolean contains(Class<?> type) {
return components.containsKey(type);
}
private static class Component<T> {
final T instance;
final Commissioner commissioner;
final Decommissioner decommissioner;
Component(T instance, Commissioner commissioner, Decommissioner decommissioner) {
this.instance = argNotNull(instance);
this.commissioner = argNotNull(commissioner);
this.decommissioner = argNotNull(decommissioner);
}
}
}
| true |