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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
e275cfbc964cbf6d77540908d6fbabd0e33d19dd | Java | P3dr4o/PI---OcorrenciaDePonto | /OcorrenciaDePonto/src/Conexao/ConexaoBD.java | UTF-8 | 1,859 | 3.078125 | 3 | [] | no_license | package Conexao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
public class ConexaoBD {
private static Connection con = null;
private ConexaoBD() {}
//Metodo para iniciar/pegar conexão com banco de dados
public static Connection getConnection() {
try {
if(con == null) {
//Driver do mysql
Class.forName("com.mysql.jdbc.Driver");
//Caminho/usuario/senha do banco de dados
con = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "");
//JOptionPane.showMessageDialog(null, "Conectado ao banco de dados");
}
}
catch(SQLException e) {
JOptionPane.showMessageDialog(null, "Erro de conexão com o banco", "Erro", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
catch(ClassNotFoundException e) {
System.err.println("Erro: Drive do Banco n�o encontrado");
System.exit(1);
}
return con;
}
//Metodos para desconectar connection/statement/resultset
public static void desconectar(Connection con) {
try {
con.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro: "+ex);
}
}
public static void desconectar(Connection con, Statement stmt) {
try {
stmt.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro: "+ex);
}
desconectar(con);
}
public static void desconectar(Connection con, Statement stmt, ResultSet rs) {
try {
rs.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro: "+ex);
}
desconectar(con, stmt);
}
}
| true |
b5c2189f9e663e6fdd374c6d6287c4a577d7c26c | Java | hausbence/mockaroo | /src/main/java/com/worldofbooks/mockaroo/entity/Location.java | UTF-8 | 892 | 2.21875 | 2 | [] | no_license | package com.worldofbooks.mockaroo.entity;
import com.sun.istack.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.UUID;
@AllArgsConstructor
@Builder
@Data
@NoArgsConstructor
@Entity
@Table(name = "location")
public class Location {
@Id
@NotNull
private UUID id;
@Column(columnDefinition = "text")
private String manager_name;
@Column(columnDefinition = "text")
private String phone;
@Column(columnDefinition = "text")
private String address_primary;
@Column(columnDefinition = "text")
private String address_secondary;
@Column(columnDefinition = "text")
private String country;
@Column(columnDefinition = "text")
private String town;
@Column(columnDefinition = "text")
private String postal_code;
}
| true |
1aef8bab59822aac13d29875f9dbe0f9e83c7158 | Java | qlxrcy/MyProject | /src/main/java/com/springboot/core/repository/UserInfoRepository.java | UTF-8 | 386 | 2.015625 | 2 | [] | no_license | package com.springboot.core.repository;
import com.springboot.core.bean.UserInfo;
import org.springframework.data.repository.CrudRepository;
/**
* UserInfo持久化类;
* Created by le.qi on 10/17/2016.
*/
public interface UserInfoRepository extends CrudRepository<UserInfo,Long> {
/**通过username查找用户信息;*/
public UserInfo findByUsername(String username);
}
| true |
9d36e629b6c2f7f5ce88e4377ef089a956205093 | Java | birkhoffcheng/apcsa | /CarV5.java | UTF-8 | 2,161 | 3.875 | 4 | [] | no_license | /*
Purpose: Calculate some stats about a car's gas consumption
Author: BIrkhoff Cheng
Version: 0.0.1
PMR: At first I set the private instance (or variable?) the same name as the constructor parameters. So it didn't work. But after I read the example code, I realized and removed the 1's in the end.
And I almost missed a bracket after a function ends. Carefulness needed.
*/
public class CarV5
{
//private instance variables
private int endMiles, startMiles;
private double gallonsUsed, pricePerGallon;
private String carType;
//default constructor
CarV5()
{
}
//constructor with parameters
CarV5 (String carType1, int endMiles1, int startMiles1, double gallonsUsed1, double pricePerGallon1)
{
carType = carType1;
endMiles = endMiles1;
startMiles = startMiles1;
gallonsUsed = gallonsUsed1;
pricePerGallon = pricePerGallon1;
}
public int calcDistance()
{
return endMiles - startMiles;
}
public double calcGPM(int dist)
{
return gallonsUsed / (double)dist;
}
public double calcMPG(int dist)
{
return (double)dist / gallonsUsed;
}
public double totalCost()
{
return gallonsUsed * pricePerGallon;
}
public void printCarType()
{
System.out.printf("%s", carType);
}
public static void main (String[] args)
{
//declaration and initialization
int startMiles1 = 20015, endMiles1 = 20098;
double gallonsUsed1 = 5.35, pricePerGallon1 = 2.99;
String carType1 = "Peugeot 307";
CarV5 car1 = new CarV5(carType1, endMiles1, startMiles1, gallonsUsed1, pricePerGallon1);
//calculation
int distance1 = car1.calcDistance();
double gpm1 = car1.calcGPM(distance1);
double mpg1 = car1.calcMPG(distance1);
double ttlCost = car1.totalCost();
//output
System.out.printf("\t\tGas Mileage Calculations\n");
System.out.printf("Type of Car\tStart Miles\tEnd Miles\tDistance\tGallons\t\tPrice\t\tCost\t\tMiles/Gal\tGal/Mile\n");
for (int i = 0; i < 150; i++) {
System.out.printf("=");
}
System.out.printf("\n");
car1.printCarType();
System.out.printf("\t%d\t\t%d\t\t%d\t\t%f\t%f\t%f\t%f\t%f\n", startMiles1, endMiles1, distance1, gallonsUsed1, pricePerGallon1, ttlCost, mpg1, gpm1);
}
}
| true |
a5430efbd70c042a252c18216ade730f16cc262e | Java | liuendy/escommons | /api/rest-boot/src/main/java/org/biacode/escommons/api/rest/setup/EsCommonsController.java | UTF-8 | 4,578 | 2.046875 | 2 | [
"MIT"
] | permissive | package org.biacode.escommons.api.rest.setup;
import org.biacode.escommons.api.model.common.EsCommonsRequest;
import org.biacode.escommons.api.model.common.EsCommonsResultResponse;
import org.biacode.escommons.api.model.setup.request.ChangeIndexAliasRequest;
import org.biacode.escommons.api.model.setup.request.PrepareIndexRequest;
import org.biacode.escommons.api.model.setup.request.RemoveIndexByNameRequest;
import org.biacode.escommons.api.model.setup.response.ChangeIndexAliasResponse;
import org.biacode.escommons.api.model.setup.response.PrepareIndexResponse;
import org.biacode.escommons.api.model.setup.response.RemoveIndexByNameResponse;
import org.biacode.escommons.core.component.IndexingComponent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
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 javax.ws.rs.core.MediaType;
/**
* Created by Arthur Asatryan.
* Date: 7/18/17
* Time: 5:38 PM
*/
@RestController
@RequestMapping(path = "escommons")
public class EsCommonsController {
private static final Logger LOGGER = LoggerFactory.getLogger(EsCommonsController.class);
//region Dependencies
@Autowired
private IndexingComponent indexingComponent;
//endregion
//region Constructors
public EsCommonsController() {
LOGGER.debug("Initializing");
}
//endregion
//region Public methods
@RequestMapping(path = "prepare-index", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON)
public ResponseEntity<EsCommonsResultResponse<PrepareIndexResponse>> prepareIndex(@RequestBody final PrepareIndexRequest request) {
assertPrepareIndexRequest(request);
final String newIndexName = indexingComponent.createIndexAndSetupMappings(request.getAlias(), request.getTypes(), request.getSettings());
return ResponseEntity.ok(new EsCommonsResultResponse<>(new PrepareIndexResponse(newIndexName)));
}
@RequestMapping(path = "change-alias", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON)
public ResponseEntity<EsCommonsResultResponse<ChangeIndexAliasResponse>> changeAlias(@RequestBody final ChangeIndexAliasRequest request) {
assertChangeIndexAliasRequest(request);
indexingComponent.addAlias(request.getAlias(), request.getIndexName());
return ResponseEntity.ok(new EsCommonsResultResponse<>());
}
@RequestMapping(path = "remove-index-by-name", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON)
public ResponseEntity<EsCommonsResultResponse<RemoveIndexByNameResponse>> removeIndexByName(@RequestBody final RemoveIndexByNameRequest request) {
assertRemoveIndexByNameRequest(request);
indexingComponent.removeIndexByName(request.getIndexName());
return ResponseEntity.ok(new EsCommonsResultResponse<>());
}
@RequestMapping(path = "heartbeat")
public ResponseEntity<String> heartbeat() {
return ResponseEntity.ok("OK");
}
//endregion
//region Utility methods
private void assertPrepareIndexRequest(final PrepareIndexRequest request) {
assertRequest(request);
assertAliasNotNull(request.getAlias());
Assert.notNull(request.getTypes(), "The list of document types should not be null");
}
private void assertChangeIndexAliasRequest(final ChangeIndexAliasRequest request) {
assertRequest(request);
assertAliasNotNull(request.getAlias());
assertIndexNameNotNull(request.getIndexName());
}
private void assertRemoveIndexByNameRequest(final RemoveIndexByNameRequest request) {
assertRequest(request);
assertIndexNameNotNull(request.getIndexName());
}
private void assertRequest(final EsCommonsRequest request) {
Assert.notNull(request, "The request should not be null");
}
private void assertIndexNameNotNull(final String indexName) {
Assert.notNull(indexName, "The index name should not be null");
}
private void assertAliasNotNull(final String alias) {
Assert.notNull(alias, "The alias should not be null");
}
//endregion
}
| true |
a36d94c47039a991e267de7afda4c05d6fa7c0e0 | Java | YannickMontes/RPG-Polytech | /src/com/corentin_yannick/RPG_Polytech/Actions/Action.java | UTF-8 | 28,495 | 2.6875 | 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 com.corentin_yannick.RPG_Polytech.Actions;
import com.corentin_yannick.RPG_Polytech.Controllers.ConsoleDesign;
import com.corentin_yannick.RPG_Polytech.Controllers.Controller;
import com.corentin_yannick.RPG_Polytech.Entities.Athlete;
import com.corentin_yannick.RPG_Polytech.Entities.Attribute;
import com.corentin_yannick.RPG_Polytech.Items.Armor;
import com.corentin_yannick.RPG_Polytech.Items.StuffItem;
import com.corentin_yannick.RPG_Polytech.Items.UseableItem;
import com.corentin_yannick.RPG_Polytech.Items.Weapon;
import com.corentin_yannick.RPG_Polytech.Manager.Team;
import com.corentin_yannick.RPG_Polytech.Entities.Character;
import com.corentin_yannick.RPG_Polytech.Entities.Thief;
import com.corentin_yannick.RPG_Polytech.Entities.Warrior;
import com.corentin_yannick.RPG_Polytech.Manager.Turn;
import static com.corentin_yannick.RPG_Polytech.Controllers.ConsoleDesign.RED;
import com.corentin_yannick.RPG_Polytech.Items.Item;
/**
*
* @author coren
*/
public class Action {
public Character character;
public Team opponentsTeam;
public Turn currentTurn;
public String message;
public Action(Character character, Team opponentsTeam, Turn currentTurn) {
this.character = character;
this.opponentsTeam = opponentsTeam;
this.currentTurn = currentTurn;
this.message = "";
}
public String makeAutoAttack() {
Character opponent = null;
do
{
int opponentNumber = 0;
int probaOpponent = (int) (Math.random() * (opponentsTeam.getCharacters().size() * 100));
opponentNumber = probaOpponent / 100;
opponent = opponentsTeam.getCharacters().get(opponentNumber);
}while(!opponent.isAlive());
boolean success = verifySuccess("attack");
int damages = 0;
if (success == true) {
damages = measureImpact("attack", opponent, null);
if (character instanceof Warrior) {
((Warrior) character).strikeABlow(opponent, damages);
} else if (character instanceof Athlete) {
((Athlete) character).strikeABlow(opponent, damages);
} else if (character instanceof Thief) {
((Thief) character).strikeABlow(opponent, damages);
}
}
return attackResult(success, opponent, damages);
}
/* public String makeAutoUseObject() {
UseableItem useableItem = character.getInInventoryItemOfType(UseableItem.class, );
boolean success = verifySuccess("useItem");
int upValue = 0;
if (success == true) {
if (character instanceof Warrior) {
if (((Warrior) character).getInventory().contains(useableItem)) {
upValue = measureImpact("useItem", null, useableItem);
if (((Warrior) character).useItem(useableItem, upValue) == false) {
System.out.println(ConsoleDesign.text("Vous ne possédez pas cette capacité !", RED));
return false;
}
} else {
System.out.println(ConsoleDesign.text("Vous ne possédez pas cette objet !", RED));
return false;
}
} else if (character instanceof Athlete) {
if (((Warrior) character).getInventory().contains(useableItem)) {
upValue = measureImpact("useItem", null, useableItem);
if (((Warrior) character).useItem(useableItem, upValue) == false) {
System.out.println(ConsoleDesign.text("Vous ne possédez pas cette capacité !", RED));
return false;
}
} else {
System.out.println(ConsoleDesign.text("Vous ne possédez pas cette objet !", RED));
return false;
}
} else if (character instanceof Thief) {
if (((Warrior) character).getInventory().contains(useableItem)) {
upValue = measureImpact("useItem", null, useableItem);
if (((Warrior) character).useItem(useableItem, upValue) == false) {
System.out.println(ConsoleDesign.text("Vous ne possédez pas cette capacité !", RED));
return false;
}
} else {
System.out.println(ConsoleDesign.text("Vous ne possédez pas cette objet !", RED));
return false;
}
}
}
System.out.println(ConsoleDesign.text(careResult(success, useableItem), RED));
currentTurn.turnOf(character, true);
}
*/
public String makeAutoDefense() {
int blockNumber = (int) (1 + Math.random());
if (character instanceof Warrior) {
switch (blockNumber) {
case 1:
boolean success = verifySuccess("block");
int upBlock = 0;
if (success == true) {
upBlock = measureImpact("block", null, null);
((Warrior) character).block(upBlock);
}
return blockResult(success, upBlock);
case 2:
boolean successD = verifySuccess("dodge");
int upDodge = 0;
if (successD == true) {
upDodge = measureImpact("dodge", null, null);
((Warrior) character).dodge(upDodge);
}
return dodgeResult(successD, upDodge);
}
} else if (character instanceof Athlete) {
switch (blockNumber) {
case 1:
boolean success = verifySuccess("block");
int upBlock = 0;
if (success == true) {
upBlock = measureImpact("block", null, null);
((Athlete) character).block(upBlock);
}
return blockResult(success, upBlock);
case 2:
boolean successD = verifySuccess("dodge");
int upDodge = 0;
if (successD == true) {
upDodge = measureImpact("dodge", null, null);
((Athlete) character).dodge(upDodge);
}
return dodgeResult(successD, upDodge);
}
} else if (character instanceof Thief) {
switch (blockNumber) {
case 1:
boolean success = verifySuccess("block");
int upBlock = 0;
if (success == true) {
upBlock = measureImpact("block", null, null);
((Thief) character).block(upBlock);
}
return blockResult(success, upBlock);
case 2:
boolean successD = verifySuccess("dodge");
int upDodge = 0;
if (successD == true) {
upDodge = measureImpact("dodge", null, null);
((Thief) character).dodge(upDodge);
}
return dodgeResult(successD, upDodge);
}
}
return "";
}
public boolean makeAttack() {
Character opponent = null;
String actionText = ConsoleDesign.textDashArrow("Choississez un adversaire", RED) + "\n";
int num = 0;
for (Character op : opponentsTeam.getCharacters()) {
if (op.isAlive()) {
actionText += ConsoleDesign.text(Integer.toString(num) + " -> " + op.getName(), RED) +" (Santé:"+op.getAttributeValue(Attribute.HEALTH) + ")\n";
}
num++;
}
int opponentNumber;
do {
opponentNumber = Controller.askNumberBetween(actionText, 0, num - 1);
} while (!opponentsTeam.getCharacters().get(opponentNumber).isAlive());
opponent = opponentsTeam.getCharacters().get(opponentNumber);
boolean success = verifySuccess("attack");
int damages = 0;
if (success == true) {
damages = measureImpact("attack", opponent, null);
if (character instanceof Warrior) {
if (((Warrior) character).strikeABlow(opponent, damages) == false) {
System.out.println("Vous ne possédez pas cette capacité !");
return false;
}
} else if (character instanceof Athlete) {
if (((Athlete) character).strikeABlow(opponent, damages) == false) {
System.out.println("Vous ne possédez pas cette capacité !");
return false;
}
} else if (character instanceof Thief) {
if (((Thief) character).strikeABlow(opponent, damages) == false) {
System.out.println("Vous ne possédez pas cette capacité !");
return false;
}
}
}
System.out.println(attackResult(success, opponent, damages));
return true;
}
public boolean makeDefense() {
String text = ConsoleDesign.textDashArrow("Quelle parade voulez-vous utiliser ?", RED) + " \n";
text += ConsoleDesign.text("1 -> Blocage", RED) + "\n";
text += ConsoleDesign.text("2 -> Esquive", RED) + "\n";
int blockNumber = Controller.askNumberBetween(text, 1, 2);
if (character instanceof Warrior) {
switch (blockNumber) {
case 1:
boolean success = verifySuccess("block");
int upBlock = 0;
if (success == true) {
upBlock = measureImpact("block", null, null);
if (((Warrior) character).block(upBlock) == false) {
System.out.println(ConsoleDesign.text("Vous ne possédez pas cette capacité !", RED));
return false;
}
}
System.out.println(ConsoleDesign.text(blockResult(success, upBlock), RED));
break;
case 2:
boolean successD = verifySuccess("dodge");
int upDodge = 0;
if (successD == true) {
upDodge = measureImpact("dodge", null, null);
if (((Warrior) character).dodge(upDodge) == false) {
System.out.println(ConsoleDesign.text("Vous ne possédez pas cette capacité !", RED));
return false;
}
}
System.out.println(ConsoleDesign.text(dodgeResult(successD, upDodge), RED));
break;
}
} else if (character instanceof Athlete) {
switch (blockNumber) {
case 1:
boolean success = verifySuccess("block");
int upBlock = 0;
if (success == true) {
upBlock = measureImpact("block", null, null);
if (((Athlete) character).block(upBlock) == false) {
System.out.println(ConsoleDesign.text("Vous ne possédez pas cette capacité !", RED));
return false;
}
}
System.out.println(ConsoleDesign.text(blockResult(success, upBlock), RED));
break;
case 2:
boolean successD = verifySuccess("dodge");
int upDodge = 0;
if (successD == true) {
upDodge = measureImpact("dodge", null, null);
if (((Athlete) character).dodge(upDodge) == false) {
System.out.println(ConsoleDesign.text("Vous ne possédez pas cette capacité !", RED));
return false;
}
}
System.out.println(ConsoleDesign.text(dodgeResult(successD, upDodge), RED));
break;
}
} else if (character instanceof Thief) {
switch (blockNumber) {
case 1:
boolean success = verifySuccess("block");
int upBlock = 0;
if (success == true) {
upBlock = measureImpact("block", null, null);
if (((Thief) character).block(upBlock) == false) {
System.out.println(ConsoleDesign.text("Vous ne possédez pas cette capacité !", RED));
return false;
}
}
System.out.println(ConsoleDesign.text(blockResult(success, upBlock), RED));
break;
case 2:
boolean successD = verifySuccess("dodge");
int upDodge = 0;
if (successD == true) {
upDodge = measureImpact("dodge", null, null);
if (((Thief) character).dodge(upDodge) == false) {
System.out.println(ConsoleDesign.text("Vous ne possédez pas cette capacité !", RED));
return false;
}
}
System.out.println(ConsoleDesign.text(dodgeResult(successD, upDodge), RED));
break;
}
}
return true;
}
public boolean useObject() {
UseableItem useableItem = null;
if (character.getNumberUseableItem()> 0) {
String careText = ConsoleDesign.textDashArrow("Quel item voulez-vous utiliser ?[0->Retour]", RED);
System.out.println(character.getUseableItemsToString());
int useableNumber = Controller.askNumberBetween(careText, 0, character.getNumberUseableItem());
useableItem = (UseableItem)character.getInInventoryItemOfType(UseableItem.class, useableNumber);
}else{
System.out.println(ConsoleDesign.text("Vous ne possédez d'objet utilisatbles !", RED));
return false;
}
boolean success = verifySuccess("useItem");
int upValue = 0;
if (success == true) {
if (character instanceof Warrior) {
if (((Warrior) character).inventoryContains(useableItem)) {
upValue = measureImpact("useItem", null, useableItem);
if (((Warrior) character).useItem(useableItem, upValue) == false) {
System.out.println(ConsoleDesign.text("Vous ne possédez pas cette capacité !", RED));
return false;
}
} else {
System.out.println(ConsoleDesign.text("Vous ne possédez pas cette objet !", RED));
return false;
}
} else if (character instanceof Athlete) {
if (((Athlete) character).inventoryContains(useableItem)) {
upValue = measureImpact("useItem", null, useableItem);
if (((Athlete) character).useItem(useableItem, upValue) == false) {
System.out.println(ConsoleDesign.text("Vous ne possédez pas cette capacité !", RED));
return false;
}
} else {
System.out.println(ConsoleDesign.text("Vous ne possédez pas cette objet !", RED));
return false;
}
} else if (character instanceof Thief) {
if (((Thief) character).inventoryContains(useableItem)) {
upValue = measureImpact("useItem", null, useableItem);
if (((Thief) character).useItem(useableItem, upValue) == false) {
System.out.println(ConsoleDesign.text("Vous ne possédez pas cette capacité !", RED));
return false;
}
} else {
System.out.println(ConsoleDesign.text("Vous ne possédez pas cette objet !", RED));
return false;
}
}
}
System.out.println(ConsoleDesign.text(careResult(success, useableItem), RED));
currentTurn.turnOf(character, true);
return true;
}
public boolean useCapacity()
{
Character opponent = null;
String actionText = ConsoleDesign.textDashArrow("Choississez un adversaire", RED) + "\n";
int num = 0;
for (Character op : opponentsTeam.getCharacters()) {
if (op.isAlive()) {
actionText += ConsoleDesign.text(Integer.toString(num) + " -> " + op.getName(), RED) + "\n";
}
num++;
}
int opponentNumber;
do {
opponentNumber = Controller.askNumberBetween(actionText, 0, num - 1);
} while (!opponentsTeam.getCharacters().get(opponentNumber).isAlive());
opponent = opponentsTeam.getCharacters().get(opponentNumber);
String result = this.verifySuccesCapacity(opponent);
if(result.equals(""))
{
int damages = measureImpact("capacity", opponent, null);
opponent.takeABlow(damages);
this.message += this.capacityResult(opponent, damages);
}
else
{
this.message += result;
if(result.equals("Vous n'avez pas assez de mana"))
{
System.out.println(this.message);
return false;
}
}
System.out.println(ConsoleDesign.text(this.message, RED));
return true;
}
/**
* Fonction permettant d'utiliser une capacité.
*
* @param capacity La capacité a utiliser.
* @return Vrai si la capacité à fonctionnée, faux sinon.
*/
public boolean verifySuccess(String capacity) {
//selon la capacitié utilisée: selon ses caractéristiques et son arme (s'il en a)
//calcule de proba
float probability = 0;
if ("attack".equals(capacity)) {
float mania = 1;
StuffItem weapon = character.getEquipment(Weapon.class);
mania = weapon.getHandlingAbility() / 100;
probability = mania;
probability += 2 * (1 - mania) * (character.getAttributeValue(Attribute.DEXTERITY) * 0.004);
//System.out.println("Probabilité d'attaquer: " + probability);
} else if ("block".equals(capacity)) {
//probability = this.attributes.get(Attribute.DEFENSE);
StuffItem armor = character.getEquipment(Armor.class);
probability += (float) (((Armor) armor).getHandlingAbility() / 100) * 0.2; // entre 0 et 100
probability += (float) ((float)character.getAttributeValue(Attribute.DEFENSE) / 100)/* * (1 - (0.2 * this.getEquipment(Armor.class).size()))*/;
} else if ("dodge".equals(capacity)) {
probability -= character.getTotalWeightEquipment()/50;
probability += (float) ((float)character.getAttributeValue(Attribute.SPEED) / 100)/* * (1 - (0.2 * this.getEquipment().size()))*/;
} else if ("useItem".equals(capacity)) {
probability = 1;
}
if (probability > 1) {
probability = 1;
} else if (probability < 0) {
probability = 0;
}
int rand = (int) (Math.random() * (100));
if (rand <= (probability * 100)) {
return true;
}
return false;
}
/**
*
* @param capacity
* @param opponent
* @param useableItem
* @return
*/
public int measureImpact(String capacity, Character opponent, UseableItem useableItem) {
if ("attack".equals(capacity) && opponent != null) {
return this.reduceDamages(opponent, (int) (character.getAttributeValue(Attribute.STRENGTH)*1.5f));
} else if ("block".equals(capacity)) {
return (int) (0.5 * character.getAttributeValue(Attribute.STRENGTH));
} else if ("useItem".equals(capacity) && useableItem != null) {
return useableItem.getValue();
} else if("capacity".equals(capacity))
{
return this.calculateDamageCapacity(opponent);
}
return 0;
}
private int reduceDamages(Character opponent, int initialValue) {
int defenseOpponent = opponent.getAttributeValue(Attribute.DEFENSE);
int damage = 0;
float reduction;
if (defenseOpponent <= 50) {
reduction = (float) (defenseOpponent * 0.01f);
} else if (defenseOpponent <= 100) {
reduction = (float) (0.5f + (defenseOpponent - 50) * 0.005f);
} else if (defenseOpponent <= 200) {
reduction = (float) (0.75f + (defenseOpponent - 100) * 0.00149925f);
} else {
reduction = 0.9f;
}
damage = (int) (initialValue * (1 - reduction));
return damage;
}
/**
* Fonction permettant de vérifier si l'attaque à fonctionner.
*
* @param success Réussite de l'attaque
* @param opponent Cible
* @param damages Dommages à infliger
* @return Le texte à afficher.
*/
public String attackResult(boolean success, Character opponent, int damages) {
String text;
if (success == true) {
text = "(" + character.getName() + ") Attaque " + opponent.getName() + " avec une attaque de base, provoquant " + damages
+ " points de dégats. (Santé: " + opponent.getAttributeValue(Attribute.HEALTH) + ")";
if (!opponent.isAlive()) {
text += "\nLe personnage " + opponent.getName() + " est mort!";
}
return text;
}
return "(" + character.getName() + ") L'attaque sur " + opponent.getName() + " a échoué.";
}
/**
* Fonction permettant de vérifier la réussite du soin
*
* @param success Réussite du soin
* @param item Item à utiliser
* @return Le texte à afficher
*/
public String careResult(boolean success, UseableItem item) {
String text;
if (success == true) {
if (item.getAttributeBonus() == Attribute.HEALTH) {
text = "(" + character.getName() + ") Se soigne de " + item.getValue() + ".";
} else {
text = "(" + character.getName() + ") Augmente de " + item.getValue() + " son attribut de " + item.getAttributeBonus() + " pour le tour actuel.";
}
return text;
}
return "(" + character.getName() + ") L'utilisation d'item a échoué.";
}
/**
* Fonction permettant de vérifier la réussite du block
*
* @param success Réussite
* @param blockValue valeur du block
* @return Le texte à afficher
*/
public String blockResult(boolean success, int blockValue) {
if (success == true) {
return "(" + character.getName() + ") Bloque les attaques pour le prochain coup. Défense augmentée de " + blockValue
+ ". (Défense: " + character.getAttributeValue(Attribute.DEFENSE) + ")";
}
return "(" + character.getName() + ") Bloquage échoué.";
}
/**
* Fonction permettant de vérifier la réussite de l'esquive.
*
* @param success Réussite de l'esquive
* @param blockValue valeur de l'esquive (?)
* @return Le texte ç afficher
*/
public String dodgeResult(boolean success, int blockValue) {
if (success == true) {
return "(" + character.getName() + ") Esquive les attaques le prochain tour.";
}
return "L'esquive a échoué";
}
public String capacityResult(Character opponent, int damages)
{
String text = "";
if(character instanceof Warrior)
{
text += "(" + character.getName() + ") Frappe "+opponent.getName()+" avec Anger, infligeant "+damages+" points de dégâts (Santé: "+opponent.getAttributeValue(Attribute.HEALTH)+")";
}
else if(character instanceof Athlete)
{
text += "(" + character.getName() + ") Frappe "+opponent.getName()+" avec Uppercut, ignorant ainsi la défense de l'adversaire et infligeant "+damages+" points de dégâts (Santé: "+opponent.getAttributeValue(Attribute.HEALTH)+")";
}
else if(character instanceof Thief)
{
text += "(" + character.getName() + ") Frappe "+opponent.getName()+" avec Pickpocket, infligeant "+damages+" points de dégâts (Santé: "+opponent.getAttributeValue(Attribute.HEALTH)+")";
}
if (!opponent.isAlive())
{
text += "\nLe personnage " + opponent.getName() + " est mort!";
}
return text;
}
private String verifySuccesCapacity(Character opponent)
{
if(character instanceof Warrior)
{
return ((Warrior)character).anger(opponent);
}
else if(character instanceof Athlete)
{
return ((Athlete)character).uppercut(opponent);
}
else if(character instanceof Thief)
{
return ((Thief)character).pickpocket(opponent);
}
return "Problème";
}
private int calculateDamageCapacity(Character opponent)
{
if(character instanceof Warrior)
{
this.character.decreaseAttribute(Attribute.MANA, 25);
int basedmg = 40+(5*this.character.getLevel());
float ratio = 0.8f;
int finaldamage = (int) (basedmg + ratio*this.character.getAttributeValue(Attribute.STRENGTH));
return this.reduceDamages(opponent, finaldamage);
}
else if(character instanceof Athlete)
{
this.character.decreaseAttribute(Attribute.MANA, 15);
int basedmg = 25+(5*this.character.getLevel());
float ratio = 0.5f;
int finaldamage = (int) (basedmg + ratio*this.character.getAttributeValue(Attribute.STRENGTH));
return finaldamage;
}
else if(character instanceof Thief)
{
this.character.decreaseAttribute(Attribute.MANA, 10);
int basedmg = 15+(5*this.character.getLevel());
float ratioVit = 2f;
float ratioAtt = 0.2f;
int finaldamage = (int) (basedmg + ratioAtt*this.character.getAttributeValue(Attribute.STRENGTH) + ratioVit*this.character.getAttributeValue(Attribute.SPEED));
int nbItems = opponent.getNbItemsInInventory();
if(nbItems!=0)
{
Item item = opponent.getItem((int) (Math.random()*nbItems));
if(this.character.addInventory(item))
{
opponent.removeItemInInventory(item);
}
this.message += "(" + character.getName() + ") vole l'item suivant:\n"+item.toString();
}
else
{
this.message += "\nVotre ennemi n'as pas d'item à piller.\n";
}
return this.reduceDamages(opponent, finaldamage);
}
return 0;
}
}
| true |
f8e6b109b12f46a7553638f8a5840cd769abcd46 | Java | honeybee-hive/bus-admin | /bus-modules/bus-upms-service/src/main/java/com/github/bus/upms/configure/Swagger2Config.java | UTF-8 | 1,308 | 2.15625 | 2 | [
"MIT"
] | permissive | package com.github.bus.upms.configure;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* 接口测试配置
*
* @author zcq
* @date 2018/10/21 14:03
*/
@Configuration
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// 配置扫描的包的路径
.apis(RequestHandlerSelectors.basePackage("com.github.bus.upms.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger2接口文档")
.description("可以直接在改文档中进行http请求的测试,如果异常请优先使用该工具测试接口")
.version("1.0")
.build();
}
}
| true |
bf83ab147a13acf37fb41d635076dcb3f6c59de5 | Java | basaigh/temp | /net/minecraft/client/renderer/entity/WolfRenderer.java | UTF-8 | 2,051 | 2.5 | 2 | [] | no_license | package net.minecraft.client.renderer.entity;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.Mob;
import com.mojang.blaze3d.platform.GlStateManager;
import net.minecraft.client.renderer.entity.layers.RenderLayer;
import net.minecraft.client.renderer.entity.layers.WolfCollarLayer;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.client.model.WolfModel;
import net.minecraft.world.entity.animal.Wolf;
public class WolfRenderer extends MobRenderer<Wolf, WolfModel<Wolf>> {
private static final ResourceLocation WOLF_LOCATION;
private static final ResourceLocation WOLF_TAME_LOCATION;
private static final ResourceLocation WOLF_ANGRY_LOCATION;
public WolfRenderer(final EntityRenderDispatcher dsa) {
super(dsa, new WolfModel(), 0.5f);
this.addLayer(new WolfCollarLayer(this));
}
@Override
protected float getBob(final Wolf arz, final float float2) {
return arz.getTailAngle();
}
@Override
public void render(final Wolf arz, final double double2, final double double3, final double double4, final float float5, final float float6) {
if (arz.isWet()) {
final float float7 = arz.getBrightness() * arz.getWetShade(float6);
GlStateManager.color3f(float7, float7, float7);
}
super.render(arz, double2, double3, double4, float5, float6);
}
protected ResourceLocation getTextureLocation(final Wolf arz) {
if (arz.isTame()) {
return WolfRenderer.WOLF_TAME_LOCATION;
}
if (arz.isAngry()) {
return WolfRenderer.WOLF_ANGRY_LOCATION;
}
return WolfRenderer.WOLF_LOCATION;
}
static {
WOLF_LOCATION = new ResourceLocation("textures/entity/wolf/wolf.png");
WOLF_TAME_LOCATION = new ResourceLocation("textures/entity/wolf/wolf_tame.png");
WOLF_ANGRY_LOCATION = new ResourceLocation("textures/entity/wolf/wolf_angry.png");
}
}
| true |
82fef9913b0bbcad90e9926d382a44c589e96bd1 | Java | dpopkov/learn | /ijpds2/src/test/java/learn/ijpds2nd/ch07arrays/exer/E0715EliminateDuplicatesTest.java | UTF-8 | 503 | 2.875 | 3 | [] | no_license | package learn.ijpds2nd.ch07arrays.exer;
import org.junit.Test;
import static learn.ijpds2nd.ch07arrays.exer.E0715EliminateDuplicates.removeDupes;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class E0715EliminateDuplicatesTest {
@Test
public void testRemoveDupes() {
int[] array = {1, 2, 2, 1, 3, 2, 4, 3};
int[] result = removeDupes(array);
int[] expected = {1, 2, 3, 4};
assertThat(result, is(expected));
}
}
| true |
cfe2be716fc6d851ebd5283339c26c46952cd4a6 | Java | chenqing/algs4 | /chapter01/Exercise1_1_3.java | UTF-8 | 482 | 3.609375 | 4 | [
"MIT"
] | permissive | public class Exercise1_1_3 {
public static void main(String args[]) {
int len = args.length;
if ( len != 3) {
System.out.println("need three number input");
}
int number01 = Integer.parseInt(args[0]);
int number02 = Integer.parseInt(args[1]);
int number03 = Integer.parseInt(args[2]);
if (number01 == number02 && number02 == number03) {
System.out.println("equal");
} else {
System.out.println("not equal");
}
}
}
| true |
d557e5f968246cd666476116b256ccedc69e9d13 | Java | rww4287/mentos | /mentos-admin/src/main/java/com/ktds/mentos/admin/authorization/vo/AuthVO.java | UTF-8 | 371 | 1.890625 | 2 | [] | no_license | package com.ktds.mentos.admin.authorization.vo;
public class AuthVO {
public String authId;
public String authName;
public String getAuthId() {
return authId;
}
public void setAuthId(String authId) {
this.authId = authId;
}
public String getAuthName() {
return authName;
}
public void setAuthName(String authName) {
this.authName = authName;
}
}
| true |
d27cce475af7fd6509347ef233acd207a69fa56b | Java | Edward-Aidi/cse131-Java | /coursesupport/blts/SetsAndLists.java | UTF-8 | 538 | 3.609375 | 4 | [] | no_license | package blts;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class SetsAndLists {
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
List<String> list = new LinkedList<String>();
String[] lunch = { "open mouth", "insert food", "chew", "chew", "swallow" };
for (String s : lunch) {
set.add(s); set.add(s);
list.add(s); list.add(s);
}
System.out.println("Set is " + set);
System.out.println("List is " + list);
}
}
| true |
25c4107eb62343332e935388b9c4fab2200ba619 | Java | Syu125/APCS-A-2020 | /APCS-A-2020/src/Unit2/Trap.java | WINDOWS-1252 | 280 | 2.875 | 3 | [] | no_license | // A+ Computer Science - www.apluscompsci.com
//Name - Sophia Yu
//Date - 2/3/20
//Class - APCS-A
//Lab = Trapezoid Area
package Unit2;
public class Trap
{
public static double area( int base1, int base2, int height )
{
return (double)(base1+base2)*height/2;
}
} | true |
5169701f06f3e544ea7d8a0236890b58448c306a | Java | AdilhanKaikenov/swagger-ui-app | /src/main/java/com/kaikenov/spring/swaggeruiapp/service/HobbyService.java | UTF-8 | 848 | 2.15625 | 2 | [] | no_license | package com.kaikenov.spring.swaggeruiapp.service;
import com.kaikenov.spring.swaggeruiapp.entity.Hobby;
import com.kaikenov.spring.swaggeruiapp.repository.HobbyRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@RequiredArgsConstructor
@Service
public class HobbyService {
@Autowired
private HobbyRepository hobbyRepository;
public Hobby create(Hobby hobby) {
return hobbyRepository.save(hobby);
}
public List<Hobby> findAll() {
return hobbyRepository.findAll();
}
public Hobby findOne(Long hobbyId) {
return hobbyRepository.findById(hobbyId).orElse(null);
}
public void delete(Long hobbyId) {
hobbyRepository.deleteById(hobbyId);
}
}
| true |
9d00c022d1d3674dc7bb291549b355278b726e07 | Java | clilystudio/NetBook | /allsrc/com/iflytek/speech/aidl/ISpeechSynthesizer$Stub.java | UTF-8 | 4,266 | 1.8125 | 2 | [
"Unlicense"
] | permissive | package com.iflytek.speech.aidl;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.Parcelable.Creator;
import com.iflytek.speech.SynthesizerListener.Stub;
public abstract class ISpeechSynthesizer$Stub extends Binder
implements ISpeechSynthesizer
{
private static final String DESCRIPTOR = "com.iflytek.speech.aidl.ISpeechSynthesizer";
static final int TRANSACTION_getLocalSpeakerList = 7;
static final int TRANSACTION_isSpeaking = 6;
static final int TRANSACTION_pauseSpeaking = 3;
static final int TRANSACTION_resumeSpeaking = 4;
static final int TRANSACTION_startSpeaking = 2;
static final int TRANSACTION_stopSpeaking = 5;
static final int TRANSACTION_synthesizeToUrl = 1;
public ISpeechSynthesizer$Stub()
{
attachInterface(this, "com.iflytek.speech.aidl.ISpeechSynthesizer");
}
public static ISpeechSynthesizer asInterface(IBinder paramIBinder)
{
if (paramIBinder == null)
return null;
IInterface localIInterface = paramIBinder.queryLocalInterface("com.iflytek.speech.aidl.ISpeechSynthesizer");
if ((localIInterface != null) && ((localIInterface instanceof ISpeechSynthesizer)))
return (ISpeechSynthesizer)localIInterface;
return new ISpeechSynthesizer.Stub.Proxy(paramIBinder);
}
public IBinder asBinder()
{
return this;
}
public boolean onTransact(int paramInt1, Parcel paramParcel1, Parcel paramParcel2, int paramInt2)
{
switch (paramInt1)
{
default:
return super.onTransact(paramInt1, paramParcel1, paramParcel2, paramInt2);
case 1598968902:
paramParcel2.writeString("com.iflytek.speech.aidl.ISpeechSynthesizer");
return true;
case 1:
paramParcel1.enforceInterface("com.iflytek.speech.aidl.ISpeechSynthesizer");
int i2 = paramParcel1.readInt();
Intent localIntent2 = null;
if (i2 != 0)
localIntent2 = (Intent)Intent.CREATOR.createFromParcel(paramParcel1);
int i3 = synthesizeToUrl(localIntent2, SynthesizerListener.Stub.asInterface(paramParcel1.readStrongBinder()));
paramParcel2.writeNoException();
paramParcel2.writeInt(i3);
return true;
case 2:
paramParcel1.enforceInterface("com.iflytek.speech.aidl.ISpeechSynthesizer");
int n = paramParcel1.readInt();
Intent localIntent1 = null;
if (n != 0)
localIntent1 = (Intent)Intent.CREATOR.createFromParcel(paramParcel1);
int i1 = startSpeaking(localIntent1, SynthesizerListener.Stub.asInterface(paramParcel1.readStrongBinder()));
paramParcel2.writeNoException();
paramParcel2.writeInt(i1);
return true;
case 3:
paramParcel1.enforceInterface("com.iflytek.speech.aidl.ISpeechSynthesizer");
int m = pauseSpeaking(SynthesizerListener.Stub.asInterface(paramParcel1.readStrongBinder()));
paramParcel2.writeNoException();
paramParcel2.writeInt(m);
return true;
case 4:
paramParcel1.enforceInterface("com.iflytek.speech.aidl.ISpeechSynthesizer");
int k = resumeSpeaking(SynthesizerListener.Stub.asInterface(paramParcel1.readStrongBinder()));
paramParcel2.writeNoException();
paramParcel2.writeInt(k);
return true;
case 5:
paramParcel1.enforceInterface("com.iflytek.speech.aidl.ISpeechSynthesizer");
int j = stopSpeaking(SynthesizerListener.Stub.asInterface(paramParcel1.readStrongBinder()));
paramParcel2.writeNoException();
paramParcel2.writeInt(j);
return true;
case 6:
paramParcel1.enforceInterface("com.iflytek.speech.aidl.ISpeechSynthesizer");
boolean bool = isSpeaking();
paramParcel2.writeNoException();
if (bool);
for (int i = 1; ; i = 0)
{
paramParcel2.writeInt(i);
return true;
}
case 7:
}
paramParcel1.enforceInterface("com.iflytek.speech.aidl.ISpeechSynthesizer");
String str = getLocalSpeakerList();
paramParcel2.writeNoException();
paramParcel2.writeString(str);
return true;
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.iflytek.speech.aidl.ISpeechSynthesizer.Stub
* JD-Core Version: 0.6.0
*/ | true |
93843d8f11d47931988480a56f7ba9c88e5833bb | Java | sdkuker/Realm | /Realm/src/main/java/com/sdk/realm/persistance/domain/PersistantDomainObject.java | UTF-8 | 651 | 2.5 | 2 | [] | no_license | package com.sdk.realm.persistance.domain;
/*
* I describe common behavior of all domain objects that are persisted - players, characters,
* combat results, etc.
*/
public abstract class PersistantDomainObject {
protected int _id;
public int getId() {
return _id;
}
public void setId(int anId) {
_id = anId;
}
public boolean equals(Object o) {
boolean isEquals = false;
if (o instanceof PersistantDomainObject) {
PersistantDomainObject otherDomainObject = (PersistantDomainObject) o;
if (_id == otherDomainObject._id) {
isEquals = true;
}
}
return isEquals;
}
public int hashCode() {
return _id;
}
}
| true |
5e12fb9e57471c38a60e80dd70d7a6befb291d19 | Java | stokpop/lograter | /src/test/java/nl/stokpop/lograter/report/MetricsWindowTest.java | UTF-8 | 6,242 | 2.328125 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2023 Peter Paul Bakker, Stokpop
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.stokpop.lograter.report;
import nl.stokpop.lograter.counter.CounterKey;
import nl.stokpop.lograter.counter.RequestCounter;
import nl.stokpop.lograter.store.TimeMeasurementStoreInMemory;
import nl.stokpop.lograter.util.metric.MetricPoint;
import nl.stokpop.lograter.util.metric.MetricsWindow;
import org.joda.time.DateTime;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class MetricsWindowTest {
private static final double LITTLE_DELTA = 0.0001;
@Test
public void testProcessLargeDataSet() {
final MetricsWindow window = new MetricsWindow("Test large window", 1000);
final RequestCounter requestCounter = createTimeMeasurementsTestSet(1000, true);
final List<MetricPoint> points = new ArrayList<>();
window.processDataSet(requestCounter, points::add);
assertEquals("Expected 1 metric point", 1, points.size());
for (MetricPoint point : points) {
assertEquals(point.toString(), 500.5, point.getAverageResponseTimeMillis(), LITTLE_DELTA);
assertEquals(point.toString(), 1000, point.getHitsPerSecond(), LITTLE_DELTA);
assertEquals(point.toString(), 250, point.getFirstQuartileResponseTimeMillis(), LITTLE_DELTA);
assertEquals(point.toString(), 1000, point.getMaxResponseTimeMillis(), LITTLE_DELTA);
assertEquals(point.toString(), 1, point.getMinResponseTimeMillis(), LITTLE_DELTA);
assertEquals(point.toString(), 500, point.getMedianResponseTimeMillis(), LITTLE_DELTA);
assertEquals(point.toString(), 750, point.getThirdQuartileResponseTimeMillis(), LITTLE_DELTA);
assertEquals(point.toString(), 950, point.getPercentile95ResponseTimeMillis(), LITTLE_DELTA);
assertEquals(point.toString(), 990, point.getPercentile99ResponseTimeMillis(), LITTLE_DELTA);
}
}
@Test
public void testProcessLargeDataSetMultiplePointsNoOverlap() {
final MetricsWindow window = new MetricsWindow("Test large window", 100);
final RequestCounter requestCounter = createTimeMeasurementsTestSet(1000, false);
final List<MetricPoint> points = new ArrayList<>();
window.processDataSet(requestCounter, points::add);
assertEquals("Expected 10 metric points", 10, points.size());
int i = 1;
for (MetricPoint point : points) {
String message = "Point " + i + " " + point.toString();
System.out.println(message);
// TODO: why the one off?
assertEquals(message, 1000, point.getHitsPerSecond(), 12.0);
i = i + 1;
}
}
@Test
public void testProcessSmallDataSet() {
final MetricsWindow window = new MetricsWindow("Test small window", 10);
final RequestCounter requestCounter = createTimeMeasurementsTestSet(10, false);
final List<MetricPoint> points = new ArrayList<>();
window.processDataSet(requestCounter, points::add);
assertEquals("Expected 1 metric points", 1, points.size());
for (MetricPoint point : points) {
assertEquals(point.toString(), 5.5, point.getAverageResponseTimeMillis(), LITTLE_DELTA);
assertEquals(point.toString(), 1000, point.getHitsPerSecond(), LITTLE_DELTA);
assertEquals(point.toString(), 3, point.getFirstQuartileResponseTimeMillis(), LITTLE_DELTA);
assertEquals(point.toString(), 10, point.getMaxResponseTimeMillis(), LITTLE_DELTA);
assertEquals(point.toString(), 1, point.getMinResponseTimeMillis(), LITTLE_DELTA);
assertEquals(point.toString(), 5, point.getMedianResponseTimeMillis(), LITTLE_DELTA);
assertEquals(point.toString(), 8, point.getThirdQuartileResponseTimeMillis(), LITTLE_DELTA);
assertEquals(point.toString(), 10, point.getPercentile95ResponseTimeMillis(), LITTLE_DELTA);
assertEquals(point.toString(), 10, point.getPercentile99ResponseTimeMillis(), LITTLE_DELTA);
}
}
@Test
public void testHalfFilledWindow() {
final MetricsWindow window = new MetricsWindow("Test half filled small window", 100);
final RequestCounter requestCounter = createTimeMeasurementsHalfTestSet(100);
final List<MetricPoint> points = new ArrayList<>();
window.processDataSet(requestCounter, points::add);
assertEquals("Expected 0 metric points", 0, points.size());
}
private RequestCounter createTimeMeasurementsTestSet(final int size, final boolean shuffle) {
final RequestCounter requestCounter = new RequestCounter(CounterKey.of("Test"), new TimeMeasurementStoreInMemory());
final List<Integer> durations = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
// i + 1: all calculations work better with 1 ms to X ms instead of 0 ms to X ms
durations.add(i + 1);
}
if (shuffle) {
Collections.shuffle(durations);
}
for (int i = 0; i < size; i++) {
long offset = new DateTime(1981, 11, 29, 10, 0).getMillis();
requestCounter.incRequests(offset + i, durations.get(i));
}
return requestCounter;
}
private RequestCounter createTimeMeasurementsHalfTestSet(int size) {
final RequestCounter requestCounter = new RequestCounter(CounterKey.of("Test"), new TimeMeasurementStoreInMemory());
for (int i = size / 2; i < size; i++) {
requestCounter.incRequests(i, i);
}
return requestCounter;
}
} | true |
c940156d29227f60980270d45f7d1038ab88b2e9 | Java | geraldcraig/pa-spring-boot | /TodoApplication/src/main/java/uk/ac/belfastmet/todo/service/ToDoService.java | UTF-8 | 1,846 | 2.875 | 3 | [] | no_license | package uk.ac.belfastmet.todo.service;
import java.util.ArrayList;
import java.util.Iterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import uk.ac.belfastmet.todo.domain.Task;
import uk.ac.belfastmet.todo.repository.TaskRepository;
@Service
public class ToDoService {
// logger here for the array debugging
Logger log = LoggerFactory.getLogger(ToDoService.class);
@Autowired
private TaskRepository taskRepository;
public void getNumberOfTasks() {
log .info("# of tasks: {}", taskRepository.count());
}
public ArrayList<Task> taskToDo;
public ArrayList<Task> gettaskToDo() {
this.taskToDo = new ArrayList<Task>();
// Task(String task, String description, String date, Boolean status, String name, String
// priority)
/*this.taskToDo.add(new Task("1", "learn java", "23 Sep 19", true, "Gerald", "high"));
this.taskToDo.add(new Task("2", "learn html", "24 Sep 19", false, "Gerald", "high"));
this.taskToDo.add(new Task("3", "learn css", "25 Sep 19", false, "Gerald", "high"));
this.taskToDo.add(new Task("4", "learn javascript", "26 Sep 19", false, "Gerald", "high"));
this.taskToDo.add(new Task("5", "learn spring boot", "27 Sep 19", false, "Gerald", "high"));*/
Iterable < Task > toDotasks = taskRepository.findAll();
Iterator < Task > iterator = toDotasks.iterator();
ArrayList<Task> todoList = new ArrayList<Task>();
while (iterator.hasNext()) {
//log.info("{}", iterator.next().toString());
todoList.add(iterator.next());
}
// log debug here for the debugger console to read to know if the array has been successfully read
log.debug("if array shows its working correctly if not theres an issue");
// returning the tasktodo array
return todoList;
}
}
| true |
cc2596962ce3a4def4967bf2208fb15193fd0fdb | Java | ram441/sample | /src/main/java/com/itcinfotech/pbb/sql/model/CustomUserDetails.java | UTF-8 | 1,716 | 2.078125 | 2 | [] | no_license | package com.itcinfotech.pbb.sql.model;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.itcinfotech.pbb.sql.repository.RoleRepository;
public class CustomUserDetails implements UserDetails {
@Autowired
RoleRepository roleRepo;
/**
*
*/
private static final long serialVersionUID = 1L;
private Optional<User> user;
public CustomUserDetails(Optional<User> user) {
//super();
this.user = user;
}
public Optional<User> getUser() {
return user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Long roleId = user.get().getRoleId();
Role role = roleRepo.findOne(roleId);
GrantedAuthority authority = new SimpleGrantedAuthority(role.getRoleName());
return Arrays.asList(authority);
}
@Override
public String getPassword() {
// TODO Auto-generated method stub
return user.get().getPassword();
}
@Override
public String getUsername() {
// TODO Auto-generated method stub
return user.get().getEmail();
}
@Override
public boolean isAccountNonExpired() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isAccountNonLocked() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isCredentialsNonExpired() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isEnabled() {
// TODO Auto-generated method stub
return true;
}
}
| true |
4e98e1841f74009ceb021da2a9625bba20422f46 | Java | jyneo/irobot | /app/src/main/java/com/arcsoft/irobot/object/GridMap.java | UTF-8 | 615 | 2.359375 | 2 | [] | no_license | package com.arcsoft.irobot.object;
import java.nio.ByteBuffer;
import java.util.Locale;
/**
*
* Created by yj2595 on 2018/3/9.
*/
public class GridMap {
public long timestamp;
public int width;
public int height;
public ByteBuffer data;
public float scale = 1.0f;
public final float[] origin = new float[] { 0, 0 };
@Override
public String toString() {
return String.format(Locale.ENGLISH, "GridMap: timestamp=%d, width=%d, height=%d, scale=%f, origin=(%f,%f)",
timestamp, width, height, scale, origin[0], origin[1]);
}
}
| true |
ad82e0044c31adb68d3e6b6c0210e332024547a3 | Java | Unostot/ambientlight | /RadioAdapter/src/org/radio/Stream.java | UTF-8 | 5,261 | 2.203125 | 2 | [] | no_license | package org.radio;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.radio.playist.PlayListRunnable;
@WebServlet(description = "Streams converted radio from tvheadend")
public class Stream extends HttpServlet {
private static final String PATH = "path";
private static final String URL = "url";
private static final String REPLACEMENT = "replacement";
private static final String CHANNEL_REGEX = "channelRegex";
private static final String SERVER_URL = "serverUrl";
private static final String TRANSCODER_COMMAND = "transconderCommand";
private static final String DEBUG_CONSOLE = "debugConsole";
private static final long serialVersionUID = 1L;
PlayListRunnable playListGen;
String serverUrl = null;
String[] args = null;
boolean debug = false;
@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("RadioAdapter: init");
try {
// get command
args = getProperties().getProperty(TRANSCODER_COMMAND).split(" ");
// get server url
serverUrl = getProperties().getProperty(SERVER_URL);
// debug output?
debug = "true".equals(getProperties().getProperty(DEBUG_CONSOLE));
// create a playlist for Mediatomb in 1000 seconds intervalls
String channelRegex = getProperties().getProperty(CHANNEL_REGEX);
String replacement = getProperties().getProperty(REPLACEMENT);
String urlString = getProperties().getProperty(URL);
String path = getProperties().getProperty(PATH);
System.out.println("RadioAdapter: init playListGenerator");
playListGen = new PlayListRunnable(channelRegex, replacement, urlString, path, debug);
new Thread(playListGen, "PlayListGenerator").start();
System.out.println("RadioAdapter: init complete");
} catch (Exception e) {
System.out.println("RadioAdapter - init: did not init propperly");
}
}
@Override
public void destroy() {
try {
playListGen.stop();
// wait for playListGen to stop
Thread.sleep(1200);
} catch (InterruptedException e) {
System.out.println("playlistGen could not be stopped gracefully!");
e.printStackTrace();
}
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path = request.getPathInfo();
String channelId = path.substring(path.lastIndexOf('/') + 1);
try {
Integer.parseInt(channelId);
} catch (Exception e) {
System.out.println("RadioAdapter: no valid channel given!");
return;
}
final String requestUrl = this.serverUrl.replace("$$", channelId);
System.out.println("Radio Adapter: transcoding client request for: " + requestUrl);
OutputStream intoProcessStream = null;
InputStream errorProcessStream = null;
DataInputStream fromProcessStream = null;
Process process = null;
StreamSourceRunnable streamSourceRunnable = null;
try {
process = new ProcessBuilder(args).start();
intoProcessStream = process.getOutputStream();
fromProcessStream = new DataInputStream(process.getInputStream());
errorProcessStream = process.getErrorStream();
// log console output and avoid errorStreamOverflow
new Thread(new TranscodingLogRunnable(errorProcessStream, debug)).start();
// // handle input into process in a seperate process
streamSourceRunnable = new StreamSourceRunnable(intoProcessStream, requestUrl, debug);
new Thread(streamSourceRunnable).start();
// write output until stream will be closed by client with an exception
response.setContentType("audio/mp3");
while (true) {
response.getOutputStream().write(fromProcessStream.readUnsignedByte());
}
} catch (Exception e) {
System.out.println("RadioAdapter: stopped streaming");
if (debug) {
e.printStackTrace();
}
} finally {
try {
// stop streaming from server
if (streamSourceRunnable != null) {
streamSourceRunnable.stop();
}
// handle extra because stream could be closed by datasource error before
try {
intoProcessStream.close();
} catch (Exception e) {
}
fromProcessStream.close();
errorProcessStream.close();
process.destroy();
} catch (Exception finallyException) {
finallyException.printStackTrace();
// if anything goes wrong here - its ok
}
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
public Properties getProperties() throws IOException {
File file = new File("/opt/RadioAdapter/config.properties");
FileInputStream fis = new FileInputStream(file);
Properties props = new java.util.Properties();
props.load(fis);
return props;
}
}
| true |
6671f5b53f8b50742aa23b226e8e069431da7fbe | Java | MCVitzz/StockManager | /src/com/stockmanager/controllers/SaleItemController.java | UTF-8 | 2,209 | 2.4375 | 2 | [] | no_license | package com.stockmanager.controllers;
import com.stockmanager.model.Sale;
import com.stockmanager.model.SaleItem;
import com.stockmanager.utils.Utilities;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
public class SaleItemController {
private Sale sale;
@FXML
private TableView<SaleItem> tblSaleItem;
@FXML
private TableColumn<SaleItem, String> clmnItem;
@FXML
private TableColumn<SaleItem, String> clmnName;
@FXML
private TableColumn<SaleItem, Double> clmnQuantity;
@FXML
private TableColumn<SaleItem, Double> clmnConfirmed;
@FXML
private TableColumn<SaleItem, String> clmnUnit;
@FXML
private TableColumn<SaleItem, String> clmnState;
public SaleItemController(Sale sale) {
this.sale = sale;
}
public void initialize() {
clmnItem.setCellValueFactory(new PropertyValueFactory<SaleItem, String>("item"));
clmnName.setCellValueFactory(new PropertyValueFactory<SaleItem, String>("name"));
clmnQuantity.setCellValueFactory(new PropertyValueFactory<SaleItem, Double>("quantity"));
clmnConfirmed.setCellValueFactory(new PropertyValueFactory<SaleItem, Double>("confirmedQuantity"));
clmnState.setCellValueFactory(new PropertyValueFactory<SaleItem, String>("state"));
clmnUnit.setCellValueFactory(new PropertyValueFactory<SaleItem, String>("unit"));
getData();
}
public void getData() {
tblSaleItem.setItems(FXCollections.observableArrayList(SaleItem.getAllItemsInSale(sale)));
}
@FXML
public void tblSaleItem_OnClick(MouseEvent e) {
if (tblSaleItem.getSelectionModel().getSelectedItem() != null && e.getClickCount() == 2) {
SaleItem w = tblSaleItem.getSelectionModel().getSelectedItem();
Utilities.openDialog("DialogSaleItemView", new DialogSaleItemController(w.getCompany(), w.getSale(), w.getItem(), this));
}
}
@FXML
public void btnAddSaleItem_OnClick() {
Utilities.openDialog("DialogSaleItemView", new DialogSaleItemController(sale.getCompany(), sale.getSale(), this));
}
@FXML
public void btnRefresh_OnClick() {
getData();
}
}
| true |
b0665c0353e98f0dc07ff267335f8492d2853d21 | Java | 0yuyuko0/mall | /mall-user/src/main/java/com/yuyuko/mall/user/entity/UserPersonalInfoDO.java | UTF-8 | 402 | 1.640625 | 2 | [] | no_license | package com.yuyuko.mall.user.entity;
import lombok.Data;
import lombok.experimental.Accessors;
import java.time.LocalDateTime;
@Data
@Accessors(chain = true)
public class UserPersonalInfoDO {
private Long id;
private Long userId;
private String username;
private String nickname;
private String avatar;
private Boolean isSeller;
private LocalDateTime timeCreate;
}
| true |
535b8b636edc35f23294dd22b21b4caf3a825f6e | Java | rite2rohit/school | /school/src/main/java/com/kstech/logic/EmployeeLogic.java | UTF-8 | 516 | 1.96875 | 2 | [] | no_license | package com.kstech.logic;
import java.util.List;
import org.springframework.stereotype.Service;
import com.kstech.model.Address;
import com.kstech.model.EmployeeVO;
import com.kstech.model.Project;
@Service
public interface EmployeeLogic {
void addEmployee(EmployeeVO employee);
EmployeeVO getEmployeeById(Long id);
void addEmployeeAddress(Long id, Address address);
void addEmployeeProject(Long id, Project project);
List<EmployeeVO> getEmployeeByName(String name);
}
| true |
1ed9336c3ca72c2fffa9776f4521110f5f657078 | Java | Inkin88/job4j | /chapter_002/src/main/java/ru/job4j/pseudo/Paint.java | UTF-8 | 195 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | package ru.job4j.pseudo;
/**
* @author Airat Muzafarov
* @since 17/02/2019
* @version 0.1
*/
public class Paint {
public void draw(Shape shape) {
System.out.println(shape.draw());
}
}
| true |
13d3c388ffbf85ec642c43313a652399e90b07f6 | Java | IvoUlbricht/crypto-wallet-simulator | /src/main/java/com/hotovo/cws/domain/Wallet.java | UTF-8 | 601 | 2.015625 | 2 | [] | no_license | package com.hotovo.cws.domain;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Wallet {
private static AtomicLong walletId = new AtomicLong(1);
private Long id;
private String privateKey;
private String publicKey;
private String name;
private Set<Currency> currencies = new LinkedHashSet<>();
public static AtomicLong getWalletId() {
return walletId;
}
}
| true |
434242a370ddfca6483ecb61ca68a12cb724de32 | Java | dinaurazalina/java-project | /src/LeetCode/RomantoIntV3.java | UTF-8 | 551 | 3.40625 | 3 | [] | no_license | package LeetCode;
import java.util.*;
import java.util.Scanner;
public class RomantoIntV3 {
public static void main(String[] args) {
String roman[]= {"I", "V", "X", "L", "C", "D", "M"};
int ints[] = { 1, 5, 10, 50, 100, 500, 1000};
Scanner scan = new Scanner(System.in);
System.out.println("Enter a roman number");
String s = scan.next();
String arr[] = s.split("");
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if(arr[i].equals(roman[j])) {
}
}
}
}
}
| true |
7eb42f0f2c93cc1c8cfbedf5258ede8fbc096791 | Java | dastonzerg/sd3x_homework2 | /Test.java | UTF-8 | 2,765 | 3.015625 | 3 | [] | no_license | import java.util.*;
import static java.lang.System.out;
public class Test
{
public static void main(String args[])
{
// Test1
GreedyDynamicAlgorithms.Interval blue1=new GreedyDynamicAlgorithms.Interval(0, 2);
GreedyDynamicAlgorithms.Interval blue2=new GreedyDynamicAlgorithms.Interval(5, 5);
GreedyDynamicAlgorithms.Interval blue3=new GreedyDynamicAlgorithms.Interval(7, 10);
GreedyDynamicAlgorithms.Interval blue4=new GreedyDynamicAlgorithms.Interval(11, 13);
GreedyDynamicAlgorithms.Interval red1=new GreedyDynamicAlgorithms.Interval(1, 4);
GreedyDynamicAlgorithms.Interval red2=new GreedyDynamicAlgorithms.Interval(5, 7);
GreedyDynamicAlgorithms.Interval red3=new GreedyDynamicAlgorithms.Interval(7, 8);
GreedyDynamicAlgorithms.Interval red4=new GreedyDynamicAlgorithms.Interval(9, 10);
GreedyDynamicAlgorithms.Interval red5=new GreedyDynamicAlgorithms.Interval(9, 11);
GreedyDynamicAlgorithms.Interval red6=new GreedyDynamicAlgorithms.Interval(10, 12);
GreedyDynamicAlgorithms.Interval red7=new GreedyDynamicAlgorithms.Interval(11, 12);
ArrayList<GreedyDynamicAlgorithms.Interval> blueIntervals=new ArrayList<GreedyDynamicAlgorithms.Interval>();
ArrayList<GreedyDynamicAlgorithms.Interval> redIntervals=new ArrayList<GreedyDynamicAlgorithms.Interval>();
blueIntervals.add(blue1);
blueIntervals.add(blue2);
blueIntervals.add(blue3);
blueIntervals.add(blue4);
redIntervals.add(red1);
redIntervals.add(red2);
redIntervals.add(red3);
redIntervals.add(red4);
redIntervals.add(red5);
redIntervals.add(red6);
redIntervals.add(red7);
out.println(GreedyDynamicAlgorithms.optimalIntervals(redIntervals, blueIntervals));
//
// int[][] grid=new int[2][3];
// out.println(grid.length);
// out.println(grid[0].length);
// Test2
// int[][] grid=new int[4][3];
// grid[0][0]=5;
// grid[0][1]=1;
// grid[0][2]=1;
// grid[1][0]=2;
// grid[1][1]=4;
// grid[1][2]=7;
// grid[2][0]=2;
// grid[2][1]=4;
// grid[2][2]=5;
// grid[3][0]=5;
// grid[3][1]=6;
// grid[3][2]=3;
//
// List<GreedyDynamicAlgorithms.Direction> directionList=GreedyDynamicAlgorithms.optimalGridPath(grid);
//
// Iterator<GreedyDynamicAlgorithms.Direction> iterator=directionList.iterator();
// while(iterator.hasNext())
// {
// if(iterator.next()==GreedyDynamicAlgorithms.Direction.DOWN)
// {
// out.println("DOWN");
// }
// else
// {
// out.println("RIGHT");
// }
// }
// Test3
// out.println("aaa"+'b');
// Huffman huffman=new Huffman("aabc");
// out.println(huffman.encode());
// out.println(huffman.decode("110100"));
}
}
| true |
f7fd97673c71eda0f1d337d4967cda33afe31ada | Java | Ranjodh-Singh/servicetalk | /servicetalk-grpc-protobuf/src/main/java/io/servicetalk/grpc/protobuf/ProtoBufSerializationProviderBuilder.java | UTF-8 | 9,819 | 1.804688 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright © 2019 Apple Inc. and the ServiceTalk project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 io.servicetalk.grpc.protobuf;
import io.servicetalk.buffer.api.Buffer;
import io.servicetalk.buffer.api.BufferAllocator;
import io.servicetalk.concurrent.BlockingIterable;
import io.servicetalk.concurrent.api.Publisher;
import io.servicetalk.grpc.api.GrpcMessageEncoding;
import io.servicetalk.grpc.api.GrpcMetadata;
import io.servicetalk.grpc.api.GrpcSerializationProvider;
import io.servicetalk.http.api.HttpDeserializer;
import io.servicetalk.http.api.HttpHeaders;
import io.servicetalk.http.api.HttpPayloadWriter;
import io.servicetalk.http.api.HttpSerializer;
import io.servicetalk.serialization.api.DefaultSerializer;
import io.servicetalk.serialization.api.SerializationException;
import io.servicetalk.serialization.api.Serializer;
import com.google.protobuf.MessageLite;
import com.google.protobuf.Parser;
import java.io.IOException;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
import static io.servicetalk.grpc.api.GrpcMessageEncoding.None;
import static io.servicetalk.http.api.CharSequences.newAsciiString;
import static io.servicetalk.http.api.HttpHeaderNames.CONTENT_TYPE;
import static java.util.Collections.unmodifiableMap;
/**
* A builder for building a {@link GrpcSerializationProvider} that can serialize and deserialize
* pre-registered <a href="https://developers.google.com/protocol-buffers/">protocol buffer</a> objects.
* {@link #registerMessageType(Class, Parser)} is used to add one or more {@link MessageLite} message types. Resulting
* {@link GrpcSerializationProvider} from {@link #build()} will only serialize and deserialize those message types.
*/
public final class ProtoBufSerializationProviderBuilder {
private static final CharSequence GRPC_MESSAGE_ENCODING_KEY = newAsciiString("grpc-encoding");
private static final CharSequence APPLICATION_GRPC_PROTO = newAsciiString("application/grpc+proto");
private final Map<Class, EnumMap<GrpcMessageEncoding, HttpSerializer>> serializers = new HashMap<>();
private final Map<Class, EnumMap<GrpcMessageEncoding, HttpDeserializer>> deserializers = new HashMap<>();
/**
* Register the passed {@code messageType} with the provided {@link Parser}.
*
* @param messageType {@link Class} of the type of message to register.
* @param parser {@link Parser} for this message type.
* @param <T> Type of {@link MessageLite} to register.
* @return {@code this}
*/
public <T extends MessageLite> ProtoBufSerializationProviderBuilder
registerMessageType(Class<T> messageType, Parser<T> parser) {
EnumMap<GrpcMessageEncoding, HttpSerializer> serializersForType = new EnumMap<>(GrpcMessageEncoding.class);
EnumMap<GrpcMessageEncoding, HttpDeserializer> deserializersForType = new EnumMap<>(GrpcMessageEncoding.class);
for (GrpcMessageEncoding grpcMessageEncoding : GrpcMessageEncoding.values()) {
DefaultSerializer serializer = new DefaultSerializer(
new ProtoBufSerializationProvider<>(messageType, grpcMessageEncoding, parser));
HttpSerializer<T> httpSerializer = new ProtoHttpSerializer<>(serializer, grpcMessageEncoding, messageType);
serializersForType.put(grpcMessageEncoding, httpSerializer);
deserializersForType.put(grpcMessageEncoding, new HttpDeserializer<T>() {
@Override
public T deserialize(final HttpHeaders headers, final Buffer payload) {
return serializer.deserializeAggregatedSingle(payload, messageType);
}
@Override
public BlockingIterable<T> deserialize(final HttpHeaders headers,
final BlockingIterable<Buffer> payload) {
return serializer.deserialize(payload, messageType);
}
@Override
public Publisher<T> deserialize(final HttpHeaders headers, final Publisher<Buffer> payload) {
return serializer.deserialize(payload, messageType);
}
});
}
serializers.put(messageType, serializersForType);
deserializers.put(messageType, deserializersForType);
return this;
}
/**
* Builds a new {@link GrpcSerializationProvider} containing all the message types registered with this builder.
*
* @return New {@link GrpcSerializationProvider} that will serialize and deserialize message types that were
* registered to this builder.
*/
public GrpcSerializationProvider build() {
return new ProtoSerializationProvider(serializers, deserializers);
}
private static class ProtoSerializationProvider implements GrpcSerializationProvider {
private final Map<Class, EnumMap<GrpcMessageEncoding, HttpSerializer>> serializers;
private final Map<Class, EnumMap<GrpcMessageEncoding, HttpDeserializer>> deserializers;
ProtoSerializationProvider(final Map<Class, EnumMap<GrpcMessageEncoding, HttpSerializer>> serializers,
final Map<Class, EnumMap<GrpcMessageEncoding, HttpDeserializer>> deserializers) {
this.serializers = unmodifiableMap(serializers);
this.deserializers = unmodifiableMap(deserializers);
}
@Override
public <T> HttpSerializer<T> serializerFor(final GrpcMetadata metadata, final Class<T> type) {
EnumMap<GrpcMessageEncoding, HttpSerializer> serializersForType = serializers.get(type);
if (serializersForType == null) {
throw new SerializationException("Unknown class to serialize: " + type.getName());
}
@SuppressWarnings("unchecked")
HttpSerializer<T> httpSerializer = serializersForType.get(None); // compression not yet supported.
return httpSerializer;
}
@Override
public <T> HttpDeserializer<T> deserializerFor(final GrpcMessageEncoding messageEncoding, final Class<T> type) {
EnumMap<GrpcMessageEncoding, HttpDeserializer> deserializersForType = deserializers.get(type);
if (deserializersForType == null) {
throw new SerializationException("Unknown class to deserialize: " + type.getName());
}
@SuppressWarnings("unchecked")
HttpDeserializer<T> httpSerializer = deserializersForType.get(messageEncoding);
return httpSerializer;
}
}
private static final class ProtoHttpSerializer<T> implements HttpSerializer<T> {
private final Serializer serializer;
private final GrpcMessageEncoding grpcMessageEncoding;
private final Class<T> type;
ProtoHttpSerializer(final Serializer serializer, final GrpcMessageEncoding grpcMessageEncoding,
final Class<T> type) {
this.serializer = serializer;
this.grpcMessageEncoding = grpcMessageEncoding;
this.type = type;
}
@Override
public Buffer serialize(final HttpHeaders headers, final T value, final BufferAllocator allocator) {
addContentHeaders(headers);
return serializer.serialize(value, allocator);
}
@Override
public BlockingIterable<Buffer> serialize(final HttpHeaders headers,
final BlockingIterable<T> value,
final BufferAllocator allocator) {
addContentHeaders(headers);
return serializer.serialize(value, allocator, type);
}
@Override
public Publisher<Buffer> serialize(final HttpHeaders headers, final Publisher<T> value,
final BufferAllocator allocator) {
addContentHeaders(headers);
return serializer.serialize(value, allocator, type);
}
@Override
public HttpPayloadWriter<T> serialize(final HttpHeaders headers,
final HttpPayloadWriter<Buffer> payloadWriter,
final BufferAllocator allocator) {
addContentHeaders(headers);
return new HttpPayloadWriter<T>() {
@Override
public HttpHeaders trailers() {
return payloadWriter.trailers();
}
@Override
public void write(final T t) throws IOException {
payloadWriter.write(serializer.serialize(t, allocator));
}
@Override
public void close() throws IOException {
payloadWriter.close();
}
@Override
public void flush() throws IOException {
payloadWriter.flush();
}
};
}
private void addContentHeaders(final HttpHeaders headers) {
headers.set(CONTENT_TYPE, APPLICATION_GRPC_PROTO);
headers.set(GRPC_MESSAGE_ENCODING_KEY, grpcMessageEncoding.encoding());
}
}
}
| true |
5ab7d81fbc8386e6387a3d129baefdcfb27d92d3 | Java | wyman58/patterns | /src/main/java/common/patterns/commandchain/processor/Processor.java | UTF-8 | 548 | 2.046875 | 2 | [] | no_license | package common.patterns.commandchain.processor;
import common.patterns.commandchain.context.ApplicationContext;
import org.slf4j.Logger;
import java.util.Optional;
public interface Processor<R extends ProcessorRequest, C extends ApplicationContext> {
boolean isApplicable(R request, C context);
boolean isProcessingTerminatedOnException();
ProcessorResponse process(R request, C context);
Logger getLogger();
Optional<Processor<R,C>> getNextProcessor();
void setNextProcessor(Processor<R, C> processor);
}
| true |
c465de05e600acbe8c049690b4983ffe6d847f11 | Java | AndreaReyesSerna/Taller-1 | /Taller1_Eco_AndroidStudio/app/src/main/java/com/example/talleres/ecosistemas/nemo/MainActivity.java | UTF-8 | 1,293 | 1.96875 | 2 | [] | no_license | package com.example.talleres.ecosistemas.nemo;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button btn_empezar;
EditText et_ip;
static public String IP;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.activity_main);
this.btn_empezar = findViewById(R.id.btn_empezar);
this.et_ip = findViewById(R.id.et_ip);
this.btn_empezar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String iptext = et_ip.getText().toString();
if(iptext != ""){
IP = iptext;
Intent controles = new Intent(MainActivity.this, Personajes.class);
startActivity(controles);
}
}
});
}
}
| true |
40484d9e827d5e3eac8c469d7f0bdc9827b0445e | Java | MrChuJian/cake | /cake_ssh/src/main/java/zzw/vo/VarietyVO.java | UTF-8 | 938 | 2.046875 | 2 | [] | no_license | package zzw.vo;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import com.opensymphony.xwork2.ActionSupport;
public class VarietyVO {
private Integer vid;
private String variety;
private Date gmt_create;
private Date gmt_modified;
private Set<CakeVO> cakes;
public Set<CakeVO> getCakes() {
return cakes;
}
public void setCakes(Set<CakeVO> cakes) {
this.cakes = cakes;
}
public Integer getVid() {
return vid;
}
public void setVid(Integer vid) {
this.vid = vid;
}
public String getVariety() {
return variety;
}
public void setVariety(String variety) {
this.variety = variety;
}
public Date getGmt_create() {
return gmt_create;
}
public void setGmt_create(Date gmt_create) {
this.gmt_create = gmt_create;
}
public Date getGmt_modified() {
return gmt_modified;
}
public void setGmt_modified(Date gmt_modified) {
this.gmt_modified = gmt_modified;
}
}
| true |
e4d3f367bc1bdd0c6004c235a396502a617761a1 | Java | joakimgrutle/INF112-Games | /Spooks source code/core/src/logicClasses/Item.java | UTF-8 | 7,530 | 2.1875 | 2 | [] | no_license | package logicClasses;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.oblig4.spooks.Gamesprites;
import com.oblig4.spooks.Hud;
import com.oblig4.spooks.ItemInfoWindow;
import com.oblig4.spooks.Spooks;
import interfaces.IItem;
import items.*;
public abstract class Item extends Gamesprites implements IItem {
private String itemName;
private ArrayList<String> compatibleItems = new ArrayList<>();
private boolean used = false;
private boolean pickable = true;
private boolean consumeable = false;
private boolean justCreated;
private boolean isKeyItem = false;
public ItemInfoWindow window;
public Item(Sprite sprite) {
super(sprite);
this.justCreated = true;
}
@Override
public void setPosition(Vector2 vec) {
this.position = vec;
}
public static Item createItem(String it) {
String item = it.toLowerCase();
switch (item) {
// Case for single item.
case "boltcutter":
return new BoltCutter(new Sprite(new Texture(Gdx.files.internal("images/boltesaks.png"))));
case "brokenboltcutter":
return new BrokenBoltCutter(new Sprite(new Texture(Gdx.files.internal("images/boltesaksUtenSkrue.png"))));
case "boltcutterandscrew":
return new BoltCutterAndScrew(new Sprite(new Texture(Gdx.files.internal("images/boltesaksMedSkrue.png"))));
case "candle":
return new Candle(new Sprite(new Texture(Gdx.files.internal("images/candle_extinguished.png"))));
case "candlelight":
return new Candlelight(new Sprite(new Texture(Gdx.files.internal("images/lysIStakeBrenner.png"))));
case "candlestick":
return new Candlestick(new Sprite(new Texture(Gdx.files.internal("images/lysestakeUtenLys.png"))));
case "candlestickandcandle":
return new CandlestickAndCandle(new Sprite(new Texture(Gdx.files.internal("images/lysIStakeSlukket.png"))));
case "hand":
return new Hand(new Sprite(new Texture(Gdx.files.internal("images/Hand.png"))));
case "key":
return new Key(new Sprite(new Texture(Gdx.files.internal("images/key.png"))));
case "knife":
return new Knife(new Sprite(new Texture(Gdx.files.internal("images/kniv_stor.png"))));
case "lighter":
return new Lighter(new Sprite(new Texture(Gdx.files.internal("images/lighter.png"))));
case "pumpkin":
return new Pumpkin(new Sprite(new Texture(Gdx.files.internal("images/gresskar.png"))));
case "pumpkincarvedremote":
return new PumpkinCarvedRemote(
new Sprite(new Texture(Gdx.files.internal("images/gresskar_deltiito_fjernkontroll.png"))));
case "pumpkincarved":
return new PumpkinCarved(new Sprite(new Texture(Gdx.files.internal("images/gresskar_deltito.png"))));
case "remotecontrol":
return new RemoteControl(new Sprite(new Texture(Gdx.files.internal("images/fjernkontroll_inventory.png"))));
case "screw":
return new Screw(new Sprite(new Texture(Gdx.files.internal("images/skrue.png"))));
case "screwdriver":
return new Screwdriver(new Sprite(new Texture(Gdx.files.internal("images/skruetrekker_inventory.png"))));
case "flashlight":
return new Flashlight(new Sprite(new Texture(Gdx.files.internal("images/lommelykt.png"))));
// Case for combinations
case "screw" + "brokenboltcutter":
return new BoltCutterAndScrew(new Sprite(new Texture(Gdx.files.internal("images/boltesaksMedSkrue.png"))));
case "brokenboltcutter" + "screw":
return new BoltCutterAndScrew(new Sprite(new Texture(Gdx.files.internal("images/boltesaksMedSkrue.png"))));
case "boltcutterandscrew" + "screwdriver":
Spooks.manager.get("sound/combine2.wav", Sound.class).play();
return new BoltCutter(new Sprite(new Texture(Gdx.files.internal("images/boltesaks.png"))));
case "screwdriver" + "boltcutterandscrew":
Spooks.manager.get("sound/combine2.wav", Sound.class).play();
return new BoltCutter(new Sprite(new Texture(Gdx.files.internal("images/boltesaks.png"))));
case "knife" + "pumpkin":
Spooks.manager.get("sound/cut.wav", Sound.class).play();
return new PumpkinCarvedRemote(new Sprite(new Texture(Gdx.files.internal("images/gresskar_deltiito_fjernkontroll.png"))));
case "pumpkin" + "knife":
Spooks.manager.get("sound/cut.wav", Sound.class).play();
return new PumpkinCarvedRemote(new Sprite(new Texture(Gdx.files.internal("images/gresskar_deltiito_fjernkontroll.png"))));
case "candle" + "candlestick":
return new CandlestickAndCandle(new Sprite(new Texture(Gdx.files.internal("images/lysIStakeSlukket.png"))));
case "candlestick" + "candle":
return new CandlestickAndCandle(new Sprite(new Texture(Gdx.files.internal("images/lysIStakeSlukket.png"))));
case "candlestickandcandle" + "lighter":
Spooks.manager.get("sound/burn.wav", Sound.class).play();
return new Candlelight(new Sprite(new Texture(Gdx.files.internal("images/lysIStakeBrenner.png"))));
case "lighter" + "candlestickandcandle":
Spooks.manager.get("sound/burn.wav", Sound.class).play();
return new Candlelight(new Sprite(new Texture(Gdx.files.internal("images/lysIStakeBrenner.png"))));
default:
return null;
}
}
@Override
public ArrayList<Item> combineTwoItems(Item item) {
ArrayList<Item> ret = new ArrayList<>();
if (item instanceof KeyItem){
item.setSprite(((KeyItem) item).getDestroyedSprite());
((KeyItem) item).destroyKeyItem();
SpooksGame.getInstance().getHud().getInventory().updateImage((KeyItem) item);
ret.add(createItem("candlelight"));
return ret;
}
this.used = true;
item.used = true;
Item A = createItem(this.itemName + item.getItemName());
if (A == null)
return ret;
ret.add(A);
if (A instanceof PumpkinCarved){
ret.add(createItem("remotecontroller"));
Collections.swap(ret, 0, 1);
}
else if (A instanceof BoltCutter){
ret.add(createItem("screwdriver"));
Collections.swap(ret, 0, 1);
}
return ret;
}
@Override
public void draw(SpriteBatch spriteBatch) {
sprite.setX(position.x);
sprite.setY(position.y);
sprite.draw(spriteBatch);
}
@Override
public boolean canCombineTwoItems(Item item) {
if (this.compatibleItems.isEmpty())
return false;
return this.compatibleItems.contains(item.getItemName());
}
@Override
public List<String> getCompatibleList(Item item) {
return compatibleItems;
}
protected void setName(String itemName) {
this.itemName = itemName;
}
protected void setCompatibleList(ArrayList compatibleItems) {
this.compatibleItems = compatibleItems;
}
@Override
public String getItemName() {
return itemName;
}
@Override
public boolean getUsedStatus() {
return used;
}
@Override
public void setUsedStatus(boolean e) {
this.used = e;
}
protected void setPickable(boolean e) {
this.pickable = e;
}
@Override
public boolean getPickableStatus() {
return pickable;
}
@Override
public void setConsumeable(boolean e) {
this.consumeable = e;
}
@Override
public boolean getConsumeableStatus() {
return this.consumeable;
}
public void removeInfoWindow() {
if (window != null)
window.remove();
}
@Override
public void infoWindow(Hud hud) {
window = new ItemInfoWindow(this, Spooks.skin, hud, this.position, true);
hud.stage.addActor(window);
}
protected void setKeyItem(boolean e){
this.isKeyItem = e;
}
public boolean getKeyItemStatus(){
return isKeyItem;
}
}
| true |
9e0e5bd20e461bf7051be666f2e2c1fce9e3e116 | Java | 95thcobra/osrs-server-1 | /server/src/main/java/nl/bartpelle/veteres/services/serializers/MongoDBPlayerSerializer.java | UTF-8 | 671 | 2.40625 | 2 | [
"MIT"
] | permissive | package nl.bartpelle.veteres.services.serializers;
import nl.bartpelle.veteres.model.entity.Player;
import nl.bartpelle.veteres.model.uid.UIDProvider;
import java.util.function.Consumer;
/**
* Created by Bart on 4-3-2015.
*
* Serializer which utilizes a MongoDB to store and load player data.
*/
public class MongoDBPlayerSerializer extends PlayerSerializer {
public MongoDBPlayerSerializer(UIDProvider provider) {
super(provider);
}
@Override
public boolean loadPlayer(Player player, Object i, String password, Consumer<PlayerLoadResult> fn) {
fn.accept(PlayerLoadResult.OK);
return true;
}
@Override
public void savePlayer(Player player) {
}
}
| true |
3b0e4360d51908dbfe3c1aa87819d642a45ea257 | Java | sunstarvip/webShop | /src/main/java/com/darknight/webShop/goodsType/entity/GoodsType.java | UTF-8 | 1,361 | 2.140625 | 2 | [] | no_license | package com.darknight.webShop.goodsType.entity;
import com.alibaba.fastjson.annotation.JSONField;
import com.darknight.core.base.entity.DefaultEntity;
import com.darknight.webShop.goods.entity.Goods;
import com.darknight.webShop.shop.entity.Shop;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.*;
import java.util.List;
/**
* 商品类型
* Created by DarKnight on 2015/9/7.
*/
@Entity
@DynamicInsert()
@DynamicUpdate()
@Table(name = "t_webshop_goods_type")
public class GoodsType extends DefaultEntity {
private String typeName; // 类型名称
private Shop shop; // 所属店铺
private List<Goods> goodsList; // 包含商品
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
@JSONField(serialize = false)
@ManyToOne
@JoinColumn(name = "shop_id", referencedColumnName = "id")
public Shop getShop() {
return shop;
}
public void setShop(Shop shop) {
this.shop = shop;
}
@JSONField(serialize = false)
@OneToMany(mappedBy = "goodsType")
public List<Goods> getGoodsList() {
return goodsList;
}
public void setGoodsList(List<Goods> goodsList) {
this.goodsList = goodsList;
}
}
| true |
dae39d77648245ea7f4c5709079e19072d3e7cf9 | Java | FreudFan/StockInvest | /server/src/main/java/com/fmy/server/config/dynamicDataSource/DataSourceEntity.java | UTF-8 | 3,369 | 2.3125 | 2 | [] | no_license | package com.fmy.server.config.dynamicDataSource;
import com.alibaba.druid.pool.DruidDataSource;
import com.fmy.server.common.EmployeeUtil;
import com.fmy.server.config.dynamicDataSource.dataSource.DynamicDataSource;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.Map;
public class DataSourceEntity {
private static Logger logger = LoggerFactory.getLogger(DataSourceEntity.class);
public static void setDynamicDataSource( Map dataSource ) throws Exception {
EmployeeUtil employeeUtil = new EmployeeUtil();
employeeUtil.invalidEmployeeSession();
String DBName = MapUtils.getString(dataSource, "DBName", "").trim();
String DBUrl = MapUtils.getString(dataSource, "DBUrl", "").trim();
String DBUser = MapUtils.getString(dataSource, "DBUser", "").trim();
String DBPassword = MapUtils.getString(dataSource, "DBPassword", "").trim();
if ( !DBName.equals("") && !DBUrl.equals("") && !DBUser.equals("") && !DBPassword.equals("") ) {
logger.info("正在设置自定义数据源" + dataSource.toString());
DynamicDataSource dynamicDataSource = DynamicDataSource.getInstance();
String url = "jdbc:mysql://" + DBUrl +"/" + DBName +"?characterEncoding=UTF-8&useUnicode=true&useSSL=false&serverTimezone=Hongkong";
// jdbc:mysql://106.14.120.166:3306/bs_support?characterEncoding=UTF-8&useUnicode=true&useSSL=false&serverTimezone=Hongkong
DruidDataSource defaultDataSource = new DruidDataSource();
defaultDataSource.setUrl(url);
defaultDataSource.setUsername(DBUser);
defaultDataSource.setPassword(DBPassword);
defaultDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
Map<Object,Object> map = new HashMap<>();
map.put("dynamic-slave", defaultDataSource);
dynamicDataSource.setTargetDataSources(map);
dynamicDataSource.setDefaultTargetDataSource(defaultDataSource);
}
}
public static String testDataSource( Map dataSource ) throws Exception {
String DBName = MapUtils.getString(dataSource, "DBName", "").trim();
String DBUrl = MapUtils.getString(dataSource, "DBUrl", "").trim();
String DBUser = MapUtils.getString(dataSource, "DBUser", "").trim();
String DBPassword = MapUtils.getString(dataSource, "DBPassword", "").trim();
if ( !DBName.equals("") && !DBUrl.equals("") && !DBUser.equals("") && !DBPassword.equals("") ) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");//加载驱动类
String url = "jdbc:mysql://" + DBUrl +"/" + DBName +"?characterEncoding=UTF-8&useUnicode=true&useSSL=false&serverTimezone=Hongkong";
String username = DBUser;
String password = DBPassword;
Connection conn= DriverManager.getConnection(url,username,password);//用参数得到连接对象
return "ok";
} catch (Exception e) {
logger.error("测试数据库连接失败");
return "error";
}
} else {
return "error";
}
}
}
| true |
bdab81651a2325969e1ea28cd1fac5c21e7dee19 | Java | totond/LearnAnimation | /app/src/main/java/scut/com/learnanimation/InterpolatorsActivity.java | UTF-8 | 6,244 | 2.34375 | 2 | [] | no_license | package scut.com.learnanimation;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.TextView;
import static android.R.anim.accelerate_decelerate_interpolator;
import static android.R.anim.accelerate_interpolator;
import static android.R.anim.anticipate_interpolator;
import static android.R.anim.anticipate_overshoot_interpolator;
import static android.R.anim.bounce_interpolator;
import static android.R.anim.cycle_interpolator;
import static android.R.anim.decelerate_interpolator;
import static android.R.anim.linear_interpolator;
import static android.R.anim.overshoot_interpolator;
public class InterpolatorsActivity extends AppCompatActivity {
private Button btn_start;
private TextView tv_AccelerateDecelerate,tv_Accelerate,tv_Anticipate,tv_AnticipateOvershoot,tv_Bounce,
tv_Cycle,tv_Decelerate,tv_Linear,tv_Overshoot;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_interpolators);
btn_start = (Button) findViewById(R.id.btn_start);
tv_AccelerateDecelerate = (TextView) findViewById(R.id.tv_AccelerateDecelerate);
tv_Accelerate = (TextView) findViewById(R.id.tv_Accelerate);
tv_Anticipate = (TextView) findViewById(R.id.tv_Anticipate);
tv_AnticipateOvershoot = (TextView) findViewById(R.id.tv_AnticipateOvershoot);
tv_Bounce = (TextView) findViewById(R.id.tv_Bounce);
tv_Cycle = (TextView) findViewById(R.id.tv_Cycle);
tv_Decelerate = (TextView) findViewById(R.id.tv_Decelerate);
tv_Linear = (TextView) findViewById(R.id.tv_Linear);
tv_Overshoot = (TextView) findViewById(R.id.tv_Overshoot);
btn_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Animation animation1 = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,0,Animation.RELATIVE_TO_PARENT,0.5f,
Animation.RELATIVE_TO_PARENT,0,Animation.RELATIVE_TO_PARENT,0);
animation1.setDuration(3000);
animation1.setFillAfter(true);
animation1.setInterpolator(InterpolatorsActivity.this,accelerate_decelerate_interpolator);
tv_AccelerateDecelerate.startAnimation(animation1);
Animation animation2 = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,0,Animation.RELATIVE_TO_PARENT,0.5f,
Animation.RELATIVE_TO_PARENT,0,Animation.RELATIVE_TO_PARENT,0);
animation2.setDuration(3000);
animation2.setFillAfter(true);
animation2.setInterpolator(InterpolatorsActivity.this,accelerate_interpolator);
tv_Accelerate.startAnimation(animation2);
Animation animation3 = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,0,Animation.RELATIVE_TO_PARENT,0.5f,
Animation.RELATIVE_TO_PARENT,0,Animation.RELATIVE_TO_PARENT,0);
animation3.setDuration(3000);
animation3.setFillAfter(true);
animation3.setInterpolator(InterpolatorsActivity.this,anticipate_interpolator);
tv_Anticipate.startAnimation(animation3);
Animation animation4 = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,0,Animation.RELATIVE_TO_PARENT,0.5f,
Animation.RELATIVE_TO_PARENT,0,Animation.RELATIVE_TO_PARENT,0);
animation4.setDuration(3000);
animation4.setFillAfter(true);
animation4.setInterpolator(InterpolatorsActivity.this,anticipate_overshoot_interpolator);
tv_AnticipateOvershoot.startAnimation(animation4);
Animation animation5 = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,0,Animation.RELATIVE_TO_PARENT,0.5f,
Animation.RELATIVE_TO_PARENT,0,Animation.RELATIVE_TO_PARENT,0);
animation5.setDuration(3000);
animation5.setFillAfter(true);
animation5.setInterpolator(InterpolatorsActivity.this,bounce_interpolator);
tv_Bounce.startAnimation(animation5);
Animation animation6 = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,0,Animation.RELATIVE_TO_PARENT,0.5f,
Animation.RELATIVE_TO_PARENT,0,Animation.RELATIVE_TO_PARENT,0);
animation6.setDuration(3000);
animation6.setFillAfter(true);
animation6.setInterpolator(InterpolatorsActivity.this,cycle_interpolator);
tv_Cycle.startAnimation(animation6);
Animation animation7 = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,0,Animation.RELATIVE_TO_PARENT,0.5f,
Animation.RELATIVE_TO_PARENT,0,Animation.RELATIVE_TO_PARENT,0);
animation7.setDuration(3000);
animation7.setFillAfter(true);
animation7.setInterpolator(InterpolatorsActivity.this,decelerate_interpolator);
tv_Decelerate.startAnimation(animation7);
Animation animation8 = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,0,Animation.RELATIVE_TO_PARENT,0.5f,
Animation.RELATIVE_TO_PARENT,0,Animation.RELATIVE_TO_PARENT,0);
animation8.setDuration(3000);
animation8.setFillAfter(true);
animation8.setInterpolator(InterpolatorsActivity.this,linear_interpolator);
tv_Linear.startAnimation(animation8);
Animation animation9 = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,0,Animation.RELATIVE_TO_PARENT,0.5f,
Animation.RELATIVE_TO_PARENT,0,Animation.RELATIVE_TO_PARENT,0);
animation9.setDuration(3000);
animation9.setFillAfter(true);
animation9.setInterpolator(InterpolatorsActivity.this,overshoot_interpolator);
tv_Overshoot.startAnimation(animation9);
}
});
}
}
| true |
6608cbe686919c3dd21c40c2012a490563460a5b | Java | indrajra/certificate-registry | /service/test/validators/CertDownloadRequestValidatorTest.java | UTF-8 | 1,224 | 1.929688 | 2 | [
"MIT"
] | permissive | package validators;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.sunbird.BaseException;
import org.sunbird.JsonKeys;
import org.sunbird.request.Request;
import utils.JsonKey;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
public class CertDownloadRequestValidatorTest {
private Request request;
private IRequestValidator requestValidator;
private Map<String, Object> reqMap;
@Before
public void setUp(){
reqMap= new HashMap<>();
request = new Request();
request.setRequest(reqMap);
requestValidator=new CertDownloadRequestValidator();
}
@After
public void tearDown(){
requestValidator=null;
reqMap.clear();
request=null;
}
@Test(expected = BaseException.class)
public void testValidateWhenMandatoryParamMissing() throws BaseException {
requestValidator.validate(request);
}
@Test(expected = Test.None.class)
public void testValidateWhenMandatoryParamIsPresent() throws BaseException {
reqMap.put(JsonKeys.PDF_URL,"/pdf_uRL");
request.setRequest(reqMap);
requestValidator.validate(request);
}
} | true |
26239cbfd947c708035515b70a3c3dbd3ace35a2 | Java | joy-sec/Task1 | /app/src/main/java/net/apkkothon/tourkit/AllPlaceActivity.java | UTF-8 | 9,323 | 1.929688 | 2 | [] | no_license | package net.apkkothon.tourkit;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import net.apkkothon.tourkit.adapters.HomeAdapter;
import net.apkkothon.tourkit.models.Place;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class AllPlaceActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private ArrayAdapter adapter,unit_adapter;
private Spinner state,city;
private RecyclerView recyclerView;
private Button filter;
private String str_division,str_district;
private HomeAdapter homeAdapter;
private List<Place> list=new ArrayList<>();
private LinearLayout linearLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_place);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
linearLayout=(LinearLayout) findViewById(R.id.llayout);
linearLayout.setVisibility(View.GONE);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
linearLayout.setVisibility(View.VISIBLE);
}
});
filter=(Button)findViewById(R.id.filter);
recyclerView=(RecyclerView)findViewById(R.id.recyclerView);
homeAdapter=new HomeAdapter(this,list);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.setAdapter(homeAdapter);
state=(Spinner)findViewById(R.id.spinner);
city= (Spinner) findViewById(R.id.spinner1);
state.setOnItemSelectedListener(this);
adapter=ArrayAdapter.createFromResource(this,R.array.State_array,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(R.layout.spinner_item);
state.setAdapter(adapter);
city.setOnItemSelectedListener(this);
filter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
filterData();
}
});
parseData();
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int pos;
pos=state.getSelectedItemPosition();
int iden=parent.getId();
if(iden==R.id.spinner)
{
str_division=state.getSelectedItem().toString();
switch (pos)
{
case 0:unit_adapter=ArrayAdapter.createFromResource(
this,R.array.Dhaka_array_filter,android.R.layout.simple_spinner_item
);
break;
case 1:unit_adapter=ArrayAdapter.createFromResource(
this,R.array.Chittagong_array_filter,android.R.layout.simple_spinner_item
);
break;
case 2:unit_adapter=ArrayAdapter.createFromResource(
this,R.array.Rajshashi_array_filter,android.R.layout.simple_spinner_item
);
break;
case 3:unit_adapter=ArrayAdapter.createFromResource(
this,R.array.Sylhet_array_filter,android.R.layout.simple_spinner_item
);
break;
case 4:unit_adapter=ArrayAdapter.createFromResource(
this,R.array.Barishal_array_filter,android.R.layout.simple_spinner_item
);
break;
case 5:unit_adapter=ArrayAdapter.createFromResource(
this,R.array.Khulna_array_filter,android.R.layout.simple_spinner_item
);
break;
case 6:unit_adapter=ArrayAdapter.createFromResource(
this,R.array.Rangpur_array_filter,android.R.layout.simple_spinner_item
);
break;
case 7:unit_adapter=ArrayAdapter.createFromResource(
this,R.array.Mymensingh_array_filter,android.R.layout.simple_spinner_item
);
break;
default:
break;
}
city.setAdapter(unit_adapter);
unit_adapter.setDropDownViewResource(R.layout.spinner_item);
}
str_district=city.getSelectedItem().toString();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
private void parseData(){
recyclerView.removeAllViews();
list.clear();
JsonArrayRequest jsonArrayRequest =new JsonArrayRequest("http://apkkothon.net/tour/all-place-json.php", new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length();i++){
try {
JSONObject jsonObject= (JSONObject) response.get(i);
Place place=new Place();
place.setPlaceName(jsonObject.getString("name"));
place.setPlaceDetails(jsonObject.getString("details"));
place.setPlaceDistrict(jsonObject.getString("district"));
place.setPlaceImage(jsonObject.getString("url"));
place.setPostID(jsonObject.getString("id"));
place.setPlaceDivision(jsonObject.getString("division"));
place.setPlaceLat(jsonObject.getString("lat"));
place.setPlaceLon(jsonObject.getString("lon"));
list.add(place);
homeAdapter.notifyItemChanged(i);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(this).add(jsonArrayRequest);
}
private void filterData(){
recyclerView.removeAllViews();
list.clear();
System.out.println(str_district+str_division);
StringRequest request = new StringRequest(Request.Method.POST, "http://apkkothon.net/tour/filter.php", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
System.out.println(response);
try {
JSONArray jsonArray=new JSONArray(response);
for (int i=0;i<jsonArray.length();i++){
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
Place place = new Place();
place.setPlaceName(jsonObject.getString("name"));
place.setPlaceDetails(jsonObject.getString("details"));
place.setPlaceDistrict(jsonObject.getString("district"));
place.setPlaceImage(jsonObject.getString("url"));
place.setPostID(jsonObject.getString("id"));
place.setPlaceDivision(jsonObject.getString("division"));
place.setPlaceLat(jsonObject.getString("lat"));
place.setPlaceLon(jsonObject.getString("lon"));
list.add(place);
homeAdapter.notifyItemChanged(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params=new HashMap<>();
params.put("post_div",str_division);
params.put("post_dis",str_district);
return params;
}
};
Volley.newRequestQueue(this).add(request);
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
}
| true |
dc9cf5a34f834b9f9e38e7a4668ad880cf15e1d6 | Java | vprooks/urgLibJavaWrapper | /src/main/java/com/vprooks/urgLibJavaWrapper/urg_t.java | UTF-8 | 2,816 | 1.648438 | 2 | [
"BSD-2-Clause"
] | permissive | package com.vprooks.urgLibJavaWrapper;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import java.util.Arrays;
import java.util.List;
/**
* <i>native declaration : urg_sensor.h</i><br>
* This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br>
* a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br>
* For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>.
*/
public class urg_t extends Structure {
public int is_active;
public int last_errno;
/**
* C type : urg_connection_t
*/
public urg_connection_t connection;
public int first_data_index;
public int last_data_index;
public int front_data_index;
public int area_resolution;
public NativeLong scan_usec;
public int min_distance;
public int max_distance;
public int scanning_first_step;
public int scanning_last_step;
public int scanning_skip_step;
public int scanning_skip_scan;
/**
* @see UrgLib.urg_range_data_byte_t
* C type : urg_range_data_byte_t
*/
public int range_data_byte;
public int timeout;
public int specified_scan_times;
public int scanning_remain_times;
public int is_laser_on;
public int received_first_index;
public int received_last_index;
public int received_skip_step;
/**
* @see UrgLib.urg_range_data_byte_t
* C type : urg_range_data_byte_t
*/
public int received_range_data_byte;
public int is_sending;
/**
* C type : urg_error_handler
*/
public UrgLib.urg_error_handler error_handler;
/**
* C type : char[80]
*/
public byte[] return_buffer = new byte[80];
public urg_t() {
super();
}
protected List<?> getFieldOrder() {
return Arrays.asList("is_active", "last_errno", "connection", "first_data_index", "last_data_index", "front_data_index", "area_resolution", "scan_usec", "min_distance", "max_distance", "scanning_first_step", "scanning_last_step", "scanning_skip_step", "scanning_skip_scan", "range_data_byte", "timeout", "specified_scan_times", "scanning_remain_times", "is_laser_on", "received_first_index", "received_last_index", "received_skip_step", "received_range_data_byte", "is_sending", "error_handler", "return_buffer");
}
public urg_t(Pointer peer) {
super(peer);
}
public static class ByReference extends urg_t implements Structure.ByReference {
}
public static class ByValue extends urg_t implements Structure.ByValue {
}
}
| true |
82cbca546996658df074a0f248a5985b600f5c72 | Java | leosimoez/shop | /src/main/java/br/com/lm/shop/entities/BasicAddress.java | UTF-8 | 1,735 | 2.390625 | 2 | [] | no_license | package br.com.lm.shop.entities;
import javax.persistence.Column;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.MappedSuperclass;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonView;
import br.com.lm.shop.view.ViewLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@MappedSuperclass
@Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString(callSuper=true)
@JsonView(ViewLevel.Public.class)
public abstract class BasicAddress extends BasicEntity {
private static final long serialVersionUID = 1L;
@Column(name="ADDRESS_TYPE", nullable=false, length=20)
@Enumerated(EnumType.STRING)
@NotNull
protected AddressType type;
@Column(name="LINE1", nullable=false, length=100)
@NotEmpty @Size(min=3, max=100)
protected String line1;
@Column(name="LINE2", nullable=true, length=100)
@Size(min=3, max=100)
protected String line2;
@Column(name="LINE3", nullable=true, length=100)
@Size(min=3, max=100)
protected String line3;
@Column(name="CITY", nullable=false, length=100)
@NotEmpty @Size(min=3, max=100)
protected String city;
@Column(name="STATE", nullable=false, length=100)
@NotEmpty @Size(min=2, max=3)
protected String state;
@Column(name="COUNTRY", nullable=false, length=100)
@NotEmpty @Size(min=3, max=100)
protected String country;
@Column(name="ZIP_CODE", nullable=false, length=100)
@NotEmpty @Pattern(regexp="^(\\d{5}\\-\\d{3})$")
protected String zipCode;
}
| true |
0c247f5bd4471915e0983eed3bea7b96bc9f3ac7 | Java | arcanine525/Android | /AndroidDemo1/app/src/main/java/com/example/windows10timt/androiddemo1/MainActivity.java | UTF-8 | 2,264 | 2.515625 | 3 | [] | no_license | package com.example.windows10timt.androiddemo1;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText passwordEdt, userNameEdt;
private Button logInBtn, signUpBtn;
private TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
passwordEdt = (EditText) findViewById(R.id.password);
userNameEdt = (EditText) findViewById(R.id.userName);
logInBtn = (Button) findViewById(R.id.logInBtn);
signUpBtn = (Button) findViewById(R.id.signUpBtn);
text = (TextView) findViewById(R.id.text123);
View.OnClickListener click = new View.OnClickListener() {
@Override
public void onClick(View v) {
int id = v.getId();
String userName = userNameEdt.getText().toString();
String password = passwordEdt.getText().toString();
switch (id) {
case R.id.signUpBtn:
Toast.makeText(MainActivity.this, "Sign Up", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, SignUp.class);
intent.putExtra("x", userName);
intent.putExtra("y", password);
startActivity(intent);
break;
case R.id.logInBtn:
if (password.equals("a")) {
Toast.makeText(MainActivity.this, "Successfull", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
text.setText(userName + password);
break;
}
}
};
logInBtn.setOnClickListener(click);
signUpBtn.setOnClickListener(click);
}
}
| true |
09b270737cdc615a8ba6d86be7c5323f599ea3ab | Java | premiumMina/AlgorithmPractice | /src/acmicpc/Q1305.java | UTF-8 | 661 | 3.078125 | 3 | [] | no_license | package acmicpc;
import java.io.IOException;
import java.util.Scanner;
public class Q1305 {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String str = sc.next();
int m = str.length();
int[] pi = getPi(str);
System.out.println(n - pi[m - 1]);
}
private static int[] getPi(String pattern) {
int m = pattern.length();
int j = 0;
char[] p = new char[m];
int[] pi = new int[m];
p = pattern.toCharArray();
for (int i = 1; i < m; i++) {
while (j > 0 && p[i] != p[j]) {
j = pi[j - 1];
}
if (p[i] == p[j]) {
pi[i] = ++j;
}
}
return pi;
}
} | true |
824e2c25b5063d19e7fec83485a9313ce326c971 | Java | 13525846841/ConSonP | /app/src/main/java/com/yksj/consultation/son/consultation/CommonwealAidAty.java | UTF-8 | 6,208 | 1.90625 | 2 | [] | no_license | package com.yksj.consultation.son.consultation;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import com.yksj.consultation.comm.BaseFragmentActivity;
import com.yksj.consultation.son.R;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.utils.HStringUtil;
import com.yksj.healthtalk.utils.ToastUtil;
/**
* Created by HEKL on 16/5/6.
* Used for
*/
public class CommonwealAidAty extends BaseFragmentActivity implements View.OnClickListener {
public static final String URL = "url";
public static final String TITLE = "TITLE";
private WebView mWebView;
String url = "";
public static final String TYPE = "type";
private String type = "";//加载类型 1名医名院
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.aty_commonwealaid);
initView();
}
private void initView() {
initTitle();
if (getIntent().hasExtra(TYPE)) {
type = getIntent().getStringExtra(TYPE);
}
titleLeftBtn.setVisibility(View.VISIBLE);
titleLeftBtn.setOnClickListener(this);
titleRightBtn.setVisibility(View.VISIBLE);
titleRightBtn.setText("复制");
titleRightBtn.setOnClickListener(this);
if (getIntent().hasExtra(TITLE))
titleTextV.setText(getIntent().getStringExtra(TITLE));
if (getIntent().hasExtra(URL))
url = getIntent().getStringExtra(URL);
mWebView = (WebView) findViewById(R.id.wv_web);
final ProgressBar bar = (ProgressBar) findViewById(R.id.myProgressBar);
mWebView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress == 100) {
bar.setVisibility(View.INVISIBLE);
} else {
if (View.INVISIBLE == bar.getVisibility()) {
bar.setVisibility(View.VISIBLE);
}
bar.setProgress(newProgress);
}
super.onProgressChanged(view, newProgress);
}
});
setWebStyle();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.title_back:
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
onBackPressed();
}
break;
case R.id.title_right:
copyWord();
break;
}
}
private void copyWord() {
ClipboardManager myClipboard;
myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData myClip;
myClip = ClipData.newPlainText("text", url);//text是内容
myClipboard.setPrimaryClip(myClip);
ToastUtil.showShort("复制成功,可以发给朋友们了");
}
/**
* WebView设置
*/
private void setWebStyle() {
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setSupportMultipleWindows(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.requestFocus();
if (HStringUtil.isEmpty(url)) {
url = HttpRestClient.getmHttpUrls().PUBLICDONATE;
}
if (!url.startsWith("http")) {
mWebView.loadUrl("https://" + url);
} else {
mWebView.loadUrl(url);
}
mWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//重写此方法表明点击网页里面的链接还是在当前的webview里跳转,不跳到浏览器那边
// view.loadUrl(url);
switch (type) {
case "1":
if (url.startsWith("tel")) {//六一健康
if (hasSimCard()) {
Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));//跳转到拨号界面,同时传递电话号码
startActivity(dialIntent);
} else {
ToastUtil.showShort("请检查sim卡");
}
} else {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
break;
default:
view.loadUrl(url);
break;
}
return true;
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* @return
*/
public boolean hasSimCard() {
TelephonyManager telMgr = (TelephonyManager)
CommonwealAidAty.this.getSystemService(Context.TELEPHONY_SERVICE);
int simState = telMgr.getSimState();
boolean result = true;
switch (simState) {
case TelephonyManager.SIM_STATE_ABSENT:
result = false; // 没有SIM卡
break;
case TelephonyManager.SIM_STATE_UNKNOWN:
result = false;
break;
}
return result;
}
}
| true |
8c0c3ba51be29f4a79707bae5a81258bba96891d | Java | majian1234554321/WhereToPlay | /WhereToPlay/app/src/main/java/com/fanc/wheretoplay/adapter/HotCityAdapter.java | UTF-8 | 1,741 | 2.171875 | 2 | [] | no_license | package com.fanc.wheretoplay.adapter;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.fanc.wheretoplay.R;
import com.fanc.wheretoplay.base.BaseAdapter;
import com.fanc.wheretoplay.databinding.ItemCityHotGridviewBinding;
import com.fanc.wheretoplay.datamodel.CityResource;
import java.util.List;
/**
* Created by Administrator on 2017/6/21.
*/
public class HotCityAdapter extends BaseAdapter {
/**
* 构造方法
*
* @param context
* @param data
*/
public HotCityAdapter(Context context, List data) {
super(context, data);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
ItemCityHotGridviewBinding binding = DataBindingUtil.inflate(LayoutInflater.from(getContext()),
R.layout.item_city_hot_gridview, parent, false);
convertView = binding.getRoot();
holder = new ViewHolder(binding);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
CityResource.City city = (CityResource.City) getItem(position);
holder.binding.setCity(city);
return convertView;
}
static class ViewHolder {
ItemCityHotGridviewBinding binding;
// TextView mTvCityName;
public ViewHolder(ViewDataBinding binding) {
this.binding = (ItemCityHotGridviewBinding) binding;
// mTvCityName = this.binding.tvHotCityName;
}
}
}
| true |
a5c9e912cd378119072fc0dda4e3c726e5b50c5b | Java | dovanduy/WechatSimulation | /app/src/main/java/com/lcjian/wechatsimulation/job/foreground/RegisterOMarketJob.java | UTF-8 | 12,685 | 1.75 | 2 | [] | no_license | package com.lcjian.wechatsimulation.job.foreground;
import android.accessibilityservice.AccessibilityService;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.telephony.SmsMessage;
import android.view.accessibility.AccessibilityEvent;
import com.lcjian.wechatsimulation.utils.accessibility.AccessibilityNodeInfoUtils;
import com.lcjian.wechatsimulation.utils.accessibility.ClassNameNodeFilter;
import com.lcjian.wechatsimulation.utils.accessibility.TextNodeFilter;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import timber.log.Timber;
/**
* 注册OMarket 2016-11-30 completed
*
* @author LCJ
*/
public class RegisterOMarketJob extends OMarketJob {
private static final int STATE_NONE = 0;
private static final int STATE_MAIN = 1;
private static final int STATE_LOGIN = 2;
private static final int STATE_REGISTER = 3;
private static final int STATE_PHONE_INPUTTED = 4;
private static final int STATE_CODE_SENT = 5;
private static final int STATE_CODE_INPUTTED = 6;
private static final int STATE_SET_PWD = 7;
private int mState = STATE_NONE;
private BroadcastReceiver mSmsObserver;
@Override
public void doWithEvent(AccessibilityService service, AccessibilityEvent event) {
super.doWithEvent(service, event);
if (mSmsObserver == null) {
mSmsObserver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
try {
Object[] pdu = (Object[]) bundle.get("pdus");
if (pdu != null) {
for (Object aPdu : pdu) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) aPdu);
String messageBody = smsMessage.getMessageBody();
Pattern pattern = Pattern.compile("验证码是:([0-9]{4,})");
Matcher matcher = pattern.matcher(messageBody);
if (matcher.find()) {
Observable.just(matcher.group(1))
.delay(3, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<String>() {
@Override
public void call(String string) {
((ClipboardManager) mService.getSystemService(Context.CLIPBOARD_SERVICE)).setPrimaryClip(ClipData.newPlainText("code", string));
AccessibilityNodeInfoUtils.searchFromBfs(mService, mRootNodeInfoCompat,
new ClassNameNodeFilter("android.widget.EditText")).performAction(AccessibilityNodeInfoCompat.ACTION_PASTE);
}
}, mAction1Throwable);
break;
}
}
}
} catch (Exception e) {
notifyError(e);
}
}
}
}
};
mService.registerReceiver(mSmsObserver, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
addJobListener(new JobListener() {
@Override
public void onCancelled() {
if (mSmsObserver != null) {
mService.unregisterReceiver(mSmsObserver);
mSmsObserver = null;
}
}
@Override
public void onFinished() {
if (mSmsObserver != null) {
mService.unregisterReceiver(mSmsObserver);
mSmsObserver = null;
}
}
@Override
public void onError(Throwable t) {
if (mSmsObserver != null) {
mService.unregisterReceiver(mSmsObserver);
mSmsObserver = null;
}
}
});
}
try {
handleRegister();
} catch (Exception e) {
notifyError(e);
}
Timber.d("state:%d", mState);
}
private void handleRegister() {
if (mEventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
AccessibilityNodeInfoCompat pass = AccessibilityNodeInfoUtils.searchFromBfs(mService, mRootNodeInfoCompat, new TextNodeFilter("跳过"));
if (pass != null) {
AccessibilityNodeInfoUtils.getSelfOrMatchingAncestor(mService, pass,
AccessibilityNodeInfoUtils.FILTER_CLICKABLE).performAction(AccessibilityNodeInfoCompat.ACTION_CLICK);
}
}
if (mState == STATE_NONE
&& mEventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
&& "com.oppo.market.activity.MainMenuActivity".equals(mEventClassName)) {
mState = STATE_MAIN;
Observable.just(true).delay(2, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.map(new Func1<Boolean, Boolean>() {
@Override
public Boolean call(Boolean aBoolean) {
AccessibilityNodeInfoUtils.getSelfOrMatchingAncestor(mService,
AccessibilityNodeInfoUtils.searchFromBfs(mService, mRootNodeInfoCompat, new TextNodeFilter("我")),
AccessibilityNodeInfoUtils.FILTER_CLICKABLE).performAction(AccessibilityNodeInfoCompat.ACTION_CLICK);
return aBoolean;
}
})
.delay(3, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean aBoolean) {
AccessibilityNodeInfoUtils.getSelfOrMatchingAncestor(mService,
AccessibilityNodeInfoUtils.searchFromBfs(mService, mRootNodeInfoCompat, new TextNodeFilter("点击登录")),
AccessibilityNodeInfoUtils.FILTER_CLICKABLE).performAction(AccessibilityNodeInfoCompat.ACTION_CLICK);
}
}, mAction1Throwable);
} else if (mState == STATE_MAIN
&& mEventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
&& "com.nearme.ucplugin.activity.LoginActivity".equals(mEventClassName)) {
mState = STATE_LOGIN;
AccessibilityNodeInfoUtils.getSelfOrMatchingAncestor(mService,
AccessibilityNodeInfoUtils.searchFromBfs(mService, mRootNodeInfoCompat, new TextNodeFilter("注册新帐号")),
AccessibilityNodeInfoUtils.FILTER_CLICKABLE).performAction(AccessibilityNodeInfoCompat.ACTION_CLICK);
} else if (mState == STATE_LOGIN
&& mEventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
&& "com.nearme.ucplugin.activity.RegGetVerifyCodeActivity".equals(mEventClassName)) {
mState = STATE_REGISTER;
Observable.just(true).delay(2, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean aBoolean) {
((ClipboardManager) mService.getSystemService(Context.CLIPBOARD_SERVICE)).setPrimaryClip(ClipData.newPlainText("phone_no", getJobData().phoneNoOMarket));
AccessibilityNodeInfoUtils.searchFromBfs(mService, mRootNodeInfoCompat,
new ClassNameNodeFilter("android.widget.EditText")).performAction(AccessibilityNodeInfoCompat.ACTION_PASTE);
}
}, mAction1Throwable);
} else if (mState == STATE_REGISTER
&& mEventType == AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
&& "android.widget.EditText".equals(mEventClassName)) {
mState = STATE_PHONE_INPUTTED;
AccessibilityNodeInfoUtils.getSelfOrMatchingAncestor(mService,
AccessibilityNodeInfoUtils.searchFromBfs(mService, mRootNodeInfoCompat, new TextNodeFilter("获取验证码")),
AccessibilityNodeInfoUtils.FILTER_CLICKABLE).performAction(AccessibilityNodeInfoCompat.ACTION_CLICK);
} else if (mState == STATE_PHONE_INPUTTED
&& mEventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
&& "com.nearme.ucplugin.activity.RegSendVerifyCodeActivity".equals(mEventClassName)) {
mState = STATE_CODE_SENT;
} else if (mState == STATE_CODE_SENT
&& mEventType == AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
&& "android.widget.EditText".equals(mEventClassName)) {
mState = STATE_CODE_INPUTTED;
AccessibilityNodeInfoUtils.getSelfOrMatchingAncestor(mService,
AccessibilityNodeInfoUtils.searchFromBfs(mService, mRootNodeInfoCompat, new TextNodeFilter("提交验证码")),
AccessibilityNodeInfoUtils.FILTER_CLICKABLE).performAction(AccessibilityNodeInfoCompat.ACTION_CLICK);
} else if (mState == STATE_CODE_INPUTTED
&& mEventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
&& "com.nearme.ucplugin.activity.RegSendPasswordActivity".equals(mEventClassName)) {
mState = STATE_SET_PWD;
Observable.just(true).delay(2, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean aBoolean) {
((ClipboardManager) mService.getSystemService(Context.CLIPBOARD_SERVICE)).setPrimaryClip(ClipData.newPlainText("password", getJobData().passwordOMarket));
AccessibilityNodeInfoUtils.searchFromBfs(mService, mRootNodeInfoCompat,
new ClassNameNodeFilter("android.widget.EditText")).performAction(AccessibilityNodeInfoCompat.ACTION_PASTE);
}
}, mAction1Throwable);
} else if (mState == STATE_SET_PWD
&& mEventType == AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
&& "android.widget.EditText".equals(mEventClassName)) {
Observable.just(true).delay(3, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean aBoolean) {
AccessibilityNodeInfoUtils.getSelfOrMatchingAncestor(mService,
AccessibilityNodeInfoUtils.searchFromBfs(mService, mRootNodeInfoCompat, new TextNodeFilter("完成")),
AccessibilityNodeInfoUtils.FILTER_CLICKABLE).performAction(AccessibilityNodeInfoCompat.ACTION_CLICK);
notifyFinish();
}
}, mAction1Throwable);
}
}
}
| true |
0105f9dd40f66443a12e25a4d1d3654f9e3c759e | Java | Fikri1234/Springboot-Oauth-JUnit | /src/main/java/com/project/buku/Configuration/WebServerConfiguration.java | UTF-8 | 2,412 | 2.109375 | 2 | [] | no_license | /**
*
*/
package com.project.buku.Configuration;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
/**
* @author Fikri
*
*/
@Configuration
@EnableWebSecurity
@Import(Encoder.class)
public class WebServerConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private PasswordEncoder userPasswordEncoder;
@Autowired
@Qualifier("dataSource")
private DataSource dataSource;
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
auth.userDetailsService(userDetailsService).passwordEncoder(userPasswordEncoder);
}
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Bean
@Primary
//Making this primary to avoid any accidental duplication with another token service instance of the same name
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
defaultTokenServices.setSupportRefreshToken(true);
return defaultTokenServices;
}
}
| true |
eb3b0571766e67bfb42bebe6fb9d38274f7038a0 | Java | bnegrao/minesweeper-api | /src/main/java/com/zica/minesweeper/game/Board.java | UTF-8 | 9,593 | 3.25 | 3 | [
"CC0-1.0"
] | permissive | package com.zica.minesweeper.game;
import org.springframework.data.annotation.PersistenceConstructor;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
public class Board {
private final int nRows;
private final int nColumns;
private final int nMines;
private int unarmedClosedCellsCounter;
private final TreeMap<Position, Cell> cellTree;
public Board (int nRows, int nColumns, int nMines) {
this.nRows = nRows;
this.nColumns = nColumns;
this.nMines = nMines;
this.cellTree = populateBoard(getRandomizedMinePositions(nRows, nColumns, nMines));
this.unarmedClosedCellsCounter = ( nRows * nColumns ) - nMines;
}
/**
* Creates a Board with mines at fixed places (i.e., not random)
* what enables the creation of precise unit tests.
* This constructor isn't public because it is not meant to be used for
* the creating of real games.
*/
Board (int nRows, int nColumns, Set<Position> minePositions) {
this.nRows = nRows;
this.nColumns = nColumns;
this.nMines = minePositions.size();
this.cellTree = populateBoard(minePositions);
this.unarmedClosedCellsCounter = ( nRows * nColumns ) - nMines;
}
@PersistenceConstructor
protected Board (int nRows, int nColumns, int nMines, int unarmedClosedCellsCounter, TreeMap<Position, Cell> cellTree){
this.nRows = nRows;
this.nColumns = nColumns;
this.nMines = nMines;
this.unarmedClosedCellsCounter = unarmedClosedCellsCounter;
this.cellTree = cellTree;
}
public int getnRows() {
return nRows;
}
public int getnColumns() {
return nColumns;
}
public int getnMines() {
return nMines;
}
/**
* @return The Cells in this Board in proper order.
*/
public Cell[][] getCells2D() {
Cell[][] cellsArr = new Cell[nRows][nColumns];
for (int row = 0; row < nRows; row++) {
for (int column = 0; column < nColumns; column++) {
cellsArr[row][column] = cellTree.get(new Position(row, column));
}
}
return cellsArr;
}
public Collection<Cell> getCellsFlat(){
return cellTree.values();
}
public ToggleFlagResult toggleFlagAt(Position position, Cell.Flags flag) {
Cell cell = cellTree.get(position);
if (cell == null){
return ToggleFlagResult.INVALID_POSITION;
}
if (!cell.isClosed()) {
return ToggleFlagResult.NO_CHANGE;
}
if (cell.getFlag() == flag) {
cell.setFlag(null);
return ToggleFlagResult.UNSET;
} else {
cell.setFlag(flag);
return ToggleFlagResult.SET;
}
}
/**
* convenience method that creates a Position instance and invokes openCellAt(Position)
*/
public OpenCellResult openCellAt(int row, int column) {
return this.openCellAt(new Position(row, column));
}
/**
* Opens the Cell at the given Position, performs extra logic that can open other cells,
* then returns a OPEN_CELL_RESULT to indicate what happened.
*
* Valid ranges for Position coordinates are from 0 to nRows-1 and 0 to nColumns-1
*
* @param position of the cell that should be opened
* @return OPEN_CELL_RESULT
*/
public OpenCellResult openCellAt(Position position) {
Cell cell = cellTree.get(position);
if (cell == null){
return OpenCellResult.INVALID_POSITION;
}
if (!cell.isClosed()) {
return OpenCellResult.NO_CHANGE;
} else if (cell.isMine()) {
openAllCells();
return OpenCellResult.IS_A_MINE;
} else {
if (cell.getAdjacentMines() == 0) {
openCellsWithNoAdjacentMines(cell);
} else {
cell.setClosed(false);
unarmedClosedCellsCounter--;
}
if (unarmedClosedCellsCounter == 0){
openAllCells();
return OpenCellResult.BOARD_COMPLETE;
}
return OpenCellResult.OPENED_OK;
}
}
/**
* @return Counter of Cells in this Board that are closed and "unarmed", i.e., don't hold a mine.
* The counter is updated during each openCellAt() invocation.
*/
public int getUnarmedClosedCellsCounter(){
return unarmedClosedCellsCounter;
}
private void openCellsWithNoAdjacentMines(Cell startCell){
TreeSet<Position> stack = new TreeSet<>();
stack.add(startCell.getPosition());
while (!stack.isEmpty()){
Cell cell = this.cellTree.get(stack.pollFirst());
if (cell.isClosed()){
cell.open();
unarmedClosedCellsCounter--;
if (cell.getAdjacentMines()==0){
for (Cell adjCell: getAdjacentClosedUnarmedCells(cell.getPosition())){
stack.add(adjCell.getPosition());
}
}
} else {
throw new RuntimeException("Bug! Cell at position "+ cell.getPosition() + " should be closed");
}
}
}
private List<Cell> getAdjacentClosedUnarmedCells(Position position){
List<Cell> adjacentClosedCells = new LinkedList<>();
for (Position adjPosition: getAdjacentPositions(position)){
Cell adjCell = cellTree.get(adjPosition);
if (adjCell.isClosed() && !adjCell.isMine()){
adjacentClosedCells.add(adjCell);
}
}
return adjacentClosedCells;
}
private void openAllCells() {
for (Cell cell: cellTree.values()){
cell.open();
}
}
private TreeMap<Position, Cell> populateBoard(Set<Position> minePositions) {
TreeMap<Position, Cell> treeMap = new TreeMap<>();
for (int row = 0; row < nRows; row++) {
for (int column = 0; column < nColumns; column++) {
Position position = new Position(row, column);
boolean isMine = minePositions.contains(position);
int adjacentMinesCounter = countAdjacentMines(position, minePositions);
Cell cell = new Cell(row, column, isMine, adjacentMinesCounter);
treeMap.put(position, cell);
}
}
return treeMap;
}
public String toAsciiArt() {
StringBuilder str = new StringBuilder();
for (Cell cell: cellTree.values()){
String art;
if (!cell.isClosed()) {
if (!cell.isMine()) {
art = cell.getAdjacentMines() == 0 ? "." : Integer.toString(cell.getAdjacentMines());
} else {
art = "@"; // this is a bomb
}
} else {
if (cell.getFlag() == null) {
art = "X";
} else {
if (cell.getFlag() == Cell.Flags.MINE) {
art = "@";
} else {
art = "?";
}
}
}
str.append(art);
str.append(" ");
if (cell.getPosition().getColumn() == nColumns - 1) {
str.append("\n");
}
}
return str.toString();
}
private List<Position> getAdjacentPositions(Position position) {
int r = position.getRow();
int c = position.getColumn();
Position topLeft = new Position(r - 1, c - 1);
Position topCenter = new Position(r - 1, c);
Position topRight = new Position(r - 1, c + 1);
Position left = new Position(r, c - 1);
Position right = new Position(r, c + 1);
Position bottomLeft = new Position(r + 1, c - 1);
Position bottomCenter = new Position( r + 1, c);
Position bottomRight = new Position( r + 1, c + 1);
Position[] possibleAdjacentPositions = new Position[]{topLeft, topCenter, topRight, left, right, bottomLeft, bottomCenter, bottomRight};
List<Position> adjacentPositions = new LinkedList<>();
for (Position possiblePosition: possibleAdjacentPositions) {
int adjRow = possiblePosition.getRow();
int adjCol = possiblePosition.getColumn();
if ( adjRow >= 0 && adjRow < this.nRows && adjCol >= 0 && adjCol < this.nColumns ) {
adjacentPositions.add(new Position(adjRow, adjCol));
}
}
return adjacentPositions;
}
private int countAdjacentMines(Position position, Set<Position> minePositions) {
int counter = 0;
for (Position adjacentPosition: getAdjacentPositions(position)) {
if (minePositions.contains(adjacentPosition)) counter++;
}
return counter;
}
private static Set<Position> getRandomizedMinePositions(int nRows, int nColumns, int nMines) {
Set<Position> randomPositions = new HashSet<>();
for (int i = 0; i<nMines; i++){
int randomRow = ThreadLocalRandom.current().nextInt(0, nRows);
int randomCol = ThreadLocalRandom.current().nextInt(0, nColumns);
Position randomPosition = new Position(randomRow, randomCol);
if (randomPositions.contains(randomPosition)){
i--;
} else {
randomPositions.add(randomPosition);
}
}
return randomPositions;
}
}
| true |
1890487a7ba064cfe6bb60ea6b96119945420714 | Java | e7san99/Guess-Game | /Main.java | UTF-8 | 4,377 | 3.0625 | 3 | [
"MIT"
] | permissive | package com.company;
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class Main {
private static JFrame frame;
private static JPanel panel;
private static JLabel lgs, result, footer;
private static ImageIcon imageIcon, scaledIcon;
private static Image image,modify;
private static JTextField textField;
private static JButton button, reset;
private static int number, enterValue;
private static int count = 0;
private static Random random;
public static void main(String[] args) {
panel = new JPanel();
panel.setLayout(null);
frame = new JFrame();
frame.setTitle("Guess Game");
frame.setSize(350,400);
frame.add(panel);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
random = new Random();
number = random.nextInt(10)+1;
image();
textfield();
button();
footer();
frame.setVisible(true);
} //End Main Class
private static void image() {
lgs = new JLabel(); //lgs = lets get started
lgs.setBounds(55,20,220,150);
panel.add(lgs);
imageIcon = new ImageIcon("C:\\Users\\LENOVO\\IdeaProjects\\Guess Game\\src\\com\\company\\gg.png");
image = imageIcon.getImage();
modify = image.getScaledInstance(lgs.getWidth(), lgs.getHeight(), Image.SCALE_SMOOTH);
scaledIcon = new ImageIcon(modify);
lgs.setIcon(scaledIcon);
}
private static void textfield() {
textField = new JTextField();
textField.setBounds(110,220,100,50);
textField.setFont(new Font("Tahoma",Font.ITALIC,20));
textField.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(textField);
}
private static void button() {
button = new JButton("check");
button.setBounds(120,300,80,20);
button.addActionListener(e -> {
try {
enterValue = Integer.parseInt(textField.getText());
if (enterValue > number)
JOptionPane.showMessageDialog(null, "Less than this Number");
else if (enterValue < number)
JOptionPane.showMessageDialog(null, "More than this Number");
if (enterValue == number) {
JOptionPane.showMessageDialog(null, "Congratulation.!");
reSet(random);
result("Success");
result.setFont(new Font("Tahoma", Font.ITALIC,20));
panel.add(result);
textField.setEnabled(false);
button.setEnabled(false);
}
}catch (Throwable ex) {
JOptionPane.showMessageDialog(null, "Enter a Number");
}
count();
});
panel.add(button);
}
private static void reSet(Random random) {
reset = new JButton("Reset");
reset.setBounds(230,250,70,18);
reset.addActionListener(e->{
count=-1;
count();
number = random.nextInt(5)+1;
textField.setEnabled(true);
textField.setText(null);
button.setEnabled(true);
footer.setVisible(true);
result.setText(null);
reset.setVisible(false);
});
panel.add(reset);
}
private static void count() {
count++;
if (count==3 && enterValue !=number) {
JOptionPane.showMessageDialog(null, "You're Failed");
textField.setEnabled(false);
button.setEnabled(false);
reSet(random);
result("Failed");
result.setFont(new Font("Tahoma", Font.ITALIC,20));
panel.add(result);
}
if (count==1) {
footer.setVisible(false);
}
}
private static void result(String text) {
result = new JLabel(text);
result.setBounds(125,185,80,20);
panel.add(result);
}
private static void footer() {
footer = new JLabel("Enter Number Between 1 to 10");
footer.setBounds(70, 185, 200, 20);
panel.add(footer);
}
} | true |
3dedfc975380f00350e1a4a15e86303f5cf00403 | Java | Marija26/Java_for_interview | /src/com/company/Lesson09/Test01.java | UTF-8 | 1,097 | 3.21875 | 3 | [] | no_license | package com.company.Lesson09;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ПК on 29.09.2016.
*/
public class Test01 {
public static void main(String[] args) throws IOException {
List<Integer> ar = new ArrayList<>();
List<Integer> par = new ArrayList<>();
List<Integer> nepar = new ArrayList<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while(true){
String s = reader.readLine();
if (s.isEmpty()) break;
ar.add(Integer.parseInt(s));
}
for (int i = 0; i < ar.size(); i++) {
if(ar.get(i)%2 ==0)
par.add(ar.get(i));
else {
nepar.add(ar.get(i));
}
}
for (int i = 0; i < par.size(); i++) {
System.out.println(par.get(i));
}
for (int i = 0; i < nepar.size(); i++) {
System.out.println(nepar.get(i));
}
}
}
| true |
116afbed8c7be5aae015bda5c1d5a77d23f2f6d1 | Java | ChineduVickreg/speedconverter | /SpeedConverter.java | UTF-8 | 978 | 3.8125 | 4 | [] | no_license | package udemyFullCourse.TimBuchalkaExpressionsAndStatements;
//An Application that converts the speed from kilometers to miles.
import java.util.Scanner;
public class SpeedConverter {
Scanner scanner = new Scanner(System.in);
double kilometersPerHour = scanner.nextDouble();
public static long toMilesPerHour(double kilometersPerHour) {
System.out.println("Enter a Number");
if (kilometersPerHour < 0){
return -1;
}
return Math.round(kilometersPerHour / 1.609);
}
public static void printConversion(double kiloMetersPerHour ){
if (kiloMetersPerHour < 0){
System.out.println("Invalid Value");
}else {
long milesPerHour = toMilesPerHour(kiloMetersPerHour);
System.out.println(kiloMetersPerHour +
"km/h = " + milesPerHour +
"mi/h");
}
}
}
| true |
6f11c474125bf7e38be5704b96ce82bebab9a88a | Java | bReal7/APIS2015 | /APIS2015/src/main/java/swt/apis2015/interfaces/PatientDao.java | UTF-8 | 688 | 2.046875 | 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 swt.apis2015.interfaces;
import java.util.List;
import swt2.apis2015.dto.PatientDto;
/**
* Data Acces für Patient
*/
public interface PatientDao {
public PatientDto getPatientByID(long id);
public List<PatientDto> getPatientByName(String name);
public PatientDto findPatientByOid(int oid);
public void updatePatient(PatientDto pat);
public void addPatient(PatientDto nPat);
public boolean isAlreadyRegistered(int oid);
}
| true |
14ca3942c2a29d372ad3e4ee0791bedfcd93bcf6 | Java | minhhuynh12/AstroTVChannel | /app/src/main/java/com/example/astro/astrotechnology/LoginActivity.java | UTF-8 | 3,337 | 2.3125 | 2 | [] | no_license | package com.example.astro.astrotechnology;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
import Model.LoginItems;
/**
* Created by vitinhHienAnh on 08-05-18.
*/
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
Button btnSubmitLogin;
EditText edUsername;
EditText edPassword;
String username;
String password;
ArrayList<LoginItems> list;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefsLogin";
public static final String Pin = "PIN_";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
setContentView(R.layout.activity_login);
btnSubmitLogin = findViewById(R.id.btnSubmitLogin);
edUsername = findViewById(R.id.edUsername);
edPassword = findViewById(R.id.edPassword);
btnSubmitLogin.setOnClickListener(this);
list = new ArrayList<>();
list.add(new LoginItems("minhhc", "123456"));
list.add(new LoginItems("minhhc2", "123456"));
list.add(new LoginItems("minhhc3", "123456"));
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
sharedpreferences = getSharedPreferences(Pin, Context.MODE_PRIVATE);
String usernameSp = sharedpreferences.getString("username", "");
String pin = sharedpreferences.getString("pin_code" , "");
if (!usernameSp.isEmpty() && !pin.isEmpty()) {
Intent intent = new Intent(this, PinActivity.class);
startActivity(intent);
}
super.onCreate(savedInstanceState);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnSubmitLogin:
if (edUsername.getText().equals("")) {
Toast.makeText(this, "Please input username", Toast.LENGTH_SHORT).show();
} else if (edPassword.getText().equals("")) {
Toast.makeText(this, "Please input password", Toast.LENGTH_SHORT).show();
} else {
username = edUsername.getText().toString();
password = edPassword.getText().toString();
checkLogin(username, password);
}
// Toast.makeText(this, "Please input username" , Toast.LENGTH_SHORT).show();
break;
}
}
private void checkLogin(String username, String password) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getUsername().equals(username) && list.get(i).getPassword().equals(password)) {
Toast.makeText(this, "Exactly", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("username", username);
editor.commit();
} else {
Toast.makeText(this, "Wrong", Toast.LENGTH_SHORT).show();
}
}
}
}
| true |
649925212aac93f4c9693e0617cfe690da53add5 | Java | linanbupt/restful | /gs-accessing-data-mongodb-complete/src/main/java/hello/url/url.java | UTF-8 | 1,577 | 1.859375 | 2 | [] | no_license | package hello.url;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Field;
public class url {
@Id private String id;
@Field("file-index")
private String file_index;
private String format;
private String code;
@Field("items-index")
private String items_index;
private String url;
@Field("play-url")
private String play_url;
@Field("auth-play-url")
private String auth_play_url;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFile_index() {
return file_index;
}
public void setFile_index(String file_index) {
this.file_index = file_index;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getItems_index() {
return items_index;
}
public void setItems_index(String items_index) {
this.items_index = items_index;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPlay_url() {
return play_url;
}
public void setPlay_url(String play_url) {
this.play_url = play_url;
}
public String getAuth_play_url() {
return auth_play_url;
}
public void setAuth_play_url(String auth_play_url) {
this.auth_play_url = auth_play_url;
}
}
| true |
c17e98b32454f241ce0d576ce61fe55da5147430 | Java | FisherWY/Leetcode | /src/solution_mid/solution1386.java | UTF-8 | 2,804 | 3.515625 | 4 | [] | no_license | package solution_mid;
/**
* @Author Fisher
* @Date 2020/6/18 21:34
**/
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* 如上图所示,电影院的观影厅中有 n 行座位,行编号从 1 到 n ,且每一行内总共有 10 个座位,列编号从 1 到 10 。
* 给你数组 reservedSeats ,包含所有已经被预约了的座位。比如说,researvedSeats[i]=[3,8] ,它表示第 3 行第 8 个座位被预约了。
* 请你返回 最多能安排多少个 4 人家庭 。4 人家庭要占据 同一行内连续 的 4 个座位。隔着过道的座位(比方说 [3,3] 和 [3,4])不是连续的座位,
* 但是如果你可以将 4 人家庭拆成过道两边各坐 2 人,这样子是允许的。
*
* 示例 1:
* 输入:n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]
* 输出:4
* 解释:上图所示是最优的安排方案,总共可以安排 4 个家庭。蓝色的叉表示被预约的座位,橙色的连续座位表示一个 4 人家庭。
*
* 示例 2:
* 输入:n = 2, reservedSeats = [[2,1],[1,8],[2,6]]
* 输出:2
*
* 示例 3:
* 输入:n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]]
* 输出:4
*
* 提示:
* 1 <= n <= 10^9
* 1 <= reservedSeats.length <= min(10*n, 10^4)
* reservedSeats[i].length == 2
* 1 <= reservedSeats[i][0] <= n
* 1 <= reservedSeats[i][1] <= 10
* 所有 reservedSeats[i] 都是互不相同的。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/cinema-seat-allocation
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class solution1386 {
public int maxNumberOfFamilies(int n, int[][] reservedSeats) {
int left = 0b11110000, middle = 0b11000011, right = 0b00001111;
Map<Integer, Integer> occupied = new HashMap<>();
for (int[] seat : reservedSeats) {
if (seat[1] >= 2 && seat[1] <= 9) {
int origin = occupied.getOrDefault(seat[0], 0);
int value = origin | (1 << (seat[1] - 2));
occupied.put(seat[0], value);
}
}
int ans = (n - occupied.size()) * 2;
for (Map.Entry<Integer, Integer> entry : occupied.entrySet()) {
int bitMask = entry.getValue();
if (((bitMask | left) == left) || ((bitMask | middle) == middle) || ((bitMask | right) == right)) {
++ans;
}
}
return ans;
}
public static void main(String[] args) {
int[][] reservedSeats = {
{2,1},{1,8},{2,6}
};
int n = 3;
solution1386 s = new solution1386();
System.out.println(s.maxNumberOfFamilies(3, reservedSeats));
}
}
| true |
78139751ad32c26cdd58c86a4eaaaf5ad8a3040d | Java | wonderfulMorty/BooksManageSys | /src/main/java/com/dev/books/service/iml/SupplierServiceImpl.java | UTF-8 | 1,168 | 1.914063 | 2 | [] | no_license | package com.dev.books.service.iml;
import com.dev.books.dao.SuppliersMapper;
import com.dev.books.pojo.Supplier;
import com.dev.books.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class SupplierServiceImpl implements SupplierService {
@Autowired
SuppliersMapper suppliersMapper;
@Override
public List<Supplier> findAllSupplierByPages(int start, int pageSize) {
return suppliersMapper.findAllSupplierByPages(start,pageSize);
}
@Override
public List<Supplier> findAllSupplier() {
return suppliersMapper.findAllSupplier();
}
@Override
public int addSupplier(Map map) {
return suppliersMapper.addSupplier(map);
}
@Override
public int deleteQsById(String id) {
return suppliersMapper.deleteQsById(id);
}
@Override
public int updateQsById(Map map) {
return suppliersMapper.updateQsById(map);
}
@Override
public List<String> findAllQsName() {
return suppliersMapper.findAllQsName();
}
}
| true |
da88b2c8dcd3e7a30cc232dcd5b3d1a20df01ac3 | Java | jingl-skywalker/njwu-css | /src/main/java/businesslogic/framebl/EduFrame.java | UTF-8 | 3,381 | 2.421875 | 2 | [] | no_license | package businesslogic.framebl;
//import dataservice.datafactory.DataFactory;
//import dataservice.framedataservice.FrameDataService;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import dataservice.datafactory.DataFactory;
import dataservice.framedataservice.FrameDataService;
import po.framepo.BlockPO;
import po.framepo.FramePO;
import vo.framevo.FrameVO;
public class EduFrame {
FrameDataService fds;
DataFactory dataFactory;
private String description;
private BlockList bList;
private int total;
private boolean isPublic;
public EduFrame() {
System.out.println("edu frame constructor");
bList = new BlockList();
try {
dataFactory = (DataFactory) Naming.lookup("dataFactory");
System.out.println(dataFactory==null);
fds = dataFactory.getFrameData();
} catch (NotBoundException ex) {
Logger.getLogger(EduFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(EduFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (RemoteException ex) {
Logger.getLogger(EduFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
public EduFrame(String description, int total) {
this();
this.description = description;
this.total = total;
}
public BlockList getBlocks() {
return bList;
}
public boolean addBlock(Block block) {
this.bList.add(block);
return true;
}
public boolean modifyBlock(int num, Block block) {
return false;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public boolean setPublic() {
this.isPublic = true;
this.save();
return true;
}
public boolean createFrame()
{
FramePO fpo=new FramePO(this);
try {
fds.insert(fpo);
} catch (RemoteException ex) {
Logger.getLogger(EduFrame.class.getName()).log(Level.SEVERE, null, ex);
return false;
}
return true;
}
public FrameVO find() {
FramePO fpo = null;
try {
// fpo =new FramePO(fds.find());
///fpo=new FramePO(fds.find());
fpo=fds.find();
} catch (RemoteException ex) {
Logger.getLogger(EduFrame.class.getName()).log(Level.SEVERE, null, ex);
}
FrameVO fvo = new FrameVO(fpo);
return fvo;
}
private boolean save() {
FramePO fpo = new FramePO(total, description);
fpo.setPublic();
int size = bList.getSum();
for (int i = 0; i < size; i++) {
// fpo.addBlock(new BlockPO(bList.getBlock(i)));
}
try {
fds.update(fpo);
} catch (RemoteException ex) {
Logger.getLogger(EduFrame.class.getName()).log(Level.SEVERE, null, ex);
}
return true;
}
}
| true |
075304a4d49ed8d8fe7e510963587d26c01fa467 | Java | Sunflowers0214/flysnow | /flysnow-serviceWeb/flysnow-demo/src/main/java/com/flysnow/authority/service/UserPermissionService.java | UTF-8 | 1,107 | 2.125 | 2 | [] | no_license | package com.flysnow.authority.service;
import com.flysnow.authority.model.UserPermission;
import com.flysnow.common.base.Page;
import java.util.List;
import java.util.Map;
/**
* @description 用户登录权限逻辑层接口
* @author huangyongsheng
* @version 1.0.0
* @createtime 2018-12-09
*/
public interface UserPermissionService{
/**
* 增加
* @param entity
* @return
*/
public abstract UserPermission insert(UserPermission entity);
/**
* 删除
* @param entity
* @return
*/
public abstract boolean delete(UserPermission entity);
/**
* 修改
* @param entity
* @return
*/
public abstract boolean update(UserPermission entity);
/**
* 查询单条
* @param entity
* @return
*/
public abstract UserPermission get(UserPermission entity);
/**
* 多条查询
* @param entity
* @return
*/
public abstract List getList(UserPermission entity);
/**
* 分页查询
* @param map
* @param pageNo
* @param pageSize
* @param sort
* @return
*/
public abstract Page getListForPage(Map map, int pageNo, int pageSize, String sort);
}
| true |
a3bc532be4af4a3e0100cd372412aae6835e84d7 | Java | o2p-asiainfo/o2p-service-migration | /src/main/java/com/asiainfo/integretion/o2p/servicemigration/domain/RuleStrategy.java | UTF-8 | 2,320 | 2.25 | 2 | [] | no_license | package com.asiainfo.integretion.o2p.servicemigration.domain;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ruleStrategy", propOrder = {
"ruleStrategyCode",
"ruleStrategyName",
"ruleStrategyDesc"
})
public class RuleStrategy extends BasedBean {
@XmlElement(required = true)
protected String ruleStrategyCode;
@XmlElement(required = true)
protected String ruleStrategyName;
protected String ruleStrategyDesc;
/**
* Gets the value of the ruleStrategyCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRuleStrategyCode() {
return ruleStrategyCode;
}
/**
* Sets the value of the ruleStrategyCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRuleStrategyCode(String value) {
this.ruleStrategyCode = value;
}
/**
* Gets the value of the ruleStrategyName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRuleStrategyName() {
return ruleStrategyName;
}
/**
* Sets the value of the ruleStrategyName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRuleStrategyName(String value) {
this.ruleStrategyName = value;
}
/**
* Gets the value of the ruleStrategyDesc property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRuleStrategyDesc() {
return ruleStrategyDesc;
}
/**
* Sets the value of the ruleStrategyDesc property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRuleStrategyDesc(String value) {
this.ruleStrategyDesc = value;
}
@Override
public boolean equals(Object obj){
return super.equals(obj);
}
@Override
public int hashCode(){
return super.hashCode();
}
}
| true |
7cb931fd1abb4d13a6d46d2eae4a6ce707aa33a3 | Java | GeorgeSherif/DatabaseEngine | /src/main/java/Page.java | UTF-8 | 5,611 | 2.671875 | 3 | [] | no_license | import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;
public class Page implements Serializable, Comparable{
private static final long serialVersionUID = 2L;
String PageName;
int maxSize;
String TableName;
Vector<Record> records;
Vector<String> columns;
Object Min;
private Properties dbProps;
public Page(String PageName, String TableName) {
try {
dbProps = new java.util.Properties();
FileInputStream fis = new FileInputStream("src/main/resources/DBApp.config");
dbProps.load(fis);
}
catch (Exception e){
System.out.println("DBApp.config is not found");
}
maxSize = Integer.parseInt(dbProps.getProperty("MaximumRowsCountinPage"));
this.PageName = PageName;
this.TableName = TableName;
records = new Vector<Record>();
columns =Helpers.getMetaData2(TableName);
}
public boolean isEmpty(){
return records.size() == 0;
}
public Record get(int idx){
if(idx >= 0 && idx < this.size())
return records.get(idx);
throw new IndexOutOfBoundsException(""+idx);
}
public int size(){
return records.size();
}
public void insertIntoPage (Hashtable ht , String TableName) {
String s =Helpers.getclusterkey(TableName);
Object clusterkey=null;
for(int i=0;i<columns.size();i++){
if(columns.get(i).equals(s)){
clusterkey=ht.get(s);
}
}
Record newrec =new Record(TableName,clusterkey);
for(int i=0;i<columns.size();i++){
newrec.insert(ht.get(columns.get(i)));;
}
this.records.add(newrec);
java.util.Collections.sort(records);
}
public Object getmaxValue (){
return Helpers.getclusterkeyValue2(this.records.lastElement() ,TableName);
}
public Object getminValue (){
return Helpers.getclusterkeyValue2(this.records.firstElement() ,TableName) ;
}
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
Page tmp = (Page) o;
if (Min instanceof Integer)
return ((Integer)this.Min).compareTo((Integer)tmp.Min);
if (Min instanceof String)
return ((String)this.Min).compareTo((String)tmp.Min);
if (Min instanceof Double)
return ((Double)this.Min).compareTo((Double)tmp.Min);
if (Min instanceof Boolean)
return ((Boolean)this.Min).compareTo((Boolean)tmp.Min);
if (Min instanceof Date)
return ((Date)this.Min).compareTo((Date)tmp.Min);
return 1;
}
public static void main(String[] args) throws IOException, DBAppException {
Table t=new Table("Student","id");
Hashtable colNameMax = new Hashtable( );
colNameMax.put("id", 1);
colNameMax.put("name", "ZZZZZZZZZZZ");
colNameMax.put("gpa","5");
Hashtable colNameMax2 = new Hashtable( );
colNameMax2.put("id", 5);
colNameMax2.put("name", "ZZZZZZZZZZZ");
colNameMax2.put("gpa","4");
Hashtable colNameMax3 = new Hashtable( );
colNameMax3.put("id", 7);
colNameMax3.put("name", "ZZZZZZZZZZZ");
colNameMax3.put("gpa","5");
Hashtable colNameMax4 = new Hashtable( );
colNameMax4.put("id", 8);
colNameMax4.put("name", "ZZZZZZZZZZZ");
colNameMax4.put("gpa","4");
Hashtable colNameMax5 = new Hashtable( );
colNameMax5.put("id", 3);
colNameMax5.put("name", "ZZZZZZZZZZZ");
colNameMax5.put("gpa","4");
Hashtable colNameMax6 = new Hashtable( );
colNameMax6.put("id", 2);
colNameMax6.put("name", "ZZZZZZZZZZZ");
colNameMax6.put("gpa","4");
Hashtable colNameMax7 = new Hashtable( );
colNameMax7.put("id",10);
colNameMax7.put("name", "ZZZZZZZZZZZ");
colNameMax7.put("gpa","4");
Hashtable colNameMax8 = new Hashtable( );
colNameMax8.put("id", 4);
colNameMax8.put("name", "ZZZZZZZZZZZ");
Hashtable colNameMax9 = new Hashtable( );
colNameMax9.put("id", 0);
colNameMax9.put("name", "ZZZZZZZZZZZ");
colNameMax9.put("gpa","4");
Hashtable colNameMax10 = new Hashtable( );
colNameMax10.put("id", -1);
colNameMax10.put("name", "Kerz");
colNameMax10.put("gpa","10");
t.insertIntoPages (colNameMax ,"Student"); //1
t.insertIntoPages (colNameMax2 ,"Student"); //5
t.insertIntoPages (colNameMax3 ,"Student"); //7
t.insertIntoPages (colNameMax4 ,"Student"); //8
t.insertIntoPages (colNameMax5 ,"Student"); //3
t.insertIntoPages (colNameMax6 ,"Student"); //2
t.insertIntoPages (colNameMax7 ,"Student"); //10
t.insertIntoPages (colNameMax8 ,"Student"); //4
t.insertIntoPages (colNameMax9 ,"Student");
t.insertIntoPages (colNameMax10 ,"Student");
for(int i = 0 ; i < t.positions.size(); i++) {
Page p = t.deserializePage(t.positions.get(i));
System.out.println(p.PageName);
for(int j = 0 ; j < p.records.size() ; j++) {
Record r = p.records.get(j);
System.out.println(r.values.get(2));
}
}
System.out.println("--------------------------------------");
String table = "Student";
Hashtable<String, Object> row = new Hashtable();
row.put("name", "ZZZZZZZZZZZ");
row.put("gpa", "5");
t.deleteFromPages(row,"Student");
for(int i = 0 ; i < t.positions.size(); i++) {
Page p = t.deserializePage(t.positions.get(i));
System.out.println(p.PageName);
for(int j = 0 ; j < p.records.size() ; j++) {
Record r = p.records.get(j);
System.out.println(r.values.get(2));
}
}
//t.deleteFromPages(colNameMax10, "Student");
//t.UpdatePages(colNameMax10, "Student", "id");
// for(int i = 0 ; i < t.pages.size(); i++) {
// System.out.println(t.pages.get(i).records);
// for(int j = 0 ; j < t.pages.get(i).size() ; j++) {
// System.out.println(t.pages.get(i).records.get(j).values);
// Record r =t.pages.get(i).records.get(j);
// System.out.println(r.values.get(2));
// }
//}
}
}
| true |
9b771b67d6cb83b38d8aa507f03757e2c14d1f09 | Java | yessine66/PIDEV-SKYWAY | /PIDEV-SKYWAY-main/src/Esprit/entities/Participation.java | UTF-8 | 1,375 | 2.203125 | 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 Esprit.entities;
import java.util.Date;
import java.util.Objects;
/**
*
* @author simop
*/
public class Participation {
private int id_participer;
private int id_cours;
private int id_user;
public Participation(int id_participer, int id_cours, int id_user) {
this.id_participer = id_participer;
this.id_cours = id_cours;
this.id_user = id_user;
}
public Participation(int id_cours, int id_user) {
this.id_cours = id_cours;
this.id_user = id_user;
}
public int getId_participer() {
return id_participer;
}
public void setId_participer(int id_participer) {
this.id_participer = id_participer;
}
public int getId_cours() {
return id_cours;
}
public void setId_cours(int id_cours) {
this.id_cours = id_cours;
}
public int getId_user() {
return id_user;
}
public void setId_user(int id_user) {
this.id_user = id_user;
}
@Override
public String toString() {
return "Participation{" + "id_participer=" + id_participer + ", id_cours=" + id_cours + ", id_user=" + id_user + '}';
}
}
| true |
66bdd97410c4d85280fcfeeffa39f790be22aada | Java | rheehot/Algorithm-17 | /Baekjoon/week1/BaekJoon13300.java | UTF-8 | 1,336 | 3.34375 | 3 | [] | no_license | package week1;
import java.util.ArrayList;
import java.util.Scanner;
public class BaekJoon13300 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String studentInfo = sc.nextLine();
String[] info = studentInfo.split(" ");
int total = Integer.parseInt(info[0]);
int k = Integer.parseInt(info[1]);
int answer = 0;
ArrayList<Integer> female = new ArrayList<>(6);
ArrayList<Integer> male = new ArrayList<>(6);
for (int i = 0; i < total; i++) {
String infoLine = sc.nextLine();
String[] who = infoLine.split(" ");
int g = Integer.parseInt(who[1])-1;
int gender = Integer.parseInt(who[0]);
if (gender == 0) {
female.add(g, female.get(g)+1);
if (female.get(g) == k) {
answer++;
female.add(g, 0);
}
} else {
male.add(g, male.get(g)+1);
if (male.get(g) == k) {
answer++;
male.add(g, 0);
}
}
}
for (int f : female)
answer += f == 0 ? 0 : 1;
for (int m : male)
answer += m == 0 ? 0 : 1;
System.out.println(answer);
}
}
| true |
5194ca33a622babf2716e5a4de6cdecc3c4b3a3a | Java | stronglee/sdk | /app/src/main/java/com/android/common/sdk/app/lifecycle/LifeCycleComponentManager.java | UTF-8 | 3,333 | 2.6875 | 3 | [] | no_license | package com.android.common.sdk.app.lifecycle;
import java.util.HashMap;
import java.util.Map.Entry;
public class LifeCycleComponentManager implements IComponentContainer {
private HashMap<String, LifeCycleComponent> mComponentList;
public LifeCycleComponentManager() {
}
public static boolean addComponentToContainer(LifeCycleComponent component,
Object matrixContainer, boolean throwEx) {
if (matrixContainer instanceof IComponentContainer) {
((IComponentContainer) matrixContainer).addComponent(component);
return true;
} else {
if (throwEx) {
throw new IllegalArgumentException("componentContainerContext "
+ "should implements IComponentContainer");
}
return false;
}
}
public void addComponent(LifeCycleComponent component) {
if (component != null) {
if (mComponentList == null) {
mComponentList = new HashMap<String,LifeCycleComponent>();
}
mComponentList.put(component.toString(), component);
}
}
public void onBecomesVisibleFromTotallyInvisible() {
if (mComponentList == null) {
return;
}
for (Entry<String, LifeCycleComponent> stringLifeCycleComponentEntry : mComponentList.entrySet()) {
LifeCycleComponent component = stringLifeCycleComponentEntry.getValue();
if (component != null) {
component.onBecomesVisibleFromTotallyInvisible();
}
}
}
public void onBecomesTotallyInvisible() {
if (mComponentList == null) {
return;
}
for (Entry<String, LifeCycleComponent> stringLifeCycleComponentEntry : mComponentList.entrySet()) {
LifeCycleComponent component = stringLifeCycleComponentEntry.getValue();
if (component != null) {
component.onBecomesTotallyInvisible();
}
}
}
public void onBecomesPartiallyInvisible() {
if (mComponentList == null) {
return;
}
for (Entry<String, LifeCycleComponent> stringLifeCycleComponentEntry : mComponentList.entrySet()) {
LifeCycleComponent component = stringLifeCycleComponentEntry.getValue();
if (component != null) {
component.onBecomesPartiallyInvisible();
}
}
}
public void onBecomesVisibleFromPartiallyInvisible() {
if (mComponentList == null) {
return;
}
for (Entry<String, LifeCycleComponent> stringLifeCycleComponentEntry : mComponentList.entrySet()) {
LifeCycleComponent component = stringLifeCycleComponentEntry.getValue();
if (component != null) {
component.onBecomesVisible();
}
}
}
public void onDestroy() {
if (mComponentList == null) {
return;
}
for (Entry<String, LifeCycleComponent> stringLifeCycleComponentEntry : mComponentList.entrySet()) {
LifeCycleComponent component = stringLifeCycleComponentEntry.getValue();
if (component != null) {
component.onDestroy();
}
}
}
}
| true |
8ee837de5be8983184652500d052b836079dddf2 | Java | ProstoZhukov/HelloWorld | /app/src/main/java/com/zhukov/android/myapplicationlist/di/infocontact/ContactComponent.java | UTF-8 | 331 | 1.679688 | 2 | [] | no_license | package com.zhukov.android.myapplicationlist.di.infocontact;
import com.zhukov.android.myapplicationlist.presentation.infocontact.view.ContactFragment;
import dagger.Subcomponent;
@Subcomponent(modules = ContactModule.class)
@ContactScope
public interface ContactComponent {
void inject(ContactFragment contactFragment);
}
| true |
be84ce5aaee07d4e2db6513f69d59b7f33ee661e | Java | gudaoge/helloword-springboot | /src/main/java/com/origin/demo/json/PropertiesController.java | UTF-8 | 2,223 | 2.34375 | 2 | [] | no_license | package com.origin.demo.json;
import com.origin.demo.properties.CustomProperties;
import com.origin.demo.properties.CustomPropertiesBean;
import com.origin.demo.properties.OutCustomPropertiesBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by dengqingling on 2019-07-04
* 自定义配置文件使用测试
*
* 目前来看 只添加@ConfigurationProperties注解是无效的
* 需要配合@Component或者@EnableConfigurationProperties注解才能注入
* @EnableConfigurationProperties 使用时需要指定配置类
* @Component 则不需要
* 看起来@Component更方便一些,@EnableConfigurationProperties的意义在于啥
* 个人猜测是@Component通过包扫描,任何带有注解的都会被注入
* 而@EnableConfigurationProperties通常用于配置类上,可以指定加载对应配置,通过springboot的自动配置所以无需包扫描
*
*/
@EnableConfigurationProperties(CustomProperties.class)
@RequestMapping("/properties")
@RestController
public class PropertiesController {
@Autowired
private CustomProperties customProperties;
@Autowired
private CustomPropertiesBean customPropertiesBean;
@Autowired
private OutCustomPropertiesBean outCustomPropertiesBean;
@Autowired
private Environment environment;
@RequestMapping("/getCustomProperties")
public Object getCustomProperties() {
return customProperties;
}
@RequestMapping("/getCustomPropertiesBean")
public Object getCustomPropertiesBean() {
return customPropertiesBean;
}
@RequestMapping("/getOutCustomPropertiesBean")
public Object getOutCustomPropertiesBean() {
return outCustomPropertiesBean;
}
@RequestMapping("/getEnvironmentProperties")
public Object getEnvironmentProperties(@RequestParam("key") String key) {
return environment.getProperty(key);
}
}
| true |
43a76df4f3fb7be6d2915b91dd626d8389cc14f8 | Java | tombigun/java-some-codes | /test-basis/src/main/java/com/basic/TestString.java | UTF-8 | 418 | 2.8125 | 3 | [] | no_license | package com.basic;
public class TestString {
public static void main(String[] args) {
String s1 = "100";
String s2 = "100";
String s3 = new String("100");
String s4 = new String("100");
System.out.println(s1 == s2);
System.out.println(s3 == s4);
String s5 = new String("200");
String s6 = "200";
System.out.println(s5 == s6);
}
}
| true |
cffd9d3e29dc52a767325d9bdad2e44b499482c5 | Java | MontclairRobotics/RelicRecovery2017 | /TeamCode/src/main/java/org/montclairrobotics/sprocket/drive/DTInput.java | UTF-8 | 416 | 2.296875 | 2 | [
"BSD-3-Clause"
] | permissive | package org.montclairrobotics.sprocket.drive;
import org.montclairrobotics.sprocket.geometry.Angle;
import org.montclairrobotics.sprocket.geometry.Vector;
public interface DTInput {
/**
* X and Y from -1 to 1 inclusive; the power for x and y translation
*/
public Vector getDir();
/**
* The rotation value, from -1 to 1, with 1 being a rotation to the right at full power
*/
public double getTurn();
}
| true |
341d5e85d1bddce6d07dcbe2a0f2b2adb21be6de | Java | wisgood/mobile-core | /log_analytics/0.1.0/src/java_src/log_analytics/src/com/bi/client/quality/enums/PlayHaltDetailFormatEnum.java | UTF-8 | 1,568 | 1.867188 | 2 | [] | no_license | package com.bi.client.quality.enums;
public enum PlayHaltDetailFormatEnum {
/*
* DATE_ID,日期ID
* HOUR_ID,小时ID
* VERSION_ID,版本ID
* PROVINCE_ID,省ID
* CITY_ID,城市ID
* ISP_ID,运营商ID
* MAC_FORMAT, 经过验证的MAC地址
* HC_FORMAT, 卡次数,验证为非负整数
* HTA_FORMAT, 卡时间,验证为非负整数
* HT_FORMAT, 卡类别,验证只有两种(1-边看边下;2-先下后看)
* DHC_FORMAT, 自由拖动导致卡总时间,验证为非负整数
* DHT_FORMAT, 自由拖动导致卡总时间,验证为非负整数
* SID, SESSION ID
* CLIENTIP, 客户端IP
* TIMESTAMP, 接收上报时间(rt):unix时间戳
* PGID, package_id,每个客户端独立编号
* PVS, 工作模式
* DHC, 自由拖动导致卡总时间
* DHT, 自由拖动导致卡总次数
* HC, 卡的总次数
* HT, 卡类别
* HTA, 卡的总时间
* IH, 任务infohash
* MAC, MAC地址
* NT, NAT类型
* TPT, 任务播放时间
* TT, 卡时平均下载速度
* VV, 客户端版本,点分十进制
* PROVINCE, 省ID
* CITY, 城市ID
* ISP, 运营商ID
* 详情请见http://redmine.funshion.com/redmine/projects/data-analysis/wiki/Play_halt_detail
*/
DATE_ID, HOUR_ID, VERSION_ID, PROVINCE_ID, CITY_ID, ISP_ID, MAC_FORMAT, HC_FORMAT, HTA_FORMAT, HT_FORMAT, DHC_FORMAT, DHT_FORMAT,
SID, CLIENTIP, TIMESTAMP, PGID, PVS, DHC, DHT, HC, HT, HTA, IH, MAC, NT, TPT, TT, VV, PROVINCE, CITY, ISP;
}
| true |
a0d40be97c5951f9133e2597097c798467e766ea | Java | kafferty/DrawLogicalCircuitAndroid | /СircuitDraw/app/src/main/java/com/kafferty/circuitdraw/Quadrant.java | UTF-8 | 130 | 1.585938 | 2 | [] | no_license | package com.kafferty.circuitdraw;
public enum Quadrant { LEFT_TOP,
LEFT_BOTTOM,
RIGHT_TOP,
RIGHT_BOTTOM } | true |
2f68df2e147e2c7d03fdfb4b577cdd124b1ecbf4 | Java | Shyamjith06/project-2 | /gooddeed/src/main/java/com/mindtree/gooddeed/controller/CampusMindController.java | UTF-8 | 982 | 2.09375 | 2 | [] | no_license | package com.mindtree.gooddeed.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.mindtree.gooddeed.entity.CampusMind;
import com.mindtree.gooddeed.service.CampusMindService;
@RestController
public class CampusMindController {
@Autowired
CampusMindService campusService;
@PostMapping("/addminds")
public CampusMind addCampusMind(@RequestBody CampusMind campusMind)
{
return campusService.addCampusMind(campusMind);
}
@GetMapping("/displayCampusMind")
public List<CampusMind> displayCampusMind(@RequestParam int gid)
{
return campusService.displayCampusMind(gid);
}
}
| true |
6a90fb141c2851522eb0fe348879c3d78e498621 | Java | arthurHamon2/Intelligent-Home | /src/server/models/VirtualCalendarSensor.java | UTF-8 | 1,144 | 2.484375 | 2 | [] | no_license | package server.models;
import java.util.ArrayList;
import java.util.Date;
import server.database.service.MeasureTypeService;
import com.google.gdata.data.DateTime;
public class VirtualCalendarSensor extends Sensor {
protected final DateTime wakeUpHour = null;
protected final int wakeUpHour_NUM = 0;
protected final int currentTime_NUM = 1;
public VirtualCalendarSensor(Long ref, String title) {
super(ref, title, new ArrayList<Measure>(), new Date());
MeasureTypeService s = new MeasureTypeService();
MeasureType t = s.findByTitle("Heure_Reveil");
getMeasures().add(new Measure(0L, getSensorRef(), t, 0));
MeasureType w = s.findByTitle("Heure_Actuelle");
getMeasures().add(new Measure(0L, getSensorRef(), w, 0));
}
public VirtualCalendarSensor() {
super();
}
public Measure getWakeUpHour() {
return getMeasures().get(wakeUpHour_NUM);
}
public Measure getCurrentTime() {
return getMeasures().get(currentTime_NUM);
}
public void setWakeUpHour(long w) {
getMeasures().get(wakeUpHour_NUM).setValue(w);
}
public void setCurrentTime(long h) {
getMeasures().get(currentTime_NUM).setValue(h);
}
}
| true |
de4fc497235f41e17a6512b209ea7707578792d8 | Java | SunnyStyle/AndroidPracticeProject | /rxjavatest/src/main/java/com/amigo/ai/rxjavatest/model/exception/ErrorData.java | UTF-8 | 178 | 1.914063 | 2 | [] | no_license | package com.amigo.ai.rxjavatest.model.exception;
/**
* Created by wf on 18-4-2.
*/
public interface ErrorData {
Exception getException();
String getErrorMessage();
}
| true |
804f05bdece64636e9f92e713e0aed600c9c7c3b | Java | grazielevasconcelos/projetoam_javax | /src/br/com/fiap/daoimpl/ComentarioEventoDAOImpl.java | ISO-8859-1 | 543 | 1.953125 | 2 | [] | no_license | package br.com.fiap.daoimpl;
import javax.persistence.EntityManager;
import br.com.fiap.dao.ComentarioEventoDAO;
import br.com.fiap.entity.ComentarioEvento;
public class ComentarioEventoDAOImpl extends DAOImpl<ComentarioEvento, Integer> implements ComentarioEventoDAO {
/**
* Construtor padro
*
* @param entityManager Gerenciador das persistncias
* @author Ariel Molina
*/
public ComentarioEventoDAOImpl(EntityManager entityManager) {
super(entityManager);
// TODO Auto-generated constructor stub
}
}
| true |
58071451260ed2fe8ffe43875ef9dd2f9f5d6ce9 | Java | 5710546615/codeguide | /src/SplitYourCodeIntoShort/ListNumber.java | UTF-8 | 905 | 3.671875 | 4 | [] | no_license | package SplitYourCodeIntoShort;
/**
* ListNumber is the class for list of odd or even number.
*
* @author Visurt Anuttivong
* @version 5710546615
*/
public class ListNumber {
// TODO rebuild ListOddNumber to be more shorter.
/**
* List odd number from 1 to limit.
*
* @param limit
* is the maximum number to be list.
*/
public void ListOddNumber(int limit) {
int i = 0;
while (true) {
i++;
if (i <= limit) {
if (i % 2 != 0) {
System.out.print(i + " ");
}
} else {
break;
}
}
}
// TODO rebuild ListEvenNumber to be more shorter.
/**
* List even number from 1 to limit.
*
* @param limit
* is the maximum number to be list.
*/
public void ListEvenNumber(int limit) {
int i = 0;
while (true) {
i++;
if (i <= limit) {
if (i % 2 == 0) {
System.out.print(i + " ");
}
} else {
break;
}
}
}
}
| true |
ea166b459aec2845af49b2650107250bdd9015d6 | Java | hanif-ali/CodeBench-Desktop | /MyApp/src/sample/Visible.java | UTF-8 | 1,500 | 2.234375 | 2 | [] | no_license | package sample;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;
import java.util.ResourceBundle;
public class Visible implements Initializable {
JSONObject test;
@FXML
Label testcases;
@FXML
Label ttest;
@FXML
Label stest;
@FXML
Label linter;
int passed=0;
Visible(JSONObject obj){
this.test=obj;
}
@Override
public void initialize(URL location, ResourceBundle resources) {
try {
//int num=(int)((Double.parseDouble((String) test.getJSONObject("scores").get("linter")))*1000);
int num=(int)(test.getJSONObject("scores").getDouble("linter")*1000);
int numb=(int)(test.getJSONObject("percentages").getDouble("linter")) ;
linter.setText(num+"/"+numb);
JSONArray vis=(JSONArray)test.getJSONArray("visible_test_cases");
ttest.setText(vis.length()+"");
int tot=vis.length();
for(int i=0;i<vis.length();i++){
if(vis.getJSONObject(i).getBoolean("passed")){
passed+=1;
}
}
stest.setText(passed+"");
double percent=passed/tot*100;
int p=(int)percent;
testcases.setText(p+"");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
| true |
40a815a5f46a0c3a48a646a9d18817bb923c9d2b | Java | nystuen/Nettverksprogrammering_5 | /src/main/java/Konto.java | UTF-8 | 1,201 | 2.4375 | 2 | [] | no_license | import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
@Entity
@Table(name="konto_table")
public class Konto {
@Version
private int laas=0;
@Id
@Column(name = "id")
@GeneratedValue(generator = "incrementor")
@GenericGenerator(name = "incrementor", strategy = "increment")
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "name")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "saldo")
private double saldo;
public double getSaldo() {
return saldo;
}
public void setSaldo(double saldo) {
this.saldo = saldo;
}
public boolean trekk(double belop) {
if (belop > 0) {
this.saldo -= belop;
return true;
} else {
return false;
}
}
public boolean leggTil(double belop){
if (belop > 0) {
this.saldo += belop;
return true;
} else {
return false;
}
}
}
| true |
3223dfe928fe441cfc0372ea90d84fa1c5b50957 | Java | Muzamil-Nawaz/BitForge-System-Console-App | /BitForgeSys/src/bitforgesys/PrintJob.java | UTF-8 | 3,814 | 3.75 | 4 | [] | no_license | package bitforgesys;
/**
* This class represents a entity of PrintJob in Stage A of the project with
* required attributes, with methods to calculate price and display details.
*
* @author
*/
public class PrintJob {
// Variable used for storing print id of the print job object
protected int printId;
// Variable used for storing customer id of the print job object
protected String customerId;
// Variable used for storing short description of the print job object
protected String shortDescription;
// Variable used for storing print quantity of the print job object
protected int printQuantity;
// Variable used for storing volume in Cmm of the print job object
protected double volumeInCmm;
// Variable used for storing plastic type of the print job object
protected String plasticType;
// Variable used for storing price of the print job object
protected double price;
/**
* Empty constructor for empty object-initialization where needed
*/
public PrintJob() {
}
/**
* Parametrized constructor to directly initialize the attributes with
* passed values
*
* @param printId storing the print id passed from the caller
* @param customerId storing the customer id passed from the caller
* @param shortDescription storing the short description passed from the
* caller
* @param printQuantity storing the print quantity passed from the caller
* @param volumeInCmm storing the volume of print job passed from the caller
* @param plasticType storing the plastic type passed from the caller
*/
public PrintJob(int printId, String customerId, String shortDescription,
int printQuantity, double volumeInCmm, String plasticType) {
this.printId = printId;
this.customerId = customerId;
this.shortDescription = shortDescription;
this.printQuantity = printQuantity;
this.volumeInCmm = volumeInCmm;
this.plasticType = plasticType;
this.price = this.calcTotalPrice();
}
/**
* This method is used to calculate the final price of the print job based
* on it's attributes
*
* @return final calculated price
*/
public double calcTotalPrice() {
// if plastic type is PLA
if (this.plasticType.equalsIgnoreCase("PLA")) {
// calculate price for 5 cents per CMM for each unit
price = volumeInCmm * 5 * printQuantity;
} // if plastic type is ABS
else if (this.plasticType.equalsIgnoreCase("ABS")) {
// calculate price for 6 cents per CMM for each unit
price = volumeInCmm * 6 * printQuantity;
} // if plastic type is Nylon
else if (this.plasticType.equalsIgnoreCase("NYLON")) {
// calculate price for 7 cents per CMM for each unit
price = volumeInCmm * 7 * printQuantity;
}
//converting price into dollars
price = price / 100;
// If price is less than $60.50
if (price < 60.50) {
// then set the price to $60.50 anyway to cover fixed overheads
price = 60.50;
}
// Setting price of current print job object to calculated price
this.price = price;
// returning the calculated price
return this.price;
}
/**
* This method is used to print details (attributes) of the print job object
*/
public void displayAllDetails() {
System.out.println("" + "printId=" + printId + ", customerId=" + customerId
+ ", shortDescription=" + shortDescription + ", printQuantity=" + printQuantity + ", "
+ "volumeInCmm=" + volumeInCmm + ", plasticType=" + plasticType + ", price=" + price + " dollars");
}
}
| true |
44d2743c5438002c97082be9ee45ebd1cf3a94d6 | Java | BambangHeriSetiawan/riskiprojects | /app/src/main/java/com/simx/riskiprojects/data/remote/API/Api.java | UTF-8 | 2,669 | 2.125 | 2 | [] | no_license | package com.simx.riskiprojects.data.remote.API;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.simx.riskiprojects.BuildConfig;
import com.simx.riskiprojects.data.model.ResponsePlace;
import com.simx.riskiprojects.data.model.ResponseSample;
import com.simx.riskiprojects.data.model.waypoint.ResponseWaypoint;
import io.reactivex.Observable;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.Query;
/**
* User: simx Date: 08/08/18 1:01
*/
public interface Api {
@Headers({"Accept: application/json", "Content-type: application/json"})
@GET("place/nearbysearch/json")
Observable<ResponsePlace> getPlaceNearby(
@Query("key") String key,
@Query("type") String type,
@Query("radius") int radius,
@Query("location") String location,
@Query("keyword") String keyword
);
@Headers({"Accept: application/json", "Content-type: application/json"})
@GET("place/nearbysearch/json")
Observable<ResponsePlace> getAll(
@Query("key") String key,
@Query("type") String type,
@Query("radius") int radius,
@Query("mode") int mode,
@Query("sensor") String sensor
);
@Headers({"Accept: application/json", "Content-type: application/json"})
@GET("directions/json")
Observable<ResponseWaypoint> getPolyline(
@Query("key") String key,
@Query("origin") String origin,
@Query("destination") String destination,
@Query("alternatives") String alternatives,
@Query("mode") String mode,
@Query("sensor") String sensor
);
@Headers({"Accept: application/json", "Content-type: application/json"})
@GET("rs.json")
Observable<List<ResponseSample>> getAll();
class Factory {
private static Retrofit retrofit = null;
public static Retrofit getRetrofit(){
return retrofit;
}
public static Api create() {
return getRetrofitConfig().create(Api.class);
}
public static Retrofit getRetrofitConfig() {
return new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL_GITHUB)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client())
.build();
}
private static OkHttpClient client() {
return new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.addInterceptor(new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY)
)
.build();
}
}
}
| true |
8d0cd46b6c3c3677f5a5ba07bd7ce2ee1cee9c63 | Java | h2n0/D-DProj | /src/uk/fls/h2n0/main/util/Dice.java | UTF-8 | 1,708 | 3.90625 | 4 | [] | no_license | package uk.fls.h2n0.main.util;
public class Dice {
/**
* Takes a given dice string and returns the correct number of dice
* @param dice
* @return Int[]
*/
public static int[] rollDice(String dice){
dice = dice.toLowerCase();
int indexOfD = dice.indexOf("d");
if(indexOfD == -1){//Checks to see if this dice string given is even valid
System.err.println("Invalid dice: " + dice);
return null;
}
if(dice.substring(0,indexOfD).isEmpty() || Integer.parseInt(dice.substring(0, indexOfD)) == 1){//Single dice
String sides = dice.substring(indexOfD+1);
System.out.println("Rolling dice: D"+sides);// Console output to help debug
int res = genNumber(Integer.parseInt(sides));
System.out.println("Dice value: " + res);
System.out.println(" ");
return new int[]{res};
}else{//Many dice
String numberOfDice = dice.substring(0,indexOfD);
String sides = dice.substring(indexOfD+1);
int[] res = new int[Integer.parseInt(numberOfDice)];
for(int i = 0; i < res.length; i++){ //Generate enough dice as requested
res[i] = genNumber(Integer.parseInt(sides));
}
System.out.println("Rolling dice: "+ numberOfDice +"D"+sides); // More output for easy debugging
String diceValues = "";
for(int i = 0; i < res.length; i++){
diceValues += res[i] + ",";
}
diceValues = diceValues.trim().substring(0, diceValues.length()-1);
System.out.println("Dice values: " + diceValues);
System.out.println(" ");
return res;// Final output
}
}
/**
* Generates a number similar to dice rolls in the real world
* @param sides
* @return Int
*/
private static int genNumber(int n){
return 1 + (int)(Math.random() * n);
}
}
| true |
ebe2f8a50a492b40b1c56c31bf296e998623fd0a | Java | Valerivelli/KyryllovaLesson2 | /src/main/java/com/kyryllova/homeworks/hw15/DataMapper.java | UTF-8 | 614 | 2.90625 | 3 | [] | no_license | package com.kyryllova.homeworks.hw15;
public class DataMapper {
public static Person map(String str) {
try {
String[] info = str.split(",");
return new Person.PersonBuilder()
.name(info[0])
.surname(info[1])
.age(Integer.valueOf(info[2]))
.height(Integer.valueOf(info[3]))
.weight(Integer.valueOf(info[4]))
.email(info[5])
.build();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
| true |
7f7904f18082e75639a6ac7d8d1b43f34b0df49c | Java | jp-developer0/hybrisTrail | /bin/modules/backoffice-framework/backoffice/web/testsrc/com/hybris/backoffice/bulkedit/renderer/BulkEditValidationRendererTest.java | UTF-8 | 1,756 | 1.9375 | 2 | [] | no_license | /*
* Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved
*/
package com.hybris.backoffice.bulkedit.renderer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import com.google.common.collect.Lists;
import com.hybris.backoffice.bulkedit.ValidationResult;
import com.hybris.cockpitng.dataaccess.facades.type.TypeFacade;
import com.hybris.cockpitng.validation.impl.DefaultValidationInfo;
import de.hybris.platform.core.model.product.ProductModel;
@RunWith(MockitoJUnitRunner.class)
public class BulkEditValidationRendererTest
{
@Mock
private TypeFacade typeFacade;
@InjectMocks
private BulkEditValidationRenderer renderer;
@Test
public void shouldAddTypePrefixToToInvalidPropertyPath()
{
// given
final ProductModel product = mock(ProductModel.class);
final DefaultValidationInfo info = new DefaultValidationInfo();
info.setInvalidPropertyPath("name[en]");
final List<ValidationResult> validations = Lists.newArrayList(new ValidationResult(product, Lists.newArrayList(info)));
doReturn("Product").when(typeFacade).getType(product);
// when
final List<ValidationResult> results = renderer.addTypePrefixToToInvalidPropertyPath(validations);
// then
assertThat(results).hasSize(1);
assertThat(results.get(0).getItem()).isEqualTo(product);
assertThat(results.get(0).getValidationInfos()).hasSize(1);
assertThat(results.get(0).getValidationInfos().get(0).getInvalidPropertyPath()).isEqualTo("Product.name[en]");
}
}
| true |
6ff7086ad608949dd846ff35f60f00352ee415c6 | Java | vivekbattala/Master_Eclipse_hall | /Workspace/.metadata/.plugins/org.eclipse.core.resources/.history/49/704b7a3083ae00181ee4fdc351da5806 | UTF-8 | 1,457 | 3.40625 | 3 | [] | no_license | package abc;
public class Master extends Scan {
static String scan;
static String optVal;
public static void main(String[] args) {
Master master = new Master();
master.operation(); // this method has got operations to display.
// I separately write the Scanner function in a separate class.
// WE get the user values converted to string and saved in "scan" global variable.
scan = master.fetch(send);
master.validate(); // this method validates the user value and calls the operations.java class
}
public String validate() {
Master master = new Master();
switch (scan) {
case "1":
System.out.println("*** You Have Entered The Fibonacci Operation ***\nPlease Enter a Value to Execute.");
fibo=master.operationVal(user_input_num);
master.fibonacci(fibo);
break;
case "2":
System.out.println("*** You Have Entered Natural Number Operation ***\nPlease Enter a Value to Execute.");
naturalnum=master.operationVal(user_input_num);
master.naturalNum(naturalnum);
break;
default:
System.out.println("**Error**");
}
return null;
}
public void operation() {
System.out.println("Hi there, Please Select the operation from below..??\n");
System.out.println("Press 1. For Fibonacci Operations \nPress 2. For Natural Numbers.");
}
public int operationVal(int num)
{
Master master=new Master();
optVal=master.fetch(send);
num=Integer.parseInt(optVal);
return num;
}
}
| true |
1d122f46fe10fc80e2534f0b6706abd8a0b6cdb7 | Java | papayam/papayam | /src/main/java/com/palfish/framework/command/AssertExistCommand.java | UTF-8 | 1,701 | 2.578125 | 3 | [] | no_license | package com.palfish.framework.command;
import com.palfish.framework.core.DriverManagerFactory;
import com.palfish.framework.utils.ElementUtil;
import com.palfish.framework.utils.Log;
import io.appium.java_client.MobileElement;
import org.openqa.selenium.By;
import org.testng.Assert;
import java.util.List;
public class AssertExistCommand implements Command {
private static Log logger = Log.getLogger(AssertExistCommand.class);
private String arg;
private boolean isElementExist = true;
public AssertExistCommand(String arg) {
this.arg = arg;
}
public AssertExistCommand(String arg, boolean isElementExist) {
this.arg = arg;
this.isElementExist = isElementExist;
}
public void execute() {
String[] str = arg.split(",");
ElementUtil elementUtil = new ElementUtil();
if(str.length == 2) {
By by = elementUtil.getByLocator(str[0], str[1]);
boolean rs = elementUtil.isElementExist(DriverManagerFactory.getInstance().getDriverManager().getRunningDriver(),by,5);
Assert.assertEquals(rs, isElementExist);
} else if(str.length == 3) {
By by = elementUtil.getByLocator(str[0], str[1]);
List<MobileElement> list = elementUtil.findElements(DriverManagerFactory.getInstance().getDriverManager().getRunningDriver(),by,5);
if(Integer.valueOf(str[2]) <= list.size()) {
Assert.assertTrue(true);
} else if(isElementExist) {
Assert.fail("第三个参数超出取值范围,页面该元素有"+list.size()+"个");
} else {
Assert.assertTrue(true);
}
}
}
}
| true |
7c8cb03ab3f8995daa34f3e38b03dc7abf0efc5e | Java | epalafox/FirebaseCourse | /RealtimeDatabase/app/src/main/java/com/frozencore/realtime/realtimedatabase/adapters/TextAdapter.java | UTF-8 | 1,478 | 2.609375 | 3 | [
"MIT"
] | permissive | package com.frozencore.realtime.realtimedatabase.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.frozencore.realtime.realtimedatabase.R;
import java.util.ArrayList;
/**
* This Adapter is to show the text of the messages in a ListView
*/
public class TextAdapter extends BaseAdapter {
ArrayList<String> arrayList;
LayoutInflater layoutInflater;
public TextAdapter(Context context, ArrayList<String> textList)
{
arrayList = textList;
layoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return arrayList.size();
}
@Override
public Object getItem(int i) {
return arrayList.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ContenedorView contenedorView = null;
if(view == null)
{
view = layoutInflater.inflate(R.layout.adapter_text,null);
contenedorView = new ContenedorView();
contenedorView.tvText = view.findViewById(R.id.etMessage);
contenedorView.tvText.setText(arrayList.get(i));
return view;
}
return view;
}
private class ContenedorView{
TextView tvText;
}
}
| true |
340bb67c8267589c17c1c4e210949afb7de63ec2 | Java | Vershal-Igor/ParserWithDB | /src/test/java/com/epam/parser/reader/impl/XMLReaderTest.java | UTF-8 | 1,273 | 2.359375 | 2 | [] | no_license | package com.epam.parser.reader.impl;
import com.epam.entity.Article;
import com.epam.entity.ArticleCreator;
import com.epam.parser.Loader;
import com.epam.parser.reader.Reader;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.util.ResourceBundle;
import static org.junit.Assert.*;
public class XMLReaderTest {
private static final Logger logger = Logger.getLogger(XMLReaderTest.class);
private static final ResourceBundle RB = ResourceBundle.getBundle("properties/common");
private static final Article XML_ARTICLE_3 = new ArticleCreator()
.setTitle(RB.getString("XML.TITLE.3"))
.setAuthor(RB.getString("XML.AUTHOR.3"))
.setContents(RB.getString("XML.CONTENTS.3"))
.create();
Reader xmlReader;
File file;
@Before
public void setUp() throws Exception {
xmlReader = new XMLReader();
file = new File(Loader.getXmlArticle3());
}
@Test
public void shouldReadXMLArticleFromFile() throws Exception {
Article expected;
Article actual;
expected = XML_ARTICLE_3;
actual = xmlReader.read(file);
logger.info(expected);
assertEquals(expected, actual);
}
} | true |
69e9a74efd9b44badc7c82774ee2105b2f8475f8 | Java | MarianSalapa/MyInventory | /src/frames/AllTransactionsFrame.java | UTF-8 | 4,907 | 2.359375 | 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 frames;
import itemsAndTransactions.InventoryItem;
import itemsAndTransactions.Transaction;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;
/**
*
* @author MMM
*/
public class AllTransactionsFrame extends javax.swing.JInternalFrame {
/**
* Creates new form AllTransactionslFrame
*/
public AllTransactionsFrame() {
initComponents();
addRowToTrTable();
}
public void addRowToTrTable(){
DefaultTableModel model= (DefaultTableModel)jTable1.getModel();
ArrayList<Transaction> list=itemsAndTransactions.AddTransaction.listAllTrArrayList();
float totalValue=0;
Object rowData[]=new Object[7];
for (int i=0;i<list.size();i++){
rowData[0]=list.get(i).getNo();
rowData[1]=list.get(i).getDate();
rowData[2]=list.get(i).getType();
rowData[3]=list.get(i).getCode();
rowData[4]=list.get(i).getQ();
rowData[5]=String.format("%.02f",list.get(i).getPrice());
rowData[6]=list.get(i).getDescription();
model.addRow(rowData);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
setClosable(true);
setIconifiable(true);
setMaximizable(true);
setResizable(true);
setVisible(true);
jLabel1.setText("All Transactions");
jButton1.setText("Close");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Trans No", "Date", "Type", "Code", "Q", "Price", "Description"
}
));
jScrollPane2.setViewportView(jTable1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(layout.createSequentialGroup()
.addGap(117, 117, 117)
.addComponent(jButton1)))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 584, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(174, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 357, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(24, 24, 24))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
super.dispose();
}//GEN-LAST:event_jButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
}
| true |
27df2ae27fbac4452f32689a03451eee964b43c7 | Java | ebasurto002/GraphiAppAndroid | /app/src/main/java/eus/ehu/tta/graphiapp/Level3Activity.java | UTF-8 | 3,963 | 2.234375 | 2 | [] | no_license | package eus.ehu.tta.graphiapp;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import eus.ehu.tta.graphiapp.Levels.Nivel3;
public class Level3Activity extends LevelBaseActivity<Nivel3> {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout frameLayout = findViewById(R.id.content_frame);
LayoutInflater inflater = LayoutInflater.from(this);
inflater.inflate(R.layout.activity_level3,frameLayout,true);
if (pin != null)
{
Button button = findViewById(R.id.levelBackButton);
button.setEnabled(false);
puntuacionesArray = getIntent().getDoubleArrayExtra("puntuacionesArray");
}
if (savedInstanceState == null)
{
new getLevelTask(this).execute();
}
else
{
setViews();
setButtons();
}
}
private void setButtons() {
Button button1 = findViewById(R.id.level3Word1);
button1.setEnabled(true);
button1.setOnClickListener(new ButtonOnClickListener(1));
Button button2 = findViewById(R.id.level3Word2);
button2.setOnClickListener(new ButtonOnClickListener(2));
button2.setEnabled(true);
}
private void setViews() {
ImageView imageView = findViewById(R.id.level3Image);
Glide.with(this).load(levelArray[index].getUrlImagen()).into(imageView);
Button button1 = findViewById(R.id.level3Word1);
button1.setText(levelArray[index].getPalabra1());
Button button2 = findViewById(R.id.level3Word2);
button2.setText(levelArray[index].getPalabra2());
}
private class ButtonOnClickListener implements View.OnClickListener {
int position;
public ButtonOnClickListener(int position) {
this.position = position;
}
@Override
public void onClick(View view) {
if (position == levelArray[index].getCorrecta())
{
correctas++;
}
index++;
if (index >= levelArray.length)
{
endLevel(3);
}
else
{
setViews();
}
}
}
protected void endLevel(int numNivel) {
super.endLevel(numNivel);
if (pin != null)
{
puntuacionesArray[2] = (float)(correctas*10)/(float)levelArray.length;
goToNextLevel();
}
}
private void goToNextLevel() {
Intent intent = new Intent(this,Level4Activity.class);
intent.putExtra("pin",pin);
intent.putExtra("puntuacionesArray",puntuacionesArray);
startActivity(intent);
this.finish();
}
private class getLevelTask extends ProgressTask<Nivel3[]>
{
public getLevelTask(Context context) {
super(context);
}
@Override
protected Nivel3[] work() throws Exception {
return business.getNivel3(nickname,pin);
}
@Override
protected void onFinish(Nivel3[] result) {
levelArray = result;
if (levelArray != null) {
if (levelArray.length != 0) {
setViews();
setButtons();
}
else
{
puntuacionesArray[2] = -1;
goToNextLevel();
}
}
else
{
Toast.makeText(Level3Activity.this, "No se ha podido obtener los ejercicios del servidor",Toast.LENGTH_LONG).show();
}
}
}
}
| true |
b96dc0cf49639444c8adf0d209ed83769e2dc421 | Java | gihon19/posNewTexaco | /texacoPos/src/modelo/CierreCaja.java | UTF-8 | 4,381 | 2.265625 | 2 | [] | no_license | package modelo;
import java.math.BigDecimal;
public class CierreCaja {
private Integer id;
private String fecha;
private Integer noFacturaInicio=0;
private Integer noFacturaFinal=0;
private BigDecimal total=new BigDecimal(0.0);
private BigDecimal totalEfectivo=new BigDecimal(0.0);
private BigDecimal efectivoInicial=new BigDecimal(0.0);
private BigDecimal efectivo=new BigDecimal(0.0);
private BigDecimal tarjeta=new BigDecimal(0.0);
private BigDecimal credito=new BigDecimal(0.0);
private BigDecimal isv15=new BigDecimal(0.0);
private BigDecimal totalIsv15=new BigDecimal(0.0);
private BigDecimal totalExcento=new BigDecimal(0.0);
private BigDecimal apertura=new BigDecimal(0.0);
private BigDecimal isv18=new BigDecimal(0.0);
private BigDecimal totalIsv18=new BigDecimal(0.0);
private BigDecimal totalSalida=new BigDecimal(0.0);
private BigDecimal totalCobro=new BigDecimal(0.0);
private BigDecimal totalEfectivoCaja=new BigDecimal(0.0);
private int noSalidaInicial=0;
private int noSalidaFinal=0;
private int noCobroInicial=0;
private int noCobroFinal=0;
private boolean estado=false;
private String usuario="";
public void setEfectivoCaja(BigDecimal t){
totalEfectivoCaja=t;
}
public BigDecimal getEfectivoCaja(){
return totalEfectivoCaja;
}
public void setTotalCobro(BigDecimal t){
totalCobro=t;
}
public BigDecimal getTotalCobro(){
return totalCobro;
}
public void setNoCobroInicial(int noCobro){
noCobroInicial=noCobro;
}
public int getNoCobroInicial(){
return noCobroInicial;
}
public void setNoCobroFinal(int noCobro){
noCobroFinal=noCobro;
}
public int getNoCobroFinal(){
return noCobroFinal;
}
public void setTotalSalida(BigDecimal t){
totalSalida=t;
}
public BigDecimal getTotalSalida(){
return totalSalida;
}
public void setNoSalidaInicial(int noSalida){
noSalidaInicial=noSalida;
}
public int getNoSalidaInicial(){
return noSalidaInicial;
}
public void setNoSalidaFinal(int nSalida){
noSalidaFinal=nSalida;
}
public int getNoSalidaFinal(){
return noSalidaFinal;
}
public void setTotalEfectivo(BigDecimal c){
totalEfectivo=c;
}
public BigDecimal getTotalEfectivo(){
return totalEfectivo;
}
public void setTotalExcento(BigDecimal c){
totalExcento=c;
}
public BigDecimal getTotalExcento(){
return totalExcento;
}
public void setTotalIsv18(BigDecimal c){
totalIsv18=c;
}
public BigDecimal getTotalIsv18(){
return totalIsv18;
}
public void setTotalIsv15(BigDecimal c){
totalIsv15=c;
}
public BigDecimal getTotalIsv15(){
return totalIsv15;
}
public void setUsuario(String u){
usuario=u;
}
public String getUsuario(){
return usuario;
}
public void setId(Integer i){
id=i;
}
public Integer getId(){
return id;
}
public void setEstado(boolean e){
estado=e;
}
public boolean getEstado(){
return estado;
}
public void setCredito(BigDecimal c){
credito=c;
}
public BigDecimal getCredito(){
return credito;
}
public void setApertura(BigDecimal a){
apertura=a;
}
public BigDecimal getApertura(){
return apertura;
}
public void setIsv15(BigDecimal i){
isv15=i;
}
public BigDecimal getIsv15(){
return isv15;
}
public void setIsv18(BigDecimal i){
isv18=i;
}
public BigDecimal getIsv18(){
return isv18;
}
public void setEfectivo(BigDecimal e){
efectivo=e;
}
public BigDecimal getEfectivo(){
return efectivo;
}
public void setEfectivoInicial(BigDecimal e){
efectivoInicial=e;
}
public BigDecimal getEfectivoInicial(){
return efectivoInicial;
}
public void setTarjeta(BigDecimal t){
tarjeta=t;
}
public BigDecimal getTarjeta(){
return tarjeta;
}
public void setTotal(BigDecimal t){
total=t;
}
public BigDecimal getTotal(){
return total;
}
public void setNoFacturaFinal(Integer i){
noFacturaFinal=i;
}
public Integer getNoFacturaFinal(){
return noFacturaFinal;
}
public void setNoFacturaInicio(Integer i){
noFacturaInicio=i;
}
public Integer getNoFacturaInicio(){
return noFacturaInicio;
}
public void setFecha(String f){
fecha=f;
}
public String getFecha(){
return fecha;
}
}
| true |
0a44e08f5d80f25924e6ad13be666157beb0dca8 | Java | 596861134/PayModule | /android/app/src/main/java/com/paymodule/weixin/ConnectCallBack.java | UTF-8 | 144 | 1.734375 | 2 | [] | no_license | package com.paymodule.weixin;
public interface ConnectCallBack {
public void onResponse(String response);
public void onNetError();
}
| true |
c63e55a84520d507c8ed6b51953db0533cc2dd43 | Java | leesj8115/CloneProject | /src/main/java/the/domain/dto/test/TestWriteDto.java | UTF-8 | 907 | 2.140625 | 2 | [] | no_license | package the.domain.dto.test;
import java.time.LocalDateTime;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import the.domain.entity.test.TestEntity;
@AllArgsConstructor
@RequiredArgsConstructor
@Data
public class TestWriteDto {
private String title;
@DateTimeFormat(iso = ISO.DATE_TIME)
private LocalDateTime startDate;
@DateTimeFormat(iso = ISO.DATE_TIME)
private LocalDateTime endDate;
// 파일은 수동으로 설정
private String fileName;
private String fileUrl;
private long fileSize;
public TestEntity toEntity() {
return TestEntity.builder()
.title(title)
.startDate(startDate)
.endDate(endDate)
.fileName(fileName)
.fileUrl(fileUrl)
.fileSize(fileSize)
.build();
}
}
| true |
b1ab6e4cec9caf642869d83253c7f3ae2eab23d8 | Java | PuddleHound/All-Dem-Dimensions | /alldemdimensions/world/gen/WorldGenNetherCrevice.java | UTF-8 | 1,492 | 2.515625 | 3 | [] | no_license | package alldemdimensions.world.gen;
import java.util.Random;
import net.minecraft.init.Blocks;
import net.minecraft.world.World;
import net.minecraft.world.gen.feature.WorldGenerator;
public class WorldGenNetherCrevice extends WorldGenerator
{
@Override
public boolean generate(World world, Random random, int i, int j, int k)
{
if(j <= 5 || j > 32 || !world.getBlock(i, j, k).getMaterial().isSolid())
{
return true;
}
addSection(world, random, i, j, k, 0, random.nextInt(3) - 1, random.nextInt(3) - 1);
return true;
}
private void addSection(World world, Random random, int i, int j, int k, int count, int dirX, int dirZ)
{
if(random.nextInt(3) == 0 || (dirX == 0 && random.nextBoolean()))
{
dirX = random.nextInt(3) - 1;
}
if(random.nextInt(3) == 0 || (dirZ == 0 && random.nextBoolean()))
{
dirZ = random.nextInt(3) - 1;
}
if((dirX == 0 && dirZ == 0) || count > 64)
{
return;
}
int l = 0;
while(l < 32)
{
if(world.isAirBlock(i, j + l, k))
{
break;
}
func_150515_a(world, i, j + l, k, Blocks.air);
func_150515_a(world, i + 1, j + l, k, Blocks.air);
l++;
}
addSection(world, random, i + dirX, j + random.nextInt(3) - 1, k + dirZ, count + 1, dirX, dirZ);
}
} | true |
fdfdf49de9cc67f6f16036696834f6ad1312c4ce | Java | raymondcqk/MVPCommon | /MVPCommon/app/src/main/java/edu/com/mvpcommon/setting/SettingsActivity.java | UTF-8 | 1,978 | 2.09375 | 2 | [
"Apache-2.0"
] | permissive | package edu.com.mvpcommon.setting;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import edu.com.mvpcommon.R;
import edu.com.mvplibrary.ui.activity.AbsSwipeBackActivity;
import edu.com.mvplibrary.ui.widget.CircleImageView;
/**
* Created by Anthony on 2016/5/10.
* Class Note:
* SettingsActivity using {@link PreferenceFragment},support swipe back
*/
public class SettingsActivity extends AbsSwipeBackActivity {
@Bind(R.id.title_image_left)
CircleImageView titleImageLeft;
@Bind(R.id.title_txt_center)
TextView titleTxtCenter;
@Bind(R.id.title_txt_right)
TextView titleTxtRight;
@Bind(R.id.setting_content)
RelativeLayout settingContent;
// @Bind(R.id.setting_content)
// RelativeLayout mSettingContent;
@Override
protected View getLoadingTargetView() {
return settingContent;
}
@Override
protected void initViewsAndEvents() {
// Display the fragment as the main content.
titleTxtCenter.setText("设置");
titleTxtRight.setVisibility(View.GONE);
titleImageLeft.setImageResource(R.mipmap.ico_back);
getFragmentManager().beginTransaction()
.replace(R.id.setting_content, new SettingsFragment())
.commit();
}
@Override
protected int getContentViewID() {
return R.layout.activity_settings;
}
@Override
protected boolean isApplyStatusBarTranslucency() {
return false;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: add setContentView(...) invocation
ButterKnife.bind(this);
}
@OnClick(R.id.title_image_left)
public void onClick() {
scrollToFinishActivity();
}
}
| true |
693dd01dd7c70a6fc3747c595bbe54e1ecca5f81 | Java | shuifan/javaStudy | /src/other/SerialCloneable.java | UTF-8 | 764 | 2.71875 | 3 | [] | no_license | package other;
import java.io.*;
/**
* @author fandong
* @create 2018/5/7
*/
public class SerialCloneable implements Serializable, Cloneable{
@Override
public Object clone(){
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(bout);
objectOutputStream.writeObject(this);
objectOutputStream.close();
ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bout.toByteArray()));
Object object = objectInputStream.readObject();
objectInputStream.close();
return object;
}catch (Exception e){
return null;
}
}
}
| true |
0e1214e8b84b25e82de01b8b33e944bbbbffc093 | Java | minnal/minnal | /minnal-jaxrs/minnal-instrumentation-jaxrs/src/main/java/org/minnal/instrument/resource/metadata/handler/PathAnnotationHandler.java | UTF-8 | 1,752 | 2.390625 | 2 | [
"Apache-2.0"
] | permissive | /**
*
*/
package org.minnal.instrument.resource.metadata.handler;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Set;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import org.minnal.instrument.resource.metadata.ResourceMetaData;
import org.minnal.utils.http.HttpUtil;
import org.minnal.utils.reflection.ClassUtils;
import com.google.common.collect.Sets;
/**
* @author ganeshs
*
*/
public class PathAnnotationHandler extends AbstractResourceAnnotationHandler {
public static final Set<Class<? extends Annotation>> httpMethods = Sets.newHashSet(GET.class, PUT.class, DELETE.class, POST.class, HEAD.class, OPTIONS.class);
/**
* @param metaData
* @param annotation
* @param method
*/
public void handle(ResourceMetaData metaData, Annotation annotation, Method method) {
if (! hasHttpMethod(method)) {
ResourceMetaData subResource = new ResourceMetaData(method.getReturnType(), HttpUtil.concatPaths(metaData.getPath(), ((Path)annotation).value()));
metaData.addSubResource(subResource);
}
}
public Class<?> getAnnotationType() {
return Path.class;
}
/**
* Checks if a HTTP method annotation is defined for the given method
*
* @param method
* @return
*/
protected boolean hasHttpMethod(Method method) {
for (Class<? extends Annotation> annotationClass : httpMethods) {
if (ClassUtils.hasAnnotation(method, annotationClass)) {
return true;
}
}
return false;
}
@Override
public void handle(ResourceMetaData metaData, Annotation annotation, Field field) {
// do nothing
}
}
| true |
e9fba8c0ed2869155bda348439cf56d5570669bd | Java | whddbs507/bitcamp-study | /bitcamp-java/src/main/java/com/eomcs/oop/ex08/test/B.java | UTF-8 | 647 | 2.9375 | 3 | [] | no_license | package com.eomcs.oop.ex08.test;
public class B {
// field
static int a; // 클래스 필드 = 스태틱 필드
String b; // 인스턴스 필드 = 논스태틱 필드
// method
static void m1() { // 클래스 메서드 = 스태틱 메서드
}
int m2() { // 인스턴스 메서드 = 논스태틱 메서드
return 0;
}
// initializer block
static {} // 스태틱 블록
{} // 인스턴스 블록
// constructor(생성자)
B() {}
// nested class
static class L1 {} // static nested class
class L2 {} // non-static nested class = inner class
}
| true |
a5d127a3561c0ea019ccc28f2dbd482e3563b9bf | Java | chiangfire/cql-desktop | /src/main/java/com/firecode/cqldesktop/app/DialogPanel.java | UTF-8 | 7,375 | 2.359375 | 2 | [
"MIT"
] | permissive | /*
* Copyright 2002 and later by MH Software-Entwicklung. All rights reserved.
* Use is subject to license terms.
*/
package com.firecode.cqldesktop.app;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FileDialog;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import com.firecode.cqldesktop.GridBagHelper;
import com.firecode.cqldesktop.images.ImageHelper;
import com.firecode.cqldesktop.utils.StyleUtils;
/**
*
* @author Michael Hagen
*/
public class DialogPanel extends JPanel {
private Component parent = null;
private JButton informationButton = null;
private JButton confirmationButton = null;
private JButton warningButton = null;
private JButton errorButton = null;
private JButton optionButton = null;
private JButton nativeFileChooserButton = null;
private JButton fileChooserButton = null;
private JButton colorChooserButton = null;
private JButton customDialogButton = null;
private FileDialog fileDialog = null;
public DialogPanel(Component aParent) {
super(new BorderLayout());
parent = aParent;
init();
}
private void init() {
setName("Dialogs");
setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
informationButton = new JButton("Information dialog");
informationButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(parent, "Information dialog", "Information", JOptionPane.INFORMATION_MESSAGE);
}
});
confirmationButton = new JButton("Confirmation dialog");
confirmationButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(parent, "Confirmation dialog", "Confirmation", JOptionPane.QUESTION_MESSAGE);
}
});
warningButton = new JButton("Warning dialog");
warningButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(parent, "Warning dialog", "Warning", JOptionPane.WARNING_MESSAGE);
}
});
errorButton = new JButton("Error dialog");
errorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(parent, "Error dialog", "Error", JOptionPane.ERROR_MESSAGE);
}
});
optionButton = new JButton("Option dialog");
optionButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] options = {"Yes", "No"};
int confirm = JOptionPane.showOptionDialog(null, "Please select yes or no using the keyboard (tab/enter) keys\n", "Confirmation Required", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,null, options, options[1]);
if (confirm == 0 || confirm == 1) {
optionButton.setText("Option dialog. Selected: " + options[confirm]);
} else {
optionButton.setText("Option dialog. Selected: nothing ");
}
}
});
nativeFileChooserButton = new JButton("Native FileChooser dialog");
nativeFileChooserButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fileDialog = new FileDialog(JOptionPane.getFrameForComponent(parent), "Open File");
fileDialog .setResizable(true);
fileDialog .setVisible(true);
}
});
fileChooserButton = new JButton("FileChooser dialog");
fileChooserButton.setEnabled(!(parent instanceof JApplet));
fileChooserButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(parent);
}
});
colorChooserButton = new JButton("ColorChooser dialog");
colorChooserButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Color c = JColorChooser.showDialog(parent, "JColorChooser", Color.blue);
}
});
customDialogButton = new JButton("Custom dialog");
customDialogButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openCustomDialog();
}
});
JPanel contentPanel = new JPanel(new GridBagLayout());
GridBagHelper.addComponent(contentPanel, informationButton, 0, 0, 1, 1, 16, 8, 0, 4, 0.0, 0.0, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER);
GridBagHelper.addComponent(contentPanel, confirmationButton, 0, 1, 1, 1, 16, 8, 0, 4, 0.0, 0.0, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER);
GridBagHelper.addComponent(contentPanel, warningButton, 0, 2, 1, 1, 16, 8, 0, 4, 0.0, 0.0, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER);
GridBagHelper.addComponent(contentPanel, errorButton, 0, 3, 1, 1, 16, 8, 0, 4, 0.0, 0.0, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER);
GridBagHelper.addComponent(contentPanel, optionButton, 0, 4, 1, 1, 16, 8, 0, 4, 0.0, 0.0, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER);
GridBagHelper.addComponent(contentPanel, nativeFileChooserButton, 0, 5, 1, 1, 16, 8, 0, 4, 0.0, 0.0, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER);
GridBagHelper.addComponent(contentPanel, fileChooserButton, 0, 6, 1, 1, 16, 8, 0, 4, 0.0, 0.0, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER);
GridBagHelper.addComponent(contentPanel, colorChooserButton, 0, 7, 1, 1, 16, 8, 0, 4, 0.0, 0.0, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER);
GridBagHelper.addComponent(contentPanel, customDialogButton, 0, 8, 1, 1, 16, 8, 0, 4, 0.0, 0.0, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER);
JScrollPane scrollPane = new JScrollPane(contentPanel);
scrollPane.setBorder(BorderFactory.createEmptyBorder());
add(scrollPane, BorderLayout.CENTER);
}
private void openCustomDialog() {
JDialog dlg = new JDialog(Main.app, "Custom dialog");
dlg.setResizable(false);
CustomDialogPanel panel = new CustomDialogPanel(dlg);
dlg.setContentPane(panel);
int x = Main.app.getLocation().x + 200;
int y = Main.app.getLocation().y + 100;
dlg.setBounds(x, y, 336, 240);
if (StyleUtils.getJavaVersion() >= 1.6) {
dlg.setIconImage(ImageHelper.loadImage("cab_small.gif").getImage());
}
dlg.setVisible(true);
}
}
| true |
5f1cf0f07dfa184c23206f3155aa38f52203f404 | Java | BugBang/paipaixueche | /DGJP/src/com/session/dgjp/request/GetAllCityRequestData.java | UTF-8 | 618 | 1.765625 | 2 | [] | no_license | package com.session.dgjp.request;
import com.session.common.BaseRequestData;
/** 获取所有城市 */
public class GetAllCityRequestData extends BaseRequestData {
private static final long serialVersionUID = 5932121751388817057L;
private int pageIndex = 1;
private int pageSize = 0;
public int getPageIndex() {
return pageIndex;
}
public void setPageIndex(int pageIndex) {
this.pageIndex = pageIndex;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
@Override
protected String getSpecificUrlPath() {
return "";
}
}
| true |
be78e136e38d1bb63fdcad92c6cf0b4eabf7c5f2 | Java | yizhou136/zystudio | /zystudio-leaning/common-java/src/main/java/com/zy/common/alg/TrieTree.java | UTF-8 | 307 | 2.234375 | 2 | [] | no_license | package com.zy.common.alg;
import java.util.HashMap;
import java.util.Set;
/**
* @author by zy.
*/
public class TrieTree {
private HashMap<String, Object> senstivsWordTree;
public void addSenstiveWord(Set<String> wordSet){
senstivsWordTree = new HashMap<>(wordSet.size());
}
}
| true |
6b29eac5befb7bd74cb425fd8eab4a0251963e53 | Java | chamanbharti/java-works | /data-structure-and-algorithm/data-structure-with-algorithms/src/main/java/ds/linear/arraylist/DynamicArray.java | UTF-8 | 1,578 | 4.1875 | 4 | [] | no_license | package ds.linear.arraylist;
class Array{
private int[] items;
private int count;
public Array(int length) {
items = new int[length];
}
public void add(int item) {
//if the array is full, resize it,
if(items.length == count) {
//create a new array (twice the size)
int[] newItems = new int[count * 2];
//copy all the existing items
for (int i = 0; i < count; i++) {
newItems[i] = items[i];
}
//set items to this new array
items = newItems;
}
//add the new item at the end
items[count++] = item;
}
public void remove(int index) {
//validate the index
if(index < 0 || index >= count) {
throw new IllegalArgumentException();
}
//shift the items to the left to fill the hole
for (int i = index; i < count; i++) {
items[i] = items[i+1];
}
}
public int indexOf(int item) {
// int index = -1;
// for (int i = 0; i < count; i++) {
// if(items[i] == item) {
// index = i;
// break;
// }
// }
// return index;
//if we find it, return index, otherwise return -1
//Best Case O(1)
//Worst Case O(n)
for (int i = 0; i < count; i++)
if(items[i] == item)
return i;
return -1;
}
public void print() {
// for (int i = 0; i < items.length; i++) {
for (int i = 0; i < count; i++) {
System.out.println(items[i]);
}
}
}
public class DynamicArray {
public static void main(String[] args) {
Array al = new Array(3);
al.add(10);
al.add(20);
al.add(30);
al.add(40);
//al.remove(5);
System.out.println("index of "+al.indexOf(5));
al.print();
}
}
| true |
b4d9d856bb3e4786271e241cdd7a744d435bf768 | Java | ezaack/desafio-coopersystem | /teste-backend/src/main/java/br/com/teste/testebackend/negocio/servico/ClienteService.java | UTF-8 | 798 | 2.234375 | 2 | [] | no_license | package br.com.teste.testebackend.negocio.servico;
import br.com.teste.testebackend.negocio.entidade.Cliente;
import br.com.teste.testebackend.negocio.repositorio.ClienteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ClienteService {
@Autowired
private ClienteRepository repository;
public Cliente salvar(Cliente cliente){
return this.repository.save(cliente);
}
public Cliente recupera(Integer id) {
return repository.findById(id).orElse(null);
}
public List<Cliente> listaTodos(){
return (List<Cliente>) repository.findAll();
}
public void apaga(Cliente cliente){
repository.delete(cliente);
}
}
| true |