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 |
---|---|---|---|---|---|---|---|---|---|---|---|
3c626f46b7c73bdb8b8e976ebf719a7e3816873b
|
Java
|
srathore2/java_project
|
/JavaProject/src/com/common/StringNumberAtlastCheck.java
|
UTF-8
| 685 | 3.28125 | 3 |
[] |
no_license
|
package com.common;
public class StringNumberAtlastCheck {
public static void main(String[] args) {
String s="geeksforgeeks13";
int length=s.length();
System.out.println("length:"+length);
System.out.println(s.charAt(length-1));
int count =0;
for(int i=length;i>0;i--){
if(Character.isDigit(s.charAt(i-1))){
count++;
}
}
System.out.println("count is"+count);
System.out.println("number string "+s.substring(length-count, length));
Integer number=Integer.parseInt(s.substring(length-count, length));
int stringlength=length-count;
if(number==stringlength){
System.out.println("ture");
}else{
System.out.println("false");
}
}
}
| true |
4f78e856ef6f3752253eeabc9fcbf0930c5727df
|
Java
|
brzaskun/NetBeansProjects
|
/taxmanfk/src/main/java/view/DeklaracjaVatPozycjeKoncoweView.java
|
UTF-8
| 2,666 | 1.976563 | 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 view;
import dao.DeklaracjaVatPozycjeKoncoweDAO;
import entity.DeklaracjaVatPozycjeKoncowe;
import error.E;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import msg.Msg;
/**
*
* @author Osito
*/
@Named
@ViewScoped
public class DeklaracjaVatPozycjeKoncoweView implements Serializable {
@Inject
private DeklaracjaVatPozycjeKoncoweDAO deklaracjaVatPozycjeKoncoweDAO;
private List<DeklaracjaVatPozycjeKoncowe> wierszesumarycznelista;
@Inject
private DeklaracjaVatPozycjeKoncowe nazwawierszasumarycznego;
public DeklaracjaVatPozycjeKoncoweView() {
}
@PostConstruct
private void init() { //E.m(this);
wierszesumarycznelista = deklaracjaVatPozycjeKoncoweDAO.findAll();
}
public void dodajwiersz() {
try {
deklaracjaVatPozycjeKoncoweDAO.create(nazwawierszasumarycznego);
wierszesumarycznelista.add(nazwawierszasumarycznego);
nazwawierszasumarycznego = new DeklaracjaVatPozycjeKoncowe();
Msg.msg("Dodano nowy wiersz sumaryczny");
} catch (Exception e) {
E.e(e);
}
}
public void usun(DeklaracjaVatPozycjeKoncowe i) {
deklaracjaVatPozycjeKoncoweDAO.remove(i);
wierszesumarycznelista.remove(i);
Msg.msg("Usunięto wiersz sumaryczny");
}
public DeklaracjaVatPozycjeKoncoweDAO getDeklaracjaVatPozycjeKoncoweDAO() {
return deklaracjaVatPozycjeKoncoweDAO;
}
public void setDeklaracjaVatPozycjeKoncoweDAO(DeklaracjaVatPozycjeKoncoweDAO deklaracjaVatPozycjeKoncoweDAO) {
this.deklaracjaVatPozycjeKoncoweDAO = deklaracjaVatPozycjeKoncoweDAO;
}
public List<DeklaracjaVatPozycjeKoncowe> getWierszesumarycznelista() {
return wierszesumarycznelista;
}
public void setWierszesumarycznelista(List<DeklaracjaVatPozycjeKoncowe> wierszesumarycznelista) {
this.wierszesumarycznelista = wierszesumarycznelista;
}
public DeklaracjaVatPozycjeKoncowe getNazwawierszasumarycznego() {
return nazwawierszasumarycznego;
}
public void setNazwawierszasumarycznego(DeklaracjaVatPozycjeKoncowe nazwawierszasumarycznego) {
this.nazwawierszasumarycznego = nazwawierszasumarycznego;
}
}
| true |
ce117fd41974ee8e1738b825adce3d8bc19b617d
|
Java
|
santhoshArun/database-migration
|
/src/migration/MySQLtoPostgreSQL.java
|
UTF-8
| 7,958 | 2.84375 | 3 |
[] |
no_license
|
package migration;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class MySQLtoPostgreSQL {
static Connection connection_mysql = null;
static PreparedStatement statement_mysql = null;
static Connection connection_postgres = null;
static PreparedStatement statement_postgres = null;
static File file = new File("E:\\migration\\key\\aes_key.txt"); //save your key at this location or copy your key location here
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String aes_key = null;
aes_key = br.readLine();
br.close();
//mysql database connection
Class.forName("com.mysql.cj.jdbc.Driver");
connection_mysql = DriverManager.getConnection("jdbc:mysql://localhost:3306/migration", "root", "ch3coona");
System.out.println("mysql database connected");
//postgres database connection
Class.forName("org.postgresql.Driver");
connection_postgres = DriverManager.getConnection("jdbc:postgresql://localhost:5432/migration", "postgres", "ch3coona");
System.out.println("postgres database connected");
//extracting all existing tables from mysql
statement_mysql = connection_mysql.prepareStatement("SHOW FULL TABLES WHERE Table_type != 'VIEW'");
ResultSet rs_mysql_table = statement_mysql.executeQuery();
//the real work starts here
//for every table in mysql, this block creates query for creating table
//inserting data with all constraints and the executes the query
//so as to insert the data in postgres database
while(rs_mysql_table.next()) {
String table_name = rs_mysql_table.getString(1);
//deletes table if any exists with the same name in postgres
//drop_existing_table(table_name);
//creates SQL query for each table
String query_mysql = create_query(table_name);
System.out.println("generated 'create' query: " + query_mysql);
///*
//create tables in postgres
statement_postgres = connection_postgres.prepareStatement(query_mysql);
statement_postgres.execute();
//*/
//creates SQL query for inserting data
String data_mysql = data_query(table_name, aes_key);
System.out.println("generated 'insert' query: " + data_mysql);
///*
//insert data in postgres
statement_postgres = connection_postgres.prepareStatement(data_mysql);
statement_postgres.execute();
//*/
System.out.println("'" + table_name + "' migrated successfully...");
}
} catch(Exception e) {
System.out.println("error... " + e.getMessage()); //no one cares
}
}
static void drop_existing_table(String table_name) throws SQLException{
System.out.println("dropping the table '" + table_name + "' if exists in postgres...");
statement_postgres = connection_postgres.prepareStatement("DROP TABLE IF EXISTS " + table_name);
statement_postgres.execute();
}
//this method generates query for creating table with postgres compatibility
static String create_query(String table_name) throws SQLException {
//all changes for create table query like BIT to BOOLEAN
//BLOB to TEXT, AUTO_INCREMENT, PK, FK setting are done here
//we use metadata to extract all information about columns
statement_mysql = connection_mysql.prepareStatement("SELECT * FROM " + table_name);
ResultSetMetaData rsmd_mysql_column = statement_mysql.getMetaData();
int rsmd_mysql_column_count = rsmd_mysql_column.getColumnCount();
StringBuilder query_mysql = new StringBuilder("CREATE TABLE " + table_name + "(");
int count = 1;
while(count <= rsmd_mysql_column_count) {
String mysql_column_name = rsmd_mysql_column.getColumnName(count);
String mysql_column_type_name = rsmd_mysql_column.getColumnTypeName(count);
query_mysql.append(mysql_column_name + " ");
//changes bit to boolean
if(mysql_column_type_name.equals("BIT")) {
mysql_column_type_name = "BOOLEAN";
}
//changes blob to text
if(mysql_column_type_name.equals("BLOB")) {
mysql_column_type_name = "BYTEA";
}
//sets size for varchar
if(mysql_column_type_name.equals("VARCHAR")) {
int size = rsmd_mysql_column.getPrecision(count);
query_mysql.append(mysql_column_type_name + "(" + size +")" + ", ");
} else {
query_mysql.append(mysql_column_type_name + ", ");
}
//sets auto increment
if(rsmd_mysql_column.isAutoIncrement(count)) {
query_mysql.setLength(query_mysql.length()-5);
query_mysql.append("SERIAL, ");
}
//sets not null
if(rsmd_mysql_column.isNullable(count) == 0) {
query_mysql.setLength(query_mysql.length()-2);
query_mysql.append(" NOT NULL, ");
}
count++;
}
//sets key constraints
//from information schema we can obtain where pk enabled, fk and where it references
statement_mysql = connection_mysql.prepareStatement("SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE table_schema = 'migration' and table_name = '" + table_name + "';");
ResultSet rs_constraints = statement_mysql.executeQuery();
while(rs_constraints.next()) {
String constraint = rs_constraints.getString(3);
if(constraint.equals("PRIMARY")) {
query_mysql.append("PRIMARY KEY ("+ rs_constraints.getString(7) +"), ");
} else {
query_mysql.append("FOREIGN KEY (" + rs_constraints.getString(7)+") REFERENCES " + rs_constraints.getString(11) + "(" + rs_constraints.getString(12) + "), ");
}
}
//final touch for generation query
query_mysql.setLength(query_mysql.length()-2);
query_mysql.append(");");
return query_mysql.toString();
}
//this method generates query for inserting data with postgres compatibility
static String data_query(String table_name, String aes_key) throws SQLException {
//the changes like single quotes(') for text are done here and aes_decryption too
statement_mysql = connection_mysql.prepareStatement("SELECT * FROM " + table_name);
ResultSet rs_data = statement_mysql.executeQuery();
ResultSetMetaData rsmd_data = statement_mysql.getMetaData();
int column_size = rsmd_data.getColumnCount();
StringBuilder data_query = new StringBuilder("INSERT INTO " + table_name + " VALUES(");
int row = 1;
while(rs_data.next()) {
int count = 1;
while(count <= column_size) {
String type = rs_data.getMetaData().getColumnTypeName(count);
if(type.equals("INT")) {
data_query.append(rs_data.getString(count) + ", ");
}
//this statement decrypts aes encrypted password by mysterious way, it works! difficult to explain here
else if(type.equals("BLOB")) {
statement_mysql = connection_mysql.prepareStatement("SELECT CAST(AES_DECRYPT(" + rs_data.getMetaData().getColumnName(count) + ", '" + aes_key + "') AS CHAR(50)) FROM " + table_name + ";");
ResultSet rs = statement_mysql.executeQuery();
String password = null;
int row_count = 0;
while(rs.next() && row != row_count) {
password = rs.getString(1);
row_count++;
}
//pgp_sym_encrypt for encryption back the password with postgres compatibility
data_query.append("PGP_SYM_ENCRYPT('" + password + "', '" + aes_key + "'), ");
row++;
} else {
data_query.append("'" + rs_data.getString(count) + "', ");
}
count++;
}
data_query.setLength(data_query.length()-2);
data_query.append("),(");
}
//final touch
data_query.setLength(data_query.length()-2);
data_query.append(";");
return data_query.toString();
}
}
| true |
0a405019e0d68728c852cdad1b85775fc06f3164
|
Java
|
BrunoTrojahnBolzan/Jogo-grafos
|
/IA/Grafo.java
|
UTF-8
| 3,280 | 3.71875 | 4 |
[] |
no_license
|
package com.gLstudios.IA;
// importando classes de Lista encadeada do Java
import java.util.LinkedList;
import com.gLstudios.world.World;
public class Grafo {
Nodo g[][] = new Nodo[World.WIDTH][World.HEIGHT]; // Matriz que representa o grafo
public int xInicio, yInicio; // Coordenadas de início
public int xFim, yFim; // Coordenadas de fim
public int menor = 9999999; // Menor distância percorrida
public LinkedList<Coord> caminhoMenor = new LinkedList<Coord>(); // Lista encadeada que salva caminho menor
LinkedList<Coord> caminhoAux = new LinkedList<Coord>(); // Lista encadeada que salva caminho atual
public Grafo() { // Função construtora do Grafo
for(int i = 0; i < World.WIDTH; i++) {
for (int j=0; j<World.HEIGHT; j++) {
g[i][j] = new Nodo(0); // aloca espaço para cada nodo
}
}
}
class Nodo { // classe que determina estrutura do Nodo
int peso;
boolean visit;
public Nodo(int peso){ // função construtora do Nodo
this.peso = peso;
this.visit = false;
}
}
class Coord { // classe que representa coordenada
int x, y;
Coord(int x, int y){ // Função construtora da Coord
this.x = x;
this.y = y;
}
}
public void definePeso(int x, int y, int w) { // função que atribui pesos
g[x][y].peso = w;
}
/*
Objetivo: Encontrar menor caminho em um grafo recursivamente
Entrada: Grafo, coordenadas do ínicio, distância
Saída: Menor caminho possível
*/
public void procuraMenorCaminho(int x, int y, int distancia) {
caminhoAux.add(new Coord(x, y)); // adiciona posição atual a Lista de coordenadas auxiliar
if(!(x == xFim && y == yFim)) { // verifica se está no fim do caminho
g[x][y].visit = true; // marca posição como visitada
if(g[x][y - 1].peso != -1 && g[x][y - 1].visit == false) { // se há caminho acima
procuraMenorCaminho(x, y - 1, distancia + g[x][y - 1].peso); // chama recursivamente a função
}
if(g[x + 1][y].peso != -1 && g[x + 1][y].visit == false) { // se há caminho à direita
procuraMenorCaminho(x + 1, y, distancia + g[x + 1][y].peso); // chama recursivamente a função
}
if(g[x][y + 1].peso != -1 && g[x][y + 1].visit == false) { // se há caminho abaixo
procuraMenorCaminho(x, y + 1, distancia + g[x][y + 1].peso); // chama recursivamente a função
}
}else { // se está no fim
if(distancia < menor) { // se o caminho encontrado é mais curto
menor = distancia; // sua distância é salva como menor
caminhoMenor = (LinkedList<Coord>) caminhoAux.clone(); // ele é salvo como menor caminho
}
}
// Limpa o caminho auxiliar ao desempilhar
if(caminhoAux.size() > 0)
caminhoAux.removeLast() ;
else
caminhoAux.clear();
g[x][y].visit = false; // redefine as posições como não visitadas ao desempilhar
}
public void printgrafo() { // função de teste que imprime grafo
for (int i=0; i<World.WIDTH; i++)
{
for (int j=0; j<World.HEIGHT; j++)
System.out.print(g[i][j]+" ");
System.out.println();
}
}
}
| true |
6de2eea8d2059052b695169348557b2228b04003
|
Java
|
vaishsh/copart-g1-contract-services
|
/src/main/java/com/copart/g1/contracts/repository/SubhaulerRepository.java
|
UTF-8
| 301 | 1.664063 | 2 |
[] |
no_license
|
package com.copart.g1.contracts.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.copart.g1.contracts.domain.Subhauler;
@Repository
public interface SubhaulerRepository extends CrudRepository<Subhauler, Long>
{
}
| true |
0a0c09ef5255915673ed8713630508f5049b8246
|
Java
|
Alison-NET/MedicalSystem
|
/src/main/java/com/alisonnet/medicalsystem/employeeportal/entity/account/unregistered/UnregisteredPickUpTime.java
|
UTF-8
| 682 | 1.859375 | 2 |
[] |
no_license
|
package com.alisonnet.medicalsystem.employeeportal.entity.account.unregistered;
import com.alisonnet.medicalsystem.employeeportal.entity.account.PickUpTimeBase;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.time.LocalTime;
@Entity
@Data
@EqualsAndHashCode(exclude = "specimenPickUpDayTime", callSuper = true)
@ToString(exclude = "specimenPickUpDayTime")
@Table(name = "unregistered_pick_up_times")
public class UnregisteredPickUpTime extends PickUpTimeBase {
@ManyToOne
private UnregisteredSpecimenPickUpDayTime specimenPickUpDayTime;
}
| true |
03b3337a93b21e0d16081bf17bc9b3e0e0a211cf
|
Java
|
2019-Arizona-Opportunity-Hack/Team-7
|
/manager/src/main/java/com/zuri/circle/manager/Request/DonationRequest.java
|
UTF-8
| 612 | 2.25 | 2 |
[] |
no_license
|
package com.zuri.circle.manager.Request;
import java.io.Serializable;
public class DonationRequest implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String donor;
private String amount;
public DonationRequest(String donor, String amount) {
super();
this.donor = donor;
this.amount = amount;
}
public DonationRequest() {}
public String getDonor() {
return donor;
}
public void setDonor(String donor) {
this.donor = donor;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
| true |
266605da13e60c15be6013782a5c87f37f8e4aca
|
Java
|
Salmon4/MKS22X-Quick
|
/Quick.java
|
UTF-8
| 9,029 | 3.296875 | 3 |
[] |
no_license
|
import java.util.*;
import java.util.Arrays;
public class Quick{
public static void quicksort(int[] data){
//quicksortHelper(data, 0 , data.length - 1);
quicksortDutchHelper(data,0,data.length-1);
}
private static void quicksortDutchHelper(int[] data, int start, int end){
if (start >= end){
return;
}
//else{
// System.out.println("1: " + data.length);
int[] data2 = partitionDutch(data,start,end);
//System.out.println("1: " + data2.length);
if (data2[0] - start <= 50){
insertionsort(data,start,data2[0]);
}
else{
quicksortDutchHelper(data,start,data2[0]);
}
if (end - data2[1] <= 50){
insertionsort(data,data2[1],end);
}
else{
quicksortDutchHelper(data,data2[1],end);
}
// }
}
public static void insertionsort(int[] data, int lo, int hi){
for (int i = lo; i <= hi;i++){
int orig = data[i];
int c = i;
while (c > lo && data[c-1] > orig){//left number is bigger
data[c] = data[c-1];
//data[c] = orig;
c--;
}
data[c] = orig;
}
}
private static void quicksortHelper(int[] data, int lo, int hi){
if (lo >= hi){
return;
}
//debug(data);
int pivot = partition(data,lo,hi);
//debug(data);
quicksortHelper(data,lo,pivot-1);
//debug(data);
quicksortHelper(data,pivot+1,hi);
//debug(data);
}
private static int[] partitionDutch(int[] data,int start, int end){
if (end == start){
int[] thing = new int[2];
thing[0] = start;
thing[1] = end;
return thing;
}
//finding the median
int median;// = (end+start)/2;//rand.nextInt(end - start)+start;
//System.out.println((end+start)/2);
//System.out.println("" + end + " " + start + " ");
int middle = data[(end+start)/2];
//System.out.println("" + middle);
int first = data[start];
int last = data[end];
if ((first < middle && first > last) || (first > middle && first < last)){
median = start;
}
else{
if ((last < middle && last > first) || (last > middle && last < first)){
median = end;
}
else{
median = (end+start)/2;
}
}
//swapping median and start
int pivotIndex = median;
int temp = data[pivotIndex];
data[pivotIndex] = data[start];
data[start] = temp;
pivotIndex = start;
int pivot = data[pivotIndex];
int currentIndex = start;
while (currentIndex <= end){
if (data[currentIndex] > pivot){
temp = data[currentIndex];
data[currentIndex] = data[end];
data[end] = temp;
end -= 1;
}
else{
if (data[currentIndex] < pivot){
temp = data[currentIndex];
data[currentIndex] = data[start];
data[start] = temp;
start++;
currentIndex++;
}
else{
currentIndex++;
}
}
}
//int length = (end + 1) - (start - 1);
int[] ans = new int[2];
ans[0] = start-1;
ans[1] = end+1;
//System.out.println(ans[1]);
//for (int i = 0; i < length; i++){
// ans[i] = data[start - 1];
// start++;
//}
return ans;
}
/*return the value that is the kth smallest value of the array.
*/
public static int quickselect(int []data, int k){
//k--;
int first = partition(data,0,data.length - 1);
while (k != first){
boolean go = true;
if (k < first){
go = false;
first = partition(data,0,first-1);
}
if (go && k > first){
first = partition(data,first+1,data.length-1);
}
}
return data[first];
}
/*Modify the array such that:
*1. Only the indices from start to end inclusive are considered in range
*2. A random index from start to end inclusive is chosen, the corresponding
* element is designated the pivot element.
*3. all elements in range that are smaller than the pivot element are placed before the pivot element.
*4. all elements in range that are larger than the pivot element are placed after the pivot element.
*@return the index of the final position of the pivot element.
*/
private static void debug(int[] data){
System.out.println(" ");
for (int r = 0; r < data.length; r++){
System.out.print(data[r]+", ");
}
}
public static int partition (int[] data, int start, int end){
//int newPivotIndex = 0;
//end++;
//Random rand;// = new Random();
int median;// = (end+start)/2;//rand.nextInt(end - start)+start;
int middle = data[(end+start)/2];
int first = data[start];
int last = data[end];
// System.out.println(first + " " + middle + " " + last);
if ((first < middle && first > last) || (first > middle && first < last)){
median = start;
// System.out.println("works");
}
else{
if ((last < middle && last > first) || (last > middle && last < first)){
median = end;
}
else{
median = (end+start)/2;
}
}
int pivotIndex = median;
int pivot = data[median];
// System.out.println(pivot + "pivot");
if (start == end){
return data[start];
}
// debug(data);
// System.out.println("start: " + pivot);
int temp = pivot;
data[median] = data[start];
data[start] = temp;
pivotIndex = start;
start++;
Random a = new Random();
while (start < end){
if (data[start] < pivot){
start += 1;
}
else{
if (data[start] == pivot){
if (a.nextInt(2) == 1){
temp = data[start];
data[start] = data[end];
data[end] = temp;
end -= 1;
}
else{
start += 1;
}
}
else{
temp = data[start];
data[start] = data[end];
data[end] = temp;
end -= 1;
}
}
}
if (pivot > data[start]){
temp = pivot;
data[pivotIndex] = data[start];
data[start] = temp;
return start;
}else{
temp = pivot;
data[pivotIndex] = data[start-1];
data[start-1] = temp;
return start - 1;
}
}
public static void main(String args[]){
// int[] data6 = {0,1,2,3,50,60,50,50,40,20,30,11,12,13};
// System.out.println(partition(data6,4,10) + "ANS");
//quicksort(data6);
// System.out.println("");
// for (int i = 0; i < data6.length;i++){
// System.out.print(data6[i] + ", ");
// }
/**
int[] data7 = {100,300,6,300,100,200,0};
System.out.println("ans = " + quickselect(data7,5));
int[] data3 = new int[20];
int[] data4 = new int[20];
for (int i = 0; i < data3.length; i++){
data3[i] = (int)(Math.random()*1000000000);
data4[i] = data3[i];
}
quicksort(data3);
System.out.println("ans: ");
for (int i = 0; i < data3.length;i++){
System.out.print(data3[i] + ", ");
}
System.out.println("");
Arrays.sort(data4);
for (int i = 0; i < data4.length;i++){
System.out.print(data4[i] + ", ");
}
/**
start++;
end--;
for (int i = start; i != end;i++){
boolean moved = false;
if (data[i] == data[start - 1]){
rand = new Random();
int randInt = rand.nextInt(2);
if (randInt == 0){
temp = data[i];
data[i] = data[end];
data[end] = temp;
end--;
i--;
moved = true;
}
}
if (!(moved) && data[i] > data[start - 1]){
temp = data[i];
data[i] = data[end];
data[end] = temp;
end--;
i--;
}
}*/
System.out.println("Size\t\tMax Value\tquick/builtin ratio ");
int[]MAX_LIST = {1000000000,500,10};
for(int MAX : MAX_LIST){
for(int size = 31250; size < 2000001; size*=2){
long qtime=0;
long btime=0;
//average of 5 sorts.
for(int trial = 0 ; trial <=5; trial++){
int []data1 = new int[size];
int []data2 = new int[size];
for(int i = 0; i < data1.length; i++){
data1[i] = (int)(Math.random()*MAX);
data2[i] = data1[i];
}
long t1,t2;
t1 = System.currentTimeMillis();
Quick.quicksort(data2);
t2 = System.currentTimeMillis();
qtime += t2 - t1;
t1 = System.currentTimeMillis();
Arrays.sort(data1);
t2 = System.currentTimeMillis();
btime+= t2 - t1;
//System.out.println("works");
if(!Arrays.equals(data1,data2)){
System.out.println("FAIL TO SORT!");
//debug(data2);
System.exit(0);
}
}
System.out.println(size +"\t\t"+MAX+"\t"+1.0*qtime/btime);
}
System.out.println();
}
/**
System.out.println("Size\t\tMax Value\tquick/builtin ratio ");
int[]MAX_LIST = {1000000000};//,500,10};
for(int MAX : MAX_LIST){
for(int size = 100000; size == 100000; size*=2){
long qtime=0;
long btime=0;
//average of 5 sorts.
for(int trial = 0 ; trial <=5; trial++){
int []data1 = new int[size];
int []data2 = new int[size];
for(int i = 0; i < data1.length; i++){
data1[i] = (int)(Math.random()*MAX);
data2[i] = data1[i];
}
long t1,t2;
t1 = System.currentTimeMillis();
Quick.quicksort(data2);
t2 = System.currentTimeMillis();
qtime += t2 - t1;
t1 = System.currentTimeMillis();
Arrays.sort(data1);
t2 = System.currentTimeMillis();
btime+= t2 - t1;
//debug(data1);
//debug(data2);
if(!Arrays.equals(data1,data2)){
System.out.println("FAIL TO SORT!");
// debug(data2);
System.out.println("failed");
System.exit(0);
}
}
// System.out.println("here");
System.out.println(size +"\t\t"+MAX+"\t"+1.0*qtime/btime);
}
//System.out.println();
}
**/
}
}
| true |
2965dc2a4e3fb03345f07ab925a17aa60da95bbe
|
Java
|
saransh2405/Koo-and-Toueg-s-algorithm
|
/checkpoint.java
|
UTF-8
| 30,336 | 2.09375 | 2 |
[] |
no_license
|
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.*;
import java.net.*;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class checkpoint {
LinkedList<Integer> neighbours;
int check,check1;
int version,iterator;
final int maxdelay = 5000;
LinkedList<String> hostname;
int[] label_value;
static int totalnodes;
LinkedList<String> port;
LinkedList<Integer> nextHost;
LinkedList<String> hostWork;
LinkedList<String> lls,llr,vclock,itr;
int[] last_label_rcvd, first_label_sent , vectorClock, vclockbackup,last_label_Sent;
LinkedList<Integer> coverednodes;
int[] last_checkpoint_rcvd,last_checkpoint_sent;
static int id;
static boolean sendappmessages,close;
int taskid;
String taskval;
boolean task;
public checkpoint(int id)
{
this.id = id;
version = 0;
iterator = 0;
task = false;
taskval= "e";
taskid = -1;
check = 0;
check1 = 0;
hostname = new LinkedList<>();
sendappmessages = true;
vclock = new LinkedList<>();
itr = new LinkedList<>();
llr = new LinkedList<>();
lls = new LinkedList<>();
coverednodes = new LinkedList<>();
port = new LinkedList<>();
neighbours = new LinkedList<>();
nextHost = new LinkedList<>();
hostWork = new LinkedList<>();
}
void startThread() {
final int numProcesses = neighbours.size();
final int nos = totalnodes;
vectorClock = new int[nos];
last_label_Sent = new int[numProcesses];
last_label_rcvd = new int[numProcesses];
label_value = new int[numProcesses];
first_label_sent = new int[numProcesses];
vclockbackup = new int[nos];
last_checkpoint_rcvd = new int[numProcesses];
last_checkpoint_sent = new int[numProcesses];
new serverThread(this).start();
new appThread(this).start();
new appControlThread(this).start();
}
class serverThread extends Thread {
checkpoint server;
public serverThread(checkpoint main) {
this.server = main;
for(int i=0;i<last_label_rcvd.length;i++)
{
last_label_rcvd[i] = -1;
first_label_sent[i] = -1;
last_checkpoint_rcvd[i] = -1;
close = false;
label_value[i] = 0;
last_checkpoint_sent[i] = -1;
}
for(int j=0;j<vectorClock.length;j++)
{
vectorClock[j]=0;
vclockbackup[j]=0;
}
}
public String sender(String msg, int id) {
String sentence = msg;
String modifiedSentence = "";
//System.out.println(msg);
try {
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName(server.hostname.get(id - 1));
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
sentence = msg;
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, Integer.parseInt(server.port.get(id - 1)));
clientSocket.send(sendPacket);
clientSocket.close();
/*DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();*/
} catch (IOException e) {
}
return modifiedSentence;
}
public void updateVC(String vc)
{
String vcs[] = vc.split(",");
for(int i=0;i<totalnodes;i++)
{
if(i==id)
{
if(Integer.parseInt(vcs[i])>vectorClock[i])
{
vectorClock[i] = Integer.parseInt(vcs[i])+1;
}
else
{
vectorClock[i] +=1;
}
}
else
{
vectorClock[i] = Integer.parseInt(vcs[i]);
}
}
}
public String covered()
{
String cov = "";
/*for(int i:neighbours)
{
cov += i+",";
}*/
for(int i:coverednodes)
{
cov += i+",";
}
//cov +=id+1+",";
return cov;
}
public boolean incovs(int x)
{
for(int i:coverednodes)
{
if(i==x)
return true;
}
return false;
}
public void addDone(String nodes)
{
//System.out.println("nodes"+nodes);
String allnodes[] = nodes.split(",");
for(int i=0;i<allnodes.length;i++)
{
if(!incovs(Integer.parseInt(allnodes[i])))
coverednodes.add(Integer.parseInt(allnodes[i]));
}
if(!incovs(id+1))
coverednodes.add(id+1);
}
public boolean inDone(int s)
{
for(int i:coverednodes)
{
//System.out.println("i="+i+" s= "+s);
if(i==s)
return true;
}
return false;
}
public void takecheckpoint()
{
String l="";
String s = "";
String k = "";
for(int j=0;j<vectorClock.length;j++)
{
k+=vectorClock[j]+",";
vclockbackup[j] = vectorClock[j];
}
for(int i=0;i<last_label_rcvd.length;i++)
{
last_checkpoint_rcvd[i] = last_label_rcvd[i];
l+=last_label_rcvd[i]+",";
s+=first_label_sent[i]+",";
last_checkpoint_sent[i] = first_label_sent[i];
last_label_rcvd[i] = -1;
first_label_sent[i] = -1;
}
lls.add(s);
llr.add(l);
vclock.add(k);
//System.out.println(vclock.get(vclock.size()-1));
check =1;
System.out.println("Taking checkpoint -- - - - - - -- -- - - - - - - -- ");
}
public void recover()
{
/*if(lls.size()>0)
{
String w[] = lls.get(lls.size()-1).split(",");
String p[] = llr.get(llr.size()-1).split(",");
for(int i=0;i<last_label_rcvd.length;i++)
{
last_label_rcvd[i] = Integer.parseInt(p[i]);
first_label_sent[i] = Integer.parseInt(w[i]);
last_label_rcvd[i]=-1;
}
lls.remove(lls.size()-1);
llr.remove(llr.size()-1);
}
else{
for(int i=0;i<last_label_rcvd.length;i++)
{
last_label_rcvd[i] = -1;
first_label_sent[i] = -1;;
last_label_rcvd[i]=-1;
}
}*/
for(int i=0;i<last_label_rcvd.length;i++)
last_label_rcvd[i] = -1;
check =1;
System.out.println("Before recovering");
for(int j=0;j<vectorClock.length;j++)
{
System.out.println(j+1+" : "+vectorClock[j]);
vectorClock[j] = vclockbackup[j];
}
System.out.println("Taking recovery -- - - - - - -- -- - - - - - - -- ");
System.out.println("After recovering");
for(int j=0;j<vectorClock.length;j++)
{
System.out.println(j+1+" : "+vectorClock[j]);
}
}
public String floodNetwork(String message)
{
//System.out.println("neigbours"+" "+neighbours);
int x=0;
for(int s:neighbours)
{
if(!inDone(s))
{
//System.out.println("sending to "+s);
sender(message+";"+last_label_rcvd[x]+";"+iterator+";"+version,s);
}
x++;
}
return "Test";
}
public String floodNetwork1(String message)
{
//System.out.println("neigbours"+" "+neighbours);
int x=0;
for(int s:neighbours)
{
if(!inDone(s))
{
//System.out.println("sending to "+s);
sender(message+";"+last_label_Sent[x]+";"+iterator+";"+version,s);
System.out.println(message+";"+last_label_Sent[x]+";"+iterator+";"+version);
}
x++;
}
return "Test";
}
public void setLLR(int index,int val)
{
last_label_rcvd[index] = val;
}
public void printllr()
{
for(int i=0;i<last_label_rcvd.length;i++)
{
//System.out.println("label check:"+server.neighbours.get(i)+":"+last_label_rcvd[i]+":"+first_label_sent[i]);
}
}
public int getfLS(int x)
{
return first_label_sent[x];
}
public int getRealIndex(int x)
{
int t = 0;
for(int i:neighbours)
{
//System.out.println(i+"i+x "+x);
if(i==x)
{
return t;
}
t +=1;
}
return -1;
}
public String messageProcessor(DatagramPacket receivePacket, String message, DatagramSocket serverSocket) {
//addDone(message.split(";")[1]);
//floodNetwork("test");
String[] messageparts = message.split(";");
String from = messageparts[0];
String type = messageparts[1];
String vc = messageparts[2];
String reply = "";
if(Integer.parseInt(type)==Message.APP.id)
{
//System.out.println(getRealIndex(Integer.parseInt(from)+1)+" "+from);
setLLR(getRealIndex(Integer.parseInt(from)+1),Integer.parseInt(messageparts[3]));
printllr();
updateVC(vc);
reply = "OK";
}
else if(Integer.parseInt(type)==Message.CHECKPOINT.id)
{
System.out.print("vector clock for iteration "+iterator+" :");
for(int i =0;i<vectorClock.length;i++)
{
System.out.print(vectorClock[i]+" ");
}
System.out.println();
sendappmessages = false;
try{
appControlThread.sleep(100);
appThread.sleep(100);
}
catch(Exception e){}
if(from.equals(""+id+""))
{
while(coverednodes.size()>0)
{
coverednodes.remove(coverednodes.size()-1);
}
addDone(vc);
takecheckpoint();
floodNetwork(id+";"+1+";"+covered());
}
else
{
while(coverednodes.size()>0)
{
coverednodes.remove(coverednodes.size()-1);
}
addDone(vc);
System.out.println(Integer.parseInt(from)+1 + " "+getRealIndex(Integer.parseInt(from)+1)+" "+neighbours);
if(getRealIndex(Integer.parseInt(from)+1) != -1)
{
if(Integer.parseInt(messageparts[3])>=getfLS(getRealIndex(Integer.parseInt(from)+1))&&getfLS(getRealIndex(Integer.parseInt(from)+1))>-1&&check==0)
takecheckpoint();
coverednodes.add(-1);
floodNetwork(id+";"+1+";"+covered());
}
//version = Integer.parseInt(messageparts[messageparts.length-1])+1;
try{
appControlThread.sleep(100);
appThread.sleep(100);
}
catch(Exception e){}}
//iterator ++;
reply="checkpointinggg";
}
else if(Integer.parseInt(type)==Message.STEP.id)
{
}
else if(Integer.parseInt(type)==Message.RECOVER.id)
{
try{
appControlThread.sleep(100);
appThread.sleep(100);
}
catch(Exception e){}
if(from.equals(""+id+""))
{
while(coverednodes.size()>0)
{
coverednodes.remove(coverednodes.size()-1);
}
addDone(vc);
recover();
floodNetwork1(id+";"+3+";"+covered());
}
if(!from.equals(""+id+""))
{
while(coverednodes.size()>0)
{
coverednodes.remove(coverednodes.size()-1);
}
addDone(vc);
System.out.println("-----------------here--------------");
if(Integer.parseInt(messageparts[3])<last_label_rcvd[getRealIndex( Integer.parseInt(from)+1)]&&check==0)
recover();
floodNetwork1(id+";"+3+";"+covered());
}
//iterator ++;
reply="recover";
}
else if(Integer.parseInt(type)==Message.VER.id)
{
/*if(Integer.parseInt(from)==id+1)
{}
else
iterator = id;
try{
appControlThread.sleep(100);
appThread.sleep(100);
}
catch(Exception e){}
//for(int i1=0;i1<server.hostname.size();i1++)
//if(i1!=id)
//sender(id+";"+4+";-1;"+iterator,i1+1);*/
}
else
{
System.out.println("Got this message: "+message);
reply = "ok";
}
return reply;
}
@Override
public void run() {
//if(id==0)
//messageProcessor("test1;-1");
String host = server.hostname.get(id);
String clientSentence;
int port = Integer.parseInt(server.port.get(id));
String replymessage;
try {
String port2 = server.port.get(id);
DatagramSocket serverSocket = new DatagramSocket(Integer.parseInt(port2));
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while (close == false) {
System.out.println("Listening....");
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = "";
sentence = "";
sentence = new String( receivePacket.getData(),0, receivePacket.getLength());
//System.out.println("RECEIVED: " + sentence);
messageProcessor(receivePacket, sentence, serverSocket);
InetAddress IPAddress = receivePacket.getAddress();
int port1 = receivePacket.getPort();
sendData = "ok".getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port1);
serverSocket.send(sendPacket);
//messageProcessor(sentence);
//System.out.println("11sent11");
}
} catch (IOException e) {
}
}
}
class State {
int n;
public State() {}
public State(int n) {
this.n = n;
}
}
enum Message {
APP(0), CHECKPOINT(1), STEP(2), RECOVER(3), VER(4);
final int id;
Message(int id) {
this.id = id;
}
int getMessageId() {
return id;
}
}
class appThread extends Thread
{
checkpoint server;
public appThread(checkpoint main)
{
this.server = main;
}
public void setfLS(int index,int labelvalue)
{
if(first_label_sent[index]==-1)
first_label_sent[index] = labelvalue;
last_label_Sent[index] = labelvalue;
}
public int getlabelvalue(int index)
{
label_value[index] +=1;
return label_value[index];
}
public String vectorclock()
{
String vcs = "";
vectorClock[id]+=1;
for(int i=0;i<vectorClock.length;i++)
{
if(i!=vectorClock.length-1)
vcs += vectorClock[i]+",";
else
vcs += vectorClock[i];
}
return vcs;
}
public void sendmessage()
{
int id1 = (int) (Math.random() * (neighbours.size()));
//System.out.println(id1);
//System.out.println(id);
int lbval = getlabelvalue(id1);
String msg = id+";0;"+vectorclock()+";"+lbval;
setfLS(id1,lbval);
id1 = neighbours.get(id1);
//System.out.println(id1+" neighbour "+neighbours);
//System.out.println("sending...." + msg);
try {
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName(server.hostname.get(id1 - 1));
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = msg;
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, Integer.parseInt(server.port.get(id1 - 1)));
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
//System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
} catch (IOException e) {
System.out.println(e);
}
}
@Override
public void run() {
//System.out.println(nextHost.size()+" hostwork number- - - ----");
while(iterator<nextHost.size())
{
if(true)
{
try{
Thread.sleep(1000);
}
catch(Exception e)
{}
// System.out.println("Check here:"+sendappmessages);
sendmessage();
}
else
{
//System.out.println("hereeeeeeeeeee"+sendappmessages);
}
}
}
}
class appControlThread extends Thread
{
checkpoint server;
int id;
public appControlThread(checkpoint main)
{
this.server = main;
this.id = main.id;
}
public void writetofile()
{
}
@Override
public void run() {
int i = 0;
while(iterator<nextHost.size())
{
try{
appControlThread.sleep(maxdelay);
}
catch(Exception e)
{
System.out.println(e);
}
if(sendappmessages == false)
{
sendappmessages = true;
check = 0;
check1 = 0;
//System.out.println("Check:"+sendappmessages);
iterator +=1;
System.out.println("Iterator:"+iterator);
try{
appThread.sleep(maxdelay);
//System.out.println("heyyyyyyy------"+sendappmessages+"------");
}
catch(Exception e)
{
System.out.println(e);
}
}
else
{
try{
appControlThread.sleep(1000);
//System.out.println("heyyyyyyy------"+sendappmessages+"------");
}
catch(Exception e)
{
System.out.println(e);
}
sendappmessages = false;
//System.out.println("Check:"+sendappmessages);
//System.out.println(hostWork.size()+" hostwork "+iterator);
if(hostWork.size()>iterator)
{
int x = 0;
x = id+1;
//System.out.println(nextHost.get(iterator)+" "+x);
if(nextHost.get(iterator)==id+1 && hostWork.get(iterator).equals("c"))
{
String msg = id+";1;"+"-1;100000;"+version+";"+iterator;
try {
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
//System.out.println("Taking 1");
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName(server.hostname.get(id));
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = msg;
sendData = sentence.getBytes();
try{
appControlThread.sleep(500);
}
catch(Exception e)
{
System.out.println(e);
}
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, Integer.parseInt(server.port.get(id)));
clientSocket.send(sendPacket);
//System.out.println("Taking 2");
try{
appControlThread.sleep(500);
}
catch(Exception e)
{
System.out.println(e);
}
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
clientSocket.close();
//iterator++;
} catch (IOException e) {
System.out.println(e);
}
}
if(nextHost.get(iterator)==id+1 && hostWork.get(iterator).equals("r"))
{
String msg = id+";3;"+"-1;100000;"+version+";"+iterator;
try {
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
//System.out.println("Taking 1");
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName(server.hostname.get(id));
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = msg;
sendData = sentence.getBytes();
try{
appControlThread.sleep(500);
}
catch(Exception e)
{
System.out.println(e);
}
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, Integer.parseInt(server.port.get(id)));
clientSocket.send(sendPacket);
System.out.println("Taking 2");
try{
appControlThread.sleep(500);
}
catch(Exception e)
{
System.out.println(e);
}
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
clientSocket.close();
System.out.println("Taking 3");
// iterator++;
} catch (IOException e) {
System.out.println(e);
}
}
else
{
System.out.println("no no no");
}
}
}
i++;
}
for(int j=0;j<vclock.size();j++)
{
System.out.println(vclock.get(j));
}
}
}
public static void main(String args[]) {
File f = new File("config.txt");
id = Integer.parseInt(args[0]);
checkpoint main = new checkpoint(id);
int totalneigbhours = 0 ;
try {
Scanner reader = new Scanner(f);
while (reader.hasNextLine()) {
String line = reader.nextLine();
System.out.println(line + "!");
if (!line.startsWith("#")) {
int numberOfNodes = Integer.parseInt(line);
totalnodes = numberOfNodes;
break;
}
}
int cntr = 0;
while (reader.hasNextLine()) {
String line = reader.nextLine();
System.out.println(line + "?");
if(line.startsWith("$$"))
{
break;
}
if (!line.startsWith(" ") && !line.startsWith("#")
&& !line.equals("") && !line.startsWith("$$") && !line.startsWith("--")) {
String[] split = line.split("\t+| +");
String host = split[0];
String port = split[1];
if (id == cntr) {
for (int i = 2; i < split.length; i++) {
main.neighbours.add(Integer.parseInt(split[i]));
}
}
main.hostname.add(host);
main.port.add(port);
cntr++;
}
}
while(reader.hasNextLine())
{
String line = reader.nextLine();
System.out.println(line + "$");
if (!line.startsWith(" ") && !line.startsWith("#")
&& !line.equals("") && !line.startsWith("$$") && !line.startsWith("--")) {
String[] split = line.split("\t+| +");
String host = split[0];
String type = split[1];
main.nextHost.add(Integer.parseInt(host));
main.hostWork.add(type);
}
if(line.startsWith("--"))
{
break;
}
}
if(main.nextHost.get(0)==id)
{
main.task = true;
main.taskid = id;
main.taskval = main.hostWork.get(0);
}
main.startThread();
} catch (FileNotFoundException ex) {
//Logger.getLogger(Print.class.getName()).log(Level.SEVERE,null,ex);
}
}
}
| true |
a38c0e9a2c0a7ff99374031d40ba3783986d0d7f
|
Java
|
And1sS/Online-chat
|
/src/main/java/com/and1ss/onlinechat/api/ws/mappers/WsGroupMessageMapper.java
|
UTF-8
| 388 | 1.96875 | 2 |
[] |
no_license
|
package com.and1ss.onlinechat.api.ws.mappers;
import com.and1ss.onlinechat.api.ws.dto.WsGroupMessagePatchDTO;
import com.and1ss.onlinechat.services.dto.GroupMessagePatchDTO;
public class WsGroupMessageMapper {
public static GroupMessagePatchDTO toGroupMessagePatchDTO(WsGroupMessagePatchDTO patchDTO) {
return new GroupMessagePatchDTO(patchDTO.getContents(), null);
}
}
| true |
099bf561f8a4161a91b80e77f2dd3c05714f3410
|
Java
|
marcphilipp/junit-quickcheck
|
/src/main/java/com/pholser/junit/parameters/internal/extractors/ShortExtractor.java
|
UTF-8
| 382 | 2.4375 | 2 |
[] |
no_license
|
package com.pholser.junit.parameters.internal.extractors;
import com.pholser.junit.parameters.extractors.RandomValueExtractor;
import com.pholser.junit.parameters.random.SourceOfRandomness;
public class ShortExtractor implements RandomValueExtractor<Short> {
@Override
public Short randomValue(SourceOfRandomness random) {
return (short) random.nextInt();
}
}
| true |
2ac214dbd6b422641ada6e38a7cdd2fed9525827
|
Java
|
tonngw/leetcode
|
/java/1189-maximum-number-of-balloons.java
|
UTF-8
| 974 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
class Solution {
public int maxNumberOfBalloons(String text) {
HashMap<Character, Integer> balloon = new HashMap<>();
HashMap<Character, Integer> countText = new HashMap<>();
char[] balloonArray = "balloon".toCharArray();
for (char c : balloonArray) {
if (balloon.containsKey(c)) {
balloon.put(c,balloon.get(c)+1);
} else {
balloon.put(c,1);
}
}
char[] countTextArray = text.toCharArray();
for (char c : countTextArray) {
if (countText.containsKey(c)) {
countText.put(c,countText.get(c)+1);
} else {
countText.put(c,1);
}
}
int res = text.length();
for (Character c : balloon.keySet()) {
res = Math.min(res,countText.getOrDefault(c,0) / balloon.get(c));
}
return res;
}
}
| true |
bd7d9089bc3205d457d9417a21de21a6231a3be5
|
Java
|
weichk/MyExperimentProject
|
/src/myProject/Test14.java
|
UTF-8
| 1,409 | 2.09375 | 2 |
[] |
no_license
|
package myProject;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.eabax.test.SendMessageJDBC;
import com.sun.xml.internal.ws.resources.SenderMessages;
public class Test14 {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Connection conn = null;
ResultSet record = null;
conn = SendMessageJDBC.getConnection();
PreparedStatement statement = null;
String message = "云大大注册验证码:"+189564+"。请您尽快完成注册。如非本人操作,请忽略本短信。";
String getSequenceSql = "select DYMSG_ID.NEXTVAL FROM dual";
statement = conn.prepareStatement(getSequenceSql);
record = statement.executeQuery();
record.next();
long sequence = record.getLong("NEXTVAL");
statement.close();
record.close();
StringBuilder sql = new StringBuilder();
sql.append("insert into DYHIKEMESSAGES (dymsgid,to_mobile,pay_mobile_tel,msg_content,cost,create_date,send_time,send_out_flag,prefix,presend_time,epid)");
sql.append(" values (?,?,' ',?,0,sysdate,sysdate,0,'0000',sysdate,'cqjsp')");
statement = conn.prepareStatement(sql.toString());
statement.setLong(1, sequence);
statement.setString(2, "18696725229");
statement.setString(3, message);
statement.execute();
conn.close();
statement.close();
}
}
| true |
1f9551b26b2f510004de862a7327c3c64ffd63a1
|
Java
|
sunyujia21/Project_Rock
|
/fmcg/src/com/fmcg/pojo/Kuaixiao.java
|
UTF-8
| 1,531 | 2.046875 | 2 |
[] |
no_license
|
package com.fmcg.pojo;
public class Kuaixiao {
private String id;
private String kname;
private String kprice;
private String ktype;
private String kpic;
private String kpoint;
private String kdetails;
private String kdate;
private Integer kcheck;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getKname() {
return kname;
}
public void setKname(String kname) {
this.kname = kname;
}
public String getKprice() {
return kprice;
}
public void setKprice(String kprice) {
this.kprice = kprice;
}
public String getKtype() {
return ktype;
}
public void setKtype(String ktype) {
this.ktype = ktype;
}
public String getKpic() {
return kpic;
}
public void setKpic(String kpic) {
this.kpic = kpic;
}
public String getKpoint() {
return kpoint;
}
public void setKpoint(String kpoint) {
this.kpoint = kpoint;
}
public String getKdetails() {
return kdetails;
}
public void setKdetails(String kdetails) {
this.kdetails = kdetails;
}
public String getKdate() {
return kdate;
}
public void setKdate(String kdate) {
this.kdate = kdate;
}
public Integer getKcheck() {
return kcheck;
}
public void setKcheck(Integer kcheck) {
this.kcheck = kcheck;
}
@Override
public String toString() {
return "Kuaixiao [id=" + id + ", kname=" + kname + ", kprice=" + kprice + ", ktype=" + ktype + ", kpic=" + kpic
+ ", kpoint=" + kpoint + ", kdetails=" + kdetails + ", kdate=" + kdate + ", kcheck=" + kcheck + "]";
}
}
| true |
144d9b3c2a6de629def726437cba4e4be8570e69
|
Java
|
Yagayev/AkariSolver
|
/src/AkariProject.java
|
UTF-8
| 673 | 3.21875 | 3 |
[] |
no_license
|
import java.util.Scanner;
public class AkariProject {
/*
*
*
This project was written by Meir Yagayev and Bar Siman Tov
as an assistant at the course "Topic in Logic Puzzel"
by prof. Daniel Berend
Ben Gurion University of the Negev
2018
*
*/
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("What do you want to do? : \n1.Create boards \n2.Solve a board");
int action = sc.nextInt();
if(action == 1) {
GenerateManyBoards.gen();
System.out.println("DONE!");
}
else if(action == 2) {
AkariSolver.solve();
}
else {
System.out.println("iligal action");
}
}
}
| true |
26ff22ea52254a20871806944945862efda737b5
|
Java
|
roberttop/BILD-IT-Zadaci
|
/zadaci_12_02_2018/KolikoSeBrojPutaPonovio.java
|
UTF-8
| 415 | 3.34375 | 3 |
[] |
no_license
|
package zadaci_12_02_2018;
public class KolikoSeBrojPutaPonovio {
public static void ponavljanjeBroja() {
int[] niz = new int[10];
for (int i = 0; i < 100; i++) {
int broj = (int) (Math.random() * 10);
niz[broj]++;
}
for (int i = 0; i < niz.length; i++) {
System.out.println(i + " se ponavlja " + niz[i] + " puta.");
}
}
public static void main(String[] args) {
ponavljanjeBroja();
}
}
| true |
7c02e57490588883180ebb074a1db2825f3d83e2
|
Java
|
Yolean/kafka-keyvalue
|
/src/test/java/se/yolean/kafka/keyvalue/ConsumerAtLeastOnceTest.java
|
UTF-8
| 1,416 | 2.234375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package se.yolean.kafka.keyvalue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
public class ConsumerAtLeastOnceTest {
@Test
void testToStats() {
var registry = new SimpleMeterRegistry();
var instance = new ConsumerAtLeastOnce(registry);
assertFalse(registry.getMetersAsString().contains("17"));
instance.toStats(new UpdateRecord("mytopic", 0, 17, "key1", 100));
assertTrue(registry.getMetersAsString().contains("17"));
instance.toStats(new UpdateRecord("mytopic", 0, 27, "key1", 100));
assertFalse(registry.getMetersAsString().contains("17"));
assertFalse(registry.getMetersAsString().contains("NaN"));
assertTrue(registry.getMetersAsString().contains("27"));
instance.toStats(new UpdateRecord("mytopic", 0, 30, "key1", 100));
assertTrue(registry.getMetersAsString().contains("30"));
instance.toStats(new UpdateRecord("mytopic", 0, 31, "key1", 100));
assertTrue(registry.getMetersAsString().contains("31"));
instance.toStats(new UpdateRecord("mytopic", 0, 32, "key1", 100));
assertTrue(registry.getMetersAsString().contains("32"));
instance.toStats(new UpdateRecord("mytopic", 0, 33, "key1", 100));
assertTrue(registry.getMetersAsString().contains("33"));
}
}
| true |
5ee599054563c0ef576e055d7cb2e12bfcec0cf1
|
Java
|
yuayixio/MQTT2Kafka
|
/src/main/java/org/example/relayservice/api/RelayResources.java
|
UTF-8
| 3,220 | 2.25 | 2 |
[] |
no_license
|
package org.example.relayservice.api;/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import org.example.relayservice.relay.RelayManager;
import org.example.relayservice.relay.RunningRelayInstances;
import org.example.relayservice.relay.Status;
import org.example.relayservice.model.RelayRequest;
import org.example.relayservice.model.StopRequest;
import org.rapidoid.http.MediaType;
import org.rapidoid.http.Resp;
import org.rapidoid.setup.On;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RelayResources {
private final static Logger LOG = LoggerFactory.getLogger(RelayResources.class);
private static final String API_VERSION = "/api/v1";
private static final String RELAY_ROUTE = "/relay";
public RelayResources() {
}
public static void start() {
On.post(API_VERSION + RELAY_ROUTE + "/start").json((RelayRequest req, Resp res) -> {
Status status;
if (!RunningRelayInstances.INSTANCE.isRunning(req.sourceTopic)) {
RelayManager relay = new RelayManager(req);
relay.startRelay();
RunningRelayInstances.INSTANCE.addRelay(req.sourceTopic, relay);
status = Status.ACCEPTED;
}
else {
status = Status.REJECTED;
}
String json = "{\"status\": \"" + status + "\"}";
return res.code(200).contentType(MediaType.JSON).body(json.getBytes());
});
On.post(API_VERSION + RELAY_ROUTE + "/stop").json((StopRequest stopRequest, Resp res) -> {
Status status;
if (RunningRelayInstances.INSTANCE.isRunning(stopRequest.id)) {
RelayManager relay = RunningRelayInstances.INSTANCE.removeRelay(stopRequest.id);
relay.stopRelay();
status = Status.ACCEPTED;
}
else {
status = Status.REJECTED;
}
String json = "{\"status\": \"" + status + "\"}";
return res.code(200).contentType(MediaType.JSON).body(json.getBytes());
});
On.get(API_VERSION + RELAY_ROUTE + "/stats").json((String id, Resp res) -> {
RelayManager relay = RunningRelayInstances.INSTANCE.get(id);
String json = relay !=null ? relay.stats() : "{\"status\": \"" + Status.REJECTED + "\"}";
return res.code(200).contentType(MediaType.JSON).body(json.getBytes());
});
}
}
| true |
1267e4b4fd58095c691320d1900b2403b1cfe4a0
|
Java
|
KarajkoGabor/Szakdolgozat
|
/app/src/main/java/hu/blogspot/limarapeksege/activity/MainActivity.java
|
UTF-8
| 2,550 | 1.898438 | 2 |
[] |
no_license
|
package hu.blogspot.limarapeksege.activity;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import java.util.ArrayList;
import java.util.Collections;
import hu.blogspot.limarapeksege.R;
import hu.blogspot.limarapeksege.adapters.MainPageGridAdapter;
import hu.blogspot.limarapeksege.model.Recipe;
import hu.blogspot.limarapeksege.util.AnalyticsTracker;
import hu.blogspot.limarapeksege.util.GlobalStaticVariables;
import hu.blogspot.limarapeksege.util.SqliteHelper;
@SuppressLint("NewApi")
public class MainActivity extends BaseActivity{
private AnalyticsTracker trackerApp;
private MainPageGridAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
super.onCreateDrawer(getLocalClassName());
trackerApp = (AnalyticsTracker) getApplication();
prepareMainView();
}
private void prepareMainView() {
SqliteHelper db = SqliteHelper.getInstance(this);
ArrayList<Recipe> allRecipes = (ArrayList<Recipe>) db.getAllRecipes();
Collections.shuffle(allRecipes);
super.setGridAdapter(allRecipes);
db.closeDatabase();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
@Override
public void onResume() {
super.onResume();
trackerApp.sendScreen(getString(R.string.analytics_screen_main_page_screen));
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.w(GlobalStaticVariables.LOG_TAG, "onActivityResult session");
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
}
| true |
15c687190f577fee98d90e2821699a9dda5d2ee8
|
Java
|
Fradantim/APD
|
/APD_SERVER/src/dao/RemitoDao.java
|
UTF-8
| 1,782 | 2.5625 | 3 |
[] |
no_license
|
package dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import entities.FacturaEntity;
import entities.RemitoEntity;
import exception.ObjetoInexistenteException;
import hbt.HibernateUtil;
import model.Factura;
import model.Remito;
public class RemitoDao {
private static RemitoDao instancia;
private RemitoDao() {}
public static RemitoDao getInstance() {
if(instancia == null)
instancia = new RemitoDao();
return instancia;
}
public Remito getById(int idRemito) throws ObjetoInexistenteException {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
RemitoEntity entity = (RemitoEntity) session.createQuery("from RemitoEntity where idRemito = ?")
.setParameter(0, idRemito)
.uniqueResult();
if(entity != null)
return entity.toNegocio();
else
throw new ObjetoInexistenteException("No se encontro el remito con id "+ idRemito);
}
public RemitoEntity getByIdRem(int idRemito) throws ObjetoInexistenteException {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
RemitoEntity entity = (RemitoEntity) session.createQuery("from RemitoEntity where idRemito = ?")
.setParameter(0, idRemito)
.uniqueResult();
if(entity != null)
return entity;
else
throw new ObjetoInexistenteException("No se encontro el remito con id "+ idRemito);
}
public Integer grabar(Remito remito) throws ObjetoInexistenteException{
RemitoEntity re = new RemitoEntity(remito);
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.saveOrUpdate(re);
session.getTransaction().commit();
session.close();
return re.toNegocio().getIdRemito();
}
}
| true |
ed6eba5b726be1711b0012b95361d40e60743ab6
|
Java
|
sevab/picture-house
|
/src/picturehouse/views/WriteReviewPanel.java
|
UTF-8
| 6,849 | 2.40625 | 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 picturehouse.views;
import javax.swing.JOptionPane;
import org.javalite.activejdbc.Base;
import picturehouse.PictureHouse;
import picturehouse.controllers.MovieReviewController;
import picturehouse.models.Movie;
import picturehouse.views.MainFrame;
/**
*
* @author sevabaskin
*/
public class WriteReviewPanel extends javax.swing.JPanel {
private PictureHouse app;
private MainFrame parentFrame;
private Movie targetMovie;
/**
* Creates new form WriteReviewPanel
*/
public WriteReviewPanel() {
initComponents();
}
public WriteReviewPanel(PictureHouse app, MainFrame parentFrame) {
initComponents();
this.app = app;
this.parentFrame = parentFrame;
}
public void updateView() {
this.targetMovie = this.parentFrame.getCurrentlySelectedMovie();
this.cardTitle.setText("Leave your review for " + this.targetMovie.getString("title"));
}
/**
* 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() {
cardTitle = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
movieReviewTextArea = new javax.swing.JTextArea();
submitReviewButton = new javax.swing.JButton();
goBackButton = new javax.swing.JButton();
cardTitle.setFont(new java.awt.Font("Lucida Grande", 0, 20)); // NOI18N
jScrollPane1.setPreferredSize(new java.awt.Dimension(400, 250));
jScrollPane1.setSize(new java.awt.Dimension(400, 250));
movieReviewTextArea.setColumns(20);
movieReviewTextArea.setLineWrap(true);
movieReviewTextArea.setRows(5);
movieReviewTextArea.setPreferredSize(new java.awt.Dimension(380, 230));
movieReviewTextArea.setSize(new java.awt.Dimension(380, 230));
jScrollPane1.setViewportView(movieReviewTextArea);
submitReviewButton.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
submitReviewButton.setText("Submit your review");
submitReviewButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
submitReviewButtonActionPerformed(evt);
}
});
goBackButton.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
goBackButton.setText("< Go Back");
goBackButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
goBackButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(cardTitle)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(goBackButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(submitReviewButton)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(cardTitle)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(submitReviewButton, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(goBackButton, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void goBackButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_goBackButtonActionPerformed
this.parentFrame.showCard("browseMoviesCard");
}//GEN-LAST:event_goBackButtonActionPerformed
private void submitReviewButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitReviewButtonActionPerformed
if (movieReviewTextArea.getText().equals("")) {
JOptionPane.showMessageDialog(this, "A movie review cannot be blank! Please write something.", "Input Errors", JOptionPane.WARNING_MESSAGE);
} else {
Base.open("com.mysql.jdbc.Driver", "jdbc:mysql://db4free.net:3306/picturehouse", "picturehouse", "65CEerFwXESQmL9nDaE");
MovieReviewController controller = new MovieReviewController();
controller.create(
this.app.getCurrentCustomer().getInteger("id"),
this.targetMovie.getInteger("id"),
movieReviewTextArea.getText());
// this.parentFrame.updateCard("homePageCard");
Base.close();
this.parentFrame.showCard("browseMoviesCard");
movieReviewTextArea.setText("");
}
}//GEN-LAST:event_submitReviewButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel cardTitle;
private javax.swing.JButton goBackButton;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea movieReviewTextArea;
private javax.swing.JButton submitReviewButton;
// End of variables declaration//GEN-END:variables
}
| true |
b2d694c91877da99859dab15ae357d9e30b3d32a
|
Java
|
WALDOISCOMING/codeforce_study
|
/src/day_2017_08_03_EducationalCodeforcesRound26/a.java
|
UHC
| 2,846 | 3.484375 | 3 |
[] |
no_license
|
package day_2017_08_03_EducationalCodeforcesRound26;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/*
* A.,
*
*
A. ؽƮ
Ʈ ð 1
Ʈ 256 ް Ʈ
Է ǥ Է
ǥ
ҹڿ 빮 ƾ ڷ и ܾ ؽƮ ˴ϴ.
ܾ ܾ 빮 Դϴ. ؽƮ ؽƮ ܾ ִ Դϴ.
־ ؽƮ Ͻʽÿ.
Է
ù ° ٿ ϳ n (1 n 200) - ؽƮ ̰ Ե˴ϴ.
° и s1, s2, ..., si ؽƮ ԵǾ ֽϴ. 빮 ƾ ڷθ ˴ϴ.
ϳ - ؽƮ μϽʽÿ.
*/
public class a {
static int BIGCOUNT=0;
static int BEST=0;
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int n = sc.nextInt();
String input = sc.nextLine();
for(int i=0;i<n;i++)
{
counting(input.charAt(i));
}
if(BEST==0)BEST=BIGCOUNT;
out.println(BEST);
out.close();
}
public static void counting(char c)
{
if(c>=65&&c<=90)
BIGCOUNT++;
if(c==' '){
if(BIGCOUNT>BEST){
BEST=BIGCOUNT;
}
BIGCOUNT=0;
}
}
static PrintWriter out;
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| true |
e7dc64aae036d5d266ba819942b183763a3dd307
|
Java
|
luohaiyun/sqlbuilder
|
/src/main/java/com/github/haivan/sqlbuilder/clauses/condition/QueryCondition.java
|
UTF-8
| 1,273 | 2.296875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.github.haivan.sqlbuilder.clauses.condition;
import com.github.haivan.sqlbuilder.Query;
import com.github.haivan.sqlbuilder.clauses.AbstractClause;
import com.github.haivan.sqlbuilder.BaseQuery;
public class QueryCondition<T extends BaseQuery<T>> extends AbstractCondition
{
public String column;
public String operator;
public Query query;
public QueryCondition()
{
}
public QueryCondition(String column, String operator, Query query, boolean isNot, boolean isOr)
{
this.column = column;
this.operator = operator;
this.query = query;
this.isNot = isNot;
this.isOr = isOr;
}
public String getColumn()
{
return column;
}
public void setColumn(String column)
{
this.column = column;
}
public String getOperator()
{
return operator;
}
public void setOperator(String operator)
{
this.operator = operator;
}
public Query getQuery()
{
return query;
}
public void setQuery(Query query)
{
this.query = query;
}
@Override
public AbstractClause clone()
{
QueryCondition<T> clone = new QueryCondition<>();
clone.column = column;
clone.query = query;
clone.operator = operator;
clone.isNot = isNot;
clone.isOr = isOr;
clone.component = component;
clone.dialect = dialect;
return clone;
}
}
| true |
4dc58733167a1b8fe127c3e6b4da8c9e8a097294
|
Java
|
mupengX/RestfulFrameWork
|
/tk/framework/src/main/java/com/tk/framework/service/BaseService.java
|
UTF-8
| 2,155 | 2.359375 | 2 |
[] |
no_license
|
package com.tk.framework.service;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.tk.framework.page.PageBeanDto;
/**
* <pre>
*
* File: BaseService.java
*
* Copyright (C): 2014
* Description: Service基础类
* TODO
*
* Notes:
* $Id: BaseService.java 2014-12-24 23:59:59Z \TK $
*
* @Revision History:
* <<2014年12月25日下午3:39:17>>, <<Who>>, <<what>>
* 2014年12月25日 TK Initial.
* </pre>
*/
public interface BaseService<T, QT>
{
/**
* 根据对象添加
*
* @param t
* @throws Exception
*/
public void add(T t) throws Exception;
/**
* 根据对象修改
*
* @param t
* @throws Exception
*/
public void update(T t) throws Exception;
/**
* 按照id删除对象
*
* @param id
* @throws Exception
*/
@SuppressWarnings("rawtypes")
public void deleteById(Class cls, Serializable id) throws Exception;
/**
* 按照id查询对象
*
* @param id
* @throws Exception
*/
@SuppressWarnings("rawtypes")
public T findById(Class cls, Serializable id) throws Exception;
/**
* 查询全部
*
* @param entityName 实体类名称
* @throws Exception
*/
public List<T> findAll(String entityName) throws Exception;
/**
* 执行条件查询
*
* @throws Exception
*/
public Object executeQuery(String hql, HashMap<String, Object> params) throws Exception;
/**
* 根据自定义SQL进行分页查询。totalSQLName:查询结果总数的SQL对应的SQL名称;querySQLName:查询结果集的SQL对应的SQL名称;requestURI:用户请求地址;
* pageBeanDto:分页相关参数;params:查询参数MAP,用于放置自定义的查询参数;clazz:查询结果对应的实体类。
*
* @param totalSQLName
* @param querySQLName
* @param requestURI
* @param pageBeanDto
* @param params
* @param clazz
* @return
* @throws Exception
*/
@SuppressWarnings("rawtypes")
public PageBeanDto pageQueryByCustomSQLName(String totalSQLName, String querySQLName, String requestURI,
PageBeanDto pageBeanDto, Map params, Class clazz) throws Exception;
}
| true |
97c9988d42deeb563aed68a2b85dd49c48089160
|
Java
|
17huaProject/Front-end-Project
|
/src/com/yqh/bsp/base/quartz/ResourceKit.java
|
UTF-8
| 2,126 | 2.796875 | 3 |
[] |
no_license
|
package com.yqh.bsp.base.quartz;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
public class ResourceKit {
/**
* @Title: loadSqlFile
* @Description: 加载sql.properties文件,并获取其中的内容(key-value)
* @param filePath
* : 文件路径
* @author
* @date 2011-12-28
*/
public static Map<String,String> readProperties(String filePath) {
Map<String,String> proMap = new HashMap<String, String>();
if (null == filePath || "".equals(filePath.trim())) {
System.out.println("The file path is null,return");
return null;
}
filePath = filePath.trim();
// 获取资源文件
InputStream is = ResourceKit.class.getClassLoader()
.getResourceAsStream(filePath);
// 属性列表
Properties prop = new Properties();
try {
// 从输入流中读取属性列表
prop.load(is);
} catch (IOException e) {
System.out.println("load file faile." + e);
return null;
} catch (Exception e) {
System.out.println("load file faile." + e);
return null;
}
// 返回Properties中包含的key-value的Set视图
Set<Entry<Object, Object>> set = prop.entrySet();
// 返回在此Set中的元素上进行迭代的迭代器
Iterator<Map.Entry<Object, Object>> it = set.iterator();
String key = null, value = null;
// 循环取出key-value
while (it.hasNext()) {
Entry<Object, Object> entry = it.next();
key = String.valueOf(entry.getKey());
value = String.valueOf(entry.getValue());
key = key == null ? key : key.trim();
value = value == null ? value : value.trim();
// 将key-value放入map中
proMap.put(key, value);
}
return proMap;
}
}
| true |
bcb4bc057001cb9e574277bc2f1eaad1711c69b2
|
Java
|
underwindfall/Android_MVP_Sport
|
/app/src/main/java/com/sport/qifan/sport/views/fragment/news/NewFragView.java
|
UTF-8
| 356 | 1.601563 | 2 |
[] |
no_license
|
package com.sport.qifan.sport.views.fragment.news;
import com.sport.qifan.sport.model.module.SportsNews;
import com.sport.qifan.sport.views.BaseView;
import java.util.ArrayList;
/**
* Created by qifan on 2016/11/17.
*/
public interface NewFragView extends BaseView {
void goToDetail();
// void refreshList(ArrayList<SportsNews> sportsList);
}
| true |
1d0159e0857b8cead34bcf020cbcde3395c4d462
|
Java
|
Majsan3k/Image-transfer
|
/src/ImageClient.java
|
UTF-8
| 4,517 | 3.21875 | 3 |
[] |
no_license
|
//Då jag inte använder mig av klassen Storage i denna uppgift har jag byggt en egen server.
//Den ligger i mappen Server och behöver startas innan programmet körs.
/**
* A program for sending and receiving images
*
* @author Maja Lund
*/
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
public class ImageClient extends JFrame implements Runnable{
private ObjectOutputStream objOut;
private Socket socket;
private JLabel imageView;
/**
* Creates a GUI and a socket and opens a ObjectOutputStream on the socket.
*
* @param host socket host
* @param port socket port
*/
public ImageClient(String host, int port){
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Menu");
JMenuItem getImage = new JMenuItem("Choose Image");
getImage.addActionListener(e -> sendImage());
menu.add(getImage);
menuBar.add(menu);
setJMenuBar(menuBar);
imageView = new JLabel();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setPreferredSize(new Dimension(500, 300));
setVisible(true);
pack();
try {
socket = new Socket(host, port);
objOut = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
System.out.println("Couldn't connect. " + e.getMessage());
System.exit(1);
}
}
/**
* Show the image for the user
* @param image
*/
private void showImage(ImageIcon image){
imageView.setIcon(image);
add(imageView);
pack();
repaint();
}
/**
* Get image from JFileChooser and send in throw ObjectOutPutStream
*/
private synchronized void sendImage(){
JFileChooser selectImage = new JFileChooser("");
FileNameExtensionFilter filter = new FileNameExtensionFilter("Pictures (png, jpg)", "png", "jpg");
selectImage.setFileFilter(filter);
int newImage = selectImage.showOpenDialog(this);
if (newImage != JFileChooser.APPROVE_OPTION) {
return;
}
File imageFile = selectImage.getSelectedFile();
ImageIcon image = new ImageIcon(imageFile.getAbsolutePath());
try{
objOut.writeObject(image);
objOut.flush();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
/**
* Listens for incoming data throw ObjectInputStream. If any data receives it while casts to a ImageIcon
* and shows for the user.
*/
@Override
public void run() {
ObjectInputStream objIn = null;
try {
objIn = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
Object image;
try {
while((image = objIn.readObject()) != null){
ImageIcon receivedImage = (ImageIcon) image;
showImage(receivedImage);
}
}catch(SocketException s){
close();
System.out.println("You lost connection");
System.exit(1);
}catch (IOException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
close();
}
/**
* Close socket and ObjectOutPutStream
*/
private void close(){
try {
socket.close();
objOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Starts the program. Uses host 127.0.0.1 and port 2000 if nothing else is specified by user.
* Host should be specified at index 0 and host at index 1.
* Closes program if more than 2 arguments is specified
* @param args
*/
public static void main(String[] args){
String host = "127.0.0.1";
int port = 2000;
if(args.length > 2){
System.out.println("To many arguments");
System.exit(1);
}
if(args.length > 0){
host = args[0];
}
if(args.length > 1){
port = Integer.parseInt(args[1].toString());
}
ImageClient imageClient = new ImageClient(host, port);
Thread thread = new Thread(imageClient);
thread.start();
}
}
| true |
290b2ef98d0c0713487ebd3affb8e253429655b0
|
Java
|
NicolasPafundi/UTNPhones
|
/src/main/java/com/utn/TPFinal/controllers/MobileReportController.java
|
UTF-8
| 3,459 | 2.265625 | 2 |
[] |
no_license
|
package com.utn.TPFinal.controllers;
import com.utn.TPFinal.exceptions.ResourceNotExistException;
import com.utn.TPFinal.model.dtos.MobileReportFilter;
import com.utn.TPFinal.model.projections.MobileReportUserBills;
import com.utn.TPFinal.model.projections.MobileReportUserCalls;
import com.utn.TPFinal.model.projections.MobileReportUserCallsRank;
import com.utn.TPFinal.services.MobileReportService;
import com.utn.TPFinal.session.SessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import static java.util.Objects.isNull;
@RestController
@RequestMapping("/api/MobileReport")
public class MobileReportController {
private final MobileReportService mobileReportService;
private final SessionManager sessionManager;
@Autowired
public MobileReportController(MobileReportService mobileReportService, SessionManager sessionManager){
this.mobileReportService= mobileReportService;
this.sessionManager = sessionManager;
}
@PostMapping("/Client/callByDate")
public ResponseEntity<List<MobileReportUserCalls>> getCallsByUserByDate(@RequestHeader("Authorization") String sessionToken, @RequestBody MobileReportFilter mobileReportFilter) throws ResourceNotExistException {
try{
Integer userId = sessionManager.getCurrentUser(sessionToken).getId();
List<MobileReportUserCalls> mobileReportUserCalls = mobileReportService.getCallsByUserByDate(mobileReportFilter.getDateFrom(),mobileReportFilter.getDateTo(),userId);
return (mobileReportUserCalls.size() > 0) ? ResponseEntity.ok(mobileReportUserCalls) : ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}catch (ResourceNotExistException ex){
throw ex;
}
}
@PostMapping("/Client/billsByDate")
public ResponseEntity<List<MobileReportUserBills>> getBillsByUserByDate(@RequestHeader("Authorization") String sessionToken,@RequestBody MobileReportFilter mobileReportFilter) throws ResourceNotExistException {
try{
Integer userId = sessionManager.getCurrentUser(sessionToken).getId();
List<MobileReportUserBills> mobileReportUserBills = mobileReportService.getBillsByUserByDate(mobileReportFilter.getDateFrom(),mobileReportFilter.getDateTo(),userId);
return (mobileReportUserBills.size() > 0) ? ResponseEntity.ok(mobileReportUserBills) : ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}catch (ResourceNotExistException ex){
throw ex;
}
}
@GetMapping("/Client/destinationRank/{top?}")
public ResponseEntity<List<MobileReportUserCallsRank>> getDestinationRankByUser(@RequestHeader("Authorization") String sessionToken,@RequestParam(value= "top",required = false, defaultValue = "10") Integer top) throws ResourceNotExistException {
try{
Integer userId = sessionManager.getCurrentUser(sessionToken).getId();
List<MobileReportUserCallsRank> mobileReportUserCallsRank = mobileReportService.getDestinationRankByUser(userId,top);
return (mobileReportUserCallsRank.size() > 0) ? ResponseEntity.ok(mobileReportUserCallsRank) : ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}catch (ResourceNotExistException ex){
throw ex;
}
}
}
| true |
811372f733c9d1aeb7d4c6da8e2dc5eae4af402a
|
Java
|
aWildElephant/unoriginal-rdbms
|
/engine/storage/src/main/java/fr/awildelephant/rdbms/engine/data/record/MultipleColumnsIterator.java
|
UTF-8
| 687 | 2.59375 | 3 |
[] |
no_license
|
package fr.awildelephant.rdbms.engine.data.record;
import fr.awildelephant.rdbms.engine.data.column.Column;
import java.util.Iterator;
import java.util.List;
public final class MultipleColumnsIterator implements Iterator<Record> {
private final MultipleColumnsIteratorRecord record;
private int cursor;
public MultipleColumnsIterator(List<? extends Column> columns) {
record = new MultipleColumnsIteratorRecord(columns);
cursor = -1;
}
@Override
public boolean hasNext() {
return record.validPosition(cursor + 1);
}
@Override
public Record next() {
record.setPosition(++cursor);
return record;
}
}
| true |
283dedc37143b25f82f0cc50a7766d0702ca4d5d
|
Java
|
halla2709/Golf-Tournament-Pal-App
|
/java/com/example/halla/golftournamentpal/models/User.java
|
UTF-8
| 602 | 2.53125 | 3 |
[] |
no_license
|
package com.example.halla.golftournamentpal.models;
/**
* Created by Halla on 21-Feb-17.
*/
public class User {
private long mSocial;
private String mPassword;
public User(long social, String password) {
mSocial = social;
mPassword = password;
}
public long getSocial() {
return mSocial;
}
public void setSocial(long social) {
mSocial = social;
}
public String getPassword() {
return mPassword;
}
public void setPassword(String password) {
mPassword = password;
}
}
| true |
10043d48bf761fa56396ffec44da29fa2001cb91
|
Java
|
shakilur157/car_repair_finde
|
/src/main/java/car/repair/finder/models/ServiceProviderRequest.java
|
UTF-8
| 1,751 | 2.234375 | 2 |
[] |
no_license
|
package car.repair.finder.models;
import javax.validation.constraints.NotNull;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
import org.hibernate.annotations.CreationTimestamp;
import org.springframework.validation.annotation.Validated;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name = "service_provider_request")
@Validated
@Getter
@Setter
@NoArgsConstructor
public class ServiceProviderRequest {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Column(name = "service_request_id")
private Long serviceRequestId;
@NotNull
@Column(name = "service_centre_id")
private Long serviceCentreId;
@ColumnDefault("0.00")
private double discount;
@NotNull
private double repairTime;
@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(columnDefinition = "DATE DEFAULT CURRENT_DATE",name = "created_at", updatable = false)
private Date createdAt;
public ServiceProviderRequest(Long serviceRequestId, Long serviceCentreId, double discount, double repairTime) {
this.serviceRequestId = serviceRequestId;
this.serviceCentreId = serviceCentreId;
this.discount = discount;
this.repairTime = repairTime;
}
public ServiceProviderRequest(Long serviceRequestId, double discount, double repairTime) {
this.serviceRequestId = serviceRequestId;
this.discount = discount;
this.repairTime = repairTime;
}
public ServiceProviderRequest(Long serviceRequestId, double repairTime) {
this.serviceRequestId = serviceRequestId;
this.repairTime = repairTime;
}
}
| true |
9d63a841d8ad3b00be2fb78086caad16af01c643
|
Java
|
MindSelf/Gallery
|
/app/src/main/java/com/example/zhaolexi/imageloader/redirect/router/Result.java
|
UTF-8
| 981 | 2.421875 | 2 |
[
"MIT"
] |
permissive
|
package com.example.zhaolexi.imageloader.redirect.router;
public class Result<T> {
public static final int SUCCESS = 1;
public static final int FAIL = 0;
public static final int TOKEN_ERROR = -1;
public static final int ILLEGAL_ARGUMENT = -2;
public static final int SERVER_ERROR = -3;
public static final int PERMISSION_DENIED = -4;
private int code;
private String msg;
private T data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public boolean isSuccess() {
return code >= SUCCESS;
}
@Override
public String toString() {
return "[code:" + code + ",msg:" + msg + "]";
}
}
| true |
dd1e14894b53febe962ae9d73f8d90c5dcc954d1
|
Java
|
zakiva/2Order
|
/app/src/main/java/com/example/zakiva/tworder/write_sms.java
|
UTF-8
| 2,964 | 1.921875 | 2 |
[] |
no_license
|
package com.example.zakiva.tworder;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.CountCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import org.w3c.dom.Text;
public class write_sms extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write_sms);
Bundle extras = getIntent().getExtras();
TextView name = (TextView) findViewById(R.id.to_customer_name);
name.setText("To: " + extras.getString("name"));
}
public void alertToast(String alert){
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.my_custom_alert,
(ViewGroup) findViewById(R.id.my_custom_layout_id));
TextView text = (TextView) layout.findViewById(R.id.alertText);
text.setText(alert);
Toast toast2 = new Toast(getApplicationContext());
toast2.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
toast2.setDuration(Toast.LENGTH_LONG);
toast2.setView(layout);
toast2.show();
}
public void send_sms(final String number, final String content) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Baned");
query.whereEqualTo("phone_number", number);
query.countInBackground(new CountCallback() {
public void done(int count, ParseException e) {
if (count == 0) {
Log.d("banned: ", "not inside! sms should be sent");
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(number, null, content, null, null);
} catch (Exception e1) {
}
} else {
Log.d("banned: ", "inside! no sms");
alertToast("Sms was not sent, since the phone number owner does not want to get sms messages");
}
}
});
}
public void send_sms(View view){
Bundle extras = getIntent().getExtras();
String phone = extras.getString("phone");
EditText sms_content = (EditText) findViewById(R.id.editText4);
String content = sms_content.getText().toString();
send_sms(phone, content);
Intent i = new Intent(this, business_orders__screen.class);
startActivity(i);
}
}
| true |
c94e7da052226fdbd96aafdce406454597e19656
|
Java
|
vikymediana/RaspberryHome
|
/src/rbhmessage/RbhMessage.java
|
UTF-8
| 895 | 2.453125 | 2 |
[] |
no_license
|
package rbhmessage;
import java.io.Serializable;
public class RbhMessage implements Serializable {
public enum MessageType {
CREATE,
DELETE,
ORDER,
DATA
}
private MessageType messageType;
private Item item;
private String itemId;
private byte[] data;
public MessageType getMessageType() {
return messageType;
}
public void setMessageType(MessageType messageType) {
this.messageType = messageType;
}
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
}
| true |
c0d39a5a8acbc68296e73cb7d90a16a08bfe9380
|
Java
|
cpuksm/Work05
|
/src/Workshop04/Book.java
|
UTF-8
| 974 | 3.09375 | 3 |
[] |
no_license
|
package Workshop04;
public class Book {
private String bookName;
private int bookPrice;
private double bookDiscountRate;
public Book() {
super();
// TODO Auto-generated constructor stub
}
public Book(String bookName, int bookPrice, double bookDiscountRate) {
super();
this.bookName = bookName;
this.bookPrice = bookPrice;
this.bookDiscountRate = bookDiscountRate;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getBookPrice() {
return bookPrice;
}
public void setBookPrice(int bookPrice) {
this.bookPrice = bookPrice;
}
public double getBookDiscountRate() {
return bookDiscountRate;
}
public void setBookDiscountRate(double bookDiscountRate) {
this.bookDiscountRate = bookDiscountRate;
}
public double getDiscountBookPrice() {
double d = bookPrice*(1 - bookDiscountRate/100);
return d;
}
}
| true |
455bc0e64856c9dc1c1b7277729a85ebe00ab97b
|
Java
|
JuanVillaraus/conexionPV
|
/src/conexionpv/comSPV.java
|
UTF-8
| 10,517 | 2.21875 | 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 conexionpv;
import java.net.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.JFrame;
/**
*
* @author siviso
*/
public class comSPV extends Thread {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Socket socket;
byte[] mensaje_bytes = new byte[256];
String mensaje = "";
String msn;
String texto;
String word;
String save;
int nDatos;
boolean error;
boolean habilitado = false;
int t = 500;
DatagramSocket socketComInterfaz;
int portComInterfaz;
InetAddress address;
DatagramPacket comUP;
DatagramPacket comDW;
DatagramPacket paqGan;
InetAddress ping;
int gan;
boolean bSensorPV = true;
Properties prop = new Properties();
InputStream input = null;
String DIR = "";
int PORT = 0;
int n;
comSPPsend cspps;
public boolean getHabilitado() {
return this.habilitado;
}
public boolean getHabilitarSensorPV() {
return this.bSensorPV;
}
public void setHabilitado(boolean h) {
this.habilitado = h;
}
public void setPortComInterfaz(int portComInterfaz) {
this.portComInterfaz = portComInterfaz;
}
public void setHabilitarSensorPV(boolean bSensorPV) {
this.bSensorPV = bSensorPV;
}
public void setSend(comSPPsend cspps) {
this.cspps = cspps;
}
public void run() {
try {
//socket = new Socket(DIR, PORT);
socketComInterfaz = new DatagramSocket();
address = InetAddress.getByName("localhost");
mensaje = "C_UP";
mensaje_bytes = mensaje.getBytes();
comUP = new DatagramPacket(mensaje_bytes, mensaje.length(), address, portComInterfaz);
mensaje = "C_DW";
mensaje_bytes = mensaje.getBytes();
comDW = new DatagramPacket(mensaje_bytes, mensaje.length(), address, portComInterfaz);
//DataOutputStream out = new DataOutputStream(socketComInterfaz.getOutputStream());
//BufferedReader inp = new BufferedReader(new InputStreamReader(socketComInterfaz.getInputStream()));
sleep(1000);
int n = 0;
String ip = "192.168.1.10"; // Ip de la máquina remota
try {
input = new FileInputStream("config.properties");
prop.load(input);
DIR = prop.getProperty("dirSSPV");
PORT = Integer.parseInt(prop.getProperty("portBTR"));
System.out.println("BTR comSPV " + DIR + " " + PORT);
} catch (IOException e) {
System.err.println(e.getMessage());
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}
socket = new Socket(DIR, PORT);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
BufferedReader inp = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
if (getHabilitado()) {
try {
ping = InetAddress.getByName(ip);
if (ping.isReachable(5000)) {
System.out.println("Enlazado");
socketComInterfaz.send(comUP);
} else {
System.out.println("Desconectado");
socketComInterfaz.send(comDW);
}
} catch (IOException ex) {
System.out.println(ex);
}
}
n = 0;
if (getHabilitarSensorPV()) {
do {
try {
sleep(2000); //espera un segundo
} catch (Exception e) {
System.err.println("Error espera en sleep: " + e.getMessage());
}
mensaje = "TempHum";
out.writeUTF(mensaje);
System.out.println("Envie: " + mensaje);
msn = inp.readLine();
System.out.println("Recibí: " + msn);
mensaje = "ConfPulsRx";
out.writeUTF(mensaje);
System.out.println("Envie: " + mensaje);
msn = inp.readLine();
System.out.println("Recibí: " + msn);
n++;
} while (!"NO OK".equals(msn) && n < 2);
char[] charArray = msn.toCharArray();
word = "";
for (char temp : charArray) {
if (temp == '1' || temp == '2' || temp == '3' || temp == '4' || temp == '5' || temp == '6' || temp == '7' || temp == '8' || temp == '9' || temp == '0'|| temp == '.') {
word += temp;
}
/*if (temp == ',') {
System.out.println("Temp interior: " + word);
cspps.setTempIn(word);
} else if (temp == ';' && !"".equals(temp)) {
System.out.println("Hum interior: " + word);
cspps.setHum(word);
}*/
if (temp == ',' || temp == ';') {
System.out.println("TempHum: " + word);
switch (n) {
case 1:
cspps.setTempIn(word);
break;
case 2:
cspps.setHum(word);
break;
}
n++;
}
word = "";
}
mensaje = "Paq1";
out.writeUTF(mensaje);
System.out.println("Envie: " + mensaje);
msn = inp.readLine();
System.out.println("Recibí: " + msn);
mensaje = "MLM_Rx";
out.writeUTF(mensaje);
System.out.println("Envie: " + mensaje);
msn = inp.readLine();
System.out.println("Recibí: " + msn);
n = 0;
word = "";
for (char temp : charArray) {
if (temp == '1' || temp == '2' || temp == '3' || temp == '4' || temp == '5' || temp == '6' || temp == '7' || temp == '8' || temp == '9' || temp == '0'|| temp == '.') {
word += temp;
}
if (temp == ',' || temp == ';') {
System.out.println("YPR: " + word);
switch (n) {
case 1:
cspps.setYaw(word);
break;
case 2:
cspps.setPitch(word);
break;
case 3:
cspps.setRoll(word);
break;
}
n++;
}
word = "";
}
mensaje = "Paq2";
out.writeUTF(mensaje);
System.out.println("Envie: " + mensaje);
msn = inp.readLine();
System.out.println("Recibí: " + msn);
mensaje = "MLM_Rx";
out.writeUTF(mensaje);
System.out.println("Envie: " + mensaje);
msn = inp.readLine();
System.out.println("Recibí: " + msn);
n = 0;
word = "";
for (char temp : charArray) {
if (temp == '1' || temp == '2' || temp == '3' || temp == '4' || temp == '5' || temp == '6' || temp == '7' || temp == '8' || temp == '9' || temp == '0'|| temp == '.') {
word += temp;
}
if (temp == ',' || temp == ';') {
System.out.println("PTS: " + word);
switch (n) {
case 1:
cspps.setProf(word);
break;
case 2:
cspps.setTemp(word);
break;
case 3:
cspps.setSal(word);
break;
}
n++;
}
word = "";
}
mensaje = "Paq3";
out.writeUTF(mensaje);
System.out.println("Envie: " + mensaje);
msn = inp.readLine();
System.out.println("Recibí: " + msn);
mensaje = "MLM_Rx";
out.writeUTF(mensaje);
System.out.println("Envie: " + mensaje);
msn = inp.readLine();
System.out.println("Recibí: " + msn);
cspps.setVelSound(msn);
}
try {
sleep(t);
} catch (Exception e) {
Thread.currentThread().interrupt();
System.err.println(e.getMessage());
}
}
} catch (Exception e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
}
| true |
e4637f0a6ff932de5ec47bcaab51afb7a20173fe
|
Java
|
mpplaza/icplayer
|
/src/test/java/com/lorepo/icplayer/client/page/mockup/ModuleFactoryMockup.java
|
UTF-8
| 1,503 | 2.046875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.lorepo.icplayer.client.page.mockup;
import com.lorepo.icplayer.client.module.IModuleFactory;
import com.lorepo.icplayer.client.module.api.IModuleModel;
import com.lorepo.icplayer.client.module.api.IModuleView;
import com.lorepo.icplayer.client.module.api.IPresenter;
import com.lorepo.icplayer.client.module.api.player.IPlayerServices;
import com.lorepo.icplayer.client.module.choice.ChoiceModel;
import com.lorepo.icplayer.client.module.choice.ChoicePresenter;
import com.lorepo.icplayer.client.module.choice.mockup.ChoiceViewMockup;
import com.lorepo.icplayer.client.module.sourcelist.SourceListModule;
import com.lorepo.icplayer.client.module.sourcelist.SourceListPresenter;
public class ModuleFactoryMockup implements IModuleFactory {
private IPlayerServices services;
public ModuleFactoryMockup(IPlayerServices services){
this.services = services;
}
@Override
public IModuleModel createModel(String xmlNodeName) {
// TODO Auto-generated method stub
return null;
}
@Override
public IModuleView createView(IModuleModel module) {
if(module instanceof ChoiceModel){
return new ChoiceViewMockup((ChoiceModel) module);
}
return null;
}
@Override
public IPresenter createPresenter(IModuleModel model) {
if(model instanceof ChoiceModel){
return new ChoicePresenter((ChoiceModel) model, services);
}
else if(model instanceof SourceListModule){
return new SourceListPresenter((SourceListModule) model, services);
}
return null;
}
}
| true |
a753d9b3e8c83f0b20c31097292c47bde7b722e5
|
Java
|
MovilesJuanDeDios/ProyectoAerolineaUlt
|
/ProyectoAerolineaFrontend/app/src/main/java/cr/ac/una/escinf/proyectoaerolinea/activities/BookFlightActivity.java
|
UTF-8
| 3,007 | 2.0625 | 2 |
[] |
no_license
|
package cr.ac.una.escinf.proyectoaerolinea.activities;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Currency;
import cr.ac.una.escinf.proyectoaerolinea.R;
import cr.ac.una.escinf.proyectoaerolinea.fragments.DatePickerFragment;
import cr.ac.una.escinf.proyectoaerolinea.fragments.Tab1;
import cr.ac.una.escinf.proyectoaerolinea.fragments.Tab2;
import cr.ac.una.escinf.proyectoaerolinea.fragments.Tab3;
public class BookFlightActivity extends BaseActivity implements DatePickerDialog.OnDateSetListener {
private FragmentTabHost tabHost;
EditText fecha_ida;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_flight);
tabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
tabHost.setup(this, getSupportFragmentManager(),android.R.id.tabcontent);
tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Busca Vuelo"),
Tab1.class, null);
tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("Selecciona tu asiento"),
Tab2.class, null);
tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("Check Out"),
Tab3.class, null);
tabHost.getTabWidget().getChildTabViewAt(0).setEnabled(false);
tabHost.getTabWidget().getChildTabViewAt(1).setEnabled(false);
tabHost.getTabWidget().getChildTabViewAt(2).setEnabled(false);
LayoutInflater factory = getLayoutInflater();
View textView = factory.inflate(R.layout.activity_tab1, null);
fecha_ida = (EditText) textView.findViewById(R.id.fecha_ida_editText);
fecha_ida.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "date picker");
}
});
}
@Override
public void onBackPressed() {
Intent intent = new Intent(BookFlightActivity.this, MainPageActivity.class);
startActivity(intent);
finish();
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String currentDateString = DateFormat.getDateInstance().format(calendar.getTime());
fecha_ida.setText(currentDateString);
}
}
| true |
7404d582124de57dce3b9c4c2e16af3485ac5cb4
|
Java
|
mfroehlich/utils
|
/src/main/java/com/froehlich/utils/mbeans/MBeanRegistrator.java
|
UTF-8
| 1,493 | 2.75 | 3 |
[] |
no_license
|
package com.froehlich.utils.mbeans;
import org.slf4j.Logger;
import javax.inject.Inject;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
/**
* Created by mfroehlich on 21.11.2014.
*/
public class MBeanRegistrator {
@Inject
private MBeanServer mbeanServer;
@Inject
private Logger logger;
public <M> void registerMBean(String objectNameStr, M mbeanInstance) {
try {
ObjectName objectName = new ObjectName(objectNameStr);
try {
mbeanServer.unregisterMBean(objectName);
} catch (InstanceNotFoundException e) {
logger.info("Tried to unregister MBean before registering it, but wasn't there. Everything's ok.");
}
mbeanServer.registerMBean(mbeanInstance, objectName);
logger.debug("MBean " + objectNameStr + " registered");
} catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException
| MalformedObjectNameException e) {
logger.error("Error registering MBean " + objectNameStr, e);
throw new IllegalArgumentException("Error registering MBean " + objectNameStr);
}
}
}
| true |
ca8bf044081e3935235961bcad1949392dd722f3
|
Java
|
riccardotommasini/gsonld
|
/src/main/java/it/polimi/gsonld/JsonLDSerializer.java
|
UTF-8
| 22,762 | 2.09375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package it.polimi.gsonld;
import com.google.gson.*;
import it.polimi.gsonld.annotations.*;
import it.polimi.gsonld.annotations.Object;
import it.polimi.gsonld.annotations.Type;
import java.lang.reflect.*;
import java.util.*;
import java.util.stream.Collectors;
import static it.polimi.gsonld.JsonldUtils.*;
/**
* Created by riccardo on 24/08/2017.
*/
public class JsonLDSerializer<T> implements JsonSerializer<T> {
private HashMap<String, String> prefixes, aliases;
private HashMap<String, String> inverse_aliases;
private HashMap<String, Set<String>> properties;
private HashMap<String, String> reference_names;
private boolean expand_prefixes = false, autogen_prefixes = false;
public JsonLDSerializer() {
this.prefixes = new HashMap<>();
this.aliases = new HashMap<>();
this.inverse_aliases = new HashMap<>();
this.properties = new HashMap<>();
this.reference_names = new HashMap<>();
}
public static JsonLDSerializer<?> get(Class<?> c) {
return new JsonLDSerializer<>();
}
public JsonElement serialize(T t, java.lang.reflect.Type typeOfSrc, JsonSerializationContext jsonc) {
JsonElement res = null;
if (t.getClass().isAnnotationPresent(Object.class)) {
Object a = t.getClass().getAnnotation(Object.class);
if (a.expanded()) {
} else if (a.flattened()) {
} else if (a.framed()) {
} else {
JsonObject o = new JsonObject();
JsonElement c = buildContext(t, t.getClass(), new JsonObject());
o.add(JSONLD_CONTEXT, c);
res = getJsonElement(t, t.getClass(), o, c);
}
} else if (t.getClass().isAnnotationPresent(Property.class)) {
}
return res;
}
private JsonElement buildContext(java.lang.Object t, Class<?> c, JsonElement context) {
extractAliases(c, context);
Arrays.stream(c.getMethods()).filter(this::isGetter).filter(m -> !"getClass".equals(m.getName())).collect(Collectors.toList())
.forEach(m -> updateContext(c, context, m, m.getName(), getPropertyName(m), m));
Arrays.stream(c.getFields()).forEach((Field f) ->
updateContext(c, context, f, f.getName(), getPropertyName(f), f));
if (c.isAnnotationPresent(Base.class) && isURI(c.getAnnotation(Base.class).value())) {
if (!context.isJsonObject() || ((JsonObject) context).size() == 0) {
return new JsonPrimitive(c.getAnnotation(Base.class).value());
} else
((JsonObject) context).addProperty(JSONLD_VOCAB, c.getAnnotation(Base.class).value());
}
if (c.isAnnotationPresent(Vocab.class) && isURI(c.getAnnotation(Vocab.class).value())) {
if (!context.isJsonObject() || ((JsonObject) context).size() == 0) {
return new JsonPrimitive(c.getAnnotation(Vocab.class).value());
} else
((JsonObject) context).addProperty(JSONLD_VOCAB, c.getAnnotation(Vocab.class).value());
}
return context;
}
private void updateContext(Class<?> aClass, JsonElement context, AccessibleObject m, String name, String property, AccessibleObject a) {
String reference_name = property;
if (m.isAnnotationPresent(Property.class)) {
String field_uri = m.getAnnotation(Property.class).value();
if (m.isAnnotationPresent(Type.class)) {
JsonObject p = new JsonObject();
String property_type = m.getAnnotation(Type.class).value();
p.addProperty(JSONLD_TYPE, property_type);
p.addProperty(JSONLD_ID, field_uri);
checkPrefix(property_type, aClass);
if (context.isJsonPrimitive()) {
} else if (context.isJsonObject() && !((JsonObject) context).has(property_type)) {
((JsonObject) context).add(reference_name, p);
}
} else {
if (context.isJsonPrimitive()) {
} else if (context.isJsonObject() && !((JsonObject) context).has(reference_name)) {
if (!field_uri.equals(reference_name) && (!isAliased(field_uri) || isPrefixed(field_uri))) {
((JsonObject) context).addProperty(reference_name, field_uri);
}
}
}
}
if (m.isAnnotationPresent(Prefix.class) && isPrefix(m.getAnnotation(Prefix.class).value())) {
String prefix = m.getAnnotation(Prefix.class).value();
reference_name = prefix + ":" + reference_name;
if (m.isAnnotationPresent(Type.class)) {
JsonObject p = new JsonObject();
String property_type = m.getAnnotation(Type.class).value();
p.addProperty(JSONLD_TYPE, property_type);
checkPrefix(property_type, aClass);
if (context.isJsonPrimitive()) {
} else if (context.isJsonObject()) {
((JsonObject) context).add(reference_name, p);
}
}
}
reference_names.put(name, reference_name);
if (!a.isAnnotationPresent(Graph.class) || (!a.isAnnotationPresent(Metadata.class) && aClass.isAnnotationPresent(Graph.class))) {
Set<String> s = properties.containsKey(reference_name) ? properties.get(reference_name) : new HashSet<>();
s.add(name);
properties.put(reference_name, s);
}
}
private JsonElement getJsonElement(java.lang.Object t, Class<?> aClass, JsonObject o, JsonElement context) {
Map<String, JsonArray> properties_objects = new HashMap<>();
String type = new String();
if (!aClass.isAnnotationPresent(Object.class)) {
buildContext(t, aClass, context);
}
if (aClass.isAnnotationPresent(Graph.class)) {
Graph annotation = aClass.getAnnotation(Graph.class);
String id = !"[unassigned]".equals(annotation.id()) ? annotation.id() : "_b" + Math.round(Math.random());
o.addProperty(JSONLD_ID, id);
o.addProperty(JSONLD_TYPE, annotation.type());
o.add(JSONLD_GRAPH, new JsonArray());
}
if (aClass.isAnnotationPresent(Type.class)) {
type = aClass.getAnnotation(Type.class).value();
checkPrefix(type, aClass);
if (expand_prefixes) {
type = expand(type);
}
o.addProperty(JSONLD_TYPE, type);
}
Arrays.stream(aClass.getMethods()).filter(this::isGetter).filter(m -> !"getClass".equals(m.getName())).collect(Collectors.toList()).forEach(
m -> {
String property = reference_names.containsKey(m.getName()) ? reference_names.get(m.getName()) : getPropertyName(m);
getMethodValue(t, o, m, property, context);
});
Arrays.stream(aClass.getFields()).forEach(f -> {
if (aClass.isAnnotationPresent(Graph.class) && f.isAnnotationPresent(Metadata.class)) {
//TODO process field as metadata
} else if (aClass.isAnnotationPresent(Graph.class)) {
JsonArray g = o.getAsJsonArray(JSONLD_GRAPH);
g.add(buildProperty(t, new JsonObject(), context, new HashMap<>(), f));
} else if (f.isAnnotationPresent(Graph.class)) {
//TODO add {field} to class @graph
String id = f.getAnnotation(Graph.class).id();
String tt = f.getAnnotation(Graph.class).type();
if (!o.has(JSONLD_GRAPH)) {
o.add(JSONLD_GRAPH, new JsonArray());
}
JsonArray g = o.getAsJsonArray(JSONLD_GRAPH);
boolean found = false;
for (int i = 0; i < g.size(); i++) {
JsonObject elem = g.get(i).getAsJsonObject();
if (!found && elem.get(JSONLD_ID).getAsString().equals(id)) {
found = true;
//TODO probably properties_objects should be persisted to handle arrays in further elements
buildProperty(t, elem, context, new HashMap<>(), f);
if (!elem.has(JSONLD_TYPE)) {
elem.addProperty(JSONLD_TYPE, tt);
}
}
}
if (!found) {
JsonObject p = buildProperty(t, new JsonObject(), context, new HashMap<>(), f);
p.addProperty(JSONLD_TYPE, tt);
p.addProperty(JSONLD_ID, id);
g.add(p);
}
} else {
buildProperty(t, o, context, properties_objects, f);
}
/* else if (f.isAnnotationPresent(Property.class)) {
field_uri = f.getAnnotation(Property.class).value();
checkPrefix(field_uri, aClass);
if (expanded)
field_uri = expand(field_uri);
if (properties.containsKey(field_uri) && properties.get(field_uri).size() < 2) {
context.addProperty(f.getName(), field_uri);
}
} else if (!f.isAnnotationPresent(Property.class) && aClass.isAnnotationPresent(Base.class)) {
context.addProperty(f.getName(), aClass.getAnnotation(Base.class).value() + f.getName());
} else if (!f.isAnnotationPresent(Property.class) && f.isAnnotationPresent(Type.class) && f.isAnnotationPresent(NameSpace.class)) {
JsonObject p = new JsonObject();
p.addProperty(JSONLD_ID, field_uri = f.getAnnotation(NameSpace.class).value() + f.getName());
p.addProperty(JSONLD_TYPE, f.getAnnotation(Type.class).value());
context.add(f.getName(), p);
getFieldValue(t, o, f, context);
} else if (!f.isAnnotationPresent(Property.class) && f.isAnnotationPresent(NameSpace.class)) {
context.addProperty(f.getName(), field_uri = f.getAnnotation(NameSpace.class).value() + f.getName());
} else {
getFieldValue(t, o, f, null);
}*/
});
properties_objects.forEach((k, v) ->
{
o.add(k, v);
});
return o;
}
private JsonObject buildProperty(java.lang.Object t, JsonObject o, JsonElement context, Map<String, JsonArray> properties_objects, Field f) {
String name = f.getName();
String prop_name = reference_names.containsKey(name) ? reference_names.get(name) : name;
if (properties.containsKey(prop_name) && properties.get(prop_name).size() > 1) {
try {
if (properties_objects.containsKey(prop_name)) {
JsonArray array = properties_objects.get(prop_name);
if (f.getType().isAssignableFrom(String.class)) {
array.add((String) f.get(t));
} else if (f.getType().isAssignableFrom(Boolean.class)) {
array.add((Boolean) f.get(t));
} else {
array.add(f.get(t).toString());
}
} else {
JsonArray array = new JsonArray();
if (f.getType().isAssignableFrom(String.class)) {
array.add((String) f.get(t));
} else if (f.getType().isAssignableFrom(Boolean.class)) {
array.add((Boolean) f.get(t));
} else {
array.add(f.get(t).toString());
}
properties_objects.put(prop_name, array);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
getFieldValue(t, o, f, prop_name, context);
}
return o;
}
private void extractAliases(Class<?> tclass, JsonElement context) {
boolean has_alias = tclass.isAnnotationPresent(Alias.class);
boolean has_aliases = tclass.isAnnotationPresent(Aliases.class);
if (has_alias) {
Alias p = tclass.getAnnotation(Alias.class);
addAlias(context, p);
}
if (has_aliases) {
Alias[] prefixes = tclass.getAnnotationsByType(Alias.class);
Arrays.stream(prefixes).forEach(p -> {
addAlias(context, p);
});
}
if ((has_alias || has_aliases) && !tclass.getSuperclass().equals(java.lang.Object.class)) {
extractAliases(tclass.getSuperclass(), context);
}
}
private void addAlias(JsonElement context, Alias p) {
String alias = p.alias();
String val = p.value();
this.aliases.put(alias, val);
this.inverse_aliases.put(val, alias);
if ("[Unassigned]".equals(p.type())) {
if (context.isJsonObject())
((JsonObject) context).addProperty(alias, val);
} else {
JsonObject ao = new JsonObject();
ao.addProperty(JSONLD_ID, val);
ao.addProperty(JSONLD_TYPE, p.type());
((JsonObject) context).add(alias, ao);
}
}
private String expand(String type) {
String[] prefix_val = type.split(":");
return prefixes.get(prefix_val[0]) + prefix_val[1];
}
private void checkPrefix(String value, Class<?> aClass) {
if (JSONLD_ID.equals(value)) {
return;
} else if (!isURI(value) && !isPrefixed(value) && !isAliased(value) && !aClass.isAnnotationPresent(Vocab.class)) {
throw new RuntimeException(value);
}
}
private boolean isURI(String s) {
return uri_pattern.matcher(s).matches();
}
private boolean isAliased(String s) {
boolean b = aliases.containsKey(s) && inverse_aliases.containsKey(aliases.get(s));
return b;
}
private boolean isPrefixed(String s) {
String[] prefix_uri = s.split(":");
boolean b = aliases.containsKey(prefix_uri[0]) && inverse_aliases.containsKey(aliases.get(prefix_uri[0]));
return s.contains(":") && b;
}
private boolean isPrefix(String p) {
return aliases.containsKey(p);
}
private JsonObject getFieldValue(java.lang.Object t, JsonObject o, Field f, String property_name, JsonElement context) {
try {
Class<?> type = f.getType();
java.lang.Object val = f.get(t);
return accessValue(o, context, type, property_name, val);
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
}
}
private JsonObject getMethodValue(java.lang.Object t, JsonObject o, Method f, String method, JsonElement context) {
try {
if (f.getName().equals("getClass")) {
return null;
}
java.lang.Object invoke = f.invoke(t);
Class<?> type = f.getReturnType();
return accessValue(o, context, type, method, invoke);
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
} catch (InvocationTargetException e) {
e.printStackTrace();
return null;
}
}
private String getPropertyName(Method f) {
String method = f.getName().replace("get", "").replace("is", "");
String substring = method.substring(0, 1);
method = method.replace(substring, substring.toLowerCase());
String property = f.isAnnotationPresent(Property.class) ? f.getAnnotation(Property.class).value() : method;
if (f.isAnnotationPresent(As.class)) {
property = !f.getAnnotation(As.class).value().equals("[Unassigned]") ? f.getAnnotation(As.class).value() : method;
}
// property = isURI(property) ? method : property;
if (!isURI(property) && !isPrefixed(property) && f.isAnnotationPresent(Prefix.class)) {
String prefix = f.getAnnotation(Prefix.class).value();
if (prefixes.containsKey(prefix)) {
property = prefix + ":" + property;
}
}
return property;
}
private String getPropertyName(Field f) {
String property = f.isAnnotationPresent(Property.class) ? f.getAnnotation(Property.class).value() : f.getName();
if (f.isAnnotationPresent(As.class)) {
property = (!f.getAnnotation(As.class).value().equals("[Unassigned]")) ? f.getAnnotation(As.class).value() : f.getName();
}
// property = isURI(property) ? f.getName() : property;
if (!isURI(property) && !isPrefixed(property) && f.isAnnotationPresent(Prefix.class)) {
String prefix = f.getAnnotation(Prefix.class).value();
if (prefixes.containsKey(prefix)) {
property = prefix + ":" + property;
}
}
return property;
}
private JsonObject accessValue(JsonObject o, JsonElement context, Class<?> type, String property, java.lang.Object val) {
if (type.isArray()) {
Class<?> componentType = type.getComponentType();
java.lang.Object[] values = (java.lang.Object[]) val;
JsonArray list = new JsonArray();
Arrays.stream(values).forEach(v -> {
list.add(getJsonElement(v, componentType, new JsonObject(), context));
});
o.add(property, list);
} else if (String.class.isAssignableFrom(type))
o.addProperty(property, (String) val);
else if (Character.class.isAssignableFrom(type))
o.addProperty(property, (Character) val);
else if (Number.class.isAssignableFrom(type))
o.addProperty(property, val.toString());
else if (int.class.isAssignableFrom(type))
o.addProperty(property, (Integer) val);
else if (float.class.isAssignableFrom(type))
o.addProperty(property, val.toString());
else if (long.class.isAssignableFrom(type))
o.addProperty(property, val.toString());
else if (double.class.isAssignableFrom(type))
o.addProperty(property, val.toString());
else if (Boolean.class.isAssignableFrom(type) || boolean.class.isAssignableFrom(type))
o.addProperty(property, (Boolean) val);
else {
JsonElement jsonElement = getJsonElement(val, val.getClass(), new JsonObject(), context);
o.add(property, jsonElement);
}
return o;
}
private void getFieldsValue(java.lang.Object t, JsonObject o, List<Field> fl, String field_uri, JsonElement context) {
Field f = fl.get(0);
try {
if (String.class.isAssignableFrom(f.getType())) {
o.add(field_uri, getStringValueList(t, fl));
} else if (Character.class.isAssignableFrom(f.getType()))
o.add(field_uri, getCharValueList(t, fl));
else if (Number.class.isAssignableFrom(f.getType()))
o.add(field_uri, getNumValueList(t, fl));
else if (int.class.isAssignableFrom(f.getType()))
o.add(field_uri, getIntValueList(t, fl));
else if (float.class.isAssignableFrom(f.getType()))
o.add(field_uri, getFloatValueList(t, fl));
else if (long.class.isAssignableFrom(f.getType()))
o.add(field_uri, getLongValueList(t, fl));
else if (double.class.isAssignableFrom(f.getType()))
o.add(field_uri, getDoubleValueList(t, fl));
else if (Boolean.class.isAssignableFrom(f.getType()) || boolean.class.isAssignableFrom(f.getType()))
o.add(field_uri, getBooleanValueList(t, fl));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private JsonArray getStringValueList(java.lang.Object t, List<Field> fields) throws IllegalAccessException {
JsonArray list = new JsonArray();
for (Field f : fields) {
list.add((String) f.get(t));
}
return list;
}
private JsonArray getBooleanValueList(java.lang.Object t, List<Field> fields) throws IllegalAccessException {
JsonArray list = new JsonArray();
for (Field f : fields) {
list.add((Boolean) f.get(t));
}
return list;
}
private JsonArray getIntValueList(java.lang.Object t, List<Field> fields) throws IllegalAccessException {
JsonArray list = new JsonArray();
for (Field f : fields) {
list.add((int) f.get(t));
}
return list;
}
private JsonArray getLongValueList(java.lang.Object t, List<Field> fields) throws IllegalAccessException {
JsonArray list = new JsonArray();
for (Field f : fields) {
list.add((long) f.get(t));
}
return list;
}
private JsonArray getFloatValueList(java.lang.Object t, List<Field> fields) throws IllegalAccessException {
JsonArray list = new JsonArray();
for (Field f : fields) {
list.add((float) f.get(t));
}
return list;
}
private JsonArray getDoubleValueList(java.lang.Object t, List<Field> fields) throws IllegalAccessException {
JsonArray list = new JsonArray();
for (Field f : fields) {
list.add((double) f.get(t));
}
return list;
}
private JsonArray getNumValueList(java.lang.Object t, List<Field> fields) throws IllegalAccessException {
JsonArray list = new JsonArray();
for (Field f : fields) {
list.add((Number) f.get(t));
}
return list;
}
private JsonArray getCharValueList(java.lang.Object t, List<Field> fields) throws IllegalAccessException {
JsonArray list = new JsonArray();
for (Field f : fields) {
list.add((Character) f.get(t));
}
return list;
}
private boolean isGetter(Method method) {
if (Modifier.isPublic(method.getModifiers()) &&
method.getParameterTypes().length == 0) {
if (method.getName().matches("^get[A-Z].*") &&
!method.getReturnType().equals(void.class))
return true;
if (method.getName().matches("^is[A-Z].*") &&
method.getReturnType().equals(boolean.class))
return true;
}
return false;
}
}
| true |
d5bdcdedb10985a53726fc92c35e5641df3e5a62
|
Java
|
huberto-88/Amazing_Numbers
|
/Topics/The while and do-while loops/The smallest value/src/Main.java
|
UTF-8
| 437 | 3.359375 | 3 |
[] |
no_license
|
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println(smallestIntNumber(scanner.nextLong()));
scanner.close();
}
private static int smallestIntNumber(long m) {
int n = 1;
long result = 1;
while (result <= m) {
n++;
result *= n;
}
return n;
}
}
| true |
2e0a9db4321048513e5453f9d15d26626758c16d
|
Java
|
zxc81906119/r1
|
/budget/src/main/java/model/roughdollcost.java
|
UTF-8
| 1,086 | 2.34375 | 2 |
[] |
no_license
|
package model;
import java.util.Date;
public class roughdollcost {
private Date thisdate;
private int withdrawmoney;
private int totalcost;
private int alldollindollmachinecount;
private int alldolloutdollmachinecount;
public Date getThisdate() {
return thisdate;
}
public void setThisdate(Date thisdate) {
this.thisdate = thisdate;
}
public int getWithdrawmoney() {
return withdrawmoney;
}
public void setWithdrawmoney(int withdrawmoney) {
this.withdrawmoney = withdrawmoney;
}
public int getTotalcost() {
return totalcost;
}
public void setTotalcost(int totalcost) {
this.totalcost = totalcost;
}
public int getAlldollindollmachinecount() {
return alldollindollmachinecount;
}
public void setAlldollindollmachinecount(int alldollindollmachinecount) {
this.alldollindollmachinecount = alldollindollmachinecount;
}
public int getAlldolloutdollmachinecount() {
return alldolloutdollmachinecount;
}
public void setAlldolloutdollmachinecount(int alldolloutdollmachinecount) {
this.alldolloutdollmachinecount = alldolloutdollmachinecount;
}
}
| true |
fbc086a3185f445defd889e907bea3f76ff22838
|
Java
|
HongkaiWen/harvest
|
/src/main/java/com/github/hongkaiwen/harvest/media/MediaInfoAccessorBuilder.java
|
UTF-8
| 522 | 2.4375 | 2 |
[] |
no_license
|
package com.github.hongkaiwen.harvest.media;
import com.github.hongkaiwen.harvest.util.HarvestFileUtils;
import java.io.File;
/**
* Created by hongkai on 2017/9/27.
*/
public enum MediaInfoAccessorBuilder {
INSTANCE;
public MediaInfoAccessor build(File mediaFile){
String suffix = HarvestFileUtils.getSuffix(mediaFile);
if("jpg".equals(suffix) || "jpeg".equals(suffix)){
return new JpegInfoAccessor(mediaFile);
}
return new VideoInfoAccessor(mediaFile);
}
}
| true |
cedc8594115958cdaaf2e3f17eff73832340b4f0
|
Java
|
walterh/blc-amazon
|
/src/test/java/org/broadleafcommerce/vendor/amazon/s3/S3DefaultRegionTest.java
|
UTF-8
| 1,880 | 2.171875 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* #%L
* BroadleafCommerce Amazon Integrations
* %%
* Copyright (C) 2009 - 2016 Broadleaf Commerce
* %%
* 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.
* #L%
*/
package org.broadleafcommerce.vendor.amazon.s3;
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.Test;
public class S3DefaultRegionTest extends AbstractS3Test {
final String expectedEndpoint = "https://s3-us-west-2.amazonaws.com";
final String westRegion = "us-west-2";
final String defaultV4EndpointUri = "https://s3.amazonaws.com";
@Test
public void regionTest1() throws IOException {
final S3Configuration s3config = new S3Configuration();
s3config.setDefaultBucketRegion(westRegion);
s3config.setEndpointURI(defaultV4EndpointUri);
assertTrue(
String.format("expected endpointURI=%s, found %s instead", expectedEndpoint, s3config.getEndpointURI()),
s3config.getEndpointURI().compareTo(expectedEndpoint) == 0);
}
@Test
public void regionTest2() throws IOException {
// do the other way
final S3Configuration s3config = new S3Configuration();
s3config.setEndpointURI(defaultV4EndpointUri);
s3config.setDefaultBucketRegion(westRegion);
assertTrue(
String.format("expected endpointURI=%s, found %s instead", expectedEndpoint, s3config.getEndpointURI()),
s3config.getEndpointURI().compareTo(expectedEndpoint) == 0);
}
}
| true |
b89227e53d19c878bcf898b6c8c85f9465d10371
|
Java
|
zhanghaichun/ccm
|
/src/com/saninco/ccm/model/bi/.svn/text-base/BIVendor.java.svn-base
|
UTF-8
| 664 | 2.25 | 2 |
[] |
no_license
|
package com.saninco.ccm.model.bi;
import java.util.Set;
/**
* BIVendor entity. @author MyEclipse Persistence Tools
*/
public class BIVendor extends AbstractBIVendor implements java.io.Serializable {
// Constructors
private String labelName;
/** default constructor */
public BIVendor() {
}
/** minimal constructor */
public BIVendor(Integer id) {
super(id);
}
/** full constructor */
public BIVendor(Integer id, String vendorName) {
super(id, vendorName);
}
public String getLabelName() {
return labelName == null ? this.getVendorName() : labelName;
}
public void setLabelName(String labelName) {
this.labelName = labelName;
}
}
| true |
bf14c95a1f0b3dc178fc447324f5ac82ba4f5c8f
|
Java
|
DongXiaLei/Java
|
/src/Offer66/Problem42.java
|
UTF-8
| 671 | 3.125 | 3 |
[] |
no_license
|
package Offer66;
public class Problem42 {
public static void main(String[] args){
System.out.println("Problem 41");
int [] arrays = {1,-2,3,1-0,-4,7,2,-5};
System.out.println(findMaxSubArray(arrays));
}
public static int findMaxSubArray(int [] arrays){
if(arrays==null)return -1;
int curSum = 0;
int maxSum =Integer.MIN_VALUE;
for(int i=0;i<arrays.length;i++){
if(curSum<=0){
curSum = arrays[i];
} else {
curSum += arrays[i];
}
if(maxSum<curSum)
maxSum = curSum ;
}
return maxSum;
}
}
| true |
353c41181e039b3cb0753d8150f07f35d4bb8c4c
|
Java
|
L1021204735/myspringcloud5
|
/myspringcloud-service/src/main/java/com/en/service/IProductClientService.java
|
UTF-8
| 837 | 1.976563 | 2 |
[] |
no_license
|
package com.en.service;
import com.en.feign.FeignClientConfig;
import com.en.po.ProductPo;
import com.en.service.fallback.IProductClientServiceFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@FeignClient(name = "MYSPRINGCLOUD-PROVIDER-PRODUCT",configuration = FeignClientConfig.class,fallbackFactory = IProductClientServiceFallbackFactory.class)
public interface IProductClientService {
@RequestMapping("/product/getInfoById/{id}")
ProductPo getProduct(@PathVariable("id")long id);
@RequestMapping("/product/getAllInfo")
List<ProductPo> listProduct() ;
@RequestMapping("/product/addInfo")
boolean addPorduct(ProductPo productPo) ;
}
| true |
ac808c77013255961e735d1e4f1f3327915753da
|
Java
|
javier-a-agustin/OOP-Java
|
/Aeropuerto/src/aeropuerto/Aeropuerto.java
|
UTF-8
| 1,427 | 3.546875 | 4 |
[] |
no_license
|
package aeropuerto;
import java.util.ArrayList;
/**
* Clase que representa un aeropuerto
* @author Javier Fernandez
* @see Empresa
*/
public class Aeropuerto {
private ArrayList<Empresa> empresas;
/**
* Crea un aeropuerto
*/
public Aeropuerto() {
this.empresas = new ArrayList<Empresa>();
}
/**
* Agrega una empresa a la lista de empresas del aeropuerto
* @param empresa Empresa que se desea agregar
*/
public void agregarEmpresa(Empresa empresa) {
this.empresas.add(empresa);
}
/**
* Devuelve la lista de empresas que posee el aeropuerto
* @return empresas
*/
public ArrayList<Empresa> getEmpresas() {
return this.empresas;
}
/**
* Muestra la informacion del aeropuerto. Mostrando por cada empresa los vuelos asociados
*/
public void infoEmpresas() {
if (this.empresas.isEmpty()) {
// Si no tengo ninguna empresa asociada
System.out.println("Ninguna empresa registrada");
} else {
// Si tengo alguna empresa asociada las muestro
for (Empresa empresa : this.empresas) {
if (empresa.getVuelos().isEmpty()) {
// Si no tengo vuelos asociados a mi empresa
System.out.printf("\n=> Empresa: %s -- sin vuelos registrados\n", empresa.getNombreComercial());
} else {
// Si tengo vuelos asociados los muestro
System.out.printf("\n=> Empresa: %s\n", empresa.getNombreComercial());
empresa.mostrarVuelos();
}
}
}
}
}
| true |
c94b177e6c2564a28ff0f1a20b3d9ddb90d7b78d
|
Java
|
cperceful/dan-things
|
/src/main/java/com/cperceful/models/Danism.java
|
UTF-8
| 924 | 2.703125 | 3 |
[] |
no_license
|
package com.cperceful.models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
* class for storing Danisms in database
*/
@Entity
public class Danism {
@GeneratedValue
@Id
private int id;
@NotNull
@Size(min = 3)
private String title;
@NotNull
@Size(min = 3)
private String body;
public Danism(){
}
public Danism(String title, String body){
this.title = title;
this.body = body;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
| true |
ee3d39f117babca588edb9262108649430150ca3
|
Java
|
afonsocrg/portfolio
|
/schoolManager/sth-app/src/sth/app/student/DoShowSurveyResults.java
|
UTF-8
| 1,646 | 2.578125 | 3 |
[] |
no_license
|
package sth.app.student;
import pt.tecnico.po.ui.Command;
import pt.tecnico.po.ui.DialogException;
import pt.tecnico.po.ui.Input;
import sth.SchoolManager;
import sth.app.exceptions.NoSuchDisciplineException;
import sth.exceptions.InvalidDisciplineException;
import sth.exceptions.InvalidOperationException;
import sth.app.exceptions.NoSuchProjectException;
import sth.app.exceptions.NoSurveyException;
import sth.exceptions.InvalidProjectException;
import sth.exceptions.InvalidSurveyException;
/**
* 4.4.3. Show survey results.
*/
public class DoShowSurveyResults extends Command<SchoolManager> {
Input<String> _disciplineName;
Input<String> _projectName;
/**
* @param receiver
*/
public DoShowSurveyResults(SchoolManager receiver) {
super(Label.SHOW_SURVEY_RESULTS, receiver);
_disciplineName = _form.addStringInput(Message.requestDisciplineName());
_projectName = _form.addStringInput(Message.requestProjectName());
}
/** @see pt.tecnico.po.ui.Command#execute() */
@Override
public final void execute() throws DialogException {
_form.parse();
try{
_display.popup(_receiver.showSurveyResults(_disciplineName.value(), _projectName.value()));
} catch (InvalidDisciplineException e){
throw new NoSuchDisciplineException(_disciplineName.value());
} catch (InvalidProjectException e){
throw new NoSuchProjectException(_disciplineName.value(), _projectName.value());
} catch (InvalidSurveyException e){
throw new NoSurveyException(_disciplineName.value(), _projectName.value());
} catch (InvalidOperationException e){
e.printStackTrace();
}
}
}
| true |
b15fdd06576c8ff7aa96e18731b9de8b7c85fdd7
|
Java
|
dhautsch/etc
|
/java/SortListOfStrings.java
|
UTF-8
| 920 | 3.390625 | 3 |
[] |
no_license
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class SortListOfStrings {
public static void main(String[] args) {
ArrayList<String> words_ = new ArrayList<String>(50);
words_.add("once");
words_.add("upon");
words_.add("a");
words_.add("time");
Collections.sort(words_);
for (String s_ : words_) {
System.out.println(s_);
}
Map<String,String> countryNames_ = new HashMap<String,String>(50);
countryNames_.put("GB", "Great Britain");
countryNames_.put("FR", "France");
countryNames_.put("IT", "Italy");
countryNames_.put("FW", "Far Far Away");
Map<String, String> sortedCountryNames_ = new TreeMap<String, String>(countryNames_);
for (String s_ : sortedCountryNames_.keySet()) {
System.out.println(s_ + " -> " + sortedCountryNames_.get(s_));
}
}
}
| true |
3e26ffa91a78f9c9470ec048d8319fe4ddef22c5
|
Java
|
mikastamm/sound-mixer-android
|
/redone-project/app/src/main/java/mikastamm/com/soundmixer/Networking/ServerConnection.java
|
UTF-8
| 262 | 2.046875 | 2 |
[] |
no_license
|
package mikastamm.com.soundmixer.Networking;
import java.io.IOException;
import mikastamm.com.soundmixer.Datamodel.Server;
/**
* Created by Mika on 28.03.2018.
*/
public interface ServerConnection extends Connection{
Server getServer();
}
| true |
59b55b81f470201a810a0f3253946ed895d7faa6
|
Java
|
VSPotdukhe/SpringMavenProject
|
/SpringMavenWebApp/FashionKing/src/main/java/com/ecomm/dao/CartDAOImpl.java
|
UTF-8
| 1,678 | 2.625 | 3 |
[] |
no_license
|
package com.ecomm.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.ecomm.model.Cart;
@Repository("cartDAO")
@Transactional
public class CartDAOImpl implements CartDAO
{
@Autowired
SessionFactory sessionFactory;
@Override
public boolean addCart(Cart cart)
{
try
{
sessionFactory.getCurrentSession().save(cart);
System.out.println("CartAdded");
return true;
}
catch(Exception e)
{
System.out.println("Exception Arised:"+e);
return false;
}
}
@Override
public boolean deleteCart(Cart cart) {
try
{
sessionFactory.getCurrentSession().delete(cart);
System.out.println("MySQL updated after deleting cart");
return true;
}
catch(Exception e)
{
System.out.println("Exception Arised:"+e);
return false;
}
}
@Override
public boolean updateCart(Cart cart) {
try
{
sessionFactory.getCurrentSession().update(cart);
System.out.println("Cart Updated");
return true;
}
catch(Exception e)
{
System.out.println("Exception Arised:"+e);
return false;
}
}
@Override
public Cart getCart(int cartId)
{
Session session=sessionFactory.openSession();
Cart cart=(Cart)session.get(Cart.class, cartId);
session.close();
return cart;
}
@Override
public List<Cart> retrieveCarts()
{
Session session=sessionFactory.openSession();
List<Cart> cartList=(List<Cart>)session.createQuery("from Cart").list();
session.close();
return cartList;
}
}
| true |
54886e8f3fffae4d1bc5f6ccde51e8ee1b4b773f
|
Java
|
chinatip/Snake-and-Ladder
|
/app/src/main/java/com/ske/snakebaddesign/models/Player.java
|
UTF-8
| 632 | 3.296875 | 3 |
[] |
no_license
|
package com.ske.snakebaddesign.models;
public class Player {
private static int NUMBER = 1;
private int number;
private Piece piece;
public Player(int color){
this.number = NUMBER;
piece = new Piece(color);
NUMBER++;
}
public int getNumber() {
return number;
}
public int getPosition(){
return piece.getPosition();
}
public void setPosition(int position) {
piece.setPosition(position);
}
public Piece getPiece() {
return piece;
}
public void reset(){
piece.reset();
}
}
| true |
091f2907b315218ba71da284984130c7c1e4c505
|
Java
|
solaris0403/Teardroid
|
/teardroid/src/main/java/com/tony/teardroid/common/util/PatchUtils.java
|
UTF-8
| 407 | 1.898438 | 2 |
[] |
no_license
|
package com.tony.teardroid.common.util;
import com.tony.teardroid.common.entity.PatchResult;
/**
* PatchUtils
*/
public class PatchUtils {
/**
* patch old apk and patch file to new apk
*
* @param oldApkPath
* @param patchPath
* @param newApkPath
* @return
*/
public static native PatchResult patch(String oldApkPath, String patchPath, String newApkPath);
}
| true |
2705081bc5dca9dea1df0ba840284a18e9b59120
|
Java
|
hittepit/conditions-exemple
|
/src/main/java/toImplement/condition/simple/HeuresNuitCondition.java
|
UTF-8
| 251 | 2.21875 | 2 |
[] |
no_license
|
package toImplement.condition.simple;
import existing.entity.Prestation;
public class HeuresNuitCondition extends SimplePrestationCondition {
@Override
public boolean check(Prestation prestation) {
return prestation.getHeuresNuit() != 0;
}
}
| true |
8069d87935c2f00724ff8b1ab1e5167a7ace1305
|
Java
|
bellmit/ibizlab-runtime
|
/ibzrt/ibzrt-core/src/main/java/cn/ibizlab/core/workflow/service/impl/WFUserServiceImpl.java
|
UTF-8
| 3,935 | 1.851563 | 2 |
[
"Apache-2.0"
] |
permissive
|
package cn.ibizlab.core.workflow.service.impl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Collection;
import java.util.Objects;
import java.util.Optional;
import java.math.BigInteger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import cn.ibizlab.util.errors.BadRequestAlertException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Lazy;
import cn.ibizlab.core.workflow.domain.WFUser;
import cn.ibizlab.core.workflow.filter.WFUserSearchContext;
import cn.ibizlab.core.workflow.service.IWFUserService;
import cn.ibizlab.util.helper.CachedBeanCopier;
import cn.ibizlab.util.helper.DEFieldCacheMap;
import cn.ibizlab.core.workflow.client.WFUserFeignClient;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* 实体[用户] 服务对象接口实现
*/
@Slf4j
@Service
public class WFUserServiceImpl implements IWFUserService {
@Autowired
WFUserFeignClient wFUserFeignClient;
@Override
public boolean create(WFUser et) {
WFUser rt = wFUserFeignClient.create(et);
if(rt==null)
return false;
CachedBeanCopier.copy(rt, et);
return true;
}
public void createBatch(List<WFUser> list){
wFUserFeignClient.createBatch(list) ;
}
@Override
public boolean update(WFUser et) {
WFUser rt = wFUserFeignClient.update(et.getId(),et);
if(rt==null)
return false;
CachedBeanCopier.copy(rt, et);
return true;
}
public void updateBatch(List<WFUser> list){
wFUserFeignClient.updateBatch(list) ;
}
@Override
public boolean remove(String id) {
boolean result=wFUserFeignClient.remove(id) ;
return result;
}
public void removeBatch(Collection<String> idList){
wFUserFeignClient.removeBatch(idList);
}
@Override
public WFUser get(String id) {
WFUser et=wFUserFeignClient.get(id);
if(et==null){
throw new BadRequestAlertException("数据不存在", this.getClass().getSimpleName(), id);
}
else{
}
return et;
}
@Override
public WFUser getDraft(WFUser et) {
et=wFUserFeignClient.getDraft(et);
return et;
}
@Override
public boolean checkKey(WFUser et) {
return wFUserFeignClient.checkKey(et);
}
@Override
@Transactional
public boolean save(WFUser et) {
boolean result = true;
Object rt = wFUserFeignClient.saveEntity(et);
if(rt == null)
return false;
try {
if (rt instanceof Map) {
ObjectMapper mapper = new ObjectMapper();
rt = mapper.readValue(mapper.writeValueAsString(rt), WFUser.class);
if (rt != null) {
CachedBeanCopier.copy(rt, et);
}
} else if (rt instanceof Boolean) {
result = (boolean) rt;
}
} catch (Exception e) {
}
return result;
}
@Override
public void saveBatch(List<WFUser> list) {
wFUserFeignClient.saveBatch(list) ;
}
/**
* 查询集合 DEFAULT
*/
@Override
public Page<WFUser> searchDefault(WFUserSearchContext context) {
Page<WFUser> wFUsers=wFUserFeignClient.searchDefault(context);
return wFUsers;
}
}
| true |
dbbc074b6bd45807f09ff25f9ba4e62c6bef0e7e
|
Java
|
metodi123/SOSM_web_app
|
/SOSM/src/main/java/sosm/web/app/service/InfoTextValidationService.java
|
UTF-8
| 440 | 2.28125 | 2 |
[] |
no_license
|
package sosm.web.app.service;
import org.springframework.stereotype.Service;
import sosm.web.app.exception.InvalidInfoTextException;
@Service
public class InfoTextValidationService {
public static final int MAX_LENGTH = 1000;
public void validateInfoText(String infoText) throws InvalidInfoTextException {
if(infoText.length() > MAX_LENGTH) {
throw new InvalidInfoTextException("Parameter value out of range");
}
}
}
| true |
d124c8761a55351d8adfa09fa009a23e4da3ade2
|
Java
|
kunalkalbande/SQLDM
|
/Development/Web UI/zk-web/src/com/idera/sqldm/ui/components/charts/bar/IderaStackedBarChart.java
|
UTF-8
| 2,922 | 2.34375 | 2 |
[] |
no_license
|
package com.idera.sqldm.ui.components.charts.bar;
import com.idera.i18n.I18NStrings;
import com.idera.server.web.ELFunctions;
import com.idera.sqldm.ui.components.charts.IderaChart;
import com.idera.sqldm.ui.components.charts.IderaChartModel;
import com.idera.sqldm.d3zk.chart.BarChart;
import com.idera.sqldm.d3zk.chart.StackedBarChart;
import org.apache.log4j.Logger;
import java.util.*;
import java.util.Map.Entry;
public class IderaStackedBarChart extends IderaChart {
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(IderaStackedBarChart.class);
private static final int DEFAULT_BAR_HEIGHT = 25;
private Map<String, Map<String,Number>> chartData;
public IderaStackedBarChart() {
super("~./sqldm/com/idera/sqldm/ui/components/stackedBarChart.zul");
}
@Override
@SuppressWarnings("unchecked")
public StackedBarChart<Number> getChart() {
return (StackedBarChart<Number>) super.getChart();
}
@Override
public IderaChartModel getModel() {
throw new UnsupportedOperationException("Method not supported by IderaStackedBarChart");
}
public Map<String, Map<String,Number>> getChartData() {
return this.chartData;
}
public void setOrient(String orient) {
getChart().setOrient(orient);
}
public void setChartData(Map<String, Map<String,Number>> chartData) {
if (!(chartData instanceof TreeMap<?, ?>)) {
this.chartData = chartData;
} else {
this.chartData = chartData;
}
updateChart();
}
@Override
public void updateChart() {
try {
Map<String, Map<String,Number>> filteredChartData = getChartData();
/*for (Entry<String, Double> entry : getChartData().entrySet()) {
if (entry.getKey() != null) {
Double value = entry.getValue() == null ? 0 : entry.getValue();
if (isShowZeroValues() || value > 0) {
filteredChartData.put(entry.getKey(), value);
}
}
}*/
if (!filteredChartData.isEmpty()) {
getChart().setValueFormat(getValueFormat());
// feed the chart data to the D3 bar chart control
getChart().setSeries(filteredChartData);
//Default y-axis tick padding
getChart().setYAxisTickPadding(20);
getChart().setXAxisTickPadding(5);
/* getChart().setXAxisTitle(xAxisTitle);
getChart().setXAxisTickPadding(10);
*/
getErrorLabel().setVisible(false);
getChart().setVisible(true);
super.invalidate();
} else {
showError(noDataMessage);
}
} catch (Exception x) {
log.error(x.getMessage(), x);
showError(ELFunctions.getMessage(I18NStrings.ERROR_OCCURRED_LOADING_CHART));
}
}
private static final Comparator<Entry<String, Number>> doubleComparator = new Comparator<Entry<String, Number>>() {
@Override
public int compare(Entry<String, Number> a, Entry<String, Number> b) {
return ((Double)b.getValue()).compareTo((Double)a.getValue());
}
};
}
| true |
b088363de4f4c782f19bb6aecf408c44eddabc43
|
Java
|
1657486787/mk-project
|
/mk-zookeeper/mk-zk-register/mk-zk-register-order/src/main/java/com/suns/utils/ZkClientUtil.java
|
UTF-8
| 1,848 | 2.34375 | 2 |
[] |
no_license
|
/**
* Project Name:mk-project <br>
* Package Name:com.suns.utils <br>
*
* @author mk <br>
* Date:2018-11-7 9:45 <br>
*/
package com.suns.utils;
import com.suns.constant.ZkConstant;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
/**
* ClassName: ZkClientUtil <br>
* Description: <br>
* @author mk
* @Date 2018-11-7 9:45 <br>
* @version
*/
public class ZkClientUtil {
private static ZkClient zkClient = null;
static String parentPath = ZkConstant.BASE_SERVICES + ZkConstant.SERVICE_NAME;
public static void init(String zookeeperConn) {
zkClient = new ZkClient(zookeeperConn, ZkConstant.CONNECTIONTIMEOUT_DEFAULT);
zkClient.subscribeChildChanges(parentPath, new IZkChildListener() {
@Override
public void handleChildChange(String s, List<String> list) throws Exception {
System.out.println("handleChildChange.....s=" + s + ",list="+list);
updateServiceList();
}
});
}
public static void updateServiceList() {
List<String> childrenList = zkClient.getChildren(parentPath);
if(CollectionUtils.isEmpty(childrenList)){
System.out.println(parentPath+" is no childrenList...over");
return ;
}
List<String> service_list = new ArrayList<>();//产品服务ip+port列表,由于有可能新增也有可能删除,所以这里需要每次都new
for(String node : childrenList){
String nodeValue = zkClient.readData(parentPath + "/" + node);
service_list.add(nodeValue);
}
LoadBalance.service_list = service_list;
System.out.println("获取所有订单服务,"+childrenList);
}
}
| true |
9a0659ec32604685487cf6afb344032b9f97dfc8
|
Java
|
guptadipanshu/CourseDataManagement
|
/src/system/Student.java
|
UTF-8
| 1,727 | 2.765625 | 3 |
[] |
no_license
|
package system;
import database.course.student.CourseStudentDb;
import database.course.student.CourseStudentDbImpl;
import interfaces.Enrollment;
import java.util.List;
/**
* Student class to keep track for information about a student
* @author dipanshugupta
*
*/
public class Student extends Person{
private final CourseStudentDb courseDb;
public Student(final String id, final String name, final String address, final String number){
super(id,name,address,number);
this.courseDb = new CourseStudentDbImpl();
}
/**
* gets the unique id associated with a student
* @return the UDID associated with a student
*/
public String getID() {
return super.getID();
}
/**
* Get the name of the student
* @return the name of the student
*/
public String getName(){
return super.getName();
}
public void addCourseCompleted(String courseID, String grade,String semester, String year,String enrollmentStatus){
courseDb.addCourseGrade(getID(),courseID,grade,semester,year,enrollmentStatus);
}
public List<CourseStudentDbImpl.Record> getRecordAllTerms(){
return courseDb.getRecordAllTerms(getID());
}
public List<CourseStudentDbImpl.Record> getRecordByTerm(String semester, String year){
return courseDb.getGradesByTerm(getID(),semester,year);
}
public List<CourseStudentDbImpl.Record> getCompletedCourse() {
return courseDb.getCompletedCourse(getID());
}
public List<CourseStudentDbImpl.Record> getCompletedCourseByTerm(List<Course.Term> terms) {
return courseDb.getCompletedCourseByTerm(getID(),terms);
}
public List<Course> getWaitListedCourse(String semester, String year) {
return courseDb.getWaitListedCourse(semester,year, Enrollment.NO_SEATS.getValue());
}
}
| true |
dc20e682da06e85184910d9d36a2a3cce31db12a
|
Java
|
Institute-of-Marine-Research-NMD/nmdapi-loader
|
/src/main/java/no/imr/nmdapi/client/loader/dao/Datatypes.java
|
UTF-8
| 893 | 2.109375 | 2 |
[] |
no_license
|
package no.imr.nmdapi.client.loader.dao;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
/**
*
* @author Terry Hannant <a5119>
*/
public class Datatypes {
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public int countBiotic(String missionID)
{
return jdbcTemplate.queryForObject("select count(*) from"
+ " nmdbiotic.fishstation where id_m_mission = ?", Integer.class,missionID);
}
public int countEchoSounder(String missionID)
{
return jdbcTemplate.queryForObject("select count(*) from"
+ " nmdechosounder.echosounder_dataset where id_m_mission = ?", Integer.class,missionID);
}
}
| true |
9f09be731e48cfed7527b6f9d5f8b9e8137d6384
|
Java
|
RafasTavares/VisualNRP
|
/src/main/java/sobol/problems/requirements/hc/VisualizationMainProgram.java
|
UTF-8
| 3,528 | 2.515625 | 3 |
[] |
no_license
|
package sobol.problems.requirements.hc;
import sobol.base.random.RandomGeneratorFactory;
import sobol.base.random.pseudo.PseudoRandomGeneratorFactory;
import sobol.problems.requirements.model.Project;
import sobol.problems.requirements.reader.RequirementReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
public class VisualizationMainProgram
{
private static int CICLOS = 1;
private static String[] instanceFilenamesClassic =
{
// "data/requirements/padilha_1req_30cust.txt",
// "data/requirements/padilha_3req_30cust.txt",
// "data/requirements/padilha_5req_30cust.txt",
// "data/requirements/padilha_1req_50cust.txt",
// "data/requirements/padilha_3req_50cust.txt",
// "data/requirements/padilha_5req_50cust.txt",
// "data/requirements/padilha_1req_100cust.txt",
// "data/requirements/padilha_3req_100cust.txt",
// "data/requirements/padilha_5req_100cust.txt",
"data/requirements/classic/nrp1.txt",
"data/requirements/classic/nrp2.txt",
"data/requirements/classic/nrp3.txt",
"data/requirements/classic/nrp4.txt",
"data/requirements/classic/nrp5.txt",
""
};
private static String[] instanceFilenamesRealistic =
{
/*"data/requirements/realistic/nrp-e1.txt",
"data/requirements/realistic/nrp-e2.txt",
"data/requirements/realistic/nrp-e3.txt",
"data/requirements/realistic/nrp-e4.txt",
"data/requirements/realistic/nrp-g1.txt",
"data/requirements/realistic/nrp-g2.txt",
"data/requirements/realistic/nrp-g3.txt",
"data/requirements/realistic/nrp-g4.txt",
"data/requirements/realistic/nrp-m1.txt",
"data/requirements/realistic/nrp-m2.txt",
"data/requirements/realistic/nrp-m3.txt",
"data/requirements/realistic/nrp-m4.txt",*/
""
};
private List<Project> readInstances(String[] filenames) throws Exception
{
List<Project> instances = new ArrayList<Project>();
for (String filename : filenames)
if (filename.length() > 0)
{
RequirementReader reader = new RequirementReader(filename);
Project project = reader.execute();
instances.add (project);
}
return instances;
}
private void runInstance(PrintWriter out, PrintWriter details, String tipo, Project instance, int cycles, double budgetFactor) throws Exception
{
for (int i = 0; i < cycles; i++)
{
int budget = (int)(budgetFactor * instance.getTotalCost());
Visualization hcr = new Visualization(details, instance, budget, 100);
details.println(tipo + " " + instance.getName() + " #" + cycles);
boolean[] solution = hcr.execute();
details.println();
}
}
public static final void main(String[] args) throws Exception
{
VisualizationMainProgram mp = new VisualizationMainProgram();
Vector<Project> instances = new Vector<Project>();
instances.addAll(mp.readInstances(instanceFilenamesClassic));
instances.addAll(mp.readInstances(instanceFilenamesRealistic));
FileWriter outFile = new FileWriter("saida.txt");
PrintWriter out = new PrintWriter(outFile);
FileWriter detailsFile = new FileWriter("saida details.txt");
PrintWriter details = new PrintWriter(detailsFile);
for (Project instance : instances)
{
RandomGeneratorFactory.setRandomFactoryForPopulation(new PseudoRandomGeneratorFactory());
mp.runInstance(out, details, "PSEUDO", instance, CICLOS, 0.7);
}
out.close();
details.close();
}
}
| true |
259491fdcf60fc15fb9cd29d39cdf1a597af6caf
|
Java
|
Lakemonsters2635/FRC2021
|
/src/main/java/frc/robot/commands/AutonomousDriveCommand.java
|
UTF-8
| 2,438 | 2.640625 | 3 |
[] |
no_license
|
package frc.robot.commands;
import edu.wpi.first.wpilibj.command.Command;
import frc.robot.Robot;
import java.util.ArrayList;
import org.frcteam2910.common.math.Vector2;
import org.frcteam2910.common.util.HolonomicDriveSignal;
/**
*
*/
public class AutonomousDriveCommand extends Command {
ArrayList<HolonomicDriveSignal> driveSequence;
int index;
public AutonomousDriveCommand(ArrayList<HolonomicDriveSignal> driveSequence, double timeout) {
super(timeout);
requires(Robot.drivetrainSubsystem);
this.driveSequence = driveSequence;
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
}
// Called just before this Command runs the first time
protected void initialize() {
Robot.drivetrainSubsystem.getGyroscope().setAdjustmentAngle(Robot.drivetrainSubsystem.getGyroscope().getUnadjustedAngle());
Vector2 position = new Vector2(0, 0);
Robot.drivetrainSubsystem.resetKinematics(position, 0);
index = 0;
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
//Robot.drivetrainSubsystem.setTargetVelocity(velocity);
if (index < driveSequence.size()) {
Vector2 translation = driveSequence.get(index).getTranslation();
Double rotation = driveSequence.get(index).getRotation();
Robot.drivetrainSubsystem.holonomicDrive(translation, rotation, true);
index++;
} else {
Robot.drivetrainSubsystem.holonomicDrive(Vector2.ZERO, 0, true);
}
}
// Called once after timeout
protected void end() {
Robot.drivetrainSubsystem.holonomicDrive(Vector2.ZERO, 0.0, true);
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
Robot.drivetrainSubsystem.holonomicDrive(Vector2.ZERO, 0.0, true);
}
@Override protected boolean isFinished() {
boolean isFinished = (index >= driveSequence.size());
if(isFinished) {
System.out.println("Drive Straight Finished.");
System.out.println("-----------");
}
if(isTimedOut()){
System.out.println("Timed Out");
isFinished = true;
}
return isFinished;
}
}
| true |
0a50aff183bdb25f8b90275095462ee3eafa6e53
|
Java
|
agotanemes/SerenityProject-Continuation
|
/src/main/java/com/firestarters/steps/MainPageSteps.java
|
UTF-8
| 354 | 1.765625 | 2 |
[] |
no_license
|
package com.firestarters.steps;
import com.firestarters.page.MainPage;
import net.thucydides.core.annotations.Step;
public class MainPageSteps {
MainPage homepagePage;
@Step
public void clickOnSaleSection() {
homepagePage.clickOnSaleHeaderOption();
}
@Step
public void clickOnMenSection() {
homepagePage.clickOnMenHeaderOption();
}
}
| true |
6110b68a58fa6c6283a33f8b28a765889e6f843a
|
Java
|
eduardo19Fu/ProyectoStd
|
/src/prstd/modelos/Rol.java
|
UTF-8
| 1,588 | 2.78125 | 3 |
[] |
no_license
|
package prstd.modelos;
import java.util.ArrayList;
import java.util.List;
import prstd.controladores.CRol;
/**
*
* @author Edfu-Pro
*/
public class Rol {
private int idrol;
private String rol;
private String descripcion;
private String estado;
public Rol(){
}
public Rol(int idrol, String rol, String estado) {
this.idrol = idrol;
this.rol = rol;
this.estado = estado;
}
public int getIdrol() {
return idrol;
}
public void setIdrol(int idrol) {
this.idrol = idrol;
}
public String getRol() {
return rol;
}
public void setRol(String rol) {
this.rol = rol;
}
public String getDescripcion(){
return descripcion;
}
public void setDescripcion(String descripcion){
this.descripcion = descripcion;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
/*
* Métodos controlador de la Clase Rol.
*/
public List<Rol> consultar(){
CRol rols = new CRol();
List<Rol> lista = new ArrayList<>();
lista = rols.consultar();
return lista;
}
public int consultar(String rol){
CRol cr = new CRol();
return cr.consultar(rol);
}
public int crear(Rol rol){
CRol cr = new CRol();
return cr.crear(rol);
}
public String consultar(int id){
CRol cr = new CRol();
return cr.consultar(id);
}
}
| true |
6766d691ad5d7b1e4fec06f2072d1101b12abb21
|
Java
|
davidalonsobadia/security_awareness
|
/src/main/java/org/security_awareness/model/projections/ActivityStatusesExpanded.java
|
UTF-8
| 659 | 1.8125 | 2 |
[] |
no_license
|
package org.security_awareness.model.projections;
import org.security_awareness.model.Activity;
import org.security_awareness.model.ActivityStatus;
import org.security_awareness.model.User;
import org.security_awareness.model.Zone;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.rest.core.config.Projection;
@Projection(name="expanded", types={ActivityStatus.class})
public interface ActivityStatusesExpanded {
long getId();
boolean getInterested();
boolean getAssistant();
Activity getActivity();
User getUser();
@Value("#{target.getActivity().getZone()}")
Zone getZone();
}
| true |
14b78214151165b0f46dd55d70203ce0d884658f
|
Java
|
wrbbz/Verification
|
/Lab1/report/listings/recursive.java
|
UTF-8
| 514 | 2.625 | 3 |
[] |
no_license
|
private List<ASTEntry> getMethodBlocks(List<ASTEntry> trees){
List<ASTEntry> methodsList = new ArrayList<>();
for(ASTEntry tree : trees){
if(!tree.nodeName.contains(METHOD_TOKEN))
methodsList.addAll(getMethodBlocks(tree.children));
else {
for(ASTEntry node : tree.children)
if(node.nodeName.contains(CODEBLOCK_TOKEN)) {
methodsList.add(node);
break;
}
}
}
return methodsList;
}
| true |
aec7fecd825a3238bc09e9e0c87aed2e9cd35722
|
Java
|
bmariesan/iStudent
|
/src/main/java/ro/ubb/samples/structural/decorator/window/Window.java
|
UTF-8
| 122 | 2.234375 | 2 |
[
"MIT"
] |
permissive
|
package ro.ubb.samples.structural.decorator.window;
interface Window {
void draw();
String getDescription();
}
| true |
e61361f2a8fc116eeaf2c74b38148e157bddb23a
|
Java
|
huangjixin/zhiwo-mall
|
/fushenlan-java/FWD-api-webservice/src/main/java/com/fulan/api/agent/vo/CustomerSearchParm.java
|
UTF-8
| 1,729 | 1.976563 | 2 |
[] |
no_license
|
/**
* Project Name:FWD-api-webservice
* File Name:CustomerSearchParm.java
* Package Name:com.fulan.api.agent.vo
* Date:2018年4月9日上午9:39:47
* Copyright (c) 上海复深蓝软件股份有限公司.
*
*/
package com.fulan.api.agent.vo;
import java.io.Serializable;
/**
* ClassName:CustomerSearchParm Reason: TODO ADD REASON Date: 2018年4月9日
* 上午9:39:47
*
* @author chen.zhuang
* @version
* @since JDK 1.8
*/
public class CustomerSearchParm implements Serializable{
private static final long serialVersionUID = 1L;
private String dob;
private String gender;
private String idNumber;
private String idType;
private String mobileNumber;
private String name;
private String status;
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getIdNumber() {
return idNumber;
}
public void setIdNumber(String idNumber) {
this.idNumber = idNumber;
}
public String getIdType() {
return idType;
}
public void setIdType(String idType) {
this.idType = idType;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
| true |
1b22ce820bacb0b3a9825fd6e3a66475b146b2df
|
Java
|
lfkimura/paguemob
|
/src/main/java/br/com/paguemob/kimura/interview/service/impl/CompanyServiceImpl.java
|
UTF-8
| 1,916 | 2.234375 | 2 |
[] |
no_license
|
package br.com.paguemob.kimura.interview.service.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import br.com.paguemob.kimura.interview.enums.IndustryType;
import br.com.paguemob.kimura.interview.filters.Filter;
import br.com.paguemob.kimura.interview.model.Company;
import br.com.paguemob.kimura.interview.repository.CompanyRepository;
import br.com.paguemob.kimura.interview.service.CompanyService;
import br.com.paguemob.kimura.interview.vo.CompanyVO;
@Service
public class CompanyServiceImpl implements CompanyService {
@Autowired
private CompanyRepository companyRepository;
@Override
public List<CompanyVO> getCompanies(List<Filter<String>> filters) {
return (List<CompanyVO>) companyRepository.findCompaniesWithFilters(filters).stream()
.map(company -> new CompanyVO(company)).collect(Collectors.toList());
}
@Override
public CompanyVO createCompany(CompanyVO company) {
return new CompanyVO(companyRepository.save(new Company(company)));
}
@Override
public CompanyVO getCompany(String id) {
Company company;
CompanyVO companyVO = (company = companyRepository.findOne(Long.valueOf(id))) != null ? new CompanyVO(company)
: null;
return companyVO;
}
@Override
public List<IndustryType> geIndustries() {
return new ArrayList<IndustryType>(Arrays.asList(IndustryType.values()));
}
@Override
public List<CompanyVO> getCompanies(List<Filter<String>> filters, Pageable pageRequest) {
return ((List<Company>) companyRepository.findCompaniesWithFilters(filters, pageRequest).getContent()).stream()
.map(company -> new CompanyVO(company)).collect(Collectors.toList());
}
}
| true |
1565cb7f77109a955052e1f9a46951f7fefe0a39
|
Java
|
ivanovg94/Luck-Test-Android-App
|
/LuckTest/app/src/main/java/com/example/lucktest/Main.java
|
UTF-8
| 2,545 | 2.28125 | 2 |
[] |
no_license
|
package com.example.lucktest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import java.util.Random;
public class Main extends AppCompatActivity {
int diff = 0;
String difficulty="";
SharedPreferences preferences;
Button lastTestBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = getSharedPreferences("data", Context.MODE_PRIVATE);
lastTestBtn = (Button) findViewById(R.id.lastTestBtn);
String value = preferences.getString("Result",null);
if (value == null) {
lastTestBtn.setVisibility(View.INVISIBLE);
} else {
lastTestBtn.setVisibility(View.VISIBLE);
}
diff=30;
difficulty="Easy";
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked() ;
// Check which radio button was clicked
switch(view.getId()) {
case R.id.opt1:
if (checked)
diff=30;
difficulty="Easy";
break;
case R.id.opt2:
if (checked)
diff=20;
difficulty="Medium";
break;
case R.id.opt3:
if (checked)
diff=10;
difficulty="Hard";
break;
}
}
public void startTest(View view) {
lastTestBtn = (Button) findViewById(R.id.lastTestBtn);
lastTestBtn.setVisibility(View.INVISIBLE);
preferences = getSharedPreferences("data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.apply();
Random rand = new Random();
int startOfRange = rand.nextInt(100-diff);
editor.putInt("StartOfRange",startOfRange);
editor.putInt("Difference",diff);
editor.putString("Difficulty",difficulty);
editor.apply();
Intent intent = new Intent(this, Test.class);
startActivity(intent);
}
public void GoToResults(View view) {
Intent intent = new Intent(this, Details.class);
startActivity(intent);
}
}
| true |
7e3cbef205521086f7f4c99a626e9a0ed6719bdd
|
Java
|
as184511/cmfz
|
/src/main/java/com/baizhi/controller/UserController.java
|
UTF-8
| 2,249 | 1.84375 | 2 |
[] |
no_license
|
package com.baizhi.controller;
import com.alibaba.fastjson.JSONObject;
import com.baizhi.entity.User;
import com.baizhi.service.UserService;
import io.goeasy.GoEasy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Map;
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
UserService userService;
@RequestMapping("selectAll")
@ResponseBody
public Map selectAll(int page, int rows) {
Map map = userService.selectAll(page, rows);
return map;
}
@RequestMapping("register")
@ResponseBody
public Map register(String phone, String password) {
Map register = userService.insert(phone, password);
Map map = userService.userAmount();
return register;
}
@RequestMapping("login")
@ResponseBody
public Map login(String phone, String password) {
Map map = userService.login(phone, password);
return map;
}
@RequestMapping("insert")
@ResponseBody
public void insert(User user) {
userService.insert2(user);
Map map = userService.userAmount();
String s = JSONObject.toJSONString(map);
GoEasy goEasy = new GoEasy("http://rest-hangzhou.goeasy.io", "BC-07858a5c21ad4fefaa551ffab72e40bb");
goEasy.publish("cmfz", "s");
}
@RequestMapping("updateStatus")
@ResponseBody
public void updateStatus(User user) {
userService.updateStatus(user);
}
@RequestMapping("userAmount")
@ResponseBody
public Map userAmount() {
Map map = userService.userAmount();
return map;
}
@RequestMapping("userScatter")
@ResponseBody
public Map userScatter(int sex) {
Map map = userService.userScatter(sex);
return map;
}
//服务端发送消息
@RequestMapping("goEasySend")
@ResponseBody
public void send() {
GoEasy goEasy = new GoEasy("http://rest-hangzhou.goeasy.io", "BC-07858a5c21ad4fefaa551ffab72e40bb");
goEasy.publish("cmfz", "Hello, GoEasy!");
}
}
| true |
c3a3da3fca30a10d49de0932e653589cb0355417
|
Java
|
solehfuddin/PenghitungHari
|
/src/Utama.java
|
UTF-8
| 17,702 | 2.203125 | 2 |
[] |
no_license
|
import javax.swing.JOptionPane;
/*
* 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.
*/
/**
*
* @author sholeh
*/
public class Utama extends javax.swing.JFrame {
/**
* Creates new form Utama
*/
public Utama() {
initComponents();
}
/**
* 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() {
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
txt_tahun = new javax.swing.JTextField();
txt_bulan = new javax.swing.JTextField();
jPanel3 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
lbl_hari = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
btn_hitung = new javax.swing.JButton();
btn_hapus = new javax.swing.JButton();
btn_simpan = new javax.swing.JButton();
btn_keluar = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(""), "Aplikasi Penentu Jumlah Hari", 0, 0, new java.awt.Font("Segoe UI", 1, 12))); // NOI18N
jPanel1.setToolTipText("");
jPanel2.setBackground(new java.awt.Color(204, 255, 204));
jLabel3.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N
jLabel3.setText("Tahun");
jLabel4.setText("Bulan");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addGap(29, 29, 29)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txt_tahun)
.addComponent(txt_bulan))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txt_tahun, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(txt_bulan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(18, Short.MAX_VALUE))
);
jPanel3.setBackground(new java.awt.Color(255, 255, 204));
jLabel5.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
jLabel5.setText("Jumlah hari adalah");
lbl_hari.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
lbl_hari.setText("0");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lbl_hari)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(lbl_hari))
.addContainerGap(19, Short.MAX_VALUE))
);
jPanel4.setBackground(new java.awt.Color(255, 204, 204));
btn_hitung.setText("Hitung");
btn_hitung.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_hitungActionPerformed(evt);
}
});
btn_hapus.setText("Hapus");
btn_hapus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_hapusActionPerformed(evt);
}
});
btn_simpan.setText("Simpan");
btn_keluar.setText("Keluar");
btn_keluar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_keluarActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(btn_hitung)
.addGap(36, 36, 36)
.addComponent(btn_hapus)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 41, Short.MAX_VALUE)
.addComponent(btn_simpan)
.addGap(37, 37, 37)
.addComponent(btn_keluar)
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addContainerGap(23, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn_hitung)
.addComponent(btn_hapus)
.addComponent(btn_simpan)
.addComponent(btn_keluar))
.addContainerGap())
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jLabel1.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
jLabel1.setText("Nugraha Indra");
jLabel2.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N
jLabel2.setText("41516120092");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
setSize(new java.awt.Dimension(454, 372));
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void btn_keluarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_keluarActionPerformed
// TODO add your handling code here:
dispose();
}//GEN-LAST:event_btn_keluarActionPerformed
private void btn_hitungActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_hitungActionPerformed
// TODO add your handling code here:
int jmlHari = 0;
boolean isThn = false;
String bul, thn;
bul = txt_bulan.getText();
thn = txt_tahun.getText();
if (thn.isEmpty())
{
JOptionPane.showMessageDialog(this, "Tahun wajib diisi");
isThn = false;
}
else
{
if (isNumeric(thn))
{
int cekThn = Integer.parseInt(thn);
if (cekThn <= 2050)
{
isThn = true;
}
else
{
JOptionPane.showMessageDialog(this, "Tahun maksimal hingga 2050");
}
}
else
{
JOptionPane.showMessageDialog(this, "Masukkan tahun dengan angka");
isThn = false;
}
}
if (bul.isEmpty())
{
JOptionPane.showMessageDialog(this, "Bulan wajib diisi");
}
else
{
if (isNumeric(bul))
{
int bln = Integer.parseInt(bul);
if (bln <= 12)
{
if (isThn)
{
jmlHari = getHari(bln, Integer.parseInt(thn));
lbl_hari.setText(String.valueOf(jmlHari));
}
}
else
{
JOptionPane.showMessageDialog(this, "Bulan maksimal 12");
}
}
else
{
JOptionPane.showMessageDialog(this, "Masukkan bulan dengan angka");
}
}
}//GEN-LAST:event_btn_hitungActionPerformed
private void btn_hapusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_hapusActionPerformed
// TODO add your handling code here:
clear();
}//GEN-LAST:event_btn_hapusActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Utama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Utama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Utama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Utama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Utama().setVisible(true);
}
});
}
private boolean isKabisat(int tahun)
{
return (tahun % 4) == 0;
}
private boolean isNumeric(String str)
{
return str != null && str.matches("[0-9]+");
}
private int getHari(int bulan, int tahun)
{
int hari = 0;
int kabisat = 1;
switch(bulan)
{
case 1: hari = 31;
break;
case 2:
if (isKabisat(tahun))
{
hari = 28 + kabisat;
}
else
{
hari = 28;
}
break;
case 3: hari = 31;
break;
case 4: hari = 30;
break;
case 5: hari = 31;
break;
case 6: hari = 30;
break;
case 7: hari = 31;
break;
case 8: hari = 31;
break;
case 9: hari = 30;
break;
case 10: hari = 31;
break;
case 11: hari = 30;
break;
default: hari = 31;
break;
}
return hari;
}
private void clear()
{
txt_tahun.setText("");
txt_bulan.setText("");
lbl_hari.setText("0");
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btn_hapus;
private javax.swing.JButton btn_hitung;
private javax.swing.JButton btn_keluar;
private javax.swing.JButton btn_simpan;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JLabel lbl_hari;
private javax.swing.JTextField txt_bulan;
private javax.swing.JTextField txt_tahun;
// End of variables declaration//GEN-END:variables
}
| true |
01196fb07a6f869a8e0996d37938ad84c06eb319
|
Java
|
sonu-chahar/sb_indent_app
|
/src/main/java/com/chahar/indent/model/UserType.java
|
UTF-8
| 422 | 2.328125 | 2 |
[] |
no_license
|
package com.chahar.indent.model;
public enum UserType {
ADMIN("ADMIN"), ORGANIZATION("ORGANIZATION"), SUB_ORGNIZATION("SUB_ORGNIZATION"), DOCTOR("DOCTOR"), MMU("MMU");
private String userTypeName;
private UserType(String userTypeName) {
this.userTypeName = userTypeName;
}
public String getUserTypeName() {
return this.userTypeName;
}
@Override
public String toString() {
return this.userTypeName;
}
}
| true |
cedd7c3b2b86a1733fc5689d3ed6dbe4c8aebe22
|
Java
|
jimobama/RMIClient-Server
|
/Server/src/server/Server.java
|
UTF-8
| 517 | 1.898438 | 2 |
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package server;
import server.controllers.ServerController;
import server.models.ServerModel;
/**
*
* @author 21187498
*/
public class Server {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ServerController controller = new ServerController(new ServerModel());
controller.startServer();
}
}
| true |
43851535ea1ec652e31a80237597e14e6f956631
|
Java
|
alexandervbarkov/DesignPatterns
|
/src/composite/menu/MenuItem.java
|
UTF-8
| 1,353 | 3.265625 | 3 |
[] |
no_license
|
package composite.menu;
import java.util.List;
import java.util.stream.Collector;
public class MenuItem implements Menu {
private final String name;
private final String description;
private final float price;
private final boolean vegetarian;
public MenuItem(String name, String description, float price, boolean vegetarian) {
this.name = name;
this.description = description;
this.price = price;
this.vegetarian = vegetarian;
}
@Override
public void printMenu() {
System.out.println(name + " - " + description + (vegetarian ? ". Vegetarian" : ". Not vegetarian") + ". $" + price);
}
@Override
public boolean isItem() {
return true;
}
@Override
public String getName() {
return name;
}
@Override
public String getDescription() {
return description;
}
@Override
public boolean isVegetarian() {
return vegetarian;
}
@Override
public float getPrice() {
return price;
}
@Override
public List<Menu> getMenuList() {
throw new UnsupportedOperationException();
}
@Override
public <T> T performAction(MenuAction<T> menuListAction, MenuAction<T> menuItemAction, Collector<T, ?, T> collector) {
return menuItemAction.perform(this);
}
}
| true |
1e260dd3a0cc5a1809296b14da542e67fd501cac
|
Java
|
JonnHenry/WebPageMDE
|
/PrograWeb.tests/src/webPage/tests/MapTest.java
|
UTF-8
| 1,642 | 2.15625 | 2 |
[] |
no_license
|
/**
*/
package webPage.tests;
import junit.framework.TestCase;
import junit.textui.TestRunner;
import webPage.Map;
import webPage.WebPageFactory;
/**
* <!-- begin-user-doc -->
* A test case for the model object '<em><b>Map</b></em>'.
* <!-- end-user-doc -->
* @generated
*/
public class MapTest extends TestCase {
/**
* The fixture for this Map test case.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Map fixture = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static void main(String[] args) {
TestRunner.run(MapTest.class);
}
/**
* Constructs a new Map test case with the given name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MapTest(String name) {
super(name);
}
/**
* Sets the fixture for this Map test case.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void setFixture(Map fixture) {
this.fixture = fixture;
}
/**
* Returns the fixture for this Map test case.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Map getFixture() {
return fixture;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see junit.framework.TestCase#setUp()
* @generated
*/
@Override
protected void setUp() throws Exception {
setFixture(WebPageFactory.eINSTANCE.createMap());
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see junit.framework.TestCase#tearDown()
* @generated
*/
@Override
protected void tearDown() throws Exception {
setFixture(null);
}
} //MapTest
| true |
704d635b6760dc88dbd55c9d8f714d9ab9246374
|
Java
|
BurningChain/algorithm
|
/src/main/java/com/algorithm/sort/MergeSort.java
|
UTF-8
| 2,662 | 3.484375 | 3 |
[] |
no_license
|
package com.algorithm.sort;
import java.util.Arrays;
public class MergeSort {
public MergeSort() {
}
private static int[] mainSort(int[] arr) {
mergeSort(arr, 0, arr.length - 1);
return arr;
}
private static void mergeSort(int[] arr, int left, int right) {
if (left >= right) {
return;
}
mergeSort(arr, left, (right + left) / 2);
mergeSort(arr, (right + left) / 2 + 1, right);
merge(arr, left, (right + left) / 2, right);
}
private static void merge(int[] arr, int left, int mid, int right) {
int[] help = new int[right - left + 1];
int nl = 0;
int p1 = left;
int p2 = mid + 1;
while (p1 <= mid && p2 <= right) {
help[nl++] = (arr[p1] >= arr[p2] ? arr[p2++] : arr[p1++]);
}
while (p1 <= mid) {
help[nl++] = arr[p1++];
}
while (p2 <= right) {
help[nl++] = arr[p2++];
}
for (int i = 0; i < help.length; i++) {
arr[left + i] = help[i];
}
}
private static int[] arr = {5, 13, 28, 15, 9, 6, 3, 18};
public static void main(String[] args) {
System.out.println(Arrays.toString(mainSort(arr)));
}
}
class Sumtotal {
private static int[] newarr = {1, 3, 4, 2, 5};
public static int getSumFromArr(int[] arr) {
int res = mergeSort(arr, 0, arr.length - 1);
System.out.println(res);
return res;
}
private static int mergeSort(int[] arr, int left, int right) {
if (left >= right) {
return 0;
}
int sl = mergeSort(arr, left, (left + right) / 2);
int sr = mergeSort(arr, (left + right) / 2 + 1, right);
int ss = merge(arr, left, (right + left) / 2, right);
return sl + sr + ss;
}
private static int merge(int[] arr, int left, int mid, int right) {
int[] help = new int[right - left + 1];
int nl = 0, p1 = left, p2 = mid + 1;
int result = 0;
while (p1 <= mid && p2 <= right) {
result += arr[p1] <= arr[p2] ? arr[p1] * (right - p2 + 1) : 0;
help[nl++] = arr[p1] <= arr[p2] ? arr[p1++] : arr[p2++];
}
while (p1 <= mid) {
help[nl++] = arr[p1++];
}
while (p2 <= right) {
help[nl++] = arr[p2++];
}
for (int i = 0; i < help.length; i++) {
arr[left + i] = help[i];
}
return result;
}
public static void main(String[] args){
int sumFromArr = getSumFromArr(newarr);
System.out.println(sumFromArr);
}
}
| true |
627d0cbe2d0006a027e7da970da3924352b85c41
|
Java
|
lavanya80/MyCourseApp
|
/src/main/java/com/App/domain/Course.java
|
UTF-8
| 3,112 | 2.359375 | 2 |
[] |
no_license
|
package com.App.domain;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "courses", schema = "mycourseapp")
public class Course extends BaseEntity {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long CId;
private String CName;
private String CDes;
private Long CDuration;
private String CPreq;
@Enumerated(EnumType.STRING)
private Skilllevel CSkillLevel;
private String UserName;
@OneToMany(mappedBy = "course", cascade = CascadeType.ALL)
private Set<Topic> toipcs = new HashSet<>();
@ManyToMany(cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH })
@JoinTable(name = "courses_users", joinColumns = @JoinColumn(name = "CId"), inverseJoinColumns = @JoinColumn(name = "UserName"))
private Set<User> users = new HashSet<>();
public Long getCId() {
return CId;
}
public void setCId(Long cId) {
CId = cId;
}
public String getCName() {
return CName;
}
public void setCName(String cName) {
CName = cName;
}
public String getCDes() {
return CDes;
}
public void setCDes(String cDes) {
CDes = cDes;
}
public Long getCDuration() {
return CDuration;
}
public void setCDuration(Long cDuration) {
CDuration = cDuration;
}
public String getCPreq() {
return CPreq;
}
public void setCPreq(String cPreq) {
CPreq = cPreq;
}
public Skilllevel getCSkillLevel() {
return CSkillLevel;
}
public void setCSkillLevel(Skilllevel cSkillLevel) {
CSkillLevel = cSkillLevel;
}
public Set<Topic> getToipcs() {
return toipcs;
}
public void setToipcs(Set<Topic> toipcs) {
this.toipcs = toipcs;
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((CId == null) ? 0 : CId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Course other = (Course) obj;
if (CId == null) {
if (other.CId != null)
return false;
} else if (!CId.equals(other.CId))
return false;
return true;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
@Override
public String toString() {
return "Course [CId=" + CId + ", CName=" + CName + ", CDes=" + CDes + ", CDuration=" + CDuration + ", CPreq="
+ CPreq + ", CSkillLevel=" + CSkillLevel + ", UserName=" + UserName + "]";
}
}
| true |
c6eb9c2858fe03f8bc689d8372121a3f280cc068
|
Java
|
h265/camera
|
/camerazadas/source/apk/com.sonyericsson.android.camera/src-cfr/com/sonymobile/cameracommon/opengl/TextureMappingFrame.java
|
UTF-8
| 3,537 | 2.125 | 2 |
[] |
no_license
|
/*
* Decompiled with CFR 0_100.
*/
package com.sonymobile.cameracommon.opengl;
import android.content.Context;
import android.opengl.GLES20;
import android.view.View;
import com.sonyericsson.cameracommon.utility.CameraLogger;
import com.sonymobile.cameracommon.opengl.ExtendedGlSurfaceView;
import com.sonymobile.cameracommon.opengl.OpenGlException;
import com.sonymobile.cameracommon.opengl.YuvFrame;
import java.nio.Buffer;
public class TextureMappingFrame
extends YuvFrame {
private static final String TAG = TextureMappingFrame.class.getSimpleName();
protected int[] mIndexBuffers = new int[1];
protected int mIndicesNumber;
protected int[] mVertexAlphaBuffers = new int[1];
protected int mVertexAlphaInGLSL;
public TextureMappingFrame(Context context, View view) {
super(context, view);
}
@Override
protected boolean disableLocalFunctions() {
GLES20.glDisableVertexAttribArray(this.mVertexAlphaInGLSL);
return super.enableLocalFunctions();
}
@Override
protected void doRender() {
this.renderYuvFrame();
}
@Override
protected boolean enableLocalFunctions() {
GLES20.glEnableVertexAttribArray(this.mVertexAlphaInGLSL);
return super.enableLocalFunctions();
}
@Override
protected void initializeShaderProgram() throws OpenGlException {
this.mVertexAlphaInGLSL = GLES20.glGetAttribLocation(this.mShaderProgram, "vertexAlpha");
ExtendedGlSurfaceView.checkGlErrorWithException();
super.initializeShaderProgram();
}
@Override
protected void initializeVertexAndTextureCoordinatesBuffer() {
GLES20.glGenBuffers(this.mIndexBuffers.length, this.mIndexBuffers, 0);
GLES20.glGenBuffers(this.mVertexAlphaBuffers.length, this.mVertexAlphaBuffers, 0);
this.updateIndexBuffer(new byte[]{0, 1, 2, 3, 2, 1});
this.updateVertexAlphaBuffer(new float[]{1.0f, 1.0f, 1.0f, 1.0f});
super.initializeVertexAndTextureCoordinatesBuffer();
}
@Override
public void release() {
super.release();
}
protected boolean renderYuvFrame() {
GLES20.glBindBuffer(34962, this.mVertexAlphaBuffers[0]);
GLES20.glVertexAttribPointer(this.mVertexAlphaInGLSL, 1, 5126, false, 0, 0);
if (!this.setupTexture(this.mVertexBuffers[0], this.mTexCoordBuffers[0], this.mFrameTextures)) {
return false;
}
this.setupParameter(this.mShaderProgram);
this.setupMvpMatrix();
GLES20.glBindBuffer(34963, this.mIndexBuffers[0]);
GLES20.glDrawElements(4, this.mIndicesNumber, 5121, 0);
GLES20.glBindBuffer(34963, 0);
if (ExtendedGlSurfaceView.isGlErrorOccured()) {
CameraLogger.e(TAG, ".render():[Draw frame Error]");
return false;
}
return true;
}
public void updateIndexBuffer(byte[] object) {
this.mIndicesNumber = object.length;
object = ExtendedGlSurfaceView.allocByteBuffer((byte[])object);
GLES20.glBindBuffer(34963, this.mIndexBuffers[0]);
GLES20.glBufferData(34963, object.limit() * 1, (Buffer)object, 35048);
GLES20.glBindBuffer(34963, 0);
}
public void updateVertexAlphaBuffer(float[] object) {
object = ExtendedGlSurfaceView.allocFloatBuffer((float[])object);
GLES20.glBindBuffer(34962, this.mVertexAlphaBuffers[0]);
GLES20.glBufferData(34962, object.limit() * 4, (Buffer)object, 35048);
GLES20.glBindBuffer(34962, 0);
}
}
| true |
8dc28b9efd26cca8525bde802842eda4f42a21a8
|
Java
|
natagurskaya/ioccontainer
|
/src/main/java/ua/com/gurskaya/ioccontainer/service/XMLBeanDefinitionReader.java
|
UTF-8
| 4,256 | 2.625 | 3 |
[] |
no_license
|
package ua.com.gurskaya.ioccontainer.service;
import ua.com.gurskaya.ioccontainer.entity.BeanDefinition;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class XMLBeanDefinitionReader implements BeanDefinitionReader {
String[] path = {"src/main/resources/context.xml"};
public XMLBeanDefinitionReader(String[] path) {
this.path = path;
}
public List<BeanDefinition> readBeanDefinition() {
List<BeanDefinition> beanDefinitions = new ArrayList<>();
for (int i = 0; i < path.length; i++) {
try (FileReader file = new FileReader(path[i]);
BufferedReader reader = new BufferedReader(file)) {
String line = reader.readLine();
line = reader.readLine();
while (!line.equals("</beans>")) {
line = line.trim();
String[] splitLine = line.split(" ");
if (splitLine[0].equals("<bean")) {
BeanDefinition beanDefinition = new BeanDefinition();
String[] idElements = splitLine[1].split("=");
String idVal = idElements[1].substring(1, idElements[1].length() - 1);
beanDefinition.setId(idVal);
String[] classElements = splitLine[2].split("=");
String clazz = classElements[1].substring(1, classElements[1].length() - 2);
beanDefinition.setBeanClassName(clazz);
line = reader.readLine();
line = line.trim();
while (!line.equals("</bean>")) {
line = line.trim();
String[] splitLineDependencies = line.split(" ");
String[] dependencyValues = splitLineDependencies[2].split("=");
if (dependencyValues[0].equals("value")) {
Map<String, String> map = parsePropertiesValues(splitLineDependencies);
beanDefinition.setDependencies(map);
line = reader.readLine();
line = line.trim();
} else {
Map<String, String> map = parsePropertiesRefs(splitLineDependencies);
beanDefinition.setRefDependencies(map);
line = reader.readLine();
line = line.trim();
}
}
beanDefinitions.add(beanDefinition);
}
line = reader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return beanDefinitions;
}
private Map<String, String> parsePropertiesValues(String[] splitDependencies) {
Map<String, String> dependencies = new HashMap<>();
String[] splitDependenciesName = splitDependencies[1].split("=");
dependencies.put(splitDependenciesName[0], splitDependenciesName[1].substring(1, splitDependenciesName[1].length() - 1));
String[] splitDependenciesValue = splitDependencies[2].split("=");
dependencies.put(splitDependenciesValue[0], splitDependenciesValue[1].substring(1, splitDependenciesValue[1].length() - 3));
return dependencies;
}
private Map<String, String> parsePropertiesRefs(String[] splitDependencies) {
Map<String, String> dependencies = new HashMap<>();
String[] splitDependenciesName = splitDependencies[1].split("=");
dependencies.put(splitDependenciesName[0], splitDependenciesName[1].substring(1, splitDependenciesName[1].length() - 1));
String[] splitDependenciesRef = splitDependencies[2].split("=");
dependencies.put(splitDependenciesRef[0], splitDependenciesRef[1].substring(1, splitDependenciesRef[1].length() - 3));
return dependencies;
}
}
| true |
b0c2ca7911b3bbafb9cfabedbcae1e27b5ad3249
|
Java
|
clxmm/newjava
|
/004-java-spring/class17/src/test/java/Test.java
|
UTF-8
| 643 | 1.984375 | 2 |
[] |
no_license
|
import com.i.TestBean;
import com.i.TestConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
/**
* @author clxmm
* @version 1.0
* @date 2020/9/26 4:08 下午
*/
public class Test {
@org.junit.Test
public void test() {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
TestBean testBean = context.getBean("testBean", TestBean.class);
System.out.println(testBean);
context.close();
}
}
| true |
690417f36513898ac1429b1fcc6876b84650882b
|
Java
|
tsb-study/JpaSample
|
/jpa-sample/src/main/java/com/example/jpasample/repository/MemberRepository.java
|
UTF-8
| 226 | 1.671875 | 2 |
[] |
no_license
|
package com.example.jpasample.repository;
import com.example.jpasample.domain.Member;
import org.springframework.data.jpa.repository.JpaRepository;
public interface MemberRepository extends JpaRepository<Member, Long> {
}
| true |
1767d832b10dfeeb4cbd18e84f1c85c9f66186ff
|
Java
|
Posase/demo
|
/src/main/java/com/example/demo/model/Api.java
|
UTF-8
| 170 | 1.625 | 2 |
[] |
no_license
|
package com.example.demo.model;
import lombok.Data;
@Data
public class Api {
private String method_type;
private String path;
private String api_version;
}
| true |
0f404a0f641158b2741e1497a32f767921457853
|
Java
|
markoknezevic/Personal_projects
|
/3D Game(GDX Lib)/core/src/com/project/game/Core.java
|
UTF-8
| 1,245 | 2.4375 | 2 |
[] |
no_license
|
package com.project.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.project.managers.Settings;
import com.project.screens.LoadingScreen;
public class Core extends ApplicationAdapter
{
public static int SCREEN_WIDTH;
public static int SCREEN_HEIGHT;
private Screen screen;
@Override
public void create ()
{
initializeSettings();
initializeScreenWidthAndHeight();
setScreen(new LoadingScreen(this));
}
private void initializeSettings()
{
new Settings().load();
}
private void initializeScreenWidthAndHeight()
{
SCREEN_WIDTH = Gdx.graphics.getWidth();
SCREEN_HEIGHT = Gdx.graphics.getHeight();
}
public void setScreen(Screen screen)
{
if(this.screen != null)
{
this.screen.hide();
this.screen.dispose();
}
this.screen = screen;
if(this.screen != null)
{
this.screen.show();
}
}
@Override
public void render ()
{
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
screen.render(Gdx.graphics.getDeltaTime());
}
@Override
public void dispose ()
{
Assets.dispose();
Settings.save();
screen.dispose();
}
}
| true |
03df276716fbf88bf4006c139186a96300a04dfa
|
Java
|
Bjarnabofar/tictactoe
|
/src/main/java/is/ru/tictactoe/Player.java
|
UTF-8
| 1,266 | 3.6875 | 4 |
[] |
no_license
|
package is.ru.tictactoe;
/**
* Player class contains info of wins, losses and draws
* for a Player of the game Tic Tac Toe.
* @author Bjarnabofarnir
*/
public abstract class Player {
protected char sign;
protected int wins;
protected int losses;
protected int draws;
/**
*@return wins which holds track of number of wins for this player
*/
public int getWins() {
return wins;
}
/**
*@return losses which holds track of number of losses for this player
*/
public int getLosses() {
return losses;
}
/**
*@return draws which holds track of number of draws for this player
*/
public int getDraws() {
return draws;
}
/**
*@return sign which says if the player's sign is X or Y
*/
public char getSign() {
return sign;
}
/**
* Increment number of wins by one
*/
public void addWin() {
wins++;
}
/**
* Decrements number of losses by one
*/
public void addLoss() {
losses++;
}
/**
* Increments number of draws by one
*/
public void addDraw() {
draws++;
}
/**
* Gets the player's next move, implemented differently for computer player vs human player
* @return the Point instance of the next move
*/
protected abstract Point getMove();
}
| true |
6974af1d83940116eb79659e5fc0e5e73d51a1fe
|
Java
|
viethoang25/NCKH-ControlFlowGraph
|
/ControlFlowGraph/src/Main.java
|
UTF-8
| 2,184 | 2.078125 | 2 |
[] |
no_license
|
import java.util.ArrayList;
import java.util.List;
import node.BaseNode;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import prefix.InfixToPrefix;
import coverage.DFS;
import file.FileManager;
public class Main {
public static void main(String[] args) {
FileManager fileManager = FileManager.getInstance();
fileManager.init("./example/");
fileManager.readFile("sumOdd");
SyntaxManager syntaxManager = new SyntaxManager(fileManager.getData());
syntaxManager.printStatementList();
CfgTree tree = new CfgTree(fileManager.getData());
tree.printNodeList();
tree.printEdgeList();
for (BaseNode i : tree.getEndNode()) {
System.out.println("END : " + i.getIndex());
}
/*
* System.out.println("-------------------------------------");
* tree.printMainTreeList();
* System.out.println("-------------------------------------");
*/
InitGraph graph = new InitGraph();
DFS dfs = new DFS(graph.getSizeArray(), graph.getGraph(),
tree.getNodeList());
dfs.doDFS(0, 0, graph.getSizeArray() - 1);
if (tree.getStartLoop() > 0) {
DFS loopDfs = new DFS(graph.getSizeArray(), graph.getGraph(),
tree.getNodeList());
loopDfs.doDFS(tree.getStartLoop(), tree.getStartLoop(), tree
.getEndLoop().get(0));
dfs.setForTestPath(loopDfs.getTestPath(), 3, tree.getStartLoop());
}
System.out.println(dfs.getTestPath().size());
for (List<BaseNode> list : dfs.getTestPath()) {
System.out.println("LIST");
for (BaseNode n : list) {
System.out.print(n.getIndex() + "->");
}
System.out.println();
}
for (List<BaseNode> list : dfs.getTestPath()) {
System.out.println("---------------------------");
PathConstraint path = new PathConstraint(list, tree.getEdgeList());
System.out.println("VARIABLE");
path.printVariableList();
/*
* System.out.println("EXPRESSION"); path.printExpressionList();
*/
System.out.println(path.getZ3Input());
Z3Handle z3 = new Z3Handle(path.getZ3Input());
z3.printResult();
}
}
}
| true |
b75e75f0792da9eafeecb692280a891212eb115c
|
Java
|
ojinxy/roms_web
|
/src/fsl/ta/toms/roms/search/criteria/impl/CourtAppearanceCriteriaBO.java
|
UTF-8
| 2,845 | 2.203125 | 2 |
[] |
no_license
|
/**
* Created By: oanguin
* Date: Jun 19, 2013
*
*/
package fsl.ta.toms.roms.search.criteria.impl;
import java.util.Date;
import fsl.ta.toms.roms.search.criteria.SearchCriteria;
/**
* @author oanguin
* Created Date: Jun 19, 2013
*/
public class CourtAppearanceCriteriaBO implements SearchCriteria
{
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer courtAppearanceId,summonsId,courtId,pleaId;
private String courtRulingId,
statusCode,
courtTime,
courtCaseNo;
private Date courtDate;
public String getCourtCaseNo() {
return courtCaseNo;
}
public void setCourtCaseNo(String courtCaseNo) {
this.courtCaseNo = courtCaseNo;
}
public Integer getCourtAppearanceId() {
return courtAppearanceId;
}
public void setCourtAppearanceId(Integer courtAppearanceId) {
this.courtAppearanceId = courtAppearanceId;
}
public Integer getSummonsId() {
return summonsId;
}
public void setSummonsId(Integer summonsId) {
this.summonsId = summonsId;
}
public Integer getCourtId() {
return courtId;
}
public void setCourtId(Integer courtId) {
this.courtId = courtId;
}
public Integer getPleaId() {
return pleaId;
}
public void setPleaId(Integer pleaId) {
this.pleaId = pleaId;
}
public String getCourtRulingId() {
return courtRulingId;
}
public void setCourtRulingId(String courtRulingId) {
this.courtRulingId = courtRulingId;
}
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public Date getCourtDate() {
return courtDate;
}
public void setCourtDate(Date courtDate) {
this.courtDate = courtDate;
}
public CourtAppearanceCriteriaBO(Integer courtAppearanceId, Integer summonsId, Integer courtId,
Integer pleaId, String courtRulingId, String statusCode,
Date courtDate) {
super();
this.courtAppearanceId = courtAppearanceId;
this.summonsId = summonsId;
this.courtId = courtId;
this.pleaId = pleaId;
this.courtRulingId = courtRulingId;
this.statusCode = statusCode;
this.courtDate = courtDate;
}
public CourtAppearanceCriteriaBO() {
super();
// TODO Auto-generated constructor stub
}
public String getCourtTime() {
return courtTime;
}
public void setCourtTime(String courtTime) {
this.courtTime = courtTime;
}
public CourtAppearanceCriteriaBO(Integer courtAppearanceId, Integer summonsId, Integer courtId,
Integer pleaId, String courtRulingId, String statusCode,
String courtTime, Date courtDate) {
super();
this.courtAppearanceId = courtAppearanceId;
this.summonsId = summonsId;
this.courtId = courtId;
this.pleaId = pleaId;
this.courtRulingId = courtRulingId;
this.statusCode = statusCode;
this.courtTime = courtTime;
this.courtDate = courtDate;
}
}
| true |
15705ddb86ee528d0485137273524add42f08bd1
|
Java
|
thithinkadya/SeleniumRepository
|
/src/com/vfislk/hdfc/citybank.java
|
UTF-8
| 1,139 | 2.34375 | 2 |
[] |
no_license
|
package com.vfislk.hdfc;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class citybank {
public static void main(String[] args) {
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("https://www.online.citibank.co.in/");
driver.findElement(By.xpath("//img[@class='appClose']")).click();
driver.findElement(By.linkText("APPLY FOR CREDIT CARDS")).click();
System.out.println(driver.getTitle());
String parent = driver.getWindowHandle();
System.out.println(parent);
System.out.println("--------------------------------");
Set<String> windows= driver.getWindowHandles();
for(String win : windows)
{
System.out.println(win);
driver.switchTo().window(win);
System.out.println(driver.getTitle());
System.out.println("----------");
}
driver.findElement(By.linkText("Travel")).click();
driver.close();
}
}
| true |
de1a711743a1494bd53d5422f096e3afe9b21691
|
Java
|
sbjanani/GraphDatabase
|
/GDB/src/com/gdb/datastore/AdjacencyRecord.java
|
UTF-8
| 2,650 | 3.09375 | 3 |
[] |
no_license
|
package com.gdb.datastore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import com.gdb.util.Constants;
public class AdjacencyRecord {
Map<Byte,ArrayList<NeighborNodeRecord>> inComing;
Map<Byte,ArrayList<NeighborNodeRecord>> outGoing;
short[] inComingCount;
short[] outGoingCount;
public AdjacencyRecord() {
inComing = new HashMap<Byte,ArrayList<NeighborNodeRecord>>();
outGoing = new HashMap<Byte,ArrayList<NeighborNodeRecord>>();
inComingCount = new short[Constants.NUMBER_OF_EDGE_TYPES];
outGoingCount = new short[Constants.NUMBER_OF_EDGE_TYPES];
}
public short getIncomingCount(byte edgeType){
return (short) inComing.get(edgeType).size();
}
public short getOutGoingCount(byte edgeType){
return (short) outGoing.get(edgeType).size();
}
public void addIncoming(int value, byte edgeType){
NeighborNodeRecord nr = new NeighborNodeRecord(value,edgeType);
if(inComing.containsKey(edgeType)){
inComing.get(edgeType).add(nr);
}
else{
ArrayList<NeighborNodeRecord> neighborList = new ArrayList<NeighborNodeRecord>();
neighborList.add(nr);
inComing.put(edgeType, neighborList);
}
inComingCount[edgeType]++;
}
public void addOutGoing(int value,byte edgeType){
NeighborNodeRecord nr = new NeighborNodeRecord(value,edgeType);
if(outGoing.containsKey(edgeType)){
outGoing.get(edgeType).add(nr);
}
else{
ArrayList<NeighborNodeRecord> neighborList = new ArrayList<NeighborNodeRecord>();
neighborList.add(nr);
outGoing.put(edgeType, neighborList);
}
outGoingCount[edgeType]++;
}
public Map<Byte, ArrayList<NeighborNodeRecord>> getInComing() {
return inComing;
}
public void setInComing(Map<Byte, ArrayList<NeighborNodeRecord>> inComing) {
this.inComing = inComing;
}
public Map<Byte, ArrayList<NeighborNodeRecord>> getOutGoing() {
return outGoing;
}
public void setOutGoing(Map<Byte, ArrayList<NeighborNodeRecord>> outGoing) {
this.outGoing = outGoing;
}
public String toString(){
return "incoming = "+inComing + "\n" + "outoing= "+outGoing + "\n\n";
}
/**
* @return the inComingCount
*/
public short[] getInComingCount() {
return inComingCount;
}
/**
* @param inComingCount the inComingCount to set
*/
public void setInComingCount(short[] inComingCount) {
this.inComingCount = inComingCount;
}
/**
* @return the outGoingCount
*/
public short[] getOutGoingCount() {
return outGoingCount;
}
/**
* @param outGoingCount the outGoingCount to set
*/
public void setOutGoingCount(short[] outGoingCount) {
this.outGoingCount = outGoingCount;
}
}
| true |
501dda8b4f865ae4e96caa0ea7261248d1741027
|
Java
|
MichaelJFuentes/Java-Masterclass
|
/src/FirstSteps/MethodChallenge.java
|
UTF-8
| 925 | 3.53125 | 4 |
[] |
no_license
|
package FirstSteps;
public class MethodChallenge {
public static void main(String[] args) {
displayHighScorePosition("mike", 1000);
displayHighScorePosition("bob", 900);
displayHighScorePosition("mary", 400);
displayHighScorePosition("guy", 50);
displayHighScorePosition("error", -23);
}
public static void displayHighScorePosition(String name, int score) {
System.out.println(name + " managed to get into position " + calculateHighScorePosition(score) + " on the high score table");
}
public static int calculateHighScorePosition(int score) {
int position = -1;
if (score >= 1000) {
position = 1;
} else if (score >= 500) {
position = 2;
} else if (score >= 100) {
position = 3;
} else if (score > 0) {
position = 4;
}
return position;
}
}
| true |
8d0723d3f3cfb5bae05eda9bdaff3cd47c36e624
|
Java
|
hqdat809/code_JAVA
|
/SOPJ/Huong_doi_Tuong/test/src/bai13_2/Student.java
|
UTF-8
| 949 | 2.53125 | 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 bai13_2;
/**
*
* @author phuon
*/
public class Student {
private String maSV;
private String hoTen;
private int tuoi;
public Student() {
}
public Student(String maSV, String hoTen, int tuoi) {
this.maSV = maSV;
this.hoTen = hoTen;
this.tuoi = tuoi;
}
public String getMaSV() {
return maSV;
}
public void setMaSV(String maSV) {
this.maSV = maSV;
}
public String getHoTen() {
return hoTen;
}
public void setHoTen(String hoTen) {
this.hoTen = hoTen;
}
public int getTuoi() {
return tuoi;
}
public void setTuoi(int tuoi) {
this.tuoi = tuoi;
}
}
| true |
01fe1bbdac9edf275cab86ba7ba29713b9396d4d
|
Java
|
IdeaUJetBrains/TESTproject
|
/IDEA156059/src/result156059WithProperties/Driver.java
|
UTF-8
| 1,616 | 2.65625 | 3 |
[] |
no_license
|
package result156059WithProperties;
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import java.util.Collection;
/**
* Created by Olga Pavlova on 5/25/2016.
*/
@Entity
public class Driver {
private int id;
@Id
@javax.persistence.Column(name = "ID", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
private String drivername;
@Basic
@javax.persistence.Column(name = "DRIVERNAME", nullable = true, length = 255)
public String getDrivername() {
return drivername;
}
public void setDrivername(String drivername) {
this.drivername = drivername;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Driver driver = (Driver) o;
if (id != driver.id) return false;
if (drivername != null ? !drivername.equals(driver.drivername) : driver.drivername != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (drivername != null ? drivername.hashCode() : 0);
return result;
}
private Collection<Buss> bussesById;
@OneToMany(targetEntity = Buss.class, mappedBy = "driverById")
public Collection<Buss> getBussesById() {
return bussesById;
}
public void setBussesById(Collection<Buss> bussesById) {
this.bussesById = bussesById;
}
}
| true |
f6ff0d063efb19009d02a4f38536f9412f38c325
|
Java
|
zuzuauthor/Testkart
|
/app/src/main/java/com/testkart/exam/edu/myresult/Response.java
|
UTF-8
| 690 | 1.984375 | 2 |
[] |
no_license
|
package com.testkart.exam.edu.myresult;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class Response implements Serializable
{
@SerializedName("Result")
@Expose
private Result result;
@SerializedName("Exam")
@Expose
private Exam exam;
private final static long serialVersionUID = 2425656119763170377L;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
public Exam getExam() {
return exam;
}
public void setExam(Exam exam) {
this.exam = exam;
}
}
| true |
a7007e5ca07cc1716f931495d47b53a60a854f13
|
Java
|
tamarahnz/AdivinApp
|
/AdivinApp/src/main/java/dad/javafx/adivinApp/Adivina.java
|
ISO-8859-1
| 3,372 | 3.15625 | 3 |
[] |
no_license
|
package dad.javafx.adivinApp;
import java.util.Random;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
public class Adivina extends Application {
private Label comprobarLabel;
private Button comprobarButton;
private TextField nombreText;
Random r = new Random();
int adivinar = (int) Math.floor(Math.random()* 100) + 1;
int contador = 0;
@Override
public void start(Stage primaryStage) throws Exception {
// Creamos un cuadro de texto
nombreText = new TextField();
nombreText.setPrefColumnCount(5);
nombreText.setMaxWidth(100);// Establecemos el tamao mximo del componente
// Creamos una etiqueta
comprobarLabel = new Label();
comprobarLabel.setText("Introduce un nmero del 1 al 100");
// Creamos un botn
comprobarButton = new Button();
comprobarButton.setText("Comprobar");
comprobarButton.setOnAction(numIN -> onComprobarButtonAction(numIN));
comprobarButton.setDefaultButton(true);
contador++;
// Creamos un panel con disposicin vertical
VBox root = new VBox();
root.setSpacing(5);
root.setAlignment(Pos.CENTER);
root.getChildren().addAll(comprobarLabel, nombreText, comprobarButton);
// Creamos la escena
Scene escena = new Scene(root, 320, 200);
// Configuramos la ventana y le ponemos una escena
primaryStage.setScene(escena);
primaryStage.setTitle("AdivinApp");
primaryStage.show();
}
public void onComprobarButtonAction(ActionEvent numIN) {
int pasarInt = Integer.parseInt(nombreText.getText());
if(pasarInt > 100){
Alert alert4 = new Alert(AlertType.ERROR);
alert4.setTitle("AdivinApp");
alert4.setHeaderText("Error");
alert4.setContentText("El nmero introducido no es vlido");
alert4.showAndWait();
} else if(pasarInt < 0){
Alert alert4 = new Alert(AlertType.ERROR);
alert4.setTitle("AdivinApp");
alert4.setHeaderText("Error");
alert4.setContentText("El nmero introducido no es vlido");
alert4.showAndWait();
} else if (adivinar > pasarInt) {
Alert alert1 = new Alert(AlertType.WARNING);
alert1.setTitle("AdivinApp");
alert1.setHeaderText("Has Fallado!");
alert1.setContentText("El nmero a adivinar es ms grande que "+ pasarInt+ ".\nVuelve a intentarlo.");
alert1.showAndWait();
contador++;
} else if (adivinar < pasarInt) {
Alert alert2 = new Alert(AlertType.WARNING);
alert2.setTitle("AdivinApp");
alert2.setHeaderText("Has Fallado!");
alert2.setContentText("El nmero a adivinar es ms pequeo que " + pasarInt+ ".\nVuelve a intentarlo.");
alert2.showAndWait();
contador++;
} else if(adivinar == pasarInt){
Alert alert3 = new Alert(AlertType.INFORMATION);
alert3.setTitle("AdvinApp");
alert3.setHeaderText("Has Ganado!");
alert3.setContentText("Solo has necesitado " + contador + " intentos.\nVuelve a jugar y hazlo mejor.");
alert3.showAndWait();
}
}
public static void main(String[] args) {
launch(args);
}
}
| true |
f6d159496b8ffa6e640ff83429a8a0122a4fd9fc
|
Java
|
dengboyu/future
|
/by-future-common/src/main/java/by/future/common/utils/IpUtils.java
|
UTF-8
| 3,327 | 3.296875 | 3 |
[] |
no_license
|
package by.future.common.utils;
import java.net.*;
import java.util.Enumeration;
/**
* ip工具类
*
* @Author:by@Deng
* @Date:2018/9/4 14:32
*/
public class IpUtils {
/**
* 获取本地ip,兼容linux
*
* @Author:by@Deng
* @Date:2018/9/4 14:34
*/
public static String getLocalIp(){
String ip = null;
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface networkInterface = en.nextElement();
String name = networkInterface.getName();
if (!name.contains("docker") && !name.contains("lo")) {
for (Enumeration<InetAddress> addressEnumeration = networkInterface.getInetAddresses(); addressEnumeration.hasMoreElements();) {
InetAddress inetAddress = addressEnumeration.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String ipAddress = inetAddress.getHostAddress();
if (!ipAddress.contains("::") && !ipAddress.contains("0:0:") && !ipAddress.contains("fe80")) {
ip = ipAddress;
}
}
}
}
}
} catch (SocketException e) {
System.out.println("获取ip地址异常");
e.printStackTrace();
}
return ip;
}
/**
* ip地址转成long型数字
* 将IP地址转化成整数的方法如下:
* 1、通过String的split方法按.分隔得到4个长度的数组
* 2、通过左移位操作(<<)给每一段的数字加权,第一段的权为2的24次方,第二段的权为2的16次方,第三段的权为2的8次方,最后一段的权为1
* @param strIp
* @return
*/
public static long ipToLong(String strIp) {
String[]ip = strIp.split("\\.");
return (Long.parseLong(ip[0]) << 24) + (Long.parseLong(ip[1]) << 16) + (Long.parseLong(ip[2]) << 8) + Long.parseLong(ip[3]);
}
/**
* 将十进制整数形式转换成127.0.0.1形式的ip地址
* 将整数形式的IP地址转化成字符串的方法如下:
* 1、将整数值进行右移位操作(>>>),右移24位,右移时高位补0,得到的数字即为第一段IP。
* 2、通过与操作符(&)将整数值的高8位设为0,再右移16位,得到的数字即为第二段IP。
* 3、通过与操作符吧整数值的高16位设为0,再右移8位,得到的数字即为第三段IP。
* 4、通过与操作符吧整数值的高24位设为0,得到的数字即为第四段IP。
* @param longIp
* @return
*/
public static String longToIP(long longIp) {
StringBuffer sb = new StringBuffer("");
// 直接右移24位
sb.append(longIp >>> 24);
sb.append(".");
// 将高8位置0,然后右移16位
sb.append((longIp & 0x00FFFFFF) >>> 16);
sb.append(".");
// 将高16位置0,然后右移8位
sb.append((longIp & 0x0000FFFF) >>> 8);
sb.append(".");
// 将高24位置0
sb.append((longIp & 0x000000FF));
return sb.toString();
}
}
| true |
cf0235822017a16cb00fc6e2a07e006baaff9486
|
Java
|
HackathonNicaragua/elementalbrainers
|
/ExpresApp/app/src/main/java/com/elementalbraines/expressapp/ui/activity/ChatActivity.java
|
UTF-8
| 7,208 | 1.78125 | 2 |
[] |
no_license
|
package com.elementalbraines.expressapp.ui.activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
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.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.elementalbraines.expressapp.R;
import com.elementalbraines.expressapp.Util;
import com.elementalbraines.expressapp.models.ChatModel;
import com.elementalbraines.expressapp.ui.adapters.ChatAdapter;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.tumblr.remember.Remember;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class ChatActivity extends AppCompatActivity {
@BindView(R.id.rcvChat)
RecyclerView rcvChat;
public final int REQUEST_MICROFONO = 100;
TextToSpeech textToSpeech;
ChatAdapter adapter;
DatabaseReference dbChat;
@BindView(R.id.txvTitToolbart)
TextView txvTitToolbart;
/*@BindView(R.id.imvReproducir)
ImageButton imvReproducir;*/
@BindView(R.id.edtMensaje)
EditText edtMensaje;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("ChatModel");
toolbar.setNavigationIcon(R.drawable.ic_logo);
Remember.init(getApplicationContext(), "com.elementalbraines.expressapp");
ButterKnife.bind(this);
setSupportActionBar(toolbar);
validatePermission();
dbChat = FirebaseDatabase.getInstance().getReference()
.child("salas").child("sala1");
List<ChatModel> chatModelList = new ArrayList<ChatModel>();
adapter = new ChatAdapter(getApplicationContext(), chatModelList);
rcvChat.setAdapter(adapter);
rcvChat.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
//rcvChat.setHasFixedSize(true);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Di algo");
startActivityForResult(i, REQUEST_MICROFONO);
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
textToSpeech.setSpeechRate(1);
textToSpeech.setLanguage(Locale.getDefault());
}
}
});
}
});
loadMensaje();
Typeface font = Typeface.createFromAsset(getAssets(), "RobotoCondensed-Light.ttf");
txvTitToolbart.setTypeface(font);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_principal, menu);
return true;
}
public void validatePermission(){
if(Remember.getString(Util.USER_ID, "").equals("")){
Intent i = new Intent(this, LoginActivity.class);
startActivity(i);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_traductor:
Intent i = new Intent(this, TraductorActivity.class);
startActivity(i);
break;
}
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_MICROFONO) {
if(resultCode == RESULT_OK){
ArrayList<String> values = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
sendMensaje(values.get(0));
//Toast.makeText(getApplicationContext(), values.get(0), Toast.LENGTH_LONG).show();
}else{
Snackbar.make(rcvChat, "Petición cancelada", Snackbar.LENGTH_LONG).show();
}
//gifInterprete.setBackgroundResource(R.drawable.tres);
}
}
@OnClick(R.id.imvSend)
void OnImvSend(View view){
sendMensaje(edtMensaje.getText().toString());
edtMensaje.setText("");
}
public void sendMensaje(String mensaje){
String user_id = Remember.getString(Util.USER_ID,"Anonymo");
String user_name = Remember.getString(Util.USER_NAME,"Anonymo");
String user_picture = Remember.getString(Util.USER_PICTURE,"Anonymo");
ChatModel chatModel = new ChatModel(user_id, user_name, mensaje, user_picture);
dbChat.child(java.util.UUID.randomUUID().toString()).setValue(chatModel);
}
public void loadMensaje(){
ChildEventListener childEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
String token = dataSnapshot.child("user_id").getValue().toString();
String nombre = dataSnapshot.child("nombre").getValue().toString();
String mensaje = dataSnapshot.child("mensaje").getValue().toString();
String picture = dataSnapshot.child("image").getValue().toString();
adapter.addChat(new ChatModel(token, nombre, mensaje, picture));
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
dbChat.addChildEventListener(childEventListener);
}
}
| true |
04603e418b2e9b3c124208077e21b30a58312b57
|
Java
|
zhongxingyu/Seer
|
/Diff-Raw-Data/2/2_c5b953485c2a8f17a1ae7d5d598c467c84fc1e94/LocalServiceInterface/2_c5b953485c2a8f17a1ae7d5d598c467c84fc1e94_LocalServiceInterface_t.java
|
UTF-8
| 8,237 | 2.09375 | 2 |
[] |
no_license
|
package grisu.control.serviceInterfaces;
import grisu.backend.hibernate.HibernateSessionFactory;
import grisu.backend.model.User;
import grisu.control.ServiceInterface;
import grisu.control.exceptions.NoSuchTemplateException;
import grisu.control.exceptions.NoValidCredentialException;
import grisu.jcommons.utils.MyProxyServerParams;
import grisu.settings.ServerPropertiesManager;
import grisu.settings.ServiceTemplateManagement;
import grith.jgrith.Credential;
import grith.jgrith.plainProxy.LocalProxy;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import org.apache.commons.lang.StringUtils;
import org.globus.myproxy.CredentialInfo;
import org.globus.myproxy.MyProxy;
import org.globus.myproxy.MyProxyException;
import org.ietf.jgss.GSSException;
public class LocalServiceInterface extends AbstractServiceInterface implements
ServiceInterface {
private Credential credential = null;
private String myproxy_username = null;
private char[] passphrase = null;
private User user;
private static String hostname = null;
// @Override
protected final Credential getCredential() {
long oldLifetime = -1;
try {
if (credential != null) {
oldLifetime = credential.getCredential()
.getRemainingLifetime();
}
} catch (final GSSException e2) {
myLogger.debug("Problem getting lifetime of old certificate: " + e2);
credential = null;
}
if (oldLifetime < ServerPropertiesManager
.getMinProxyLifetimeBeforeGettingNewProxy()) {
myLogger.debug("Credential reached minimum lifetime. Getting new one from myproxy. Old lifetime: "
+ oldLifetime);
this.credential = null;
// user.cleanCache();
}
if ((credential == null) || !credential.isValid()) {
if ((myproxy_username == null) || (myproxy_username.length() == 0)) {
if ((passphrase == null) || (passphrase.length == 0)) {
// try local proxy
try {
credential = new Credential(
LocalProxy.loadGSSCredential());
final long newLifeTime = credential.getCredential()
.getRemainingLifetime();
if (oldLifetime < ServerPropertiesManager
.getMinProxyLifetimeBeforeGettingNewProxy()) {
throw new NoValidCredentialException(
"Proxy lifetime smaller than minimum allowed lifetime.");
}
} catch (final Exception e) {
throw new NoValidCredentialException(
"Could not load credential/no valid login data.");
}
if (!credential.isValid()) {
throw new NoValidCredentialException(
"Local proxy is not valid anymore.");
}
}
} else {
// get credential from myproxy
String myProxyServer = MyProxyServerParams.getMyProxyServer();
final int myProxyPort = MyProxyServerParams.getMyProxyPort();
try {
// this is needed because of a possible round-robin myproxy
// server
myProxyServer = InetAddress.getByName(myProxyServer)
.getHostAddress();
} catch (final UnknownHostException e1) {
myLogger.error(e1.getLocalizedMessage(), e1);
throw new NoValidCredentialException(
"Could not download myproxy credential: "
+ e1.getLocalizedMessage());
}
try {
credential = new Credential(myproxy_username, passphrase,
myProxyServer, myProxyPort,
ServerPropertiesManager.getMyProxyLifetime());
final long newLifeTime = credential.getCredential()
.getRemainingLifetime();
if (newLifeTime < ServerPropertiesManager
.getMinProxyLifetimeBeforeGettingNewProxy()) {
throw new NoValidCredentialException(
"Proxy lifetime smaller than minimum allowed lifetime.");
}
if (getUser() != null) {
getUser().cleanCache();
}
} catch (final RuntimeException re) {
throw re;
} catch (final Throwable e) {
myLogger.error(e.getLocalizedMessage(), e);
throw new NoValidCredentialException(
"Could not get myproxy credential: "
+ e.getLocalizedMessage());
}
if (!credential.isValid()) {
throw new NoValidCredentialException(
"MyProxy credential is not valid.");
}
}
}
return credential;
}
// // @Override
// protected final ProxyCredential getCredential(String fqan,
// int lifetimeInSeconds) {
//
// final String myProxyServer = MyProxyServerParams.getMyProxyServer();
// final int myProxyPort = MyProxyServerParams.getMyProxyPort();
//
// ProxyCredential temp;
// try {
// temp = new ProxyCredential(MyProxy_light.getDelegation(
// myProxyServer, myProxyPort, myproxy_username, passphrase,
// lifetimeInSeconds));
// if (StringUtils.isNotBlank(fqan)) {
//
// final VO vo = getUser().getFqans().get(fqan);
// final ProxyCredential credToUse = CertHelpers
// .getVOProxyCredential(vo, fqan, temp);
//
// myLogger.debug("Created proxy with lifetime: "
// + credToUse.getExpiryDate().toString());
// return credToUse;
// } else {
// myLogger.debug("Created proxy with lifetime: "
// + temp.getExpiryDate().toString());
// return temp;
// }
// } catch (final Exception e) {
// throw new RuntimeException(e);
// }
// }
public final long getCredentialEndTime() {
String myProxyServer = MyProxyServerParams.getMyProxyServer();
final int myProxyPort = MyProxyServerParams.getMyProxyPort();
try {
// this is needed because of a possible round-robin myproxy server
myProxyServer = InetAddress.getByName(myProxyServer)
.getHostAddress();
} catch (final UnknownHostException e1) {
myLogger.error(e1.getLocalizedMessage(), e1);
throw new NoValidCredentialException(
"Could not download myproxy credential: "
+ e1.getLocalizedMessage());
}
final MyProxy myproxy = new MyProxy(myProxyServer, myProxyPort);
CredentialInfo info = null;
try {
info = myproxy.info(getCredential().getCredential(),
myproxy_username, new String(passphrase));
} catch (final MyProxyException e) {
myLogger.error(e.getLocalizedMessage(), e);
}
return info.getEndTime();
}
@Override
public String getInterfaceInfo(String key) {
if (hostname == null) {
try {
final InetAddress addr = InetAddress.getLocalHost();
final byte[] ipAddr = addr.getAddress();
hostname = addr.getHostName();
} catch (final UnknownHostException e) {
hostname = "Unavailable";
}
} else if ("VERSION".equalsIgnoreCase(key)) {
return Integer.toString(ServiceInterface.API_VERSION);
} else if ("NAME".equalsIgnoreCase(key)) {
return "Local serviceinterface";
} else if ("BACKEND_VERSION".equalsIgnoreCase(key)) {
return BACKEND_VERSION;
}
return null;
}
public final String getTemplate(final String application)
throws NoSuchTemplateException {
final String temp = ServiceTemplateManagement.getTemplate(application);
if (StringUtils.isBlank(temp)) {
throw new NoSuchTemplateException(
"Could not find template for application: " + application
+ ".");
}
return temp;
}
@Override
protected final synchronized User getUser() {
if (user == null) {
this.user = User.createUser(getCredential(), this);
}
user.setCredential(getCredential());
return user;
}
public final String[] listHostedApplicationTemplates() {
return ServiceTemplateManagement.getAllAvailableApplications();
}
public final void login(final String username, final String password) {
this.myproxy_username = username;
this.passphrase = password.toCharArray();
try {
// init database and make sure everything is all right
HibernateSessionFactory.getSessionFactory();
} catch (final Throwable e) {
throw new RuntimeException("Could not initialize database.", e);
}
try {
getCredential();
} catch (final RuntimeException re) {
throw re;
} catch (final Exception e) {
// e.printStackTrace();
throw new NoValidCredentialException("No valid credential: "
+ e.getLocalizedMessage());
}
}
public final String logout() {
Arrays.fill(passphrase, 'x');
return null;
}
}
| true |
c0610fc0a2f8e49fd5ce4ae3494677a8527271a8
|
Java
|
AudientZhuang/community_management
|
/src/main/java/com/saltedfish/community_management/filter/StatelessAuthcFilter.java
|
UTF-8
| 2,359 | 2.265625 | 2 |
[] |
no_license
|
package com.saltedfish.community_management.filter;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author Audient
* @date 2020/6/3
*/
public class StatelessAuthcFilter extends PassThruAuthenticationFilter {
private Logger log = LoggerFactory.getLogger(this.getClass());
//获取请求方法,若为OPTIONS请求直接返回True放行
@Override
public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
log.info("OPTIONS方法直接返回True");
return true;
}
return super.onPreHandle(request, response, mappedValue);
}
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
HttpServletResponse httpResp = WebUtils.toHttp(response);
HttpServletRequest httpReq = WebUtils.toHttp(request);
/** 系统重定向会默认把请求头清空,这里通过拦截器重新设置请求头,解决跨域问题 */
httpResp.addHeader("Access-Control-Allow-Origin", httpReq.getHeader("Origin"));
httpResp.addHeader("Access-Control-Allow-Headers", "*");
httpResp.addHeader("Access-Control-Allow-Methods", "*");
httpResp.addHeader("Access-Control-Allow-Credentials", "true");
if (isLoginRequest(request, response)) {
return true;
} else {
saveRequestAndRedirectToLogin(request, response);
return false;
}
}
}
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.