blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
77955a60d348c8c2d3ab6b11114f2a88133444fd
25,589,415,194,483
97c94c34dcb6e7ea5b3b15be4b4cac7b733efaf7
/src/main/java/co/uk/plumrm/kata01_TDD/MyLibrary.java
74c1ebd39aca24d71fac352849690869f6b18416
[]
no_license
MarkPlumridge/kata01_TDD
https://github.com/MarkPlumridge/kata01_TDD
53a32b253511f42b4a9f5da49249fedaf28ff38a
0eae2e9ca19ae5626afe04b687f1f9098626dead
refs/heads/master
2020-04-13T05:04:26.235000
2019-01-20T10:23:04
2019-01-20T10:23:04
162,981,028
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package co.uk.plumrm.kata01_TDD; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class MyLibrary { private List<Book> library = new ArrayList<Book>(); private static final MyLibrary INSTANCE = new MyLibrary(); private MyLibrary() { } public static MyLibrary getINSTANCE() { return INSTANCE; } public List<Book> filterByScore(int maxValue) { return library.stream() .filter( (book)-> book.getRating() > maxValue) .collect(Collectors.toList()); } public void addBook(Book book) { library.add(book); } public int getBookCount() { return library.size(); } /** * This is very powerful and allows the client to filter and use lambdas * @return */ public Stream<Book> getStream() { return library.stream(); } public List filterByAuthorLamda(String author) { List<Book> filteredList = library.stream() .filter( (book) -> book.getAuthor().compareTo(author) == 0) .collect(Collectors.toList()); return filteredList; } public List filterByAuthorForEach(String author) { List<Book> filteredList = new ArrayList<>(); for (Book book: library) { if (book.getAuthor().compareTo(author) == 0) { filteredList.add(book); } } return filteredList; } public List<Book> filterByAuthorForI(String author) { List<Book> filteredList = new ArrayList<>(); for (int i = 0; i < library.size(); i++) { if (library.get(i).getAuthor().compareTo(author) == 0) { filteredList.add(library.get(i)); } } return filteredList; } }
UTF-8
Java
1,887
java
MyLibrary.java
Java
[]
null
[]
package co.uk.plumrm.kata01_TDD; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class MyLibrary { private List<Book> library = new ArrayList<Book>(); private static final MyLibrary INSTANCE = new MyLibrary(); private MyLibrary() { } public static MyLibrary getINSTANCE() { return INSTANCE; } public List<Book> filterByScore(int maxValue) { return library.stream() .filter( (book)-> book.getRating() > maxValue) .collect(Collectors.toList()); } public void addBook(Book book) { library.add(book); } public int getBookCount() { return library.size(); } /** * This is very powerful and allows the client to filter and use lambdas * @return */ public Stream<Book> getStream() { return library.stream(); } public List filterByAuthorLamda(String author) { List<Book> filteredList = library.stream() .filter( (book) -> book.getAuthor().compareTo(author) == 0) .collect(Collectors.toList()); return filteredList; } public List filterByAuthorForEach(String author) { List<Book> filteredList = new ArrayList<>(); for (Book book: library) { if (book.getAuthor().compareTo(author) == 0) { filteredList.add(book); } } return filteredList; } public List<Book> filterByAuthorForI(String author) { List<Book> filteredList = new ArrayList<>(); for (int i = 0; i < library.size(); i++) { if (library.get(i).getAuthor().compareTo(author) == 0) { filteredList.add(library.get(i)); } } return filteredList; } }
1,887
0.571807
0.568627
94
19.074469
22.116346
76
false
false
0
0
0
0
0
0
0.234043
false
false
7
cbf06005e11ccab003e9b8f382118f02d4562eb6
4,372,276,734,511
c7dc8f03385c970cfec3da708f95402b60cf7ed8
/harec-web/src/main/java/pe/com/bbva/harec/model/Producto.java
fb526a377a83d884092c4926062caf3cb1ea6dee
[]
no_license
balderasalberto/sarx3
https://github.com/balderasalberto/sarx3
021d5ba65d1c5f08e97e1ea6c22361d3cefd45b1
75c3074034136106bcfd320e11143f500aebcbce
refs/heads/master
2021-01-10T14:04:07.931000
2014-09-11T15:50:42
2014-09-11T15:50:42
36,672,608
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pe.com.bbva.harec.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import pe.com.bbva.harec.exception.ValidacionException; import pe.com.bbva.harec.util.Constante; import pe.com.bbva.harec.util.GeneradorID; import pe.com.bbva.harec.util.Validador; import pe.com.bbva.harec.util.beanbase.AuditoriaBean; /** * The persistent class for the PRODUCTO database table. * */ @Entity @Table(name="TAX_PRODUCTO", schema=Constante.SCHEMA.HAREC) public class Producto extends AuditoriaBean implements Validador, GeneradorID { /** * */ private static final long serialVersionUID = -7239692478605267273L; @Id @Column(unique=true, nullable=false, precision=16) private Long id; @Column(nullable=false, length=20) private String codigo; @Column(name="CODIGO_SAR", length=20) private String codigoSar; @Column(nullable=false, length=400) private String nombre; @Column(name="NOMBRE_SAR", length=400) private String nombreSar; @ManyToOne @JoinColumn(name="TIPO_PRODUCTO", nullable=false) private Valor tipoProducto; @ManyToOne @JoinColumn(name="SBS_PRODUCTO") private ProductoSBS sbsProducto; @ManyToOne @JoinColumn(name="ESTADO", nullable=false) private Valor estado; /*@OneToMany(mappedBy="productoBean") private List<Requerimiento> requerimientos; @OneToMany(mappedBy="taxProducto") private List<Taxonomia> taxTaxonomias;*/ public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getCodigoSar() { return codigoSar; } public void setCodigoSar(String codigoSar) { this.codigoSar = codigoSar; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getNombreSar() { return nombreSar; } public void setNombreSar(String nombreSar) { this.nombreSar = nombreSar; } public Valor getTipoProducto() { return tipoProducto; } public void setTipoProducto(Valor tipoProducto) { this.tipoProducto = tipoProducto; } public ProductoSBS getSbsProducto() { return sbsProducto; } public void setSbsProducto(ProductoSBS sbsProducto) { this.sbsProducto = sbsProducto; } public Valor getEstado() { return estado; } public void setEstado(Valor estado) { this.estado = estado; } @Transient public String getCodigoNombre(){ return codigo + " - " + nombre; } @Override public int hashCode() { HashCodeBuilder hashCodeBuilder = new HashCodeBuilder(3, 7); hashCodeBuilder.append(codigo); return hashCodeBuilder.toHashCode(); } @Override public boolean equals(Object obj) { boolean equals = false; if (obj instanceof Producto) { Producto bean = (Producto) obj; equals = (new EqualsBuilder().append(codigo, bean.codigo)) .isEquals(); } return equals; } @Override public void validar() { if(StringUtils.isBlank(codigo)) { throw new ValidacionException(Constante.CODIGO_MENSAJE.VALIDAR_TEXTBOX, new Object[]{"Código"}); } if(tipoProducto == null || tipoProducto.getId() == null) { throw new ValidacionException(Constante.CODIGO_MENSAJE.VALIDAR_COMBOBOX, new Object[]{"Tipo Producto"}); } if(StringUtils.isBlank(nombre)) { throw new ValidacionException(Constante.CODIGO_MENSAJE.VALIDAR_TEXTBOX, new Object[]{"Nombre"}); } if(sbsProducto == null || sbsProducto.getId() == null) { throw new ValidacionException(Constante.CODIGO_MENSAJE.VALIDAR_COMBOBOX, new Object[]{"Producto SBS"}); } if(estado == null || estado.getId() == null) { throw new ValidacionException(Constante.CODIGO_MENSAJE.VALIDAR_COMBOBOX, new Object[]{"Estado"}); } int codigoMaxLength = 10; if(codigo.length() > codigoMaxLength) { throw new ValidacionException(Constante.CODIGO_MENSAJE.VALIDAR_MAX_TAMANHO, new Object[]{"Código", codigoMaxLength}); } int nombreMaxLength = 200; if(nombre.length() >= nombreMaxLength) { throw new ValidacionException(Constante.CODIGO_MENSAJE.VALIDAR_MAX_TAMANHO, new Object[]{"Nombre", nombreMaxLength}); } } }
UTF-8
Java
4,679
java
Producto.java
Java
[]
null
[]
package pe.com.bbva.harec.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import pe.com.bbva.harec.exception.ValidacionException; import pe.com.bbva.harec.util.Constante; import pe.com.bbva.harec.util.GeneradorID; import pe.com.bbva.harec.util.Validador; import pe.com.bbva.harec.util.beanbase.AuditoriaBean; /** * The persistent class for the PRODUCTO database table. * */ @Entity @Table(name="TAX_PRODUCTO", schema=Constante.SCHEMA.HAREC) public class Producto extends AuditoriaBean implements Validador, GeneradorID { /** * */ private static final long serialVersionUID = -7239692478605267273L; @Id @Column(unique=true, nullable=false, precision=16) private Long id; @Column(nullable=false, length=20) private String codigo; @Column(name="CODIGO_SAR", length=20) private String codigoSar; @Column(nullable=false, length=400) private String nombre; @Column(name="NOMBRE_SAR", length=400) private String nombreSar; @ManyToOne @JoinColumn(name="TIPO_PRODUCTO", nullable=false) private Valor tipoProducto; @ManyToOne @JoinColumn(name="SBS_PRODUCTO") private ProductoSBS sbsProducto; @ManyToOne @JoinColumn(name="ESTADO", nullable=false) private Valor estado; /*@OneToMany(mappedBy="productoBean") private List<Requerimiento> requerimientos; @OneToMany(mappedBy="taxProducto") private List<Taxonomia> taxTaxonomias;*/ public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getCodigoSar() { return codigoSar; } public void setCodigoSar(String codigoSar) { this.codigoSar = codigoSar; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getNombreSar() { return nombreSar; } public void setNombreSar(String nombreSar) { this.nombreSar = nombreSar; } public Valor getTipoProducto() { return tipoProducto; } public void setTipoProducto(Valor tipoProducto) { this.tipoProducto = tipoProducto; } public ProductoSBS getSbsProducto() { return sbsProducto; } public void setSbsProducto(ProductoSBS sbsProducto) { this.sbsProducto = sbsProducto; } public Valor getEstado() { return estado; } public void setEstado(Valor estado) { this.estado = estado; } @Transient public String getCodigoNombre(){ return codigo + " - " + nombre; } @Override public int hashCode() { HashCodeBuilder hashCodeBuilder = new HashCodeBuilder(3, 7); hashCodeBuilder.append(codigo); return hashCodeBuilder.toHashCode(); } @Override public boolean equals(Object obj) { boolean equals = false; if (obj instanceof Producto) { Producto bean = (Producto) obj; equals = (new EqualsBuilder().append(codigo, bean.codigo)) .isEquals(); } return equals; } @Override public void validar() { if(StringUtils.isBlank(codigo)) { throw new ValidacionException(Constante.CODIGO_MENSAJE.VALIDAR_TEXTBOX, new Object[]{"Código"}); } if(tipoProducto == null || tipoProducto.getId() == null) { throw new ValidacionException(Constante.CODIGO_MENSAJE.VALIDAR_COMBOBOX, new Object[]{"Tipo Producto"}); } if(StringUtils.isBlank(nombre)) { throw new ValidacionException(Constante.CODIGO_MENSAJE.VALIDAR_TEXTBOX, new Object[]{"Nombre"}); } if(sbsProducto == null || sbsProducto.getId() == null) { throw new ValidacionException(Constante.CODIGO_MENSAJE.VALIDAR_COMBOBOX, new Object[]{"Producto SBS"}); } if(estado == null || estado.getId() == null) { throw new ValidacionException(Constante.CODIGO_MENSAJE.VALIDAR_COMBOBOX, new Object[]{"Estado"}); } int codigoMaxLength = 10; if(codigo.length() > codigoMaxLength) { throw new ValidacionException(Constante.CODIGO_MENSAJE.VALIDAR_MAX_TAMANHO, new Object[]{"Código", codigoMaxLength}); } int nombreMaxLength = 200; if(nombre.length() >= nombreMaxLength) { throw new ValidacionException(Constante.CODIGO_MENSAJE.VALIDAR_MAX_TAMANHO, new Object[]{"Nombre", nombreMaxLength}); } } }
4,679
0.704725
0.6966
191
22.497383
24.948717
120
false
false
0
0
0
0
0
0
1.539267
false
false
7
cdc402ca914ac2a590d7629a9aadd1f5e3f172cf
24,129,126,299,729
d0b7a6f69e2496d31a5b188b20161a5105498c24
/src/Bataille/Carte.java
13ea92bf8baf7387b45bf3b26d97c9a0e7015955
[]
no_license
Marc-Hu/BatailleCartes
https://github.com/Marc-Hu/BatailleCartes
45a9b9879c2e729d9a2a46c65cbd0a281be3f53e
4ab8b0ead40f79ce15798be99f63be382eba076a
refs/heads/master
2021-04-15T05:02:56.823000
2017-06-05T12:17:46
2017-06-05T12:17:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Bataille; /** * Classe représentant des cartes de jeu * @version 1.0 * @author Tony Clonier */ public class Carte { private int valeur; private String couleur; private String nomFichier; /*Constructeur*/ /** * Construit une instance de Carte * @param couleur Couleur de la carte(Carreau, Coeur, Trèfle ou Pique) * @param valeur Valeur de la carte(De 2 à 14 avec 11=Valet, ..., 14=As) */ public Carte(int valeur, String couleur){ this.valeur = valeur; this.couleur = couleur.toLowerCase(); this.nomFichier = this.nomCarte(); } /*Getters*/ /** * Retourne la couleur de la Carte * @return la couleur de la Carte */ public String getCouleur(){ return this.couleur; } /** * Retourne la valeur de la Carte * @return la valeur de la Carte */ public int getValeur(){ return this.valeur; } /** * Retourne la valeur de la Carte * @return la valeur de la Carte */ public String getNomFichier(){ return this.nomFichier; } /*Méthodes*/ /** * Retourne une chaîne de caractères contenant les informations de la Carte */ public String toString(){ return this.getValeur()+" de "+this.getCouleur(); } /** * Vérifie si la Carte courante a une plus grande valeur que la carte c * @param c La carte à comparer * @return True si la carte courante a une plus grande valeur que c */ public boolean estPlusForte(Carte c){ return this.getValeur() > c.getValeur(); } /** * Vérifie si la Carte courante a la même valeur que la carte c * @param c La carte à comparer * @return True si la carte courante a la même valeur que c */ public boolean aMemeValeur(Carte c){ return this.getValeur() == c.getValeur(); } /** * Retourne le nom du fichier correspondant aux valeurs des variables d'instance numeroCarte et couleurCarte * @return Le nom du fichier (String) */ public String nomCarte(){ String s = new String(); if(this.valeur < 10) s = "images/"+this.couleur+"_0"+this.valeur+".GIF"; else s = "images/"+this.couleur+"_"+this.valeur+".GIF"; return s; } }
UTF-8
Java
2,108
java
Carte.java
Java
[ { "context": "ntant des cartes de jeu\n * @version 1.0\n * @author Tony Clonier\n */\npublic class Carte {\n\n\tprivate int valeur;\n\tp", "end": 103, "score": 0.9995506405830383, "start": 91, "tag": "NAME", "value": "Tony Clonier" } ]
null
[]
package Bataille; /** * Classe représentant des cartes de jeu * @version 1.0 * @author <NAME> */ public class Carte { private int valeur; private String couleur; private String nomFichier; /*Constructeur*/ /** * Construit une instance de Carte * @param couleur Couleur de la carte(Carreau, Coeur, Trèfle ou Pique) * @param valeur Valeur de la carte(De 2 à 14 avec 11=Valet, ..., 14=As) */ public Carte(int valeur, String couleur){ this.valeur = valeur; this.couleur = couleur.toLowerCase(); this.nomFichier = this.nomCarte(); } /*Getters*/ /** * Retourne la couleur de la Carte * @return la couleur de la Carte */ public String getCouleur(){ return this.couleur; } /** * Retourne la valeur de la Carte * @return la valeur de la Carte */ public int getValeur(){ return this.valeur; } /** * Retourne la valeur de la Carte * @return la valeur de la Carte */ public String getNomFichier(){ return this.nomFichier; } /*Méthodes*/ /** * Retourne une chaîne de caractères contenant les informations de la Carte */ public String toString(){ return this.getValeur()+" de "+this.getCouleur(); } /** * Vérifie si la Carte courante a une plus grande valeur que la carte c * @param c La carte à comparer * @return True si la carte courante a une plus grande valeur que c */ public boolean estPlusForte(Carte c){ return this.getValeur() > c.getValeur(); } /** * Vérifie si la Carte courante a la même valeur que la carte c * @param c La carte à comparer * @return True si la carte courante a la même valeur que c */ public boolean aMemeValeur(Carte c){ return this.getValeur() == c.getValeur(); } /** * Retourne le nom du fichier correspondant aux valeurs des variables d'instance numeroCarte et couleurCarte * @return Le nom du fichier (String) */ public String nomCarte(){ String s = new String(); if(this.valeur < 10) s = "images/"+this.couleur+"_0"+this.valeur+".GIF"; else s = "images/"+this.couleur+"_"+this.valeur+".GIF"; return s; } }
2,102
0.662691
0.656966
91
22.032967
22.636375
111
false
false
0
0
0
0
0
0
1.32967
false
false
7
866d2bc49d16bf68bf5166ac215ac249607d3f42
11,166,914,975,170
06bd9a74f1525b56c66f35ec8d8614a613748568
/src/services/items/BoissonService.java
63789a558d1c4bba2b964ad657f41ab617c4f037
[ "MIT" ]
permissive
ElhadiMeriem/RestaurantManagement_JavaFX
https://github.com/ElhadiMeriem/RestaurantManagement_JavaFX
9e22b72254e3c40937af8586afa01d587ff9eb33
199658dbecac64783681cb21ea5acd84eb7798f7
refs/heads/master
2021-05-22T21:53:22.217000
2020-06-03T13:45:58
2020-06-03T13:45:58
253,113,222
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package services.items; import models.boissons.Boisson; import models.boissons.BoissonFactory; import models.boissons.BoissonType; import services.Service; import util.DatabaseConnection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class BoissonService implements Service<Boisson> { private static final String TYPE = "Boisson"; private DatabaseConnection connection; private static BoissonService instance; private BoissonService() { this.connection = DatabaseConnection.getInstance(); } public static BoissonService getInstance() { if (instance == null) instance = new BoissonService(); return instance; } @Override public Boisson create(Boisson object) { String query = String.format("INSERT INTO items(description, price, type) VALUES('%s', %f, 's%')", object.getDescription(), object.cost(), TYPE); connection.nonSelectQuery(query); query = "SELECT * FROM items ORDER BY id DESC"; ResultSet resultSet = connection.selectQuery(query); try { if (resultSet.next()) object.setId(resultSet.getInt("id")); } catch (SQLException e) { System.out.println(e.getMessage()); } return object; } @Override public void update(Boisson object) { String query = String.format("UPDATE items SET price = %f WHERE id = %d", object.cost(), object.getId()); connection.nonSelectQuery(query); } @Override public void delete(int id) { String query = String.format("DELETE FROM items WHERE id = %d", id); connection.nonSelectQuery(query); } @Override public Boisson selectOne(int id) { String query = String.format("SELECT * FROM items WHERE id = %d", id); ResultSet resultSet = connection.selectQuery(query); try { if (resultSet.next()) { Boisson boisson = BoissonFactory.getInstance().makeBoisson(BoissonType.valueOf(resultSet.getString("description"))); boisson.setId(resultSet.getInt("id")); return boisson; } } catch (SQLException e) { System.out.println(e.getMessage()); } return null; } @Override public List<Boisson> selectAll() { return filter("type = '" + TYPE + "'"); } @Override public List<Boisson> filter(String whereQuery) { List<Boisson> boissons = new ArrayList<>(); String query = "SELECT * FROM items WHERE "+ whereQuery; ResultSet resultSet = connection.selectQuery(query); try { if (resultSet.next()) { Boisson boisson = BoissonFactory.getInstance().makeBoisson(BoissonType.valueOf(resultSet.getString("description"))); boisson.setId(resultSet.getInt("id")); boissons.add(boisson); } } catch (SQLException e) { System.out.println(e.getMessage()); } return boissons; } }
UTF-8
Java
3,164
java
BoissonService.java
Java
[]
null
[]
package services.items; import models.boissons.Boisson; import models.boissons.BoissonFactory; import models.boissons.BoissonType; import services.Service; import util.DatabaseConnection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class BoissonService implements Service<Boisson> { private static final String TYPE = "Boisson"; private DatabaseConnection connection; private static BoissonService instance; private BoissonService() { this.connection = DatabaseConnection.getInstance(); } public static BoissonService getInstance() { if (instance == null) instance = new BoissonService(); return instance; } @Override public Boisson create(Boisson object) { String query = String.format("INSERT INTO items(description, price, type) VALUES('%s', %f, 's%')", object.getDescription(), object.cost(), TYPE); connection.nonSelectQuery(query); query = "SELECT * FROM items ORDER BY id DESC"; ResultSet resultSet = connection.selectQuery(query); try { if (resultSet.next()) object.setId(resultSet.getInt("id")); } catch (SQLException e) { System.out.println(e.getMessage()); } return object; } @Override public void update(Boisson object) { String query = String.format("UPDATE items SET price = %f WHERE id = %d", object.cost(), object.getId()); connection.nonSelectQuery(query); } @Override public void delete(int id) { String query = String.format("DELETE FROM items WHERE id = %d", id); connection.nonSelectQuery(query); } @Override public Boisson selectOne(int id) { String query = String.format("SELECT * FROM items WHERE id = %d", id); ResultSet resultSet = connection.selectQuery(query); try { if (resultSet.next()) { Boisson boisson = BoissonFactory.getInstance().makeBoisson(BoissonType.valueOf(resultSet.getString("description"))); boisson.setId(resultSet.getInt("id")); return boisson; } } catch (SQLException e) { System.out.println(e.getMessage()); } return null; } @Override public List<Boisson> selectAll() { return filter("type = '" + TYPE + "'"); } @Override public List<Boisson> filter(String whereQuery) { List<Boisson> boissons = new ArrayList<>(); String query = "SELECT * FROM items WHERE "+ whereQuery; ResultSet resultSet = connection.selectQuery(query); try { if (resultSet.next()) { Boisson boisson = BoissonFactory.getInstance().makeBoisson(BoissonType.valueOf(resultSet.getString("description"))); boisson.setId(resultSet.getInt("id")); boissons.add(boisson); } } catch (SQLException e) { System.out.println(e.getMessage()); } return boissons; } }
3,164
0.609355
0.609355
123
24.723577
26.957148
132
false
false
0
0
0
0
0
0
0.439024
false
false
7
ffec03ccaf39040e054dfad1655e2924576779df
26,070,451,528,592
d1a6fe288fc052e6801b6e2796c31bd5ab59eb26
/magicalLibrary/src/main/java/com/magical/library/load/core/TargetContext.java
c5aadb90b43022cc3078493d037d22ab76416300
[]
no_license
liangdy/CloudStation
https://github.com/liangdy/CloudStation
6191eede736c065c47fd0654b515157f744730fd
df863be909308448daf75af88e4d84b4f25fa800
refs/heads/master
2021-09-15T20:26:19.745000
2018-06-10T13:21:13
2018-06-10T13:21:13
111,208,626
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.magical.library.load.core; import android.content.Context; import android.view.View; import android.view.ViewGroup; /** * Project: CloudStation * FileName: TargetContext.java * Description: * Creator: ldy * Email: 1020118243@qq.com * Crete Date: 10/3/17 8:04 PM * Editor: ldy * Modify Date: 10/3/17 8:04 PM * Remark: */ public class TargetContext { private Context context; private ViewGroup parentView; private View oldContent; private int childIndex; public TargetContext(Context context, ViewGroup parentView, View oldContent, int childIndex) { this.context = context; this.parentView = parentView; this.oldContent = oldContent; this.childIndex = childIndex; } public Context getContext() { return context; } View getOldContent() { return oldContent; } int getChildIndex() { return childIndex; } ViewGroup getParentView() { return parentView; } }
UTF-8
Java
999
java
TargetContext.java
Java
[ { "context": "me: TargetContext.java\n * Description:\n * Creator: ldy\n * Email: 1020118243@qq.com\n * Crete Date: 10/3/1", "end": 222, "score": 0.9995943307876587, "start": 219, "tag": "USERNAME", "value": "ldy" }, { "context": "xt.java\n * Description:\n * Creator: ldy\n * Email: 1020118243@qq.com\n * Crete Date: 10/3/17 8:04 PM\n * Editor: ldy\n * ", "end": 250, "score": 0.9998838305473328, "start": 233, "tag": "EMAIL", "value": "1020118243@qq.com" }, { "context": "3@qq.com\n * Crete Date: 10/3/17 8:04 PM\n * Editor: ldy\n * Modify Date: 10/3/17 8:04 PM\n * Remark:\n */\npu", "end": 296, "score": 0.9994175434112549, "start": 293, "tag": "USERNAME", "value": "ldy" } ]
null
[]
package com.magical.library.load.core; import android.content.Context; import android.view.View; import android.view.ViewGroup; /** * Project: CloudStation * FileName: TargetContext.java * Description: * Creator: ldy * Email: <EMAIL> * Crete Date: 10/3/17 8:04 PM * Editor: ldy * Modify Date: 10/3/17 8:04 PM * Remark: */ public class TargetContext { private Context context; private ViewGroup parentView; private View oldContent; private int childIndex; public TargetContext(Context context, ViewGroup parentView, View oldContent, int childIndex) { this.context = context; this.parentView = parentView; this.oldContent = oldContent; this.childIndex = childIndex; } public Context getContext() { return context; } View getOldContent() { return oldContent; } int getChildIndex() { return childIndex; } ViewGroup getParentView() { return parentView; } }
989
0.665666
0.63964
46
20.717392
17.416462
98
false
false
0
0
0
0
0
0
0.413043
false
false
7
ad8691901acbaf4a84b2f63d7c31685425545ddf
807,453,859,405
3a2585bb52e4edc4cc8b126193841e40550af5fc
/yjWorkspace/0308 까지 수업/chap05-array-lecture-source/src/com/greedy/section03/array_copy/ArrayIm.java
49acb3ae0bdd9c52e3a4958532a060d2aa8df796
[]
no_license
sah604/ncs_test
https://github.com/sah604/ncs_test
dae26774738d46bf2329439e3da2f17c080d9aff
d9f53ce283537bb188492e0459705c7c73db812d
refs/heads/master
2023-03-16T00:13:11.171000
2021-03-15T06:13:08
2021-03-15T06:13:08
347,855,801
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.greedy.section03.array_copy; public class ArrayIm { int[] arr = new int[5]; }
UTF-8
Java
105
java
ArrayIm.java
Java
[]
null
[]
package com.greedy.section03.array_copy; public class ArrayIm { int[] arr = new int[5]; }
105
0.619048
0.590476
8
11.125
14.460614
40
false
false
0
0
0
0
0
0
0.625
false
false
7
4947c6764b129fceff90a0281ba06aaa62c7999f
7,232,724,932,346
0e77336566fd78e974f97124d77c734673573be3
/ZuulServer/src/main/java/com/zuul/filter/AccessFilter.java
9c96ef5911d78f508de90f82e3a8e252063b33b6
[]
no_license
1552834747/SpringCloud
https://github.com/1552834747/SpringCloud
334d231c87f30f1acbb8f36567c4cad3460450a6
72e2e5cdd29ca37280bfbbf6624625577b3f236a
refs/heads/master
2020-09-04T10:52:51.946000
2019-11-08T08:04:20
2019-11-08T08:04:20
219,714,062
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zuul.filter; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.exception.ZuulException; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class AccessFilter extends ZuulFilter { @Value("${server.port}") private String serverPort; /** * 过滤器的类型,它决定过滤器在请求的哪个生命周期中执行, * pre:请求被路由之前做一些前置工作 ,比如请求和校验 * routing : 在路由请求时被调用,路由请求转发,即是将请求转发到具体的服务实例上去. * post : 在routing 和 error过滤器之后被调用..所以post类型的过滤器可以对请求结果进行一些加工 * error :处理请求发生错误时调用 */ @Override public String filterType() { return "pre"; } /** * 过滤器的执行顺序. * 在一个阶段有多个过滤器时,需要用此指定过滤顺序 * 数值越小优先级越高 */ @Override public int filterOrder() { return 0; } /** * 判断过滤器是否执行,直接返回true,代表对所有请求过滤 * 此方法指定过滤范围 */ @Override public boolean shouldFilter() { return true; } /** * 过滤的具体逻辑 */ @Override public Object run() throws ZuulException { // 正常执行调用其他服务接口... System.out.println("网关执行端口号:" + serverPort); return null; } }
UTF-8
Java
1,579
java
AccessFilter.java
Java
[]
null
[]
package com.zuul.filter; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.exception.ZuulException; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class AccessFilter extends ZuulFilter { @Value("${server.port}") private String serverPort; /** * 过滤器的类型,它决定过滤器在请求的哪个生命周期中执行, * pre:请求被路由之前做一些前置工作 ,比如请求和校验 * routing : 在路由请求时被调用,路由请求转发,即是将请求转发到具体的服务实例上去. * post : 在routing 和 error过滤器之后被调用..所以post类型的过滤器可以对请求结果进行一些加工 * error :处理请求发生错误时调用 */ @Override public String filterType() { return "pre"; } /** * 过滤器的执行顺序. * 在一个阶段有多个过滤器时,需要用此指定过滤顺序 * 数值越小优先级越高 */ @Override public int filterOrder() { return 0; } /** * 判断过滤器是否执行,直接返回true,代表对所有请求过滤 * 此方法指定过滤范围 */ @Override public boolean shouldFilter() { return true; } /** * 过滤的具体逻辑 */ @Override public Object run() throws ZuulException { // 正常执行调用其他服务接口... System.out.println("网关执行端口号:" + serverPort); return null; } }
1,579
0.63034
0.629468
55
19.854546
17.210375
65
false
false
0
0
0
0
0
0
0.345455
false
false
7
75926486ed117928ce9d3e90fa5a834ab43e4768
27,023,934,233,437
3b91cef578149eed010ac2a6fbb0999540f98f87
/src/PolymorphicVORows/Project/src/test/example/MenImpl.java
c4ea5a2925aacd563ec5b21856a41b2f021c2359
[ "UPL-1.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
amruth006/adf-samples-master
https://github.com/amruth006/adf-samples-master
16314bd8b132c526e314c9ab3d5e5b7030126029
72636df21c9df5ddcc78752ff9e8da51928d033e
refs/heads/master
2021-05-04T16:42:50.871000
2018-02-05T05:07:23
2018-02-05T05:07:23
120,256,539
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Copyright 2010, 2017, Oracle and/or its affiliates. All rights reserved. */ package test.example; // --------------------------------------------------------------------- // --- File generated by Oracle ADF Business Components Design Time. // --- Custom code may be added to this class. // --------------------------------------------------------------------- public class MenImpl extends PeopleImpl { /** * * This is the default constructor (do not remove) */ public MenImpl() { } /**Sample exportable method. */ public void sampleMenImplExportable() { } /**Sample exportable method. */ public void sampleMenImplExportable2(String testParam1) { } }
UTF-8
Java
741
java
MenImpl.java
Java
[]
null
[]
/* Copyright 2010, 2017, Oracle and/or its affiliates. All rights reserved. */ package test.example; // --------------------------------------------------------------------- // --- File generated by Oracle ADF Business Components Design Time. // --- Custom code may be added to this class. // --------------------------------------------------------------------- public class MenImpl extends PeopleImpl { /** * * This is the default constructor (do not remove) */ public MenImpl() { } /**Sample exportable method. */ public void sampleMenImplExportable() { } /**Sample exportable method. */ public void sampleMenImplExportable2(String testParam1) { } }
741
0.502024
0.488529
25
27.68
27.168688
78
false
false
0
0
0
0
0
0
0.12
false
false
7
ef431417e92fc2d15ba397c03c66783edb0891b7
27,023,934,235,669
3dcc6b666a10919e9a9b2965c1803007ab6663e2
/src/test/java/tests/BaseTest.java
51f0fc45cc94ac8d7df22e87110c3e72a3077b9b
[]
no_license
MohamedGaberM/BlockChainTask
https://github.com/MohamedGaberM/BlockChainTask
a42d9de5c05679c90226321daddedc9dacdaa8ad
0c62b7613fa5b5509ac9d27fefb3e9321fedfdfd
refs/heads/main
2023-08-23T11:31:47.337000
2021-09-26T01:23:38
2021-09-26T01:23:38
410,418,689
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tests; import Pages.HomePage; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; public class BaseTest { public BaseTest(){ } public HomePage homePage; protected WebDriver driver; public String BASE_URL_WIX_SITE = "https://arielkiell.wixsite.com/interview"; @BeforeMethod(alwaysRun = true) public void setUp (){ WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); driver.navigate().to(BASE_URL_WIX_SITE); Assert.assertEquals(BASE_URL_WIX_SITE,driver.getCurrentUrl()); driver.manage().window().maximize(); homePage=new HomePage(driver); } @AfterMethod(alwaysRun = true) public void tearDown() { driver.close(); } }
UTF-8
Java
939
java
BaseTest.java
Java
[ { "context": "e tests;\n\nimport Pages.HomePage;\nimport io.github.bonigarcia.wdm.WebDriverManager;\nimport org.openqa.selenium.", "end": 66, "score": 0.999605655670166, "start": 56, "tag": "USERNAME", "value": "bonigarcia" } ]
null
[]
package tests; import Pages.HomePage; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; public class BaseTest { public BaseTest(){ } public HomePage homePage; protected WebDriver driver; public String BASE_URL_WIX_SITE = "https://arielkiell.wixsite.com/interview"; @BeforeMethod(alwaysRun = true) public void setUp (){ WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); driver.navigate().to(BASE_URL_WIX_SITE); Assert.assertEquals(BASE_URL_WIX_SITE,driver.getCurrentUrl()); driver.manage().window().maximize(); homePage=new HomePage(driver); } @AfterMethod(alwaysRun = true) public void tearDown() { driver.close(); } }
939
0.70394
0.70394
33
27.484848
20.589968
81
false
false
0
0
0
0
0
0
0.575758
false
false
7
73ee3c512538da0956aef8d4b52f54391947e1eb
31,894,427,147,134
68e403b2eb1bc24f7b3b9d41011d347ad08c1d8e
/blog/blog-question/src/main/java/com/tlk/blog/question/service/IQuestionService.java
51745f0a61f07a7fbf12b9b29b82d8375ed0592f
[]
no_license
tlk-dsg/blog_springboot_vue
https://github.com/tlk-dsg/blog_springboot_vue
b196f342d4cf4663be82669cbde3e0a9dbe26f6d
41acdc8626e2d95a35e48df2d5967ec9f609a6c5
refs/heads/master
2023-04-25T09:31:10.417000
2021-05-14T07:03:50
2021-05-14T07:03:50
367,084,935
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tlk.blog.question.service; import com.tlk.blog.entities.Question; import com.baomidou.mybatisplus.extension.service.IService; import com.tlk.blog.feign.req.UserInfoREQ; import com.tlk.blog.question.req.QuestionUserREQ; import com.tlk.blog.util.base.BaseRequest; import com.tlk.blog.util.base.Result; /** * <p> * 问题信息表 服务类 * </p> * * @author tlk * @since 2021-05-11 */ public interface IQuestionService extends IService<Question> { Result findHotList(BaseRequest<Question> req); Result findNewList(BaseRequest<Question> req); Result findWaitList(BaseRequest<Question> req); Result findListByLabelId(BaseRequest<Question> req, String labelId); Result findById(String id); Result updateViewCount(String id); Result updateOrSave(Question question); Result deleteById(String id); Result updateThumhup(String id, int count); Result findListByUserId(QuestionUserREQ req); Result getQuestionTotal(); boolean updateUserInfo(UserInfoREQ req); }
UTF-8
Java
1,077
java
IQuestionService.java
Java
[ { "context": "/**\r\n * <p>\r\n * 问题信息表 服务类\r\n * </p>\r\n *\r\n * @author tlk\r\n * @since 2021-05-11\r\n */\r\npublic interface IQue", "end": 377, "score": 0.9996588230133057, "start": 374, "tag": "USERNAME", "value": "tlk" } ]
null
[]
package com.tlk.blog.question.service; import com.tlk.blog.entities.Question; import com.baomidou.mybatisplus.extension.service.IService; import com.tlk.blog.feign.req.UserInfoREQ; import com.tlk.blog.question.req.QuestionUserREQ; import com.tlk.blog.util.base.BaseRequest; import com.tlk.blog.util.base.Result; /** * <p> * 问题信息表 服务类 * </p> * * @author tlk * @since 2021-05-11 */ public interface IQuestionService extends IService<Question> { Result findHotList(BaseRequest<Question> req); Result findNewList(BaseRequest<Question> req); Result findWaitList(BaseRequest<Question> req); Result findListByLabelId(BaseRequest<Question> req, String labelId); Result findById(String id); Result updateViewCount(String id); Result updateOrSave(Question question); Result deleteById(String id); Result updateThumhup(String id, int count); Result findListByUserId(QuestionUserREQ req); Result getQuestionTotal(); boolean updateUserInfo(UserInfoREQ req); }
1,077
0.717248
0.709708
44
22.113636
22.571318
72
false
false
0
0
0
0
0
0
0.477273
false
false
7
905379494e4bfab9a3bfe0fb80d2c9d9b9e891de
33,105,607,925,161
d7694cd259b194da8bac82bdf4a4a160b0e66b61
/imdb_api/src/main/java/nl/inholland/layers/persistence/MovieDAO.java
58d8eb9cbc673c0467118bd1cd88d2c756907040
[]
no_license
JeroenRoos/ServerSideJava_IMDbApi
https://github.com/JeroenRoos/ServerSideJava_IMDbApi
c049dee45517411ee3fedeff76ed6a33bdc070f4
9fa4dc3c41374cca2f04c278111cb433b236c85f
refs/heads/master
2020-03-22T01:36:16.746000
2018-01-12T12:30:13
2018-01-12T12:30:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 nl.inholland.layers.persistence; import java.util.List; import javax.inject.Inject; import nl.inholland.layers.model.Actor; import nl.inholland.layers.model.Comment; import nl.inholland.layers.model.Director; import nl.inholland.layers.model.Genre; import nl.inholland.layers.model.Movie; import org.bson.types.ObjectId; import org.mongodb.morphia.Datastore; import org.mongodb.morphia.query.Query; public class MovieDAO extends BaseDAO<Movie> { private Datastore ds; @Inject public MovieDAO(Datastore ds) { super(Movie.class, ds); this.ds = ds; } public List<Movie> getByRatingAndYearRange(int yearMin, int yearMax, int rating) { return createQuery() .field("year").greaterThanOrEq(yearMin) .field("year").lessThanOrEq(yearMax) .field("rating").greaterThanOrEq(rating) .asList(); } public List<Movie> getByActor(List<Actor> actors){ Query<Movie> query = ds.createQuery(Movie.class); query.filter("actors in", actors); return query.asList(); } public List<Movie> getByComments(List<Comment> comments){ Query<Movie> query = ds.createQuery(Movie.class); query.filter("comments in", comments); return query.asList(); } public List<Movie> getByGenre(Genre genre){ Query<Movie> query = ds.createQuery(Movie.class); query.filter("genre ==", genre); return query.asList(); } public List<Movie> getByYear(int year){ Query<Movie> query = ds.createQuery(Movie.class); query.filter("year ==", year); return query.asList(); } public List<Movie> getByDirector(List<Director> directors){ Query<Movie> query = ds.createQuery(Movie.class); query.filter("director in", directors); List<Movie> movies = query.asList(); return movies; } public void deleteManyById( List<ObjectId> objects){ Query<Movie> query = ds.createQuery(Movie.class); ds.delete(query.filter("_id in", objects)); } public List<Movie> getByYearAndGenre(Genre genre, int yearFrom, int yearTo, String sortKey){ Query<Movie> query = ds.createQuery(Movie.class); return query .field("year").greaterThanOrEq(yearFrom) .field("year").lessThanOrEq(yearTo) .filter("genre", genre) .order(sortKey) .asList(); } }
UTF-8
Java
2,793
java
MovieDAO.java
Java
[]
null
[]
/* * 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 nl.inholland.layers.persistence; import java.util.List; import javax.inject.Inject; import nl.inholland.layers.model.Actor; import nl.inholland.layers.model.Comment; import nl.inholland.layers.model.Director; import nl.inholland.layers.model.Genre; import nl.inholland.layers.model.Movie; import org.bson.types.ObjectId; import org.mongodb.morphia.Datastore; import org.mongodb.morphia.query.Query; public class MovieDAO extends BaseDAO<Movie> { private Datastore ds; @Inject public MovieDAO(Datastore ds) { super(Movie.class, ds); this.ds = ds; } public List<Movie> getByRatingAndYearRange(int yearMin, int yearMax, int rating) { return createQuery() .field("year").greaterThanOrEq(yearMin) .field("year").lessThanOrEq(yearMax) .field("rating").greaterThanOrEq(rating) .asList(); } public List<Movie> getByActor(List<Actor> actors){ Query<Movie> query = ds.createQuery(Movie.class); query.filter("actors in", actors); return query.asList(); } public List<Movie> getByComments(List<Comment> comments){ Query<Movie> query = ds.createQuery(Movie.class); query.filter("comments in", comments); return query.asList(); } public List<Movie> getByGenre(Genre genre){ Query<Movie> query = ds.createQuery(Movie.class); query.filter("genre ==", genre); return query.asList(); } public List<Movie> getByYear(int year){ Query<Movie> query = ds.createQuery(Movie.class); query.filter("year ==", year); return query.asList(); } public List<Movie> getByDirector(List<Director> directors){ Query<Movie> query = ds.createQuery(Movie.class); query.filter("director in", directors); List<Movie> movies = query.asList(); return movies; } public void deleteManyById( List<ObjectId> objects){ Query<Movie> query = ds.createQuery(Movie.class); ds.delete(query.filter("_id in", objects)); } public List<Movie> getByYearAndGenre(Genre genre, int yearFrom, int yearTo, String sortKey){ Query<Movie> query = ds.createQuery(Movie.class); return query .field("year").greaterThanOrEq(yearFrom) .field("year").lessThanOrEq(yearTo) .filter("genre", genre) .order(sortKey) .asList(); } }
2,793
0.614751
0.614751
91
29.692308
22.751738
96
false
false
0
0
0
0
0
0
0.56044
false
false
7
a8979ff54016de9ec98107e28d776ba830caaea3
33,629,593,935,345
5510cab72c500d7d27d749b160642afd1acdcfef
/src/main/java/org/thinkyard/app/wrapper/UserWrapper.java
c0784750bc7ef166c31059d7f129f5b6a323453d
[]
no_license
thinkyard/spring-boot-oauth2-mysql
https://github.com/thinkyard/spring-boot-oauth2-mysql
ab00b2f5e89368c2da3c1b3b98ead5cf16f0d3dc
cb21f9b197de026d9a7e58bb4c235e68f3c71a56
refs/heads/master
2021-05-15T21:43:07.415000
2017-10-11T13:44:44
2017-10-11T13:44:44
106,556,740
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.thinkyard.app.wrapper; import java.util.List; import lombok.Data; @Data public class UserWrapper { private String username; private String email; private String firstName; private String lastName; private List<RoleWrapper> roles; }
UTF-8
Java
257
java
UserWrapper.java
Java
[]
null
[]
package org.thinkyard.app.wrapper; import java.util.List; import lombok.Data; @Data public class UserWrapper { private String username; private String email; private String firstName; private String lastName; private List<RoleWrapper> roles; }
257
0.770428
0.770428
19
12.526316
13.019695
34
false
false
0
0
0
0
0
0
0.684211
false
false
7
5cdad0a4a459dd7b593785567b06722bc610f0b3
16,484,084,493,169
831697496698143ce98dd7bb579f117aaa8f9143
/app/src/main/java/com/example/cs246/medtracker/CalTest.java
98ed2d3dc650590c2741f31893c171b081662428
[]
no_license
kd7uns/MedTrackerUITest
https://github.com/kd7uns/MedTrackerUITest
62ed5cd25e6578f105e2c5c71240a8e15d98f4a5
99a1aefc922aea1fe714ef71040237e42659cad4
refs/heads/master
2021-01-10T08:52:32.890000
2016-03-05T03:33:53
2016-03-05T03:33:53
52,929,632
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.cs246.medtracker; import android.app.ProgressDialog; import android.content.ContentUris; import android.content.Intent; import android.provider.CalendarContract; import android.util.Log; import android.view.InputEvent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import android.content.Intent; import android.os.Bundle; import android.net.Uri; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.common.api.GoogleApiClient; import java.util.*; public class CalTest extends AppCompatActivity { /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ private GoogleApiClient client; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cal_test); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); final Button CalTestButton = (Button) findViewById(R.id.CalTestButton); CalTestButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ////////////////////////////////code Calendar cal = new GregorianCalendar(); cal.setTime(new Date()); cal.add(Calendar.MONTH, 2); long time = cal.getTime().getTime(); Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon(); builder.appendPath("time"); builder.appendPath(Long.toString(time)); Intent intent = new Intent(Intent.ACTION_VIEW, builder.build()); startActivity(intent); /* Intent intent = new Intent(Intent.ACTION_INSERT, CalendarContract.Events.CONTENT_URI); startActivity(intent); */ /* long startMillis = System.currentTimeMillis(); Uri.Builder builder2 = CalendarContract.CONTENT_URI.buildUpon(); builder2.appendPath("time"); ContentUris.appendId(builder2, startMillis); Intent intent = new Intent(Intent.ACTION_VIEW).setData(builder2.build()); startActivity(intent); */ } }); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); //inflate the menu; this adds items to the action //bar if it is present getMenuInflater().inflate(R.menu.main, menu); String title = "Menu List"; int groupID = Menu.NONE; int itemId = Menu.FIRST; int order = 103; menu.add(groupID, itemId, order, title); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.context_ScripTest: Intent item1 = new Intent(this, PrescriptionTest.class); this.startActivity(item1); break; case R.id.context_login: Intent item2 = new Intent(this, EmptyLogin.class); this.startActivity(item2); break; case R.id.context_Alerts: Intent item3 = new Intent(this, Alerts.class); this.startActivity(item3); break; case R.id.context_calTest: Intent item4 = new Intent(this, CalTest.class); this.startActivity(item4); break; default: return super.onOptionsItemSelected(item); } return true; } @Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "CalTest Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.example.cs246.medtracker/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); } @Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "CalTest Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.example.cs246.medtracker/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); } }
UTF-8
Java
6,620
java
CalTest.java
Java
[]
null
[]
package com.example.cs246.medtracker; import android.app.ProgressDialog; import android.content.ContentUris; import android.content.Intent; import android.provider.CalendarContract; import android.util.Log; import android.view.InputEvent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import android.content.Intent; import android.os.Bundle; import android.net.Uri; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.common.api.GoogleApiClient; import java.util.*; public class CalTest extends AppCompatActivity { /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ private GoogleApiClient client; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cal_test); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); final Button CalTestButton = (Button) findViewById(R.id.CalTestButton); CalTestButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ////////////////////////////////code Calendar cal = new GregorianCalendar(); cal.setTime(new Date()); cal.add(Calendar.MONTH, 2); long time = cal.getTime().getTime(); Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon(); builder.appendPath("time"); builder.appendPath(Long.toString(time)); Intent intent = new Intent(Intent.ACTION_VIEW, builder.build()); startActivity(intent); /* Intent intent = new Intent(Intent.ACTION_INSERT, CalendarContract.Events.CONTENT_URI); startActivity(intent); */ /* long startMillis = System.currentTimeMillis(); Uri.Builder builder2 = CalendarContract.CONTENT_URI.buildUpon(); builder2.appendPath("time"); ContentUris.appendId(builder2, startMillis); Intent intent = new Intent(Intent.ACTION_VIEW).setData(builder2.build()); startActivity(intent); */ } }); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); //inflate the menu; this adds items to the action //bar if it is present getMenuInflater().inflate(R.menu.main, menu); String title = "Menu List"; int groupID = Menu.NONE; int itemId = Menu.FIRST; int order = 103; menu.add(groupID, itemId, order, title); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.context_ScripTest: Intent item1 = new Intent(this, PrescriptionTest.class); this.startActivity(item1); break; case R.id.context_login: Intent item2 = new Intent(this, EmptyLogin.class); this.startActivity(item2); break; case R.id.context_Alerts: Intent item3 = new Intent(this, Alerts.class); this.startActivity(item3); break; case R.id.context_calTest: Intent item4 = new Intent(this, CalTest.class); this.startActivity(item4); break; default: return super.onOptionsItemSelected(item); } return true; } @Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "CalTest Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.example.cs246.medtracker/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); } @Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "CalTest Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.example.cs246.medtracker/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); } }
6,620
0.621148
0.616918
176
36.613636
25.896399
95
false
false
0
0
0
0
0
0
0.642045
false
false
7
a8b2365b84b596da346eaf855ed163428ade460f
4,733,053,972,651
e799117f634d402e207a6a5e2a8769c5511e2d70
/PriceConvertorApp/app/src/main/java/com/example/priceconvertorapp/data/net/RetrofitClient.java
9fc68b01096e2fcc0699c6babb6a1340eb66ce51
[]
no_license
Lemblematik/priceConvertor_Test_epay
https://github.com/Lemblematik/priceConvertor_Test_epay
30816d8ac37349f336d7feb79d86a232b491608a
8e46568c8d7dc150772e3cd92658f793cfcf72a6
refs/heads/master
2023-01-24T10:22:18.015000
2020-11-25T10:48:54
2020-11-25T10:48:54
315,908,746
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.priceconvertorapp.data.net; import com.example.priceconvertorapp.data.model.CurrencyResponse; import okhttp3.OkHttpClient; import retrofit2.Call; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class RetrofitClient { /* private final String CURRENCY_BASE_URL = "https://api.exchangeratesapi.io/"; private CurrencyApi currency; RetrofitClient(){ OkHttpClient okHttpClient = new OkHttpClient .Builder().build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(CURRENCY_BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) .build(); currency = retrofit.create(CurrencyApi.class); } public Call<CurrencyResponse> getCurrency () { return currency.getAllCurrency(); } */ private static Retrofit retrofit; private static final String BASE_URL = "https://api.exchangeratesapi.io/"; public static Retrofit getRetrofitInstance() { if (retrofit == null) { retrofit = new retrofit2.Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; } }
UTF-8
Java
1,346
java
RetrofitClient.java
Java
[]
null
[]
package com.example.priceconvertorapp.data.net; import com.example.priceconvertorapp.data.model.CurrencyResponse; import okhttp3.OkHttpClient; import retrofit2.Call; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class RetrofitClient { /* private final String CURRENCY_BASE_URL = "https://api.exchangeratesapi.io/"; private CurrencyApi currency; RetrofitClient(){ OkHttpClient okHttpClient = new OkHttpClient .Builder().build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(CURRENCY_BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) .build(); currency = retrofit.create(CurrencyApi.class); } public Call<CurrencyResponse> getCurrency () { return currency.getAllCurrency(); } */ private static Retrofit retrofit; private static final String BASE_URL = "https://api.exchangeratesapi.io/"; public static Retrofit getRetrofitInstance() { if (retrofit == null) { retrofit = new retrofit2.Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; } }
1,346
0.644874
0.641159
43
30.302326
23.56242
80
false
false
0
0
0
0
0
0
0.372093
false
false
7
36f524b6613e8842d3f2361857c8f72172c879e8
20,186,346,301,672
1537a6f5cfcca02d6592058b17f45b4aa52ef123
/shared/src/main/java/com/google/collide/shared/util/StringUtils.java
e69963a355e9e93a0eafe511b1ca2c94045b9d3b
[ "Apache-2.0" ]
permissive
soitun/collide
https://github.com/soitun/collide
6e809b7fd1a40c5570d80203082ce01190924311
2136cfc9705a96d88c69356868dda5b95c35bc6d
refs/heads/superdev
2022-05-27T15:00:06.791000
2018-11-23T09:23:58
2018-11-23T09:23:58
45,740,258
0
0
Apache-2.0
true
2022-05-11T02:22:47
2015-11-07T14:43:37
2015-11-07T14:43:47
2022-05-11T02:22:46
242,496
0
0
0
Java
false
false
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.shared.util; import javax.annotation.Nonnull; import com.google.collide.json.shared.JsonArray; import com.google.collide.json.shared.JsonIntegerMap; /** * Utility methods for string operations. * */ public class StringUtils { /** * Map [N] -> string of N spaces. Used by {@link #getSpaces} to cache strings * of spaces. */ private static final JsonIntegerMap<String> cachedSpaces = JsonCollections.createIntegerMap(); /** * Interface that defines string utility methods used by shared code but have * differing client and server implementations. */ public interface Implementation { JsonArray<String> split(String string, String separator); } private static class PureJavaImplementation implements Implementation { @Override public JsonArray<String> split(String string, String separator) { JsonArray<String> result = JsonCollections.createArray(); int sepLength = separator.length(); if (sepLength == 0) { for (int i = 0, n = string.length(); i < n; i++) { result.add(string.substring(i, i + 1)); } return result; } int position = 0; while (true) { int index = string.indexOf(separator, position); if (index == -1) { result.add(string.substring(position)); return result; } result.add(string.substring(position, index)); position = index + sepLength; } } } /** * By default, this is a pure java implementation, but can be set to a more * optimized version by the client */ private static Implementation implementation = new PureJavaImplementation(); /** * Sets the implementation for methods */ public static void setImplementation(Implementation implementation) { StringUtils.implementation = implementation; } /** * @return largest n such that * {@code string1.substring(0, n).equals(string2.substring(0, n))} */ public static int findCommonPrefixLength(String string1, String string2) { int limit = Math.min(string1.length(), string2.length()); int result = 0; while (result < limit) { if (string2.charAt(result) != string1.charAt(result)) { break; } result++; } return result; } public static int countNumberOfOccurrences(String s, String pattern) { int count = 0; int i = 0; while ((i = s.indexOf(pattern, i)) >= 0) { count++; i += pattern.length(); } return count; } /** * Check if a String ends with a specified suffix, ignoring case * * @param s the String to check, may be null * @param suffix the suffix to find, may be null * @return true if s ends with suffix or both s and suffix are null, false * otherwise. */ public static boolean endsWithIgnoreCase(String s, String suffix) { if (s == null || suffix == null) { return (s == null && suffix == null); } if (suffix.length() > s.length()) { return false; } return s.regionMatches(true, s.length() - suffix.length(), suffix, 0, suffix.length()); } public static boolean looksLikeImage(String path) { String lowercase = path.toLowerCase(); return lowercase.endsWith(".jpg") || lowercase.endsWith(".jpeg") || lowercase.endsWith(".ico") || lowercase.endsWith(".png") || lowercase.endsWith(".gif"); } public static <T> String join(T[] items, String separator) { StringBuilder s = new StringBuilder(); for (int i = 0; i < items.length; i++) { s.append(items[i]).append(separator); } s.setLength(s.length() - separator.length()); return s.toString(); } public static <T> String join(JsonArray<T> items, String separator) { StringBuilder s = new StringBuilder(); for (int i = 0; i < items.size(); i++) { s.append(items.get(i)).append(separator); } s.setLength(s.length() - separator.length()); return s.toString(); } /** * Check that string starts with specified prefix. * * <p>If {@code caseInsensitive == false} this check is equivalent * to {@link String#startsWith(String)}. * * <p>Otherwise {@code prefix} should be lower-case and check ignores * case of {@code string}. */ public static boolean startsWith( @Nonnull String prefix, @Nonnull String string, boolean caseInsensitive) { if (caseInsensitive) { int prefixLength = prefix.length(); if (string.length() < prefixLength) { return false; } return prefix.equals(string.substring(0, prefixLength).toLowerCase()); } else { return string.startsWith(prefix); } } /** * @return the length of the starting whitespace for the line, or the string * length if it is all whitespace */ public static int lengthOfStartingWhitespace(String s) { int n = s.length(); for (int i = 0; i < n; i++) { char c = s.charAt(i); // TODO: This currently only deals with ASCII whitespace. // Read until a non-space if (c != ' ' && c != '\t') { return i; } } return n; } /** * @return first character in the string that is not a whitespace, or * {@code 0} if there is no such characters */ public static char firstNonWhitespaceCharacter(String s) { for (int i = 0, n = s.length(); i < n; ++i) { char c = s.charAt(i); if (!isWhitespace(c)) { return c; } } return 0; } /** * @return last character in the string that is not a whitespace, or * {@code 0} if there is no such characters */ public static char lastNonWhitespaceCharacter(String s) { for (int i = s.length() - 1; i >= 0; --i) { char c = s.charAt(i); if (!isWhitespace(c)) { return c; } } return 0; } public static String nullToEmpty(String s) { return s == null ? "" : s; } public static boolean isNullOrEmpty(String s) { return s == null || "".equals(s); } public static boolean isNullOrWhitespace(String s) { return s == null || "".equals(s.trim()); } public static String trimNullToEmpty(String s) { return s == null ? "" : s.trim(); } public static String ensureNotEmpty(String s, String defaultStr) { return isNullOrEmpty(s) ? defaultStr : s; } public static boolean isWhitespace(char ch) { return (ch <= ' '); } public static boolean isAlpha(char ch) { return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z'); } public static boolean isNumeric(char ch) { return ('0' <= ch && ch <= '9'); } public static boolean isQuote(char ch) { return ch == '\'' || ch == '\"'; } public static boolean isAlphaNumOrUnderscore(char ch) { return isAlpha(ch) || isNumeric(ch) || ch == '_'; } public static long toLong(String longStr) { return longStr == null ? 0 : Long.parseLong(longStr); } /** * @return true, if both strings are empty or {@code null}, or if they are * equal */ public static boolean equalStringsOrEmpty(String a, String b) { return nullToEmpty(a).equals(nullToEmpty(b)); } /** * @return true, if the strings are not empty or {@code null}, and equal */ public static boolean equalNonEmptyStrings(String a, String b) { return !isNullOrEmpty(a) && a.equals(b); } /** * Splits with the contract of the contract of the JavaScript String.split(). * * <p>More specifically: empty segments will be produced for adjacent and * trailing separators. * * <p>If an empty string is used as the separator, the string is split * between each character. * * <p>Examples:<ul> * <li>{@code split("a", "a")} should produce {@code ["", ""]} * <li>{@code split("a\n", "\n")} should produce {@code ["a", ""]} * <li>{@code split("ab", "")} should produce {@code ["a", "b"]} * </ul> */ public static JsonArray<String> split(String s, String separator) { return implementation.split(s, separator); } /** * @return the number of editor lines this text would take up */ public static int countNumberOfVisibleLines(String text) { return countNumberOfOccurrences(text, "\n") + (text.endsWith("\n") ? 0 : 1); } public static String capitalizeFirstLetter(String s) { if (!isNullOrEmpty(s)) { s = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase(); } return s; } public static String ensureStartsWith(String s, String startText) { if (isNullOrEmpty(s)) { return startText; } else if (!s.startsWith(startText)) { return startText + s; } else { return s; } } /** * Like {@link String#substring(int)} but allows for the {@code count} * parameter to extend past the string's bounds. */ public static String substringGuarded(String s, int position, int count) { int sLength = s.length(); if (sLength - position <= count) { return position == 0 ? s : s.substring(position); } else { return s.substring(position, position + count); } } public static String repeatString(String s, int count) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < count; i++) { builder.append(s); } return builder.toString(); } /** * Gets a {@link String} consisting of the given number of spaces. * * <p>NB: The result is cached in {@link #cachedSpaces}. * * @param size the number of spaces * @return a {@link String} consisting of {@code size} spaces */ public static String getSpaces(int size) { if (cachedSpaces.hasKey(size)) { return cachedSpaces.get(size); } char[] fill = new char[size]; for (int i = 0; i < size; i++) { fill[i] = ' '; } String spaces = new String(fill); cachedSpaces.put(size, spaces); return spaces; } /** * If this given string is of length {@code maxLength} or less, it will * be returned as-is. * Otherwise it will be trucated to {@code maxLength}, regardless of whether * there are any space characters in the String. If an ellipsis is requested * to be appended to the truncated String, the String will be truncated so * that the ellipsis will also fit within maxLength. * If no truncation was necessary, no ellipsis will be added. * @param source the String to truncate if necessary * @param maxLength the maximum number of characters to keep * @param addEllipsis if true, and if the String had to be truncated, * add "..." to the end of the String before returning. Additionally, * the ellipsis will only be added if maxLength is greater than 3. * @return the original string if it's length is less than or equal to * maxLength, otherwise a truncated string as mentioned above */ public static String truncateAtMaxLength(String source, int maxLength, boolean addEllipsis) { if (source.length() <= maxLength) { return source; } if (addEllipsis && maxLength > 3) { return unicodePreservingSubstring(source, 0, maxLength - 3) + "..."; } return unicodePreservingSubstring(source, 0, maxLength); } /** * Normalizes {@code index} such that it respects Unicode character * boundaries in {@code str}. * * <p>If {@code index} is the low surrogate of a unicode character, * the method returns {@code index - 1}. Otherwise, {@code index} is * returned. * * <p>In the case in which {@code index} falls in an invalid surrogate pair * (e.g. consecutive low surrogates, consecutive high surrogates), or if * if it is not a valid index into {@code str}, the original value of * {@code index} is returned. * * @param str the String * @param index the index to be normalized * @return a normalized index that does not split a Unicode character */ private static int unicodePreservingIndex(String str, int index) { if (index > 0 && index < str.length()) { if (Character.isHighSurrogate(str.charAt(index - 1)) && Character.isLowSurrogate(str.charAt(index))) { return index - 1; } } return index; } /** * Returns a substring of {@code str} that respects Unicode character * boundaries. * * <p>The string will never be split between a [high, low] surrogate pair, * as defined by {@link Character#isHighSurrogate} and * {@link Character#isLowSurrogate}. * * <p>If {@code begin} or {@code end} are the low surrogate of a unicode * character, it will be offset by -1. * * <p>This behavior guarantees that * {@code str.equals(StringUtil.unicodePreservingSubstring(str, 0, n) + * StringUtil.unicodePreservingSubstring(str, n, str.length())) } is * true for all {@code n}. * </pre> * * <p>This means that unlike {@link String#substring(int, int)}, the length of * the returned substring may not necessarily be equivalent to * {@code end - begin}. * * @param str the original String * @param begin the beginning index, inclusive * @param end the ending index, exclusive * @return the specified substring, possibly adjusted in order to not * split unicode surrogate pairs * @throws IndexOutOfBoundsException if the {@code begin} is negative, * or {@code end} is larger than the length of {@code str}, or * {@code begin} is larger than {@code end} */ private static String unicodePreservingSubstring( String str, int begin, int end) { return str.substring(unicodePreservingIndex(str, begin), unicodePreservingIndex(str, end)); } }
UTF-8
Java
14,222
java
StringUtils.java
Java
[]
null
[]
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.shared.util; import javax.annotation.Nonnull; import com.google.collide.json.shared.JsonArray; import com.google.collide.json.shared.JsonIntegerMap; /** * Utility methods for string operations. * */ public class StringUtils { /** * Map [N] -> string of N spaces. Used by {@link #getSpaces} to cache strings * of spaces. */ private static final JsonIntegerMap<String> cachedSpaces = JsonCollections.createIntegerMap(); /** * Interface that defines string utility methods used by shared code but have * differing client and server implementations. */ public interface Implementation { JsonArray<String> split(String string, String separator); } private static class PureJavaImplementation implements Implementation { @Override public JsonArray<String> split(String string, String separator) { JsonArray<String> result = JsonCollections.createArray(); int sepLength = separator.length(); if (sepLength == 0) { for (int i = 0, n = string.length(); i < n; i++) { result.add(string.substring(i, i + 1)); } return result; } int position = 0; while (true) { int index = string.indexOf(separator, position); if (index == -1) { result.add(string.substring(position)); return result; } result.add(string.substring(position, index)); position = index + sepLength; } } } /** * By default, this is a pure java implementation, but can be set to a more * optimized version by the client */ private static Implementation implementation = new PureJavaImplementation(); /** * Sets the implementation for methods */ public static void setImplementation(Implementation implementation) { StringUtils.implementation = implementation; } /** * @return largest n such that * {@code string1.substring(0, n).equals(string2.substring(0, n))} */ public static int findCommonPrefixLength(String string1, String string2) { int limit = Math.min(string1.length(), string2.length()); int result = 0; while (result < limit) { if (string2.charAt(result) != string1.charAt(result)) { break; } result++; } return result; } public static int countNumberOfOccurrences(String s, String pattern) { int count = 0; int i = 0; while ((i = s.indexOf(pattern, i)) >= 0) { count++; i += pattern.length(); } return count; } /** * Check if a String ends with a specified suffix, ignoring case * * @param s the String to check, may be null * @param suffix the suffix to find, may be null * @return true if s ends with suffix or both s and suffix are null, false * otherwise. */ public static boolean endsWithIgnoreCase(String s, String suffix) { if (s == null || suffix == null) { return (s == null && suffix == null); } if (suffix.length() > s.length()) { return false; } return s.regionMatches(true, s.length() - suffix.length(), suffix, 0, suffix.length()); } public static boolean looksLikeImage(String path) { String lowercase = path.toLowerCase(); return lowercase.endsWith(".jpg") || lowercase.endsWith(".jpeg") || lowercase.endsWith(".ico") || lowercase.endsWith(".png") || lowercase.endsWith(".gif"); } public static <T> String join(T[] items, String separator) { StringBuilder s = new StringBuilder(); for (int i = 0; i < items.length; i++) { s.append(items[i]).append(separator); } s.setLength(s.length() - separator.length()); return s.toString(); } public static <T> String join(JsonArray<T> items, String separator) { StringBuilder s = new StringBuilder(); for (int i = 0; i < items.size(); i++) { s.append(items.get(i)).append(separator); } s.setLength(s.length() - separator.length()); return s.toString(); } /** * Check that string starts with specified prefix. * * <p>If {@code caseInsensitive == false} this check is equivalent * to {@link String#startsWith(String)}. * * <p>Otherwise {@code prefix} should be lower-case and check ignores * case of {@code string}. */ public static boolean startsWith( @Nonnull String prefix, @Nonnull String string, boolean caseInsensitive) { if (caseInsensitive) { int prefixLength = prefix.length(); if (string.length() < prefixLength) { return false; } return prefix.equals(string.substring(0, prefixLength).toLowerCase()); } else { return string.startsWith(prefix); } } /** * @return the length of the starting whitespace for the line, or the string * length if it is all whitespace */ public static int lengthOfStartingWhitespace(String s) { int n = s.length(); for (int i = 0; i < n; i++) { char c = s.charAt(i); // TODO: This currently only deals with ASCII whitespace. // Read until a non-space if (c != ' ' && c != '\t') { return i; } } return n; } /** * @return first character in the string that is not a whitespace, or * {@code 0} if there is no such characters */ public static char firstNonWhitespaceCharacter(String s) { for (int i = 0, n = s.length(); i < n; ++i) { char c = s.charAt(i); if (!isWhitespace(c)) { return c; } } return 0; } /** * @return last character in the string that is not a whitespace, or * {@code 0} if there is no such characters */ public static char lastNonWhitespaceCharacter(String s) { for (int i = s.length() - 1; i >= 0; --i) { char c = s.charAt(i); if (!isWhitespace(c)) { return c; } } return 0; } public static String nullToEmpty(String s) { return s == null ? "" : s; } public static boolean isNullOrEmpty(String s) { return s == null || "".equals(s); } public static boolean isNullOrWhitespace(String s) { return s == null || "".equals(s.trim()); } public static String trimNullToEmpty(String s) { return s == null ? "" : s.trim(); } public static String ensureNotEmpty(String s, String defaultStr) { return isNullOrEmpty(s) ? defaultStr : s; } public static boolean isWhitespace(char ch) { return (ch <= ' '); } public static boolean isAlpha(char ch) { return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z'); } public static boolean isNumeric(char ch) { return ('0' <= ch && ch <= '9'); } public static boolean isQuote(char ch) { return ch == '\'' || ch == '\"'; } public static boolean isAlphaNumOrUnderscore(char ch) { return isAlpha(ch) || isNumeric(ch) || ch == '_'; } public static long toLong(String longStr) { return longStr == null ? 0 : Long.parseLong(longStr); } /** * @return true, if both strings are empty or {@code null}, or if they are * equal */ public static boolean equalStringsOrEmpty(String a, String b) { return nullToEmpty(a).equals(nullToEmpty(b)); } /** * @return true, if the strings are not empty or {@code null}, and equal */ public static boolean equalNonEmptyStrings(String a, String b) { return !isNullOrEmpty(a) && a.equals(b); } /** * Splits with the contract of the contract of the JavaScript String.split(). * * <p>More specifically: empty segments will be produced for adjacent and * trailing separators. * * <p>If an empty string is used as the separator, the string is split * between each character. * * <p>Examples:<ul> * <li>{@code split("a", "a")} should produce {@code ["", ""]} * <li>{@code split("a\n", "\n")} should produce {@code ["a", ""]} * <li>{@code split("ab", "")} should produce {@code ["a", "b"]} * </ul> */ public static JsonArray<String> split(String s, String separator) { return implementation.split(s, separator); } /** * @return the number of editor lines this text would take up */ public static int countNumberOfVisibleLines(String text) { return countNumberOfOccurrences(text, "\n") + (text.endsWith("\n") ? 0 : 1); } public static String capitalizeFirstLetter(String s) { if (!isNullOrEmpty(s)) { s = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase(); } return s; } public static String ensureStartsWith(String s, String startText) { if (isNullOrEmpty(s)) { return startText; } else if (!s.startsWith(startText)) { return startText + s; } else { return s; } } /** * Like {@link String#substring(int)} but allows for the {@code count} * parameter to extend past the string's bounds. */ public static String substringGuarded(String s, int position, int count) { int sLength = s.length(); if (sLength - position <= count) { return position == 0 ? s : s.substring(position); } else { return s.substring(position, position + count); } } public static String repeatString(String s, int count) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < count; i++) { builder.append(s); } return builder.toString(); } /** * Gets a {@link String} consisting of the given number of spaces. * * <p>NB: The result is cached in {@link #cachedSpaces}. * * @param size the number of spaces * @return a {@link String} consisting of {@code size} spaces */ public static String getSpaces(int size) { if (cachedSpaces.hasKey(size)) { return cachedSpaces.get(size); } char[] fill = new char[size]; for (int i = 0; i < size; i++) { fill[i] = ' '; } String spaces = new String(fill); cachedSpaces.put(size, spaces); return spaces; } /** * If this given string is of length {@code maxLength} or less, it will * be returned as-is. * Otherwise it will be trucated to {@code maxLength}, regardless of whether * there are any space characters in the String. If an ellipsis is requested * to be appended to the truncated String, the String will be truncated so * that the ellipsis will also fit within maxLength. * If no truncation was necessary, no ellipsis will be added. * @param source the String to truncate if necessary * @param maxLength the maximum number of characters to keep * @param addEllipsis if true, and if the String had to be truncated, * add "..." to the end of the String before returning. Additionally, * the ellipsis will only be added if maxLength is greater than 3. * @return the original string if it's length is less than or equal to * maxLength, otherwise a truncated string as mentioned above */ public static String truncateAtMaxLength(String source, int maxLength, boolean addEllipsis) { if (source.length() <= maxLength) { return source; } if (addEllipsis && maxLength > 3) { return unicodePreservingSubstring(source, 0, maxLength - 3) + "..."; } return unicodePreservingSubstring(source, 0, maxLength); } /** * Normalizes {@code index} such that it respects Unicode character * boundaries in {@code str}. * * <p>If {@code index} is the low surrogate of a unicode character, * the method returns {@code index - 1}. Otherwise, {@code index} is * returned. * * <p>In the case in which {@code index} falls in an invalid surrogate pair * (e.g. consecutive low surrogates, consecutive high surrogates), or if * if it is not a valid index into {@code str}, the original value of * {@code index} is returned. * * @param str the String * @param index the index to be normalized * @return a normalized index that does not split a Unicode character */ private static int unicodePreservingIndex(String str, int index) { if (index > 0 && index < str.length()) { if (Character.isHighSurrogate(str.charAt(index - 1)) && Character.isLowSurrogate(str.charAt(index))) { return index - 1; } } return index; } /** * Returns a substring of {@code str} that respects Unicode character * boundaries. * * <p>The string will never be split between a [high, low] surrogate pair, * as defined by {@link Character#isHighSurrogate} and * {@link Character#isLowSurrogate}. * * <p>If {@code begin} or {@code end} are the low surrogate of a unicode * character, it will be offset by -1. * * <p>This behavior guarantees that * {@code str.equals(StringUtil.unicodePreservingSubstring(str, 0, n) + * StringUtil.unicodePreservingSubstring(str, n, str.length())) } is * true for all {@code n}. * </pre> * * <p>This means that unlike {@link String#substring(int, int)}, the length of * the returned substring may not necessarily be equivalent to * {@code end - begin}. * * @param str the original String * @param begin the beginning index, inclusive * @param end the ending index, exclusive * @return the specified substring, possibly adjusted in order to not * split unicode surrogate pairs * @throws IndexOutOfBoundsException if the {@code begin} is negative, * or {@code end} is larger than the length of {@code str}, or * {@code begin} is larger than {@code end} */ private static String unicodePreservingSubstring( String str, int begin, int end) { return str.substring(unicodePreservingIndex(str, begin), unicodePreservingIndex(str, end)); } }
14,222
0.635354
0.631065
457
30.12035
26.91889
98
false
false
0
0
0
0
0
0
0.50547
false
false
7
ee2bd36227c8713bd7188ed1c3b8cdd55fce0e1b
10,067,403,355,025
4205d1312f17bb1f3bbf28b7eb8c2b88f505d642
/DroneController/RoboFrame.java
8fa3c16b956580374d9cd109c34105bd609cc66d
[]
no_license
dillonledoux/java
https://github.com/dillonledoux/java
a3a743b36c9deb6c4844ae3627202a50cedd835d
cc6c884a2700c0d070a48aa629fc2f333ce1d769
refs/heads/master
2021-01-13T00:15:20.973000
2015-12-26T02:31:22
2015-12-26T02:31:22
48,592,518
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.*; import javax.swing.*; public class RoboFrame extends JFrame{ public RoboFrame(RoboLogic logic){ setTitle("Robot Controller"); setSize(300, 420); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); RoboPanel panel = new RoboPanel(logic); add(panel); setVisible(true); } }
UTF-8
Java
353
java
RoboFrame.java
Java
[]
null
[]
import java.awt.*; import javax.swing.*; public class RoboFrame extends JFrame{ public RoboFrame(RoboLogic logic){ setTitle("Robot Controller"); setSize(300, 420); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); RoboPanel panel = new RoboPanel(logic); add(panel); setVisible(true); } }
353
0.626062
0.609065
13
26.23077
16.912233
55
false
false
0
0
0
0
0
0
0.692308
false
false
7
ba7033f33b3ec24aaacf6dabfca7918f22f4744d
5,677,946,816,413
4c62fa408a842c21bed7966fa80906795fa04652
/hisspring/src/main/java/com/hospital/hisspring/repository/FinaldiagosticRepository.java
4525f764aea23288c3a1b501419a5cb9486db650
[]
no_license
xuzhihao0215/HIS
https://github.com/xuzhihao0215/HIS
c50d8be6b34d1557432cf9babb7d53f881215925
cb19dcebaee7ad51a1e26759f3a10c455639ed68
refs/heads/main
2023-04-09T01:55:39.009000
2021-04-20T05:24:11
2021-04-20T05:24:11
359,689,839
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hospital.hisspring.repository; import com.hospital.hisspring.entity.Finaldiagostic; import com.hospital.hisspring.entity.FinaldiagosticPrimaryKey; import org.springframework.data.jpa.repository.JpaRepository; public interface FinaldiagosticRepository extends JpaRepository<Finaldiagostic, FinaldiagosticPrimaryKey> { }
UTF-8
Java
343
java
FinaldiagosticRepository.java
Java
[]
null
[]
package com.hospital.hisspring.repository; import com.hospital.hisspring.entity.Finaldiagostic; import com.hospital.hisspring.entity.FinaldiagosticPrimaryKey; import org.springframework.data.jpa.repository.JpaRepository; public interface FinaldiagosticRepository extends JpaRepository<Finaldiagostic, FinaldiagosticPrimaryKey> { }
343
0.845481
0.845481
9
36.111111
36.127689
107
false
false
0
0
0
0
0
0
0.555556
false
false
7
b82bd79685697fa1f63b702ad0970bf146315df3
16,381,005,267,225
21bcd1da03415fec0a4f3fa7287f250df1d14051
/sources/com/google/android/gms/common/internal/C4361k1.java
c6c905e676cc81f3136f6cdbc110c25093537e4f
[]
no_license
lestseeandtest/Delivery
https://github.com/lestseeandtest/Delivery
9a5cc96bd6bd2316a535271ec9ca3865080c3ec8
bc3fae8f30804a2520e6699df92c2e6a4a0a7cfc
refs/heads/master
2022-04-24T12:14:22.396000
2020-04-25T21:50:29
2020-04-25T21:50:29
258,875,870
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.google.android.gms.common.internal; import android.os.Bundle; import android.os.IBinder; import android.os.Parcel; import android.os.Parcelable; import android.os.RemoteException; import p076c.p112d.p113a.p114a.p118d.p122d.C2613a; import p076c.p112d.p113a.p114a.p118d.p122d.C2615c; /* renamed from: com.google.android.gms.common.internal.k1 */ public final class C4361k1 extends C2613a implements C4385r { C4361k1(IBinder iBinder) { super(iBinder, "com.google.android.gms.common.internal.IGmsCallbacks"); } /* renamed from: a */ public final void mo18274a(int i, IBinder iBinder, Bundle bundle) throws RemoteException { Parcel a = mo10127a(); a.writeInt(i); a.writeStrongBinder(iBinder); C2615c.m12725a(a, (Parcelable) bundle); mo10130b(1, a); } /* renamed from: c */ public final void mo18276c(int i, Bundle bundle) throws RemoteException { Parcel a = mo10127a(); a.writeInt(i); C2615c.m12725a(a, (Parcelable) bundle); mo10130b(2, a); } /* renamed from: a */ public final void mo18275a(int i, IBinder iBinder, zzb zzb) throws RemoteException { Parcel a = mo10127a(); a.writeInt(i); a.writeStrongBinder(iBinder); C2615c.m12725a(a, (Parcelable) zzb); mo10130b(3, a); } }
UTF-8
Java
1,351
java
C4361k1.java
Java
[]
null
[]
package com.google.android.gms.common.internal; import android.os.Bundle; import android.os.IBinder; import android.os.Parcel; import android.os.Parcelable; import android.os.RemoteException; import p076c.p112d.p113a.p114a.p118d.p122d.C2613a; import p076c.p112d.p113a.p114a.p118d.p122d.C2615c; /* renamed from: com.google.android.gms.common.internal.k1 */ public final class C4361k1 extends C2613a implements C4385r { C4361k1(IBinder iBinder) { super(iBinder, "com.google.android.gms.common.internal.IGmsCallbacks"); } /* renamed from: a */ public final void mo18274a(int i, IBinder iBinder, Bundle bundle) throws RemoteException { Parcel a = mo10127a(); a.writeInt(i); a.writeStrongBinder(iBinder); C2615c.m12725a(a, (Parcelable) bundle); mo10130b(1, a); } /* renamed from: c */ public final void mo18276c(int i, Bundle bundle) throws RemoteException { Parcel a = mo10127a(); a.writeInt(i); C2615c.m12725a(a, (Parcelable) bundle); mo10130b(2, a); } /* renamed from: a */ public final void mo18275a(int i, IBinder iBinder, zzb zzb) throws RemoteException { Parcel a = mo10127a(); a.writeInt(i); a.writeStrongBinder(iBinder); C2615c.m12725a(a, (Parcelable) zzb); mo10130b(3, a); } }
1,351
0.666173
0.564027
42
31.166666
24.020742
94
false
false
0
0
0
0
0
0
0.833333
false
false
7
233653bebfebcffd3654a0f46fefbc8c93702640
16,372,415,398,978
6ca404cd241149248d35e91db098b426477a253f
/app/src/main/java/com/vnplace/foodclick/base/LoadPresenter.java
cda62d79fe6be6e99406cf3797792d3665267a42
[]
no_license
ngocsangnd259/FC_VNP
https://github.com/ngocsangnd259/FC_VNP
4fe377d1f3296cac7387ae79301dd772957a201a
e01bce68c2f4dd210c7b0aa81958f4975d7e4aab
refs/heads/master
2019-03-21T03:15:37.536000
2018-03-06T17:10:50
2018-03-06T17:10:50
124,111,075
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.vnplace.foodclick.base; /** * Created by ngocs on 1/4/2018. */ public interface LoadPresenter<T extends BaseView> { void attachView(T view); void detachView(); void onRefresh(); void onLoadMore(); }
UTF-8
Java
232
java
LoadPresenter.java
Java
[ { "context": "age com.vnplace.foodclick.base;\n\n/**\n * Created by ngocs on 1/4/2018.\n */\n\npublic interface LoadPresenter<", "end": 60, "score": 0.9996100068092346, "start": 55, "tag": "USERNAME", "value": "ngocs" } ]
null
[]
package com.vnplace.foodclick.base; /** * Created by ngocs on 1/4/2018. */ public interface LoadPresenter<T extends BaseView> { void attachView(T view); void detachView(); void onRefresh(); void onLoadMore(); }
232
0.672414
0.646552
13
16.846153
16.351175
52
false
false
0
0
0
0
0
0
0.384615
false
false
7
75809e4aa4a39ff7a2056b2e252de0ee0f223f4c
429,496,746,305
72131f2f29e4a9c80d66fd5dc9532a943d1c044b
/src/main/java/frc/robot/Subsystems/Climber.java
bb1d4f6a57477bac02030dee11130544868b4926
[]
no_license
ctaylor22/2020-Competitive-Code
https://github.com/ctaylor22/2020-Competitive-Code
0c91627a9731acb9d4bd906d8e5afe899739efa5
8a14fa56bf0f5a8a7b50de0926924a244cbe182d
refs/heads/master
2022-04-06T21:48:34.023000
2020-03-12T13:29:20
2020-03-12T13:29:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package frc.robot.Subsystems; import com.ctre.phoenix.motorcontrol.can.WPI_TalonFX; import frc.robot.ControllerMap; import frc.robot.Robot; import frc.robot.RobotMap.GearboxBrakeMap; import frc.robot.RobotMap.ShifterMap; import frc.robot.RobotMap.ClimberMap; import edu.wpi.first.wpilibj.DoubleSolenoid; public class Climber { WPI_TalonFX climbFX; // ---------Devices and Hardward private DoubleSolenoid brakerSolenoid; private DoubleSolenoid shifterSolenoid; private DoubleSolenoid leftArmSolenoid; private DoubleSolenoid rightArmSolenoid; public void robotInit() { brakerSolenoid = new DoubleSolenoid(GearboxBrakeMap.kPCM, GearboxBrakeMap.kBrakeModeOn, GearboxBrakeMap.kBrakeModeOff); shifterSolenoid = new DoubleSolenoid(GearboxBrakeMap.kPCM, ShifterMap.kShiftModeClimb, ShifterMap.kShiftModeDrive); leftArmSolenoid = new DoubleSolenoid(GearboxBrakeMap.kPCM, ClimberMap.kLeftArm_Up, ClimberMap.kLeftArm_Dn); rightArmSolenoid = new DoubleSolenoid(GearboxBrakeMap.kPCM, ClimberMap.kRightArm_Up, ClimberMap.kRightArm_Dn); } public void robotPeriodic() { } public void autonomousInit() { brakerSolenoid.set(DoubleSolenoid.Value.kReverse); shifterSolenoid.set(DoubleSolenoid.Value.kForward); leftArmSolenoid.set(DoubleSolenoid.Value.kReverse); rightArmSolenoid.set(DoubleSolenoid.Value.kReverse); Robot.climb_is_enabled = false; Robot.brake_is_enabled = false; Robot.tether_is_enabled = false; } public void autonomousPeriodic() { } public void teleopInit() { // Move this to robot init once it works. brakerSolenoid.set(DoubleSolenoid.Value.kReverse); shifterSolenoid.set(DoubleSolenoid.Value.kForward); leftArmSolenoid.set(DoubleSolenoid.Value.kReverse); rightArmSolenoid.set(DoubleSolenoid.Value.kReverse); Robot.climb_is_enabled = false; Robot.brake_is_enabled = false; Robot.tether_is_enabled = false; } boolean button_test = true; public void teleopPeriodic() { if (Robot.climbCtrl.getRawButton(ControllerMap.climbjoy.kBrake_ON)) { Robot.brake_is_enabled = true; // Apply Break brakerSolenoid.set(DoubleSolenoid.Value.kForward); } if (Robot.climbCtrl.getRawButton(ControllerMap.climbjoy.kBrake_OFF)) { Robot.brake_is_enabled = false; // Release Break brakerSolenoid.set(DoubleSolenoid.Value.kReverse); } if (Robot.climbCtrl.getRawButton(ControllerMap.climbjoy.TetherEngage)) { Robot.tether_is_enabled = true; Robot.climb_is_enabled = true; shifterSolenoid.set(DoubleSolenoid.Value.kReverse); } else { if (!Robot.climb_is_enabled) { Robot.tether_is_enabled = false; shifterSolenoid.set(DoubleSolenoid.Value.kForward); } } if (Robot.climbCtrl.getRawButton(ControllerMap.climbjoy.kResetClimbMode)) { Robot.climb_is_enabled = false; } if (Robot.climbCtrl.getRawButton(ControllerMap.climbjoy.LeftSide_UP)) { leftArmSolenoid.set(DoubleSolenoid.Value.kForward); } if (Robot.climbCtrl.getRawButton(ControllerMap.climbjoy.LeftSide_DOWN)) { leftArmSolenoid.set(DoubleSolenoid.Value.kReverse); } if (Robot.climbCtrl.getRawButton(ControllerMap.climbjoy.RightSide_UP)) { rightArmSolenoid.set(DoubleSolenoid.Value.kForward); } if (Robot.climbCtrl.getRawButton(ControllerMap.climbjoy.RightSide_DOWN)) { rightArmSolenoid.set(DoubleSolenoid.Value.kReverse); } // If the break is engaged, turn off motors, do nothing else. if (Robot.brake_is_enabled) { Robot.driveTrain.ExternalMotorControl(0.0, 0.0); return; } // IF the tehter is engaged, control motors. if (Robot.tether_is_enabled) { boolean mainpull_is_zero = false; boolean sidepull_is_zero = false; double mainpull = Robot.climbCtrl.getRawAxis(ControllerMap.climbjoy.kClimbAxis); double sidepull = Robot.climbCtrl.getRawAxis(ControllerMap.climbjoy.kBalanceAxis); if (Math.abs(mainpull) < 0.25) { mainpull = 0.0; mainpull_is_zero = true; } else { if (mainpull > 0.0) { mainpull = (mainpull - 0.25) / 0.75; } else { mainpull = (mainpull + 0.25) / 0.75; } } if (Math.abs(sidepull) < 0.25) { sidepull = 0.0; sidepull_is_zero = true; } else { if (sidepull > 0.0) { sidepull = (sidepull - 0.25) / 0.75; } else { sidepull = (sidepull + 0.25) / 0.75; } } // Scale pulling here... mainpull = mainpull * 0.75; sidepull = sidepull * 0.30; if (mainpull_is_zero && sidepull_is_zero) { Robot.driveTrain.ExternalMotorControl(0.0, 0.0); return; } if (sidepull_is_zero) { // Apply a ballanced force only. mainpull = mainpull * 0.75; Robot.driveTrain.ExternalMotorControl(mainpull, mainpull); return; } else { // This the more normal case.. apply additive pull to the side // that the ballance axis is leaning. if (sidepull > 0.0) { Robot.driveTrain.ExternalMotorControl(mainpull, mainpull + sidepull); } else { Robot.driveTrain.ExternalMotorControl(mainpull - sidepull, mainpull); } } } } public void disabledInit() { } public void disabledPeriodic() { } }
UTF-8
Java
5,391
java
Climber.java
Java
[]
null
[]
package frc.robot.Subsystems; import com.ctre.phoenix.motorcontrol.can.WPI_TalonFX; import frc.robot.ControllerMap; import frc.robot.Robot; import frc.robot.RobotMap.GearboxBrakeMap; import frc.robot.RobotMap.ShifterMap; import frc.robot.RobotMap.ClimberMap; import edu.wpi.first.wpilibj.DoubleSolenoid; public class Climber { WPI_TalonFX climbFX; // ---------Devices and Hardward private DoubleSolenoid brakerSolenoid; private DoubleSolenoid shifterSolenoid; private DoubleSolenoid leftArmSolenoid; private DoubleSolenoid rightArmSolenoid; public void robotInit() { brakerSolenoid = new DoubleSolenoid(GearboxBrakeMap.kPCM, GearboxBrakeMap.kBrakeModeOn, GearboxBrakeMap.kBrakeModeOff); shifterSolenoid = new DoubleSolenoid(GearboxBrakeMap.kPCM, ShifterMap.kShiftModeClimb, ShifterMap.kShiftModeDrive); leftArmSolenoid = new DoubleSolenoid(GearboxBrakeMap.kPCM, ClimberMap.kLeftArm_Up, ClimberMap.kLeftArm_Dn); rightArmSolenoid = new DoubleSolenoid(GearboxBrakeMap.kPCM, ClimberMap.kRightArm_Up, ClimberMap.kRightArm_Dn); } public void robotPeriodic() { } public void autonomousInit() { brakerSolenoid.set(DoubleSolenoid.Value.kReverse); shifterSolenoid.set(DoubleSolenoid.Value.kForward); leftArmSolenoid.set(DoubleSolenoid.Value.kReverse); rightArmSolenoid.set(DoubleSolenoid.Value.kReverse); Robot.climb_is_enabled = false; Robot.brake_is_enabled = false; Robot.tether_is_enabled = false; } public void autonomousPeriodic() { } public void teleopInit() { // Move this to robot init once it works. brakerSolenoid.set(DoubleSolenoid.Value.kReverse); shifterSolenoid.set(DoubleSolenoid.Value.kForward); leftArmSolenoid.set(DoubleSolenoid.Value.kReverse); rightArmSolenoid.set(DoubleSolenoid.Value.kReverse); Robot.climb_is_enabled = false; Robot.brake_is_enabled = false; Robot.tether_is_enabled = false; } boolean button_test = true; public void teleopPeriodic() { if (Robot.climbCtrl.getRawButton(ControllerMap.climbjoy.kBrake_ON)) { Robot.brake_is_enabled = true; // Apply Break brakerSolenoid.set(DoubleSolenoid.Value.kForward); } if (Robot.climbCtrl.getRawButton(ControllerMap.climbjoy.kBrake_OFF)) { Robot.brake_is_enabled = false; // Release Break brakerSolenoid.set(DoubleSolenoid.Value.kReverse); } if (Robot.climbCtrl.getRawButton(ControllerMap.climbjoy.TetherEngage)) { Robot.tether_is_enabled = true; Robot.climb_is_enabled = true; shifterSolenoid.set(DoubleSolenoid.Value.kReverse); } else { if (!Robot.climb_is_enabled) { Robot.tether_is_enabled = false; shifterSolenoid.set(DoubleSolenoid.Value.kForward); } } if (Robot.climbCtrl.getRawButton(ControllerMap.climbjoy.kResetClimbMode)) { Robot.climb_is_enabled = false; } if (Robot.climbCtrl.getRawButton(ControllerMap.climbjoy.LeftSide_UP)) { leftArmSolenoid.set(DoubleSolenoid.Value.kForward); } if (Robot.climbCtrl.getRawButton(ControllerMap.climbjoy.LeftSide_DOWN)) { leftArmSolenoid.set(DoubleSolenoid.Value.kReverse); } if (Robot.climbCtrl.getRawButton(ControllerMap.climbjoy.RightSide_UP)) { rightArmSolenoid.set(DoubleSolenoid.Value.kForward); } if (Robot.climbCtrl.getRawButton(ControllerMap.climbjoy.RightSide_DOWN)) { rightArmSolenoid.set(DoubleSolenoid.Value.kReverse); } // If the break is engaged, turn off motors, do nothing else. if (Robot.brake_is_enabled) { Robot.driveTrain.ExternalMotorControl(0.0, 0.0); return; } // IF the tehter is engaged, control motors. if (Robot.tether_is_enabled) { boolean mainpull_is_zero = false; boolean sidepull_is_zero = false; double mainpull = Robot.climbCtrl.getRawAxis(ControllerMap.climbjoy.kClimbAxis); double sidepull = Robot.climbCtrl.getRawAxis(ControllerMap.climbjoy.kBalanceAxis); if (Math.abs(mainpull) < 0.25) { mainpull = 0.0; mainpull_is_zero = true; } else { if (mainpull > 0.0) { mainpull = (mainpull - 0.25) / 0.75; } else { mainpull = (mainpull + 0.25) / 0.75; } } if (Math.abs(sidepull) < 0.25) { sidepull = 0.0; sidepull_is_zero = true; } else { if (sidepull > 0.0) { sidepull = (sidepull - 0.25) / 0.75; } else { sidepull = (sidepull + 0.25) / 0.75; } } // Scale pulling here... mainpull = mainpull * 0.75; sidepull = sidepull * 0.30; if (mainpull_is_zero && sidepull_is_zero) { Robot.driveTrain.ExternalMotorControl(0.0, 0.0); return; } if (sidepull_is_zero) { // Apply a ballanced force only. mainpull = mainpull * 0.75; Robot.driveTrain.ExternalMotorControl(mainpull, mainpull); return; } else { // This the more normal case.. apply additive pull to the side // that the ballance axis is leaning. if (sidepull > 0.0) { Robot.driveTrain.ExternalMotorControl(mainpull, mainpull + sidepull); } else { Robot.driveTrain.ExternalMotorControl(mainpull - sidepull, mainpull); } } } } public void disabledInit() { } public void disabledPeriodic() { } }
5,391
0.678538
0.667965
168
31.095238
26.555475
119
false
false
0
0
0
0
0
0
0.505952
false
false
7
b72b231254b54f2e2c4686fec34601d76ea2320b
22,101,901,751,083
187000b4f74ab5989bdc6544e528333b52ac920c
/app/src/main/java/com/bawei/zhujie2/MainActivity.java
78bd67c6b93e16f05c129df9b14137d976c1adbf
[]
no_license
caicailxq/Zhujie2
https://github.com/caicailxq/Zhujie2
3dabd8baf0978a2d83c9836ba0dc8a9015178116
30b68a2cbf3e9052fab5bb0977abfdc871bb0e93
refs/heads/master
2021-07-21T22:43:00.010000
2017-11-01T11:06:10
2017-11-01T11:06:10
109,121,239
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bawei.zhujie2; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import rx.Observable; import rx.Observer; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class MainActivity extends AppCompatActivity { public static final String URL = "http://169.254.247.113:8080/WebSample/action/book_detail?id=1"; private TextView mTvTitle; private TextView mTvDtCreated; private TextView mTvDescription; // 观察者 Observer<Qbean> mObserver = new Observer<Qbean>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { e.printStackTrace(); Toast.makeText(MainActivity.this, "请求HTTP失败!", Toast.LENGTH_LONG).show(); } @Override public void onNext(Qbean qbean) { mTvTitle.setText(qbean.getData().getTitle()); mTvDtCreated.setText(qbean.getData().getDtCreated()); mTvDescription.setText(qbean.getData().getDescription()); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTvTitle = (TextView) findViewById(R.id.tv_title); mTvDtCreated = (TextView) findViewById(R.id.tv_dt_created); mTvDescription = (TextView) findViewById(R.id.tv_description); Observable.OnSubscribe<Qbean> observable = new Observable.OnSubscribe<Qbean>() { @Override public void call(final Subscriber<? super Qbean> subscriber) { Request req = new Request.Builder().url("http://169.254.247.113:8080/WebSample/action/book_detail?id=5").build(); OkHttpClient client = new OkHttpClient(); Call call = client.newCall(req); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { subscriber.onError(e); } @Override public void onResponse(Call call, Response response) throws IOException { String data = response.body().string(); Qbean entity = new Gson().fromJson(data, Qbean.class); subscriber.onNext(entity); } }); } }; Observable.create(observable).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(mObserver); } }
UTF-8
Java
2,905
java
MainActivity.java
Java
[ { "context": "ty {\n public static final String URL = \"http://169.254.247.113:8080/WebSample/action/book_detail?id=1\";\n priv", "end": 608, "score": 0.9997512698173523, "start": 593, "tag": "IP_ADDRESS", "value": "169.254.247.113" }, { "context": " Request req = new Request.Builder().url(\"http://169.254.247.113:8080/WebSample/action/book_detail?id=5\").build()", "end": 1979, "score": 0.9997406005859375, "start": 1965, "tag": "IP_ADDRESS", "value": "169.254.247.11" } ]
null
[]
package com.bawei.zhujie2; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import rx.Observable; import rx.Observer; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class MainActivity extends AppCompatActivity { public static final String URL = "http://169.254.247.113:8080/WebSample/action/book_detail?id=1"; private TextView mTvTitle; private TextView mTvDtCreated; private TextView mTvDescription; // 观察者 Observer<Qbean> mObserver = new Observer<Qbean>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { e.printStackTrace(); Toast.makeText(MainActivity.this, "请求HTTP失败!", Toast.LENGTH_LONG).show(); } @Override public void onNext(Qbean qbean) { mTvTitle.setText(qbean.getData().getTitle()); mTvDtCreated.setText(qbean.getData().getDtCreated()); mTvDescription.setText(qbean.getData().getDescription()); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTvTitle = (TextView) findViewById(R.id.tv_title); mTvDtCreated = (TextView) findViewById(R.id.tv_dt_created); mTvDescription = (TextView) findViewById(R.id.tv_description); Observable.OnSubscribe<Qbean> observable = new Observable.OnSubscribe<Qbean>() { @Override public void call(final Subscriber<? super Qbean> subscriber) { Request req = new Request.Builder().url("http://169.254.247.113:8080/WebSample/action/book_detail?id=5").build(); OkHttpClient client = new OkHttpClient(); Call call = client.newCall(req); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { subscriber.onError(e); } @Override public void onResponse(Call call, Response response) throws IOException { String data = response.body().string(); Qbean entity = new Gson().fromJson(data, Qbean.class); subscriber.onNext(entity); } }); } }; Observable.create(observable).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(mObserver); } }
2,905
0.62513
0.610938
90
31.088888
29.669155
130
false
false
0
0
0
0
0
0
0.522222
false
false
7
59b927a035347684f83704b9ca2096da1b5db276
11,957,189,001,159
1715c01e735d33f352f9c16be297febf3c6e7269
/treinamento-parent/tr-adapter-outbound-parent/tr-dynamodb-adapter-outbound/src/main/java/br/com/treinamento/tr/adapter/outbound/handler/DynamodbAdapterOutboundHandler.java
56a09e14ee27a0faeb4d480072645ff5b540c48a
[]
no_license
misaelsco/TreinamentoSTF
https://github.com/misaelsco/TreinamentoSTF
13a81e8d135248d41a06759b05295a4169291b01
743e239e27ea041eeddf430c70764dd94acd7778
refs/heads/master
2021-08-31T14:20:17.784000
2017-12-20T12:12:40
2017-12-20T12:12:40
114,803,874
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.treinamento.tr.adapter.outbound.handler; import java.time.LocalDate; import org.apache.log4j.spi.LoggerFactory; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import br.com.treinamento.tr.adapter.outbound.entity.TransacaoProcessadaEntity; import br.com.treinamento.tr.adapter.outbound.repository.DynamodbOutboundRepository; import br.com.treinamento.tr.core.commons.dto.TransacaoProcessadaDTO; import br.com.treinamento.tr.core.port.outbound.DynamodbOutboundPort; @Service public class DynamodbAdapterOutboundHandler implements DynamodbOutboundPort{ @Autowired private DynamodbOutboundRepository dynamodbOutboundRepository; @Override public void enviarParaDynamoDB(TransacaoProcessadaDTO dto) throws Exception{ TransacaoProcessadaEntity entity = new TransacaoProcessadaEntity(); System.out.println("Enviando para o dynamo" + entity ); try { } catch (Exception e) { System.out.println("Erro"); } } @Override public void consultarExtrato(Integer idConta, LocalDate dataInicial, LocalDate dataFinal) { // TODO Auto-generated method stub } }
UTF-8
Java
1,195
java
DynamodbAdapterOutboundHandler.java
Java
[]
null
[]
package br.com.treinamento.tr.adapter.outbound.handler; import java.time.LocalDate; import org.apache.log4j.spi.LoggerFactory; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import br.com.treinamento.tr.adapter.outbound.entity.TransacaoProcessadaEntity; import br.com.treinamento.tr.adapter.outbound.repository.DynamodbOutboundRepository; import br.com.treinamento.tr.core.commons.dto.TransacaoProcessadaDTO; import br.com.treinamento.tr.core.port.outbound.DynamodbOutboundPort; @Service public class DynamodbAdapterOutboundHandler implements DynamodbOutboundPort{ @Autowired private DynamodbOutboundRepository dynamodbOutboundRepository; @Override public void enviarParaDynamoDB(TransacaoProcessadaDTO dto) throws Exception{ TransacaoProcessadaEntity entity = new TransacaoProcessadaEntity(); System.out.println("Enviando para o dynamo" + entity ); try { } catch (Exception e) { System.out.println("Erro"); } } @Override public void consultarExtrato(Integer idConta, LocalDate dataInicial, LocalDate dataFinal) { // TODO Auto-generated method stub } }
1,195
0.803347
0.801674
43
26.790697
30.348026
92
false
false
0
0
0
0
0
0
1.255814
false
false
7
ef38990b44f488e1d5d3667d7e475a131af4665a
3,324,304,729,132
5e423f52bd4b34a4cce050f2edcaa57532021ade
/src/main/java/com/deal/service/conference/Impl/ConfEditServiceImpl.java
9614bee33136c5ee7ae40d09e0e87d1b986953f1
[]
no_license
infoPowerSource/dealCall
https://github.com/infoPowerSource/dealCall
52cd6b78f64f26192e52a4d1efbb6cdafe808f72
a828eac70bea3d737abf6d94d380f81b0a30c4f1
refs/heads/master
2022-12-21T23:48:58.109000
2019-07-26T03:19:04
2019-07-27T01:20:49
198,925,745
0
0
null
false
2022-12-16T08:19:52
2019-07-26T01:37:17
2019-07-27T01:23:41
2022-12-16T08:19:50
102,304
0
0
16
Java
false
false
package com.deal.service.conference.Impl; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.ObjectUtils; import com.deal.dao.create.ConferenceDao; import com.deal.entity.create.ConferenceInfo; import com.deal.entity.party.CahcheConference; import com.deal.monitor.cache.CacheConferenceManage; import com.deal.service.acm.IACMService; import com.deal.service.cache.ICacheService; import com.deal.service.conference.IConfEditService; @Service public class ConfEditServiceImpl implements IConfEditService{ public static final Logger logger = LoggerFactory.getLogger(ConfEditServiceImpl.class); @Autowired private ConferenceDao confDao; @Autowired private IACMService acmService; @Autowired private ICacheService cacheService; @Override public void setRecordStatus(String confId, String recordStatus){ if(StringUtils.isEmpty(confId)){ throw new RuntimeException("传入的会议confId为空"); } if(StringUtils.isEmpty(recordStatus)){ throw new RuntimeException("传入的会议录音设置值recordStatus为空"); } ConferenceInfo confInfo=confDao.getConfInfoById(confId); if(cacheService.getCustomerNumber(confInfo.getConfBillingcode())==0){ throw new RuntimeException("会议中没有咨询客户,不能设置会议录音"); } if(cacheService.getExpertNumber(confInfo.getConfBillingcode())<1){ throw new RuntimeException("会议中没有顾问,正在播放提示音,不能设置会议录音"); } CahcheConference cacheConf=CacheConferenceManage.getLocalCacheConference(confInfo.getConfBillingcode()); //1:开始录音 2:暂停录音 if(!ObjectUtils.isEmpty(cacheConf)){ if(recordStatus.equals("1")){ if(acmService.startRecord(confInfo)==0){ logger.info("开始录音设置ACM成功,会议BC"+confInfo.getConfBillingcode()+"录音设置状态为"+recordStatus); }else{ logger.info("开始录音设置ACM失败,会议BC"+confInfo.getConfBillingcode()+"录音设置状态为"+recordStatus); throw new RuntimeException("开始录音设置ACM失败,会议BC"+confInfo.getConfBillingcode()+"录音设置状态为"+recordStatus); } }else if(recordStatus.equals("2")){ if(acmService.stopRecord(confInfo)==0){ logger.info("停止录音设置ACM成功,会议BC"+confInfo.getConfBillingcode()+"录音设置状态为"+recordStatus); }else{ logger.info("停止录音设置ACM失败,会议BC"+confInfo.getConfBillingcode()+"录音设置状态为"+recordStatus); throw new RuntimeException("停止录音设置ACM失败,会议BC"+confInfo.getConfBillingcode()+"录音设置状态为"+recordStatus); } } cacheConf.setRecordStatus(recordStatus); CacheConferenceManage.updateRecordStatus(confInfo.getConfBillingcode(),cacheConf); logger.info("会议录音设置保存缓存成功,会议BC"+confInfo.getConfBillingcode()+"录音设置状态为"+recordStatus); }else{ throw new RuntimeException("没查询到该会议ID的会议信息"); } } @Override public int getRecordStatus(String confId){ ConferenceInfo confInfo=confDao.getConfInfoById(confId); CahcheConference cacheConf=CacheConferenceManage.getLocalCacheConference(confInfo.getConfBillingcode()); if(ObjectUtils.isEmpty(cacheConf)){ return -1; }else{ //logger.info("会议BC:"+confInfo.getConfBillingcode()+"录音状态为"+cacheConf.getRecordStatus()); return Integer.valueOf(cacheConf.getRecordStatus()); } } }
UTF-8
Java
3,623
java
ConfEditServiceImpl.java
Java
[]
null
[]
package com.deal.service.conference.Impl; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.ObjectUtils; import com.deal.dao.create.ConferenceDao; import com.deal.entity.create.ConferenceInfo; import com.deal.entity.party.CahcheConference; import com.deal.monitor.cache.CacheConferenceManage; import com.deal.service.acm.IACMService; import com.deal.service.cache.ICacheService; import com.deal.service.conference.IConfEditService; @Service public class ConfEditServiceImpl implements IConfEditService{ public static final Logger logger = LoggerFactory.getLogger(ConfEditServiceImpl.class); @Autowired private ConferenceDao confDao; @Autowired private IACMService acmService; @Autowired private ICacheService cacheService; @Override public void setRecordStatus(String confId, String recordStatus){ if(StringUtils.isEmpty(confId)){ throw new RuntimeException("传入的会议confId为空"); } if(StringUtils.isEmpty(recordStatus)){ throw new RuntimeException("传入的会议录音设置值recordStatus为空"); } ConferenceInfo confInfo=confDao.getConfInfoById(confId); if(cacheService.getCustomerNumber(confInfo.getConfBillingcode())==0){ throw new RuntimeException("会议中没有咨询客户,不能设置会议录音"); } if(cacheService.getExpertNumber(confInfo.getConfBillingcode())<1){ throw new RuntimeException("会议中没有顾问,正在播放提示音,不能设置会议录音"); } CahcheConference cacheConf=CacheConferenceManage.getLocalCacheConference(confInfo.getConfBillingcode()); //1:开始录音 2:暂停录音 if(!ObjectUtils.isEmpty(cacheConf)){ if(recordStatus.equals("1")){ if(acmService.startRecord(confInfo)==0){ logger.info("开始录音设置ACM成功,会议BC"+confInfo.getConfBillingcode()+"录音设置状态为"+recordStatus); }else{ logger.info("开始录音设置ACM失败,会议BC"+confInfo.getConfBillingcode()+"录音设置状态为"+recordStatus); throw new RuntimeException("开始录音设置ACM失败,会议BC"+confInfo.getConfBillingcode()+"录音设置状态为"+recordStatus); } }else if(recordStatus.equals("2")){ if(acmService.stopRecord(confInfo)==0){ logger.info("停止录音设置ACM成功,会议BC"+confInfo.getConfBillingcode()+"录音设置状态为"+recordStatus); }else{ logger.info("停止录音设置ACM失败,会议BC"+confInfo.getConfBillingcode()+"录音设置状态为"+recordStatus); throw new RuntimeException("停止录音设置ACM失败,会议BC"+confInfo.getConfBillingcode()+"录音设置状态为"+recordStatus); } } cacheConf.setRecordStatus(recordStatus); CacheConferenceManage.updateRecordStatus(confInfo.getConfBillingcode(),cacheConf); logger.info("会议录音设置保存缓存成功,会议BC"+confInfo.getConfBillingcode()+"录音设置状态为"+recordStatus); }else{ throw new RuntimeException("没查询到该会议ID的会议信息"); } } @Override public int getRecordStatus(String confId){ ConferenceInfo confInfo=confDao.getConfInfoById(confId); CahcheConference cacheConf=CacheConferenceManage.getLocalCacheConference(confInfo.getConfBillingcode()); if(ObjectUtils.isEmpty(cacheConf)){ return -1; }else{ //logger.info("会议BC:"+confInfo.getConfBillingcode()+"录音状态为"+cacheConf.getRecordStatus()); return Integer.valueOf(cacheConf.getRecordStatus()); } } }
3,623
0.787308
0.783852
81
38.296295
31.219828
106
false
false
0
0
0
0
0
0
2.320988
false
false
7
ca79c48e77d3ecf319116530e9a01b0bf31014fd
31,310,311,629,039
922c91ea98e7a71b167e303685104c843a98e46a
/src/main/java/com/sec/aidog/service/impl/DogServiceImpl.java
1c219dfb94365fe67adb89aa6ae2165b309f198b
[]
no_license
nipder/aidog
https://github.com/nipder/aidog
f0d05ac924564a1ed689c29fee0bef97018abe82
65d676cd9fcd5491d49645ea352fb187dd188229
refs/heads/master
2023-04-27T05:40:23.215000
2020-07-08T16:20:45
2020-07-08T16:20:45
200,046,528
0
0
null
false
2023-04-14T17:49:01
2019-08-01T12:28:29
2020-07-08T16:27:37
2023-04-14T17:49:00
26,369
0
0
2
JavaScript
false
false
package com.sec.aidog.service.impl; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.sec.aidog.dao.*; import com.sec.aidog.model.*; import com.sec.aidog.pojo.*; import com.sec.aidog.service.DogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.text.DecimalFormat; import java.util.*; @Service("dogService") public class DogServiceImpl implements DogService{ @Autowired private DogMapper dogMapper; @Autowired private ManagerMapper managerMapper; @Autowired private LastnecdosingMapper lastnecdosingMapper; @Autowired private LastappdosingMapper lastappdosingMapper; @Autowired private DogownerMapper dogownerMapper; @Autowired private DistrictMapper districtMapper; @Autowired private AnalyzeillMapper analyzeillMapper; @Autowired private AnaallillMapper anaallillMapper; @Autowired private ChildcheckMapper childcheckMapper; @Autowired private ChildillMapper childillMapper; @Autowired private AnimalillMapper animalillMapper; @Autowired private ChildcheckMapper childCheckMapper; @Autowired private ManureMapper manureMapper; @Autowired private LastnecareabackMapper lastnecareabackMapper; @Override @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class) public Dog addDog(String username, String dogname, String dogsex, String dogbelonghamlet, String ownerhamletcode, int dogownerid, String dogweight, String dogcolor, int dogage,String govcode) throws Exception { String result = "添加失败"; Dog sheepdog = null; DogExample example = new DogExample(); example.createCriteria().andDogownerIdEqualTo(dogownerid).andDogGovcodeEqualTo(govcode); List<Dog> dogList = dogMapper.selectByExample(example); if (dogList!=null && dogList.size()==1) { return dogList.get(0); }else if(dogList.size()>1){ return null; } sheepdog = new Dog(); sheepdog.setDogName(dogname); sheepdog.setNecId("-1"); sheepdog.setAppId("-1"); sheepdog.setUsername(username); sheepdog.setManagerName(managerMapper.findUserByName(username).getManagerName()); sheepdog.setDogownerId(dogownerid); sheepdog.setDogWeight(dogweight); sheepdog.setDogColor(dogcolor); sheepdog.setDogAge(dogage); sheepdog.setDogInfo("健康"); sheepdog.setDogStatus("1"); sheepdog.setDogRegistertime(new Date()); sheepdog.setDogSex(dogsex); sheepdog.setDistrictcode(ownerhamletcode); sheepdog.setDogGovcode(govcode); boolean flag = dogMapper.insert(sheepdog)==0?false:true; if(flag){ return sheepdog; } return sheepdog; } @Override public Map<String, Object> getDogList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<DogView> doglist = dogMapper.getDogListByDistrictcode(districtcode); Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", doglist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getDogInfo(Integer dogid) { Dog dog = dogMapper.selectByPrimaryKey(dogid); Map<String, Object> map = new HashMap<String,Object>(); map.put("dog",dog); String admintel = managerMapper.findUserByName(dog.getUsername()).getManagerTel(); map.put("admintel",admintel); String hamlet = districtMapper.selectByDistrictCode(dog.getDistrictcode()).getDistrictName(); map.put("hamlet",hamlet); String nec_id = dog.getNecId(); if(!nec_id.equals("-1")){ Lastnecdosing lastnecdosing = lastnecdosingMapper.getLastnecdosing(nec_id); map.put("nec",lastnecdosing); } String app_id = dog.getAppId(); if(!app_id.equals("-1")){ Lastappdosing lastappdosing = lastappdosingMapper.getLastappdosing(app_id); map.put("app",lastappdosing); } Integer ownerid = dog.getDogownerId(); Dogowner dogowner = dogownerMapper.selectByPrimaryKey(ownerid); map.put("owner",dogowner); return map; } @Override public String modifyDog(Integer dogid, String dogname, String dogsex, String dogweight, String dogcolor, Integer dogage) { Dog dog = dogMapper.selectByPrimaryKey(dogid); dog.setDogName(dogname); dog.setDogSex(dogsex); dog.setDogWeight(dogweight); dog.setDogColor(dogcolor); dog.setDogAge(dogage); String res = dogMapper.updateByPrimaryKey(dog)>0?"修改成功!":"修改失败"; return res; } @Override public Map<String, Object> getDogStaList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); // List<DogView> doglist = dogMapper.getDogListByDistrictcode(districtcode); List<DogSta> dogstalist = new ArrayList<>(); DogSta dogSta = null; int count = 1; switch (districtcode.length()){ case 1: //国家级管理员 List<District> districtList = districtMapper.getProvinces(); for(int i=0;i<districtList.size();i++){ dogSta = new DogSta(); dogSta.setCountnum(count); count++; dogSta.setDistrictname(districtList.get(i).getDistrictName()); String provinceCode0to2 = districtList.get(i).getDistrictcode().substring(0,2); //获得该省所有的狗 List<Dog> sdlist = dogMapper.getIndexInforByDistrictcode(provinceCode0to2); dogSta.setDognum(sdlist.size()); //佩戴项圈牧犬数量和喂食器数量 int neckdognumtotal = 0; int feedernumtotal = 0; for(Dog each:sdlist){ //"-1"表示未佩戴项圈 if(!each.getNecId().equals("-1")) { neckdognumtotal++; } //"-1"表示无喂食器 if(!each.getAppId().equals("-1")) { feedernumtotal++; } } dogSta.setNecdognum(neckdognumtotal); dogSta.setAppdognum(feedernumtotal); dogSta.setManagedognum(sdlist.size()); if(sdlist.size() == 0){ dogSta.setNecdognumper("0"); dogSta.setAppdognumper("0"); }else{ DecimalFormat df = new DecimalFormat("0.00");//保留2位小数 // String s = df.format(num); dogSta.setNecdognumper(df.format((neckdognumtotal/(sdlist.size()*1.00))*100)+"%"); dogSta.setAppdognumper(df.format((feedernumtotal/(sdlist.size()*1.00))*100)+"%"); } dogstalist.add(dogSta); } break; case 2: //省级管理员 List<District> districtList2 = districtMapper.getCities(districtcode); for(int i=0;i<districtList2.size();i++){ dogSta = new DogSta(); dogSta.setCountnum(count); count++; dogSta.setDistrictname(districtList2.get(i).getDistrictName()); String cityCode0to4 = districtList2.get(i).getDistrictcode().substring(0,4); //获得该省所有的狗 List<Dog> sdlist = dogMapper.getIndexInforByDistrictcode(cityCode0to4); dogSta.setDognum(sdlist.size()); //佩戴项圈牧犬数量和喂食器数量 int neckdognumtotal = 0; int feedernumtotal = 0; for(Dog each:sdlist){ //"-1"表示未佩戴项圈 if(!each.getNecId().equals("-1")) { neckdognumtotal++; } //"-1"表示无喂食器 if(!each.getAppId().equals("-1")) { feedernumtotal++; } } dogSta.setNecdognum(neckdognumtotal); dogSta.setAppdognum(feedernumtotal); dogSta.setManagedognum(sdlist.size()); if(sdlist.size() == 0){ dogSta.setNecdognumper("0"); dogSta.setAppdognumper("0"); }else{ DecimalFormat df = new DecimalFormat("0.00");//保留2位小数 // String s = df.format(num); dogSta.setNecdognumper(df.format((neckdognumtotal/(sdlist.size()*1.00))*100)+"%"); dogSta.setAppdognumper(df.format((feedernumtotal/(sdlist.size()*1.00))*100)+"%"); } dogstalist.add(dogSta); } break; case 4: //市级管理员 List<District> districtList3 = districtMapper.getCounties(districtcode); for(int i=0;i<districtList3.size();i++){ dogSta = new DogSta(); dogSta.setCountnum(count); count++; dogSta.setDistrictname(districtList3.get(i).getDistrictName()); String countyCode0to6 = districtList3.get(i).getDistrictcode().substring(0,6); //获得该市所有的狗 List<Dog> sdlist = dogMapper.getIndexInforByDistrictcode(countyCode0to6); dogSta.setDognum(sdlist.size()); //佩戴项圈牧犬数量和喂食器数量 int neckdognumtotal = 0; int feedernumtotal = 0; for(Dog each:sdlist){ //"-1"表示未佩戴项圈 if(!each.getNecId().equals("-1")) { neckdognumtotal++; } //"-1"表示无喂食器 if(!each.getAppId().equals("-1")) { feedernumtotal++; } } dogSta.setNecdognum(neckdognumtotal); dogSta.setAppdognum(feedernumtotal); dogSta.setManagedognum(sdlist.size()); if(sdlist.size() == 0){ dogSta.setNecdognumper("0"); dogSta.setAppdognumper("0"); }else{ DecimalFormat df = new DecimalFormat("0.00");//保留2位小数 // String s = df.format(num); dogSta.setNecdognumper(df.format((neckdognumtotal/(sdlist.size()*1.00))*100)+"%"); dogSta.setAppdognumper(df.format((feedernumtotal/(sdlist.size()*1.00))*100)+"%"); } dogstalist.add(dogSta); } break; case 6: //县级管理员 List<District> districtList4 = districtMapper.getVillages(districtcode); for(int i=0;i<districtList4.size();i++){ dogSta = new DogSta(); dogSta.setCountnum(count); count++; dogSta.setDistrictname(districtList4.get(i).getDistrictName()); String villageCode0to9 = districtList4.get(i).getDistrictcode().substring(0,9); //获得该县所有的狗 List<Dog> sdlist = dogMapper.getIndexInforByDistrictcode(villageCode0to9); dogSta.setDognum(sdlist.size()); //佩戴项圈牧犬数量和喂食器数量 int neckdognumtotal = 0; int feedernumtotal = 0; for(Dog each:sdlist){ //"-1"表示未佩戴项圈 if(!each.getNecId().equals("-1")) { neckdognumtotal++; } //"-1"表示无喂食器 if(!each.getAppId().equals("-1")) { feedernumtotal++; } } dogSta.setNecdognum(neckdognumtotal); dogSta.setAppdognum(feedernumtotal); dogSta.setManagedognum(sdlist.size()); if(sdlist.size() == 0){ dogSta.setNecdognumper("0"); dogSta.setAppdognumper("0"); }else{ // DecimalFormat df = new DecimalFormat("0.0000");//保留4位小数 // String s = df.format(num); // dogSta.setNecdognumper((neckdognumtotal/(sdlist.size()*1.00))*100+"%"); // dogSta.setAppdognumper((feedernumtotal/(sdlist.size()*1.00))*100+"%"); DecimalFormat df = new DecimalFormat("0.00");//保留2位小数 // String s = df.format(num); dogSta.setNecdognumper(df.format((neckdognumtotal/(sdlist.size()*1.00))*100)+"%"); dogSta.setAppdognumper(df.format((feedernumtotal/(sdlist.size()*1.00))*100)+"%"); } dogstalist.add(dogSta); } break; case 9: //乡级管理员 List<District> districtList5 = districtMapper.getHamlets(districtcode); for(int i=0;i<districtList5.size();i++){ dogSta = new DogSta(); dogSta.setCountnum(count); count++; dogSta.setDistrictname(districtList5.get(i).getDistrictName()); String hamletCode = districtList5.get(i).getDistrictcode(); //获得该乡所有的狗 List<Dog> sdlist = dogMapper.getIndexInforByDistrictcode(hamletCode); dogSta.setDognum(sdlist.size()); //佩戴项圈牧犬数量和喂食器数量 int neckdognumtotal = 0; int feedernumtotal = 0; for(Dog each:sdlist){ //"-1"表示未佩戴项圈 if(!each.getNecId().equals("-1")) { neckdognumtotal++; } //"-1"表示无喂食器 if(!each.getAppId().equals("-1")) { feedernumtotal++; } } dogSta.setNecdognum(neckdognumtotal); dogSta.setAppdognum(feedernumtotal); dogSta.setManagedognum(sdlist.size()); if(sdlist.size() == 0){ dogSta.setNecdognumper("0"); dogSta.setAppdognumper("0"); }else{ // DecimalFormat df = new DecimalFormat("0.0000");//保留4位小数 // String s = df.format(num); // dogSta.setNecdognumper((neckdognumtotal/(sdlist.size()*1.00))*100+"%"); // dogSta.setAppdognumper((feedernumtotal/(sdlist.size()*1.00))*100+"%"); DecimalFormat df = new DecimalFormat("0.00");//保留2位小数 // String s = df.format(num); dogSta.setNecdognumper(df.format((neckdognumtotal/(sdlist.size()*1.00))*100)+"%"); dogSta.setAppdognumper(df.format((feedernumtotal/(sdlist.size()*1.00))*100)+"%"); } dogstalist.add(dogSta); } break; } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", dogstalist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getDeviceStaList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<DeviceSta> devicestalist = new ArrayList<>(); DeviceSta deviceSta = null; int count = 1; switch (districtcode.length()){ case 1: //国家级管理员 List<District> districtList = districtMapper.getProvinces(); for(int i=0;i<districtList.size();i++){ deviceSta = new DeviceSta(); deviceSta.setCountnum(count); count++; deviceSta.setDistrictname(districtList.get(i).getDistrictName()); String provinceCode0to2 = districtList.get(i).getDistrictcode().substring(0,2); //获得该省所有的狗 List<Dog> sdlist = dogMapper.getIndexInforByDistrictcode(provinceCode0to2); deviceSta.setDognum(sdlist.size()); //佩戴项圈牧犬数量和喂食器数量 int neckdognumtotal = 0; int feedernumtotal = 0; int necbadnum = 0; int appbadnum = 0; for(Dog each:sdlist){ //项圈 if(!each.getNecId().equals("-1")) { neckdognumtotal++; String nec_status = "0"; Lastnecareaback lastnecareaback = lastnecareabackMapper.getLastnecareaback(each.getNecId()); if(lastnecareaback != null){ nec_status = lastnecareaback.getNecStatus(); if(nec_status != null && !nec_status.equals("0")){ necbadnum++; } } } //喂食器(待开发) if(!each.getAppId().equals("-1")) { feedernumtotal++; } } deviceSta.setNecdognum(neckdognumtotal); deviceSta.setAppdognum(feedernumtotal); deviceSta.setManagedognum(sdlist.size()); deviceSta.setNecbadnum(necbadnum); deviceSta.setAppbadnum(0); if(sdlist.size() == 0){ deviceSta.setNecbadnumper("0.00%"); deviceSta.setAppbadnumper("0.00%"); }else{ DecimalFormat df = new DecimalFormat("0.00");//保留2位小数 if(neckdognumtotal!=0){ //暂时只考虑了项圈 deviceSta.setNecbadnumper(df.format((necbadnum/(neckdognumtotal*1.00))*100)+"%"); deviceSta.setAppbadnumper("0.00%"); deviceSta.setAllbadnum(necbadnum+appbadnum); deviceSta.setAllbadnumper(df.format((necbadnum/(neckdognumtotal*1.00))*100)+"%"); }else{ deviceSta.setNecbadnumper("0.00%"); deviceSta.setAppbadnumper("0.00%"); deviceSta.setAllbadnum(necbadnum+appbadnum); deviceSta.setAllbadnumper("0.00%"); } } devicestalist.add(deviceSta); } break; case 2: //省级管理员 List<District> districtList2 = districtMapper.getCities(districtcode); for(int i=0;i<districtList2.size();i++){ deviceSta = new DeviceSta(); deviceSta.setCountnum(count); count++; deviceSta.setDistrictname(districtList2.get(i).getDistrictName()); String cityCode0to4 = districtList2.get(i).getDistrictcode().substring(0,4); //获得该省所有的狗 List<Dog> sdlist = dogMapper.getIndexInforByDistrictcode(cityCode0to4); deviceSta.setDognum(sdlist.size()); //佩戴项圈牧犬数量和喂食器数量 int neckdognumtotal = 0; int feedernumtotal = 0; int necbadnum = 0; int appbadnum = 0; for(Dog each:sdlist){ //项圈 if(!each.getNecId().equals("-1")) { neckdognumtotal++; String nec_status = "0"; Lastnecareaback lastnecareaback = lastnecareabackMapper.getLastnecareaback(each.getNecId()); if(lastnecareaback != null){ nec_status = lastnecareaback.getNecStatus(); if(nec_status != null && !nec_status.equals("0")){ necbadnum++; } } } //喂食器(待开发) if(!each.getAppId().equals("-1")) { feedernumtotal++; } } deviceSta.setNecbadnum(necbadnum); deviceSta.setAppbadnum(0); deviceSta.setNecdognum(neckdognumtotal); deviceSta.setAppdognum(feedernumtotal); deviceSta.setManagedognum(sdlist.size()); if(sdlist.size() == 0){ deviceSta.setNecbadnumper("0.00%"); deviceSta.setAppbadnumper("0.00%"); }else{ DecimalFormat df = new DecimalFormat("0.00");//保留2位小数 if(neckdognumtotal!=0){ //暂时只考虑了项圈 deviceSta.setNecbadnumper(df.format((necbadnum/(neckdognumtotal*1.00))*100)+"%"); deviceSta.setAppbadnumper("0.00%"); deviceSta.setAllbadnum(necbadnum+appbadnum); deviceSta.setAllbadnumper(df.format((necbadnum/(neckdognumtotal*1.00))*100)+"%"); }else{ deviceSta.setNecbadnumper("0.00%"); deviceSta.setAppbadnumper("0.00%"); deviceSta.setAllbadnum(necbadnum+appbadnum); deviceSta.setAllbadnumper("0.00%"); } } devicestalist.add(deviceSta); } break; case 4: //市级管理员 List<District> districtList3 = districtMapper.getCounties(districtcode); for(int i=0;i<districtList3.size();i++){ deviceSta = new DeviceSta(); deviceSta.setCountnum(count); count++; deviceSta.setDistrictname(districtList3.get(i).getDistrictName()); String countyCode0to6 = districtList3.get(i).getDistrictcode().substring(0,6); //获得该市所有的狗 List<Dog> sdlist = dogMapper.getIndexInforByDistrictcode(countyCode0to6); deviceSta.setDognum(sdlist.size()); //佩戴项圈牧犬数量和喂食器数量 int neckdognumtotal = 0; int feedernumtotal = 0; int necbadnum = 0; int appbadnum = 0; for(Dog each:sdlist){ //项圈 if(!each.getNecId().equals("-1")) { neckdognumtotal++; String nec_status = "0"; Lastnecareaback lastnecareaback = lastnecareabackMapper.getLastnecareaback(each.getNecId()); if(lastnecareaback != null){ nec_status = lastnecareaback.getNecStatus(); if(nec_status != null && !nec_status.equals("0")){ necbadnum++; } } } //喂食器(待开发) if(!each.getAppId().equals("-1")) { feedernumtotal++; } } deviceSta.setNecbadnum(necbadnum); deviceSta.setAppbadnum(0); deviceSta.setNecdognum(neckdognumtotal); deviceSta.setAppdognum(feedernumtotal); deviceSta.setManagedognum(sdlist.size()); if(sdlist.size() == 0){ deviceSta.setNecbadnumper("0.00%"); deviceSta.setAppbadnumper("0.00%"); }else{ DecimalFormat df = new DecimalFormat("0.00");//保留2位小数 if(neckdognumtotal!=0){ //暂时只考虑了项圈 deviceSta.setNecbadnumper(df.format((necbadnum/(neckdognumtotal*1.00))*100)+"%"); deviceSta.setAppbadnumper("0.00%"); deviceSta.setAllbadnum(necbadnum+appbadnum); deviceSta.setAllbadnumper(df.format((necbadnum/(neckdognumtotal*1.00))*100)+"%"); }else{ deviceSta.setNecbadnumper("0.00%"); deviceSta.setAppbadnumper("0.00%"); deviceSta.setAllbadnum(necbadnum+appbadnum); deviceSta.setAllbadnumper("0.00%"); } } devicestalist.add(deviceSta); } break; case 6: //县级管理员 List<District> districtList4 = districtMapper.getVillages(districtcode); for(int i=0;i<districtList4.size();i++){ deviceSta = new DeviceSta(); deviceSta.setCountnum(count); count++; deviceSta.setDistrictname(districtList4.get(i).getDistrictName()); String villageCode0to9 = districtList4.get(i).getDistrictcode().substring(0,9); //获得该县所有的狗 List<Dog> sdlist = dogMapper.getIndexInforByDistrictcode(villageCode0to9); deviceSta.setDognum(sdlist.size()); //佩戴项圈牧犬数量和喂食器数量 int neckdognumtotal = 0; int feedernumtotal = 0; int necbadnum = 0; int appbadnum = 0; for(Dog each:sdlist){ //项圈 if(!each.getNecId().equals("-1")) { neckdognumtotal++; String nec_status = "0"; Lastnecareaback lastnecareaback = lastnecareabackMapper.getLastnecareaback(each.getNecId()); if(lastnecareaback != null){ nec_status = lastnecareaback.getNecStatus(); if(nec_status != null && !nec_status.equals("0")){ necbadnum++; } } } //喂食器(待开发) if(!each.getAppId().equals("-1")) { feedernumtotal++; } } deviceSta.setNecbadnum(necbadnum); deviceSta.setAppbadnum(0); deviceSta.setNecdognum(neckdognumtotal); deviceSta.setAppdognum(feedernumtotal); deviceSta.setManagedognum(sdlist.size()); if(sdlist.size() == 0){ deviceSta.setNecbadnumper("0.00%"); deviceSta.setAppbadnumper("0.00%"); }else{ DecimalFormat df = new DecimalFormat("0.00");//保留2位小数 if(neckdognumtotal!=0){ //暂时只考虑了项圈 deviceSta.setNecbadnumper(df.format((necbadnum/(neckdognumtotal*1.00))*100)+"%"); deviceSta.setAppbadnumper("0.00%"); deviceSta.setAllbadnum(necbadnum+appbadnum); deviceSta.setAllbadnumper(df.format((necbadnum/(neckdognumtotal*1.00))*100)+"%"); }else{ deviceSta.setNecbadnumper("0.00%"); deviceSta.setAppbadnumper("0.00%"); deviceSta.setAllbadnum(necbadnum+appbadnum); deviceSta.setAllbadnumper("0.00%"); } } devicestalist.add(deviceSta); } break; case 9: //乡级管理员 List<District> districtList5 = districtMapper.getHamlets(districtcode); for(int i=0;i<districtList5.size();i++){ deviceSta = new DeviceSta(); deviceSta.setCountnum(count); count++; deviceSta.setDistrictname(districtList5.get(i).getDistrictName()); String hamletCode = districtList5.get(i).getDistrictcode(); //获得该乡所有的狗 List<Dog> sdlist = dogMapper.getIndexInforByDistrictcode(hamletCode); deviceSta.setDognum(sdlist.size()); //佩戴项圈牧犬数量和喂食器数量 int neckdognumtotal = 0; int feedernumtotal = 0; int necbadnum = 0; int appbadnum = 0; for(Dog each:sdlist){ //项圈 if(!each.getNecId().equals("-1")) { neckdognumtotal++; String nec_status = "0"; Lastnecareaback lastnecareaback = lastnecareabackMapper.getLastnecareaback(each.getNecId()); if(lastnecareaback != null){ nec_status = lastnecareaback.getNecStatus(); if(nec_status != null && !nec_status.equals("0")){ necbadnum++; } } } //喂食器(待开发) if(!each.getAppId().equals("-1")) { feedernumtotal++; } } deviceSta.setNecbadnum(necbadnum); deviceSta.setAppbadnum(0); deviceSta.setNecdognum(neckdognumtotal); deviceSta.setAppdognum(feedernumtotal); deviceSta.setManagedognum(sdlist.size()); if(sdlist.size() == 0){ deviceSta.setNecbadnumper("0.00%"); deviceSta.setAppbadnumper("0.00%"); }else{ DecimalFormat df = new DecimalFormat("0.00");//保留2位小数 if(neckdognumtotal!=0){ //暂时只考虑了项圈 deviceSta.setNecbadnumper(df.format((necbadnum/(neckdognumtotal*1.00))*100)+"%"); deviceSta.setAppbadnumper("0.00%"); deviceSta.setAllbadnum(necbadnum+appbadnum); deviceSta.setAllbadnumper(df.format((necbadnum/(neckdognumtotal*1.00))*100)+"%"); }else{ deviceSta.setNecbadnumper("0.00%"); deviceSta.setAppbadnumper("0.00%"); deviceSta.setAllbadnum(necbadnum+appbadnum); deviceSta.setAllbadnumper("0.00%"); } } devicestalist.add(deviceSta); } break; } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", devicestalist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getIllStaList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<Analyzeill> illstalist = new ArrayList<>(); Analyzeill illsta = null; int count = 1; switch (districtcode.length()){ case 1: //国家级管理员 AnalyzeillExample example1 = new AnalyzeillExample(); example1.createCriteria().andDistrictLevelEqualTo(0); illstalist = analyzeillMapper.selectByExample(example1); break; case 2: //省级管理员 AnalyzeillExample example2 = new AnalyzeillExample(); example2.createCriteria().andDistrictLevelEqualTo(1).andDistrictcodeLike(districtcode.substring(0,2)+"%"); illstalist = analyzeillMapper.selectByExample(example2); break; case 4: //市级管理员 AnalyzeillExample example3 = new AnalyzeillExample(); example3.createCriteria().andDistrictLevelEqualTo(2).andDistrictcodeLike(districtcode.substring(0,4)+"%"); illstalist = analyzeillMapper.selectByExample(example3); break; case 6: //县级管理员 AnalyzeillExample example4 = new AnalyzeillExample(); example4.createCriteria().andDistrictLevelEqualTo(3).andDistrictcodeLike(districtcode.substring(0,6)+"%"); illstalist = analyzeillMapper.selectByExample(example4); break; case 9: //乡级管理员 AnalyzeillExample example5 = new AnalyzeillExample(); example5.createCriteria().andDistrictLevelEqualTo(4).andDistrictcodeLike(districtcode.substring(0,9)+"%"); illstalist = analyzeillMapper.selectByExample(example5); break; } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", illstalist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getBillStaList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<Anaallill> illstalist = new ArrayList<>(); Analyzeill illsta = null; int count = 1; switch (districtcode.length()){ case 1: //国家级管理员 AnaallillExample example1 = new AnaallillExample(); example1.createCriteria().andDistrictLevelEqualTo(0); illstalist = anaallillMapper.selectByExample(example1); break; case 2: //省级管理员 AnaallillExample example2 = new AnaallillExample(); example2.createCriteria().andDistrictLevelEqualTo(1).andDistrictcodeLike(districtcode.substring(0,2)+"%"); illstalist = anaallillMapper.selectByExample(example2); break; case 4: //市级管理员 AnaallillExample example3 = new AnaallillExample(); example3.createCriteria().andDistrictLevelEqualTo(2).andDistrictcodeLike(districtcode.substring(0,4)+"%"); illstalist = anaallillMapper.selectByExample(example3); break; case 6: //县级管理员 AnaallillExample example4 = new AnaallillExample(); example4.createCriteria().andDistrictLevelEqualTo(3).andDistrictcodeLike(districtcode.substring(0,6)+"%"); illstalist = anaallillMapper.selectByExample(example4); break; case 9: //乡级管理员 AnaallillExample example5 = new AnaallillExample(); example5.createCriteria().andDistrictLevelEqualTo(4).andDistrictcodeLike(districtcode.substring(0,9)+"%"); illstalist = anaallillMapper.selectByExample(example5); break; } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", illstalist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getAnaBillStaList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<District> districtList = new ArrayList<>(); List<Childill> illAllstalist = new ArrayList<>(); List<Childill> illstalist = new ArrayList<>(); List<AnaChildill> anaillstalist = new ArrayList<>(); AnaChildill anaChildill = null; int count = 1; illAllstalist = childillMapper.selectByExample(new ChildillExample()); switch (districtcode.length()){ case 1: //国家级管理员 districtList = districtMapper.getProvinces(); for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Childill cd : illAllstalist){ if(cd.getBcheckres()!=null && cd.getBcheckres()!= "" && cd.getNum().substring(0,2).equals(di.getDistrictcode().substring(0,2))){ checknum++; if(cd.getBcheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 2: //省级管理员 districtList = districtMapper.getCities(districtcode); for(Childill cd : illAllstalist){ if(cd.getNum().substring(0,2).equals(districtcode)){ illstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Childill cd : illstalist){ if(cd.getBcheckres()!=null && cd.getBcheckres()!= "" && cd.getNum().substring(0,4).equals(di.getDistrictcode().substring(0,4))){ checknum++; if(cd.getBcheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 4: //市级管理员 districtList = districtMapper.getCounties(districtcode); for(Childill cd : illAllstalist){ if(cd.getNum().substring(0,4).equals(districtcode)){ illstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Childill cd : illstalist){ if(cd.getBcheckres()!=null && cd.getBcheckres()!= "" && cd.getNum().substring(0,6).equals(di.getDistrictcode().substring(0,6))){ checknum++; if(cd.getBcheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 6: //县级管理员 districtList = districtMapper.getVillages(districtcode); for(Childill cd : illAllstalist){ if(cd.getNum().substring(0,6).equals(districtcode)){ illstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Childill cd : illstalist){ if(cd.getBcheckres()!=null && cd.getBcheckres()!= "" && cd.getNum().substring(0,9).equals(di.getDistrictcode().substring(0,9))){ checknum++; if(cd.getBcheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 9: //乡级管理员 districtList = districtMapper.getHamlets(districtcode); for(Childill cd : illAllstalist){ if(cd.getNum().substring(0,9).equals(districtcode)){ illstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Childill cd : illstalist){ if(cd.getBcheckres()!=null && cd.getBcheckres()!= "" && cd.getNum().equals(di.getDistrictcode())){ checknum++; if(cd.getBcheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", anaillstalist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getAnaChildCheckStaList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<District> districtList = new ArrayList<>(); List<Childcheck> checkAllstalist = new ArrayList<>(); List<Childcheck> checkstalist = new ArrayList<>(); List<AnaChildill> anaillstalist = new ArrayList<>(); AnaChildill anaChildill = null; int count = 1; checkAllstalist = childCheckMapper.selectByExample(new ChildcheckExample()); switch (districtcode.length()){ case 1: //国家级管理员 districtList = districtMapper.getProvinces(); for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Childcheck cd : checkAllstalist){ if(cd.getCheckres()!=null && cd.getCheckres()!= "" && cd.getNum().substring(0,2).equals(di.getDistrictcode().substring(0,2))){ checknum++; if(cd.getCheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 2: //省级管理员 districtList = districtMapper.getCities(districtcode); for(Childcheck cd : checkAllstalist){ if(cd.getNum().substring(0,2).equals(districtcode)){ checkstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Childcheck cd : checkstalist){ if(cd.getCheckres()!=null && cd.getCheckres()!= "" && cd.getNum().substring(0,4).equals(di.getDistrictcode().substring(0,4))){ checknum++; if(cd.getCheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 4: //市级管理员 districtList = districtMapper.getCounties(districtcode); for(Childcheck cd : checkAllstalist){ if(cd.getNum().substring(0,4).equals(districtcode)){ checkstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Childcheck cd : checkstalist){ if(cd.getCheckres()!=null && cd.getCheckres()!= "" && cd.getNum().substring(0,6).equals(di.getDistrictcode().substring(0,6))){ checknum++; if(cd.getCheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 6: //县级管理员 districtList = districtMapper.getVillages(districtcode); for(Childcheck cd : checkAllstalist){ if(cd.getNum().substring(0,6).equals(districtcode)){ checkstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Childcheck cd : checkstalist){ if(cd.getCheckres()!=null && cd.getCheckres()!= "" && cd.getNum().substring(0,9).equals(di.getDistrictcode().substring(0,9))){ checknum++; if(cd.getCheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 9: //乡级管理员 districtList = districtMapper.getHamlets(districtcode); for(Childcheck cd : checkAllstalist){ if(cd.getNum().substring(0,9).equals(districtcode)){ checkstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Childcheck cd : checkstalist){ if(cd.getCheckres()!=null && cd.getCheckres()!= "" && cd.getNum().equals(di.getDistrictcode())){ checknum++; if(cd.getCheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", anaillstalist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getAnaDogillStaList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<District> districtList = new ArrayList<>(); List<Manure> dogillAllstalist = new ArrayList<>(); List<Manure> dogillstalist = new ArrayList<>(); List<AnaChildill> anaillstalist = new ArrayList<>(); AnaChildill anaChildill = null; int count = 1; dogillAllstalist = manureMapper.selectByExample(new ManureExample()); switch (districtcode.length()){ case 1: //国家级管理员 districtList = districtMapper.getProvinces(); for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Manure cd : dogillAllstalist){ if(cd.getTestingResult()!=null && cd.getTestingResult()!= "" && cd.getDistrictcode().substring(0,2).equals(di.getDistrictcode().substring(0,2))){ checknum++; if(cd.getTestingResult().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 2: //省级管理员 districtList = districtMapper.getCities(districtcode); for(Manure cd : dogillAllstalist){ if(cd.getDistrictcode().substring(0,2).equals(districtcode)){ dogillstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Manure cd : dogillstalist){ if(cd.getTestingResult()!=null && cd.getTestingResult()!= "" && cd.getDistrictcode().substring(0,4).equals(di.getDistrictcode().substring(0,4))){ checknum++; if(cd.getTestingResult().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 4: //市级管理员 districtList = districtMapper.getCounties(districtcode); for(Manure cd : dogillAllstalist){ if(cd.getDistrictcode().substring(0,4).equals(districtcode)){ dogillstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Manure cd : dogillstalist){ if(cd.getTestingResult()!=null && cd.getTestingResult()!= "" && cd.getDistrictcode().substring(0,6).equals(di.getDistrictcode().substring(0,6))){ checknum++; if(cd.getTestingResult().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 6: //县级管理员 districtList = districtMapper.getVillages(districtcode); for(Manure cd : dogillAllstalist){ if(cd.getDistrictcode().substring(0,6).equals(districtcode)){ dogillstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Manure cd : dogillstalist){ if(cd.getTestingResult()!=null && cd.getTestingResult()!= "" && cd.getDistrictcode().substring(0,9).equals(di.getDistrictcode().substring(0,9))){ checknum++; if(cd.getTestingResult().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 9: //乡级管理员 districtList = districtMapper.getHamlets(districtcode); for(Manure cd : dogillAllstalist){ if(cd.getDistrictcode().substring(0,9).equals(districtcode)){ dogillstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Manure cd : dogillstalist){ if(cd.getTestingResult()!=null && cd.getTestingResult()!= "" && cd.getDistrictcode().equals(di.getDistrictcode())){ checknum++; if(cd.getTestingResult().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", anaillstalist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getAnaAnimalillStaList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<District> districtList = new ArrayList<>(); List<Animalill> dogillAllstalist = new ArrayList<>(); List<Animalill> dogillstalist = new ArrayList<>(); List<AnaChildill> anaillstalist = new ArrayList<>(); AnaChildill anaChildill = null; int count = 1; dogillAllstalist = animalillMapper.selectByExample(new AnimalillExample()); switch (districtcode.length()){ case 1: //国家级管理员 districtList = districtMapper.getProvinces(); for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Animalill cd : dogillAllstalist){ if(cd.getCheckres()!=null && cd.getCheckres()!= "" && cd.getNum().substring(0,2).equals(di.getDistrictcode().substring(0,2))){ checknum++; if(cd.getCheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 2: //省级管理员 districtList = districtMapper.getCities(districtcode); for(Animalill cd : dogillAllstalist){ if(cd.getNum().substring(0,2).equals(districtcode)){ dogillstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Animalill cd : dogillstalist){ if(cd.getCheckres()!=null && cd.getCheckres()!= "" && cd.getNum().substring(0,4).equals(di.getDistrictcode().substring(0,4))){ checknum++; if(cd.getCheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 4: //市级管理员 districtList = districtMapper.getCounties(districtcode); for(Animalill cd : dogillAllstalist){ if(cd.getNum().substring(0,4).equals(districtcode)){ dogillstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Animalill cd : dogillstalist){ if(cd.getCheckres()!=null && cd.getCheckres()!= "" && cd.getNum().substring(0,6).equals(di.getDistrictcode().substring(0,6))){ checknum++; if(cd.getCheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 6: //县级管理员 districtList = districtMapper.getVillages(districtcode); for(Animalill cd : dogillAllstalist){ if(cd.getNum().substring(0,6).equals(districtcode)){ dogillstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Animalill cd : dogillstalist){ if(cd.getCheckres()!=null && cd.getCheckres()!= "" && cd.getNum().substring(0,9).equals(di.getDistrictcode().substring(0,9))){ checknum++; if(cd.getCheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 9: //乡级管理员 districtList = districtMapper.getHamlets(districtcode); for(Animalill cd : dogillAllstalist){ if(cd.getNum().substring(0,9).equals(districtcode)){ dogillstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Animalill cd : dogillstalist){ if(cd.getCheckres()!=null && cd.getCheckres()!= "" && cd.getNum().equals(di.getDistrictcode())){ checknum++; if(cd.getCheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", anaillstalist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getChildCheckList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<Childcheck> childchecklist = new ArrayList<>(); Childcheck childcheck = null; int count = 1; switch (districtcode.length()){ case 1: //国家级管理员 ChildcheckExample example1 = new ChildcheckExample(); childchecklist = childcheckMapper.selectByExample(example1); break; case 2: //省级管理员 ChildcheckExample example2 = new ChildcheckExample(); example2.createCriteria().andNumLike(districtcode.substring(0,2)+"%"); childchecklist = childcheckMapper.selectByExample(example2); break; case 4: //市级管理员 ChildcheckExample example3 = new ChildcheckExample(); example3.createCriteria().andNumLike(districtcode.substring(0,4)+"%"); childchecklist = childcheckMapper.selectByExample(example3); break; case 6: //县级管理员 ChildcheckExample example4 = new ChildcheckExample(); example4.createCriteria().andNumLike(districtcode.substring(0,6)+"%"); childchecklist = childcheckMapper.selectByExample(example4); break; case 9: //乡级管理员 ChildcheckExample example5 = new ChildcheckExample(); example5.createCriteria().andNumLike(districtcode.substring(0,9)+"%"); childchecklist = childcheckMapper.selectByExample(example5); break; case 12: //村级管理员 ChildcheckExample example6 = new ChildcheckExample(); example6.createCriteria().andNumEqualTo(districtcode); childchecklist = childcheckMapper.selectByExample(example6); } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", childchecklist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getAnimalillList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<Animalill> animalillList = new ArrayList<>(); Animalill animalill = null; int count = 1; switch (districtcode.length()){ case 1: //国家级管理员 AnimalillExample example1 = new AnimalillExample(); animalillList = animalillMapper.selectByExample(example1); break; case 2: //省级管理员 AnimalillExample example2 = new AnimalillExample(); example2.createCriteria().andNumLike(districtcode.substring(0,2)+"%"); animalillList = animalillMapper.selectByExample(example2); break; case 4: //市级管理员 AnimalillExample example3 = new AnimalillExample(); example3.createCriteria().andNumLike(districtcode.substring(0,4)+"%"); animalillList = animalillMapper.selectByExample(example3); break; case 6: //县级管理员 AnimalillExample example4 = new AnimalillExample(); example4.createCriteria().andNumLike(districtcode.substring(0,6)+"%"); animalillList = animalillMapper.selectByExample(example4); break; case 9: //乡级管理员 AnimalillExample example5 = new AnimalillExample(); example5.createCriteria().andNumLike(districtcode.substring(0,9)+"%"); animalillList = animalillMapper.selectByExample(example5); break; case 12: //村级管理员 AnimalillExample example6 = new AnimalillExample(); example6.createCriteria().andNumEqualTo(districtcode); animalillList = animalillMapper.selectByExample(example6); } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", animalillList); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getChildIllList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<Childill> childilllist = new ArrayList<>(); Childill childill = null; int count = 1; switch (districtcode.length()){ case 1: //国家级管理员 ChildillExample example1 = new ChildillExample(); childilllist = childillMapper.selectByExample(example1); break; case 2: //省级管理员 ChildillExample example2 = new ChildillExample(); example2.createCriteria().andNumLike(districtcode.substring(0,2)+"%"); childilllist = childillMapper.selectByExample(example2); break; case 4: //市级管理员 ChildillExample example3 = new ChildillExample(); example3.createCriteria().andNumLike(districtcode.substring(0,4)+"%"); childilllist = childillMapper.selectByExample(example3); break; case 6: //县级管理员 ChildillExample example4 = new ChildillExample(); example4.createCriteria().andNumLike(districtcode.substring(0,6)+"%"); childilllist = childillMapper.selectByExample(example4); break; case 9: //乡级管理员 ChildillExample example5 = new ChildillExample(); example5.createCriteria().andNumLike(districtcode.substring(0,9)+"%"); childilllist = childillMapper.selectByExample(example5); break; case 12: //村级管理员 ChildillExample example6 = new ChildillExample(); example6.createCriteria().andNumEqualTo(districtcode); childilllist = childillMapper.selectByExample(example6); break; } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", childilllist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } }
UTF-8
Java
78,868
java
DogServiceImpl.java
Java
[ { "context": "pdog.setAppId(\"-1\");\n sheepdog.setUsername(username);\n sheepdog.setManagerName(managerMapper.f", "end": 2506, "score": 0.9580960273742676, "start": 2498, "tag": "USERNAME", "value": "username" } ]
null
[]
package com.sec.aidog.service.impl; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.sec.aidog.dao.*; import com.sec.aidog.model.*; import com.sec.aidog.pojo.*; import com.sec.aidog.service.DogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.text.DecimalFormat; import java.util.*; @Service("dogService") public class DogServiceImpl implements DogService{ @Autowired private DogMapper dogMapper; @Autowired private ManagerMapper managerMapper; @Autowired private LastnecdosingMapper lastnecdosingMapper; @Autowired private LastappdosingMapper lastappdosingMapper; @Autowired private DogownerMapper dogownerMapper; @Autowired private DistrictMapper districtMapper; @Autowired private AnalyzeillMapper analyzeillMapper; @Autowired private AnaallillMapper anaallillMapper; @Autowired private ChildcheckMapper childcheckMapper; @Autowired private ChildillMapper childillMapper; @Autowired private AnimalillMapper animalillMapper; @Autowired private ChildcheckMapper childCheckMapper; @Autowired private ManureMapper manureMapper; @Autowired private LastnecareabackMapper lastnecareabackMapper; @Override @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class) public Dog addDog(String username, String dogname, String dogsex, String dogbelonghamlet, String ownerhamletcode, int dogownerid, String dogweight, String dogcolor, int dogage,String govcode) throws Exception { String result = "添加失败"; Dog sheepdog = null; DogExample example = new DogExample(); example.createCriteria().andDogownerIdEqualTo(dogownerid).andDogGovcodeEqualTo(govcode); List<Dog> dogList = dogMapper.selectByExample(example); if (dogList!=null && dogList.size()==1) { return dogList.get(0); }else if(dogList.size()>1){ return null; } sheepdog = new Dog(); sheepdog.setDogName(dogname); sheepdog.setNecId("-1"); sheepdog.setAppId("-1"); sheepdog.setUsername(username); sheepdog.setManagerName(managerMapper.findUserByName(username).getManagerName()); sheepdog.setDogownerId(dogownerid); sheepdog.setDogWeight(dogweight); sheepdog.setDogColor(dogcolor); sheepdog.setDogAge(dogage); sheepdog.setDogInfo("健康"); sheepdog.setDogStatus("1"); sheepdog.setDogRegistertime(new Date()); sheepdog.setDogSex(dogsex); sheepdog.setDistrictcode(ownerhamletcode); sheepdog.setDogGovcode(govcode); boolean flag = dogMapper.insert(sheepdog)==0?false:true; if(flag){ return sheepdog; } return sheepdog; } @Override public Map<String, Object> getDogList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<DogView> doglist = dogMapper.getDogListByDistrictcode(districtcode); Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", doglist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getDogInfo(Integer dogid) { Dog dog = dogMapper.selectByPrimaryKey(dogid); Map<String, Object> map = new HashMap<String,Object>(); map.put("dog",dog); String admintel = managerMapper.findUserByName(dog.getUsername()).getManagerTel(); map.put("admintel",admintel); String hamlet = districtMapper.selectByDistrictCode(dog.getDistrictcode()).getDistrictName(); map.put("hamlet",hamlet); String nec_id = dog.getNecId(); if(!nec_id.equals("-1")){ Lastnecdosing lastnecdosing = lastnecdosingMapper.getLastnecdosing(nec_id); map.put("nec",lastnecdosing); } String app_id = dog.getAppId(); if(!app_id.equals("-1")){ Lastappdosing lastappdosing = lastappdosingMapper.getLastappdosing(app_id); map.put("app",lastappdosing); } Integer ownerid = dog.getDogownerId(); Dogowner dogowner = dogownerMapper.selectByPrimaryKey(ownerid); map.put("owner",dogowner); return map; } @Override public String modifyDog(Integer dogid, String dogname, String dogsex, String dogweight, String dogcolor, Integer dogage) { Dog dog = dogMapper.selectByPrimaryKey(dogid); dog.setDogName(dogname); dog.setDogSex(dogsex); dog.setDogWeight(dogweight); dog.setDogColor(dogcolor); dog.setDogAge(dogage); String res = dogMapper.updateByPrimaryKey(dog)>0?"修改成功!":"修改失败"; return res; } @Override public Map<String, Object> getDogStaList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); // List<DogView> doglist = dogMapper.getDogListByDistrictcode(districtcode); List<DogSta> dogstalist = new ArrayList<>(); DogSta dogSta = null; int count = 1; switch (districtcode.length()){ case 1: //国家级管理员 List<District> districtList = districtMapper.getProvinces(); for(int i=0;i<districtList.size();i++){ dogSta = new DogSta(); dogSta.setCountnum(count); count++; dogSta.setDistrictname(districtList.get(i).getDistrictName()); String provinceCode0to2 = districtList.get(i).getDistrictcode().substring(0,2); //获得该省所有的狗 List<Dog> sdlist = dogMapper.getIndexInforByDistrictcode(provinceCode0to2); dogSta.setDognum(sdlist.size()); //佩戴项圈牧犬数量和喂食器数量 int neckdognumtotal = 0; int feedernumtotal = 0; for(Dog each:sdlist){ //"-1"表示未佩戴项圈 if(!each.getNecId().equals("-1")) { neckdognumtotal++; } //"-1"表示无喂食器 if(!each.getAppId().equals("-1")) { feedernumtotal++; } } dogSta.setNecdognum(neckdognumtotal); dogSta.setAppdognum(feedernumtotal); dogSta.setManagedognum(sdlist.size()); if(sdlist.size() == 0){ dogSta.setNecdognumper("0"); dogSta.setAppdognumper("0"); }else{ DecimalFormat df = new DecimalFormat("0.00");//保留2位小数 // String s = df.format(num); dogSta.setNecdognumper(df.format((neckdognumtotal/(sdlist.size()*1.00))*100)+"%"); dogSta.setAppdognumper(df.format((feedernumtotal/(sdlist.size()*1.00))*100)+"%"); } dogstalist.add(dogSta); } break; case 2: //省级管理员 List<District> districtList2 = districtMapper.getCities(districtcode); for(int i=0;i<districtList2.size();i++){ dogSta = new DogSta(); dogSta.setCountnum(count); count++; dogSta.setDistrictname(districtList2.get(i).getDistrictName()); String cityCode0to4 = districtList2.get(i).getDistrictcode().substring(0,4); //获得该省所有的狗 List<Dog> sdlist = dogMapper.getIndexInforByDistrictcode(cityCode0to4); dogSta.setDognum(sdlist.size()); //佩戴项圈牧犬数量和喂食器数量 int neckdognumtotal = 0; int feedernumtotal = 0; for(Dog each:sdlist){ //"-1"表示未佩戴项圈 if(!each.getNecId().equals("-1")) { neckdognumtotal++; } //"-1"表示无喂食器 if(!each.getAppId().equals("-1")) { feedernumtotal++; } } dogSta.setNecdognum(neckdognumtotal); dogSta.setAppdognum(feedernumtotal); dogSta.setManagedognum(sdlist.size()); if(sdlist.size() == 0){ dogSta.setNecdognumper("0"); dogSta.setAppdognumper("0"); }else{ DecimalFormat df = new DecimalFormat("0.00");//保留2位小数 // String s = df.format(num); dogSta.setNecdognumper(df.format((neckdognumtotal/(sdlist.size()*1.00))*100)+"%"); dogSta.setAppdognumper(df.format((feedernumtotal/(sdlist.size()*1.00))*100)+"%"); } dogstalist.add(dogSta); } break; case 4: //市级管理员 List<District> districtList3 = districtMapper.getCounties(districtcode); for(int i=0;i<districtList3.size();i++){ dogSta = new DogSta(); dogSta.setCountnum(count); count++; dogSta.setDistrictname(districtList3.get(i).getDistrictName()); String countyCode0to6 = districtList3.get(i).getDistrictcode().substring(0,6); //获得该市所有的狗 List<Dog> sdlist = dogMapper.getIndexInforByDistrictcode(countyCode0to6); dogSta.setDognum(sdlist.size()); //佩戴项圈牧犬数量和喂食器数量 int neckdognumtotal = 0; int feedernumtotal = 0; for(Dog each:sdlist){ //"-1"表示未佩戴项圈 if(!each.getNecId().equals("-1")) { neckdognumtotal++; } //"-1"表示无喂食器 if(!each.getAppId().equals("-1")) { feedernumtotal++; } } dogSta.setNecdognum(neckdognumtotal); dogSta.setAppdognum(feedernumtotal); dogSta.setManagedognum(sdlist.size()); if(sdlist.size() == 0){ dogSta.setNecdognumper("0"); dogSta.setAppdognumper("0"); }else{ DecimalFormat df = new DecimalFormat("0.00");//保留2位小数 // String s = df.format(num); dogSta.setNecdognumper(df.format((neckdognumtotal/(sdlist.size()*1.00))*100)+"%"); dogSta.setAppdognumper(df.format((feedernumtotal/(sdlist.size()*1.00))*100)+"%"); } dogstalist.add(dogSta); } break; case 6: //县级管理员 List<District> districtList4 = districtMapper.getVillages(districtcode); for(int i=0;i<districtList4.size();i++){ dogSta = new DogSta(); dogSta.setCountnum(count); count++; dogSta.setDistrictname(districtList4.get(i).getDistrictName()); String villageCode0to9 = districtList4.get(i).getDistrictcode().substring(0,9); //获得该县所有的狗 List<Dog> sdlist = dogMapper.getIndexInforByDistrictcode(villageCode0to9); dogSta.setDognum(sdlist.size()); //佩戴项圈牧犬数量和喂食器数量 int neckdognumtotal = 0; int feedernumtotal = 0; for(Dog each:sdlist){ //"-1"表示未佩戴项圈 if(!each.getNecId().equals("-1")) { neckdognumtotal++; } //"-1"表示无喂食器 if(!each.getAppId().equals("-1")) { feedernumtotal++; } } dogSta.setNecdognum(neckdognumtotal); dogSta.setAppdognum(feedernumtotal); dogSta.setManagedognum(sdlist.size()); if(sdlist.size() == 0){ dogSta.setNecdognumper("0"); dogSta.setAppdognumper("0"); }else{ // DecimalFormat df = new DecimalFormat("0.0000");//保留4位小数 // String s = df.format(num); // dogSta.setNecdognumper((neckdognumtotal/(sdlist.size()*1.00))*100+"%"); // dogSta.setAppdognumper((feedernumtotal/(sdlist.size()*1.00))*100+"%"); DecimalFormat df = new DecimalFormat("0.00");//保留2位小数 // String s = df.format(num); dogSta.setNecdognumper(df.format((neckdognumtotal/(sdlist.size()*1.00))*100)+"%"); dogSta.setAppdognumper(df.format((feedernumtotal/(sdlist.size()*1.00))*100)+"%"); } dogstalist.add(dogSta); } break; case 9: //乡级管理员 List<District> districtList5 = districtMapper.getHamlets(districtcode); for(int i=0;i<districtList5.size();i++){ dogSta = new DogSta(); dogSta.setCountnum(count); count++; dogSta.setDistrictname(districtList5.get(i).getDistrictName()); String hamletCode = districtList5.get(i).getDistrictcode(); //获得该乡所有的狗 List<Dog> sdlist = dogMapper.getIndexInforByDistrictcode(hamletCode); dogSta.setDognum(sdlist.size()); //佩戴项圈牧犬数量和喂食器数量 int neckdognumtotal = 0; int feedernumtotal = 0; for(Dog each:sdlist){ //"-1"表示未佩戴项圈 if(!each.getNecId().equals("-1")) { neckdognumtotal++; } //"-1"表示无喂食器 if(!each.getAppId().equals("-1")) { feedernumtotal++; } } dogSta.setNecdognum(neckdognumtotal); dogSta.setAppdognum(feedernumtotal); dogSta.setManagedognum(sdlist.size()); if(sdlist.size() == 0){ dogSta.setNecdognumper("0"); dogSta.setAppdognumper("0"); }else{ // DecimalFormat df = new DecimalFormat("0.0000");//保留4位小数 // String s = df.format(num); // dogSta.setNecdognumper((neckdognumtotal/(sdlist.size()*1.00))*100+"%"); // dogSta.setAppdognumper((feedernumtotal/(sdlist.size()*1.00))*100+"%"); DecimalFormat df = new DecimalFormat("0.00");//保留2位小数 // String s = df.format(num); dogSta.setNecdognumper(df.format((neckdognumtotal/(sdlist.size()*1.00))*100)+"%"); dogSta.setAppdognumper(df.format((feedernumtotal/(sdlist.size()*1.00))*100)+"%"); } dogstalist.add(dogSta); } break; } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", dogstalist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getDeviceStaList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<DeviceSta> devicestalist = new ArrayList<>(); DeviceSta deviceSta = null; int count = 1; switch (districtcode.length()){ case 1: //国家级管理员 List<District> districtList = districtMapper.getProvinces(); for(int i=0;i<districtList.size();i++){ deviceSta = new DeviceSta(); deviceSta.setCountnum(count); count++; deviceSta.setDistrictname(districtList.get(i).getDistrictName()); String provinceCode0to2 = districtList.get(i).getDistrictcode().substring(0,2); //获得该省所有的狗 List<Dog> sdlist = dogMapper.getIndexInforByDistrictcode(provinceCode0to2); deviceSta.setDognum(sdlist.size()); //佩戴项圈牧犬数量和喂食器数量 int neckdognumtotal = 0; int feedernumtotal = 0; int necbadnum = 0; int appbadnum = 0; for(Dog each:sdlist){ //项圈 if(!each.getNecId().equals("-1")) { neckdognumtotal++; String nec_status = "0"; Lastnecareaback lastnecareaback = lastnecareabackMapper.getLastnecareaback(each.getNecId()); if(lastnecareaback != null){ nec_status = lastnecareaback.getNecStatus(); if(nec_status != null && !nec_status.equals("0")){ necbadnum++; } } } //喂食器(待开发) if(!each.getAppId().equals("-1")) { feedernumtotal++; } } deviceSta.setNecdognum(neckdognumtotal); deviceSta.setAppdognum(feedernumtotal); deviceSta.setManagedognum(sdlist.size()); deviceSta.setNecbadnum(necbadnum); deviceSta.setAppbadnum(0); if(sdlist.size() == 0){ deviceSta.setNecbadnumper("0.00%"); deviceSta.setAppbadnumper("0.00%"); }else{ DecimalFormat df = new DecimalFormat("0.00");//保留2位小数 if(neckdognumtotal!=0){ //暂时只考虑了项圈 deviceSta.setNecbadnumper(df.format((necbadnum/(neckdognumtotal*1.00))*100)+"%"); deviceSta.setAppbadnumper("0.00%"); deviceSta.setAllbadnum(necbadnum+appbadnum); deviceSta.setAllbadnumper(df.format((necbadnum/(neckdognumtotal*1.00))*100)+"%"); }else{ deviceSta.setNecbadnumper("0.00%"); deviceSta.setAppbadnumper("0.00%"); deviceSta.setAllbadnum(necbadnum+appbadnum); deviceSta.setAllbadnumper("0.00%"); } } devicestalist.add(deviceSta); } break; case 2: //省级管理员 List<District> districtList2 = districtMapper.getCities(districtcode); for(int i=0;i<districtList2.size();i++){ deviceSta = new DeviceSta(); deviceSta.setCountnum(count); count++; deviceSta.setDistrictname(districtList2.get(i).getDistrictName()); String cityCode0to4 = districtList2.get(i).getDistrictcode().substring(0,4); //获得该省所有的狗 List<Dog> sdlist = dogMapper.getIndexInforByDistrictcode(cityCode0to4); deviceSta.setDognum(sdlist.size()); //佩戴项圈牧犬数量和喂食器数量 int neckdognumtotal = 0; int feedernumtotal = 0; int necbadnum = 0; int appbadnum = 0; for(Dog each:sdlist){ //项圈 if(!each.getNecId().equals("-1")) { neckdognumtotal++; String nec_status = "0"; Lastnecareaback lastnecareaback = lastnecareabackMapper.getLastnecareaback(each.getNecId()); if(lastnecareaback != null){ nec_status = lastnecareaback.getNecStatus(); if(nec_status != null && !nec_status.equals("0")){ necbadnum++; } } } //喂食器(待开发) if(!each.getAppId().equals("-1")) { feedernumtotal++; } } deviceSta.setNecbadnum(necbadnum); deviceSta.setAppbadnum(0); deviceSta.setNecdognum(neckdognumtotal); deviceSta.setAppdognum(feedernumtotal); deviceSta.setManagedognum(sdlist.size()); if(sdlist.size() == 0){ deviceSta.setNecbadnumper("0.00%"); deviceSta.setAppbadnumper("0.00%"); }else{ DecimalFormat df = new DecimalFormat("0.00");//保留2位小数 if(neckdognumtotal!=0){ //暂时只考虑了项圈 deviceSta.setNecbadnumper(df.format((necbadnum/(neckdognumtotal*1.00))*100)+"%"); deviceSta.setAppbadnumper("0.00%"); deviceSta.setAllbadnum(necbadnum+appbadnum); deviceSta.setAllbadnumper(df.format((necbadnum/(neckdognumtotal*1.00))*100)+"%"); }else{ deviceSta.setNecbadnumper("0.00%"); deviceSta.setAppbadnumper("0.00%"); deviceSta.setAllbadnum(necbadnum+appbadnum); deviceSta.setAllbadnumper("0.00%"); } } devicestalist.add(deviceSta); } break; case 4: //市级管理员 List<District> districtList3 = districtMapper.getCounties(districtcode); for(int i=0;i<districtList3.size();i++){ deviceSta = new DeviceSta(); deviceSta.setCountnum(count); count++; deviceSta.setDistrictname(districtList3.get(i).getDistrictName()); String countyCode0to6 = districtList3.get(i).getDistrictcode().substring(0,6); //获得该市所有的狗 List<Dog> sdlist = dogMapper.getIndexInforByDistrictcode(countyCode0to6); deviceSta.setDognum(sdlist.size()); //佩戴项圈牧犬数量和喂食器数量 int neckdognumtotal = 0; int feedernumtotal = 0; int necbadnum = 0; int appbadnum = 0; for(Dog each:sdlist){ //项圈 if(!each.getNecId().equals("-1")) { neckdognumtotal++; String nec_status = "0"; Lastnecareaback lastnecareaback = lastnecareabackMapper.getLastnecareaback(each.getNecId()); if(lastnecareaback != null){ nec_status = lastnecareaback.getNecStatus(); if(nec_status != null && !nec_status.equals("0")){ necbadnum++; } } } //喂食器(待开发) if(!each.getAppId().equals("-1")) { feedernumtotal++; } } deviceSta.setNecbadnum(necbadnum); deviceSta.setAppbadnum(0); deviceSta.setNecdognum(neckdognumtotal); deviceSta.setAppdognum(feedernumtotal); deviceSta.setManagedognum(sdlist.size()); if(sdlist.size() == 0){ deviceSta.setNecbadnumper("0.00%"); deviceSta.setAppbadnumper("0.00%"); }else{ DecimalFormat df = new DecimalFormat("0.00");//保留2位小数 if(neckdognumtotal!=0){ //暂时只考虑了项圈 deviceSta.setNecbadnumper(df.format((necbadnum/(neckdognumtotal*1.00))*100)+"%"); deviceSta.setAppbadnumper("0.00%"); deviceSta.setAllbadnum(necbadnum+appbadnum); deviceSta.setAllbadnumper(df.format((necbadnum/(neckdognumtotal*1.00))*100)+"%"); }else{ deviceSta.setNecbadnumper("0.00%"); deviceSta.setAppbadnumper("0.00%"); deviceSta.setAllbadnum(necbadnum+appbadnum); deviceSta.setAllbadnumper("0.00%"); } } devicestalist.add(deviceSta); } break; case 6: //县级管理员 List<District> districtList4 = districtMapper.getVillages(districtcode); for(int i=0;i<districtList4.size();i++){ deviceSta = new DeviceSta(); deviceSta.setCountnum(count); count++; deviceSta.setDistrictname(districtList4.get(i).getDistrictName()); String villageCode0to9 = districtList4.get(i).getDistrictcode().substring(0,9); //获得该县所有的狗 List<Dog> sdlist = dogMapper.getIndexInforByDistrictcode(villageCode0to9); deviceSta.setDognum(sdlist.size()); //佩戴项圈牧犬数量和喂食器数量 int neckdognumtotal = 0; int feedernumtotal = 0; int necbadnum = 0; int appbadnum = 0; for(Dog each:sdlist){ //项圈 if(!each.getNecId().equals("-1")) { neckdognumtotal++; String nec_status = "0"; Lastnecareaback lastnecareaback = lastnecareabackMapper.getLastnecareaback(each.getNecId()); if(lastnecareaback != null){ nec_status = lastnecareaback.getNecStatus(); if(nec_status != null && !nec_status.equals("0")){ necbadnum++; } } } //喂食器(待开发) if(!each.getAppId().equals("-1")) { feedernumtotal++; } } deviceSta.setNecbadnum(necbadnum); deviceSta.setAppbadnum(0); deviceSta.setNecdognum(neckdognumtotal); deviceSta.setAppdognum(feedernumtotal); deviceSta.setManagedognum(sdlist.size()); if(sdlist.size() == 0){ deviceSta.setNecbadnumper("0.00%"); deviceSta.setAppbadnumper("0.00%"); }else{ DecimalFormat df = new DecimalFormat("0.00");//保留2位小数 if(neckdognumtotal!=0){ //暂时只考虑了项圈 deviceSta.setNecbadnumper(df.format((necbadnum/(neckdognumtotal*1.00))*100)+"%"); deviceSta.setAppbadnumper("0.00%"); deviceSta.setAllbadnum(necbadnum+appbadnum); deviceSta.setAllbadnumper(df.format((necbadnum/(neckdognumtotal*1.00))*100)+"%"); }else{ deviceSta.setNecbadnumper("0.00%"); deviceSta.setAppbadnumper("0.00%"); deviceSta.setAllbadnum(necbadnum+appbadnum); deviceSta.setAllbadnumper("0.00%"); } } devicestalist.add(deviceSta); } break; case 9: //乡级管理员 List<District> districtList5 = districtMapper.getHamlets(districtcode); for(int i=0;i<districtList5.size();i++){ deviceSta = new DeviceSta(); deviceSta.setCountnum(count); count++; deviceSta.setDistrictname(districtList5.get(i).getDistrictName()); String hamletCode = districtList5.get(i).getDistrictcode(); //获得该乡所有的狗 List<Dog> sdlist = dogMapper.getIndexInforByDistrictcode(hamletCode); deviceSta.setDognum(sdlist.size()); //佩戴项圈牧犬数量和喂食器数量 int neckdognumtotal = 0; int feedernumtotal = 0; int necbadnum = 0; int appbadnum = 0; for(Dog each:sdlist){ //项圈 if(!each.getNecId().equals("-1")) { neckdognumtotal++; String nec_status = "0"; Lastnecareaback lastnecareaback = lastnecareabackMapper.getLastnecareaback(each.getNecId()); if(lastnecareaback != null){ nec_status = lastnecareaback.getNecStatus(); if(nec_status != null && !nec_status.equals("0")){ necbadnum++; } } } //喂食器(待开发) if(!each.getAppId().equals("-1")) { feedernumtotal++; } } deviceSta.setNecbadnum(necbadnum); deviceSta.setAppbadnum(0); deviceSta.setNecdognum(neckdognumtotal); deviceSta.setAppdognum(feedernumtotal); deviceSta.setManagedognum(sdlist.size()); if(sdlist.size() == 0){ deviceSta.setNecbadnumper("0.00%"); deviceSta.setAppbadnumper("0.00%"); }else{ DecimalFormat df = new DecimalFormat("0.00");//保留2位小数 if(neckdognumtotal!=0){ //暂时只考虑了项圈 deviceSta.setNecbadnumper(df.format((necbadnum/(neckdognumtotal*1.00))*100)+"%"); deviceSta.setAppbadnumper("0.00%"); deviceSta.setAllbadnum(necbadnum+appbadnum); deviceSta.setAllbadnumper(df.format((necbadnum/(neckdognumtotal*1.00))*100)+"%"); }else{ deviceSta.setNecbadnumper("0.00%"); deviceSta.setAppbadnumper("0.00%"); deviceSta.setAllbadnum(necbadnum+appbadnum); deviceSta.setAllbadnumper("0.00%"); } } devicestalist.add(deviceSta); } break; } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", devicestalist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getIllStaList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<Analyzeill> illstalist = new ArrayList<>(); Analyzeill illsta = null; int count = 1; switch (districtcode.length()){ case 1: //国家级管理员 AnalyzeillExample example1 = new AnalyzeillExample(); example1.createCriteria().andDistrictLevelEqualTo(0); illstalist = analyzeillMapper.selectByExample(example1); break; case 2: //省级管理员 AnalyzeillExample example2 = new AnalyzeillExample(); example2.createCriteria().andDistrictLevelEqualTo(1).andDistrictcodeLike(districtcode.substring(0,2)+"%"); illstalist = analyzeillMapper.selectByExample(example2); break; case 4: //市级管理员 AnalyzeillExample example3 = new AnalyzeillExample(); example3.createCriteria().andDistrictLevelEqualTo(2).andDistrictcodeLike(districtcode.substring(0,4)+"%"); illstalist = analyzeillMapper.selectByExample(example3); break; case 6: //县级管理员 AnalyzeillExample example4 = new AnalyzeillExample(); example4.createCriteria().andDistrictLevelEqualTo(3).andDistrictcodeLike(districtcode.substring(0,6)+"%"); illstalist = analyzeillMapper.selectByExample(example4); break; case 9: //乡级管理员 AnalyzeillExample example5 = new AnalyzeillExample(); example5.createCriteria().andDistrictLevelEqualTo(4).andDistrictcodeLike(districtcode.substring(0,9)+"%"); illstalist = analyzeillMapper.selectByExample(example5); break; } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", illstalist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getBillStaList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<Anaallill> illstalist = new ArrayList<>(); Analyzeill illsta = null; int count = 1; switch (districtcode.length()){ case 1: //国家级管理员 AnaallillExample example1 = new AnaallillExample(); example1.createCriteria().andDistrictLevelEqualTo(0); illstalist = anaallillMapper.selectByExample(example1); break; case 2: //省级管理员 AnaallillExample example2 = new AnaallillExample(); example2.createCriteria().andDistrictLevelEqualTo(1).andDistrictcodeLike(districtcode.substring(0,2)+"%"); illstalist = anaallillMapper.selectByExample(example2); break; case 4: //市级管理员 AnaallillExample example3 = new AnaallillExample(); example3.createCriteria().andDistrictLevelEqualTo(2).andDistrictcodeLike(districtcode.substring(0,4)+"%"); illstalist = anaallillMapper.selectByExample(example3); break; case 6: //县级管理员 AnaallillExample example4 = new AnaallillExample(); example4.createCriteria().andDistrictLevelEqualTo(3).andDistrictcodeLike(districtcode.substring(0,6)+"%"); illstalist = anaallillMapper.selectByExample(example4); break; case 9: //乡级管理员 AnaallillExample example5 = new AnaallillExample(); example5.createCriteria().andDistrictLevelEqualTo(4).andDistrictcodeLike(districtcode.substring(0,9)+"%"); illstalist = anaallillMapper.selectByExample(example5); break; } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", illstalist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getAnaBillStaList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<District> districtList = new ArrayList<>(); List<Childill> illAllstalist = new ArrayList<>(); List<Childill> illstalist = new ArrayList<>(); List<AnaChildill> anaillstalist = new ArrayList<>(); AnaChildill anaChildill = null; int count = 1; illAllstalist = childillMapper.selectByExample(new ChildillExample()); switch (districtcode.length()){ case 1: //国家级管理员 districtList = districtMapper.getProvinces(); for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Childill cd : illAllstalist){ if(cd.getBcheckres()!=null && cd.getBcheckres()!= "" && cd.getNum().substring(0,2).equals(di.getDistrictcode().substring(0,2))){ checknum++; if(cd.getBcheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 2: //省级管理员 districtList = districtMapper.getCities(districtcode); for(Childill cd : illAllstalist){ if(cd.getNum().substring(0,2).equals(districtcode)){ illstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Childill cd : illstalist){ if(cd.getBcheckres()!=null && cd.getBcheckres()!= "" && cd.getNum().substring(0,4).equals(di.getDistrictcode().substring(0,4))){ checknum++; if(cd.getBcheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 4: //市级管理员 districtList = districtMapper.getCounties(districtcode); for(Childill cd : illAllstalist){ if(cd.getNum().substring(0,4).equals(districtcode)){ illstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Childill cd : illstalist){ if(cd.getBcheckres()!=null && cd.getBcheckres()!= "" && cd.getNum().substring(0,6).equals(di.getDistrictcode().substring(0,6))){ checknum++; if(cd.getBcheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 6: //县级管理员 districtList = districtMapper.getVillages(districtcode); for(Childill cd : illAllstalist){ if(cd.getNum().substring(0,6).equals(districtcode)){ illstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Childill cd : illstalist){ if(cd.getBcheckres()!=null && cd.getBcheckres()!= "" && cd.getNum().substring(0,9).equals(di.getDistrictcode().substring(0,9))){ checknum++; if(cd.getBcheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 9: //乡级管理员 districtList = districtMapper.getHamlets(districtcode); for(Childill cd : illAllstalist){ if(cd.getNum().substring(0,9).equals(districtcode)){ illstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Childill cd : illstalist){ if(cd.getBcheckres()!=null && cd.getBcheckres()!= "" && cd.getNum().equals(di.getDistrictcode())){ checknum++; if(cd.getBcheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", anaillstalist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getAnaChildCheckStaList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<District> districtList = new ArrayList<>(); List<Childcheck> checkAllstalist = new ArrayList<>(); List<Childcheck> checkstalist = new ArrayList<>(); List<AnaChildill> anaillstalist = new ArrayList<>(); AnaChildill anaChildill = null; int count = 1; checkAllstalist = childCheckMapper.selectByExample(new ChildcheckExample()); switch (districtcode.length()){ case 1: //国家级管理员 districtList = districtMapper.getProvinces(); for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Childcheck cd : checkAllstalist){ if(cd.getCheckres()!=null && cd.getCheckres()!= "" && cd.getNum().substring(0,2).equals(di.getDistrictcode().substring(0,2))){ checknum++; if(cd.getCheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 2: //省级管理员 districtList = districtMapper.getCities(districtcode); for(Childcheck cd : checkAllstalist){ if(cd.getNum().substring(0,2).equals(districtcode)){ checkstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Childcheck cd : checkstalist){ if(cd.getCheckres()!=null && cd.getCheckres()!= "" && cd.getNum().substring(0,4).equals(di.getDistrictcode().substring(0,4))){ checknum++; if(cd.getCheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 4: //市级管理员 districtList = districtMapper.getCounties(districtcode); for(Childcheck cd : checkAllstalist){ if(cd.getNum().substring(0,4).equals(districtcode)){ checkstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Childcheck cd : checkstalist){ if(cd.getCheckres()!=null && cd.getCheckres()!= "" && cd.getNum().substring(0,6).equals(di.getDistrictcode().substring(0,6))){ checknum++; if(cd.getCheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 6: //县级管理员 districtList = districtMapper.getVillages(districtcode); for(Childcheck cd : checkAllstalist){ if(cd.getNum().substring(0,6).equals(districtcode)){ checkstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Childcheck cd : checkstalist){ if(cd.getCheckres()!=null && cd.getCheckres()!= "" && cd.getNum().substring(0,9).equals(di.getDistrictcode().substring(0,9))){ checknum++; if(cd.getCheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 9: //乡级管理员 districtList = districtMapper.getHamlets(districtcode); for(Childcheck cd : checkAllstalist){ if(cd.getNum().substring(0,9).equals(districtcode)){ checkstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Childcheck cd : checkstalist){ if(cd.getCheckres()!=null && cd.getCheckres()!= "" && cd.getNum().equals(di.getDistrictcode())){ checknum++; if(cd.getCheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", anaillstalist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getAnaDogillStaList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<District> districtList = new ArrayList<>(); List<Manure> dogillAllstalist = new ArrayList<>(); List<Manure> dogillstalist = new ArrayList<>(); List<AnaChildill> anaillstalist = new ArrayList<>(); AnaChildill anaChildill = null; int count = 1; dogillAllstalist = manureMapper.selectByExample(new ManureExample()); switch (districtcode.length()){ case 1: //国家级管理员 districtList = districtMapper.getProvinces(); for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Manure cd : dogillAllstalist){ if(cd.getTestingResult()!=null && cd.getTestingResult()!= "" && cd.getDistrictcode().substring(0,2).equals(di.getDistrictcode().substring(0,2))){ checknum++; if(cd.getTestingResult().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 2: //省级管理员 districtList = districtMapper.getCities(districtcode); for(Manure cd : dogillAllstalist){ if(cd.getDistrictcode().substring(0,2).equals(districtcode)){ dogillstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Manure cd : dogillstalist){ if(cd.getTestingResult()!=null && cd.getTestingResult()!= "" && cd.getDistrictcode().substring(0,4).equals(di.getDistrictcode().substring(0,4))){ checknum++; if(cd.getTestingResult().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 4: //市级管理员 districtList = districtMapper.getCounties(districtcode); for(Manure cd : dogillAllstalist){ if(cd.getDistrictcode().substring(0,4).equals(districtcode)){ dogillstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Manure cd : dogillstalist){ if(cd.getTestingResult()!=null && cd.getTestingResult()!= "" && cd.getDistrictcode().substring(0,6).equals(di.getDistrictcode().substring(0,6))){ checknum++; if(cd.getTestingResult().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 6: //县级管理员 districtList = districtMapper.getVillages(districtcode); for(Manure cd : dogillAllstalist){ if(cd.getDistrictcode().substring(0,6).equals(districtcode)){ dogillstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Manure cd : dogillstalist){ if(cd.getTestingResult()!=null && cd.getTestingResult()!= "" && cd.getDistrictcode().substring(0,9).equals(di.getDistrictcode().substring(0,9))){ checknum++; if(cd.getTestingResult().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 9: //乡级管理员 districtList = districtMapper.getHamlets(districtcode); for(Manure cd : dogillAllstalist){ if(cd.getDistrictcode().substring(0,9).equals(districtcode)){ dogillstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Manure cd : dogillstalist){ if(cd.getTestingResult()!=null && cd.getTestingResult()!= "" && cd.getDistrictcode().equals(di.getDistrictcode())){ checknum++; if(cd.getTestingResult().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", anaillstalist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getAnaAnimalillStaList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<District> districtList = new ArrayList<>(); List<Animalill> dogillAllstalist = new ArrayList<>(); List<Animalill> dogillstalist = new ArrayList<>(); List<AnaChildill> anaillstalist = new ArrayList<>(); AnaChildill anaChildill = null; int count = 1; dogillAllstalist = animalillMapper.selectByExample(new AnimalillExample()); switch (districtcode.length()){ case 1: //国家级管理员 districtList = districtMapper.getProvinces(); for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Animalill cd : dogillAllstalist){ if(cd.getCheckres()!=null && cd.getCheckres()!= "" && cd.getNum().substring(0,2).equals(di.getDistrictcode().substring(0,2))){ checknum++; if(cd.getCheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 2: //省级管理员 districtList = districtMapper.getCities(districtcode); for(Animalill cd : dogillAllstalist){ if(cd.getNum().substring(0,2).equals(districtcode)){ dogillstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Animalill cd : dogillstalist){ if(cd.getCheckres()!=null && cd.getCheckres()!= "" && cd.getNum().substring(0,4).equals(di.getDistrictcode().substring(0,4))){ checknum++; if(cd.getCheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 4: //市级管理员 districtList = districtMapper.getCounties(districtcode); for(Animalill cd : dogillAllstalist){ if(cd.getNum().substring(0,4).equals(districtcode)){ dogillstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Animalill cd : dogillstalist){ if(cd.getCheckres()!=null && cd.getCheckres()!= "" && cd.getNum().substring(0,6).equals(di.getDistrictcode().substring(0,6))){ checknum++; if(cd.getCheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 6: //县级管理员 districtList = districtMapper.getVillages(districtcode); for(Animalill cd : dogillAllstalist){ if(cd.getNum().substring(0,6).equals(districtcode)){ dogillstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Animalill cd : dogillstalist){ if(cd.getCheckres()!=null && cd.getCheckres()!= "" && cd.getNum().substring(0,9).equals(di.getDistrictcode().substring(0,9))){ checknum++; if(cd.getCheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; case 9: //乡级管理员 districtList = districtMapper.getHamlets(districtcode); for(Animalill cd : dogillAllstalist){ if(cd.getNum().substring(0,9).equals(districtcode)){ dogillstalist.add(cd); } } for(District di : districtList){ anaChildill = new AnaChildill(); anaChildill.setDistrictcode(di.getDistrictcode()); anaChildill.setDistrictname(di.getDistrictName()); int checknum = 0; int bcheckyang = 0; for(Animalill cd : dogillstalist){ if(cd.getCheckres()!=null && cd.getCheckres()!= "" && cd.getNum().equals(di.getDistrictcode())){ checknum++; if(cd.getCheckres().equals("阳性")){ bcheckyang++; } } } anaChildill.setBchecknum(checknum); anaChildill.setIllnum(bcheckyang); if(bcheckyang == 0){ anaChildill.setChecklv("0"); }else{ anaChildill.setChecklv(String.format("%.2f", bcheckyang*1.00/checknum).toString()); } anaillstalist.add(anaChildill); } break; } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", anaillstalist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getChildCheckList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<Childcheck> childchecklist = new ArrayList<>(); Childcheck childcheck = null; int count = 1; switch (districtcode.length()){ case 1: //国家级管理员 ChildcheckExample example1 = new ChildcheckExample(); childchecklist = childcheckMapper.selectByExample(example1); break; case 2: //省级管理员 ChildcheckExample example2 = new ChildcheckExample(); example2.createCriteria().andNumLike(districtcode.substring(0,2)+"%"); childchecklist = childcheckMapper.selectByExample(example2); break; case 4: //市级管理员 ChildcheckExample example3 = new ChildcheckExample(); example3.createCriteria().andNumLike(districtcode.substring(0,4)+"%"); childchecklist = childcheckMapper.selectByExample(example3); break; case 6: //县级管理员 ChildcheckExample example4 = new ChildcheckExample(); example4.createCriteria().andNumLike(districtcode.substring(0,6)+"%"); childchecklist = childcheckMapper.selectByExample(example4); break; case 9: //乡级管理员 ChildcheckExample example5 = new ChildcheckExample(); example5.createCriteria().andNumLike(districtcode.substring(0,9)+"%"); childchecklist = childcheckMapper.selectByExample(example5); break; case 12: //村级管理员 ChildcheckExample example6 = new ChildcheckExample(); example6.createCriteria().andNumEqualTo(districtcode); childchecklist = childcheckMapper.selectByExample(example6); } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", childchecklist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getAnimalillList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<Animalill> animalillList = new ArrayList<>(); Animalill animalill = null; int count = 1; switch (districtcode.length()){ case 1: //国家级管理员 AnimalillExample example1 = new AnimalillExample(); animalillList = animalillMapper.selectByExample(example1); break; case 2: //省级管理员 AnimalillExample example2 = new AnimalillExample(); example2.createCriteria().andNumLike(districtcode.substring(0,2)+"%"); animalillList = animalillMapper.selectByExample(example2); break; case 4: //市级管理员 AnimalillExample example3 = new AnimalillExample(); example3.createCriteria().andNumLike(districtcode.substring(0,4)+"%"); animalillList = animalillMapper.selectByExample(example3); break; case 6: //县级管理员 AnimalillExample example4 = new AnimalillExample(); example4.createCriteria().andNumLike(districtcode.substring(0,6)+"%"); animalillList = animalillMapper.selectByExample(example4); break; case 9: //乡级管理员 AnimalillExample example5 = new AnimalillExample(); example5.createCriteria().andNumLike(districtcode.substring(0,9)+"%"); animalillList = animalillMapper.selectByExample(example5); break; case 12: //村级管理员 AnimalillExample example6 = new AnimalillExample(); example6.createCriteria().andNumEqualTo(districtcode); animalillList = animalillMapper.selectByExample(example6); } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", animalillList); //管理员总数 map.put("totalNum", page.getTotal()); return map; } @Override public Map<String, Object> getChildIllList(String districtcode, int startPage, int pageSize) { Page page = PageHelper.startPage(startPage, pageSize); List<Childill> childilllist = new ArrayList<>(); Childill childill = null; int count = 1; switch (districtcode.length()){ case 1: //国家级管理员 ChildillExample example1 = new ChildillExample(); childilllist = childillMapper.selectByExample(example1); break; case 2: //省级管理员 ChildillExample example2 = new ChildillExample(); example2.createCriteria().andNumLike(districtcode.substring(0,2)+"%"); childilllist = childillMapper.selectByExample(example2); break; case 4: //市级管理员 ChildillExample example3 = new ChildillExample(); example3.createCriteria().andNumLike(districtcode.substring(0,4)+"%"); childilllist = childillMapper.selectByExample(example3); break; case 6: //县级管理员 ChildillExample example4 = new ChildillExample(); example4.createCriteria().andNumLike(districtcode.substring(0,6)+"%"); childilllist = childillMapper.selectByExample(example4); break; case 9: //乡级管理员 ChildillExample example5 = new ChildillExample(); example5.createCriteria().andNumLike(districtcode.substring(0,9)+"%"); childilllist = childillMapper.selectByExample(example5); break; case 12: //村级管理员 ChildillExample example6 = new ChildillExample(); example6.createCriteria().andNumEqualTo(districtcode); childilllist = childillMapper.selectByExample(example6); break; } Map<String, Object> map = new HashMap<String,Object>(); //每页信息 map.put("data", childilllist); //管理员总数 map.put("totalNum", page.getTotal()); return map; } }
78,868
0.476988
0.464665
1,644
45.891727
27.630236
169
false
false
0
0
0
0
0
0
0.689781
false
false
7
1d372656912fc9acb9beb08c118b675321554378
26,345,329,441,506
2561b479d471945c22543bdf077f33747d025404
/src/java/eu/sig/training/ch05/buildandsendmail/BuildAndSendMail.java
292c14188ffd8de0052c8b9f473a81287b68ad09
[]
no_license
ucokm/training-assignments-simple
https://github.com/ucokm/training-assignments-simple
3aa5763c28c9ae17b969c5e92f69ac89e584923b
866bbe280376aae3726e22cb3ba688615ede3762
refs/heads/master
2020-12-30T14:19:24.718000
2017-10-09T08:22:02
2017-10-09T08:22:02
91,304,936
0
0
null
true
2017-05-15T06:56:27
2017-05-15T06:56:27
2016-12-20T10:32:56
2016-12-19T18:49:28
298
0
0
0
null
null
null
package eu.sig.training.ch05.buildandsendmail; public class BuildAndSendMail { // tag::buildAndSendMail[] public void buildAndSendMail(MailMan m, NameFormat nameFormat, MessageFormat msgFormat, MailFont font) { // Format the email address String mId = nameFormat.getFirstName().charAt(0) + "." + nameFormat.getLastName().substring(0, 7) + "@" + nameFormat.getDivision().substring(0, 5) + ".compa.ny"; // Format the message given the content type and raw message MailMessage mMessage = formatMessage(font, msgFormat.getMessage1() + msgFormat.getMessage2() + msgFormat.getMessage3()); // Send message m.send(mId, msgFormat.getSubject(), mMessage); } // end::buildAndSendMail[] @SuppressWarnings("unused") private MailMessage formatMessage(MailFont font, String string) { return null; } private class MailMan { @SuppressWarnings("unused") public void send(String mId, String subject, MailMessage mMessage) {} } private class MailFont { } private class MailMessage { } }
UTF-8
Java
1,124
java
BuildAndSendMail.java
Java
[]
null
[]
package eu.sig.training.ch05.buildandsendmail; public class BuildAndSendMail { // tag::buildAndSendMail[] public void buildAndSendMail(MailMan m, NameFormat nameFormat, MessageFormat msgFormat, MailFont font) { // Format the email address String mId = nameFormat.getFirstName().charAt(0) + "." + nameFormat.getLastName().substring(0, 7) + "@" + nameFormat.getDivision().substring(0, 5) + ".compa.ny"; // Format the message given the content type and raw message MailMessage mMessage = formatMessage(font, msgFormat.getMessage1() + msgFormat.getMessage2() + msgFormat.getMessage3()); // Send message m.send(mId, msgFormat.getSubject(), mMessage); } // end::buildAndSendMail[] @SuppressWarnings("unused") private MailMessage formatMessage(MailFont font, String string) { return null; } private class MailMan { @SuppressWarnings("unused") public void send(String mId, String subject, MailMessage mMessage) {} } private class MailFont { } private class MailMessage { } }
1,124
0.657473
0.648576
37
29.405405
31.717043
111
false
false
0
0
0
0
0
0
0.432432
false
false
7
0c65fd345b147015612dd32654901f9771a2c020
23,776,938,993,406
2a42c7fdcac82eaefea91be88c27968802dc53c5
/back/src/main/java/com/cameleon/chameleon/data/dto/DeliverableDTO.java
b2c8a53e4c2f762669bd32673a7808f89968f30a
[]
no_license
aurelienshz/isep-cameleon
https://github.com/aurelienshz/isep-cameleon
a4148c5ec703cfe08a204e1d0d2573eb807e1d27
84364ff148344548c4d67c94ebb68dfb20042459
refs/heads/master
2021-03-27T16:04:10.452000
2017-09-29T18:51:30
2017-11-25T20:20:43
83,890,802
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cameleon.chameleon.data.dto; import java.sql.Timestamp; public class DeliverableDTO { private String name; private String assignment; private Timestamp deliveryWindowBeginning; private Timestamp deliveryWindowEnd; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAssignment() { return assignment; } public void setAssignment(String assignment) { this.assignment = assignment; } public Timestamp getDeliveryWindowBeginning() { return deliveryWindowBeginning; } public void setDeliveryWindowBeginning(Timestamp deliveryWindowBeginning) { this.deliveryWindowBeginning = deliveryWindowBeginning; } public Timestamp getDeliveryWindowEnd() { return deliveryWindowEnd; } public void setDeliveryWindowEnd(Timestamp deliveryWindowEnd) { this.deliveryWindowEnd = deliveryWindowEnd; } }
UTF-8
Java
1,008
java
DeliverableDTO.java
Java
[]
null
[]
package com.cameleon.chameleon.data.dto; import java.sql.Timestamp; public class DeliverableDTO { private String name; private String assignment; private Timestamp deliveryWindowBeginning; private Timestamp deliveryWindowEnd; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAssignment() { return assignment; } public void setAssignment(String assignment) { this.assignment = assignment; } public Timestamp getDeliveryWindowBeginning() { return deliveryWindowBeginning; } public void setDeliveryWindowBeginning(Timestamp deliveryWindowBeginning) { this.deliveryWindowBeginning = deliveryWindowBeginning; } public Timestamp getDeliveryWindowEnd() { return deliveryWindowEnd; } public void setDeliveryWindowEnd(Timestamp deliveryWindowEnd) { this.deliveryWindowEnd = deliveryWindowEnd; } }
1,008
0.699405
0.699405
44
21.90909
21.849504
79
false
false
0
0
0
0
0
0
0.318182
false
false
7
37f51d7caee95b0b93855875a0617c98b84dae10
33,724,083,256,292
a5d232145ecb988ee5483950ec819dd50bae065e
/src/main/java/web_scanner/PageScannerWorker.java
08a66ecf7070ab64e42abf56085d8654a9d8dd76
[]
no_license
imbactbulletz/keyword-counter
https://github.com/imbactbulletz/keyword-counter
79bfa18fa067dd3f4714e5013b81f2ce85299b2a
2c9ff5b7037cc8d0d760157e30af80d068d4cd81
refs/heads/master
2020-05-02T23:04:38.848000
2019-04-14T19:08:36
2019-04-14T19:08:36
178,271,759
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package web_scanner; import app.Main; import job.WebJob; import misc.ApplicationSettings; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; public class PageScannerWorker implements Callable<Map<String, Integer>> { private WebJob webJob; public PageScannerWorker(WebJob webJob) { this.webJob = webJob; } @Override public Map<String, Integer> call() { String pageURL = webJob.getQuery(); Document document = null; try { document = Jsoup.connect(pageURL).get(); } catch (Exception e) { System.out.println("Could not connect to : " + pageURL); return new HashMap<>(); } List<String> foundLinks = getLinksFrom(document); if(webJob.getHops() != 0) { scheduleNewWebJobs(foundLinks); } Map<String, Integer> foundKeywords = new HashMap<>(); if(document.body() != null) { foundKeywords = scanForKeywords(document.body().text()); } // remove job after delay Main.webScannerPool.getScheduledExecutorService().schedule(new Runnable() { @Override public void run() { Main.webScannerPool.getScannedJobs().remove(webJob); // System.out.println("Scheduler has removed job from the scanned list queue! New size: " + Main.webScannerPool.getScannedJobs().size()); } }, ApplicationSettings.URLRefreshTime, TimeUnit.MILLISECONDS); return foundKeywords; } private List<String> getLinksFrom(Document document) { List<String> foundLinks = new ArrayList<>(); Elements links = document.select("a[href]"); for (Element link : links) { if(link.attr("abs:href").startsWith("http")) { foundLinks.add(link.attr("abs:href")); } } return foundLinks; } private void scheduleNewWebJobs(List<String> links) { WebJob tmpJob; for(String link : links) { // System.out.println("Scheduling new job (" + link +") with " + (webJob.getHops()-1) + " hops."); tmpJob = new WebJob(link, webJob.getHops() -1); Main.jobQueue.add(tmpJob); } } private Map<String, Integer> scanForKeywords(String text) { Map<String, Integer> resultMap = new HashMap<>(); List<String> keywordList = ApplicationSettings.keywordsList; List<String> words = Arrays.stream(text.split(" ")) .map(word -> word.replaceAll("\\p{Punct}+$", "")).collect(Collectors.toList()); for (String word : words) { if (keywordList.contains(word)) { if(resultMap.containsKey(word)) { resultMap.put(word, resultMap.get(word) + 1); } else { resultMap.put(word, 1); } } } return resultMap; } }
UTF-8
Java
3,174
java
PageScannerWorker.java
Java
[]
null
[]
package web_scanner; import app.Main; import job.WebJob; import misc.ApplicationSettings; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; public class PageScannerWorker implements Callable<Map<String, Integer>> { private WebJob webJob; public PageScannerWorker(WebJob webJob) { this.webJob = webJob; } @Override public Map<String, Integer> call() { String pageURL = webJob.getQuery(); Document document = null; try { document = Jsoup.connect(pageURL).get(); } catch (Exception e) { System.out.println("Could not connect to : " + pageURL); return new HashMap<>(); } List<String> foundLinks = getLinksFrom(document); if(webJob.getHops() != 0) { scheduleNewWebJobs(foundLinks); } Map<String, Integer> foundKeywords = new HashMap<>(); if(document.body() != null) { foundKeywords = scanForKeywords(document.body().text()); } // remove job after delay Main.webScannerPool.getScheduledExecutorService().schedule(new Runnable() { @Override public void run() { Main.webScannerPool.getScannedJobs().remove(webJob); // System.out.println("Scheduler has removed job from the scanned list queue! New size: " + Main.webScannerPool.getScannedJobs().size()); } }, ApplicationSettings.URLRefreshTime, TimeUnit.MILLISECONDS); return foundKeywords; } private List<String> getLinksFrom(Document document) { List<String> foundLinks = new ArrayList<>(); Elements links = document.select("a[href]"); for (Element link : links) { if(link.attr("abs:href").startsWith("http")) { foundLinks.add(link.attr("abs:href")); } } return foundLinks; } private void scheduleNewWebJobs(List<String> links) { WebJob tmpJob; for(String link : links) { // System.out.println("Scheduling new job (" + link +") with " + (webJob.getHops()-1) + " hops."); tmpJob = new WebJob(link, webJob.getHops() -1); Main.jobQueue.add(tmpJob); } } private Map<String, Integer> scanForKeywords(String text) { Map<String, Integer> resultMap = new HashMap<>(); List<String> keywordList = ApplicationSettings.keywordsList; List<String> words = Arrays.stream(text.split(" ")) .map(word -> word.replaceAll("\\p{Punct}+$", "")).collect(Collectors.toList()); for (String word : words) { if (keywordList.contains(word)) { if(resultMap.containsKey(word)) { resultMap.put(word, resultMap.get(word) + 1); } else { resultMap.put(word, 1); } } } return resultMap; } }
3,174
0.584751
0.583176
108
28.388889
27.978441
152
false
false
0
0
0
0
0
0
0.481481
false
false
7
b32e14d3761b27eafeafefd3f6d1b030b7f78692
33,354,716,024,018
92b691098f820475f672395e49f60177a52e5c7c
/src/twitbak/MessageBak.java
d1c4a71c6b81397b03a68f1bcc92552e14ad3aaf
[]
no_license
starchy/TwitBak
https://github.com/starchy/TwitBak
c5adc5381ebeeaea033b282e164992bf54a4dbc0
6a32cae5d02645d91d90a9e7b194d11cd659bb30
refs/heads/master
2021-01-16T19:00:35.112000
2010-07-17T18:01:40
2010-07-17T18:01:40
706,843
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2010 David "Starchy" Grant * * This file is part of TwitBak. * * TwitBak is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package twitbak; import java.util.List; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.internal.org.json.JSONArray; import twitter4j.internal.org.json.JSONObject; /** * Pattern for a class to backup Twitter messages. * * @author David @starchy Grant * */ interface MessageBak { JSONArray statusArray(); // Messages collected; will be phased out in favor of a SQLJet solution. JSONObject statusObject(); Twitter twitter(); // Class representing Twitter connection List<?> getStatusPage(int n) throws TwitterException, InterruptedException; // get n messages void getStatuses() throws TwitterException, InterruptedException; // get all messages }
UTF-8
Java
1,521
java
MessageBak.java
Java
[ { "context": "/*\n * Copyright 2010 David \"Starchy\" Grant\n *\n * This file is part of TwitBak.", "end": 26, "score": 0.9187242984771729, "start": 21, "tag": "NAME", "value": "David" }, { "context": "/*\n * Copyright 2010 David \"Starchy\" Grant\n *\n * This file is part of TwitBak.\n * \n *", "end": 35, "score": 0.9958092570304871, "start": 28, "tag": "NAME", "value": "Starchy" }, { "context": "/*\n * Copyright 2010 David \"Starchy\" Grant\n *\n * This file is part of TwitBak.\n * \n * TwitBa", "end": 42, "score": 0.9711605310440063, "start": 37, "tag": "NAME", "value": "Grant" }, { "context": "a class to backup Twitter messages.\n * \n * @author David @starchy Grant\n *\n */\ninterface MessageBak {\n\t\n\tJ", "end": 1093, "score": 0.9989584684371948, "start": 1088, "tag": "NAME", "value": "David" }, { "context": "s to backup Twitter messages.\n * \n * @author David @starchy Grant\n *\n */\ninterface MessageBak {\n\t\n\tJSO", "end": 1093, "score": 0.9724141359329224, "start": 1093, "tag": "NAME", "value": "" }, { "context": "to backup Twitter messages.\n * \n * @author David @starchy Grant\n *\n */\ninterface MessageBak {\n\t\n\tJSONArray ", "end": 1102, "score": 0.7312998175621033, "start": 1095, "tag": "NAME", "value": "starchy" }, { "context": "up Twitter messages.\n * \n * @author David @starchy Grant\n *\n */\ninterface MessageBak {\n\t\n\tJSONArray status", "end": 1108, "score": 0.6428877115249634, "start": 1103, "tag": "NAME", "value": "Grant" } ]
null
[]
/* * Copyright 2010 David "Starchy" Grant * * This file is part of TwitBak. * * TwitBak is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package twitbak; import java.util.List; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.internal.org.json.JSONArray; import twitter4j.internal.org.json.JSONObject; /** * Pattern for a class to backup Twitter messages. * * @author David @starchy Grant * */ interface MessageBak { JSONArray statusArray(); // Messages collected; will be phased out in favor of a SQLJet solution. JSONObject statusObject(); Twitter twitter(); // Class representing Twitter connection List<?> getStatusPage(int n) throws TwitterException, InterruptedException; // get n messages void getStatuses() throws TwitterException, InterruptedException; // get all messages }
1,521
0.752137
0.73833
46
32.065216
30.594402
98
false
false
0
0
0
0
0
0
0.782609
false
false
7
c0b74c19d56cbc5b2ab24a057374f14db5763bec
11,957,189,012,521
64f9dcc25f61dda30e1eac0c7f7dc3c51b9516a1
/modules/configuration/generated/com/guidewire/_generated/entity/DecimalClaimMetricInternal.java
6d11db17f189e288a92a7faeb76f74c749a8dac4
[]
no_license
kupaul/GW_CC9
https://github.com/kupaul/GW_CC9
fed506e7121d8ae57c3295c2785172f17a75d3a0
b6bd854dda057255e38be8e1fca9ac4a9099f41b
refs/heads/master
2022-11-05T12:36:46.704000
2020-06-24T16:04:43
2020-06-24T16:04:43
274,591,757
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.guidewire._generated.entity; @javax.annotation.Generated(value = "com.guidewire.pl.metadata.codegen.Codegen", comments = "DecimalClaimMetric.eti;DecimalClaimMetric.eix;DecimalClaimMetric.etx") @java.lang.SuppressWarnings(value = {"deprecation", "unchecked"}) public interface DecimalClaimMetricInternal extends com.guidewire._generated.entity.ClaimMetricInternal, com.guidewire._generated.entity.DecimalMetricDelegateInternal, gw.cc.claim.metric.entity.DecimalClaimMetric { }
UTF-8
Java
491
java
DecimalClaimMetricInternal.java
Java
[]
null
[]
package com.guidewire._generated.entity; @javax.annotation.Generated(value = "com.guidewire.pl.metadata.codegen.Codegen", comments = "DecimalClaimMetric.eti;DecimalClaimMetric.eix;DecimalClaimMetric.etx") @java.lang.SuppressWarnings(value = {"deprecation", "unchecked"}) public interface DecimalClaimMetricInternal extends com.guidewire._generated.entity.ClaimMetricInternal, com.guidewire._generated.entity.DecimalMetricDelegateInternal, gw.cc.claim.metric.entity.DecimalClaimMetric { }
491
0.830957
0.830957
7
69.285713
79.81356
214
false
false
0
0
0
0
0
0
1
false
false
7
0ac3c07e0f6a9748da388829fb2aa98f804fe879
11,957,189,009,150
b4455f4f99e4d3eda863812f29f0161089e4d0b8
/presentation/src/main/java/com/fernandocejas/android10/sample/presentation/ui/comment/CommentScene.java
4578b21f706467252a7fe5b669644e6137a5e484
[ "Apache-2.0" ]
permissive
leeprohacker/MAndroidCleanArchitecture
https://github.com/leeprohacker/MAndroidCleanArchitecture
a42d350881d9afcfd3cec26a3e4413701c5e0677
b45da787669cca38f9ba4c1c4df04bc9c2007c53
refs/heads/master
2021-04-12T11:02:53.788000
2018-03-23T01:28:14
2018-03-23T01:28:14
126,412,998
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fernandocejas.android10.sample.presentation.ui.comment; import com.fernandocejas.android10.sample.presentation.model.PComment; import com.fernandocejas.android10.sample.presentation.ui.base.MvpView; import java.util.List; /** * Created by Leeprohacker on 3/22/18. */ public interface CommentScene extends MvpView { boolean isCommentEmpty(); void onBindComment(List<PComment> transform); void addComment(PComment transform); }
UTF-8
Java
460
java
CommentScene.java
Java
[ { "context": "vpView;\n\nimport java.util.List;\n\n/**\n * Created by Leeprohacker on 3/22/18.\n */\npublic interface CommentScene ext", "end": 267, "score": 0.9996972680091858, "start": 255, "tag": "USERNAME", "value": "Leeprohacker" } ]
null
[]
package com.fernandocejas.android10.sample.presentation.ui.comment; import com.fernandocejas.android10.sample.presentation.model.PComment; import com.fernandocejas.android10.sample.presentation.ui.base.MvpView; import java.util.List; /** * Created by Leeprohacker on 3/22/18. */ public interface CommentScene extends MvpView { boolean isCommentEmpty(); void onBindComment(List<PComment> transform); void addComment(PComment transform); }
460
0.782609
0.758696
20
22
26.218315
71
false
false
0
0
0
0
0
0
0.35
false
false
7
ac70854f1a90c5147a60b578308ea8a81150f7b1
1,640,677,524,462
7be2e7622954a5878b8a10b012f81211d1cd69e4
/app/src/main/java/com/example/demo/Adapter/CricketerAdapter.java
b779b695a131133ea21259a18ec2594fad5d7aec
[]
no_license
abhay70/Trivia
https://github.com/abhay70/Trivia
870a45f88901d42c4f4981be96cbe8efcb4d3324
dfa440c24e77e705ef93171d9e88e7944f9c7deb
refs/heads/master
2020-05-03T00:04:06.588000
2019-03-28T23:59:10
2019-03-28T23:59:10
178,298,896
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo.Adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.ImageView; import com.example.demo.Activity.ColorsActivity; import com.example.demo.Activity.CricketerActivity; import com.example.demo.Database.ChatDBHelper; import com.example.demo.Database.ChatDBUtility; import com.example.demo.Model.ColorsDataRecords; import com.example.demo.Model.CricketerDataRecords; import com.example.demo.R; import java.util.ArrayList; /** * layout code 1 for displaying data for cricketers * layout code 2 for displaying data for colors * */ public class CricketerAdapter extends BaseAdapter { Context context; LayoutInflater vi; ChatDBHelper dbHelper; ChatDBUtility dbUtility; int selected_position=-1; int layout_code; ArrayList<CricketerDataRecords> cricketerDataRecords = new ArrayList<CricketerDataRecords>(); public CricketerAdapter(Context context, ArrayList<CricketerDataRecords> cricketerDataRecords,int layout_code) { super(); this.context = context; this.layout_code=layout_code; this.cricketerDataRecords = cricketerDataRecords; vi = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return cricketerDataRecords.size(); } @Override public Object getItem(int position) { return cricketerDataRecords.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { dbUtility = new ChatDBUtility(); dbHelper = dbUtility.CreateChatDB(context); final viewHolder holder; if (convertView == null) { convertView = vi.inflate(R.layout.adapter_cricketer, null); holder = new viewHolder(); holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox); convertView.setTag(holder); } else { holder = (viewHolder) convertView.getTag(); } holder.checkBox.setText(cricketerDataRecords.get(position).getCrickter()); /** * layout_code 1 - for cricketers ,2 - for colors */ if(layout_code==1) { /** * using if condition so that only checkBox is selected */ if (selected_position == position) { holder.checkBox.setChecked(true); } else { holder.checkBox.setChecked(false); } /** * for selecting cricketers */ holder.checkBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (((CheckBox) view).isChecked()) { selected_position = position; ((CricketerActivity) context).cricketer = cricketerDataRecords.get(position).getCrickter(); } else { selected_position = -1; } notifyDataSetChanged(); } }); }else if(layout_code==2) { /** * for selecting colors */ holder.checkBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (((CheckBox) view).isChecked()) { ((ColorsActivity)context).name.add(cricketerDataRecords.get(position).getCrickter()); } else { // if(((ColorsActivity)context).name.contains(cricketerDataRecords.get(position).getCrickter())) { ((ColorsActivity)context).name.remove(cricketerDataRecords.get(position).getCrickter()); } } notifyDataSetChanged(); } }); } return convertView; } static class viewHolder { public CheckBox checkBox; } }
UTF-8
Java
4,374
java
CricketerAdapter.java
Java
[]
null
[]
package com.example.demo.Adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.ImageView; import com.example.demo.Activity.ColorsActivity; import com.example.demo.Activity.CricketerActivity; import com.example.demo.Database.ChatDBHelper; import com.example.demo.Database.ChatDBUtility; import com.example.demo.Model.ColorsDataRecords; import com.example.demo.Model.CricketerDataRecords; import com.example.demo.R; import java.util.ArrayList; /** * layout code 1 for displaying data for cricketers * layout code 2 for displaying data for colors * */ public class CricketerAdapter extends BaseAdapter { Context context; LayoutInflater vi; ChatDBHelper dbHelper; ChatDBUtility dbUtility; int selected_position=-1; int layout_code; ArrayList<CricketerDataRecords> cricketerDataRecords = new ArrayList<CricketerDataRecords>(); public CricketerAdapter(Context context, ArrayList<CricketerDataRecords> cricketerDataRecords,int layout_code) { super(); this.context = context; this.layout_code=layout_code; this.cricketerDataRecords = cricketerDataRecords; vi = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return cricketerDataRecords.size(); } @Override public Object getItem(int position) { return cricketerDataRecords.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { dbUtility = new ChatDBUtility(); dbHelper = dbUtility.CreateChatDB(context); final viewHolder holder; if (convertView == null) { convertView = vi.inflate(R.layout.adapter_cricketer, null); holder = new viewHolder(); holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox); convertView.setTag(holder); } else { holder = (viewHolder) convertView.getTag(); } holder.checkBox.setText(cricketerDataRecords.get(position).getCrickter()); /** * layout_code 1 - for cricketers ,2 - for colors */ if(layout_code==1) { /** * using if condition so that only checkBox is selected */ if (selected_position == position) { holder.checkBox.setChecked(true); } else { holder.checkBox.setChecked(false); } /** * for selecting cricketers */ holder.checkBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (((CheckBox) view).isChecked()) { selected_position = position; ((CricketerActivity) context).cricketer = cricketerDataRecords.get(position).getCrickter(); } else { selected_position = -1; } notifyDataSetChanged(); } }); }else if(layout_code==2) { /** * for selecting colors */ holder.checkBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (((CheckBox) view).isChecked()) { ((ColorsActivity)context).name.add(cricketerDataRecords.get(position).getCrickter()); } else { // if(((ColorsActivity)context).name.contains(cricketerDataRecords.get(position).getCrickter())) { ((ColorsActivity)context).name.remove(cricketerDataRecords.get(position).getCrickter()); } } notifyDataSetChanged(); } }); } return convertView; } static class viewHolder { public CheckBox checkBox; } }
4,374
0.589392
0.587563
171
24.578947
27.527306
119
false
false
0
0
0
0
0
0
0.345029
false
false
7
63f946bed3ccccedb6b244b7ae5263c658578ad3
5,334,349,397,668
4c2212fee1431904b3ced0c0a919da015425de33
/seezoon-admin-server/src/main/java/com/seezoon/admin/modules/sys/security/listener/LoginEventListener.java
1408efd7069582dadebb578c44cbd217b62fb289
[ "MIT" ]
permissive
TurboLowcode/seezoon-stack
https://github.com/TurboLowcode/seezoon-stack
855afd019efb69b4fbe6d7a2a2fe05f1c0d2ccb0
1f3b954dd8716ca950302e785b112079772223df
refs/heads/master
2023-09-05T14:28:31.980000
2021-11-17T06:29:15
2021-11-17T06:29:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.seezoon.admin.modules.sys.security.listener; import java.util.Date; import java.util.Objects; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; import com.google.common.eventbus.Subscribe; import com.seezoon.admin.framework.properties.SeezoonAdminProperties; import com.seezoon.admin.modules.sys.eventbus.AdminEventBus; import com.seezoon.admin.modules.sys.security.LoginSecurityService; import com.seezoon.admin.modules.sys.security.SecurityUtils; import com.seezoon.admin.modules.sys.security.constant.LoginResult; import com.seezoon.admin.modules.sys.service.SysLoginLogService; import com.seezoon.dao.modules.sys.entity.SysLoginLog; import eu.bitwalker.useragentutils.Browser; import eu.bitwalker.useragentutils.OperatingSystem; import eu.bitwalker.useragentutils.UserAgent; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.extern.slf4j.Slf4j; /** * @author hdf */ @Component @RequiredArgsConstructor @Slf4j public class LoginEventListener implements InitializingBean { private final SysLoginLogService sysLoginLogService; private final LoginSecurityService loginSecurityService; private final SeezoonAdminProperties seezoonAdminProperties; @Subscribe public void listen(LoginResultMsg msg) { SysLoginLog sysLoginLog = new SysLoginLog(); sysLoginLog.setUserId(msg.getUserId()); sysLoginLog.setUserName(msg.getUserName()); sysLoginLog.setIp(msg.getIp()); sysLoginLog.setLoginTime(msg.getLoginTime()); sysLoginLog.setResult(msg.getResult()); sysLoginLog.setUserAgent(msg.getUserAgent()); try { UserAgent userAgent = UserAgent.parseUserAgentString(msg.getUserAgent()); Browser browser = userAgent.getBrowser(); OperatingSystem os = userAgent.getOperatingSystem(); String deviceName = os.getName() + " " + os.getDeviceType(); String browserDetail = browser.getName() + " " + browser.getVersion(msg.getUserAgent()); sysLoginLog.setBrowserName(browserDetail); sysLoginLog.setDeviceName(deviceName); } catch (Exception e) { log.error("parse userAgent error", e); } if (LoginResult.SUCCESS == msg.getResult()) { loginSecurityService.clear(msg.getUserName(), msg.getIp()); } else if (LoginResult.PASSWD_ERROR == msg.getResult()) { loginSecurityService.getIpLockStrategy().increment(msg.getIp()); if (!Objects.equals(msg.getUserId(), SecurityUtils.SUPER_ADMIN_USER_ID)) { loginSecurityService.getUsernameLockStrategy().increment(msg.getUserName()); } } else if (LoginResult.USERNAME_NOT_FOUND == msg.getResult()) { loginSecurityService.getIpLockStrategy().increment(msg.getIp()); } if (seezoonAdminProperties.getLogin().isRecordLog()) { sysLoginLogService.save(sysLoginLog); } } @Override public void afterPropertiesSet() throws Exception { AdminEventBus.register(this); } @RequiredArgsConstructor @Getter @Setter public static class LoginResultMsg { private final String userName; private final Date loginTime; private final String ip; private final String userAgent; private Integer result; private Integer userId; } }
UTF-8
Java
3,470
java
LoginEventListener.java
Java
[ { "context": "\nimport lombok.extern.slf4j.Slf4j;\n\n/**\n * @author hdf\n */\n@Component\n@RequiredArgsConstructor\n@Slf4j\npu", "end": 989, "score": 0.9996170997619629, "start": 986, "tag": "USERNAME", "value": "hdf" }, { "context": "ass LoginResultMsg {\n\n private final String userName;\n private final Date loginTime;\n pr", "end": 3285, "score": 0.8975374698638916, "start": 3277, "tag": "USERNAME", "value": "userName" } ]
null
[]
package com.seezoon.admin.modules.sys.security.listener; import java.util.Date; import java.util.Objects; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; import com.google.common.eventbus.Subscribe; import com.seezoon.admin.framework.properties.SeezoonAdminProperties; import com.seezoon.admin.modules.sys.eventbus.AdminEventBus; import com.seezoon.admin.modules.sys.security.LoginSecurityService; import com.seezoon.admin.modules.sys.security.SecurityUtils; import com.seezoon.admin.modules.sys.security.constant.LoginResult; import com.seezoon.admin.modules.sys.service.SysLoginLogService; import com.seezoon.dao.modules.sys.entity.SysLoginLog; import eu.bitwalker.useragentutils.Browser; import eu.bitwalker.useragentutils.OperatingSystem; import eu.bitwalker.useragentutils.UserAgent; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.extern.slf4j.Slf4j; /** * @author hdf */ @Component @RequiredArgsConstructor @Slf4j public class LoginEventListener implements InitializingBean { private final SysLoginLogService sysLoginLogService; private final LoginSecurityService loginSecurityService; private final SeezoonAdminProperties seezoonAdminProperties; @Subscribe public void listen(LoginResultMsg msg) { SysLoginLog sysLoginLog = new SysLoginLog(); sysLoginLog.setUserId(msg.getUserId()); sysLoginLog.setUserName(msg.getUserName()); sysLoginLog.setIp(msg.getIp()); sysLoginLog.setLoginTime(msg.getLoginTime()); sysLoginLog.setResult(msg.getResult()); sysLoginLog.setUserAgent(msg.getUserAgent()); try { UserAgent userAgent = UserAgent.parseUserAgentString(msg.getUserAgent()); Browser browser = userAgent.getBrowser(); OperatingSystem os = userAgent.getOperatingSystem(); String deviceName = os.getName() + " " + os.getDeviceType(); String browserDetail = browser.getName() + " " + browser.getVersion(msg.getUserAgent()); sysLoginLog.setBrowserName(browserDetail); sysLoginLog.setDeviceName(deviceName); } catch (Exception e) { log.error("parse userAgent error", e); } if (LoginResult.SUCCESS == msg.getResult()) { loginSecurityService.clear(msg.getUserName(), msg.getIp()); } else if (LoginResult.PASSWD_ERROR == msg.getResult()) { loginSecurityService.getIpLockStrategy().increment(msg.getIp()); if (!Objects.equals(msg.getUserId(), SecurityUtils.SUPER_ADMIN_USER_ID)) { loginSecurityService.getUsernameLockStrategy().increment(msg.getUserName()); } } else if (LoginResult.USERNAME_NOT_FOUND == msg.getResult()) { loginSecurityService.getIpLockStrategy().increment(msg.getIp()); } if (seezoonAdminProperties.getLogin().isRecordLog()) { sysLoginLogService.save(sysLoginLog); } } @Override public void afterPropertiesSet() throws Exception { AdminEventBus.register(this); } @RequiredArgsConstructor @Getter @Setter public static class LoginResultMsg { private final String userName; private final Date loginTime; private final String ip; private final String userAgent; private Integer result; private Integer userId; } }
3,470
0.713256
0.712392
91
37.131866
26.266684
100
false
false
0
0
0
0
0
0
0.582418
false
false
7
e2b899870ec1fc422d0537a8e7490d24480a26a4
26,723,286,529,373
dfbaa763aba31075958007d91c9c0d4b1b34ff1c
/crypto/xsalsa20poly1305.java
8f388f1d5fe8352b12303c593d0e53a73c38608b
[]
no_license
ATOMEN/jnacl
https://github.com/ATOMEN/jnacl
8e0b6a3ce69e755d2fcde1aa1d6ea1420d68f4d2
7c5720b17bfcdabbd3a56f0f3a3cdd849d2f8c3e
refs/heads/master
2020-12-24T17:53:51.244000
2012-01-16T23:57:14
2012-01-16T23:57:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.neilalexander.jnacl.crypto; public class xsalsa20poly1305 { final int crypto_secretbox_KEYBYTES = 32; final int crypto_secretbox_NONCEBYTES = 24; final int crypto_secretbox_ZEROBYTES = 32; final int crypto_secretbox_BOXZEROBYTES = 16; static public int crypto_secretbox(byte[] c, byte[] m, long mlen, byte[] n, byte[] k) { if (mlen < 32) return -1; xsalsa20.crypto_stream_xor(c, m, mlen, n, k); poly1305.crypto_onetimeauth(c, 16, c, 32, mlen - 32, c); for (int i = 0; i < 16; ++i) c[i] = 0; return 0; } static public int crypto_secretbox_open(byte[] m, byte[] c, long clen, byte[] n, byte[] k) { if (clen < 32) return -1; byte[] subkeyp = new byte[32]; xsalsa20.crypto_stream(subkeyp, 32, n, k); if (poly1305.crypto_onetimeauth_verify(c, 16, c, 32, clen - 32, subkeyp) != 0) return -1; xsalsa20.crypto_stream_xor(m, c, clen, n, k); for (int i = 0; i < 32; ++i) m[i] = 0; return 0; } }
UTF-8
Java
972
java
xsalsa20poly1305.java
Java
[]
null
[]
package com.neilalexander.jnacl.crypto; public class xsalsa20poly1305 { final int crypto_secretbox_KEYBYTES = 32; final int crypto_secretbox_NONCEBYTES = 24; final int crypto_secretbox_ZEROBYTES = 32; final int crypto_secretbox_BOXZEROBYTES = 16; static public int crypto_secretbox(byte[] c, byte[] m, long mlen, byte[] n, byte[] k) { if (mlen < 32) return -1; xsalsa20.crypto_stream_xor(c, m, mlen, n, k); poly1305.crypto_onetimeauth(c, 16, c, 32, mlen - 32, c); for (int i = 0; i < 16; ++i) c[i] = 0; return 0; } static public int crypto_secretbox_open(byte[] m, byte[] c, long clen, byte[] n, byte[] k) { if (clen < 32) return -1; byte[] subkeyp = new byte[32]; xsalsa20.crypto_stream(subkeyp, 32, n, k); if (poly1305.crypto_onetimeauth_verify(c, 16, c, 32, clen - 32, subkeyp) != 0) return -1; xsalsa20.crypto_stream_xor(m, c, clen, n, k); for (int i = 0; i < 32; ++i) m[i] = 0; return 0; } }
972
0.622428
0.558642
43
21.627907
24.650131
91
false
false
0
0
0
0
0
0
2.651163
false
false
7
5e7c7fc8ec23fd0237a2ccd024ed5c1353259f45
10,814,727,667,303
1fa85fcc04df5407cfd2f61d685f902cd478e14e
/src/main/java/th/test/producer/blocking/Consumer.java
7978df787058bed9f4d013a47a0f361aed397af9
[]
no_license
ravikumar9555564130/java_8th
https://github.com/ravikumar9555564130/java_8th
9db181ad0531db830ddeea3b4d8b9f330675e29b
83b9956228b09b1006140a30fcc4250cd120f391
refs/heads/master
2020-04-05T10:26:54.306000
2019-04-27T04:53:06
2019-04-27T04:53:06
156,799,092
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package th.test.producer.blocking; import java.util.concurrent.BlockingQueue; public class Consumer extends Thread { BlockingQueue<Integer> blockingQueue = null; Consumer(BlockingQueue<Integer> blockingQueue) { this.blockingQueue = blockingQueue; } public void run() { while (true) { try { Integer value = blockingQueue.take(); System.out.println("value :: " + value); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
UTF-8
Java
539
java
Consumer.java
Java
[]
null
[]
package th.test.producer.blocking; import java.util.concurrent.BlockingQueue; public class Consumer extends Thread { BlockingQueue<Integer> blockingQueue = null; Consumer(BlockingQueue<Integer> blockingQueue) { this.blockingQueue = blockingQueue; } public void run() { while (true) { try { Integer value = blockingQueue.take(); System.out.println("value :: " + value); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
539
0.658627
0.658627
27
17.962963
18.466148
49
false
false
0
0
0
0
0
0
1.592593
false
false
7
75342cc1af37bfe2ac65e2dd541c74fdc8b9ced6
15,461,882,282,015
5691d77d71c82cc96101b22f8ad7ccedfa1cdc3f
/QuanLyNhaThuocTay/src/dao/DatabaseConnection.java
99e4b51b1670e2a97de6a23af05d162bdc9ef906
[]
no_license
LongS7/Pharmacy-Managerment-System
https://github.com/LongS7/Pharmacy-Managerment-System
0fe1ca07ca5395ceefb3333db3e4979c511ce1b6
684f7668a6a4325d72305932c97280012d06cfde
refs/heads/master
2023-02-12T14:42:27.161000
2021-01-07T14:38:17
2021-01-07T14:38:17
303,634,079
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dao; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; public class DatabaseConnection { private SessionFactory sessionFactory; private static DatabaseConnection databaseConnection; private DatabaseConnection() { StandardServiceRegistry registry = new StandardServiceRegistryBuilder() .configure("CONFIG/hibernate.cfg.xml") .build(); Metadata metadata = new MetadataSources(registry) .addAnnotatedClass(entity.NhaCungCap.class) .addAnnotatedClass(entity.KhachHang.class) .addAnnotatedClass(entity.NhanVien.class) .addAnnotatedClass(entity.Thuoc.class) .addAnnotatedClass(entity.HoaDon.class) .addAnnotatedClass(entity.CTHoaDon.class) .addAnnotatedClass(entity.CTHoaDon_PK.class) .addAnnotatedClass(entity.HoatChat.class) .addAnnotatedClass(entity.LoThuoc.class) .getMetadataBuilder() .build(); this.sessionFactory = metadata.getSessionFactoryBuilder().build(); } public SessionFactory getSessionFactory() { return sessionFactory; } public static DatabaseConnection getInstance() { if(databaseConnection == null) databaseConnection = new DatabaseConnection(); return databaseConnection; } }
UTF-8
Java
1,374
java
DatabaseConnection.java
Java
[]
null
[]
package dao; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; public class DatabaseConnection { private SessionFactory sessionFactory; private static DatabaseConnection databaseConnection; private DatabaseConnection() { StandardServiceRegistry registry = new StandardServiceRegistryBuilder() .configure("CONFIG/hibernate.cfg.xml") .build(); Metadata metadata = new MetadataSources(registry) .addAnnotatedClass(entity.NhaCungCap.class) .addAnnotatedClass(entity.KhachHang.class) .addAnnotatedClass(entity.NhanVien.class) .addAnnotatedClass(entity.Thuoc.class) .addAnnotatedClass(entity.HoaDon.class) .addAnnotatedClass(entity.CTHoaDon.class) .addAnnotatedClass(entity.CTHoaDon_PK.class) .addAnnotatedClass(entity.HoatChat.class) .addAnnotatedClass(entity.LoThuoc.class) .getMetadataBuilder() .build(); this.sessionFactory = metadata.getSessionFactoryBuilder().build(); } public SessionFactory getSessionFactory() { return sessionFactory; } public static DatabaseConnection getInstance() { if(databaseConnection == null) databaseConnection = new DatabaseConnection(); return databaseConnection; } }
1,374
0.791121
0.791121
45
29.533333
21.763987
73
false
false
0
0
0
0
0
0
1.955556
false
false
7
8d7064dc97c854b5b03b3973436a26985a366837
14,877,766,734,706
7ee2cf4fd13fe7f3df463d80cddd80ac91a68f7a
/src/home/ur4eg/dev/dds/PatternStrategy/FlyBehavior.java
2e3245aa5f7763c1b207d5dc3b7f642d44214cfd
[]
no_license
Ur4eG/MyProject
https://github.com/Ur4eG/MyProject
8c84b599f79fd59b8eb0a7c0239e46ee8d1fcccc
14d95d82259755fdb3628592714f4ab34e41e0fc
refs/heads/master
2020-06-30T18:20:05.485000
2018-09-10T14:06:18
2018-09-10T14:06:18
66,629,657
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package home.ur4eg.dev.dds.PatternStrategy; /** * Created by Ur4eG on 15-Feb-16. */ interface FlyBehavior{ void fly(); }
UTF-8
Java
129
java
FlyBehavior.java
Java
[ { "context": ".ur4eg.dev.dds.PatternStrategy;\n\n/**\n * Created by Ur4eG on 15-Feb-16.\n */\n\ninterface FlyBehavior{\n voi", "end": 68, "score": 0.9996379017829895, "start": 63, "tag": "USERNAME", "value": "Ur4eG" } ]
null
[]
package home.ur4eg.dev.dds.PatternStrategy; /** * Created by Ur4eG on 15-Feb-16. */ interface FlyBehavior{ void fly(); }
129
0.674419
0.627907
9
13.333333
15.151091
43
false
false
0
0
0
0
0
0
0.222222
false
false
7
65564e8722bca09bb82125c35486f0999f203a0d
6,373,731,483,332
01eb475cb16a51d7bb9f3ebae7c6dec7d7baec56
/app/src/main/java/com/renwey/emi/emi/bean/EIMCustomersBean.java
574d43fc5a9ac88e4d95a4129fdd0f258822b559
[]
no_license
chendongde310/EMI
https://github.com/chendongde310/EMI
9933a81057790fdbee0988d38da1ef10f79355c8
3afe2ed9d071eaf7ec9d7ab6e5c015a316f16798
refs/heads/master
2016-09-22T06:07:41.280000
2016-09-02T05:53:10
2016-09-02T05:53:10
64,731,798
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.renwey.emi.emi.bean; import com.google.gson.annotations.SerializedName; import java.util.List; /** * 作者:陈东 — www.renwey.com * 日期:2016/8/2 - 16:11 * 注释: */ public class EIMCustomersBean { /** * id : ffccd25b-ceb3-4815-8f63-770add069136 * positionId : 4a58de98-3d03-4f6d-8499-a8df948542c6 * customerCardId : cd006f08-188a-471d-8074-f1ffc5748f89 * customerMark : null * comunications : [] * createTime : 2016-07-28 17:11:17 * updateTime : 2016-07-28 17:11:17 * card : {"id":"cd006f08-188a-471d-8074-f1ffc5748f89","name":"熊佳欣","phone":"18883278414","gender":null,"position":null,"company":null,"industry":null,"department":null,"tel":null,"email":null,"website":null,"address":null,"location":null,"industryDetail":null,"portraitUrl":null,"locationDetail":null} */ @SerializedName("id") private String id; @SerializedName("positionId") private String positionId; @SerializedName("customerCardId") private String customerCardId; @SerializedName("customerMark") private String customerMark; @SerializedName("createTime") private String createTime; @SerializedName("updateTime") private String updateTime; @SerializedName("card") private EIMCardBean card; @SerializedName("comunications") private List<EIMComunicationsBean> comunications; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPositionId() { return positionId; } public void setPositionId(String positionId) { this.positionId = positionId; } public String getCustomerCardId() { return customerCardId; } public void setCustomerCardId(String customerCardId) { this.customerCardId = customerCardId; } public String getCustomerMark() { return customerMark; } public void setCustomerMark(String customerMark) { this.customerMark = customerMark; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } public EIMCardBean getCard() { return card; } public void setCard(EIMCardBean card) { this.card = card; } public List<EIMComunicationsBean> getComunications() { return comunications; } public void setComunications(List<EIMComunicationsBean> comunications) { this.comunications = comunications; } }
UTF-8
Java
2,753
java
EIMCustomersBean.java
Java
[ { "context": "erializedName;\n\nimport java.util.List;\n\n/**\n * 作者:陈东 — www.renwey.com\n * 日期:2016/8/2 - 16:11\n * 注释:\n", "end": 122, "score": 0.9997386932373047, "start": 120, "tag": "NAME", "value": "陈东" }, { "context": "d\":\"cd006f08-188a-471d-8074-f1ffc5748f89\",\"name\":\"熊佳欣\",\"phone\":\"18883278414\",\"gender\":null,\"position\":n", "end": 588, "score": 0.9998638033866882, "start": 585, "tag": "NAME", "value": "熊佳欣" } ]
null
[]
package com.renwey.emi.emi.bean; import com.google.gson.annotations.SerializedName; import java.util.List; /** * 作者:陈东 — www.renwey.com * 日期:2016/8/2 - 16:11 * 注释: */ public class EIMCustomersBean { /** * id : ffccd25b-ceb3-4815-8f63-770add069136 * positionId : 4a58de98-3d03-4f6d-8499-a8df948542c6 * customerCardId : cd006f08-188a-471d-8074-f1ffc5748f89 * customerMark : null * comunications : [] * createTime : 2016-07-28 17:11:17 * updateTime : 2016-07-28 17:11:17 * card : {"id":"cd006f08-188a-471d-8074-f1ffc5748f89","name":"熊佳欣","phone":"18883278414","gender":null,"position":null,"company":null,"industry":null,"department":null,"tel":null,"email":null,"website":null,"address":null,"location":null,"industryDetail":null,"portraitUrl":null,"locationDetail":null} */ @SerializedName("id") private String id; @SerializedName("positionId") private String positionId; @SerializedName("customerCardId") private String customerCardId; @SerializedName("customerMark") private String customerMark; @SerializedName("createTime") private String createTime; @SerializedName("updateTime") private String updateTime; @SerializedName("card") private EIMCardBean card; @SerializedName("comunications") private List<EIMComunicationsBean> comunications; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPositionId() { return positionId; } public void setPositionId(String positionId) { this.positionId = positionId; } public String getCustomerCardId() { return customerCardId; } public void setCustomerCardId(String customerCardId) { this.customerCardId = customerCardId; } public String getCustomerMark() { return customerMark; } public void setCustomerMark(String customerMark) { this.customerMark = customerMark; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } public EIMCardBean getCard() { return card; } public void setCard(EIMCardBean card) { this.card = card; } public List<EIMComunicationsBean> getComunications() { return comunications; } public void setComunications(List<EIMComunicationsBean> comunications) { this.comunications = comunications; } }
2,753
0.66177
0.61256
109
23.981651
33.037643
306
false
false
0
0
0
0
0
0
0.385321
false
false
7
eba0181f181d02df1d4926cac095b796db2493ec
19,164,144,097,847
5a130eade64d589f5ab0c2d2566b16fef00b4435
/logica/src/variaveis/CalculoProduto.java
b13ed1cace374b448e9f858fc2f9a8cacff3c100
[ "Unlicense" ]
permissive
rodrigofasano/wsnewfasano
https://github.com/rodrigofasano/wsnewfasano
51666404709c5fe89d99ca419ca6b35c4c4a2bef
9a609bb85e8ba7abde37a9764c1009e32c1cbd45
refs/heads/main
2023-05-21T01:05:32.337000
2021-06-11T18:11:50
2021-06-11T18:11:50
372,499,844
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package variaveis; import javax.swing.JOptionPane; public class CalculoProduto { public static void main(String[] args) { /* * - nome do produto * - qtd do produto * - valor unitario * exibir no final: * * - nome do produto * - valor totql * - valor do imposto (17%sobre o valor total) */ String nome_produto =JOptionPane.showInputDialog("Digite o nome do produto"); int qtd_produto = Integer.parseInt(JOptionPane.showInputDialog("Digite a quantidade do produto")); double valor_unitario = Double.parseDouble(JOptionPane.showInputDialog("Digite o valor unitário do produto")); // Calculo sendo executado com entrada declaradas em variaveis e saida pelas variaveis // double valor_total = valor_unitario * qtd_produto; // double valor_imposto = (valor_unitario * qtd_produto)*0.17; //System.out.println("Produto...............: "+ nome_produto); //System.out.println("Valor Total...........: R$ "+ valor_total); //System.out.println("Imposto calculado.....: R$ "+ valor_imposto); // Calculo sendo executado direto na saida de valores System.out.println("Produto...............: "+ nome_produto); System.out.println("Valor Total...........: R$ "+ (valor_unitario * qtd_produto)); System.out.println("Imposto calculado.....: R$ "+ (valor_unitario * qtd_produto)*0.17); /* * Tipos de dados * * Tipos Primitivos (Todos aqueles que começam com letra minuscula) * Boolean => Lógico (True/False) * char => um caracter entre apostrofos " " * * byte -> -127/+127 * short => -32 mil / +32 mil * int => -2 Trilhoes / +2 trilhoes * long => (-) 9 quintilhoes / (+) 9 quintilhoes * * float => até 5 casas decimais * double => acima disso. */ } }
ISO-8859-1
Java
2,027
java
CalculoProduto.java
Java
[]
null
[]
package variaveis; import javax.swing.JOptionPane; public class CalculoProduto { public static void main(String[] args) { /* * - nome do produto * - qtd do produto * - valor unitario * exibir no final: * * - nome do produto * - valor totql * - valor do imposto (17%sobre o valor total) */ String nome_produto =JOptionPane.showInputDialog("Digite o nome do produto"); int qtd_produto = Integer.parseInt(JOptionPane.showInputDialog("Digite a quantidade do produto")); double valor_unitario = Double.parseDouble(JOptionPane.showInputDialog("Digite o valor unitário do produto")); // Calculo sendo executado com entrada declaradas em variaveis e saida pelas variaveis // double valor_total = valor_unitario * qtd_produto; // double valor_imposto = (valor_unitario * qtd_produto)*0.17; //System.out.println("Produto...............: "+ nome_produto); //System.out.println("Valor Total...........: R$ "+ valor_total); //System.out.println("Imposto calculado.....: R$ "+ valor_imposto); // Calculo sendo executado direto na saida de valores System.out.println("Produto...............: "+ nome_produto); System.out.println("Valor Total...........: R$ "+ (valor_unitario * qtd_produto)); System.out.println("Imposto calculado.....: R$ "+ (valor_unitario * qtd_produto)*0.17); /* * Tipos de dados * * Tipos Primitivos (Todos aqueles que começam com letra minuscula) * Boolean => Lógico (True/False) * char => um caracter entre apostrofos " " * * byte -> -127/+127 * short => -32 mil / +32 mil * int => -2 Trilhoes / +2 trilhoes * long => (-) 9 quintilhoes / (+) 9 quintilhoes * * float => até 5 casas decimais * double => acima disso. */ } }
2,027
0.55561
0.544241
80
24.2875
29.624819
116
false
false
0
0
0
0
0
0
2
false
false
7
88c2ebfe76ba7f148ee22905f4be8e2978e5a5fd
17,970,143,217,282
14b9305fdce5f728faeb8f04fbb05c5b5e794771
/app/src/main/java/com/abborg/glom/utils/DateUtils.java
dcb9971d2fe480f2c4b559f5850b808cb763b25e
[]
no_license
Yoshi3003/glom-android
https://github.com/Yoshi3003/glom-android
c593cbbaef4135efd97f08ccb7bb79c176c145c2
eb3277947e0c097c2cf690aebd91596e514e1f6b
refs/heads/master
2020-04-10T22:42:03.647000
2017-04-29T03:45:00
2017-04-29T03:45:00
42,091,534
8
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.abborg.glom.utils; import android.content.Context; import com.abborg.glom.R; import org.joda.time.DateTime; import org.joda.time.Days; import org.joda.time.Period; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * Helper class that deals with date time. */ public class DateUtils { public static String getFormattedTimeFromNow(Context context, DateTime timeToCompare) { String duration; DateTime now = new DateTime(); Period period = new Period(now, timeToCompare); int years = period.getYears() * -1; int months = period.getMonths() * -1; int weeks = period.getWeeks() * -1; int hours = period.getHours() * -1; int days = period.getDays() * -1; int minutes = period.getMinutes() * -1; // positive periods if (period.getYears() >= 1) duration = period.getYears() + " " + context.getResources().getString(R.string.time_unit_year) + " " + context.getResources().getString(R.string.time_unit_and_seperator) + " " + period.getMonths() + " " + context.getResources().getString(R.string.time_unit_month); else if (period.getMonths() >= 1) duration = period.getMonths() + " " + context.getResources().getString(R.string.time_unit_month) + " " + context.getResources().getString(R.string.time_unit_and_seperator) + " " + period.getDays() + " " + context.getResources().getString(R.string.time_unit_day); else if (period.getWeeks() >= 1) duration = period.getWeeks() + " " + context.getResources().getString(R.string.time_unit_week) + " " + context.getResources().getString(R.string.time_unit_and_seperator) + " " + period.getDays() + " " + context.getResources().getString(R.string.time_unit_day); else if (period.getDays() >= 1) duration = period.getDays() + " " + context.getResources().getString(R.string.time_unit_day) + " " + context.getResources().getString(R.string.time_unit_and_seperator) + " " + period.getHours() + " " + context.getResources().getString(R.string.time_unit_hour); else if (period.getHours() >= 1) duration = period.getHours() + " " + context.getResources().getString(R.string.time_unit_hour) + " " + context.getResources().getString(R.string.time_unit_and_seperator) + " " + period.getMinutes() + " " + context.getResources().getString(R.string.time_unit_minute); else if (period.getMinutes() >= 0) duration = period.getMinutes() + " " + context.getResources().getString(R.string.time_unit_minute); // negative periods (already passed) else if (period.getYears() <= -1) { duration = years + " " + context.getResources().getString(R.string.time_unit_year) + " " + context.getResources().getString(R.string.time_unit_and_seperator) + " " + months + " " + context.getResources().getString(R.string.time_unit_month) + " " + context.getResources().getString(R.string.time_suffix_ago); } else if (period.getMonths() <= -1) { duration = months + " " + context.getResources().getString(R.string.time_unit_month) + " " + context.getResources().getString(R.string.time_unit_and_seperator) + " " + days + " " + context.getResources().getString(R.string.time_unit_day) + " " + context.getResources().getString(R.string.time_suffix_ago); } else if (period.getWeeks() <= -1) { duration = weeks + " " + context.getResources().getString(R.string.time_unit_week) + " " + context.getResources().getString(R.string.time_unit_and_seperator) + " " + days + " " + context.getResources().getString(R.string.time_unit_day) + " " + context.getResources().getString(R.string.time_suffix_ago); } else if (period.getDays() <= -1) { duration = days + " " + context.getResources().getString(R.string.time_unit_day) + " " + context.getResources().getString(R.string.time_unit_and_seperator) + " " + hours + " " + context.getResources().getString(R.string.time_unit_hour) + " " + context.getResources().getString(R.string.time_suffix_ago); } else if (period.getHours() <= -1) { duration = hours + " " + context.getResources().getString(R.string.time_unit_hour) + " " + context.getResources().getString(R.string.time_unit_and_seperator) + " " + minutes + " " + context.getResources().getString(R.string.time_unit_minute) + " " + context.getResources().getString(R.string.time_suffix_ago); } else { duration = minutes + " " + context.getResources().getString(R.string.time_unit_minute) + " " + context.getResources().getString(R.string.time_suffix_ago); } return duration; } public static String getFormattedDate(Context context, DateTime startDate, DateTime endDate) { DateTimeFormatter formatter = DateTimeFormat.forPattern(context.getResources().getString(R.string.card_event_datetime_format)); DateTimeFormatter timeFormatter = DateTimeFormat.forPattern(context.getResources().getString(R.string.card_event_time_format)); DateTime now = new DateTime(); String formattedStartDateTime; String formattedEndDateTime; if (startDate == null) { startDate = now; } int daysBetween = Days.daysBetween(now.withTimeAtStartOfDay(), startDate.withTimeAtStartOfDay()).getDays(); DateTimeFormatter dayWithTimeFormatter = DateTimeFormat.forPattern("EEEE, " + context.getResources().getString(R.string.card_event_time_format)); if (startDate.getMillis() == now.getMillis()) { formattedStartDateTime = context.getResources().getString(R.string.date_now); } else if (daysBetween == -1) { formattedStartDateTime = context.getResources().getString(R.string.time_yesterday) + ", " + timeFormatter.print(startDate); } else if (daysBetween == 0) { formattedStartDateTime = context.getResources().getString(R.string.time_today) + ", " + timeFormatter.print(startDate); } else if (daysBetween == 1) { formattedStartDateTime = context.getResources().getString(R.string.time_tomorrow) + ", " + timeFormatter.print(startDate); } else if (daysBetween < 7 && daysBetween > 0) { formattedStartDateTime = dayWithTimeFormatter.print(startDate); } else { formattedStartDateTime = formatter.print(startDate); } if (endDate != null) { daysBetween = Days.daysBetween(now.withTimeAtStartOfDay(), endDate.withTimeAtStartOfDay()).getDays(); int daysDuration = Days.daysBetween(startDate.withTimeAtStartOfDay(), endDate.withTimeAtStartOfDay()).getDays(); if (daysDuration == 0) { formattedEndDateTime = " - " + timeFormatter.print(endDate) + " "; } else { if (daysBetween == -1) { formattedEndDateTime = " - " + context.getResources().getString(R.string.time_yesterday) + ", " + timeFormatter.print(endDate) + " "; } else if (daysBetween == 0) { formattedEndDateTime = " - " + context.getResources().getString(R.string.time_today) + ", " + timeFormatter.print(endDate) + " "; } else if (daysBetween == 1) { formattedEndDateTime = " - " + context.getResources().getString(R.string.time_tomorrow) + ", " + timeFormatter.print(endDate) + " "; } else if (daysBetween < 7 && daysBetween > 0) { formattedEndDateTime = " - " + dayWithTimeFormatter.print(endDate) + " "; } else { formattedEndDateTime = " - " + formatter.print(endDate) + " "; } } } else { formattedEndDateTime = ""; } return formattedStartDateTime + formattedEndDateTime; } }
UTF-8
Java
8,896
java
DateUtils.java
Java
[]
null
[]
package com.abborg.glom.utils; import android.content.Context; import com.abborg.glom.R; import org.joda.time.DateTime; import org.joda.time.Days; import org.joda.time.Period; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * Helper class that deals with date time. */ public class DateUtils { public static String getFormattedTimeFromNow(Context context, DateTime timeToCompare) { String duration; DateTime now = new DateTime(); Period period = new Period(now, timeToCompare); int years = period.getYears() * -1; int months = period.getMonths() * -1; int weeks = period.getWeeks() * -1; int hours = period.getHours() * -1; int days = period.getDays() * -1; int minutes = period.getMinutes() * -1; // positive periods if (period.getYears() >= 1) duration = period.getYears() + " " + context.getResources().getString(R.string.time_unit_year) + " " + context.getResources().getString(R.string.time_unit_and_seperator) + " " + period.getMonths() + " " + context.getResources().getString(R.string.time_unit_month); else if (period.getMonths() >= 1) duration = period.getMonths() + " " + context.getResources().getString(R.string.time_unit_month) + " " + context.getResources().getString(R.string.time_unit_and_seperator) + " " + period.getDays() + " " + context.getResources().getString(R.string.time_unit_day); else if (period.getWeeks() >= 1) duration = period.getWeeks() + " " + context.getResources().getString(R.string.time_unit_week) + " " + context.getResources().getString(R.string.time_unit_and_seperator) + " " + period.getDays() + " " + context.getResources().getString(R.string.time_unit_day); else if (period.getDays() >= 1) duration = period.getDays() + " " + context.getResources().getString(R.string.time_unit_day) + " " + context.getResources().getString(R.string.time_unit_and_seperator) + " " + period.getHours() + " " + context.getResources().getString(R.string.time_unit_hour); else if (period.getHours() >= 1) duration = period.getHours() + " " + context.getResources().getString(R.string.time_unit_hour) + " " + context.getResources().getString(R.string.time_unit_and_seperator) + " " + period.getMinutes() + " " + context.getResources().getString(R.string.time_unit_minute); else if (period.getMinutes() >= 0) duration = period.getMinutes() + " " + context.getResources().getString(R.string.time_unit_minute); // negative periods (already passed) else if (period.getYears() <= -1) { duration = years + " " + context.getResources().getString(R.string.time_unit_year) + " " + context.getResources().getString(R.string.time_unit_and_seperator) + " " + months + " " + context.getResources().getString(R.string.time_unit_month) + " " + context.getResources().getString(R.string.time_suffix_ago); } else if (period.getMonths() <= -1) { duration = months + " " + context.getResources().getString(R.string.time_unit_month) + " " + context.getResources().getString(R.string.time_unit_and_seperator) + " " + days + " " + context.getResources().getString(R.string.time_unit_day) + " " + context.getResources().getString(R.string.time_suffix_ago); } else if (period.getWeeks() <= -1) { duration = weeks + " " + context.getResources().getString(R.string.time_unit_week) + " " + context.getResources().getString(R.string.time_unit_and_seperator) + " " + days + " " + context.getResources().getString(R.string.time_unit_day) + " " + context.getResources().getString(R.string.time_suffix_ago); } else if (period.getDays() <= -1) { duration = days + " " + context.getResources().getString(R.string.time_unit_day) + " " + context.getResources().getString(R.string.time_unit_and_seperator) + " " + hours + " " + context.getResources().getString(R.string.time_unit_hour) + " " + context.getResources().getString(R.string.time_suffix_ago); } else if (period.getHours() <= -1) { duration = hours + " " + context.getResources().getString(R.string.time_unit_hour) + " " + context.getResources().getString(R.string.time_unit_and_seperator) + " " + minutes + " " + context.getResources().getString(R.string.time_unit_minute) + " " + context.getResources().getString(R.string.time_suffix_ago); } else { duration = minutes + " " + context.getResources().getString(R.string.time_unit_minute) + " " + context.getResources().getString(R.string.time_suffix_ago); } return duration; } public static String getFormattedDate(Context context, DateTime startDate, DateTime endDate) { DateTimeFormatter formatter = DateTimeFormat.forPattern(context.getResources().getString(R.string.card_event_datetime_format)); DateTimeFormatter timeFormatter = DateTimeFormat.forPattern(context.getResources().getString(R.string.card_event_time_format)); DateTime now = new DateTime(); String formattedStartDateTime; String formattedEndDateTime; if (startDate == null) { startDate = now; } int daysBetween = Days.daysBetween(now.withTimeAtStartOfDay(), startDate.withTimeAtStartOfDay()).getDays(); DateTimeFormatter dayWithTimeFormatter = DateTimeFormat.forPattern("EEEE, " + context.getResources().getString(R.string.card_event_time_format)); if (startDate.getMillis() == now.getMillis()) { formattedStartDateTime = context.getResources().getString(R.string.date_now); } else if (daysBetween == -1) { formattedStartDateTime = context.getResources().getString(R.string.time_yesterday) + ", " + timeFormatter.print(startDate); } else if (daysBetween == 0) { formattedStartDateTime = context.getResources().getString(R.string.time_today) + ", " + timeFormatter.print(startDate); } else if (daysBetween == 1) { formattedStartDateTime = context.getResources().getString(R.string.time_tomorrow) + ", " + timeFormatter.print(startDate); } else if (daysBetween < 7 && daysBetween > 0) { formattedStartDateTime = dayWithTimeFormatter.print(startDate); } else { formattedStartDateTime = formatter.print(startDate); } if (endDate != null) { daysBetween = Days.daysBetween(now.withTimeAtStartOfDay(), endDate.withTimeAtStartOfDay()).getDays(); int daysDuration = Days.daysBetween(startDate.withTimeAtStartOfDay(), endDate.withTimeAtStartOfDay()).getDays(); if (daysDuration == 0) { formattedEndDateTime = " - " + timeFormatter.print(endDate) + " "; } else { if (daysBetween == -1) { formattedEndDateTime = " - " + context.getResources().getString(R.string.time_yesterday) + ", " + timeFormatter.print(endDate) + " "; } else if (daysBetween == 0) { formattedEndDateTime = " - " + context.getResources().getString(R.string.time_today) + ", " + timeFormatter.print(endDate) + " "; } else if (daysBetween == 1) { formattedEndDateTime = " - " + context.getResources().getString(R.string.time_tomorrow) + ", " + timeFormatter.print(endDate) + " "; } else if (daysBetween < 7 && daysBetween > 0) { formattedEndDateTime = " - " + dayWithTimeFormatter.print(endDate) + " "; } else { formattedEndDateTime = " - " + formatter.print(endDate) + " "; } } } else { formattedEndDateTime = ""; } return formattedStartDateTime + formattedEndDateTime; } }
8,896
0.561264
0.558116
163
52.576687
38.131012
135
false
false
0
0
0
0
0
0
0.417178
false
false
7
64c9ac2209698affbc0f923111dc517d2b2ffff6
6,614,249,685,960
045d09449f73c1fcdd2027c63ab66689438127aa
/chapter_001/src/test/java/ru/job4j/MainTest.java
7d8299ccf0d6c50ab0e7dccf216d51bcf76de743
[ "Apache-2.0" ]
permissive
staskorobeynikov/job4j
https://github.com/staskorobeynikov/job4j
d2d7783f362ffec3d1adbdc400f155514f6af3d2
b95a745fb7e6e33decc64df4828f497272a76206
refs/heads/master
2023-05-24T20:50:59.679000
2022-03-02T15:25:34
2022-03-02T15:25:34
224,664,472
3
1
Apache-2.0
false
2023-05-23T20:10:40
2019-11-28T13:55:59
2021-11-27T13:51:05
2023-05-23T20:10:39
1,213
1
1
4
Java
false
false
package ru.job4j; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import static org.hamcrest.core.Is.is; import static org.junit.Assert.*; public class MainTest { private static final String LN = System.lineSeparator(); @Test public void testMain() { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream def = System.out; System.setOut(new PrintStream(out)); String[] args = new String[0]; Main.main(args); String expect = String.format( "Hello job4j!%s", LN); assertThat(new String(out.toByteArray()), is(expect)); System.setOut(def); } }
UTF-8
Java
715
java
MainTest.java
Java
[]
null
[]
package ru.job4j; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import static org.hamcrest.core.Is.is; import static org.junit.Assert.*; public class MainTest { private static final String LN = System.lineSeparator(); @Test public void testMain() { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream def = System.out; System.setOut(new PrintStream(out)); String[] args = new String[0]; Main.main(args); String expect = String.format( "Hello job4j!%s", LN); assertThat(new String(out.toByteArray()), is(expect)); System.setOut(def); } }
715
0.637762
0.633566
29
23.689655
19.543238
64
false
false
0
0
0
0
0
0
0.586207
false
false
7
40ef27ae8b637af5e5ebe201b93a281bd3ef75bc
17,179,873,674
43b02c909c177f54d89cf1b4679f4ad2a5d8fbf5
/src/main/java/io/squashapp/squashapp/SecurityConfiguration.java
0461c4cb07c0b355a47aeb9ca6ccdb955892d568
[]
no_license
BartekSmalec/squashapp
https://github.com/BartekSmalec/squashapp
e3c333574dbac1f5fa0a89149c083a65ebe9ac8e
afcffced8a8aa4aa52d241569cbca9c0832a0f80
refs/heads/master
2022-04-01T14:51:47.055000
2020-01-14T17:00:22
2020-01-14T17:00:22
233,439,458
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.squashapp.squashapp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired UserDetailsService userDetailService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailService); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() //.antMatchers(HttpMethod.OPTIONS,"/*").permitAll() .antMatchers("/actuator/*").permitAll() .antMatchers("/admin").hasRole("ADMIN") .antMatchers("/user").hasAnyRole("USER", "ADMIN") .antMatchers("/").permitAll() //.anyRequest().authenticated() .and().formLogin() //.loginProcessingUrl("/login") .and().csrf().disable() .logout(); // .invalidateHttpSession(true) // .deleteCookies("JSESSIONID"); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
UTF-8
Java
1,989
java
SecurityConfiguration.java
Java
[]
null
[]
package io.squashapp.squashapp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired UserDetailsService userDetailService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailService); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() //.antMatchers(HttpMethod.OPTIONS,"/*").permitAll() .antMatchers("/actuator/*").permitAll() .antMatchers("/admin").hasRole("ADMIN") .antMatchers("/user").hasAnyRole("USER", "ADMIN") .antMatchers("/").permitAll() //.anyRequest().authenticated() .and().formLogin() //.loginProcessingUrl("/login") .and().csrf().disable() .logout(); // .invalidateHttpSession(true) // .deleteCookies("JSESSIONID"); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
1,989
0.71996
0.71996
50
38.779999
30.320482
107
false
false
0
0
0
0
0
0
0.38
false
false
7
b6b406d79be95f289d1eacbf98fc7bf6182db92d
1,374,389,600,371
758fe47556e9674806a34b4112c8c35a54354fa2
/src/main/java/swtesting/FizzBuzz.java
1c9da8770bfc832f7f89e891b55d5fd3f6273d87
[]
no_license
Baipor/swtesting_swpark
https://github.com/Baipor/swtesting_swpark
dddd723eb56458f4955f7a6a5053870ea3b2a364
31529032bc5f264091fbcee07f7091afcc0090bb
refs/heads/master
2020-12-31T03:55:51.246000
2015-03-31T10:38:15
2015-03-31T10:38:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package swtesting; public class FizzBuzz { public String say(int number) { String result = String.valueOf(number); if (evaluateFizzBuzz(number)) { result = "FizzBuzz"; } else if (evaluateFizz(number)) { result = "Fizz"; } else if (evaluateBuzz(number)) { result = "Buzz"; } return result; } private boolean evaluateFizzBuzz(int number) { return evaluateFizz(number) && evaluateBuzz(number); } private boolean evaluateFizz(int number) { return number % 3 == 0; } private boolean evaluateBuzz(int number) { return number % 5 == 0; } }
UTF-8
Java
679
java
FizzBuzz.java
Java
[]
null
[]
package swtesting; public class FizzBuzz { public String say(int number) { String result = String.valueOf(number); if (evaluateFizzBuzz(number)) { result = "FizzBuzz"; } else if (evaluateFizz(number)) { result = "Fizz"; } else if (evaluateBuzz(number)) { result = "Buzz"; } return result; } private boolean evaluateFizzBuzz(int number) { return evaluateFizz(number) && evaluateBuzz(number); } private boolean evaluateFizz(int number) { return number % 3 == 0; } private boolean evaluateBuzz(int number) { return number % 5 == 0; } }
679
0.569956
0.564065
29
22.413794
18.826828
60
false
false
0
0
0
0
0
0
0.310345
false
false
7
cb7a68358680d9b1205c65b780d0bee2f39d76f8
18,915,035,980,212
2903675ea4faf8f43b23ca6f0f1399107e4e47b4
/npf-blackcat/src/main/java/com/ailk/ecs/esf/service/hessian/ext/EsfHessianProxy.java
40ed20d29e317aeceae2fd3b8ba28a2ce0b71391
[ "Apache-2.0" ]
permissive
bingoohuang/npf-blackcat
https://github.com/bingoohuang/npf-blackcat
b3450cb3e2d322a2cae22c88cd0b7a9252e16359
d52061f08a53bcc707a8b295b8316a86f81cf797
refs/heads/master
2021-01-21T02:00:27.615000
2018-10-19T00:42:02
2018-10-19T00:42:02
50,984,262
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ailk.ecs.esf.service.hessian.ext; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import com.github.bingoohuang.blackcat.javaagent.callback.Blackcat; import org.apache.commons.lang.StringUtils; import com.ailk.ecs.esf.base.exception.BusinessException; import com.ailk.ecs.esf.base.exception.EsfException; import com.ailk.ecs.esf.conf.EsfProperties; import com.caucho.hessian.client.HessianProxy; import com.caucho.hessian.client.HessianProxyFactory; public class EsfHessianProxy extends HessianProxy { protected EsfHessianProxy(HessianProxyFactory factory, URL url) { super(url, factory); } @Override protected void addRequestHeaders(URLConnection conn) { super.addRequestHeaders(conn); HttpURLConnection httpConn = (HttpURLConnection) conn; Blackcat.prepareRPC(httpConn); } /** * Method that allows subclasses to parse response headers such as cookies. * Default implementation is empty. * @param conn */ @Override protected void parseResponseHeaders(URLConnection conn) { HttpURLConnection httpConn = (HttpURLConnection) conn; int code = 500; try { code = httpConn.getResponseCode(); } catch (IOException e) { throw new EsfException("Get Response Code Error", e); } String rcStr = EsfProperties.getProperty("RC_CODES", ""); if (StringUtils.isEmpty(rcStr) && code != 200) { throw new BusinessException("RC_" + code, "HTTP Response Code:" + code + "异常"); } String[] rcs = rcStr.split(","); for (String rc : rcs) { if (rc.equals("" + code)) { throw new BusinessException("RC_" + code, "HTTP Response Code:" + code + "异常"); } } } }
UTF-8
Java
1,888
java
EsfHessianProxy.java
Java
[ { "context": "import java.net.URLConnection;\n\nimport com.github.bingoohuang.blackcat.javaagent.callback.Blackcat;\nimport org.", "end": 192, "score": 0.8231481313705444, "start": 181, "tag": "USERNAME", "value": "bingoohuang" } ]
null
[]
package com.ailk.ecs.esf.service.hessian.ext; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import com.github.bingoohuang.blackcat.javaagent.callback.Blackcat; import org.apache.commons.lang.StringUtils; import com.ailk.ecs.esf.base.exception.BusinessException; import com.ailk.ecs.esf.base.exception.EsfException; import com.ailk.ecs.esf.conf.EsfProperties; import com.caucho.hessian.client.HessianProxy; import com.caucho.hessian.client.HessianProxyFactory; public class EsfHessianProxy extends HessianProxy { protected EsfHessianProxy(HessianProxyFactory factory, URL url) { super(url, factory); } @Override protected void addRequestHeaders(URLConnection conn) { super.addRequestHeaders(conn); HttpURLConnection httpConn = (HttpURLConnection) conn; Blackcat.prepareRPC(httpConn); } /** * Method that allows subclasses to parse response headers such as cookies. * Default implementation is empty. * @param conn */ @Override protected void parseResponseHeaders(URLConnection conn) { HttpURLConnection httpConn = (HttpURLConnection) conn; int code = 500; try { code = httpConn.getResponseCode(); } catch (IOException e) { throw new EsfException("Get Response Code Error", e); } String rcStr = EsfProperties.getProperty("RC_CODES", ""); if (StringUtils.isEmpty(rcStr) && code != 200) { throw new BusinessException("RC_" + code, "HTTP Response Code:" + code + "异常"); } String[] rcs = rcStr.split(","); for (String rc : rcs) { if (rc.equals("" + code)) { throw new BusinessException("RC_" + code, "HTTP Response Code:" + code + "异常"); } } } }
1,888
0.659574
0.656383
60
30.333334
26.049738
95
false
false
0
0
0
0
0
0
0.516667
false
false
7
e3d06d695ecd4db5067d98e104138f288dfe54e0
13,950,053,786,657
5886fd4e9c1dec912fc28bf6b0e71658327c0357
/Projetos Em Java/OperadoresEmJava.java
e0fd8d61cb0d8047d729dd6807a0bfc4c4418ba9
[]
no_license
borin98/Projetos-De-Programa-o-No-Atom
https://github.com/borin98/Projetos-De-Programa-o-No-Atom
4c163f2f1a8d5b78bab35a0a90918315e9ddab7b
cc3de39c191e614110d40d1a746e3efbcacbc8ec
refs/heads/master
2021-01-25T14:04:01.921000
2018-03-03T01:06:43
2018-03-03T01:06:43
123,646,447
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class OperadoresEmJava { public static void main ( String [ ] args ) { int numero1 = 10 ; int numero2 = 20 ; System.out.println ( "A Soma de "+numero1+ " com "+numero2+ " sera de : " +( numero1+numero2 ) ); } }
UTF-8
Java
242
java
OperadoresEmJava.java
Java
[]
null
[]
public class OperadoresEmJava { public static void main ( String [ ] args ) { int numero1 = 10 ; int numero2 = 20 ; System.out.println ( "A Soma de "+numero1+ " com "+numero2+ " sera de : " +( numero1+numero2 ) ); } }
242
0.582645
0.541322
14
16.285715
27.298426
101
false
false
0
0
0
0
0
0
0.214286
false
false
7
dd59e1214201c3dba9c3ff4ecd620df6034adba1
1,271,310,332,975
76db95557c8834ad1f8494baa350f175cdae3bcf
/PluginMGR/src/dev/nova/PluginMGR/MainClass.java
8c7553b94a4b6e59c321c841c3c1b0def8e1b9ae
[]
no_license
novastosha/Projects
https://github.com/novastosha/Projects
98bdf16c85a3f9ff784bb87185511f233ea6013e
b161df2bffd9331e8537fb8ee5bb8befc60555d1
refs/heads/master
2022-04-25T08:02:12.516000
2020-04-16T15:08:49
2020-04-16T15:08:49
254,607,688
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dev.nova.PluginMGR; import dev.nova.PluginMGR.commands.PluginMGR_CMD; import dev.nova.PluginMGR.events.onCommand; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; public class MainClass extends JavaPlugin { private PluginMGR_CMD pluginMGRCmd; @Override public void onEnable(){ pluginMGRCmd = new PluginMGR_CMD(); getCommand(pluginMGRCmd.cmd).setExecutor(pluginMGRCmd); Bukkit.getServer().getPluginManager().registerEvents(new onCommand(), this); } }
UTF-8
Java
541
java
MainClass.java
Java
[]
null
[]
package dev.nova.PluginMGR; import dev.nova.PluginMGR.commands.PluginMGR_CMD; import dev.nova.PluginMGR.events.onCommand; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; public class MainClass extends JavaPlugin { private PluginMGR_CMD pluginMGRCmd; @Override public void onEnable(){ pluginMGRCmd = new PluginMGR_CMD(); getCommand(pluginMGRCmd.cmd).setExecutor(pluginMGRCmd); Bukkit.getServer().getPluginManager().registerEvents(new onCommand(), this); } }
541
0.71719
0.71719
19
26.473684
24.210411
84
false
false
0
0
0
0
0
0
0.526316
false
false
7
8154b08de10f8d3c51307d5b1e711fc840fc7827
27,230,092,676,627
96d817e3a70d7e9de2adffb7e87d492668c61f4e
/datavault-broker/src/test/java/org/datavaultplatform/broker/services/BaseUserKeyPairServiceOpenSSHTest.java
3e47eebdc3763338316c045bfa58734076f9911a
[ "MIT" ]
permissive
DataVault/datavault
https://github.com/DataVault/datavault
8b97c49ab714486cce2ec8295e7951ef95006e97
e5ea8363f5e945beb77039de9239e365322f79cd
refs/heads/master
2023-08-31T15:55:42.044000
2023-03-07T08:10:19
2023-03-07T08:10:19
36,649,267
25
19
MIT
false
2023-09-13T15:12:06
2015-06-01T08:57:03
2023-08-21T19:29:51
2023-09-13T15:12:05
116,057
20
17
38
Java
false
false
package org.datavaultplatform.broker.services; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import java.nio.charset.StandardCharsets; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.datavaultplatform.broker.services.UserKeyPairService.KeyPairInfo; import org.datavaultplatform.common.storage.impl.JSchLogger; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.wait.strategy.Wait; import org.testcontainers.utility.DockerImageName; /** * This test generates a key pair and checks that the keypair is valid by ... * using the private key with Jsch and public key with OPENSSH to establish ssh connection */ @Slf4j public abstract class BaseUserKeyPairServiceOpenSSHTest extends BaseUserKeyPairServiceTest { private static final String TEST_USER = "testuser"; private GenericContainer<?> toContainer; private static final String ENV_USER_NAME = "USER_NAME"; private static final String ENV_PUBLIC_KEY = "PUBLIC_KEY"; /** * Tests that the key pair is valid by * using keypair to perform scp between testcontainers */ @ParameterizedTest @MethodSource("provideUserKeyPairService") @Override void testKeyPair(UserKeyPairService service) { try { KeyPairInfo info = service.generateNewKeyPair(); validateKeyPair(info.getPublicKey(), info.getPrivateKey().getBytes(StandardCharsets.UTF_8)); assertTrue(isSuccessExpected()); } catch (Exception ex) { log.error("problem using ssh [{}]", getDockerImageForOpenSSH(), ex); assertFalse(isSuccessExpected()); } } @ParameterizedTest @MethodSource("provideUserKeyPairService") void testKeyPairIsInValid(UserKeyPairService service) { KeyPairInfo info = service.generateNewKeyPair(); byte[] badBytes = info.getPrivateKey().getBytes(StandardCharsets.UTF_8); //just by changing 1 byte of private key - we should get an error badBytes[0] = (byte)166; JSchException ex = assertThrows(JSchException.class, () -> validateKeyPair(info.getPublicKey(), badBytes )); assertTrue(ex.getMessage().startsWith("invalid privatekey")); } @SneakyThrows private void validateKeyPair(String publicKey, byte[] privateKeyBytes) { initContainers(publicKey); JSch.setLogger(JSchLogger.getInstance()); JSch jSch = new JSch(); Session session = jSch.getSession(TEST_USER, this.toContainer.getHost(), this.toContainer.getMappedPort(2222)); jSch.addIdentity(TEST_USER, privateKeyBytes, null, TEST_PASSPHRASE.getBytes()); java.util.Properties properties = new java.util.Properties(); properties.put(STRICT_HOST_KEY_CHECKING, NO); session.setConfig(properties); session.connect(); log.info("Connected!"); } void initContainers(String publicKey) { //we put the publicKey into the TO container at startup - so ssh daemon will trust the private key later on toContainer = new GenericContainer<>(getDockerImageForOpenSSH()) .withEnv(ENV_USER_NAME, TEST_USER) .withEnv(ENV_PUBLIC_KEY, publicKey) //this causes the public key to be added to /config/.ssh/authorized_keys .withExposedPorts(2222) .waitingFor(Wait.forListeningPort()); toContainer.start(); } @AfterEach void tearDown() { if(this.toContainer != null){ this.toContainer.stop(); } } public abstract DockerImageName getDockerImageForOpenSSH(); public abstract boolean isSuccessExpected(); }
UTF-8
Java
3,830
java
BaseUserKeyPairServiceOpenSSHTest.java
Java
[ { "context": "est {\n\n private static final String TEST_USER = \"testuser\";\n private GenericContainer<?> toContainer;\n\n p", "end": 1209, "score": 0.9983891248703003, "start": 1201, "tag": "USERNAME", "value": "testuser" } ]
null
[]
package org.datavaultplatform.broker.services; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import java.nio.charset.StandardCharsets; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.datavaultplatform.broker.services.UserKeyPairService.KeyPairInfo; import org.datavaultplatform.common.storage.impl.JSchLogger; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.wait.strategy.Wait; import org.testcontainers.utility.DockerImageName; /** * This test generates a key pair and checks that the keypair is valid by ... * using the private key with Jsch and public key with OPENSSH to establish ssh connection */ @Slf4j public abstract class BaseUserKeyPairServiceOpenSSHTest extends BaseUserKeyPairServiceTest { private static final String TEST_USER = "testuser"; private GenericContainer<?> toContainer; private static final String ENV_USER_NAME = "USER_NAME"; private static final String ENV_PUBLIC_KEY = "PUBLIC_KEY"; /** * Tests that the key pair is valid by * using keypair to perform scp between testcontainers */ @ParameterizedTest @MethodSource("provideUserKeyPairService") @Override void testKeyPair(UserKeyPairService service) { try { KeyPairInfo info = service.generateNewKeyPair(); validateKeyPair(info.getPublicKey(), info.getPrivateKey().getBytes(StandardCharsets.UTF_8)); assertTrue(isSuccessExpected()); } catch (Exception ex) { log.error("problem using ssh [{}]", getDockerImageForOpenSSH(), ex); assertFalse(isSuccessExpected()); } } @ParameterizedTest @MethodSource("provideUserKeyPairService") void testKeyPairIsInValid(UserKeyPairService service) { KeyPairInfo info = service.generateNewKeyPair(); byte[] badBytes = info.getPrivateKey().getBytes(StandardCharsets.UTF_8); //just by changing 1 byte of private key - we should get an error badBytes[0] = (byte)166; JSchException ex = assertThrows(JSchException.class, () -> validateKeyPair(info.getPublicKey(), badBytes )); assertTrue(ex.getMessage().startsWith("invalid privatekey")); } @SneakyThrows private void validateKeyPair(String publicKey, byte[] privateKeyBytes) { initContainers(publicKey); JSch.setLogger(JSchLogger.getInstance()); JSch jSch = new JSch(); Session session = jSch.getSession(TEST_USER, this.toContainer.getHost(), this.toContainer.getMappedPort(2222)); jSch.addIdentity(TEST_USER, privateKeyBytes, null, TEST_PASSPHRASE.getBytes()); java.util.Properties properties = new java.util.Properties(); properties.put(STRICT_HOST_KEY_CHECKING, NO); session.setConfig(properties); session.connect(); log.info("Connected!"); } void initContainers(String publicKey) { //we put the publicKey into the TO container at startup - so ssh daemon will trust the private key later on toContainer = new GenericContainer<>(getDockerImageForOpenSSH()) .withEnv(ENV_USER_NAME, TEST_USER) .withEnv(ENV_PUBLIC_KEY, publicKey) //this causes the public key to be added to /config/.ssh/authorized_keys .withExposedPorts(2222) .waitingFor(Wait.forListeningPort()); toContainer.start(); } @AfterEach void tearDown() { if(this.toContainer != null){ this.toContainer.stop(); } } public abstract DockerImageName getDockerImageForOpenSSH(); public abstract boolean isSuccessExpected(); }
3,830
0.753003
0.748303
104
35.826923
30.490049
116
false
false
0
0
0
0
0
0
0.586538
false
false
7
3a9c3b63f0a677a75004f0740764c9a4fe054e61
9,113,920,639,271
8d0037cb394de7c973e81a5f0f597b81f452e4ec
/state-flow-faces-impl/src/main/java/org/ssoft/faces/impl/state/TimerEventProducerImpl.java
941f91c7a293ee8088be7f9702cc2774f3d78982
[ "MIT" ]
permissive
wklaczynski/state-flow-faces
https://github.com/wklaczynski/state-flow-faces
985998b94eeed52fb96ae8b14dd912d8dc2ba726
9fde6b2fc1a68374c87744355219684beadb8b9f
refs/heads/master
2022-11-27T21:40:02.127000
2021-06-16T23:21:13
2021-06-16T23:21:13
125,044,501
4
2
MIT
false
2022-11-16T09:30:11
2018-03-13T11:58:08
2021-06-16T23:21:24
2022-11-16T09:30:08
216,672
2
1
2
Java
false
false
/* * Copyright 2018 Waldemar Kłaczyński. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ssoft.faces.impl.state; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import javax.faces.application.Application; import javax.faces.component.UIComponent; import javax.faces.component.UIOutput; import javax.faces.context.FacesContext; import javax.faces.context.PartialViewContext; import static org.ssoft.faces.impl.state.StateFlowImplConstants.STATE_FLOW_DISPATCH_TASK; import javax.faces.state.task.DelayedEventTask; import javax.faces.state.task.TimerEventProducer; import org.ssoft.faces.impl.state.renderer.StateFlowScriptRenderer; /** * * @author Waldemar Kłaczyński */ public class TimerEventProducerImpl extends TimerEventProducer { @Override public void encodeBegin(List<DelayedEventTask> taskList) { FacesContext context = FacesContext.getCurrentInstance(); Map<Object, Object> attrs = context.getAttributes(); if (!taskList.isEmpty()) { DelayedEventTask curTask = (DelayedEventTask) attrs.get(STATE_FLOW_DISPATCH_TASK); taskList = new ArrayList<>(taskList); Collections.sort(taskList, (o1, o2) -> { return (int) (o1.getTime() - o2.getTime()); }); DelayedEventTask newTask = taskList.get(0); if (curTask == null) { curTask = newTask; } else if (curTask.getTime() > newTask.getTime()) { curTask = newTask; } attrs.put(STATE_FLOW_DISPATCH_TASK, curTask); } } @Override public void encodeEnd() { FacesContext context = FacesContext.getCurrentInstance(); Map<Object, Object> attrs = context.getAttributes(); PartialViewContext partial = context.getPartialViewContext(); DelayedEventTask curTask = (DelayedEventTask) attrs.get(STATE_FLOW_DISPATCH_TASK); if (curTask != null && !partial.isAjaxRequest()) { Application application = context.getApplication(); UIComponent componentResource = application.createComponent(UIOutput.COMPONENT_TYPE); componentResource.setRendererType(StateFlowScriptRenderer.RENDERER_TYPE); componentResource.getAttributes().put("target", "head"); componentResource.setId("stateFlowDispatcher"); componentResource.setRendered(true); context.getViewRoot().addComponentResource(context, componentResource, "head"); } } }
UTF-8
Java
3,087
java
TimerEventProducerImpl.java
Java
[ { "context": "/*\n * Copyright 2018 Waldemar Kłaczyński.\n *\n * Licensed under the Apache License, Version", "end": 40, "score": 0.9998629689216614, "start": 21, "tag": "NAME", "value": "Waldemar Kłaczyński" }, { "context": "nderer.StateFlowScriptRenderer;\n\n/**\n *\n * @author Waldemar Kłaczyński\n */\npublic class TimerEventProducerImpl extends T", "end": 1252, "score": 0.9998648762702942, "start": 1233, "tag": "NAME", "value": "Waldemar Kłaczyński" } ]
null
[]
/* * Copyright 2018 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ssoft.faces.impl.state; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import javax.faces.application.Application; import javax.faces.component.UIComponent; import javax.faces.component.UIOutput; import javax.faces.context.FacesContext; import javax.faces.context.PartialViewContext; import static org.ssoft.faces.impl.state.StateFlowImplConstants.STATE_FLOW_DISPATCH_TASK; import javax.faces.state.task.DelayedEventTask; import javax.faces.state.task.TimerEventProducer; import org.ssoft.faces.impl.state.renderer.StateFlowScriptRenderer; /** * * @author <NAME> */ public class TimerEventProducerImpl extends TimerEventProducer { @Override public void encodeBegin(List<DelayedEventTask> taskList) { FacesContext context = FacesContext.getCurrentInstance(); Map<Object, Object> attrs = context.getAttributes(); if (!taskList.isEmpty()) { DelayedEventTask curTask = (DelayedEventTask) attrs.get(STATE_FLOW_DISPATCH_TASK); taskList = new ArrayList<>(taskList); Collections.sort(taskList, (o1, o2) -> { return (int) (o1.getTime() - o2.getTime()); }); DelayedEventTask newTask = taskList.get(0); if (curTask == null) { curTask = newTask; } else if (curTask.getTime() > newTask.getTime()) { curTask = newTask; } attrs.put(STATE_FLOW_DISPATCH_TASK, curTask); } } @Override public void encodeEnd() { FacesContext context = FacesContext.getCurrentInstance(); Map<Object, Object> attrs = context.getAttributes(); PartialViewContext partial = context.getPartialViewContext(); DelayedEventTask curTask = (DelayedEventTask) attrs.get(STATE_FLOW_DISPATCH_TASK); if (curTask != null && !partial.isAjaxRequest()) { Application application = context.getApplication(); UIComponent componentResource = application.createComponent(UIOutput.COMPONENT_TYPE); componentResource.setRendererType(StateFlowScriptRenderer.RENDERER_TYPE); componentResource.getAttributes().put("target", "head"); componentResource.setId("stateFlowDispatcher"); componentResource.setRendered(true); context.getViewRoot().addComponentResource(context, componentResource, "head"); } } }
3,057
0.694129
0.689912
80
37.537498
28.837017
97
false
false
0
0
0
0
0
0
0.6
false
false
7
bf93e5085ffc5a0baf6519a50d0068d91388fa36
25,177,098,297,013
af43392b7083f17bdf9683e012ea6f5d104f0ed5
/src/Mail.java
a574cb2efbde71d46e471f8dee724c688b326ec9
[]
no_license
UmayD/CS102-Lab-4
https://github.com/UmayD/CS102-Lab-4
6abd82c8e0f66122783451233a96026f1537cfd9
0d076d5fa97968acbdf6954d8ea4c6aa17babf94
refs/heads/master
2022-12-05T06:51:23.217000
2020-08-20T14:21:34
2020-08-20T14:21:34
289,023,848
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 Umay */ public class Mail extends Delivery { String content; public Mail(String content, Customer sender, Customer receiver, int packageNo){ super(sender, receiver, packageNo); this.content = content; } @Override public double getWeight(){ return 0.1; } @Override public String toString(){ String result; result = "Mail: " + "Content: " + content + " Weight: " + getWeight() + " Sender: " + sender + " Receiver: " + receiver; return result; } }
UTF-8
Java
758
java
Mail.java
Java
[ { "context": "the template in the editor.\n */\n\n/**\n *\n * @author Umay\n */\npublic class Mail extends Delivery {\n Stri", "end": 208, "score": 0.9844925403594971, "start": 204, "tag": "NAME", "value": "Umay" } ]
null
[]
/* * 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 Umay */ public class Mail extends Delivery { String content; public Mail(String content, Customer sender, Customer receiver, int packageNo){ super(sender, receiver, packageNo); this.content = content; } @Override public double getWeight(){ return 0.1; } @Override public String toString(){ String result; result = "Mail: " + "Content: " + content + " Weight: " + getWeight() + " Sender: " + sender + " Receiver: " + receiver; return result; } }
758
0.602902
0.600264
31
23.451612
29.112505
129
false
false
0
0
0
0
0
0
0.483871
false
false
7
062e7cd2e17949fde68a61abd2c863baaf587eb5
20,332,375,245,549
0db76a0e79a5302934e6879beda748f9d5a63615
/src/com/sasbury/sting/types/StingNull.java
0fa80aa81696fd3e4f4298f680258142301618b2
[ "MIT" ]
permissive
sasbury/sting
https://github.com/sasbury/sting
79f957bf7c4ade84d12f7f62389f9c199933f9b8
65cdf247f7c0faa8ea529e4b7a5381b953db383d
refs/heads/master
2021-01-23T12:17:57.916000
2013-04-29T03:03:09
2013-04-29T03:03:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sasbury.sting.types; import com.sasbury.sting.*; public class StingNull implements StingData,StingConstants { public boolean equals(Object obj) { return obj instanceof StingNull; } public int hashCode() { return NULL.hashCode(); } public StingData copy() { return new StingNull(); } public String toString() { return NULL; } }
UTF-8
Java
450
java
StingNull.java
Java
[]
null
[]
package com.sasbury.sting.types; import com.sasbury.sting.*; public class StingNull implements StingData,StingConstants { public boolean equals(Object obj) { return obj instanceof StingNull; } public int hashCode() { return NULL.hashCode(); } public StingData copy() { return new StingNull(); } public String toString() { return NULL; } }
450
0.575556
0.575556
26
15.307693
15.999445
58
false
false
0
0
0
0
0
0
0.269231
false
false
7
7356dc8f9c63473c553806b69ab29d71ceb5edb3
4,922,032,558,087
6d0d7711275b9049a00f7194a71f0d0ea1abe2c4
/Inverse/src/com/raj/engine/Delete.java
1d0b4515ad8c9949e7a226d3c561ac7973ad03e3
[]
no_license
hiaditya04/hibernateTutorial
https://github.com/hiaditya04/hibernateTutorial
8333ab24deb5609ee2d3eaecf96c39533b94e49d
a12ffe6f6c8ea0001a98aed8bbd78ea0f5132db1
refs/heads/master
2020-03-23T23:40:01.862000
2018-07-25T05:36:27
2018-07-25T05:36:27
73,454,858
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.raj.engine; import java.util.HashSet; import java.util.Set; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.raj.pojo.Parent; public class Delete { public static void main(String[] args) { System.out.println(" ....... ENGINE START ............"); System.out.println(" ....... ONE TO MANY DELETE DEMO ............\n"); Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml"); SessionFactory factory = cfg.buildSessionFactory(); Session session = factory.openSession(); Parent parentObj= (Parent) session.get(Parent.class, new Integer(1)); Transaction transaction=session.beginTransaction(); session.delete(parentObj); transaction.commit(); System.out.println("\n....... DATA DELETED SUCCESSFULLY .........."); session.close(); factory.close(); System.out.println("\n....... ENGINE STOP .........."); } }
UTF-8
Java
1,195
java
Delete.java
Java
[]
null
[]
package com.raj.engine; import java.util.HashSet; import java.util.Set; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.raj.pojo.Parent; public class Delete { public static void main(String[] args) { System.out.println(" ....... ENGINE START ............"); System.out.println(" ....... ONE TO MANY DELETE DEMO ............\n"); Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml"); SessionFactory factory = cfg.buildSessionFactory(); Session session = factory.openSession(); Parent parentObj= (Parent) session.get(Parent.class, new Integer(1)); Transaction transaction=session.beginTransaction(); session.delete(parentObj); transaction.commit(); System.out.println("\n....... DATA DELETED SUCCESSFULLY .........."); session.close(); factory.close(); System.out.println("\n....... ENGINE STOP .........."); } }
1,195
0.561506
0.560669
38
29.447369
24.979673
85
false
false
0
0
0
0
0
0
0.657895
false
false
7
3e7b0a1312b815dc24af3bf428d7270af24ec7a2
10,694,468,615,137
ad2ac9286e45813b2fe2c11346f3bcdcdef6f6d9
/4.JavaCollections/src/com/javarush/task/task35/task3501/GenericStatic.java
e3bb1ef97eb4434a929ce4ee3d472e5cf4841bf2
[]
no_license
Lupachik/JavaRushTasks
https://github.com/Lupachik/JavaRushTasks
a41da0efd77ab9f961af16817ec059f89ea17f73
950ed9d0d94d7f11e30c526ef2d34a6d610fe3dd
refs/heads/master
2020-09-09T01:57:30.710000
2019-12-13T05:25:42
2019-12-13T05:25:42
221,309,528
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.javarush.task.task35.task3501; public class GenericStatic { /* В треугольных скобках при объявлении метода мы перечисляем типы, которые будем использовать. <T> говорит о том, что все T в методе будут одного типа. При этом, если <T> было объявлено до этого на уровне класса, то мы перекрываем этот тип другим, локальным. Может быть конструкция "public static <T> void methodName" или "public <T, R> T methodName". */ public static <T> T someStaticMethod(T genericObject) { System.out.println(genericObject); return genericObject; } }
UTF-8
Java
824
java
GenericStatic.java
Java
[]
null
[]
package com.javarush.task.task35.task3501; public class GenericStatic { /* В треугольных скобках при объявлении метода мы перечисляем типы, которые будем использовать. <T> говорит о том, что все T в методе будут одного типа. При этом, если <T> было объявлено до этого на уровне класса, то мы перекрываем этот тип другим, локальным. Может быть конструкция "public static <T> void methodName" или "public <T, R> T methodName". */ public static <T> T someStaticMethod(T genericObject) { System.out.println(genericObject); return genericObject; } }
824
0.705491
0.695507
15
39.066666
36.621426
102
false
false
0
0
0
0
0
0
0.6
false
false
7
b821995986cce553590d9ff86a3787f20e66458d
28,664,611,799,978
a550ca5b5d42e3b9cdea3b4548e2c8c51c3714a7
/v1/jogoteste/src/jogoteste/Entidade.java
7ffff3104ef8f34eb5eec87a0c8265496d5a520d
[]
no_license
joao-2001/jogo2021
https://github.com/joao-2001/jogo2021
2740ae4645e7af292a1f469b82fd15e73ecc3224
586e691340b2a9a7aa5a9554d5ccdefd6649f2fe
refs/heads/main
2023-05-05T09:54:15.202000
2021-05-20T22:53:26
2021-05-20T22:53:26
360,364,564
0
0
null
false
2021-05-21T23:50:07
2021-04-22T02:09:32
2021-05-20T22:53:28
2021-05-21T23:50:07
143
0
0
1
Java
false
false
package jogoteste; import java.awt.Graphics; import java.awt.Rectangle; public abstract class Entidade { protected float altura; protected float largura; protected float posicaoX, posicaoY; protected float velocidadeX; protected float velocidadeY; GerenciadorDeEntidades gerenciador; protected ID id; public Entidade(float posx, float posy, float alt, float larg,GerenciadorDeEntidades gerenciador, ID id) { posicaoX = posx; posicaoY = posy; altura = alt; largura = larg; this.id = id; velocidadeX = 0; velocidadeY = 0; this.gerenciador = gerenciador; } public void setPosX(float x) { posicaoX = x; } public void setPosY(float y) { posicaoY = y; } public void setVelX(float vx) { velocidadeX = vx; } public void setVelY(float vy) { velocidadeY = vy; } public void setID(ID id) { this.id = id; } public float getPosX() { return posicaoX; } public float getPosY() { return posicaoY; } public float getVelX() { return velocidadeX; } public float getVelY() { return velocidadeY; } public ID getID() { return id; } public Rectangle delimitar() { return new Rectangle((int)posicaoX, (int)posicaoY, (int)altura, (int)largura); } public abstract void tick(); public abstract void render(Graphics g); }
UTF-8
Java
1,347
java
Entidade.java
Java
[]
null
[]
package jogoteste; import java.awt.Graphics; import java.awt.Rectangle; public abstract class Entidade { protected float altura; protected float largura; protected float posicaoX, posicaoY; protected float velocidadeX; protected float velocidadeY; GerenciadorDeEntidades gerenciador; protected ID id; public Entidade(float posx, float posy, float alt, float larg,GerenciadorDeEntidades gerenciador, ID id) { posicaoX = posx; posicaoY = posy; altura = alt; largura = larg; this.id = id; velocidadeX = 0; velocidadeY = 0; this.gerenciador = gerenciador; } public void setPosX(float x) { posicaoX = x; } public void setPosY(float y) { posicaoY = y; } public void setVelX(float vx) { velocidadeX = vx; } public void setVelY(float vy) { velocidadeY = vy; } public void setID(ID id) { this.id = id; } public float getPosX() { return posicaoX; } public float getPosY() { return posicaoY; } public float getVelX() { return velocidadeX; } public float getVelY() { return velocidadeY; } public ID getID() { return id; } public Rectangle delimitar() { return new Rectangle((int)posicaoX, (int)posicaoY, (int)altura, (int)largura); } public abstract void tick(); public abstract void render(Graphics g); }
1,347
0.667409
0.665924
66
18.40909
17.934204
107
false
false
0
0
0
0
0
0
1.787879
false
false
7
74df92e367f8d1727bf134d569a77e8f0fdb407e
27,358,941,701,094
f105b5501525940787aa2d0f62a46ef6e0fe30ab
/src/main/java/com/baidubce/services/route/model/CreateRouteRequest.java
d0807c360d169b268db3d9b3075a33454b60fa49
[ "Apache-2.0" ]
permissive
baidubce/bce-sdk-java
https://github.com/baidubce/bce-sdk-java
f0f203f5088cc678d3397e6faae7f2b61d71c916
716eb280dc7d78dbd2d8372ed1a9a5f682d15596
refs/heads/master
2023-07-09T18:54:32.923000
2021-05-11T03:23:10
2021-05-11T03:23:10
27,588,623
64
76
Apache-2.0
false
2022-11-16T03:46:46
2014-12-05T11:29:48
2022-10-17T05:37:50
2022-11-16T03:46:43
2,296
55
61
15
Java
false
false
package com.baidubce.services.route.model; import com.baidubce.auth.BceCredentials; import com.baidubce.model.AbstractBceRequest; /** * Created by zhangjing60 on 17/8/2. */ public class CreateRouteRequest extends AbstractBceRequest { /** * The API version number */ private String version; /** * An ASCII string whose length is less than 64. * * The request will be idempotent if clientToken is provided. * If the clientToken is not specified by the user, a random String generated by default algorithm will be used. * See more detail at * */ private String clientToken; /** * The id of the route table */ private String routeTableId; /** * The source address which can be 0.0.0.0/0, otherwise, the traffic source of the routing table must belong * to a subnet under the VPC. When the source address is user-defined, the customer segment needs to be within * the existing subnet segment */ private String sourceAddress; /** * The destination address which can be 0.0.0.0/0, otherwise, the destination address cannot be overlapped with * this VPC's cidr (except for the destination segment or the VPC's CIDR is 0.0.0.0/0) */ private String destinationAddress; /** * next hop id * when the nexthopType is "defaultGateway",this field can be empty */ private String nexthopId; /** * route type * The Bcc type is "custom"; * the VPN type is "VPN"; * the NAT type is "NAT"; * the local gateway type is "defaultGateway"" */ private String nexthopType; /** * The option param to describe the route table */ private String description; public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getClientToken() { return clientToken; } public void setClientToken(String clientToken) { this.clientToken = clientToken; } public String getSourceAddress() { return sourceAddress; } public void setSourceAddress(String sourceAddress) { this.sourceAddress = sourceAddress; } public String getDestinationAddress() { return destinationAddress; } public void setDestinationAddress(String destinationAddress) { this.destinationAddress = destinationAddress; } public String getNexthopId() { return nexthopId; } public void setNexthopId(String nexthopId) { this.nexthopId = nexthopId; } public String getNexthopType() { return nexthopType; } public void setNexthopType(String nexthopType) { this.nexthopType = nexthopType; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getRouteTableId() { return routeTableId; } public void setRouteTableId(String routeTableId) { this.routeTableId = routeTableId; } public CreateRouteRequest withVersion(String version) { this.version = version; return this; } /** * Configure optional client token for the request. The request will be idempotent if client token is provided. * If the clientToken is not specified by the user, a random String generated by default algorithm will be used. * * @param clientToken An ASCII string whose length is less than 64. * See more detail at * * @return CreateSubnetRequest with specific clientToken */ public CreateRouteRequest withClientToken(String clientToken) { this.clientToken = clientToken; return this; } /** * configure route table id for the request * @param routeTableId the id of the route table * @return CreateRouteRequest with routeTableId */ public CreateRouteRequest withRouteTableId(String routeTableId) { this.routeTableId = routeTableId; return this; } /** * configure source address for the request * @param sourceAddress the source address * @return CreateRouteRequest with source address */ public CreateRouteRequest withSourceAddress(String sourceAddress) { this.sourceAddress = sourceAddress; return this; } /** * configure destination address for the request * @param destinationAddress the destination address * @return CreateRouteRequest with destination address */ public CreateRouteRequest withDestinationAddress(String destinationAddress) { this.destinationAddress = destinationAddress; return this; } /** * configure next hop id for the request * @param nexthopId the next hop id * @return CreateRouteRequest with the nexthopId */ public CreateRouteRequest withNextHopId(String nexthopId) { this.nexthopId = nexthopId; return this; } /** * configure next hop type for the request * @param nexthopType the route type: BCC-"custom", VPN-"vpn", NAT-"nat" * @return CreateRouteRequest with the nexthopType */ public CreateRouteRequest withNextHopType(String nexthopType) { this.nexthopType = nexthopType; return this; } /** * configure description for the request * @param description the description for the route table * @return CreateRouteRequest with the description */ public CreateRouteRequest withDescription(String description) { this.description = description; return this; } /** * Configure request credential for the request. * * @param credentials a valid instance of BceCredentials. * @return CreateRouteRequest with credentials. */ @Override public CreateRouteRequest withRequestCredentials(BceCredentials credentials) { return null; } }
UTF-8
Java
6,071
java
CreateRouteRequest.java
Java
[ { "context": "dubce.model.AbstractBceRequest;\n\n/**\n * Created by zhangjing60 on 17/8/2.\n */\n\n\npublic class CreateRouteRequest ", "end": 161, "score": 0.9996258616447449, "start": 150, "tag": "USERNAME", "value": "zhangjing60" }, { "context": "\n\n /**\n * The source address which can be 0.0.0.0/0, otherwise, the traffic source of the routing t", "end": 778, "score": 0.701500654220581, "start": 773, "tag": "IP_ADDRESS", "value": "0.0.0" }, { "context": " /**\n * The destination address which can be 0.0.0.0/0, otherwise, the destination address cannot", "end": 1092, "score": 0.5615409016609192, "start": 1092, "tag": "IP_ADDRESS", "value": "" }, { "context": "**\n * The destination address which can be 0.0.0.0/0, otherwise, the destination address cannot b", "end": 1094, "score": 0.5768444538116455, "start": 1094, "tag": "IP_ADDRESS", "value": "" }, { "context": "\n * The destination address which can be 0.0.0.0/0, otherwise, the destination address cannot be ", "end": 1096, "score": 0.6144109964370728, "start": 1096, "tag": "IP_ADDRESS", "value": "" } ]
null
[]
package com.baidubce.services.route.model; import com.baidubce.auth.BceCredentials; import com.baidubce.model.AbstractBceRequest; /** * Created by zhangjing60 on 17/8/2. */ public class CreateRouteRequest extends AbstractBceRequest { /** * The API version number */ private String version; /** * An ASCII string whose length is less than 64. * * The request will be idempotent if clientToken is provided. * If the clientToken is not specified by the user, a random String generated by default algorithm will be used. * See more detail at * */ private String clientToken; /** * The id of the route table */ private String routeTableId; /** * The source address which can be 0.0.0.0/0, otherwise, the traffic source of the routing table must belong * to a subnet under the VPC. When the source address is user-defined, the customer segment needs to be within * the existing subnet segment */ private String sourceAddress; /** * The destination address which can be 0.0.0.0/0, otherwise, the destination address cannot be overlapped with * this VPC's cidr (except for the destination segment or the VPC's CIDR is 0.0.0.0/0) */ private String destinationAddress; /** * next hop id * when the nexthopType is "defaultGateway",this field can be empty */ private String nexthopId; /** * route type * The Bcc type is "custom"; * the VPN type is "VPN"; * the NAT type is "NAT"; * the local gateway type is "defaultGateway"" */ private String nexthopType; /** * The option param to describe the route table */ private String description; public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getClientToken() { return clientToken; } public void setClientToken(String clientToken) { this.clientToken = clientToken; } public String getSourceAddress() { return sourceAddress; } public void setSourceAddress(String sourceAddress) { this.sourceAddress = sourceAddress; } public String getDestinationAddress() { return destinationAddress; } public void setDestinationAddress(String destinationAddress) { this.destinationAddress = destinationAddress; } public String getNexthopId() { return nexthopId; } public void setNexthopId(String nexthopId) { this.nexthopId = nexthopId; } public String getNexthopType() { return nexthopType; } public void setNexthopType(String nexthopType) { this.nexthopType = nexthopType; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getRouteTableId() { return routeTableId; } public void setRouteTableId(String routeTableId) { this.routeTableId = routeTableId; } public CreateRouteRequest withVersion(String version) { this.version = version; return this; } /** * Configure optional client token for the request. The request will be idempotent if client token is provided. * If the clientToken is not specified by the user, a random String generated by default algorithm will be used. * * @param clientToken An ASCII string whose length is less than 64. * See more detail at * * @return CreateSubnetRequest with specific clientToken */ public CreateRouteRequest withClientToken(String clientToken) { this.clientToken = clientToken; return this; } /** * configure route table id for the request * @param routeTableId the id of the route table * @return CreateRouteRequest with routeTableId */ public CreateRouteRequest withRouteTableId(String routeTableId) { this.routeTableId = routeTableId; return this; } /** * configure source address for the request * @param sourceAddress the source address * @return CreateRouteRequest with source address */ public CreateRouteRequest withSourceAddress(String sourceAddress) { this.sourceAddress = sourceAddress; return this; } /** * configure destination address for the request * @param destinationAddress the destination address * @return CreateRouteRequest with destination address */ public CreateRouteRequest withDestinationAddress(String destinationAddress) { this.destinationAddress = destinationAddress; return this; } /** * configure next hop id for the request * @param nexthopId the next hop id * @return CreateRouteRequest with the nexthopId */ public CreateRouteRequest withNextHopId(String nexthopId) { this.nexthopId = nexthopId; return this; } /** * configure next hop type for the request * @param nexthopType the route type: BCC-"custom", VPN-"vpn", NAT-"nat" * @return CreateRouteRequest with the nexthopType */ public CreateRouteRequest withNextHopType(String nexthopType) { this.nexthopType = nexthopType; return this; } /** * configure description for the request * @param description the description for the route table * @return CreateRouteRequest with the description */ public CreateRouteRequest withDescription(String description) { this.description = description; return this; } /** * Configure request credential for the request. * * @param credentials a valid instance of BceCredentials. * @return CreateRouteRequest with credentials. */ @Override public CreateRouteRequest withRequestCredentials(BceCredentials credentials) { return null; } }
6,071
0.659694
0.655576
227
25.744493
26.908817
116
false
false
0
0
0
0
0
0
0.251101
false
false
7
3a98fded5248f2170422c97465b3228dd5734e84
1,554,778,199,712
3206a895acc6cef57a96e750fc01fa733be7fdb4
/src/java/com/hzjava/monitorcenter/service/SysabnormalObjectTypeService.java
d9a97eaf3825f51c8c397afa0b645d69343cab4c
[]
no_license
Yanwei-Tim/cms
https://github.com/Yanwei-Tim/cms
9b910e4fefd4e0bfa5c112ee05c03057514ca553
f77ca5dcbc5fa4fb28844d384886b67f4f5caa01
refs/heads/master
2021-01-20T05:08:54.975000
2016-04-16T01:35:00
2016-04-16T01:35:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hzjava.monitorcenter.service; public interface SysabnormalObjectTypeService { String findAll(); }
UTF-8
Java
115
java
SysabnormalObjectTypeService.java
Java
[]
null
[]
package com.hzjava.monitorcenter.service; public interface SysabnormalObjectTypeService { String findAll(); }
115
0.8
0.8
7
15.428572
19.085201
47
false
false
0
0
0
0
0
0
0.571429
false
false
7
2c999be20eabf20f94e5f40c5428f489510ef1c9
386,547,085,655
4640fa1e8b636222244d294992f8a5f4adf6cb33
/Module01/src/com/djh/test/ArrayAll.java
647093a2ae7aa318279049804078596f23e80b48
[]
no_license
djh-orphan/test
https://github.com/djh-orphan/test
c87305b9376a6d834978fb9009913cdb6972d989
c9d68f039c8d020b4996358b4962f74519011c30
refs/heads/master
2023-07-08T17:35:23.552000
2021-07-25T07:30:22
2021-07-25T07:30:22
382,753,282
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.djh.test; import java.util.Arrays; public class ArrayAll { public static void main(String[] args) { int a[][] = new int[2][]; int numa = 0; a[0] = new int[]{1, 2, 3, 4, 5}; a[1] = new int[]{1, 2, 3, 4, 5}; for (int j = 0; j < a.length; j++) { int[] ints = a[j]; for (int k = 0; k < ints.length; k++) { int anInt = ints[k]; numa += anInt; } } System.out.println("numa=" + numa); String s = Arrays.toString(a[0]); System.out.println(s.charAt(1)); // System.out.println(); Arrays.toString(Arrays.parallelSort(a[0])); Arrays.sort(a[0]); s = Arrays.toString(a[0]); System.out.println(s); } }
UTF-8
Java
781
java
ArrayAll.java
Java
[]
null
[]
package com.djh.test; import java.util.Arrays; public class ArrayAll { public static void main(String[] args) { int a[][] = new int[2][]; int numa = 0; a[0] = new int[]{1, 2, 3, 4, 5}; a[1] = new int[]{1, 2, 3, 4, 5}; for (int j = 0; j < a.length; j++) { int[] ints = a[j]; for (int k = 0; k < ints.length; k++) { int anInt = ints[k]; numa += anInt; } } System.out.println("numa=" + numa); String s = Arrays.toString(a[0]); System.out.println(s.charAt(1)); // System.out.println(); Arrays.toString(Arrays.parallelSort(a[0])); Arrays.sort(a[0]); s = Arrays.toString(a[0]); System.out.println(s); } }
781
0.46863
0.441741
27
27.925926
17.797058
75
false
false
0
0
0
0
0
0
1.074074
false
false
7
f141351fbc1e9a904a106b6388b26fe25417d193
386,547,089,269
cfaaf7b29632b0858c405cc373d7d8c79a728bc6
/src/online/shixun/hpeu/service/JuriService.java
359bf00b1f0c8386c9366d3236e86256c9095e2e
[]
no_license
Normanscat/AjaxStruts
https://github.com/Normanscat/AjaxStruts
67e1f90417107eb092e6784ef2daef3863df6994
186a425f805cb6b11fa0bdb0de48f035fa390c0f
refs/heads/master
2021-08-08T23:31:10.627000
2017-11-11T16:30:18
2017-11-11T16:30:18
110,361,291
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package online.shixun.hpeu.service; import java.util.List; import online.shixun.hpeu.dao.Jurdao; import online.shixun.hpeu.model.Juri; public class JuriService { private Jurdao jurdao = new Jurdao(); // 查询权限 public List<Juri> getJuri(Long JuriId) { return jurdao.getJuri(JuriId); } // 关键字查询权限 public List<Juri> search(String search) { return jurdao.searchJuri(search); } // 添加权限 public void savejuri(String jurisavename, String jurisavescp) { jurdao.savejuri(jurisavename, jurisavescp); } // 更新权限 public void upjuri(Long juriupid, String juriupname, String juriupscp) { jurdao.upjuri(juriupid, juriupname, juriupscp); } // 删除权限 public void deljuri(Long juridelId) { jurdao.deljuri(juridelId); } // 批量删除权限 public void deljuriall(List<Long> listid) { jurdao.deljuriall(listid); } }
UTF-8
Java
918
java
JuriService.java
Java
[]
null
[]
package online.shixun.hpeu.service; import java.util.List; import online.shixun.hpeu.dao.Jurdao; import online.shixun.hpeu.model.Juri; public class JuriService { private Jurdao jurdao = new Jurdao(); // 查询权限 public List<Juri> getJuri(Long JuriId) { return jurdao.getJuri(JuriId); } // 关键字查询权限 public List<Juri> search(String search) { return jurdao.searchJuri(search); } // 添加权限 public void savejuri(String jurisavename, String jurisavescp) { jurdao.savejuri(jurisavename, jurisavescp); } // 更新权限 public void upjuri(Long juriupid, String juriupname, String juriupscp) { jurdao.upjuri(juriupid, juriupname, juriupscp); } // 删除权限 public void deljuri(Long juridelId) { jurdao.deljuri(juridelId); } // 批量删除权限 public void deljuriall(List<Long> listid) { jurdao.deljuriall(listid); } }
918
0.698837
0.698837
40
19.5
20.218803
73
false
false
0
0
0
0
0
0
1.2
false
false
7
72c265095b29b3c70d011f0bad21450b5cc943ec
6,356,551,663,051
7b115833ed70077d4dcc79603f137fffaf068c63
/src/com/neusoft/web/impl/EC0601ControllerSupport.java
a53e6512fd94bc1c1caf35e07500cd6849e1c20e
[]
no_license
leotzt/ERPSystem
https://github.com/leotzt/ERPSystem
40694bd4ed29012839206851bc4da6e305e243d3
a142d6b306629ae0337f084478b32f5a88c9895e
refs/heads/master
2023-03-18T21:05:45.428000
2021-03-14T04:43:23
2021-03-14T04:43:23
347,535,590
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.neusoft.web.impl; import com.neusoft.services.impl.EC.EC0601ServicesImpl; import com.neusoft.web.support.ControllerSupport; public abstract class EC0601ControllerSupport extends ControllerSupport { public EC0601ControllerSupport() { this.setServices(new EC0601ServicesImpl()); } }
UTF-8
Java
313
java
EC0601ControllerSupport.java
Java
[]
null
[]
package com.neusoft.web.impl; import com.neusoft.services.impl.EC.EC0601ServicesImpl; import com.neusoft.web.support.ControllerSupport; public abstract class EC0601ControllerSupport extends ControllerSupport { public EC0601ControllerSupport() { this.setServices(new EC0601ServicesImpl()); } }
313
0.785942
0.734824
12
24.083334
25.064777
71
false
false
0
0
0
0
0
0
0.75
false
false
7
3bbd453ca7e27388658dacaccb385cce2d05c294
14,748,917,700,044
e12d3321364d9905535ff25aaaf306ae85b46086
/src/nl/utwente/sdm/assigment2/keyserver/KeyServer.java
207219197e2cf86f685bfb888cae796ea4e8980f
[]
no_license
tonyhuang419/sdm-assignment2
https://github.com/tonyhuang419/sdm-assignment2
c597ca5306e06c3a26416363b55dfacf7b84a1fc
ceaea3a54e31b1ebd21ec26398d8080d79aa6a6d
refs/heads/master
2021-01-23T18:59:44.296000
2008-12-12T14:35:00
2008-12-12T14:35:00
36,490,880
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package nl.utwente.sdm.assigment2.keyserver; import java.io.IOException; import java.math.BigInteger; import java.net.ServerSocket; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.SecureRandom; import java.util.HashSet; import nl.utwente.sdm.assigment2.IBEHelper; import nuim.cs.crypto.bilinear.ModifiedTatePairing; import nuim.cs.crypto.ibe.IbeSystemParameters; /** * The keyserver is responsible for generating the private * keys for identities who want to authenticate. * @author Harmen */ public class KeyServer { private static final int PORT_NUMBER = 10001; private static KeyServer _keyServer; private HashSet<String> _authenticated; public static MessageDigest _hash; private ModifiedTatePairing _map; private BigInteger _masterKey; private IbeSystemParameters _systemParameters; /** * The main procedure which starts the key server. * @param args Not used. */ public static void main(String[] args) { new KeyServer(); } /** * Get the keyserver object from other classes, this should be a singleton. * The object is created in the main method of this class. * @return The KeyServer object. */ public static KeyServer getKeyServer() { return _keyServer; } /** * Constructor. */ private KeyServer() { _keyServer = this; System.out.println("Starting KeyServer."); // Initialize the set with the authenticated identities. _authenticated = new HashSet<String>(); // Set the hash method. try { _hash = IBEHelper.getMessageDigest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } // Gordon's algorithm is used to generate the correct p,q and l values. // This algorithm will not always generate a large enough value p for // the finite field. Repeated attempts may be required. _map = new ModifiedTatePairing(); boolean fieldTooSmall = false; do { fieldTooSmall = false; // get a count of the maximum possible number of // points that we could use, i.e. p / kappa where // p is the upper limit of finite field Fp BigInteger maxPts = _map.getCurve().getField().getChar(). divide( _map.getCurve().getKappa() ); int bytes = maxPts.bitLength() / 8; if( bytes < _hash.getDigestLength() ) { _map = new ModifiedTatePairing(); fieldTooSmall = true; } } while( fieldTooSmall ); // Generate the master key and set the public parameters (systemParameters). _masterKey = new BigInteger(_map.getQ().bitLength() - 1, new SecureRandom()); _systemParameters = new IbeSystemParameters( _map, _hash, _masterKey ); /**System.out.println("Testing key generation."); String message = "This is a test message."; System.out.println("Message: " + message); byte[] encryptedMessage = IBEHelper.encryptMessage(message.getBytes(), IBEHelper.getPublicKey("test", _hash), _systemParameters); PrivateKey privateKey = IBEHelper.getPrivateKey("test", _map, _hash, _masterKey); System.out.println("private key format: " + privateKey.getFormat() + ", algorithm: " + privateKey.getAlgorithm()); String decryptedMessage = IBEHelper.decryptMessage(privateKey, _systemParameters, encryptedMessage); System.out.println("Decrypted message: " + decryptedMessage); System.out.println("End of key generation test.\n");*/ // Start the keyserver. start(); } /** * This procedure should open a socket and start listening on it. * It should be able to process messages send from clients with different content. * It could be the following messages: * - A client wants to get the global parameters. * - A client wants to authenticate and get the private key. */ public void start() { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(PORT_NUMBER); } catch (IOException e) { System.err.println("Could not listen on port: " + PORT_NUMBER); System.exit(-1); } System.out.println("KeyServer ready for clients to communicate."); while (true) { try { new KeyServerThread(serverSocket.accept()).start(); } catch (IOException e) { e.printStackTrace(); } } } /** * Procedure to authenticate with the keyserver, * this will generate a private key and send it to the authenticator. * @param identity The identity of the user who is authenticating. * @return Returns the generated private key for the authenticator. */ public PrivateKey authenticate(String identity) { boolean newUser = _authenticated.add(identity); if (newUser) { // New client/identity. add it to the list of authenticated clients. System.out.println("Authenticate: New client \"" + identity + "\" identified. Client added."); } else { // Client already registered and authenticated, so authentication comes from a new device of same client. System.out.println("Authenticate: Client \"" + identity + "\" already registered."); } return IBEHelper.getPrivateKey(identity, _map, _hash, _masterKey); } /** * Get the system parameters for the server (global parameters). * @return The system parameters. */ public IbeSystemParameters getSystemParameters() { return _systemParameters; } public ModifiedTatePairing getMap() { return _map; } }
UTF-8
Java
5,677
java
KeyServer.java
Java
[ { "context": "r identities who want to authenticate.\r\n * @author Harmen\r\n */\r\npublic class KeyServer {\r\n\tprivate static f", "end": 603, "score": 0.9997712969779968, "start": 597, "tag": "NAME", "value": "Harmen" } ]
null
[]
package nl.utwente.sdm.assigment2.keyserver; import java.io.IOException; import java.math.BigInteger; import java.net.ServerSocket; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.SecureRandom; import java.util.HashSet; import nl.utwente.sdm.assigment2.IBEHelper; import nuim.cs.crypto.bilinear.ModifiedTatePairing; import nuim.cs.crypto.ibe.IbeSystemParameters; /** * The keyserver is responsible for generating the private * keys for identities who want to authenticate. * @author Harmen */ public class KeyServer { private static final int PORT_NUMBER = 10001; private static KeyServer _keyServer; private HashSet<String> _authenticated; public static MessageDigest _hash; private ModifiedTatePairing _map; private BigInteger _masterKey; private IbeSystemParameters _systemParameters; /** * The main procedure which starts the key server. * @param args Not used. */ public static void main(String[] args) { new KeyServer(); } /** * Get the keyserver object from other classes, this should be a singleton. * The object is created in the main method of this class. * @return The KeyServer object. */ public static KeyServer getKeyServer() { return _keyServer; } /** * Constructor. */ private KeyServer() { _keyServer = this; System.out.println("Starting KeyServer."); // Initialize the set with the authenticated identities. _authenticated = new HashSet<String>(); // Set the hash method. try { _hash = IBEHelper.getMessageDigest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } // Gordon's algorithm is used to generate the correct p,q and l values. // This algorithm will not always generate a large enough value p for // the finite field. Repeated attempts may be required. _map = new ModifiedTatePairing(); boolean fieldTooSmall = false; do { fieldTooSmall = false; // get a count of the maximum possible number of // points that we could use, i.e. p / kappa where // p is the upper limit of finite field Fp BigInteger maxPts = _map.getCurve().getField().getChar(). divide( _map.getCurve().getKappa() ); int bytes = maxPts.bitLength() / 8; if( bytes < _hash.getDigestLength() ) { _map = new ModifiedTatePairing(); fieldTooSmall = true; } } while( fieldTooSmall ); // Generate the master key and set the public parameters (systemParameters). _masterKey = new BigInteger(_map.getQ().bitLength() - 1, new SecureRandom()); _systemParameters = new IbeSystemParameters( _map, _hash, _masterKey ); /**System.out.println("Testing key generation."); String message = "This is a test message."; System.out.println("Message: " + message); byte[] encryptedMessage = IBEHelper.encryptMessage(message.getBytes(), IBEHelper.getPublicKey("test", _hash), _systemParameters); PrivateKey privateKey = IBEHelper.getPrivateKey("test", _map, _hash, _masterKey); System.out.println("private key format: " + privateKey.getFormat() + ", algorithm: " + privateKey.getAlgorithm()); String decryptedMessage = IBEHelper.decryptMessage(privateKey, _systemParameters, encryptedMessage); System.out.println("Decrypted message: " + decryptedMessage); System.out.println("End of key generation test.\n");*/ // Start the keyserver. start(); } /** * This procedure should open a socket and start listening on it. * It should be able to process messages send from clients with different content. * It could be the following messages: * - A client wants to get the global parameters. * - A client wants to authenticate and get the private key. */ public void start() { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(PORT_NUMBER); } catch (IOException e) { System.err.println("Could not listen on port: " + PORT_NUMBER); System.exit(-1); } System.out.println("KeyServer ready for clients to communicate."); while (true) { try { new KeyServerThread(serverSocket.accept()).start(); } catch (IOException e) { e.printStackTrace(); } } } /** * Procedure to authenticate with the keyserver, * this will generate a private key and send it to the authenticator. * @param identity The identity of the user who is authenticating. * @return Returns the generated private key for the authenticator. */ public PrivateKey authenticate(String identity) { boolean newUser = _authenticated.add(identity); if (newUser) { // New client/identity. add it to the list of authenticated clients. System.out.println("Authenticate: New client \"" + identity + "\" identified. Client added."); } else { // Client already registered and authenticated, so authentication comes from a new device of same client. System.out.println("Authenticate: Client \"" + identity + "\" already registered."); } return IBEHelper.getPrivateKey(identity, _map, _hash, _masterKey); } /** * Get the system parameters for the server (global parameters). * @return The system parameters. */ public IbeSystemParameters getSystemParameters() { return _systemParameters; } public ModifiedTatePairing getMap() { return _map; } }
5,677
0.66285
0.661089
159
33.704403
28.425241
131
false
false
0
0
0
0
0
0
1.522013
false
false
7
c15fba33f10de67711ca97ef281b2dc212d89ca3
14,456,859,927,144
243eaf02e124f89a21c5d5afa707db40feda5144
/src/unk/com/tencent/mm/ui/qrcode/af.java
425a4103a6fd870b6b7c2dcbc26af6135c411f24
[]
no_license
laohanmsa/WeChatRE
https://github.com/laohanmsa/WeChatRE
e6671221ac6237c6565bd1aae02f847718e4ac9d
4b249bce4062e1f338f3e4bbee273b2a88814bf3
refs/heads/master
2020-05-03T08:43:38.647000
2013-05-18T14:04:23
2013-05-18T14:04:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package unk.com.tencent.mm.ui.qrcode; import android.app.Activity; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import com.tencent.mm.k.y; import com.tencent.mm.model.b; import com.tencent.mm.model.bd; import com.tencent.mm.platformtools.bf; import com.tencent.mm.storage.h; import com.tencent.mm.ui.base.i; import com.tencent.mm.ui.facebook.a.e; import com.tencent.mm.ui.facebook.v; import com.tencent.mm.z.ar; final class af implements View.OnClickListener { af(ShareToQQUI paramShareToQQUI) { } public final void onClick(View paramView) { ShareToQQUI.a(this.cOO); String str1; boolean bool1; boolean bool2; if ((ShareToQQUI.b(this.cOO) == 2) || (ShareToQQUI.b(this.cOO) == 1)) { str1 = ShareToQQUI.c(this.cOO).getText().toString(); if (ShareToQQUI.b(this.cOO) == 1) { bool1 = true; int i = ShareToQQUI.b(this.cOO); bool2 = false; if (i == 2) bool2 = true; } } for (ar localar = new ar(str1, bool1, bool2); ; localar = new ar(ShareToQQUI.c(this.cOO).getText().toString())) { bd.hM().d(localar); ShareToQQUI localShareToQQUI = this.cOO; Activity localActivity = this.cOO.acZ(); this.cOO.getString(2131165191); ShareToQQUI.a(localShareToQQUI, i.a(localActivity, this.cOO.getString(2131165770), true, new ah(this, localar))); return; bool1 = false; break; if (ShareToQQUI.b(this.cOO) != 4) break label297; long l = bf.a((Long)bd.hL().fN().get(65831)); String str2 = bf.gi((String)bd.hL().fN().get(65830)); if ((bf.B(l) > 86400000L) && (str2.length() > 0)) { e locale = new e("290293790992170"); locale.vd(str2); new v(locale, new ag(this)).ahQ(); } } label297: i.a(this.cOO.acZ(), 2131166536, 2131165191); } } /* Location: /home/danghvu/0day/WeChat/WeChat_4.5_dex2jar.jar * Qualified Name: com.tencent.mm.ui.qrcode.af * JD-Core Version: 0.6.2 */
UTF-8
Java
2,063
java
af.java
Java
[]
null
[]
package unk.com.tencent.mm.ui.qrcode; import android.app.Activity; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import com.tencent.mm.k.y; import com.tencent.mm.model.b; import com.tencent.mm.model.bd; import com.tencent.mm.platformtools.bf; import com.tencent.mm.storage.h; import com.tencent.mm.ui.base.i; import com.tencent.mm.ui.facebook.a.e; import com.tencent.mm.ui.facebook.v; import com.tencent.mm.z.ar; final class af implements View.OnClickListener { af(ShareToQQUI paramShareToQQUI) { } public final void onClick(View paramView) { ShareToQQUI.a(this.cOO); String str1; boolean bool1; boolean bool2; if ((ShareToQQUI.b(this.cOO) == 2) || (ShareToQQUI.b(this.cOO) == 1)) { str1 = ShareToQQUI.c(this.cOO).getText().toString(); if (ShareToQQUI.b(this.cOO) == 1) { bool1 = true; int i = ShareToQQUI.b(this.cOO); bool2 = false; if (i == 2) bool2 = true; } } for (ar localar = new ar(str1, bool1, bool2); ; localar = new ar(ShareToQQUI.c(this.cOO).getText().toString())) { bd.hM().d(localar); ShareToQQUI localShareToQQUI = this.cOO; Activity localActivity = this.cOO.acZ(); this.cOO.getString(2131165191); ShareToQQUI.a(localShareToQQUI, i.a(localActivity, this.cOO.getString(2131165770), true, new ah(this, localar))); return; bool1 = false; break; if (ShareToQQUI.b(this.cOO) != 4) break label297; long l = bf.a((Long)bd.hL().fN().get(65831)); String str2 = bf.gi((String)bd.hL().fN().get(65830)); if ((bf.B(l) > 86400000L) && (str2.length() > 0)) { e locale = new e("290293790992170"); locale.vd(str2); new v(locale, new ag(this)).ahQ(); } } label297: i.a(this.cOO.acZ(), 2131166536, 2131165191); } } /* Location: /home/danghvu/0day/WeChat/WeChat_4.5_dex2jar.jar * Qualified Name: com.tencent.mm.ui.qrcode.af * JD-Core Version: 0.6.2 */
2,063
0.627727
0.576345
70
28.485714
23.782192
119
false
false
0
0
0
0
0
0
0.742857
false
false
7
2c64805d1bce7ed559762890bb51af0e924bfe18
4,904,852,690,329
4a9618d3506c869a27fff61174e7bcd13c7ce47e
/testcases/populateTestForm/src/main/java/org/elsoft/platform/form/PopulateBusinessType.java
4a966438ed4a727a43a52edac3c7f571f9fda51f
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
renaudpawlak/tura
https://github.com/renaudpawlak/tura
ce4d2ca9c21fa096081ca4d4fb9f5acb27bee1f7
bbcfbaeb9a0286912712004b67966cb639b9cb5f
refs/heads/master
2021-05-08T08:20:14.259000
2013-08-07T21:57:43
2013-08-07T21:57:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/******************************************************************************* * Copyright 2012 Arseniy Isakov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.elsoft.platform.form; import org.elsoft.platform.datacontrol.DCMetaInfo; import org.elsoft.platform.datacontrol.StructureControl; import org.elsoft.platform.metamodel.objects.type.BusinessObjectDAO; import org.elsoft.platform.metamodel.objects.type.MethodDAO; import org.elsoft.platform.metamodel.objects.type.MethodReferenceDAO; import org.elsoft.platform.metamodel.objects.type.TypeDAO; import org.elsoft.platform.metamodel.suite.FunctionalDomainHandler; import org.elsoft.platform.metamodel.types.BusinessObjectHandler; import org.elsoft.platform.metamodel.types.TypeDefinitionHandler; import org.elsoft.platform.metamodel.RepositoryFactory; public class PopulateBusinessType { public void executeHR(RepositoryFactory rf, FunctionalDomainHandler fd) { createDropdowntestBusinessObject(fd, rf); createCountriesBusinessObject(fd, rf); createDepartmentsBusinessObject(fd, rf); createEmployeesBusinessObject(fd, rf); createhrFeaturesBusinessObject(fd,rf); } public void executeCommons(RepositoryFactory rf, FunctionalDomainHandler fd) { createDomainBusinessObject(fd, rf); createFunctionalDomainBusinessObject(fd, rf); createApplicationBusinessObject(fd, rf); createUIContainerBusinessObject(fd, rf); // createUIElementBusinessObject(fd, rf); } private void createDropdowntestBusinessObject(FunctionalDomainHandler fd, RepositoryFactory rf) { BusinessObjectHandler bh = fd.getBusinessObjectsHandler(); TypeDefinitionHandler tdh = rf.getTypeDefinitionHandler(); BusinessObjectDAO dropdowntest = bh.addBusinessObject("dropdowntest"); TypeDAO refDropdowntest = (TypeDAO) tdh.cleanSearch() .search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "BackOffice") .searchString("application", "HR") .searchString("typeName", "dropdowntest").getObject(); dropdowntest.setRefMntType(refDropdowntest.getObjId()); tdh.cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "BackOffice") .searchString("application", "HR") .searchString("typeName", "dropdowntestService").getObject(); MethodDAO method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "create").getObject(); MethodReferenceDAO metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.CreateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "find").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.SearchTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "insert").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.InsertTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "update").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.UpdateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "remove").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.RemoveTrigger.name()); StructureControl st = bh.getMode().getStControl(); st.toString(); } private void createCountriesBusinessObject(FunctionalDomainHandler fd, RepositoryFactory rf) { BusinessObjectHandler bh = fd.getBusinessObjectsHandler(); TypeDefinitionHandler tdh = rf.getTypeDefinitionHandler(); BusinessObjectDAO countries = bh.addBusinessObject("countries"); TypeDAO refCountries = (TypeDAO) tdh.cleanSearch() .search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "BackOffice") .searchString("application", "HR") .searchString("typeName", "countries").getObject(); countries.setRefMntType(refCountries.getObjId()); tdh.cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "BackOffice") .searchString("application", "HR") .searchString("typeName", "countriesService").getObject(); MethodDAO method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "create").getObject(); MethodReferenceDAO metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.CreateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "find").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.SearchTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "insert").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.InsertTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "update").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.UpdateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "remove").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.RemoveTrigger.name()); } private void createDepartmentsBusinessObject(FunctionalDomainHandler fd, RepositoryFactory rf) { BusinessObjectHandler bh = fd.getBusinessObjectsHandler(); TypeDefinitionHandler tdh = rf.getTypeDefinitionHandler(); BusinessObjectDAO departments = bh.addBusinessObject("departments"); TypeDAO refDepartments = (TypeDAO) tdh.cleanSearch() .search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "BackOffice") .searchString("application", "HR") .searchString("typeName", "departments").getObject(); departments.setRefMntType(refDepartments.getObjId()); tdh.cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "BackOffice") .searchString("application", "HR") .searchString("typeName", "departmentsService").getObject(); MethodDAO method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "create").getObject(); MethodReferenceDAO metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.CreateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "find").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.SearchTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "insert").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.InsertTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "update").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.UpdateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "remove").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.RemoveTrigger.name()); } private void createEmployeesBusinessObject(FunctionalDomainHandler fd, RepositoryFactory rf) { BusinessObjectHandler bh = fd.getBusinessObjectsHandler(); TypeDefinitionHandler tdh = rf.getTypeDefinitionHandler(); BusinessObjectDAO employees = bh.addBusinessObject("employees"); TypeDAO refEmployees = (TypeDAO) tdh .cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "BackOffice") .searchString("application", "HR") .searchString("typeName", "employees").getObject(); employees.setRefMntType(refEmployees.getObjId()); tdh.cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "BackOffice") .searchString("application", "HR") .searchString("typeName", "employeesService").getObject(); MethodDAO method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "create").getObject(); MethodReferenceDAO metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.CreateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "find").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.SearchTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "insert").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.InsertTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "update").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.UpdateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "remove").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.RemoveTrigger.name()); } private void createDomainBusinessObject(FunctionalDomainHandler fd, RepositoryFactory rf) { BusinessObjectHandler bh = fd.getBusinessObjectsHandler(); TypeDefinitionHandler tdh = rf.getTypeDefinitionHandler(); BusinessObjectDAO domain = bh.addBusinessObject("domain"); TypeDAO refDomain = (TypeDAO) tdh .cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "Commons") .searchString("application", "Metarepository") .searchString("typeName", "domain").getObject(); domain.setRefMntType(refDomain.getObjId()); tdh.cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "Commons") .searchString("application", "Metarepository") .searchString("typeName", "domainService").getObject(); MethodDAO method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "create").getObject(); MethodReferenceDAO metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.CreateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "find").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.SearchTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "insert").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.InsertTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "update").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.UpdateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "remove").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.RemoveTrigger.name()); } private void createFunctionalDomainBusinessObject( FunctionalDomainHandler fd, RepositoryFactory rf) { BusinessObjectHandler bh = fd.getBusinessObjectsHandler(); TypeDefinitionHandler tdh = rf.getTypeDefinitionHandler(); BusinessObjectDAO functionalDomain = bh .addBusinessObject("functionalDomain"); TypeDAO refFunctionalDomain = (TypeDAO) tdh .cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "Commons") .searchString("application", "Metarepository") .searchString("typeName", "functionalDomain").getObject(); functionalDomain.setRefMntType(refFunctionalDomain.getObjId()); tdh.cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "Commons") .searchString("application", "Metarepository") .searchString("typeName", "functionalDomainService") .getObject(); MethodDAO method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "create").getObject(); MethodReferenceDAO metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.CreateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "find").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.SearchTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "insert").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.InsertTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "update").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.UpdateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "remove").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.RemoveTrigger.name()); } private void createApplicationBusinessObject(FunctionalDomainHandler fd, RepositoryFactory rf) { BusinessObjectHandler bh = fd.getBusinessObjectsHandler(); TypeDefinitionHandler tdh = rf.getTypeDefinitionHandler(); BusinessObjectDAO application = bh.addBusinessObject("application"); TypeDAO refApplication = (TypeDAO) tdh .cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "Commons") .searchString("application", "Metarepository") .searchString("typeName", "application").getObject(); application.setRefMntType(refApplication.getObjId()); tdh.cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "Commons") .searchString("application", "Metarepository") .searchString("typeName", "applicationService").getObject(); MethodDAO method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "create").getObject(); MethodReferenceDAO metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.CreateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "find").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.SearchTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "insert").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.InsertTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "update").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.UpdateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "remove").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.RemoveTrigger.name()); } private void createUIContainerBusinessObject(FunctionalDomainHandler fd, RepositoryFactory rf) { BusinessObjectHandler bh = fd.getBusinessObjectsHandler(); TypeDefinitionHandler tdh = rf.getTypeDefinitionHandler(); BusinessObjectDAO UIContainer = bh.addBusinessObject("UIContainer"); TypeDAO refUIContainer = (TypeDAO) tdh .cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "Commons") .searchString("application", "Metarepository") .searchString("typeName", "UIContainer").getObject(); UIContainer.setRefMntType(refUIContainer.getObjId()); tdh.cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "Commons") .searchString("application", "Metarepository") .searchString("typeName", "UIContainerService").getObject(); MethodDAO method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "create").getObject(); MethodReferenceDAO metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.CreateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "find").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.SearchTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "insert").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.InsertTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "update").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.UpdateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "remove").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.RemoveTrigger.name()); } @SuppressWarnings("unused") private void createUIElementBusinessObject(FunctionalDomainHandler fd, RepositoryFactory rf) { BusinessObjectHandler bh = fd.getBusinessObjectsHandler(); TypeDefinitionHandler tdh = rf.getTypeDefinitionHandler(); BusinessObjectDAO UIElement = bh.addBusinessObject("UIElement"); TypeDAO refUIContainer = (TypeDAO) tdh .cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "Commons") .searchString("application", "Metarepository") .searchString("typeName", "UIElement").getObject(); UIElement.setRefMntType(refUIContainer.getObjId()); tdh.cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "Commons") .searchString("application", "Metarepository") .searchString("typeName", "UIElementService").getObject(); MethodDAO method = (MethodDAO) tdh.getMethodHandler() .searchString("method", "create").getObject(); MethodReferenceDAO metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.CreateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "find").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.SearchTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "insert").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.InsertTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "update").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.UpdateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "remove").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.RemoveTrigger.name()); } private void createhrFeaturesBusinessObject(FunctionalDomainHandler fd, RepositoryFactory rf) { BusinessObjectHandler bh = fd.getBusinessObjectsHandler(); TypeDefinitionHandler tdh = rf.getTypeDefinitionHandler(); BusinessObjectDAO hrFeatures = bh.addBusinessObject("hrFeatures"); TypeDAO refDropdowntest = (TypeDAO) tdh.cleanSearch() .search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "BackOffice") .searchString("application", "HR") .searchString("typeName", "hrFeatures").getObject(); hrFeatures.setRefMntType(refDropdowntest.getObjId()); tdh.cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "BackOffice") .searchString("application", "HR") .searchString("typeName", "hrFeaturesService").getObject(); MethodDAO method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "create").getObject(); MethodReferenceDAO refMeth =bh.getMethodReferenceHandler().addMethodReference(method); refMeth.setMethodType(DCMetaInfo.CreateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "find").getObject(); refMeth = bh.getMethodReferenceHandler().addMethodReference(method); refMeth.setMethodType(DCMetaInfo.SearchTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "insert").getObject(); refMeth = bh.getMethodReferenceHandler().addMethodReference(method); refMeth.setMethodType(DCMetaInfo.InsertTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "update").getObject(); refMeth = bh.getMethodReferenceHandler().addMethodReference(method); refMeth.setMethodType(DCMetaInfo.UpdateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "remove").getObject(); refMeth = bh.getMethodReferenceHandler().addMethodReference(method); refMeth.setMethodType(DCMetaInfo.RemoveTrigger.name()); StructureControl st = bh.getMode().getStControl(); st.toString(); } }
UTF-8
Java
22,954
java
PopulateBusinessType.java
Java
[ { "context": "********************************\n * Copyright 2012 Arseniy Isakov\n * \n * Licensed under the Apache License, Version", "end": 113, "score": 0.9998315572738647, "start": 99, "tag": "NAME", "value": "Arseniy Isakov" } ]
null
[]
/******************************************************************************* * Copyright 2012 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.elsoft.platform.form; import org.elsoft.platform.datacontrol.DCMetaInfo; import org.elsoft.platform.datacontrol.StructureControl; import org.elsoft.platform.metamodel.objects.type.BusinessObjectDAO; import org.elsoft.platform.metamodel.objects.type.MethodDAO; import org.elsoft.platform.metamodel.objects.type.MethodReferenceDAO; import org.elsoft.platform.metamodel.objects.type.TypeDAO; import org.elsoft.platform.metamodel.suite.FunctionalDomainHandler; import org.elsoft.platform.metamodel.types.BusinessObjectHandler; import org.elsoft.platform.metamodel.types.TypeDefinitionHandler; import org.elsoft.platform.metamodel.RepositoryFactory; public class PopulateBusinessType { public void executeHR(RepositoryFactory rf, FunctionalDomainHandler fd) { createDropdowntestBusinessObject(fd, rf); createCountriesBusinessObject(fd, rf); createDepartmentsBusinessObject(fd, rf); createEmployeesBusinessObject(fd, rf); createhrFeaturesBusinessObject(fd,rf); } public void executeCommons(RepositoryFactory rf, FunctionalDomainHandler fd) { createDomainBusinessObject(fd, rf); createFunctionalDomainBusinessObject(fd, rf); createApplicationBusinessObject(fd, rf); createUIContainerBusinessObject(fd, rf); // createUIElementBusinessObject(fd, rf); } private void createDropdowntestBusinessObject(FunctionalDomainHandler fd, RepositoryFactory rf) { BusinessObjectHandler bh = fd.getBusinessObjectsHandler(); TypeDefinitionHandler tdh = rf.getTypeDefinitionHandler(); BusinessObjectDAO dropdowntest = bh.addBusinessObject("dropdowntest"); TypeDAO refDropdowntest = (TypeDAO) tdh.cleanSearch() .search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "BackOffice") .searchString("application", "HR") .searchString("typeName", "dropdowntest").getObject(); dropdowntest.setRefMntType(refDropdowntest.getObjId()); tdh.cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "BackOffice") .searchString("application", "HR") .searchString("typeName", "dropdowntestService").getObject(); MethodDAO method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "create").getObject(); MethodReferenceDAO metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.CreateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "find").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.SearchTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "insert").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.InsertTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "update").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.UpdateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "remove").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.RemoveTrigger.name()); StructureControl st = bh.getMode().getStControl(); st.toString(); } private void createCountriesBusinessObject(FunctionalDomainHandler fd, RepositoryFactory rf) { BusinessObjectHandler bh = fd.getBusinessObjectsHandler(); TypeDefinitionHandler tdh = rf.getTypeDefinitionHandler(); BusinessObjectDAO countries = bh.addBusinessObject("countries"); TypeDAO refCountries = (TypeDAO) tdh.cleanSearch() .search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "BackOffice") .searchString("application", "HR") .searchString("typeName", "countries").getObject(); countries.setRefMntType(refCountries.getObjId()); tdh.cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "BackOffice") .searchString("application", "HR") .searchString("typeName", "countriesService").getObject(); MethodDAO method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "create").getObject(); MethodReferenceDAO metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.CreateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "find").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.SearchTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "insert").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.InsertTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "update").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.UpdateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "remove").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.RemoveTrigger.name()); } private void createDepartmentsBusinessObject(FunctionalDomainHandler fd, RepositoryFactory rf) { BusinessObjectHandler bh = fd.getBusinessObjectsHandler(); TypeDefinitionHandler tdh = rf.getTypeDefinitionHandler(); BusinessObjectDAO departments = bh.addBusinessObject("departments"); TypeDAO refDepartments = (TypeDAO) tdh.cleanSearch() .search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "BackOffice") .searchString("application", "HR") .searchString("typeName", "departments").getObject(); departments.setRefMntType(refDepartments.getObjId()); tdh.cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "BackOffice") .searchString("application", "HR") .searchString("typeName", "departmentsService").getObject(); MethodDAO method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "create").getObject(); MethodReferenceDAO metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.CreateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "find").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.SearchTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "insert").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.InsertTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "update").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.UpdateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "remove").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.RemoveTrigger.name()); } private void createEmployeesBusinessObject(FunctionalDomainHandler fd, RepositoryFactory rf) { BusinessObjectHandler bh = fd.getBusinessObjectsHandler(); TypeDefinitionHandler tdh = rf.getTypeDefinitionHandler(); BusinessObjectDAO employees = bh.addBusinessObject("employees"); TypeDAO refEmployees = (TypeDAO) tdh .cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "BackOffice") .searchString("application", "HR") .searchString("typeName", "employees").getObject(); employees.setRefMntType(refEmployees.getObjId()); tdh.cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "BackOffice") .searchString("application", "HR") .searchString("typeName", "employeesService").getObject(); MethodDAO method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "create").getObject(); MethodReferenceDAO metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.CreateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "find").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.SearchTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "insert").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.InsertTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "update").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.UpdateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "remove").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.RemoveTrigger.name()); } private void createDomainBusinessObject(FunctionalDomainHandler fd, RepositoryFactory rf) { BusinessObjectHandler bh = fd.getBusinessObjectsHandler(); TypeDefinitionHandler tdh = rf.getTypeDefinitionHandler(); BusinessObjectDAO domain = bh.addBusinessObject("domain"); TypeDAO refDomain = (TypeDAO) tdh .cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "Commons") .searchString("application", "Metarepository") .searchString("typeName", "domain").getObject(); domain.setRefMntType(refDomain.getObjId()); tdh.cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "Commons") .searchString("application", "Metarepository") .searchString("typeName", "domainService").getObject(); MethodDAO method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "create").getObject(); MethodReferenceDAO metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.CreateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "find").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.SearchTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "insert").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.InsertTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "update").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.UpdateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "remove").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.RemoveTrigger.name()); } private void createFunctionalDomainBusinessObject( FunctionalDomainHandler fd, RepositoryFactory rf) { BusinessObjectHandler bh = fd.getBusinessObjectsHandler(); TypeDefinitionHandler tdh = rf.getTypeDefinitionHandler(); BusinessObjectDAO functionalDomain = bh .addBusinessObject("functionalDomain"); TypeDAO refFunctionalDomain = (TypeDAO) tdh .cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "Commons") .searchString("application", "Metarepository") .searchString("typeName", "functionalDomain").getObject(); functionalDomain.setRefMntType(refFunctionalDomain.getObjId()); tdh.cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "Commons") .searchString("application", "Metarepository") .searchString("typeName", "functionalDomainService") .getObject(); MethodDAO method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "create").getObject(); MethodReferenceDAO metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.CreateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "find").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.SearchTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "insert").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.InsertTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "update").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.UpdateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "remove").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.RemoveTrigger.name()); } private void createApplicationBusinessObject(FunctionalDomainHandler fd, RepositoryFactory rf) { BusinessObjectHandler bh = fd.getBusinessObjectsHandler(); TypeDefinitionHandler tdh = rf.getTypeDefinitionHandler(); BusinessObjectDAO application = bh.addBusinessObject("application"); TypeDAO refApplication = (TypeDAO) tdh .cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "Commons") .searchString("application", "Metarepository") .searchString("typeName", "application").getObject(); application.setRefMntType(refApplication.getObjId()); tdh.cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "Commons") .searchString("application", "Metarepository") .searchString("typeName", "applicationService").getObject(); MethodDAO method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "create").getObject(); MethodReferenceDAO metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.CreateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "find").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.SearchTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "insert").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.InsertTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "update").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.UpdateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "remove").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.RemoveTrigger.name()); } private void createUIContainerBusinessObject(FunctionalDomainHandler fd, RepositoryFactory rf) { BusinessObjectHandler bh = fd.getBusinessObjectsHandler(); TypeDefinitionHandler tdh = rf.getTypeDefinitionHandler(); BusinessObjectDAO UIContainer = bh.addBusinessObject("UIContainer"); TypeDAO refUIContainer = (TypeDAO) tdh .cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "Commons") .searchString("application", "Metarepository") .searchString("typeName", "UIContainer").getObject(); UIContainer.setRefMntType(refUIContainer.getObjId()); tdh.cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "Commons") .searchString("application", "Metarepository") .searchString("typeName", "UIContainerService").getObject(); MethodDAO method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "create").getObject(); MethodReferenceDAO metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.CreateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "find").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.SearchTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "insert").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.InsertTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "update").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.UpdateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "remove").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.RemoveTrigger.name()); } @SuppressWarnings("unused") private void createUIElementBusinessObject(FunctionalDomainHandler fd, RepositoryFactory rf) { BusinessObjectHandler bh = fd.getBusinessObjectsHandler(); TypeDefinitionHandler tdh = rf.getTypeDefinitionHandler(); BusinessObjectDAO UIElement = bh.addBusinessObject("UIElement"); TypeDAO refUIContainer = (TypeDAO) tdh .cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "Commons") .searchString("application", "Metarepository") .searchString("typeName", "UIElement").getObject(); UIElement.setRefMntType(refUIContainer.getObjId()); tdh.cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "Commons") .searchString("application", "Metarepository") .searchString("typeName", "UIElementService").getObject(); MethodDAO method = (MethodDAO) tdh.getMethodHandler() .searchString("method", "create").getObject(); MethodReferenceDAO metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.CreateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "find").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.SearchTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "insert").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.InsertTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "update").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.UpdateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler() .cleanSearch().searchString("method", "remove").getObject(); metRef = bh.getMethodReferenceHandler().addMethodReference(method); metRef.setMethodType(DCMetaInfo.RemoveTrigger.name()); } private void createhrFeaturesBusinessObject(FunctionalDomainHandler fd, RepositoryFactory rf) { BusinessObjectHandler bh = fd.getBusinessObjectsHandler(); TypeDefinitionHandler tdh = rf.getTypeDefinitionHandler(); BusinessObjectDAO hrFeatures = bh.addBusinessObject("hrFeatures"); TypeDAO refDropdowntest = (TypeDAO) tdh.cleanSearch() .search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "BackOffice") .searchString("application", "HR") .searchString("typeName", "hrFeatures").getObject(); hrFeatures.setRefMntType(refDropdowntest.getObjId()); tdh.cleanSearch().search("domain", String.class, "Manufacturing") .searchString("functionalDomain", "BackOffice") .searchString("application", "HR") .searchString("typeName", "hrFeaturesService").getObject(); MethodDAO method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "create").getObject(); MethodReferenceDAO refMeth =bh.getMethodReferenceHandler().addMethodReference(method); refMeth.setMethodType(DCMetaInfo.CreateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "find").getObject(); refMeth = bh.getMethodReferenceHandler().addMethodReference(method); refMeth.setMethodType(DCMetaInfo.SearchTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "insert").getObject(); refMeth = bh.getMethodReferenceHandler().addMethodReference(method); refMeth.setMethodType(DCMetaInfo.InsertTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "update").getObject(); refMeth = bh.getMethodReferenceHandler().addMethodReference(method); refMeth.setMethodType(DCMetaInfo.UpdateTrigger.name()); method = (MethodDAO) tdh.getMethodHandler().cleanSearch() .searchString("method", "remove").getObject(); refMeth = bh.getMethodReferenceHandler().addMethodReference(method); refMeth.setMethodType(DCMetaInfo.RemoveTrigger.name()); StructureControl st = bh.getMode().getStControl(); st.toString(); } }
22,946
0.753551
0.753202
536
41.824627
27.169092
89
false
false
0
0
0
0
0
0
2.63806
false
false
7
e64a67217047beb7c5347133533cf0e5892d4a64
12,558,484,373,800
4c29081750c7a5bdbfc95800cc7dbe65c09ff872
/rabbitmq/rabbitmqdemo/src/main/java/com/ssslinppp/rabbitmq/springamqp/tut5/Tut5Config.java
7696b13dcd6a40cb9a0917000ef63ac8c755c36d
[]
no_license
ssslinppp/SpringBootStudy
https://github.com/ssslinppp/SpringBootStudy
4525bccc25577d6b2c9b4f0cb441209e8cd3ff08
aa045718d757829522e79990745efa0af1a85c96
refs/heads/master
2021-06-03T04:28:13.639000
2019-05-22T15:00:21
2019-05-22T15:00:21
95,901,067
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ssslinppp.rabbitmq.springamqp.tut5; import org.springframework.amqp.core.*; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; /** */ @Profile({"tut5", "topics"}) @Configuration public class Tut5Config { /** * 消息队列结构图: https://www.rabbitmq.com/img/tutorials/python-five.png * 官方示例:https://www.rabbitmq.com/tutorials/tutorial-five-spring-amqp.html * <p> * routingKey格式:用于描述动物, {@code <speed>.<colour>.<species>} * * @return */ @Bean public TopicExchange topic() { return new TopicExchange("tut.topic"); } @Profile("sender") @Bean public Tut5Sender sender() { return new Tut5Sender(); } /** * 创建了2个Queue: * <pre> * Queue1: bingingKey: {@code "*.orange.*" } * Queue2: bingingKey: {@code "*.*.rabbit" 和 "lazy.#"} * </pre> * * A message with a routing key set to : * <pre> * 1. "quick.orange.rabbit": will be delivered to both queues. * 2. "lazy.orange.elephant" : also will go to both of them. * 3. "quick.orange.fox" : will only go to the first queue. * 4. "lazy.brown.fox" : only to the second. * 5. "lazy.pink.rabbit" : will be delivered to the second queue only once, even though it matches two bindings. * 6. "quick.brown.fox": doesn't match any binding so it will be discarded. * 7. "orange" or "quick.orange.male.rabbit": these messages won't match any bindings and will be lost. * 8. "lazy.orange.male.rabbit": even though it has four words, will match the last binding("lazy.#") and will be delivered to the second queue * </pre> */ @Profile("receiver") private static class ReceiverConfig { /** * Queue1: bingingKey: {@code "*.orange.*" } * <p> * Queue1 is interested in all the orange animals. * * @return */ @Bean public Queue autoDeleteQueue1() { return new AnonymousQueue(); } @Bean public Binding binding1a(TopicExchange topic, Queue autoDeleteQueue1) { return BindingBuilder.bind(autoDeleteQueue1).to(topic).with("*.orange.*"); } /** * Queue2: bingingKey: {@code "*.*.rabbit" 和 "lazy.#"} * <p> * Queue2 wants to hear everything about rabbits, and everything about lazy animals. * * @return */ @Bean public Queue autoDeleteQueue2() { return new AnonymousQueue(); } @Bean public Binding binding2a(TopicExchange topic, Queue autoDeleteQueue2) { return BindingBuilder.bind(autoDeleteQueue2).to(topic).with("lazy.#"); } @Bean public Binding binding1b(TopicExchange topic, Queue autoDeleteQueue2) { return BindingBuilder.bind(autoDeleteQueue2).to(topic).with("*.*.rabbit"); } @Bean public Tut5Receiver receiver() { return new Tut5Receiver(); } } }
UTF-8
Java
3,300
java
Tut5Config.java
Java
[]
null
[]
package com.ssslinppp.rabbitmq.springamqp.tut5; import org.springframework.amqp.core.*; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; /** */ @Profile({"tut5", "topics"}) @Configuration public class Tut5Config { /** * 消息队列结构图: https://www.rabbitmq.com/img/tutorials/python-five.png * 官方示例:https://www.rabbitmq.com/tutorials/tutorial-five-spring-amqp.html * <p> * routingKey格式:用于描述动物, {@code <speed>.<colour>.<species>} * * @return */ @Bean public TopicExchange topic() { return new TopicExchange("tut.topic"); } @Profile("sender") @Bean public Tut5Sender sender() { return new Tut5Sender(); } /** * 创建了2个Queue: * <pre> * Queue1: bingingKey: {@code "*.orange.*" } * Queue2: bingingKey: {@code "*.*.rabbit" 和 "lazy.#"} * </pre> * * A message with a routing key set to : * <pre> * 1. "quick.orange.rabbit": will be delivered to both queues. * 2. "lazy.orange.elephant" : also will go to both of them. * 3. "quick.orange.fox" : will only go to the first queue. * 4. "lazy.brown.fox" : only to the second. * 5. "lazy.pink.rabbit" : will be delivered to the second queue only once, even though it matches two bindings. * 6. "quick.brown.fox": doesn't match any binding so it will be discarded. * 7. "orange" or "quick.orange.male.rabbit": these messages won't match any bindings and will be lost. * 8. "lazy.orange.male.rabbit": even though it has four words, will match the last binding("lazy.#") and will be delivered to the second queue * </pre> */ @Profile("receiver") private static class ReceiverConfig { /** * Queue1: bingingKey: {@code "*.orange.*" } * <p> * Queue1 is interested in all the orange animals. * * @return */ @Bean public Queue autoDeleteQueue1() { return new AnonymousQueue(); } @Bean public Binding binding1a(TopicExchange topic, Queue autoDeleteQueue1) { return BindingBuilder.bind(autoDeleteQueue1).to(topic).with("*.orange.*"); } /** * Queue2: bingingKey: {@code "*.*.rabbit" 和 "lazy.#"} * <p> * Queue2 wants to hear everything about rabbits, and everything about lazy animals. * * @return */ @Bean public Queue autoDeleteQueue2() { return new AnonymousQueue(); } @Bean public Binding binding2a(TopicExchange topic, Queue autoDeleteQueue2) { return BindingBuilder.bind(autoDeleteQueue2).to(topic).with("lazy.#"); } @Bean public Binding binding1b(TopicExchange topic, Queue autoDeleteQueue2) { return BindingBuilder.bind(autoDeleteQueue2).to(topic).with("*.*.rabbit"); } @Bean public Tut5Receiver receiver() { return new Tut5Receiver(); } } }
3,300
0.579208
0.568998
101
31
29.786367
148
false
false
0
0
0
0
0
0
0.207921
false
false
7
c6933f5139db5f28a8cbd6020b4ed8ea1019f3ed
4,260,607,575,333
e078e97dba70d85bdc836610a6e276979ed2d3c7
/src/main/java/com/leap/network/HttpServlet.java
5aaafcbf318844177b0cd159ea5bd466ebcb83a7
[]
no_license
leap66/spring_boot
https://github.com/leap66/spring_boot
f11c15253f36e29f5ed41e8ebfdccdab45bd200d
2100b8d7984fc810a0f2eff6e0e363093220a975
refs/heads/master
2021-09-13T16:55:56.947000
2017-12-22T04:58:37
2017-12-22T04:58:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.leap.network; import com.leap.config.MarsConfig; import com.leap.handle.exception.base.BaseException; import com.leap.model.VoiceParam; import com.leap.model.baidu.BVoice; import com.leap.model.baidu.SToken; import com.leap.model.enums.TtsCode; import com.leap.model.tuling.BChat; import com.leap.util.GsonUtil; import com.leap.util.IsEmpty; import io.jsonwebtoken.impl.Base64Codec; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.springframework.stereotype.Service; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * @author : ylwei * @time : 2017/9/19 * @description : */ @Service public class HttpServlet { public String getToken() throws IOException { String url = MarsConfig.BAI_DU_TOKEN_URL // + "?grant_type=client_credentials" // + "&client_id=" + MarsConfig.BAI_DU_API_KEY // + "&client_secret=" + MarsConfig.BAI_DU_SECRET_KEY; // 创建HttpClient对象 HttpClient client = HttpClients.createDefault(); // 创建GET请求(在构造器中传入URL字符串即可) HttpGet get = new HttpGet(url); // 调用HttpClient对象的execute方法获得响应 HttpResponse response = client.execute(get); // 调用HttpResponse对象的getEntity方法得到响应实体 HttpEntity httpEntity = response.getEntity(); // 使用EntityUtils工具类得到响应的字符串表示 String result = EntityUtils.toString(httpEntity, "utf-8"); SToken token = GsonUtil.parse(result, SToken.class); MarsConfig.BAI_DU_TOKEN = token.getAccess_token(); return MarsConfig.BAI_DU_TOKEN; } /** * 图灵网络请求 * * @param chat * 入参 * @return 返回字符串 * @throws IOException * IO异常 */ public String tuLingQuest(BChat chat) throws IOException { // 创建HttpClient对象 HttpClient client = HttpClients.createDefault(); // 创建POST请求 HttpPost post = new HttpPost(MarsConfig.TU_LING_URL); // 创建一个List容器,用于存放基本键值对(基本键值对即:参数名-参数值) List<BasicNameValuePair> parameters = new ArrayList<>(); parameters.add(new BasicNameValuePair("key", MarsConfig.TU_LING_KEY)); parameters.add(new BasicNameValuePair("userid", chat.getUserid().substring(0, chat.getUserid().length() - 6))); parameters.add(new BasicNameValuePair("info", chat.getInfo())); if (!IsEmpty.string(chat.getLoc())) parameters.add(new BasicNameValuePair("loc", chat.getLoc())); // 向POST请求中添加消息实体 post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8")); // 得到响应并转化成字符串 HttpResponse response = client.execute(post); HttpEntity httpEntity = response.getEntity(); return EntityUtils.toString(httpEntity, "utf-8"); } /** * 百度语音转文字 * * @param voice * 入参 * @return 返回字符串 * @throws IOException * IO异常 */ public String vop(VoiceParam param, String token, BVoice voice) throws IOException { // 创建HttpClient对象 HttpClient client = HttpClients.createDefault(); // 创建POST请求 HttpPost post = new HttpPost(MarsConfig.BAI_DU_VOP_URL); // 创建一个List容器,用于存放基本键值对(基本键值对即:参数名-参数值) List<BasicNameValuePair> parameters = new ArrayList<>(); // 语音文件的格式,pcm 或者 wav 或者 amr。不区分大小写 parameters.add(new BasicNameValuePair("format", voice.getFormat())); // 采样率,支持 8000 或者 16000 parameters.add(new BasicNameValuePair("rate", param.getRate())); // 声道数,仅支持单声道,请填写固定值 1 parameters.add(new BasicNameValuePair("channel", param.getChannel())); // 用户唯一标识,用来区分用户,计算UV值。建议填写能区分用户的机器 MAC 地址或 IMEI 码,长度为60字符以内。 parameters.add(new BasicNameValuePair("cuid", param.getUserId())); // 开放平台获取到的开发者access_token parameters.add(new BasicNameValuePair("token", token)); // 语种选择,默认中文(zh)。 中文=zh、粤语=ct、英文=en,不区分大小写。 parameters.add(new BasicNameValuePair("lan", param.getLan())); // 语音下载地址,与callback连一起使用,确保百度服务器可以访问 // parameters.add(new BasicNameValuePair("url", "")); // 识别结果回调地址,确保百度服务器可以访问 // parameters.add(new BasicNameValuePair("callback", "")); // 真实的语音数据 ,需要进行base64 编码。与len参数连一起使用。 String temp = Base64Codec.BASE64.encode(voice.getCode()); parameters.add(new BasicNameValuePair("speech", temp)); // 原始语音长度,单位字节 parameters.add(new BasicNameValuePair("len", String.valueOf(voice.getLen()))); // 向POST请求中添加消息实体 post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8")); // 得到响应并转化成字符串 HttpResponse response = client.execute(post); HttpEntity httpEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() != 200) throw new BaseException(response.getStatusLine().getStatusCode(), TtsCode.getEnum(response.getStatusLine().getStatusCode()).getMessage()); return EntityUtils.toString(httpEntity, "utf-8"); } /** * 百度文字转语音 * * @param value * 入参 * @return 返回字符串 * @throws IOException * IO异常 */ public byte[] tts(VoiceParam param, String token, String value) throws IOException, BaseException { // 创建HttpClient对象 HttpClient client = HttpClients.createDefault(); // 创建POST请求 HttpPost post = new HttpPost(MarsConfig.BAI_DU_TTS_URL); // 创建一个List容器,用于存放基本键值对(基本键值对即:参数名-参数值) List<BasicNameValuePair> parameters = new ArrayList<>(); // 合成的文本,使用UTF-8编码,请注意文本长度必须小于1024字节 parameters.add(new BasicNameValuePair("tex", value)); // 语言选择,目前只有中英文混合模式,填写固定值zh parameters.add(new BasicNameValuePair("lan", param.getLan())); // 开放平台获取到的开发者access_token parameters.add(new BasicNameValuePair("tok", token)); // 客户端类型选择,web端填写固定值1 parameters.add(new BasicNameValuePair("ctp", param.getCtp())); // 用户唯一标识,用来区分用户,计算UV值。建议填写能区分用户的机器 MAC 地址或 IMEI 码,长度为60字符以内。 parameters.add(new BasicNameValuePair("cuid", param.getUserId())); // 语速,取值0-9,默认为5中语速 parameters.add(new BasicNameValuePair("spd", param.getSpd())); // 音调,取值0-9,默认为5中语调 parameters.add(new BasicNameValuePair("pit", param.getPit())); // 音量,取值0-15,默认为5中音量 parameters.add(new BasicNameValuePair("vol", param.getVol())); // 发音人选择, 0为普通女声,1为普通男声,3为情感合成-度逍遥,4为情感合成-度丫丫,默认为普通女声 parameters.add(new BasicNameValuePair("per", param.getPer())); // 向POST请求中添加消息实体 post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8")); // 得到响应并转化成字符串 HttpResponse response = client.execute(post); HttpEntity httpEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() != 200) throw new BaseException(response.getStatusLine().getStatusCode(), TtsCode.getEnum(response.getStatusLine().getStatusCode()).getMessage()); // InputStream转换为byte[] ByteArrayOutputStream stream = new ByteArrayOutputStream(); byte[] buff = new byte[1000];// buff用于存放循环读取的临时数据 int rc; while ((rc = httpEntity.getContent().read(buff, 0, 1000)) > 0) stream.write(buff, 0, rc); return stream.toByteArray();// ByteArrayOutputStream转换为byte[] } }
UTF-8
Java
8,617
java
HttpServlet.java
Java
[ { "context": "rrayList;\nimport java.util.List;\n\n/**\n * @author : ylwei\n * @time : 2017/9/19\n * @description :\n */\n@Servi", "end": 992, "score": 0.9996793866157532, "start": 987, "tag": "USERNAME", "value": "ylwei" } ]
null
[]
package com.leap.network; import com.leap.config.MarsConfig; import com.leap.handle.exception.base.BaseException; import com.leap.model.VoiceParam; import com.leap.model.baidu.BVoice; import com.leap.model.baidu.SToken; import com.leap.model.enums.TtsCode; import com.leap.model.tuling.BChat; import com.leap.util.GsonUtil; import com.leap.util.IsEmpty; import io.jsonwebtoken.impl.Base64Codec; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.springframework.stereotype.Service; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * @author : ylwei * @time : 2017/9/19 * @description : */ @Service public class HttpServlet { public String getToken() throws IOException { String url = MarsConfig.BAI_DU_TOKEN_URL // + "?grant_type=client_credentials" // + "&client_id=" + MarsConfig.BAI_DU_API_KEY // + "&client_secret=" + MarsConfig.BAI_DU_SECRET_KEY; // 创建HttpClient对象 HttpClient client = HttpClients.createDefault(); // 创建GET请求(在构造器中传入URL字符串即可) HttpGet get = new HttpGet(url); // 调用HttpClient对象的execute方法获得响应 HttpResponse response = client.execute(get); // 调用HttpResponse对象的getEntity方法得到响应实体 HttpEntity httpEntity = response.getEntity(); // 使用EntityUtils工具类得到响应的字符串表示 String result = EntityUtils.toString(httpEntity, "utf-8"); SToken token = GsonUtil.parse(result, SToken.class); MarsConfig.BAI_DU_TOKEN = token.getAccess_token(); return MarsConfig.BAI_DU_TOKEN; } /** * 图灵网络请求 * * @param chat * 入参 * @return 返回字符串 * @throws IOException * IO异常 */ public String tuLingQuest(BChat chat) throws IOException { // 创建HttpClient对象 HttpClient client = HttpClients.createDefault(); // 创建POST请求 HttpPost post = new HttpPost(MarsConfig.TU_LING_URL); // 创建一个List容器,用于存放基本键值对(基本键值对即:参数名-参数值) List<BasicNameValuePair> parameters = new ArrayList<>(); parameters.add(new BasicNameValuePair("key", MarsConfig.TU_LING_KEY)); parameters.add(new BasicNameValuePair("userid", chat.getUserid().substring(0, chat.getUserid().length() - 6))); parameters.add(new BasicNameValuePair("info", chat.getInfo())); if (!IsEmpty.string(chat.getLoc())) parameters.add(new BasicNameValuePair("loc", chat.getLoc())); // 向POST请求中添加消息实体 post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8")); // 得到响应并转化成字符串 HttpResponse response = client.execute(post); HttpEntity httpEntity = response.getEntity(); return EntityUtils.toString(httpEntity, "utf-8"); } /** * 百度语音转文字 * * @param voice * 入参 * @return 返回字符串 * @throws IOException * IO异常 */ public String vop(VoiceParam param, String token, BVoice voice) throws IOException { // 创建HttpClient对象 HttpClient client = HttpClients.createDefault(); // 创建POST请求 HttpPost post = new HttpPost(MarsConfig.BAI_DU_VOP_URL); // 创建一个List容器,用于存放基本键值对(基本键值对即:参数名-参数值) List<BasicNameValuePair> parameters = new ArrayList<>(); // 语音文件的格式,pcm 或者 wav 或者 amr。不区分大小写 parameters.add(new BasicNameValuePair("format", voice.getFormat())); // 采样率,支持 8000 或者 16000 parameters.add(new BasicNameValuePair("rate", param.getRate())); // 声道数,仅支持单声道,请填写固定值 1 parameters.add(new BasicNameValuePair("channel", param.getChannel())); // 用户唯一标识,用来区分用户,计算UV值。建议填写能区分用户的机器 MAC 地址或 IMEI 码,长度为60字符以内。 parameters.add(new BasicNameValuePair("cuid", param.getUserId())); // 开放平台获取到的开发者access_token parameters.add(new BasicNameValuePair("token", token)); // 语种选择,默认中文(zh)。 中文=zh、粤语=ct、英文=en,不区分大小写。 parameters.add(new BasicNameValuePair("lan", param.getLan())); // 语音下载地址,与callback连一起使用,确保百度服务器可以访问 // parameters.add(new BasicNameValuePair("url", "")); // 识别结果回调地址,确保百度服务器可以访问 // parameters.add(new BasicNameValuePair("callback", "")); // 真实的语音数据 ,需要进行base64 编码。与len参数连一起使用。 String temp = Base64Codec.BASE64.encode(voice.getCode()); parameters.add(new BasicNameValuePair("speech", temp)); // 原始语音长度,单位字节 parameters.add(new BasicNameValuePair("len", String.valueOf(voice.getLen()))); // 向POST请求中添加消息实体 post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8")); // 得到响应并转化成字符串 HttpResponse response = client.execute(post); HttpEntity httpEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() != 200) throw new BaseException(response.getStatusLine().getStatusCode(), TtsCode.getEnum(response.getStatusLine().getStatusCode()).getMessage()); return EntityUtils.toString(httpEntity, "utf-8"); } /** * 百度文字转语音 * * @param value * 入参 * @return 返回字符串 * @throws IOException * IO异常 */ public byte[] tts(VoiceParam param, String token, String value) throws IOException, BaseException { // 创建HttpClient对象 HttpClient client = HttpClients.createDefault(); // 创建POST请求 HttpPost post = new HttpPost(MarsConfig.BAI_DU_TTS_URL); // 创建一个List容器,用于存放基本键值对(基本键值对即:参数名-参数值) List<BasicNameValuePair> parameters = new ArrayList<>(); // 合成的文本,使用UTF-8编码,请注意文本长度必须小于1024字节 parameters.add(new BasicNameValuePair("tex", value)); // 语言选择,目前只有中英文混合模式,填写固定值zh parameters.add(new BasicNameValuePair("lan", param.getLan())); // 开放平台获取到的开发者access_token parameters.add(new BasicNameValuePair("tok", token)); // 客户端类型选择,web端填写固定值1 parameters.add(new BasicNameValuePair("ctp", param.getCtp())); // 用户唯一标识,用来区分用户,计算UV值。建议填写能区分用户的机器 MAC 地址或 IMEI 码,长度为60字符以内。 parameters.add(new BasicNameValuePair("cuid", param.getUserId())); // 语速,取值0-9,默认为5中语速 parameters.add(new BasicNameValuePair("spd", param.getSpd())); // 音调,取值0-9,默认为5中语调 parameters.add(new BasicNameValuePair("pit", param.getPit())); // 音量,取值0-15,默认为5中音量 parameters.add(new BasicNameValuePair("vol", param.getVol())); // 发音人选择, 0为普通女声,1为普通男声,3为情感合成-度逍遥,4为情感合成-度丫丫,默认为普通女声 parameters.add(new BasicNameValuePair("per", param.getPer())); // 向POST请求中添加消息实体 post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8")); // 得到响应并转化成字符串 HttpResponse response = client.execute(post); HttpEntity httpEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() != 200) throw new BaseException(response.getStatusLine().getStatusCode(), TtsCode.getEnum(response.getStatusLine().getStatusCode()).getMessage()); // InputStream转换为byte[] ByteArrayOutputStream stream = new ByteArrayOutputStream(); byte[] buff = new byte[1000];// buff用于存放循环读取的临时数据 int rc; while ((rc = httpEntity.getContent().read(buff, 0, 1000)) > 0) stream.write(buff, 0, rc); return stream.toByteArray();// ByteArrayOutputStream转换为byte[] } }
8,617
0.702317
0.692052
187
37.5508
22.402046
86
false
false
0
0
0
0
0
0
0.68984
false
false
7
a7fe03df6e74c7b3a819636061aae03fa36b058f
29,961,691,918,017
8a19e5c48f56452031d0c50db3abae6284128161
/UpBup/src/main/java/com/main/upbup/locators/CareGiverLocators.java
1d91545a797fca8f95ea1bc5a426402adee86ef7
[]
no_license
ssrivastava90/Practice-Java-POM
https://github.com/ssrivastava90/Practice-Java-POM
8013bc68bceeb5897ebc71ed7fa620579dffba14
1a5aba2ca666423208035e1f88ac49a36d404959
refs/heads/master
2021-04-06T04:23:24.453000
2018-04-11T14:54:05
2018-04-11T14:54:05
124,728,406
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.main.upbup.locators; public class CareGiverLocators extends CommonLocators { public static final String careGiver = ""; }
UTF-8
Java
140
java
CareGiverLocators.java
Java
[]
null
[]
package com.main.upbup.locators; public class CareGiverLocators extends CommonLocators { public static final String careGiver = ""; }
140
0.771429
0.771429
6
22.333334
22.997585
55
false
false
0
0
0
0
0
0
0.333333
false
false
7
59154c70675abc872cddc2690b7ed3cef7335b0d
16,174,846,852,592
3be34c3b74f751d417dd44ac6ef44496fed6eeb8
/leetcode/136_SingleNumber.java
73ffee09b19f8523d77f3517a7091d39646aed7a
[]
no_license
haeungun/algorithm
https://github.com/haeungun/algorithm
7d47237b3d90e13346e0f67e0d18f73abc6bff1b
7cb959a2cb877f7c6f7f9b61bf0a8d65692aafbe
refs/heads/master
2021-06-10T00:04:44.030000
2021-04-22T15:08:41
2021-04-22T15:08:41
133,589,723
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * 출처: https://leetcode.com/problems/single-number */ // Solution 1 class Solution1 { public int singleNumber(int[] nums) { Arrays.sort(nums); return this.findByBinary(nums); } private int findByBinary(int[] nums) { int l = 0; int r = nums.length - 1; int m = 0; while (l < r) { m = (l + r) / 2; if (m % 2 == 0) { if (nums[m] == nums[m - 1]) { r = m; } else if (nums[m] == nums[m + 1]) { l = m; } else { return nums[m]; } } else { if (nums[m] == nums[m - 1]) { l = m + 1; } else if (nums[m] == nums[m + 1]) { r = m - 1; } else { return nums[m]; } } } return nums[(l + r) / 2]; } } // Solution 2 class Solution2 { public int singleNumber(int[] nums) { Arrays.sort(nums); for (int i = 0; i < nums.length - 2; i += 2) { if (nums[i] != nums[i + 1]) return nums[i]; } return nums[nums.length-1]; } }
UTF-8
Java
1,274
java
136_SingleNumber.java
Java
[]
null
[]
/** * 출처: https://leetcode.com/problems/single-number */ // Solution 1 class Solution1 { public int singleNumber(int[] nums) { Arrays.sort(nums); return this.findByBinary(nums); } private int findByBinary(int[] nums) { int l = 0; int r = nums.length - 1; int m = 0; while (l < r) { m = (l + r) / 2; if (m % 2 == 0) { if (nums[m] == nums[m - 1]) { r = m; } else if (nums[m] == nums[m + 1]) { l = m; } else { return nums[m]; } } else { if (nums[m] == nums[m - 1]) { l = m + 1; } else if (nums[m] == nums[m + 1]) { r = m - 1; } else { return nums[m]; } } } return nums[(l + r) / 2]; } } // Solution 2 class Solution2 { public int singleNumber(int[] nums) { Arrays.sort(nums); for (int i = 0; i < nums.length - 2; i += 2) { if (nums[i] != nums[i + 1]) return nums[i]; } return nums[nums.length-1]; } }
1,274
0.352756
0.335433
52
23.423077
15.34519
54
false
false
0
0
0
0
0
0
0.346154
false
false
7
f16905af225b51723457c37d753e4a3ef5990bc3
14,362,370,689,271
9bd51be66af220437a1657bf7f2922547765c291
/app/src/main/java/com/moritz/android/locationfinder/StartFragment.java
dde36d7c797158ff084642309805034c3c4fd12c
[]
no_license
Moritz-Bergemann/LocationFinderApp
https://github.com/Moritz-Bergemann/LocationFinderApp
4c44d96df1da40a1084c837b215370fd6d10262e
010957fcf240f1360548e28682d880b3a1748b71
refs/heads/master
2022-11-19T15:04:07.329000
2020-07-21T07:32:18
2020-07-21T07:32:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.moritz.android.locationfinder; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; import com.google.android.material.snackbar.Snackbar; /** * A simple {@link Fragment} subclass. * Use the {@link StartFragment#newInstance} factory method to * create an instance of this fragment. */ public class StartFragment extends Fragment { private static final String TAG = "start_fragment"; public StartFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @return A new instance of fragment StartFragment. */ // TODO: Rename and change types and number of parameters public static StartFragment newInstance() { StartFragment fragment = new StartFragment(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { //Argument parsing stuff here } } //This is called when the actual VIEW is created. You can't do stuff like assign values to // buttons in onCreate() because they haven't been created yet (I think this is done so that // you can keep a fragment alive while being able to kill its view to save resources) @Override public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_start, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); //Adding buttons and whatnot view.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getActivity(), R.string.button_1_toast, Toast.LENGTH_SHORT).show(); } }); view.findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //TODO } }); } }
UTF-8
Java
2,579
java
StartFragment.java
Java
[]
null
[]
package com.moritz.android.locationfinder; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; import com.google.android.material.snackbar.Snackbar; /** * A simple {@link Fragment} subclass. * Use the {@link StartFragment#newInstance} factory method to * create an instance of this fragment. */ public class StartFragment extends Fragment { private static final String TAG = "start_fragment"; public StartFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @return A new instance of fragment StartFragment. */ // TODO: Rename and change types and number of parameters public static StartFragment newInstance() { StartFragment fragment = new StartFragment(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { //Argument parsing stuff here } } //This is called when the actual VIEW is created. You can't do stuff like assign values to // buttons in onCreate() because they haven't been created yet (I think this is done so that // you can keep a fragment alive while being able to kill its view to save resources) @Override public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_start, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); //Adding buttons and whatnot view.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getActivity(), R.string.button_1_toast, Toast.LENGTH_SHORT).show(); } }); view.findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //TODO } }); } }
2,579
0.672354
0.67119
79
31.658228
28.076246
98
false
false
0
0
0
0
0
0
0.35443
false
false
7
8ea8b96032cb62837c0d2f710c56d5785760caf9
20,822,001,496,376
43c4aa6bf1304de716d4cf511a7d21c2b82596fe
/app/src/main/java/com/dhn/peanut/shots/ShotPresenter.java
a8db209688d47823ea31bb058fa6c712d3b635d4
[]
no_license
zjpjohn/Peanut
https://github.com/zjpjohn/Peanut
4f7cd834e1ce1231038f16418e72f8d68c546790
a8235060f2a80750505324da0a50d48785869f52
refs/heads/master
2020-04-06T03:42:44.630000
2016-07-30T13:37:56
2016-07-30T13:37:56
64,715,162
1
0
null
true
2016-08-02T01:53:05
2016-08-02T01:53:03
2016-08-02T01:53:05
2016-07-30T13:38:08
11,077
0
0
0
Java
null
null
package com.dhn.peanut.shots; import android.util.Log; import com.dhn.peanut.data.Shot; import com.dhn.peanut.data.base.LoadShotsCallback; import com.dhn.peanut.data.base.ShotDataSource; import java.util.List; /** * Created by DHN on 2016/5/31. */ public class ShotPresenter implements ShotsContract.Presenter { public static final String TAG = "ShortPresenter"; private ShotsContract.View mShotView; private ShotsContract.View mDebutsView; private ShotsContract.View mGifView; private ShotDataSource mShotDataSource; private int shotsPage = 1; private int debutsPage = 1; private int gifsPage = 1; public ShotPresenter(ShotsContract.View shotView, ShotsContract.View debutsView, ShotsContract.View gifView, ShotDataSource dataSource) { mShotView = shotView; mDebutsView = debutsView; mGifView = gifView; mShotDataSource = dataSource; mShotView.setPresenter(this); mDebutsView.setPresenter(this); mGifView.setPresenter(this); } @Override public void loadShots(boolean isFirstPage) { if (isFirstPage == true) { shotsPage = 1; } if (shotsPage == 1) { mShotView.showLoading(); } mShotDataSource.getShots(null, shotsPage, new LoadShotsCallback() { @Override public void onShotsLoaded(List<Shot> shots) { mShotView.hideLoading(); mShotView.showLoadingIndicator(false); mShotView.showShots(shots); //Log.e(TAG, "shots: " + shots); } @Override public void onDataNotAvailable() { } }); shotsPage++; } @Override public void loadDebuts(boolean isFirstPage) { if (isFirstPage == true) { debutsPage = 1; } if (debutsPage == 1) { mDebutsView.showLoading(); } mShotDataSource.getDebuts(null, debutsPage, new LoadShotsCallback() { @Override public void onShotsLoaded(List<Shot> debuts) { mDebutsView.hideLoading(); mDebutsView.showLoadingIndicator(false); mDebutsView.showShots(debuts); } @Override public void onDataNotAvailable() { } }); debutsPage++; } @Override public void loadGifs(boolean isFirstPage) { if (isFirstPage == true) { gifsPage = 1; } if (gifsPage == 1) { mGifView.showLoading(); } mShotDataSource.getGifs(null, gifsPage, new LoadShotsCallback() { @Override public void onShotsLoaded(List<Shot> gifs) { mGifView.hideLoading(); mGifView.showLoadingIndicator(false); mGifView.showShots(gifs); } @Override public void onDataNotAvailable() { } }); gifsPage++; } }
UTF-8
Java
3,124
java
ShotPresenter.java
Java
[ { "context": "Source;\n\nimport java.util.List;\n\n/**\n * Created by DHN on 2016/5/31.\n */\npublic class ShotPresenter impl", "end": 237, "score": 0.9991658926010132, "start": 234, "tag": "USERNAME", "value": "DHN" } ]
null
[]
package com.dhn.peanut.shots; import android.util.Log; import com.dhn.peanut.data.Shot; import com.dhn.peanut.data.base.LoadShotsCallback; import com.dhn.peanut.data.base.ShotDataSource; import java.util.List; /** * Created by DHN on 2016/5/31. */ public class ShotPresenter implements ShotsContract.Presenter { public static final String TAG = "ShortPresenter"; private ShotsContract.View mShotView; private ShotsContract.View mDebutsView; private ShotsContract.View mGifView; private ShotDataSource mShotDataSource; private int shotsPage = 1; private int debutsPage = 1; private int gifsPage = 1; public ShotPresenter(ShotsContract.View shotView, ShotsContract.View debutsView, ShotsContract.View gifView, ShotDataSource dataSource) { mShotView = shotView; mDebutsView = debutsView; mGifView = gifView; mShotDataSource = dataSource; mShotView.setPresenter(this); mDebutsView.setPresenter(this); mGifView.setPresenter(this); } @Override public void loadShots(boolean isFirstPage) { if (isFirstPage == true) { shotsPage = 1; } if (shotsPage == 1) { mShotView.showLoading(); } mShotDataSource.getShots(null, shotsPage, new LoadShotsCallback() { @Override public void onShotsLoaded(List<Shot> shots) { mShotView.hideLoading(); mShotView.showLoadingIndicator(false); mShotView.showShots(shots); //Log.e(TAG, "shots: " + shots); } @Override public void onDataNotAvailable() { } }); shotsPage++; } @Override public void loadDebuts(boolean isFirstPage) { if (isFirstPage == true) { debutsPage = 1; } if (debutsPage == 1) { mDebutsView.showLoading(); } mShotDataSource.getDebuts(null, debutsPage, new LoadShotsCallback() { @Override public void onShotsLoaded(List<Shot> debuts) { mDebutsView.hideLoading(); mDebutsView.showLoadingIndicator(false); mDebutsView.showShots(debuts); } @Override public void onDataNotAvailable() { } }); debutsPage++; } @Override public void loadGifs(boolean isFirstPage) { if (isFirstPage == true) { gifsPage = 1; } if (gifsPage == 1) { mGifView.showLoading(); } mShotDataSource.getGifs(null, gifsPage, new LoadShotsCallback() { @Override public void onShotsLoaded(List<Shot> gifs) { mGifView.hideLoading(); mGifView.showLoadingIndicator(false); mGifView.showShots(gifs); } @Override public void onDataNotAvailable() { } }); gifsPage++; } }
3,124
0.5621
0.556978
131
22.847328
20.722622
77
false
false
0
0
0
0
0
0
0.40458
false
false
7
629caa181751793f274130d81e949ea4ebdff303
19,378,892,444,765
66f628f4066f38e661b4bb7c604865c5b064bc1d
/src/main/java/com/risk/riskybackend/service/RiskServiceImpl.java
febc086d4e04a1b9a12175d2956158bf1231ec3a
[]
no_license
AndersNordin/riskyapp-backend
https://github.com/AndersNordin/riskyapp-backend
e8f3872362bbfaccce00aba1aec3c8a60dcaae1a
1a99b74188b2b0b110503266be16ce1fb551746b
refs/heads/master
2020-08-08T16:53:25.098000
2020-08-06T08:35:01
2020-08-06T08:35:01
213,872,827
0
0
null
false
2020-08-05T09:06:57
2019-10-09T09:12:33
2020-08-04T20:03:42
2020-08-05T09:06:56
118
0
0
0
Java
false
false
package com.risk.riskybackend.service; import com.risk.riskybackend.model.Risk; import com.risk.riskybackend.repository.RiskRepository; import org.springframework.stereotype.Service; import java.util.List; @Service public class RiskServiceImpl implements RiskService{ private RiskRepository riskRepo; public RiskServiceImpl(RiskRepository riskRepo) { this.riskRepo = riskRepo; } @Override public List<Risk> getAll() { return riskRepo.findAll(); } @Override public Risk get(String id) { return riskRepo.findById(id).orElse(null); } @Override public void delete(String id) { riskRepo.deleteById(id); } @Override public boolean doesExist(String id) { return riskRepo.existsById(id); } @Override public void create(Risk risk) { riskRepo.insert(risk); } @Override public void update(Risk risk) { riskRepo.save(risk); } }
UTF-8
Java
955
java
RiskServiceImpl.java
Java
[]
null
[]
package com.risk.riskybackend.service; import com.risk.riskybackend.model.Risk; import com.risk.riskybackend.repository.RiskRepository; import org.springframework.stereotype.Service; import java.util.List; @Service public class RiskServiceImpl implements RiskService{ private RiskRepository riskRepo; public RiskServiceImpl(RiskRepository riskRepo) { this.riskRepo = riskRepo; } @Override public List<Risk> getAll() { return riskRepo.findAll(); } @Override public Risk get(String id) { return riskRepo.findById(id).orElse(null); } @Override public void delete(String id) { riskRepo.deleteById(id); } @Override public boolean doesExist(String id) { return riskRepo.existsById(id); } @Override public void create(Risk risk) { riskRepo.insert(risk); } @Override public void update(Risk risk) { riskRepo.save(risk); } }
955
0.677487
0.677487
45
20.222221
18.987585
61
false
false
0
0
0
0
0
0
0.288889
false
false
7
32f72845aba86feace1ba682f23f83c01b62fa04
6,090,263,632,745
5297e664a22201b7b136358fc3046e5558881d99
/DiguitsFX/src/main/java/com/diguits/javafx/undo/ChangeQueue.java
cb70f7faab60330b0217a7b7e1b8563f379b90c6
[ "Apache-2.0" ]
permissive
diguits/domainmodeldesigner
https://github.com/diguits/domainmodeldesigner
804b2210f3b4f2fa6932a09d2299e7998ee8a116
212ea0ce34f69e1eb08be7dcb52f45fe65ec82db
refs/heads/master
2021-08-26T08:32:56.588000
2017-11-15T15:16:59
2017-11-15T15:16:59
110,843,509
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.diguits.javafx.undo; import com.diguits.javafx.undo.changes.Change; import javafx.beans.property.ReadOnlyBooleanProperty; public interface ChangeQueue { ReadOnlyBooleanProperty hasNextProperty(); boolean hasNext(); ReadOnlyBooleanProperty hasPrevProperty(); boolean hasPrev(); Change next(); Change prev(); Change popPrev(); void push(Change change); Change getCurrent(); void clean(); }
UTF-8
Java
423
java
ChangeQueue.java
Java
[]
null
[]
package com.diguits.javafx.undo; import com.diguits.javafx.undo.changes.Change; import javafx.beans.property.ReadOnlyBooleanProperty; public interface ChangeQueue { ReadOnlyBooleanProperty hasNextProperty(); boolean hasNext(); ReadOnlyBooleanProperty hasPrevProperty(); boolean hasPrev(); Change next(); Change prev(); Change popPrev(); void push(Change change); Change getCurrent(); void clean(); }
423
0.761229
0.761229
28
14.107142
16.674059
53
false
false
0
0
0
0
0
0
0.821429
false
false
7
ac564b115df9f186e0c53727484126e297630825
10,170,482,565,362
bd08e5c4e3cd02bb934abaf6212b023a2c1cc4be
/blade-ajax/src/main/java/com/blade/demo/ajax/AjaxApplication.java
311d6739e88eee00baf76142ea4d5d5a55fa57a6
[]
no_license
zhaoweih/EasyCourse-Back-End
https://github.com/zhaoweih/EasyCourse-Back-End
6c97387d9b4ff1c973fd8122075b0be0954de7a8
eed1eb17079e59dc0a0633e4dec33fca8df04734
refs/heads/master
2021-06-19T17:00:38.416000
2020-12-12T08:22:38
2020-12-12T08:22:38
136,622,379
1
1
null
false
2020-12-12T08:23:46
2018-06-08T13:26:51
2020-12-12T08:23:35
2020-12-12T08:23:45
127
1
1
3
HTML
false
false
package com.blade.demo.ajax; import com.blade.Blade; /** * @author biezhi * @date 2017/9/28 */ public class AjaxApplication { public static void main(String[] args) { Blade.of().start(AjaxApplication.class, args); } }
UTF-8
Java
240
java
AjaxApplication.java
Java
[ { "context": "emo.ajax;\n\nimport com.blade.Blade;\n\n/**\n * @author biezhi\n * @date 2017/9/28\n */\npublic class AjaxApplicati", "end": 76, "score": 0.9995136857032776, "start": 70, "tag": "USERNAME", "value": "biezhi" } ]
null
[]
package com.blade.demo.ajax; import com.blade.Blade; /** * @author biezhi * @date 2017/9/28 */ public class AjaxApplication { public static void main(String[] args) { Blade.of().start(AjaxApplication.class, args); } }
240
0.654167
0.625
14
16.142857
17.058125
54
false
false
0
0
0
0
0
0
0.285714
false
false
7
b4188c77fa2d04952fbee0f6b9823f30fead6dff
33,157,147,556,193
86bfd3f3a253191f6dbbac722242feb4a6d68be7
/base/src/test/java/com/xcj/common/HashMapTtest.java
26c7142c9cd18c55e6e460a831d2d0b566b936ea
[]
no_license
duanlizhi/base
https://github.com/duanlizhi/base
b8ee7b739d5b99a34928bc9f2266f3dae121374f
f258aebf619901613bb9e1a40b6697907d10228c
refs/heads/master
2020-07-06T10:46:38.563000
2016-08-19T09:05:56
2016-08-19T09:05:56
66,068,328
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** *<dl> *<dt><span class="strong">方法说明:</span></dt> *<dd>主要是实现了什么功能</dd> *</dl> *<dl><dt><span class="strong">创建时间:</span></dt> *<dd> 2016年3月3日 上午10:57:56</dd></dl> *</dl> *@param <T> 对象类型 *@param entity 对象 *@return boolean true/false *@throws Exception XX异常 */ package com.xcj.common; import java.util.HashMap; import org.junit.Test; /** * <dl> * <dt><span class="strong">方法说明:</span></dt> * <dd>主要是实现了什么功能</dd> * </dl> * <dl> * <dt><span class="strong">创建时间:</span></dt> * <dd>2016年3月3日 上午10:57:56</dd> * </dl> * </dl> * * @param <T> * 对象类型 * @param entity * 对象 * @return boolean true/false * @throws Exception * XX异常 */ public class HashMapTtest { @Test public void testTotalHashMap(){ testHashMap1(); testHashMap2(); testHashMap3(); testHashMap4(); testHashMap5(); testHashMap6(); testHashMap7(); } public static void testHashMap1(){ //System.out.println(1 << 10); Long s1=System.currentTimeMillis(); HashMap<String, Object> map =new HashMap<String, Object>(32,3f); for (int i = 0; i < 10000; i++) { map.put(i+"", i+""); } System.out.println(map.size()); Long s2= System.currentTimeMillis(); System.out.println("testHashMap1:"+(s2-s1)); } public static void testHashMap2(){ //System.out.println(1 << 10); Long s1=System.currentTimeMillis(); HashMap<String, Object> map =new HashMap<String, Object>(32,2f); for (int i = 0; i < 10000; i++) { map.put(i+"", i+""); } System.out.println(map.size()); Long s2= System.currentTimeMillis(); System.out.println("testHashMap2:"+(s2-s1)); } public static void testHashMap3(){ //System.out.println(1 << 10); Long s1=System.currentTimeMillis(); HashMap<String, Object> map =new HashMap<String, Object>(32,1f); for (int i = 0; i < 10000; i++) { map.put(i+"", i+""); } System.out.println(map.size()); Long s2= System.currentTimeMillis(); System.out.println("testHashMap3:"+(s2-s1)); } public static void testHashMap4(){ System.out.println(1 << 5); Long s1=System.currentTimeMillis(); HashMap<String, Object> map =new HashMap<String, Object>(32,0.75f); for (int i = 0; i < 10000; i++) { map.put(i+"", i+""); } System.out.println(map.size()); Long s2= System.currentTimeMillis(); System.out.println("testHashMap4:"+(s2-s1)); } public static void testHashMap5(){ //System.out.println(1 << 10); Long s1=System.currentTimeMillis(); HashMap<String, Object> map =new HashMap<String, Object>(); for (int i = 0; i < 10000; i++) { map.put(i+"", i+""); } System.out.println(map.size()); Long s2= System.currentTimeMillis(); System.out.println("testHashMap5:"+(s2-s1)); } public static void testHashMap6(){ System.out.println(1 << 5); Long s1=System.currentTimeMillis(); HashMap<String, Object> map =new HashMap<String, Object>(32,0.75f); for (int i = 0; i < 10000; i++) { map.put(i+"", i+""); } for (int i = 10000; i < 10000; i++) { map.put(i+"", i+""); } System.out.println(map.size()); Long s2= System.currentTimeMillis(); System.out.println("testHashMap6:"+(s2-s1)); } public static void testHashMap7(){ System.out.println(1 << 5); Long s1=System.currentTimeMillis(); HashMap<String, Object> map =new HashMap<String, Object>(32,0.75f); for (int i = 0; i < 10000; i++) { map.put(i+"", i+""); } System.out.println(map.size()); Long s2= System.currentTimeMillis(); System.out.println("testHashMap7:"+(s2-s1)); } }
UTF-8
Java
3,645
java
HashMapTtest.java
Java
[]
null
[]
/** *<dl> *<dt><span class="strong">方法说明:</span></dt> *<dd>主要是实现了什么功能</dd> *</dl> *<dl><dt><span class="strong">创建时间:</span></dt> *<dd> 2016年3月3日 上午10:57:56</dd></dl> *</dl> *@param <T> 对象类型 *@param entity 对象 *@return boolean true/false *@throws Exception XX异常 */ package com.xcj.common; import java.util.HashMap; import org.junit.Test; /** * <dl> * <dt><span class="strong">方法说明:</span></dt> * <dd>主要是实现了什么功能</dd> * </dl> * <dl> * <dt><span class="strong">创建时间:</span></dt> * <dd>2016年3月3日 上午10:57:56</dd> * </dl> * </dl> * * @param <T> * 对象类型 * @param entity * 对象 * @return boolean true/false * @throws Exception * XX异常 */ public class HashMapTtest { @Test public void testTotalHashMap(){ testHashMap1(); testHashMap2(); testHashMap3(); testHashMap4(); testHashMap5(); testHashMap6(); testHashMap7(); } public static void testHashMap1(){ //System.out.println(1 << 10); Long s1=System.currentTimeMillis(); HashMap<String, Object> map =new HashMap<String, Object>(32,3f); for (int i = 0; i < 10000; i++) { map.put(i+"", i+""); } System.out.println(map.size()); Long s2= System.currentTimeMillis(); System.out.println("testHashMap1:"+(s2-s1)); } public static void testHashMap2(){ //System.out.println(1 << 10); Long s1=System.currentTimeMillis(); HashMap<String, Object> map =new HashMap<String, Object>(32,2f); for (int i = 0; i < 10000; i++) { map.put(i+"", i+""); } System.out.println(map.size()); Long s2= System.currentTimeMillis(); System.out.println("testHashMap2:"+(s2-s1)); } public static void testHashMap3(){ //System.out.println(1 << 10); Long s1=System.currentTimeMillis(); HashMap<String, Object> map =new HashMap<String, Object>(32,1f); for (int i = 0; i < 10000; i++) { map.put(i+"", i+""); } System.out.println(map.size()); Long s2= System.currentTimeMillis(); System.out.println("testHashMap3:"+(s2-s1)); } public static void testHashMap4(){ System.out.println(1 << 5); Long s1=System.currentTimeMillis(); HashMap<String, Object> map =new HashMap<String, Object>(32,0.75f); for (int i = 0; i < 10000; i++) { map.put(i+"", i+""); } System.out.println(map.size()); Long s2= System.currentTimeMillis(); System.out.println("testHashMap4:"+(s2-s1)); } public static void testHashMap5(){ //System.out.println(1 << 10); Long s1=System.currentTimeMillis(); HashMap<String, Object> map =new HashMap<String, Object>(); for (int i = 0; i < 10000; i++) { map.put(i+"", i+""); } System.out.println(map.size()); Long s2= System.currentTimeMillis(); System.out.println("testHashMap5:"+(s2-s1)); } public static void testHashMap6(){ System.out.println(1 << 5); Long s1=System.currentTimeMillis(); HashMap<String, Object> map =new HashMap<String, Object>(32,0.75f); for (int i = 0; i < 10000; i++) { map.put(i+"", i+""); } for (int i = 10000; i < 10000; i++) { map.put(i+"", i+""); } System.out.println(map.size()); Long s2= System.currentTimeMillis(); System.out.println("testHashMap6:"+(s2-s1)); } public static void testHashMap7(){ System.out.println(1 << 5); Long s1=System.currentTimeMillis(); HashMap<String, Object> map =new HashMap<String, Object>(32,0.75f); for (int i = 0; i < 10000; i++) { map.put(i+"", i+""); } System.out.println(map.size()); Long s2= System.currentTimeMillis(); System.out.println("testHashMap7:"+(s2-s1)); } }
3,645
0.614598
0.567168
146
23.116438
17.973539
69
false
false
0
0
0
0
0
0
1.986301
false
false
7
2eea7b86fbcbc03e0c27a6685d6ce5b3cd4c583c
20,212,116,101,247
a8b53f0843998cfe7e0eb59ef5d6e4caf65214a4
/src/utility/MyDate.java
381a2cf5f4e1dfb7cf7753800425acad49a90b23
[]
no_license
Berkec98/School-Management-System
https://github.com/Berkec98/School-Management-System
1c9c721c00923777867ce15599a7312792b07528
9b12dd20bd90891801737398c3168b7eb0731e04
refs/heads/master
2023-07-05T21:48:12.021000
2021-08-10T15:13:36
2021-08-10T15:13:36
394,698,576
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package utility; import java.text.SimpleDateFormat; import java.time.*; import java.util.Calendar; import java.util.Date; /** * TARİH CONVERT CLASS * Bu sınıf; tarih değerini kullanıcıdan almakta ve kendisinde olan myDate değşkenine yükleyip daha sonra kullanıcıya tarih olarak sunmaktadır * sınıfın avantajları ise aldığı tarihin kısıtlı olmaması hemen hemen bütün tarih formatlarını alabilmesi ve kullanıcının istediği tarih türüne dönüştürmesi * <p> * <p> * A) Kabul Ettiği Tarih Türleri: 1) MyDate(util.Date) * 2) MyDate(LocalDate) * (YAPILANDIRICILARI) 3) MyDate(sql.Date) * 4) MyDate(String date, String format) * 5) MyDate(int gun, int ay, int yil) * 6) MyDate(Long date) * <p> * <p> * B) Getter Metodları 1) getMyDateAsCalendar() * 2) getMyDateAsLocalDate() * 3) getMyDateAsUtilDate() * 4) getMyDateAsSQLDate() * 5) getMyDateAsString(String format) * 6) getMyDateAsLong() * 7) getGun() * 8) getAy() * 9) getYil() * <p> * <p> * C) Diğer Metodları 1) void add(int whatAdd, int piece) * 2) Long diffDates(Date dateCikarilan) */ public class MyDate { private java.util.Date myDate; public MyDate(java.util.Date myDate) { this.myDate = myDate; } public MyDate(LocalDate localDate) { if (localDate == null) this.myDate = null; else this.myDate = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); } public MyDate(LocalDateTime localDateTime) { ZonedDateTime z = localDateTime.atZone(ZoneId.systemDefault()); try { this.myDate = Date.from(z.toInstant()); } catch (Exception e) { this.myDate = null; } } public MyDate(java.sql.Date myDate) { try { this.myDate = new Date(myDate.getTime()); } catch (Exception e) { this.myDate = null; } } public MyDate(Long date) { try { myDate = new Date(date); } catch (Exception e) { this.myDate = null; } } /* Bu metod MyDate(String date, String format) yapılandırıcısı tarafından kullanılmaktadır format üret fonksiyonu sayesinde kullanıcının runtime gireceği her format kabul edilecektir fonksiyon işaret olarak * karakterini aramaktadır örnek: 12/10/2019 5/5/2005 12-10-2019 12.10.2019*/ private String sembolleriDuzelt(String girilenTarih) { girilenTarih=girilenTarih.replace(".", "/"); //girilen tarihteki nokta ve tireler / ile değiştiriliyor girilenTarih=girilenTarih.replace("-", "/"); return girilenTarih; } //format üret fonksiyonu sayesinde kullanıcının runtime gireceği her format kabul edilecektir public MyDate(String date, String format) { if(date==null||date.isEmpty()){ this.myDate=null; return; } date=sembolleriDuzelt(date.trim()); try { SimpleDateFormat sdf = new SimpleDateFormat(format); this.myDate = sdf.parse(date); } catch (Exception ex) { //myDate=null; //önemli silme.. bazı yerler buna bakarak karar veriyor this.myDate = null; } } public MyDate(int gun, int ay, int yil) { if (gun < 1 || gun > 31 || ay < 1 || ay > 12 || yil < 2000) { myDate = null; return; } Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DATE, gun); calendar.set(Calendar.MONTH, ay - 1); calendar.set(Calendar.YEAR, yil); this.myDate = calendar.getTime(); } public Calendar getMyDateAsCalendar() { Calendar cal = Calendar.getInstance(); try { cal.setTime(myDate); } catch (Exception e) { return null; } return cal; } public LocalDateTime getMyDateAsLocalDateTime() { return myDate == null ? null : LocalDateTime.ofInstant(myDate.toInstant(), ZoneId.systemDefault()); } public LocalDate getMyDateAsLocalDate() { return myDate == null ? null : Instant.ofEpochMilli(myDate.getTime()).atZone(ZoneId.systemDefault()).toLocalDate(); } //myDate değişkenini olduğu gibi gönderir. string bir ifadenin doğru formatta girildeğini kontrol için idealdir public java.util.Date getMyDateAsUtilDate() { return myDate; } public java.sql.Date getMyDateAsSQLDate() { return myDate == null ? null : new java.sql.Date(myDate.getTime()); } public String getMyDateAsString(String format) { if (myDate == null) return null; SimpleDateFormat sdf; try { sdf = new SimpleDateFormat(format); } catch (Exception e) { return null; } return sdf.format(this.myDate); } public Long getMyDateAsLong() { return myDate == null ? null : myDate.getTime(); } public int getGun() { return myDate == null ? -1 : getMyDateAsCalendar().get(Calendar.DAY_OF_MONTH); } public int getAy() { return myDate == null ? -1 : getMyDateAsCalendar().get(Calendar.MONTH); } public int getYil() { return myDate == null ? -1 : getMyDateAsCalendar().get(Calendar.YEAR); } /** * mevcut mydate değişkenine tarih veya saat ekleme veya çıkarmak için kullanılır * eğer mydate null ise hata oluşacaktır bu sebeple try catch ile korunması gerekir * @param whatAdd : neyin eklenmesi-çıkarılması isteniyorsa o belirtilir Calendar.HOUR_OF_DAY, * @param piece : miktarı çıkarmak iiçin eksi sayı verilmesi gerekir. */ public void add(int whatAdd, int piece) { //Calender.HOURS Calendar c = Calendar.getInstance(); c.setTime(myDate); c.add(whatAdd, piece); myDate = c.getTime(); } /** * long olarak alınan tarihin toplam kaç ay,gün,yıl,hafta olduğunu veren fonksiyonlar * <p> * Birimler MiliSecond(yani Long) karşılığı * ---------------------------------------------------- * 1-MiliSecond 1L * 1-Second 1000L * 1-Minute 60000L * 1-Hour 3600000L * 1-Day 86400000L * 1-Week 604800000L * 1-Month 2592000000L * 1-Year 31104000000L */ private static long toSeconds(long date) { return date / 1000L; } private static long toMinutes(long date) { return toSeconds(date) / 60L; } private static long toHours(long date) { return toMinutes(date) / 60L; } private static long toDays(long date) { return toHours(date) / 24L; } private static long toMonths(long date) { return toDays(date) / 30L; } }
UTF-8
Java
6,959
java
MyDate.java
Java
[]
null
[]
package utility; import java.text.SimpleDateFormat; import java.time.*; import java.util.Calendar; import java.util.Date; /** * TARİH CONVERT CLASS * Bu sınıf; tarih değerini kullanıcıdan almakta ve kendisinde olan myDate değşkenine yükleyip daha sonra kullanıcıya tarih olarak sunmaktadır * sınıfın avantajları ise aldığı tarihin kısıtlı olmaması hemen hemen bütün tarih formatlarını alabilmesi ve kullanıcının istediği tarih türüne dönüştürmesi * <p> * <p> * A) Kabul Ettiği Tarih Türleri: 1) MyDate(util.Date) * 2) MyDate(LocalDate) * (YAPILANDIRICILARI) 3) MyDate(sql.Date) * 4) MyDate(String date, String format) * 5) MyDate(int gun, int ay, int yil) * 6) MyDate(Long date) * <p> * <p> * B) Getter Metodları 1) getMyDateAsCalendar() * 2) getMyDateAsLocalDate() * 3) getMyDateAsUtilDate() * 4) getMyDateAsSQLDate() * 5) getMyDateAsString(String format) * 6) getMyDateAsLong() * 7) getGun() * 8) getAy() * 9) getYil() * <p> * <p> * C) Diğer Metodları 1) void add(int whatAdd, int piece) * 2) Long diffDates(Date dateCikarilan) */ public class MyDate { private java.util.Date myDate; public MyDate(java.util.Date myDate) { this.myDate = myDate; } public MyDate(LocalDate localDate) { if (localDate == null) this.myDate = null; else this.myDate = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); } public MyDate(LocalDateTime localDateTime) { ZonedDateTime z = localDateTime.atZone(ZoneId.systemDefault()); try { this.myDate = Date.from(z.toInstant()); } catch (Exception e) { this.myDate = null; } } public MyDate(java.sql.Date myDate) { try { this.myDate = new Date(myDate.getTime()); } catch (Exception e) { this.myDate = null; } } public MyDate(Long date) { try { myDate = new Date(date); } catch (Exception e) { this.myDate = null; } } /* Bu metod MyDate(String date, String format) yapılandırıcısı tarafından kullanılmaktadır format üret fonksiyonu sayesinde kullanıcının runtime gireceği her format kabul edilecektir fonksiyon işaret olarak * karakterini aramaktadır örnek: 12/10/2019 5/5/2005 12-10-2019 12.10.2019*/ private String sembolleriDuzelt(String girilenTarih) { girilenTarih=girilenTarih.replace(".", "/"); //girilen tarihteki nokta ve tireler / ile değiştiriliyor girilenTarih=girilenTarih.replace("-", "/"); return girilenTarih; } //format üret fonksiyonu sayesinde kullanıcının runtime gireceği her format kabul edilecektir public MyDate(String date, String format) { if(date==null||date.isEmpty()){ this.myDate=null; return; } date=sembolleriDuzelt(date.trim()); try { SimpleDateFormat sdf = new SimpleDateFormat(format); this.myDate = sdf.parse(date); } catch (Exception ex) { //myDate=null; //önemli silme.. bazı yerler buna bakarak karar veriyor this.myDate = null; } } public MyDate(int gun, int ay, int yil) { if (gun < 1 || gun > 31 || ay < 1 || ay > 12 || yil < 2000) { myDate = null; return; } Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DATE, gun); calendar.set(Calendar.MONTH, ay - 1); calendar.set(Calendar.YEAR, yil); this.myDate = calendar.getTime(); } public Calendar getMyDateAsCalendar() { Calendar cal = Calendar.getInstance(); try { cal.setTime(myDate); } catch (Exception e) { return null; } return cal; } public LocalDateTime getMyDateAsLocalDateTime() { return myDate == null ? null : LocalDateTime.ofInstant(myDate.toInstant(), ZoneId.systemDefault()); } public LocalDate getMyDateAsLocalDate() { return myDate == null ? null : Instant.ofEpochMilli(myDate.getTime()).atZone(ZoneId.systemDefault()).toLocalDate(); } //myDate değişkenini olduğu gibi gönderir. string bir ifadenin doğru formatta girildeğini kontrol için idealdir public java.util.Date getMyDateAsUtilDate() { return myDate; } public java.sql.Date getMyDateAsSQLDate() { return myDate == null ? null : new java.sql.Date(myDate.getTime()); } public String getMyDateAsString(String format) { if (myDate == null) return null; SimpleDateFormat sdf; try { sdf = new SimpleDateFormat(format); } catch (Exception e) { return null; } return sdf.format(this.myDate); } public Long getMyDateAsLong() { return myDate == null ? null : myDate.getTime(); } public int getGun() { return myDate == null ? -1 : getMyDateAsCalendar().get(Calendar.DAY_OF_MONTH); } public int getAy() { return myDate == null ? -1 : getMyDateAsCalendar().get(Calendar.MONTH); } public int getYil() { return myDate == null ? -1 : getMyDateAsCalendar().get(Calendar.YEAR); } /** * mevcut mydate değişkenine tarih veya saat ekleme veya çıkarmak için kullanılır * eğer mydate null ise hata oluşacaktır bu sebeple try catch ile korunması gerekir * @param whatAdd : neyin eklenmesi-çıkarılması isteniyorsa o belirtilir Calendar.HOUR_OF_DAY, * @param piece : miktarı çıkarmak iiçin eksi sayı verilmesi gerekir. */ public void add(int whatAdd, int piece) { //Calender.HOURS Calendar c = Calendar.getInstance(); c.setTime(myDate); c.add(whatAdd, piece); myDate = c.getTime(); } /** * long olarak alınan tarihin toplam kaç ay,gün,yıl,hafta olduğunu veren fonksiyonlar * <p> * Birimler MiliSecond(yani Long) karşılığı * ---------------------------------------------------- * 1-MiliSecond 1L * 1-Second 1000L * 1-Minute 60000L * 1-Hour 3600000L * 1-Day 86400000L * 1-Week 604800000L * 1-Month 2592000000L * 1-Year 31104000000L */ private static long toSeconds(long date) { return date / 1000L; } private static long toMinutes(long date) { return toSeconds(date) / 60L; } private static long toHours(long date) { return toMinutes(date) / 60L; } private static long toDays(long date) { return toHours(date) / 24L; } private static long toMonths(long date) { return toDays(date) / 30L; } }
6,959
0.601167
0.581327
230
28.808695
28.905964
157
false
false
0
0
0
0
0
0
0.391304
false
false
7
1a96f3ba0fc79b72129dbed9a840637e71d07844
14,061,722,965,555
631ec5400d905291942d49fd4b964a7b31f36d91
/src/main/java/com/github/lespaul361/umleditor/Package.java
649a965ecebe45c1600cd6d6fd6548d1adab7258
[]
no_license
lespaul361/UMLEditor
https://github.com/lespaul361/UMLEditor
a157cf923ae950aed8da18f22d9f5423e72a36ec
3eab22f57ff7d6ed361d2baf0724b257de977b5d
refs/heads/master
2020-03-27T17:17:11.003000
2018-09-16T03:38:24
2018-09-16T03:38:24
146,841,476
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.github.lespaul361.umleditor; import java.util.ArrayList; import java.util.List; /** * * @author David Hamilton */ public final class Package implements DefaultMethods { private String packageName = ""; public static final String PROP_PACKAGENAME = "packageName"; private final List<UMLClass> umlClasses = new ArrayList<>(100); private Package(String name) { this.packageName = name; } private Package() { } /** * Creates an instance of a {@link Package} * * @param name the name of the package (ex. com.name.packagename) * @return the new Package */ public static Package getPackageInstance(String name) { return new Package(name); } @Override public String getName() { return packageName; } @Override public void setName(String name) { if (name == null) { throw new NullPointerException("Package name cannot be null"); } if (name.isEmpty()) { throw new IllegalArgumentException("Package name cannot be empty"); } this.packageName = name; } /** * Adds a class extending {@link UMLClass} * * @param umlClass a class extending {@link UMLClass} */ public void addUMLClass(UMLClass umlClass) { this.umlClasses.add(umlClass); } /** * Removes a {@link UMLClass} from the package * * @param umlClass the class to remove * @return true if class was found and removed */ public boolean remove(UMLClass umlClass) { return umlClasses.remove(umlClass); } /** * Removes a {@link UMLClass} from the package * * @param index the index to the class to remove * @return the UMLClass removed */ public UMLClass remove(int index) { return umlClasses.remove(index); } }
UTF-8
Java
2,068
java
Package.java
Java
[ { "context": "he template in the editor.\n */\npackage com.github.lespaul361.umleditor;\n\nimport java.util.ArrayList;\nimport ja", "end": 214, "score": 0.9733655452728271, "start": 204, "tag": "USERNAME", "value": "lespaul361" }, { "context": "rayList;\nimport java.util.List;\n\n/**\n *\n * @author David Hamilton\n */\npublic final class Package implements Default", "end": 311, "score": 0.9998108148574829, "start": 297, "tag": "NAME", "value": "David Hamilton" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.github.lespaul361.umleditor; import java.util.ArrayList; import java.util.List; /** * * @author <NAME> */ public final class Package implements DefaultMethods { private String packageName = ""; public static final String PROP_PACKAGENAME = "packageName"; private final List<UMLClass> umlClasses = new ArrayList<>(100); private Package(String name) { this.packageName = name; } private Package() { } /** * Creates an instance of a {@link Package} * * @param name the name of the package (ex. com.name.packagename) * @return the new Package */ public static Package getPackageInstance(String name) { return new Package(name); } @Override public String getName() { return packageName; } @Override public void setName(String name) { if (name == null) { throw new NullPointerException("Package name cannot be null"); } if (name.isEmpty()) { throw new IllegalArgumentException("Package name cannot be empty"); } this.packageName = name; } /** * Adds a class extending {@link UMLClass} * * @param umlClass a class extending {@link UMLClass} */ public void addUMLClass(UMLClass umlClass) { this.umlClasses.add(umlClass); } /** * Removes a {@link UMLClass} from the package * * @param umlClass the class to remove * @return true if class was found and removed */ public boolean remove(UMLClass umlClass) { return umlClasses.remove(umlClass); } /** * Removes a {@link UMLClass} from the package * * @param index the index to the class to remove * @return the UMLClass removed */ public UMLClass remove(int index) { return umlClasses.remove(index); } }
2,060
0.626692
0.623791
82
24.219513
22.70813
79
false
false
0
0
0
0
0
0
0.219512
false
false
7
18232ffadd55eca751a97af07a359fab400127ae
33,079,838,177,520
73d7935d95fea38ba5b819b665c26f72a76d9b4b
/app/src/main/java/com/tomash/poloniexupdater/base/mvp/view/BaseActivity.java
b50c6a57035f8a264826b2b8c5c4641e54fdc327
[]
no_license
blainepwnz/CloudFactoryTestTask
https://github.com/blainepwnz/CloudFactoryTestTask
2ee260414f9d4988383ffff8bb0107a79b7453cb
9ce7f6af6866b859c15f508d27331ddc2dd248dd
refs/heads/master
2020-03-09T12:26:26.799000
2018-04-09T14:40:39
2018-04-09T14:40:39
128,786,256
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tomash.poloniexupdater.base.mvp.view; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Toast; import com.tomash.poloniexupdater.base.PoloniexApp; import com.tomash.poloniexupdater.base.mvp.presenter.BasePresenter; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.Unbinder; public abstract class BaseActivity<Presenter extends BasePresenter> extends AppCompatActivity implements BaseView { protected final String TAG = getTag(); @Inject protected Presenter presenter; private Unbinder unbinder; @Override protected final void onCreate(@Nullable Bundle savedInstanceState) { inject(); super.onCreate(savedInstanceState); //init presenter after super presenter.onCreate(savedInstanceState, getStartingIntentBundle()); } /** * Injects all dependencies using dagger */ protected abstract void inject(); private Bundle getStartingIntentBundle() { if (getIntent() != null) return getIntent().getExtras(); return null; } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume: "); presenter.onResume(); } @Override public void initViews() { setContentView(getContentViewId()); unbinder = ButterKnife.bind(this); } @Override protected void onPause() { Log.d(TAG, "onPause: "); super.onPause(); presenter.onPause(); } @Override protected final void onDestroy() { Log.d(TAG, "onDestroy: "); super.onDestroy(); presenter.onDestroy(); if (unbinder != null) unbinder.unbind(); } protected abstract String getTag(); protected abstract int getContentViewId(); /** * */ public void replaceFragment(int containerId, Fragment fragment, String tag, boolean addToBackStack) { FragmentTransaction transaction = getSupportFragmentManager() .beginTransaction() .replace(containerId, fragment, tag); if (addToBackStack) transaction.addToBackStack(tag); transaction.commitAllowingStateLoss(); } /** * Helper method for dismissing dialogs */ protected void dismissDialog(Dialog dialog) { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); presenter.onSaveInstanceState(outState); } public PoloniexApp getPoloniexApp() { return (PoloniexApp) getApplication(); } /** * Default back press */ public void superOnBackPressed() { super.onBackPressed(); } }
UTF-8
Java
3,228
java
BaseActivity.java
Java
[]
null
[]
package com.tomash.poloniexupdater.base.mvp.view; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Toast; import com.tomash.poloniexupdater.base.PoloniexApp; import com.tomash.poloniexupdater.base.mvp.presenter.BasePresenter; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.Unbinder; public abstract class BaseActivity<Presenter extends BasePresenter> extends AppCompatActivity implements BaseView { protected final String TAG = getTag(); @Inject protected Presenter presenter; private Unbinder unbinder; @Override protected final void onCreate(@Nullable Bundle savedInstanceState) { inject(); super.onCreate(savedInstanceState); //init presenter after super presenter.onCreate(savedInstanceState, getStartingIntentBundle()); } /** * Injects all dependencies using dagger */ protected abstract void inject(); private Bundle getStartingIntentBundle() { if (getIntent() != null) return getIntent().getExtras(); return null; } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume: "); presenter.onResume(); } @Override public void initViews() { setContentView(getContentViewId()); unbinder = ButterKnife.bind(this); } @Override protected void onPause() { Log.d(TAG, "onPause: "); super.onPause(); presenter.onPause(); } @Override protected final void onDestroy() { Log.d(TAG, "onDestroy: "); super.onDestroy(); presenter.onDestroy(); if (unbinder != null) unbinder.unbind(); } protected abstract String getTag(); protected abstract int getContentViewId(); /** * */ public void replaceFragment(int containerId, Fragment fragment, String tag, boolean addToBackStack) { FragmentTransaction transaction = getSupportFragmentManager() .beginTransaction() .replace(containerId, fragment, tag); if (addToBackStack) transaction.addToBackStack(tag); transaction.commitAllowingStateLoss(); } /** * Helper method for dismissing dialogs */ protected void dismissDialog(Dialog dialog) { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); presenter.onSaveInstanceState(outState); } public PoloniexApp getPoloniexApp() { return (PoloniexApp) getApplication(); } /** * Default back press */ public void superOnBackPressed() { super.onBackPressed(); } }
3,228
0.669765
0.668835
122
25.459017
21.993347
115
false
false
0
0
0
0
0
0
0.483607
false
false
7
0d3c08c856f7378e9d385984c4c588fe4b56910c
31,121,333,072,224
bbfde94b16ae13f04157e6307395ca57bcf27b57
/johnson-runtime/src/main/java/com/github/johnson/BooleanParser.java
84b0b716609e2a7c4cfb8b15c80a5d994dc86044
[ "MIT" ]
permissive
ewanld/johnson-runtime
https://github.com/ewanld/johnson-runtime
21b16d32c66c9ecb19338586248701f53c39b446
897af704b11453ce7c2608fadabdd00723487da2
refs/heads/master
2021-01-20T22:11:59.814000
2018-12-17T14:25:25
2018-12-17T14:25:25
61,874,129
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.johnson; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; public class BooleanParser extends JohnsonParser<Boolean> { public static final BooleanParser INSTANCE = new BooleanParser(false); public static final BooleanParser INSTANCE_NULLABLE = new BooleanParser(true); public BooleanParser(boolean nullable) { super(nullable); } @Override public Boolean doParse(JsonParser jp) throws JsonParseException, IOException { if (jp.getCurrentToken() == JsonToken.VALUE_NULL) { if (nullable) return null; else throw new JsonParseException(jp, "null not allowed!"); } final boolean res = jp.getBooleanValue(); return res; } @Override public void doSerialize(Boolean value, JsonGenerator generator) throws IOException { generator.writeBoolean(value); } }
UTF-8
Java
1,007
java
BooleanParser.java
Java
[]
null
[]
package com.github.johnson; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; public class BooleanParser extends JohnsonParser<Boolean> { public static final BooleanParser INSTANCE = new BooleanParser(false); public static final BooleanParser INSTANCE_NULLABLE = new BooleanParser(true); public BooleanParser(boolean nullable) { super(nullable); } @Override public Boolean doParse(JsonParser jp) throws JsonParseException, IOException { if (jp.getCurrentToken() == JsonToken.VALUE_NULL) { if (nullable) return null; else throw new JsonParseException(jp, "null not allowed!"); } final boolean res = jp.getBooleanValue(); return res; } @Override public void doSerialize(Boolean value, JsonGenerator generator) throws IOException { generator.writeBoolean(value); } }
1,007
0.754717
0.754717
33
28.515152
27.170752
85
false
false
0
0
0
0
0
0
1.484848
false
false
7
56b0722b18c77f95f1b6aaf3ce119c454b05e71e
28,570,122,505,143
8364aa8ca59e5dc22c3273a42cc38eae5a40a2ca
/aditya-fun and food/Web Project/src/p1/C1.java
bcaf2ebf3618ff06b9318180e84904d73a662723
[]
no_license
BiztimeItSolutions/maximiser
https://github.com/BiztimeItSolutions/maximiser
03410cfd35d1740d66235ba0b9f03514a0320ffe
2e6f3031213cb9b5bb3d385b5e8e0ab7318296bf
refs/heads/master
2021-01-23T20:13:07.455000
2014-02-14T07:58:56
2014-02-14T07:58:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package p1; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class C1 */ @WebServlet("/C1") public class C1 extends HttpServlet { private static final long serialVersionUID = 1L; /** * Default constructor. */ public C1() { // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.print("Hello World"); String Studname=request.getParameter("sname"); int Studid=(Integer.parseInt(request.getParameter("sid"))); String Studpass=request.getParameter("pass"); out.print("Student Name"+Studname); out.print("Student ID"+Studid); out.print("Password"+Studpass); try { // Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); System.out.println("in forname"); Class.forName("com.ibm.db2.jcc.DB2Driver"); System.out.println("out forname"); } catch (ClassNotFoundException e) { out.println("Please include Classpath Where your DB Driver is located"); out.println("Couldn't load database driver: " + e.getMessage()); e.printStackTrace(); return; } out.println("DB driver is loaded successfully"); Connection conn = null; PreparedStatement pstmt = null; ResultSet rset=null; boolean found=false; try { conn = DriverManager.getConnection("jdbc:db2://localhost:50000/ABB","administrator","admin"); if (conn != null) { out.println("DB Database Connected"); } else { out.println("DB connection Failed "); } //String sql = "insert into aditya.registertable values (?,?,?,?,?,?,?,?)"; String sql = "insert into ADITYA.REGISTERTABLE values (?,?,?)"; PreparedStatement pst = null; pst= conn.prepareStatement(sql); // ps = conn.prepareStatement("insert into ASCHEMA.TABLE1 values (?,?,?)"); pst.setString(1, Studname); pst.setInt(2, Studid); pst.setString(3,Studpass); pst.executeUpdate(); // pst.execute(); conn.commit(); } catch (SQLException e) { out.print("DB2 Database connection Failed"+ e.getMessage()); return; } finally { try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("done"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
UTF-8
Java
3,380
java
C1.java
Java
[]
null
[]
package p1; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class C1 */ @WebServlet("/C1") public class C1 extends HttpServlet { private static final long serialVersionUID = 1L; /** * Default constructor. */ public C1() { // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.print("Hello World"); String Studname=request.getParameter("sname"); int Studid=(Integer.parseInt(request.getParameter("sid"))); String Studpass=request.getParameter("pass"); out.print("Student Name"+Studname); out.print("Student ID"+Studid); out.print("Password"+Studpass); try { // Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); System.out.println("in forname"); Class.forName("com.ibm.db2.jcc.DB2Driver"); System.out.println("out forname"); } catch (ClassNotFoundException e) { out.println("Please include Classpath Where your DB Driver is located"); out.println("Couldn't load database driver: " + e.getMessage()); e.printStackTrace(); return; } out.println("DB driver is loaded successfully"); Connection conn = null; PreparedStatement pstmt = null; ResultSet rset=null; boolean found=false; try { conn = DriverManager.getConnection("jdbc:db2://localhost:50000/ABB","administrator","admin"); if (conn != null) { out.println("DB Database Connected"); } else { out.println("DB connection Failed "); } //String sql = "insert into aditya.registertable values (?,?,?,?,?,?,?,?)"; String sql = "insert into ADITYA.REGISTERTABLE values (?,?,?)"; PreparedStatement pst = null; pst= conn.prepareStatement(sql); // ps = conn.prepareStatement("insert into ASCHEMA.TABLE1 values (?,?,?)"); pst.setString(1, Studname); pst.setInt(2, Studid); pst.setString(3,Studpass); pst.executeUpdate(); // pst.execute(); conn.commit(); } catch (SQLException e) { out.print("DB2 Database connection Failed"+ e.getMessage()); return; } finally { try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("done"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
3,380
0.647041
0.64142
118
26.644068
25.584532
119
false
false
0
0
0
0
0
0
1.940678
false
false
7
bb1b7d81a51ce6684752f7c3c6f6c101fa0479e2
18,416,819,765,913
bb74ff066519d550c043221cab6bffa5a1d80b80
/Assignment2B/src/ca/bcit/comp2526/a2b/World.java
ec4d9dfd4ecb6dd35a026c1c69ac68c3c00afb1b
[]
no_license
j-applese3d/java
https://github.com/j-applese3d/java
6fe269baaa61b8f03867bbc32736531eb8166d6a
c0bbaf459a43e6da7817fb55c1588d77bace4a91
refs/heads/master
2020-03-05T18:18:22.947000
2017-03-18T03:37:59
2017-03-18T03:37:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ca.bcit.comp2526.a2b; import java.util.ArrayList; import java.util.Collections; import java.util.Random; /** * World to contain a specific type of Cells. * Also holds the seed that all Classes refer to. * Parameterized type ensures that we can only add * the specified type of Cell to the world. * * @author Brayden Traas * @version 2016-10-22 */ public final class World<CellT extends Cell> { private static long lastTime; //private static int lastTotal; private static final String INITIALIZING_WORLD = "Initializing world with "; /** * Defines if we are debugging this application. */ public static final boolean DEBUG = Settings.getBoolean("debug"); /** * Decides if we show food on each Cell. */ public static final boolean SHOW_FOOD = Settings.get("filltext").equalsIgnoreCase("food"); /** * Decides if we show moves on each Cell. */ public static final boolean SHOW_MOVES = Settings.get("filltext").equalsIgnoreCase("moves"); /** * Decides if we have chosen to show coordinates on each Cell. */ public static final boolean SHOW_COORDINATES = Settings.get("filltext").equalsIgnoreCase("coordinate"); /** * Decides if borders are visible. */ public static final boolean VISIBLE_LINES = Settings.getBoolean("visibleLines"); /** * True if this is a hex grid. */ public static final boolean HEX = Settings.get("gridType").equalsIgnoreCase("hex"); //private Class<CellT> cellType; private final long seed; private final Random randomSeed; private int columns; private int rows; private Cell[][] cells; /** * Creates a World. If a seed is loaded from settings, use it. * Otherwise, a random seed is used (based on current time). * * @param rows to instantiate with. * @param columns to instantiate with. */ public World(int columns, int rows) { double seed = Settings.getDouble("seed"); seed = seed > 0 ? seed : System.currentTimeMillis(); System.out.println("Seed: " + seed); this.seed = (long)seed; this.randomSeed = new Random((long)seed); this.columns = columns; this.rows = rows; init(); } /** * Initializes the World with Cells and Life within the cells. */ public void init() { // Cell objects now created later; // the World object doesn't know the type of the Cell (Hexagon or Square) // cells = new Cell [columns][rows]; System.out.println(INITIALIZING_WORLD + columns + "," + rows); // Current initialization cells = new Cell[columns][rows]; // Testing (CellT is a parameterized type that extends Cell). //CellT[][] tmpCells; // Cannot create a generic array of CellT //tmpCells = new CellT[columns][rows]; // Type safety: Unchecked cast from Cell[][] to CellT[][] //tmpCells = (CellT[][])(new Cell[columns][rows]); } /** * Gets the cells of the World. * @return an ArrayList of cells. */ public ArrayList<Cell> getCells() { ArrayList<Cell> cells = new ArrayList<Cell>(); for (int i = 0; i < columns; i++) { for (int j = 0; j < rows; j++) { if (this.cells[i][j] != null) { cells.add(this.cells[i][j]); } } } return cells; } /** * Gets the current lives of the World. * @return an ArrayList of lives. */ public ArrayList<Life> getLives() { ArrayList<Life> lives = new ArrayList<Life>(); for (int i = 0; i < columns; i++) { for (int j = 0; j < rows; j++) { /* * getLife(LifeType.values()) denotes: * Get any life that: * : is-a Life * * Ergo, any life. */ if (cells[i][j] != null && cells[i][j].getLife(LifeType.values()) != null) { lives.addAll(cells[i][j].getLives()); } } } //System.out.println(lives); return lives; } /** * Processes the turn. Essentially finds the Life objects * within the Cells, and runs its processTurn() method. */ public void takeTurn() { long thisTime = System.currentTimeMillis(); long diff = (thisTime - lastTime); // long total = lastTotal+1; System.out.println(" Turn time: " + diff + "ms"); lastTime = thisTime; //boolean showFood = Boolean.parseBoolean(Settings.get.getProperty("showfood")); //System.out.println("\nSHOWFOOD: "+showFood+"\n"); ArrayList<Life> lives = getLives(); boolean debug = Settings.getBoolean("debug"); // Shuffle the order of the lives to process with the World's seed. if (!debug) { Collections.shuffle(lives, getSeed()); } else { runDebug(); } //if(debug) return; // Do this separately so we don't reprocess tiles. for (Life occupier: lives) { if (occupier != null) { occupier.processTurn(); } } } /* * Just used for testing. */ private void runDebug() { int lives = 0; for (int i = 0; i < columns; i++) { for (int j = 0; j < rows; j++) { if (cells[i][j] == null) { continue; } Life life = cells[i][j].getLife(LifeType.values()); if (life != null) { lives += cells[i][j].getLives().size(); } //System.out.print(cells[j][i].getLives().size()+","); } //System.out.println(); } System.out.println("1: " + lives + " 2: " + getLives().size()); } /** * Adds the Cell at its desired location. * * @param newCell - the Cell to add. Gets location from the Cell itself. */ public void addCell(final CellT newCell) throws IndexOutOfBoundsException { if (newCell == null) { return; } int column = newCell.getColumn(); int row = newCell.getRow(); // Return null if this row/column is outside bounds. // Now the exception must be caught. if (row < 0 || column < 0) { throw new IndexOutOfBoundsException("Index < 0!"); } if (row >= rows || column >= columns) { throw new IndexOutOfBoundsException( "Index > max (" + row + ">=" + rows + ")" + " or (" + column + ">=" + columns + ")"); } cells[column][row] = newCell; // new Cell(this, column, row); cells[column][row].addLife(Creator.createLife(cells[column][row], randomSeed)); // return cells[column][row]; } /** * Returns the Cell at this location. * * @param row the row this Cell is found in * @param column the column this Cell is found in * @return the desired Cell object */ public Cell getCellAt(int column, int row) { // Return null if this row/column is outside bounds. if (row < 0 || column < 0) { return null; } if (row >= rows || column >= columns) { return null; } return cells[column][row]; } /** * Gets the row count. * @return number of rows. */ public int getRowCount() { return rows; } /** * Gets the column count. * @return number of columns. */ public int getColumnCount() { return columns; } /** * Returns the seed of the current world. * Available to whole package but not public. * @return seed of this world */ public Random getSeed() { return randomSeed; } /** * Returns the seed (long form) of the current world. * @param raw to differentiate between getSeed() * @return long seed */ public long getSeed(boolean raw) { return seed; } public String toString() { return "World size: " + columns + "," + rows; } }
UTF-8
Java
9,122
java
World.java
Java
[ { "context": "cified type of Cell to the world.\r\n * \r\n * @author Brayden Traas\r\n * @version 2016-10-22\r\n */\r\npublic final class ", "end": 354, "score": 0.9998823404312134, "start": 341, "tag": "NAME", "value": "Brayden Traas" } ]
null
[]
package ca.bcit.comp2526.a2b; import java.util.ArrayList; import java.util.Collections; import java.util.Random; /** * World to contain a specific type of Cells. * Also holds the seed that all Classes refer to. * Parameterized type ensures that we can only add * the specified type of Cell to the world. * * @author <NAME> * @version 2016-10-22 */ public final class World<CellT extends Cell> { private static long lastTime; //private static int lastTotal; private static final String INITIALIZING_WORLD = "Initializing world with "; /** * Defines if we are debugging this application. */ public static final boolean DEBUG = Settings.getBoolean("debug"); /** * Decides if we show food on each Cell. */ public static final boolean SHOW_FOOD = Settings.get("filltext").equalsIgnoreCase("food"); /** * Decides if we show moves on each Cell. */ public static final boolean SHOW_MOVES = Settings.get("filltext").equalsIgnoreCase("moves"); /** * Decides if we have chosen to show coordinates on each Cell. */ public static final boolean SHOW_COORDINATES = Settings.get("filltext").equalsIgnoreCase("coordinate"); /** * Decides if borders are visible. */ public static final boolean VISIBLE_LINES = Settings.getBoolean("visibleLines"); /** * True if this is a hex grid. */ public static final boolean HEX = Settings.get("gridType").equalsIgnoreCase("hex"); //private Class<CellT> cellType; private final long seed; private final Random randomSeed; private int columns; private int rows; private Cell[][] cells; /** * Creates a World. If a seed is loaded from settings, use it. * Otherwise, a random seed is used (based on current time). * * @param rows to instantiate with. * @param columns to instantiate with. */ public World(int columns, int rows) { double seed = Settings.getDouble("seed"); seed = seed > 0 ? seed : System.currentTimeMillis(); System.out.println("Seed: " + seed); this.seed = (long)seed; this.randomSeed = new Random((long)seed); this.columns = columns; this.rows = rows; init(); } /** * Initializes the World with Cells and Life within the cells. */ public void init() { // Cell objects now created later; // the World object doesn't know the type of the Cell (Hexagon or Square) // cells = new Cell [columns][rows]; System.out.println(INITIALIZING_WORLD + columns + "," + rows); // Current initialization cells = new Cell[columns][rows]; // Testing (CellT is a parameterized type that extends Cell). //CellT[][] tmpCells; // Cannot create a generic array of CellT //tmpCells = new CellT[columns][rows]; // Type safety: Unchecked cast from Cell[][] to CellT[][] //tmpCells = (CellT[][])(new Cell[columns][rows]); } /** * Gets the cells of the World. * @return an ArrayList of cells. */ public ArrayList<Cell> getCells() { ArrayList<Cell> cells = new ArrayList<Cell>(); for (int i = 0; i < columns; i++) { for (int j = 0; j < rows; j++) { if (this.cells[i][j] != null) { cells.add(this.cells[i][j]); } } } return cells; } /** * Gets the current lives of the World. * @return an ArrayList of lives. */ public ArrayList<Life> getLives() { ArrayList<Life> lives = new ArrayList<Life>(); for (int i = 0; i < columns; i++) { for (int j = 0; j < rows; j++) { /* * getLife(LifeType.values()) denotes: * Get any life that: * : is-a Life * * Ergo, any life. */ if (cells[i][j] != null && cells[i][j].getLife(LifeType.values()) != null) { lives.addAll(cells[i][j].getLives()); } } } //System.out.println(lives); return lives; } /** * Processes the turn. Essentially finds the Life objects * within the Cells, and runs its processTurn() method. */ public void takeTurn() { long thisTime = System.currentTimeMillis(); long diff = (thisTime - lastTime); // long total = lastTotal+1; System.out.println(" Turn time: " + diff + "ms"); lastTime = thisTime; //boolean showFood = Boolean.parseBoolean(Settings.get.getProperty("showfood")); //System.out.println("\nSHOWFOOD: "+showFood+"\n"); ArrayList<Life> lives = getLives(); boolean debug = Settings.getBoolean("debug"); // Shuffle the order of the lives to process with the World's seed. if (!debug) { Collections.shuffle(lives, getSeed()); } else { runDebug(); } //if(debug) return; // Do this separately so we don't reprocess tiles. for (Life occupier: lives) { if (occupier != null) { occupier.processTurn(); } } } /* * Just used for testing. */ private void runDebug() { int lives = 0; for (int i = 0; i < columns; i++) { for (int j = 0; j < rows; j++) { if (cells[i][j] == null) { continue; } Life life = cells[i][j].getLife(LifeType.values()); if (life != null) { lives += cells[i][j].getLives().size(); } //System.out.print(cells[j][i].getLives().size()+","); } //System.out.println(); } System.out.println("1: " + lives + " 2: " + getLives().size()); } /** * Adds the Cell at its desired location. * * @param newCell - the Cell to add. Gets location from the Cell itself. */ public void addCell(final CellT newCell) throws IndexOutOfBoundsException { if (newCell == null) { return; } int column = newCell.getColumn(); int row = newCell.getRow(); // Return null if this row/column is outside bounds. // Now the exception must be caught. if (row < 0 || column < 0) { throw new IndexOutOfBoundsException("Index < 0!"); } if (row >= rows || column >= columns) { throw new IndexOutOfBoundsException( "Index > max (" + row + ">=" + rows + ")" + " or (" + column + ">=" + columns + ")"); } cells[column][row] = newCell; // new Cell(this, column, row); cells[column][row].addLife(Creator.createLife(cells[column][row], randomSeed)); // return cells[column][row]; } /** * Returns the Cell at this location. * * @param row the row this Cell is found in * @param column the column this Cell is found in * @return the desired Cell object */ public Cell getCellAt(int column, int row) { // Return null if this row/column is outside bounds. if (row < 0 || column < 0) { return null; } if (row >= rows || column >= columns) { return null; } return cells[column][row]; } /** * Gets the row count. * @return number of rows. */ public int getRowCount() { return rows; } /** * Gets the column count. * @return number of columns. */ public int getColumnCount() { return columns; } /** * Returns the seed of the current world. * Available to whole package but not public. * @return seed of this world */ public Random getSeed() { return randomSeed; } /** * Returns the seed (long form) of the current world. * @param raw to differentiate between getSeed() * @return long seed */ public long getSeed(boolean raw) { return seed; } public String toString() { return "World size: " + columns + "," + rows; } }
9,115
0.493971
0.490791
322
26.329193
22.720356
96
false
false
0
0
0
0
0
0
0.34472
false
false
7
31c5c6fac6ef12f62fefe25ced05ed22bfc0143d
9,706,626,132,160
bc468bb0b1272fb8ce81fc6779987cafbeb8f354
/src/mariogenetic/game/Renderer.java
6471f17a8db924ffbe84ba7c93161c41e23c16bf
[]
no_license
krzysztof/MarioGenetic
https://github.com/krzysztof/MarioGenetic
3626d3d7fcf7f21ccff99d32bf5b3d398d2ecd47
0bb896b98039852f744a436aff3e9660dd2a666a
refs/heads/master
2020-04-16T02:07:36.701000
2015-05-08T09:10:32
2015-05-08T09:10:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package mariogenetic.game; import java.awt.Color; import java.awt.Graphics2D; import mariogenetic.*; /** * * @author alice */ public abstract class Renderer { protected Camera camera; protected static Renderer singleton; protected Renderer(){ } public void render(Graphics2D g2) { } public static Renderer getInstance() { return null; } public Camera getCamera() { return camera; } void reset() { } }
UTF-8
Java
583
java
Renderer.java
Java
[ { "context": "hics2D;\nimport mariogenetic.*;\n\n\n/**\n *\n * @author alice\n */\npublic abstract class Renderer {\n\n protect", "end": 228, "score": 0.8001475930213928, "start": 223, "tag": "USERNAME", "value": "alice" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package mariogenetic.game; import java.awt.Color; import java.awt.Graphics2D; import mariogenetic.*; /** * * @author alice */ public abstract class Renderer { protected Camera camera; protected static Renderer singleton; protected Renderer(){ } public void render(Graphics2D g2) { } public static Renderer getInstance() { return null; } public Camera getCamera() { return camera; } void reset() { } }
583
0.634648
0.629503
39
13.948718
15.114858
52
false
false
0
0
0
0
0
0
0.25641
false
false
7
fc18bc6d84dcf4baa472f328f23e37d3b50281d8
22,316,650,075,233
22d5cca2ba524c0825e6e27cfe5d169711455e2d
/src/com/me4502/FractalMaker/expression/runtime/ReturnException.java
d74fb4896e1b4ab0ba5f7f0c146c126e94d6fad9
[]
no_license
me4502/FractalMaker
https://github.com/me4502/FractalMaker
33dcf3932574412230ad2e0797911cfe208e1978
e162f12b696d22eddbd9479b74d22b3e5bcbcc83
refs/heads/master
2022-03-01T10:22:33.708000
2019-12-16T13:43:16
2019-12-16T13:43:16
228,396,292
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.me4502.FractalMaker.expression.runtime; /** * Thrown when a return statement is encountered. * {@link com.sk89q.worldedit.expression.Expression#evaluate} catches this exception and returns the enclosed value. * * @author TomyLobo */ public class ReturnException extends EvaluationException { private static final long serialVersionUID = 1L; final double value; public ReturnException(double value) { super(-1); this.value = value; } public double getValue() { return value; } }
UTF-8
Java
511
java
ReturnException.java
Java
[ { "context": "tion and returns the enclosed value.\n *\n * @author TomyLobo\n */\npublic class ReturnException extends Evaluati", "end": 246, "score": 0.9942396879196167, "start": 238, "tag": "NAME", "value": "TomyLobo" } ]
null
[]
package com.me4502.FractalMaker.expression.runtime; /** * Thrown when a return statement is encountered. * {@link com.sk89q.worldedit.expression.Expression#evaluate} catches this exception and returns the enclosed value. * * @author TomyLobo */ public class ReturnException extends EvaluationException { private static final long serialVersionUID = 1L; final double value; public ReturnException(double value) { super(-1); this.value = value; } public double getValue() { return value; } }
511
0.751468
0.735812
23
21.26087
27.724134
116
false
false
0
0
0
0
0
0
0.782609
false
false
7
232d4bc2dd215646832e2d19b3d641fd363e2b4b
8,924,942,078,843
a653c9fa8cc7a97765323c0230dc62b9b3309654
/src/cn/core/framework/utils/current/CurrentUtils.java
014d5765e83ad551e8b2d95624b1ce59c9608862
[]
no_license
peterwuhua/springBootDemoT
https://github.com/peterwuhua/springBootDemoT
ef065d082017420dc56ac54f4714b11a4fbe9ee3
f8cebcae3becaa425fad93f116c40fb7ceb65e43
refs/heads/master
2020-09-13T22:47:25.013000
2019-11-20T13:16:09
2019-11-20T13:16:09
222,925,989
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.core.framework.utils.current; import org.apache.shiro.SecurityUtils; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import cn.core.framework.utils.DateUtils; import cn.demi.base.system.vo.AccountVo; public class CurrentUtils { public static final String TOCKET_COOKIE_KEY = "user.tocket"; public static final Current getCurrent() { Subject currentUser =SecurityUtils.getSubject(); Session session = currentUser.getSession(); return (Current) session.getAttribute(TOCKET_COOKIE_KEY); } public static final String getAccountId(){ return getCurrent().getAccountId(); } public static final String getUserId(){ return getCurrent().getUserName(); } public static final String getUserName(){ return getCurrent().getUserName(); } public static final void setCurrent(AccountVo accountVo) { // 使用ticket作为标示,防止过期的cookie内存在同key ticket; Current current = new Current(); current.setAccountId(accountVo.getId()); current.setRoleIds(accountVo.getRoleIds()); current.setRoleNames(accountVo.getRoleNames()); current.setLoginName(accountVo.getLoginName()); current.setLoginTime(DateUtils.format(DateUtils.getCurrDate(), DateUtils.formatStr_yyyyMMddHHmm)); current.setIsUse(String.valueOf(accountVo.getIsUse())); if(null!=accountVo.getUserVo()){ current.setUserId(accountVo.getUserVo().getId()); current.setAvatar(accountVo.getUserVo().getAvatar()); current.setUserName(accountVo.getUserVo().getName()); current.setDuty(accountVo.getUserVo().getDuty()); current.setTheme(accountVo.getUserVo().getTheme()); } if(null!=accountVo.getOrgVo()){ current.setOrgId(accountVo.getOrgVo().getId()); current.setOrgName(accountVo.getOrgVo().getName()); current.setOrgCode(accountVo.getOrgVo().getCode()); } if(null!=accountVo.getDepVo()) { current.setDepCode(accountVo.getDepVo().getCode()); current.setDepName(accountVo.getDepVo().getName()); current.setDepId(accountVo.getDepVo().getId()); } Subject currentUser =SecurityUtils.getSubject(); currentUser.getSession().setAttribute(CurrentUtils.TOCKET_COOKIE_KEY, current); } public static final void setCurrent(Current current) { Subject currentUser =SecurityUtils.getSubject(); currentUser.getSession().setAttribute(CurrentUtils.TOCKET_COOKIE_KEY, current); } }
UTF-8
Java
2,370
java
CurrentUtils.java
Java
[ { "context": "blic static final String TOCKET_COOKIE_KEY = \"user.tocket\";\n\t\n\tpublic static final Current getCurrent", "end": 329, "score": 0.57416832447052, "start": 329, "tag": "KEY", "value": "" }, { "context": "c static final String TOCKET_COOKIE_KEY = \"user.tocket\";\n\t\n\tpublic static final Current getCurrent() {\n\t", "end": 336, "score": 0.5278723239898682, "start": 332, "tag": "KEY", "value": "cket" } ]
null
[]
package cn.core.framework.utils.current; import org.apache.shiro.SecurityUtils; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import cn.core.framework.utils.DateUtils; import cn.demi.base.system.vo.AccountVo; public class CurrentUtils { public static final String TOCKET_COOKIE_KEY = "user.tocket"; public static final Current getCurrent() { Subject currentUser =SecurityUtils.getSubject(); Session session = currentUser.getSession(); return (Current) session.getAttribute(TOCKET_COOKIE_KEY); } public static final String getAccountId(){ return getCurrent().getAccountId(); } public static final String getUserId(){ return getCurrent().getUserName(); } public static final String getUserName(){ return getCurrent().getUserName(); } public static final void setCurrent(AccountVo accountVo) { // 使用ticket作为标示,防止过期的cookie内存在同key ticket; Current current = new Current(); current.setAccountId(accountVo.getId()); current.setRoleIds(accountVo.getRoleIds()); current.setRoleNames(accountVo.getRoleNames()); current.setLoginName(accountVo.getLoginName()); current.setLoginTime(DateUtils.format(DateUtils.getCurrDate(), DateUtils.formatStr_yyyyMMddHHmm)); current.setIsUse(String.valueOf(accountVo.getIsUse())); if(null!=accountVo.getUserVo()){ current.setUserId(accountVo.getUserVo().getId()); current.setAvatar(accountVo.getUserVo().getAvatar()); current.setUserName(accountVo.getUserVo().getName()); current.setDuty(accountVo.getUserVo().getDuty()); current.setTheme(accountVo.getUserVo().getTheme()); } if(null!=accountVo.getOrgVo()){ current.setOrgId(accountVo.getOrgVo().getId()); current.setOrgName(accountVo.getOrgVo().getName()); current.setOrgCode(accountVo.getOrgVo().getCode()); } if(null!=accountVo.getDepVo()) { current.setDepCode(accountVo.getDepVo().getCode()); current.setDepName(accountVo.getDepVo().getName()); current.setDepId(accountVo.getDepVo().getId()); } Subject currentUser =SecurityUtils.getSubject(); currentUser.getSession().setAttribute(CurrentUtils.TOCKET_COOKIE_KEY, current); } public static final void setCurrent(Current current) { Subject currentUser =SecurityUtils.getSubject(); currentUser.getSession().setAttribute(CurrentUtils.TOCKET_COOKIE_KEY, current); } }
2,370
0.759846
0.759846
65
34.938461
24.263222
100
false
false
0
0
0
0
0
0
2.107692
false
false
7
613c875d6d90f9ec7534d24813dd0fef98916577
29,841,432,781,976
2d1922231b5e667b34c87de2afb5850455bbfa62
/28-13_FileRetrieve_Easy/src/FileRetrieveServer.java
9c5ac280acd2d8660c2905fe80c42f9402c4ee86
[]
no_license
kdorcey/SoftwareDesignProjects
https://github.com/kdorcey/SoftwareDesignProjects
4a9bb26333fd57fa3d215043d2e88c1cf18ba25c
10edf09ebf894c1fb7e6abd45ece92e8de3c72db
refs/heads/master
2021-05-03T11:04:28.896000
2018-02-07T01:06:01
2018-02-07T01:06:01
120,544,150
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; /*** * Responsible for starting and controlling all server functionality * * @author Kyle Dorcey * @version 1.8 */ public class FileRetrieveServer { /**Defines the servers ServerSocket which will be used to link the server to the client**/ private ServerSocket server; /**Defines the socket Object which is used to pass and receive the client and servers IP and port numbers **/ private Socket connection; /**Stream used to send data to the client **/ private ObjectOutputStream output; /**Stream used to recieve data from the client**/ private ObjectInputStream input; /**No argument class constructor**/ public FileRetrieveServer(){ } /*** * Method responsible for creating the server. As this is the class for the server the while-loop * will run until the program is closed. Assuming neither waitForClient(), getClientStream(), or processConnection() * throw an IOException the server will process information from a single client. */ public void startServer(){ try{ server = new ServerSocket(4444,100); while(true){ try{ waitForClient(); getClientsStream(); processConnection(); } catch (IOException serverStreamProblem) //comes from { System.out.println("Broke connection: "+serverStreamProblem); } finally{ closeConnection(); } } } catch(IOException somethingWentWrong){ System.out.println("Server: couldn't run server"); } } /*** * Waits for a cliet to connect to the server's socket. When the server accepts a connection it * defines the connection variable. * @throws IOException throws in the event the server's socket cannot connect to the client's socket properly */ public void waitForClient() throws IOException{ System.out.println("Server: Waiting for friend :("); connection = server.accept(); System.out.println("Server: Found friend :) named: "+connection.getInetAddress().getHostName()); } /*** * When called (and connection has been previously defined), this method sets the ObjectOutputStream * to send data to the client * @throws IOException throws in the event that the client and servers streams do not connect properly */ public void getClientsStream() throws IOException{ output = new ObjectOutputStream(connection.getOutputStream()); output.flush(); input = new ObjectInputStream(connection.getInputStream()); System.out.println("Server: Got friends stream"); } /*** * This method contains the servers logic. In this case, the server will recieve a file-path from the * client. It will then check that the file exists. If it does, it will send the file's contents to * the client. * @throws IOException throws in the event that the method cannot properly deserialize the client's output (or server's input) */ public void processConnection () throws IOException{ System.out.println("Server: processing messages"); String recievedMessage ="Server: Connection Worked"; sendData(recievedMessage); do { try { recievedMessage = (String) input.readObject(); System.out.println("searching for file named: "+recievedMessage+" ..."); String fileCheck = checkForFile(recievedMessage); if(recievedMessage.equals("endit"))//condition used to disconnect client { sendData("endit"); } else { sendData(fileCheck); } } catch(ClassNotFoundException e){ System.out.println("Client input object not found: "+e.getCause()); } catch(IOException f){ System.out.println("Problem with clients input/output stream: "+f.getMessage()); closeConnection();} }while(!recievedMessage.equals("endit")); } /*** * Called by the processConnection() method, checks if the client requested file exists and returns a string * containing its contents if it finds one. * @param fileName Path to the file to read from * @return String foundFileInfo, contains the contents of the file that the client requested. */ public String checkForFile(String fileName){ String foundFileInfo = ""; try { File fileToRetrieve = new File(fileName); Scanner reader = new Scanner(fileToRetrieve); while (reader.hasNextLine()) { foundFileInfo += reader.nextLine(); } } catch (IOException fileNotFound){ foundFileInfo = "File Not Found"; } return foundFileInfo; } /*** * Closes the connection between the server and client by first closing the ObjectOutputStream, inputOutputStream, * and Socket */ public void closeConnection(){ System.out.println("Server: Ending connection"); try{ output.close(); input.close(); connection.close(); } catch (IOException closeConnectionProblem){ System.out.println("Server: problem in close connection"); } } /** * Used to send data to the client * @param message String to send to client */ public void sendData(String message){ try{ output.writeObject(message); output.flush(); //sends necessary information to deserialize the object sent in the ObjectOutputStream System.out.println("Server>>> "+message); } catch (IOException ioException){ System.out.println("Error writing object"); } } }
UTF-8
Java
6,098
java
FileRetrieveServer.java
Java
[ { "context": "controlling all server functionality\n *\n * @author Kyle Dorcey\n * @version 1.8\n */\n\npublic class FileRetrieveSer", "end": 198, "score": 0.9998819828033447, "start": 187, "tag": "NAME", "value": "Kyle Dorcey" } ]
null
[]
import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; /*** * Responsible for starting and controlling all server functionality * * @author <NAME> * @version 1.8 */ public class FileRetrieveServer { /**Defines the servers ServerSocket which will be used to link the server to the client**/ private ServerSocket server; /**Defines the socket Object which is used to pass and receive the client and servers IP and port numbers **/ private Socket connection; /**Stream used to send data to the client **/ private ObjectOutputStream output; /**Stream used to recieve data from the client**/ private ObjectInputStream input; /**No argument class constructor**/ public FileRetrieveServer(){ } /*** * Method responsible for creating the server. As this is the class for the server the while-loop * will run until the program is closed. Assuming neither waitForClient(), getClientStream(), or processConnection() * throw an IOException the server will process information from a single client. */ public void startServer(){ try{ server = new ServerSocket(4444,100); while(true){ try{ waitForClient(); getClientsStream(); processConnection(); } catch (IOException serverStreamProblem) //comes from { System.out.println("Broke connection: "+serverStreamProblem); } finally{ closeConnection(); } } } catch(IOException somethingWentWrong){ System.out.println("Server: couldn't run server"); } } /*** * Waits for a cliet to connect to the server's socket. When the server accepts a connection it * defines the connection variable. * @throws IOException throws in the event the server's socket cannot connect to the client's socket properly */ public void waitForClient() throws IOException{ System.out.println("Server: Waiting for friend :("); connection = server.accept(); System.out.println("Server: Found friend :) named: "+connection.getInetAddress().getHostName()); } /*** * When called (and connection has been previously defined), this method sets the ObjectOutputStream * to send data to the client * @throws IOException throws in the event that the client and servers streams do not connect properly */ public void getClientsStream() throws IOException{ output = new ObjectOutputStream(connection.getOutputStream()); output.flush(); input = new ObjectInputStream(connection.getInputStream()); System.out.println("Server: Got friends stream"); } /*** * This method contains the servers logic. In this case, the server will recieve a file-path from the * client. It will then check that the file exists. If it does, it will send the file's contents to * the client. * @throws IOException throws in the event that the method cannot properly deserialize the client's output (or server's input) */ public void processConnection () throws IOException{ System.out.println("Server: processing messages"); String recievedMessage ="Server: Connection Worked"; sendData(recievedMessage); do { try { recievedMessage = (String) input.readObject(); System.out.println("searching for file named: "+recievedMessage+" ..."); String fileCheck = checkForFile(recievedMessage); if(recievedMessage.equals("endit"))//condition used to disconnect client { sendData("endit"); } else { sendData(fileCheck); } } catch(ClassNotFoundException e){ System.out.println("Client input object not found: "+e.getCause()); } catch(IOException f){ System.out.println("Problem with clients input/output stream: "+f.getMessage()); closeConnection();} }while(!recievedMessage.equals("endit")); } /*** * Called by the processConnection() method, checks if the client requested file exists and returns a string * containing its contents if it finds one. * @param fileName Path to the file to read from * @return String foundFileInfo, contains the contents of the file that the client requested. */ public String checkForFile(String fileName){ String foundFileInfo = ""; try { File fileToRetrieve = new File(fileName); Scanner reader = new Scanner(fileToRetrieve); while (reader.hasNextLine()) { foundFileInfo += reader.nextLine(); } } catch (IOException fileNotFound){ foundFileInfo = "File Not Found"; } return foundFileInfo; } /*** * Closes the connection between the server and client by first closing the ObjectOutputStream, inputOutputStream, * and Socket */ public void closeConnection(){ System.out.println("Server: Ending connection"); try{ output.close(); input.close(); connection.close(); } catch (IOException closeConnectionProblem){ System.out.println("Server: problem in close connection"); } } /** * Used to send data to the client * @param message String to send to client */ public void sendData(String message){ try{ output.writeObject(message); output.flush(); //sends necessary information to deserialize the object sent in the ObjectOutputStream System.out.println("Server>>> "+message); } catch (IOException ioException){ System.out.println("Error writing object"); } } }
6,093
0.614956
0.61348
168
35.297619
33.819824
134
false
false
0
0
0
0
0
0
0.35119
false
false
7
f9e97b90b0ef95eec965c87a3200084ff1036136
7,645,041,826,225
1ff3c45b5144e72c568594c1314ef1bb8dcc416d
/MyTournamentV2/src/mt/entities/Registration.java
aebd11b64c3c5a3634e03690e473cce5fee70947
[]
no_license
dimnocode/MyTournamentJEE
https://github.com/dimnocode/MyTournamentJEE
b528aa1304d530e8f4ba9427ddb51dec2ef40fed
e031a19a94dacdc329f6d5ae2b1f226455c42060
refs/heads/master
2020-04-06T07:02:23.381000
2016-08-28T15:26:15
2016-08-28T15:26:15
58,478,477
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mt.entities; import java.io.Serializable; import javax.persistence.*; import java.util.Date; /** * The persistent class for the registrations database table. * */ @Entity @Table(name="registrations") @NamedQueries({ @NamedQuery(name="Registration.findAll", query="SELECT r FROM Registration r"), @NamedQuery(name="Registration.findByUserAndTournament", query="SELECT r from Registration r WHERE r.user.idUsers = :idUser AND r.tournament.idTournaments = :idTournament") }) public class Registration implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(unique=true, nullable=false) private int idRegistration; @Column(nullable=false) private boolean clanLeaderValidation; @Temporal(TemporalType.TIMESTAMP) @Column(nullable=false) private Date creationDate; @Column(nullable=false) private boolean userConfirmation; //bi-directional many-to-one association to Clan @ManyToOne @JoinColumn(name="idClan") private Clan clan; //bi-directional many-to-one association to Tournament @ManyToOne @JoinColumn(name="idTournaments", nullable=false) private Tournament tournament; //bi-directional many-to-one association to User @ManyToOne @JoinColumn(name="idUsers", nullable=false) private User user; public Registration() { } public int getIdRegistration() { return this.idRegistration; } public void setIdRegistration(int idRegistration) { this.idRegistration = idRegistration; } public boolean getClanLeaderValidation() { return this.clanLeaderValidation; } public void setClanLeaderValidation(boolean clanLeaderValidation) { this.clanLeaderValidation = clanLeaderValidation; } public Date getCreationDate() { return this.creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public boolean getUserConfirmation() { return this.userConfirmation; } public void setUserConfirmation(boolean userConfirmation) { this.userConfirmation = userConfirmation; } public Clan getClan() { return this.clan; } public void setClan(Clan clan) { this.clan = clan; } public Tournament getTournament() { return this.tournament; } public void setTournament(Tournament tournament) { this.tournament = tournament; } public User getUser() { return this.user; } public void setUser(User user) { this.user = user; } }
UTF-8
Java
2,546
java
Registration.java
Java
[]
null
[]
package mt.entities; import java.io.Serializable; import javax.persistence.*; import java.util.Date; /** * The persistent class for the registrations database table. * */ @Entity @Table(name="registrations") @NamedQueries({ @NamedQuery(name="Registration.findAll", query="SELECT r FROM Registration r"), @NamedQuery(name="Registration.findByUserAndTournament", query="SELECT r from Registration r WHERE r.user.idUsers = :idUser AND r.tournament.idTournaments = :idTournament") }) public class Registration implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(unique=true, nullable=false) private int idRegistration; @Column(nullable=false) private boolean clanLeaderValidation; @Temporal(TemporalType.TIMESTAMP) @Column(nullable=false) private Date creationDate; @Column(nullable=false) private boolean userConfirmation; //bi-directional many-to-one association to Clan @ManyToOne @JoinColumn(name="idClan") private Clan clan; //bi-directional many-to-one association to Tournament @ManyToOne @JoinColumn(name="idTournaments", nullable=false) private Tournament tournament; //bi-directional many-to-one association to User @ManyToOne @JoinColumn(name="idUsers", nullable=false) private User user; public Registration() { } public int getIdRegistration() { return this.idRegistration; } public void setIdRegistration(int idRegistration) { this.idRegistration = idRegistration; } public boolean getClanLeaderValidation() { return this.clanLeaderValidation; } public void setClanLeaderValidation(boolean clanLeaderValidation) { this.clanLeaderValidation = clanLeaderValidation; } public Date getCreationDate() { return this.creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public boolean getUserConfirmation() { return this.userConfirmation; } public void setUserConfirmation(boolean userConfirmation) { this.userConfirmation = userConfirmation; } public Clan getClan() { return this.clan; } public void setClan(Clan clan) { this.clan = clan; } public Tournament getTournament() { return this.tournament; } public void setTournament(Tournament tournament) { this.tournament = tournament; } public User getUser() { return this.user; } public void setUser(User user) { this.user = user; } }
2,546
0.730165
0.729772
111
20.954954
24.453444
173
false
false
0
0
0
0
0
0
1.045045
false
false
7
39c514b88c578e746ad1e5af28583e60ccf07edd
28,509,992,932,409
0c0c618015c3f2a38b7c65e54a1e408aa7e7a3f2
/src/main/java/eu/ydp/empiria/player/client/controller/events/interaction/InteractionEventType.java
ac5cc73bf4911d8b4d7ba9555fc0ea30dcaa542b
[]
no_license
akotynski/empiria.player
https://github.com/akotynski/empiria.player
44b0b3516fb48d9ff8b58103b1fd0b6cc9ffc906
c1264451c9c3b27d60f885fce7142e81f8fc22e3
refs/heads/master
2021-01-24T09:01:13.204000
2017-05-30T13:41:10
2017-05-30T13:41:10
93,400,409
0
0
null
true
2017-06-05T12:13:43
2017-06-05T12:13:43
2017-06-05T12:08:49
2017-05-30T13:43:05
38,518
0
0
0
null
null
null
package eu.ydp.empiria.player.client.controller.events.interaction; public enum InteractionEventType { STATE_CHANGED, FEEDBACK_SOUND, FEEDBACK_MUTE, MEDIA_SOUND_PLAY; }
UTF-8
Java
179
java
InteractionEventType.java
Java
[]
null
[]
package eu.ydp.empiria.player.client.controller.events.interaction; public enum InteractionEventType { STATE_CHANGED, FEEDBACK_SOUND, FEEDBACK_MUTE, MEDIA_SOUND_PLAY; }
179
0.776536
0.776536
5
33.799999
29.741554
67
false
false
0
0
0
0
0
0
1
false
false
7
3ffc2dd9111565f176a5cf68157cab37bb0cec9c
37,598,143,716,368
56671cb948b9295dde58c7dd983ef0a58431f1cf
/app/src/main/java/ru/tulupov/alex/teachme/views/activivties/ShowTeacherView.java
11fa962f31ec68835265c7aabfacee42c7376450
[]
no_license
Algresh/TeachMeAndroid
https://github.com/Algresh/TeachMeAndroid
0f9540b72c07897f936e6427895a05651d95acf4
7184388608eb6879d1f4a694642970f890a739e3
refs/heads/master
2021-01-11T21:26:11.685000
2017-12-03T12:07:13
2017-12-03T12:07:13
78,782,867
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.tulupov.alex.teachme.views.activivties; public interface ShowTeacherView { void setFavorite(); void deleteFavorite(); void errorFavorite(); void isFavoriteSuccess(boolean isFavorite); void isFavoriteError(); }
UTF-8
Java
245
java
ShowTeacherView.java
Java
[]
null
[]
package ru.tulupov.alex.teachme.views.activivties; public interface ShowTeacherView { void setFavorite(); void deleteFavorite(); void errorFavorite(); void isFavoriteSuccess(boolean isFavorite); void isFavoriteError(); }
245
0.734694
0.734694
12
19.416666
18.029875
50
false
false
0
0
0
0
0
0
0.5
false
false
7
3a3f9a7322344ccedb88dcd7d6f7eca0585bf103
34,454,227,688,792
ca1f5e4994d3db3c3b030c613d804b1c047c25ed
/abienasync-jaxrs/src/main/java/com/airhacks/com/airhacks/async/boundary/AsyncResource.java
0d6ef6bb5cfcfe7f71bf968258fcc16e4b729a31
[]
no_license
pawelcwik/learning
https://github.com/pawelcwik/learning
1745eeee84fb09761924364505f46618b2391888
5c4c8a94d8f33951208c8e1092c63892f59aa437
refs/heads/master
2020-05-22T04:19:27.726000
2016-10-26T19:27:34
2016-10-26T19:27:34
63,682,870
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.airhacks.com.airhacks.async.boundary; import com.airhacks.porcupine.execution.boundary.Dedicated; import org.glassfish.jersey.client.ClientProperties; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.container.AsyncResponse; import javax.ws.rs.container.Suspended; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; @Path("async") public class AsyncResource { @Inject @Dedicated ExecutorService cpu; // @Resource(name = "concurrentOrchestration") @Inject @Dedicated ExecutorService orchestration; @GET public void get(@Suspended AsyncResponse response) { CompletableFuture.supplyAsync(this::doSomeWork, cpu).thenAccept(response::resume); } String doSomeWork() { try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(AsyncResource.class.getName()).log(Level.SEVERE,"Oh well"); } return "+" + System.currentTimeMillis(); } private Client client; private WebTarget target; private WebTarget processor; @PostConstruct public void init() { this.client = ClientBuilder.newClient(); target = this.client.target("http://localhost:8080/jaxrs/resources/messages"); client.property(ClientProperties.CONNECT_TIMEOUT, 1000); client.property(ClientProperties.READ_TIMEOUT, 5000); this.processor = this.client.target("http://localhost:8080/processor/resources/processors/beautification"); } @GET @Path("Orchestration") public void fetchMessage(@Suspended AsyncResponse response) { Supplier<String> supplier = () -> target.request().get(String.class); CompletableFuture.supplyAsync(supplier,orchestration) .thenApply(this::process) .exceptionally(this::handle) .thenApply(this::consume).thenAccept(response::resume); } String handle(Throwable t) { return "sorry we're overloaded!" + t.getMessage(); } String consume(String message) { this.target.request().post(Entity.text(message)); return message; } public String process (String input) { return this.processor.request().post(Entity.text(input)).readEntity(String.class); } }
UTF-8
Java
2,642
java
AsyncResource.java
Java
[]
null
[]
package com.airhacks.com.airhacks.async.boundary; import com.airhacks.porcupine.execution.boundary.Dedicated; import org.glassfish.jersey.client.ClientProperties; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.container.AsyncResponse; import javax.ws.rs.container.Suspended; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; @Path("async") public class AsyncResource { @Inject @Dedicated ExecutorService cpu; // @Resource(name = "concurrentOrchestration") @Inject @Dedicated ExecutorService orchestration; @GET public void get(@Suspended AsyncResponse response) { CompletableFuture.supplyAsync(this::doSomeWork, cpu).thenAccept(response::resume); } String doSomeWork() { try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(AsyncResource.class.getName()).log(Level.SEVERE,"Oh well"); } return "+" + System.currentTimeMillis(); } private Client client; private WebTarget target; private WebTarget processor; @PostConstruct public void init() { this.client = ClientBuilder.newClient(); target = this.client.target("http://localhost:8080/jaxrs/resources/messages"); client.property(ClientProperties.CONNECT_TIMEOUT, 1000); client.property(ClientProperties.READ_TIMEOUT, 5000); this.processor = this.client.target("http://localhost:8080/processor/resources/processors/beautification"); } @GET @Path("Orchestration") public void fetchMessage(@Suspended AsyncResponse response) { Supplier<String> supplier = () -> target.request().get(String.class); CompletableFuture.supplyAsync(supplier,orchestration) .thenApply(this::process) .exceptionally(this::handle) .thenApply(this::consume).thenAccept(response::resume); } String handle(Throwable t) { return "sorry we're overloaded!" + t.getMessage(); } String consume(String message) { this.target.request().post(Entity.text(message)); return message; } public String process (String input) { return this.processor.request().post(Entity.text(input)).readEntity(String.class); } }
2,642
0.699849
0.692279
84
30.452381
26.219044
115
false
false
0
0
0
0
0
0
0.511905
false
false
7
02ed9b1b1047fc9091d0ec9a993f0dded602474e
25,692,494,396,919
9c1ed973795c1b1084e2e453f9448af2d8713a68
/funds-packet/src/main/java/com/palmcommerce/funds/packet/security/openssl/impl/DefaultDecrypt.java
e8f99ae31bc29b40248256530aadec7239f42ec7
[]
no_license
bellmit/funds
https://github.com/bellmit/funds
cf29e10440ca6ae41ab0a44dad203e1b1c8b550b
b17d32126f755395186fdc9de97f521442700355
refs/heads/master
2022-02-18T11:34:29.923000
2018-03-14T15:15:41
2018-03-14T15:15:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.palmcommerce.funds.packet.security.openssl.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.palmcommerce.funds.config.security.SecurityConfiguration; import com.palmcommerce.funds.config.security.SecurityConfiguration.SecurityKey; import com.palmcommerce.funds.config.security.SecurityConfiguration.SecurityKeyStore; import com.palmcommerce.funds.configuration.v2.ConfigurationManager; import com.palmcommerce.funds.configuration.v2.OpenSslCryptor; import com.palmcommerce.funds.configuration.v2.OpenSslCryptorEntry; import com.palmcommerce.funds.packet.security.OpensslPacketSecurity; import com.palmcommerce.funds.packet.security.openssl.IDecrypt; /** * @author sparrow * */ public class DefaultDecrypt implements IDecrypt { private static final Log logger=LogFactory.getLog(DefaultDecrypt.class); // private static final PacketSecurityHandler factory=new PacketSecurityHandler(); // // public static PacketSecurityHandler getInstance(){ // return factory; // } private boolean enableDebug; public void setEnableDebug(boolean enableDebug) { this.enableDebug = enableDebug; } private void log(String message){ if(enableDebug){ logger.info(message); } } ConfigurationManager configurationManager; /** * @return the configurationManager */ public ConfigurationManager getConfigurationManager() { return configurationManager; } /** * @param configurationManager the configurationManager to set */ public void setConfigurationManager(ConfigurationManager configurationManager) { this.configurationManager = configurationManager; } /** * */ public DefaultDecrypt() { // TODO Auto-generated constructor stub } public boolean validateSignature(byte[] signature, int offset, int len, String fromCode) { //SecurityKeyStore keyStore= SecurityConfiguration.getInstance().getSecurityKeyStore(); // SecurityKey key=securityConfiguration.getSecurityKeyStore().getKey(fromCode); // log("validateSignature:"+key.toString()); //OpenSslCryptor key=this.configurationManager.getCryptor(fromCode); OpenSslCryptorEntry entry=this.configurationManager.getCryptorEntry(fromCode); //log("validateSignature:"+entry.toString()); boolean ret=false; try { ret=entry.validateSignature(signature); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ this.configurationManager.returnCryptorEntry(entry); } // TODO Auto-generated method stub return ret; } public byte[] decrypt(byte[] packet, String toCode) { // TODO Auto-generated method stub //SecurityKeyStore keyStore= SecurityConfiguration.getInstance().getSecurityKeyStore(); //OpenSslCryptor key=this.configurationManager.getCryptor(toCode); OpenSslCryptorEntry entry=this.configurationManager.getCryptorEntry(toCode); log("decrypt:"+entry.toString()); byte[] decrypted=null; try { decrypted=entry.decrypt(packet); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ this.configurationManager.returnCryptorEntry(entry); } return decrypted; } }
UTF-8
Java
3,191
java
DefaultDecrypt.java
Java
[ { "context": ".packet.security.openssl.IDecrypt;\n\n/**\n * @author sparrow\n *\n */\npublic class DefaultDecrypt implements IDe", "end": 753, "score": 0.9994072914123535, "start": 746, "tag": "USERNAME", "value": "sparrow" } ]
null
[]
/** * */ package com.palmcommerce.funds.packet.security.openssl.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.palmcommerce.funds.config.security.SecurityConfiguration; import com.palmcommerce.funds.config.security.SecurityConfiguration.SecurityKey; import com.palmcommerce.funds.config.security.SecurityConfiguration.SecurityKeyStore; import com.palmcommerce.funds.configuration.v2.ConfigurationManager; import com.palmcommerce.funds.configuration.v2.OpenSslCryptor; import com.palmcommerce.funds.configuration.v2.OpenSslCryptorEntry; import com.palmcommerce.funds.packet.security.OpensslPacketSecurity; import com.palmcommerce.funds.packet.security.openssl.IDecrypt; /** * @author sparrow * */ public class DefaultDecrypt implements IDecrypt { private static final Log logger=LogFactory.getLog(DefaultDecrypt.class); // private static final PacketSecurityHandler factory=new PacketSecurityHandler(); // // public static PacketSecurityHandler getInstance(){ // return factory; // } private boolean enableDebug; public void setEnableDebug(boolean enableDebug) { this.enableDebug = enableDebug; } private void log(String message){ if(enableDebug){ logger.info(message); } } ConfigurationManager configurationManager; /** * @return the configurationManager */ public ConfigurationManager getConfigurationManager() { return configurationManager; } /** * @param configurationManager the configurationManager to set */ public void setConfigurationManager(ConfigurationManager configurationManager) { this.configurationManager = configurationManager; } /** * */ public DefaultDecrypt() { // TODO Auto-generated constructor stub } public boolean validateSignature(byte[] signature, int offset, int len, String fromCode) { //SecurityKeyStore keyStore= SecurityConfiguration.getInstance().getSecurityKeyStore(); // SecurityKey key=securityConfiguration.getSecurityKeyStore().getKey(fromCode); // log("validateSignature:"+key.toString()); //OpenSslCryptor key=this.configurationManager.getCryptor(fromCode); OpenSslCryptorEntry entry=this.configurationManager.getCryptorEntry(fromCode); //log("validateSignature:"+entry.toString()); boolean ret=false; try { ret=entry.validateSignature(signature); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ this.configurationManager.returnCryptorEntry(entry); } // TODO Auto-generated method stub return ret; } public byte[] decrypt(byte[] packet, String toCode) { // TODO Auto-generated method stub //SecurityKeyStore keyStore= SecurityConfiguration.getInstance().getSecurityKeyStore(); //OpenSslCryptor key=this.configurationManager.getCryptor(toCode); OpenSslCryptorEntry entry=this.configurationManager.getCryptorEntry(toCode); log("decrypt:"+entry.toString()); byte[] decrypted=null; try { decrypted=entry.decrypt(packet); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ this.configurationManager.returnCryptorEntry(entry); } return decrypted; } }
3,191
0.770605
0.769665
118
26.042374
27.769449
89
false
false
0
0
0
0
0
0
1.525424
false
false
7
d7d8fe23f5f0eb9c7494c33a26ef7b3461e8b551
35,759,897,741,745
21b3726c93519d1a5ea938931846f86f600cd243
/Project_AMS V2/src/kr/or/kosta/entity/Account.java
5aadc54bdcc7bb47bbcc54058e515a2558cecaf8
[]
no_license
lcw9206/hanaTI_practice
https://github.com/lcw9206/hanaTI_practice
ee06917e70eaf1616feb8a5874e635b8b4002b2b
fc49757051718e4e907ed46747f35c07a32232d9
refs/heads/master
2020-03-27T13:00:39.810000
2018-10-30T09:44:42
2018-10-30T09:44:42
146,584,466
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kr.or.kosta.entity; import java.util.Formatter; /** * 일상생활의 객체를 추상화하기 위한 모델링 클래스 정의 은행계좌 객체 * * @author 이철우 */ public class Account { public final static String bankName = "KOSTA 은행"; private String accountNum; private String accountOwner; private int passwd; private long restMoney; // Default 생성자 public Account() { this(null, null); } public Account(String accountNum, String accountOwner) { this(accountNum, accountOwner, 0, 0); } public Account(String accountNum, String accountOwner, int passwd, long restMoney) { this.accountNum = accountNum; this.accountOwner = accountOwner; this.passwd = passwd; this.restMoney = restMoney; } // Getter/Setter 메서드 public void setAccountNum(String accountNum) { this.accountNum = accountNum; } public String getAccountNum() { return accountNum; } public void setAccountOwner(String accountOwner) { this.accountOwner = accountOwner; } public String getAccountOwner() { return accountOwner; } public int getPasswd() { return passwd; } public void setRestMoney(long restMoney) { this.restMoney = restMoney; } public long getRestMoney() { return this.restMoney; } public boolean checkPasswd(int passwd) { return this.passwd == passwd; } /** * 입출금 계좌용 출력 메서드 * 줄맞춤을 위해 Formatter 클래스를 사용합니다. */ @Override public String toString() { String aNum = String.format("%19s", getAccountNum()); String aOwner = String.format("\t %-14s", getAccountOwner()); Formatter restFormatter = new Formatter(); return "입출금계좌\t" + aNum + aOwner + restFormatter.format("%,9d\n", getRestMoney()); } }
UTF-8
Java
1,843
java
Account.java
Java
[ { "context": "의 객체를 추상화하기 위한 모델링 클래스 정의 은행계좌 객체\r\n * \r\n * @author 이철우\r\n */\r\npublic class Account {\r\n\r\n\tpublic final sta", "end": 128, "score": 0.9941949248313904, "start": 125, "tag": "NAME", "value": "이철우" }, { "context": "this.accountOwner = accountOwner;\r\n\t\tthis.passwd = passwd;\r\n\t\tthis.restMoney = restMoney;\r\n\t}\r\n\r\n\t// Getter", "end": 673, "score": 0.8671212196350098, "start": 667, "tag": "PASSWORD", "value": "passwd" } ]
null
[]
package kr.or.kosta.entity; import java.util.Formatter; /** * 일상생활의 객체를 추상화하기 위한 모델링 클래스 정의 은행계좌 객체 * * @author 이철우 */ public class Account { public final static String bankName = "KOSTA 은행"; private String accountNum; private String accountOwner; private int passwd; private long restMoney; // Default 생성자 public Account() { this(null, null); } public Account(String accountNum, String accountOwner) { this(accountNum, accountOwner, 0, 0); } public Account(String accountNum, String accountOwner, int passwd, long restMoney) { this.accountNum = accountNum; this.accountOwner = accountOwner; this.passwd = <PASSWORD>; this.restMoney = restMoney; } // Getter/Setter 메서드 public void setAccountNum(String accountNum) { this.accountNum = accountNum; } public String getAccountNum() { return accountNum; } public void setAccountOwner(String accountOwner) { this.accountOwner = accountOwner; } public String getAccountOwner() { return accountOwner; } public int getPasswd() { return passwd; } public void setRestMoney(long restMoney) { this.restMoney = restMoney; } public long getRestMoney() { return this.restMoney; } public boolean checkPasswd(int passwd) { return this.passwd == passwd; } /** * 입출금 계좌용 출력 메서드 * 줄맞춤을 위해 Formatter 클래스를 사용합니다. */ @Override public String toString() { String aNum = String.format("%19s", getAccountNum()); String aOwner = String.format("\t %-14s", getAccountOwner()); Formatter restFormatter = new Formatter(); return "입출금계좌\t" + aNum + aOwner + restFormatter.format("%,9d\n", getRestMoney()); } }
1,847
0.672546
0.66843
80
19.262501
20.032314
85
false
false
0
0
0
0
0
0
1.375
false
false
7
4831cee287e94c2fb3526892b76dd54444f3dcf6
36,318,243,490,299
68be983815ce7cbfd3007bb8466df420105aa08c
/Entrega/Item 7/Acme-Orienteering-Postgres/src/main/java/converters/StringToEnteredConverter.java
a17da06cd6a2adc8848daaf80843f4f26f1e7307
[]
no_license
DPIRPSG/DPHackaton
https://github.com/DPIRPSG/DPHackaton
223a6d91c8a7a0c737c76eadd709a14c9922ffd3
215b0b76ea8766f46e07a98477b430950940f35a
refs/heads/master
2021-01-17T06:46:29.679000
2016-06-03T18:54:16
2016-06-03T18:54:16
56,570,853
0
1
null
false
2016-06-03T18:54:16
2016-04-19T06:30:58
2016-05-11T08:00:47
2016-06-03T18:54:16
54,374
0
0
1
Java
null
null
package converters; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import repositories.EnteredRepository; import domain.Entered; @Component @Transactional public class StringToEnteredConverter implements Converter<String, Entered> { @Autowired EnteredRepository enteredRepository; @Override public Entered convert(String text) { Entered result; int id; try { if (StringUtils.isEmpty(text)) result = null; else { id = Integer.valueOf(text); result = enteredRepository.findOne(id); } } catch (Throwable oops) { throw new IllegalArgumentException(oops); } return result; } }
UTF-8
Java
856
java
StringToEnteredConverter.java
Java
[]
null
[]
package converters; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import repositories.EnteredRepository; import domain.Entered; @Component @Transactional public class StringToEnteredConverter implements Converter<String, Entered> { @Autowired EnteredRepository enteredRepository; @Override public Entered convert(String text) { Entered result; int id; try { if (StringUtils.isEmpty(text)) result = null; else { id = Integer.valueOf(text); result = enteredRepository.findOne(id); } } catch (Throwable oops) { throw new IllegalArgumentException(oops); } return result; } }
856
0.775701
0.775701
38
21.526316
21.374773
77
false
false
0
0
0
0
0
0
1.526316
false
false
7
3b37eb83e1e04394da33c33e5c0707eacbfe84c5
36,696,200,603,787
359c7e46d5d143ab2f849b488d7d92ee15aeaf3d
/Tarea/tarea1.java
e27e2be8ae17eae4baf17b9c197d11b561f0fc48
[ "Apache-2.0" ]
permissive
JOSELIN-CONDORI/JOSELIN-TINTAYA-UPEU
https://github.com/JOSELIN-CONDORI/JOSELIN-TINTAYA-UPEU
38a1940a37fd2d90b85eaa6154ffd09a8c6e6af6
f3a2b2b683546620c05f63f5e8697634aac5dd99
refs/heads/main
2023-06-24T17:40:32.249000
2021-07-23T17:25:51
2021-07-23T17:25:51
358,319,955
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; public class tarea1 { static Scanner tecladoj=new Scanner(System.in); public static void salario() { //definir variables y otros int añosJMCT=1; double salario=1500; //proseso while (añosJMCT<=6) { salario=(salario*0.1)+salario; //datos de salida System.out.println("su salario del año es:"+añosJMCT+"es:"+salario); añosJMCT++; } } public static void main(String[] args) { salario(); } }
UTF-8
Java
523
java
tarea1.java
Java
[]
null
[]
import java.util.Scanner; public class tarea1 { static Scanner tecladoj=new Scanner(System.in); public static void salario() { //definir variables y otros int añosJMCT=1; double salario=1500; //proseso while (añosJMCT<=6) { salario=(salario*0.1)+salario; //datos de salida System.out.println("su salario del año es:"+añosJMCT+"es:"+salario); añosJMCT++; } } public static void main(String[] args) { salario(); } }
523
0.584942
0.567568
21
23.333334
18.385639
75
false
false
0
0
0
0
0
0
0.380952
false
false
7
f75899656e46d231f2e2d1e95e6b003af0581b1e
39,101,382,273,739
c6540eda2cca43e88c5913089889710e13ef7bcd
/pro01/src/quiz02/quiz2.java
c8b37165db082408685955bc4fb1e587761372c3
[]
no_license
leehan0617/kosta
https://github.com/leehan0617/kosta
6ab2feeddfeaabf355322db4cca63df7ff22bd0e
6225f5e8c1baaa5c29d6fddbc6989aaee147194b
refs/heads/master
2016-09-05T20:47:56.239000
2015-03-27T01:43:36
2015-03-27T01:43:36
30,576,841
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package quiz02; import java.util.Scanner; /* * 어떤 수를 입력해서 그 수가 10보다 크고 20보다 작으면 출력하는 * 프로그램을 작성하세요. */ public class quiz2 { public static void main(String[] args) { int input; //어떤수 Scanner scan = new Scanner(System.in); System.out.print("input number:"); input = scan.nextInt(); if(input>10 && input<20){ System.out.println(input); }else{ System.out.println("10보다 크고 20보다 작은수를 입력하세요."); } scan.close(); } }
UHC
Java
552
java
quiz2.java
Java
[]
null
[]
package quiz02; import java.util.Scanner; /* * 어떤 수를 입력해서 그 수가 10보다 크고 20보다 작으면 출력하는 * 프로그램을 작성하세요. */ public class quiz2 { public static void main(String[] args) { int input; //어떤수 Scanner scan = new Scanner(System.in); System.out.print("input number:"); input = scan.nextInt(); if(input>10 && input<20){ System.out.println(input); }else{ System.out.println("10보다 크고 20보다 작은수를 입력하세요."); } scan.close(); } }
552
0.633929
0.600446
26
16.23077
15.41804
50
false
false
0
0
0
0
0
0
1.5
false
false
7
3301354cb714b3cbf003aa7dc6e288f0d195b089
6,425,271,088,468
ccc3268554528f5ed5cc119bbd88cfc45b55691d
/dist/gameserver/data/scripts/services/community/CommunityBoardDropList.java
1bfdee6048e03111ada569fac229b162a45ac896
[]
no_license
trickititit/java-source
https://github.com/trickititit/java-source
447ea16c2892377a4625f742118ebfd4e3116848
724453441846ce44e65372100a70770f21572837
refs/heads/master
2021-01-18T09:38:01.836000
2016-09-17T17:43:34
2016-09-17T17:43:34
68,445,261
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package services.community; import java.text.NumberFormat; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; import l2p.gameserver.Config; import l2p.gameserver.data.htm.HtmCache; import l2p.gameserver.data.xml.holder.NpcHolder; import l2p.gameserver.handler.bbs.CommunityBoardManager; import l2p.gameserver.handler.bbs.ICommunityBoardHandler; import l2p.gameserver.model.GameObjectsStorage; import l2p.gameserver.model.Player; import l2p.gameserver.model.Spawner; import l2p.gameserver.model.base.Experience; import l2p.gameserver.model.instances.NpcInstance; import l2p.gameserver.model.instances.RaidBossInstance; import l2p.gameserver.model.reward.RewardData; import l2p.gameserver.model.reward.RewardGroup; import l2p.gameserver.model.reward.RewardList; import l2p.gameserver.model.reward.RewardType; import l2p.gameserver.serverpackets.ShowBoard; import l2p.gameserver.scripts.ScriptFile; import l2p.gameserver.stats.Stats; import l2p.gameserver.templates.npc.NpcTemplate; import l2p.gameserver.utils.HtmlUtils; import l2p.gameserver.utils.Language; import org.apache.commons.lang3.StringUtils; public class CommunityBoardDropList implements ScriptFile, ICommunityBoardHandler { private static CommunityBoardDropList _Instance = null; private static final NumberFormat pf = NumberFormat.getPercentInstance(Locale.ENGLISH); private static final NumberFormat df = NumberFormat.getInstance(Locale.ENGLISH); private static final Map<Integer, String> list = new HashMap<>(); private static final Map<Integer, String> list2 = new HashMap<>(); private static final Map<Integer, String> list3 = new HashMap<>(); private String val1 = ""; private String val2 = ""; private String val3 = ""; private String val4 = ""; static { pf.setMaximumFractionDigits(4); df.setMinimumFractionDigits(2); } public static CommunityBoardDropList getInstance() { if (_Instance == null) { _Instance = new CommunityBoardDropList(); } return _Instance; } @Override public void onLoad() { if (Config.COMMUNITYBOARD_ENABLED) { CommunityBoardManager.getInstance().registerHandler(this); } } @Override public void onReload() { if (Config.COMMUNITYBOARD_ENABLED) { CommunityBoardManager.getInstance().removeHandler(this); } } @Override public void onShutdown() { } @Override public String[] getBypassCommands() { return new String[]{ "_bbsdroplist", "_bbsrewardspage", "_bbsdropnpcnamepage", "_bbsdroppage", "_bbsdropid", "_bbsdropname", "_bbsdropnpcid", "_bbsdropnpcname", "_bbsrewards", "_bbsrewardradar"}; } @Override public void onBypassCommand(Player activeChar, String command) { StringTokenizer st = new StringTokenizer(command, " "); String cmd = st.nextToken(); val1 = ""; val2 = ""; val3 = ""; val4 = ""; if (st.countTokens() == 1) { val1 = st.nextToken(); } else if (st.countTokens() == 2) { val1 = st.nextToken(); val2 = st.nextToken(); } else if (st.countTokens() == 3) { val1 = st.nextToken(); val2 = st.nextToken(); val3 = st.nextToken(); } else if (st.countTokens() == 4) { val1 = st.nextToken(); val2 = st.nextToken(); val3 = st.nextToken(); val4 = st.nextToken(); } if (cmd.equalsIgnoreCase("_bbsdroplist")) { String content = HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "pages/rewards/list.htm", activeChar); content = content.replace("<?copyright?>", HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "block/copyright.htm", activeChar)); ShowBoard.separateAndSend(content, activeChar); } else if (cmd.equalsIgnoreCase("_bbsdropid")) { String content = HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "pages/rewards/rewards.htm", activeChar); content = content.replace("<?copyright?>", HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "block/copyright.htm", activeChar)); if (!val1.equals("")) { generateNpcList(activeChar, Integer.parseInt(val1)); String str = list.get(1); StringBuilder result2 = new StringBuilder(); content = content.replace("<?rewards?>", str); result2.append("<center><table width=690>"); result2.append("<tr>"); result2.append("<td WIDTH=690 align=center valign=top>"); result2.append("<center><button value=\""); result2.append(activeChar.getLanguage() == Language.RUSSIAN ? "Следущая страница" : "Next page"); result2.append("\" action=\"bypass _bbsdroppage " + 2 + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result2.append("</td>"); result2.append("</tr>"); result2.append("</table></center>"); content = content.replace("<?pagenext?>", list.get(2) != null ? result2.toString() : ""); ShowBoard.separateAndSend(content, activeChar); } else { activeChar.sendMessage("Please enter the Etc Item ID. Example: 57"); } } else if (cmd.equalsIgnoreCase("_bbsdropname")) { String content = HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "pages/rewards/rewards.htm", activeChar); content = content.replace("<?copyright?>", HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "block/copyright.htm", activeChar)); if (!val1.equals("")) { String str1 = null; if (!val1.equals("")) { str1 = val1; } if (!val2.equals("")) { str1 = val1 + " " + val2; } if (!val3.equals("")) { str1 = val1 + " " + val2 + " " + val3; } if (!val4.equals("")) { str1 = val1 + " " + val2 + " " + val3 + " " + val4; } generateNpcList(activeChar, str1); String str = list.get(1); StringBuilder result2 = new StringBuilder(); content = content.replace("<?rewards?>", str); result2.append("<center><table width=690>"); result2.append("<tr>"); result2.append("<td WIDTH=690 align=center valign=top>"); result2.append("<center><button value=\""); result2.append("Следущая страница"); result2.append("\" action=\"bypass _bbsdroppage " + 2 + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result2.append("</td>"); result2.append("</tr>"); result2.append("</table></center>"); content = content.replace("<?pagenext?>", result2.toString()); ShowBoard.separateAndSend(content, activeChar); } else { activeChar.sendMessage("Please enter Object Etc Item Name. Example: Animal Bone"); } } else if (cmd.equalsIgnoreCase("_bbsdroppage")) { int page = Integer.parseInt(val1); int backpage = page - 1; int nextpage = page + 1; String content = HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "pages/rewards/rewardspage.htm", activeChar); String str = list.get(page); StringBuilder result = new StringBuilder(); if (str != null) { content = content.replace("<?rewards?>", str); } content = content.replace("<?copyright?>", HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "block/copyright.htm", activeChar)); String strback = list.get(backpage); if (strback != null) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Предыдущая страница"); result.append("\" action=\"bypass _bbsdroppage ").append(backpage).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } content = content.replace("<?pageback?>", result.length() > 0 ? result.toString() : ""); result = new StringBuilder(); String strnext = list.get(nextpage); if (strnext != null) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Следущая страница"); result.append("\" action=\"bypass _bbsdroppage ").append(nextpage).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } content = content.replace("<?pagenext?>", result.length() > 0 ? result.toString() : ""); ShowBoard.separateAndSend(content, activeChar); } else if (cmd.equalsIgnoreCase("_bbsdropnpcid")) { if (!val1.equals("")) { String content = HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "pages/rewards/mobsid.htm", activeChar); content = content.replace("<?copyright?>", HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "block/copyright.htm", activeChar)); content = content.replace("<?mobs?>", generateDropListAll(activeChar, Integer.parseInt(val1))); ShowBoard.separateAndSend(content, activeChar); } else { activeChar.sendMessage("Please enter the monster ID!"); } } else if (cmd.equalsIgnoreCase("_bbsdropnpcname")) { String content = HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "pages/rewards/mobs.htm", activeChar); content = content.replace("<?copyright?>", HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "block/copyright.htm", activeChar)); if (!val1.equals("")) { String str1 = null; if (!val1.equals("")) { str1 = val1; } if (!val2.equals("")) { str1 = val1 + " " + val2; } if (!val3.equals("")) { str1 = val1 + " " + val2 + " " + val3; } if (!val4.equals("")) { str1 = val1 + " " + val2 + " " + val3 + " " + val4; } generateDropListAll(activeChar, str1); String str = list2.get(1); StringBuilder result2 = new StringBuilder(); content = content.replace("<?mobs?>", str); result2.append("<center><table width=690>"); result2.append("<tr>"); result2.append("<td WIDTH=690 align=center valign=top>"); result2.append("<center><button value=\""); result2.append("Следущая страница"); result2.append("\" action=\"bypass _bbsdropnpcnamepage " + 2 + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result2.append("</td>"); result2.append("</tr>"); result2.append("</table></center>"); result2.append("<center><table width=690>"); result2.append("<tr>"); result2.append("<td WIDTH=690 align=center valign=top>"); result2.append("<center><button value=\""); result2.append("Новый поиск"); result2.append("\" action=\"bypass _bbsdroplist" + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result2.append("</td>"); result2.append("</tr>"); result2.append("</table></center>"); content = content.replace("<?pagenext?>", list2.get(2) != null ? result2.toString() : ""); ShowBoard.separateAndSend(content, activeChar); } else { activeChar.sendMessage("Please Enter the Monster name!"); } } else if (cmd.equalsIgnoreCase("_bbsdropnpcnamepage")) { int page = Integer.parseInt(val1); int backpage = page - 1; int nextpage = page + 1; String content = HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "pages/rewards/mobspage.htm", activeChar); content = content.replace("<?copyright?>", HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "block/copyright.htm", activeChar)); String str = list2.get(page); StringBuilder result = new StringBuilder(); content = content.replace("<?mobs?>", str); String strback = list2.get(backpage); if (strback != null) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Предыдущая страница"); result.append("\" action=\"bypass _bbsdropnpcnamepage ").append(backpage).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } content = content.replace("<?pageback?>", result.length() > 0 ? result.toString() : ""); result = new StringBuilder(); String strnext = list2.get(nextpage); if (strnext != null) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Следущая страница"); result.append("\" action=\"bypass _bbsdropnpcnamepage ").append(nextpage).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } content = content.replace("<?pagenext?>", result.length() > 0 ? result.toString() : ""); ShowBoard.separateAndSend(content, activeChar); } else if (cmd.equalsIgnoreCase("_bbsrewards")) { String content = HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "pages/rewards/rewards.htm", activeChar); content = content.replace("<?copyright?>", HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "block/copyright.htm", activeChar)); RewardType type = RewardType.valueOf(val2); if (!val1.equals("")) { generateDropListAll(activeChar, Integer.parseInt(val1), type); String str = list3.get(1); StringBuilder result = new StringBuilder(); content = content.replace("<?rewards?>", str); result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append(activeChar.getLanguage() == Language.RUSSIAN ? "Следущая страница" : "Next page"); result.append("\" action=\"bypass _bbsrewardspage " + 2 + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Новый поиск"); result.append("\" action=\"bypass _bbsdroplist" + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); content = content.replace("<?pagenext?>", list3.get(2) != null ? result.toString() : ""); } ShowBoard.separateAndSend(content, activeChar); } else if (cmd.equalsIgnoreCase("_bbsrewardspage")) { int page = Integer.parseInt(val1); int backpage = page - 1; int nextpage = page + 1; String content = HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "pages/rewards/rewardspage.htm", activeChar); content = content.replace("<?copyright?>", HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "block/copyright.htm", activeChar)); String str = list3.get(page); StringBuilder result = new StringBuilder(); content = content.replace("<?rewards?>", str); result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append(activeChar.getLanguage() == Language.RUSSIAN ? "Назад" : "Back"); result.append("\" action=\"bypass _bbsdroplist" + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); String strback = list3.get(backpage); if (strback != null) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Предыдущая страница"); result.append("\" action=\"bypass _bbsrewardspage ").append(backpage).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } content = content.replace("<?pageback?>", result.length() > 0 ? result.toString() : ""); result = new StringBuilder(); String strnext = list3.get(nextpage); if (strnext != null) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Следущая страница"); result.append("\" action=\"bypass _bbsrewardspage ").append(nextpage).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } content = content.replace("<?pagenext?>", result.length() > 0 ? result.toString() : ""); ShowBoard.separateAndSend(content, activeChar); } else if (cmd.equalsIgnoreCase("_bbsrewardradar")) { String content = HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "pages/rewards/rewards.htm", activeChar); content = content.replace("<?copyright?>", HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "block/copyright.htm", activeChar)); content = content.replace("<?rewards?>", generateDropListAll(activeChar, Integer.parseInt(val1))); content = content.replace("<?pagenext?>", ""); ShowBoard.separateAndSend(content, activeChar); NpcInstance npc = GameObjectsStorage.getByNpcId(Integer.parseInt(val1)); if (npc != null) { Spawner sp = npc.getSpawn(); if (sp != null) { for (NpcInstance spawn : sp.getAllSpawned()) { if (spawn != null) { activeChar.addRadar(spawn.getSpawnedLoc().getX(), spawn.getSpawnedLoc().getY(), spawn.getSpawnedLoc().getZ()); activeChar.addRadarWithMap(spawn.getSpawnedLoc().getX(), spawn.getSpawnedLoc().getY(), spawn.getSpawnedLoc().getZ()); break; } } } } } } /** * - Генерирует список всех монстров по ID предмета * * @param player * @param id * @return */ private void generateNpcList(Player player, int id) { list.clear(); StringBuilder result = new StringBuilder(); int count = 0; int count2 = 0; int page = 0; for (NpcTemplate npc : NpcHolder.getInstance().getAll()) { if (npc != null) { boolean next = false; if (npc.getRewards() == null || npc.getRewards().isEmpty() || npc.getRewards().isEmpty()) { continue; } for (Map.Entry<RewardType, RewardList> entry : npc.getRewards().entrySet()) { if (next) { break; } for (RewardGroup group : entry.getValue()) { if (next) { break; } if (group != null) { for (RewardData dat : group.getItems()) { if (dat.getItem().getItemId() == id) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append(npc.getName()); result.append("\" action=\"bypass _bbsdropnpcid ").append(npc.getNpcId()).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"><br1>").append(" Level: ").append(npc.level).append("</center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); count++; count2++; if (count == 5) { count = 0; page++; list.put(page, result.toString()); result = new StringBuilder(); } next = true; break; } } } } } } } if (count2 < 5 && count > 0) { page++; list.put(page, result.toString()); return; } if (list.isEmpty() || list == null || list.isEmpty()) { page++; result = new StringBuilder(); result.append("<table width=690><tr><td width=690><center><font name=\"hs12\" color=\"FF0000\">Предмет не найден</font></center></td></tr></table><br>"); result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Новый поиск"); result.append("\" action=\"bypass _bbsdroplist" + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); list.put(page, result.toString()); return; } list.put(page, result.toString()); } private void generateNpcList(Player player, String name) { list.clear(); StringBuilder result = new StringBuilder(); int count = 0; int count2 = 0; int page = 0; for (NpcTemplate npc : NpcHolder.getInstance().getAll()) { if (npc != null) { boolean next = false; if (npc.getRewards() == null || npc.getRewards().isEmpty() || npc.getRewards().isEmpty()) { continue; } for (Map.Entry<RewardType, RewardList> entry : npc.getRewards().entrySet()) { if (next) { break; } for (RewardGroup group : entry.getValue()) { if (next) { break; } if (group != null) { for (RewardData dat : group.getItems()) { if (dat.getItem().getName() != null && (dat.getItem().getName() == name || val2.equals("") ? dat.getItem().getName().startsWith(name) : dat.getItem().getName().contains(name) || dat.getItem().getName().equals(name) || dat.getItem().getName().equalsIgnoreCase(name))) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append(npc.getName()); result.append("\" action=\"bypass _bbsdropnpcid ").append(npc.getNpcId()).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"><br1>").append(" Level: ").append(npc.level).append("</center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); count++; count2++; if (count == 5) { count = 0; page++; list.put(page, result.toString()); result = new StringBuilder(); } next = true; break; } } } } } } } if (count2 < 5 && count > 0) { page++; list.put(page, result.toString()); return; } if (list.isEmpty() || list == null || list.isEmpty()) { page++; result = new StringBuilder(); result.append(player.getLanguage() == Language.RUSSIAN ? "<table width=690><tr><td width=690><center><font name=\"hs12\" color=\"FF0000\">Предмет не найден</font></center></td></tr></table><br>" : "<table width=690><tr><td width=690><center><font name=\"hs12\" color=\"FF0000\">Item not found</font></center></td></tr></table><br>"); result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Новый поиск"); result.append("\" action=\"bypass _bbsdroplist" + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); list.put(page, result.toString()); return; } list.put(page, result.toString()); } private String generateDropListAll(Player player, int id) { StringBuilder result = new StringBuilder(); NpcInstance npc = GameObjectsStorage.getByNpcId(id); if (npc != null) { if (npc.getTemplate().getRewardList(RewardType.RATED_GROUPED) != null && !npc.getTemplate().getRewardList(RewardType.RATED_GROUPED).isEmpty()) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Главная награда"); result.append("\" action=\"bypass _bbsrewards ").append(npc.getNpcId()).append(" ").append(RewardType.RATED_GROUPED).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } if (npc.getTemplate().getRewardList(RewardType.NOT_RATED_NOT_GROUPED) != null && !npc.getTemplate().getRewardList(RewardType.NOT_RATED_NOT_GROUPED).isEmpty()) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Дополнительная награда"); result.append("\" action=\"bypass _bbsrewards ").append(npc.getNpcId()).append(" ").append(RewardType.NOT_RATED_NOT_GROUPED).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } if (npc.getTemplate().getRewardList(RewardType.NOT_RATED_GROUPED) != null && !npc.getTemplate().getRewardList(RewardType.NOT_RATED_GROUPED).isEmpty()) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Хербы"); result.append("\" action=\"bypass _bbsrewards ").append(npc.getNpcId()).append(" ").append(RewardType.NOT_RATED_GROUPED).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } if (npc.getTemplate().getRewardList(RewardType.SWEEP) != null && !npc.getTemplate().getRewardList(RewardType.SWEEP).isEmpty()) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Спойл"); result.append("\" action=\"bypass _bbsrewards ").append(npc.getNpcId()).append(" ").append(RewardType.SWEEP).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Поставить радар"); result.append("\" action=\"bypass _bbsrewardradar ").append(npc.getNpcId()).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Новый поиск"); result.append("\" action=\"bypass _bbsdroplist" + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } else { result.append(player.getLanguage() == Language.RUSSIAN ? "<table width=690><tr><td width=690><center><font name=\"hs12\" color=\"FF0000\">Монстер не найден</font></center></td></tr></table><br>" : "<table width=690><tr><td width=690><center><font name=\"hs12\" color=\"FF0000\">Monster not found</font></center></td></tr></table><br>"); result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Новый поиск"); result.append("\" action=\"bypass _bbsdroplist" + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } return result.toString(); } private void generateDropListAll(Player player, String name) { list2.clear(); StringBuilder result = new StringBuilder(); int count = 0; int count2 = 0; int page = 0; Language lang = player.getLanguage(); for (NpcTemplate npc : NpcHolder.getInstance().getAll()) { if (npc != null && (npc.getName() == name || val2.equals("") ? npc.getName().startsWith(name) : npc.getName().contains(name) || npc.getName().equals(name) || npc.getName().equalsIgnoreCase(name))) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><font color=\"b09979\">").append(npc.getName()).append("</font></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); if (npc.getRewardList(RewardType.RATED_GROUPED) != null && !npc.getRewardList(RewardType.RATED_GROUPED).isEmpty()) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><br><br><button value=\""); if (lang == Language.RUSSIAN) { result.append("Главная награда"); } else { result.append("Home reward"); } result.append("\" action=\"bypass _bbsrewards ").append(npc.getNpcId()).append(" ").append(RewardType.RATED_GROUPED).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } if (npc.getRewardList(RewardType.NOT_RATED_NOT_GROUPED) != null && !npc.getRewardList(RewardType.NOT_RATED_NOT_GROUPED).isEmpty()) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><br><br><button value=\""); if (lang == Language.RUSSIAN) { result.append("Дополнительная награда"); } else { result.append("More reward"); } result.append("\" action=\"bypass _bbsrewards ").append(npc.getNpcId()).append(" ").append(RewardType.NOT_RATED_NOT_GROUPED).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } if (npc.getRewardList(RewardType.NOT_RATED_GROUPED) != null && !npc.getRewardList(RewardType.NOT_RATED_GROUPED).isEmpty()) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><br><br><button value=\""); if (lang == Language.RUSSIAN) { result.append("Хербы"); } else { result.append("Herbs"); } result.append("\" action=\"bypass _bbsrewards ").append(npc.getNpcId()).append(" ").append(RewardType.NOT_RATED_GROUPED).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } if (npc.getRewardList(RewardType.SWEEP) != null && !npc.getRewardList(RewardType.SWEEP).isEmpty()) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><br><br><button value=\""); if (lang == Language.RUSSIAN) { result.append("Спойл"); } else { result.append("Spoil"); } result.append("\" action=\"bypass _bbsrewards ").append(npc.getNpcId()).append(" ").append(RewardType.SWEEP).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><br><br><button value=\""); if (lang == Language.RUSSIAN) { result.append("Поставить радар"); } else { result.append("Place the Radar"); } result.append("\" action=\"bypass _bbsrewardradar ").append(npc.getNpcId()).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><br><br><button value=\""); result.append("Новый поиск"); result.append("\" action=\"bypass _bbsdroplist" + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); count++; count2++; if (count == 5) { count = 0; page++; list2.put(page, result.toString()); result = new StringBuilder(); } } } if (count2 < 5 && count > 0) { page++; list2.put(page, result.toString()); return; } if (list2.isEmpty() || list2 == null || list2.isEmpty()) { page++; result = new StringBuilder(); result.append(player.getLanguage() == Language.RUSSIAN ? "<table width=690><tr><td width=690><center><font name=\"hs12\" color=\"FF0000\">Монстер не найден</font></center></td></tr></table><br>" : "<table width=690><tr><td width=690><center><font name=\"hs12\" color=\"FF0000\">Monster not found</font></center></td></tr></table><br>"); result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><br><br><button value=\""); result.append("Новый поиск"); result.append("\" action=\"bypass _bbsdroplist" + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); list2.put(page, result.toString()); return; } page++; list2.put(page, result.toString()); } private void generateDropListAll(Player player, int id, RewardType type) { list3.clear(); NpcInstance npc = GameObjectsStorage.getByNpcId(id); if (npc != null) { final int diff = npc.calculateLevelDiffForDrop(player.isInParty() ? player.getParty().getLevel() : player.getLevel()); double mod = npc.calcStat(Stats.REWARD_MULTIPLIER, 1., player, null); mod *= Experience.penaltyModifier(diff, 9); switch (type) { case RATED_GROUPED: generateDropList(player, npc, mod); break; case NOT_RATED_GROUPED: generateDropListContinue(player, npc, mod); break; case NOT_RATED_NOT_GROUPED: generateDropListHerbs(player, npc, mod); break; case SWEEP: generateSpoilList(player, npc, mod); break; } } } /** * - Генерирует список всех предметов у монстра * * @param player * @param id * @return */ private void generateDropList(Player player, NpcInstance npc, double mod) { list3.clear(); int page = 0; if (npc != null) { for (RewardGroup g : npc.getTemplate().getRewardList(RewardType.RATED_GROUPED)) { StringBuilder result = new StringBuilder(); double gchance = g.getChance(); double gmod = mod; double grate; double gmult; double rateDrop = npc instanceof RaidBossInstance ? Config.RATE_DROP_RAIDBOSS : npc.isSiegeGuard() ? Config.RATE_DROP_SIEGE_GUARD : Config.RATE_DROP_ITEMS * player.getRateItems(); double rateAdena = Config.RATE_DROP_ADENA * player.getRateAdena(); if (g.isAdena()) { if (rateAdena == 0) { continue; } grate = rateAdena; if (gmod > 5) { gmod *= gchance / RewardList.MAX_CHANCE; gchance = RewardList.MAX_CHANCE; } grate *= gmod; } else { if (rateDrop == 0) { continue; } grate = rateDrop; if (g.notRate()) { grate = Math.min(gmod, 1.0); } else { grate *= gmod; } } gmult = Math.ceil(grate); for (RewardData d : g.getItems()) { double imult = d.notRate() ? 1.0 : gmult; String icon = d.getItem().getIcon(); if (icon == null || icon.equals(StringUtils.EMPTY)) { icon = "icon.etc_question_mark_i00"; } result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<table border=0 cellspacing=4 cellpadding=3>"); result.append("<tr>"); result.append("<td FIXWIDTH=50 align=right valign=top>"); result.append("<img src=\"").append(icon).append("\" width=32 height=32>"); result.append("</td>"); result.append("<td FIXWIDTH=671 align=left valign=top>"); result.append("<font color=\"0099FF\">Название предмета:</font> ").append(HtmlUtils.htmlItemName(d.getItemId())).append("<br1><font color=\"LEVEL\">Шанс выпадения:</font> ").append(pf.format(d.getChance() / RewardList.MAX_CHANCE)).append(" <font color=\"b09979\">[Min: ").append(Math.round(d.getMinDrop() * (g.isAdena() ? gmult : 1.0))).append(" | Max: ").append(Math.round(d.getMaxDrop() * imult)).append("]</font>"); result.append("</td>"); result.append("</tr>"); result.append("</table>"); result.append("<table border=0 cellspacing=0 cellpadding=0>"); result.append("<tr>"); result.append("<td width=690>"); result.append("<img src=\"l2ui.squaregray\" width=\"690\" height=\"1\">"); result.append("</td>"); result.append("</tr>"); result.append("</table>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } page++; list3.put(page, result.toString()); } } } public static void generateDropListContinue(Player player, NpcInstance npc, double mod) { list3.clear(); StringBuilder result = new StringBuilder(); int count = 0; int page = 0; if (npc != null) { for (RewardGroup g : npc.getTemplate().getRewardList(RewardType.NOT_RATED_GROUPED)) { double gchance = g.getChance(); result.append("<table><tr><td width=170><font color=\"a2a0a2\">Общий шанс группы: </font><font color=\"b09979\">").append(pf.format(gchance / RewardList.MAX_CHANCE)).append("</font></td></tr><table>"); for (RewardData d : g.getItems()) { String icon = d.getItem().getIcon(); if (icon == null || icon.equals(StringUtils.EMPTY)) { icon = "icon.etc_question_mark_i00"; } result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<table border=0 cellspacing=4 cellpadding=3>"); result.append("<tr>"); result.append("<td FIXWIDTH=50 align=right valign=top>"); result.append("<img src=\"").append(icon).append("\" width=32 height=32>"); result.append("</td>"); result.append("<td FIXWIDTH=671 align=left valign=top>"); result.append("<font color=\"0099FF\">Название предмета:</font> ").append(HtmlUtils.htmlItemName(d.getItemId())).append("<br1><font color=\"LEVEL\">Шанс выпадения:</font> ").append(pf.format(d.getChance() / RewardList.MAX_CHANCE)).append(" <font color=\"b09979\">[Min: ").append(Math.round(d.getMinDrop())).append(" | Max: ").append(Math.round(d.getMaxDrop())).append("]</font>"); result.append("</td>"); result.append("</tr>"); result.append("</table>"); result.append("<table border=0 cellspacing=0 cellpadding=0>"); result.append("<tr>"); result.append("<td width=690>"); result.append("<img src=\"l2ui.squaregray\" width=\"690\" height=\"1\">"); result.append("</td>"); result.append("</tr>"); result.append("</table>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); count++; if (count == 5) { count = 0; page++; list3.put(page, result.toString()); result = new StringBuilder(); result.append("<table><tr><td width=170><font color=\"a2a0a2\">Общий шанс группы: </font><font color=\"b09979\">").append(pf.format(gchance / RewardList.MAX_CHANCE)).append("</font></td></tr></table>"); } } } } page++; list3.put(page, result.toString()); } public static void generateDropListHerbs(Player player, NpcInstance npc, double mod) { list3.clear(); StringBuilder result = new StringBuilder(); int count = 0; int page = 0; if (npc != null) { for (RewardGroup g : npc.getTemplate().getRewardList(RewardType.NOT_RATED_NOT_GROUPED)) { double grate; double gmult; grate = 1; if (g.notRate()) { grate = Math.min(mod, 1.0); } else { grate *= mod; } gmult = Math.ceil(grate); for (RewardData d : g.getItems()) { double imult = d.notRate() ? 1.0 : gmult; String icon = d.getItem().getIcon(); if (icon == null || icon.equals(StringUtils.EMPTY)) { icon = "icon.etc_question_mark_i00"; } result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<table border=0 cellspacing=4 cellpadding=3>"); result.append("<tr>"); result.append("<td FIXWIDTH=50 align=right valign=top>"); result.append("<img src=\"").append(icon).append("\" width=32 height=32>"); result.append("</td>"); result.append("<td FIXWIDTH=671 align=left valign=top>"); result.append("<font color=\"0099FF\">Название предмета:</font> ").append(HtmlUtils.htmlItemName(d.getItemId())).append("<br1><font color=\"LEVEL\">Шанс выпадения:</font> ").append(pf.format(d.getChance() / RewardList.MAX_CHANCE)).append(" <font color=\"b09979\">[Min: ").append(Math.round(d.getMaxDrop() * imult)).append(" | Max: ").append(Math.round(d.getMaxDrop() * imult)).append("]</font>"); result.append("</td>"); result.append("</tr>"); result.append("</table>"); result.append("<table border=0 cellspacing=0 cellpadding=0>"); result.append("<tr>"); result.append("<td width=690>"); result.append("<img src=\"l2ui.squaregray\" width=\"690\" height=\"1\">"); result.append("</td>"); result.append("</tr>"); result.append("</table>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); count++; if (count == 5) { count = 0; page++; list3.put(page, result.toString()); result = new StringBuilder(); result.append("<table><tr><td><table width=270 border=0><tr><td><font color=\"aaccff\">Список хербов:</font></td></tr></table></td></tr></table>"); } } } } page++; list3.put(page, result.toString()); } public static void generateSpoilList(Player player, NpcInstance npc, double mod) { list3.clear(); StringBuilder result = new StringBuilder(); int count = 0; int page = 0; result.append("<table><tr><td><table width=270 border=0><tr><td><font color=\"aaccff\">Список спойла:</font></td></tr></table></td></tr></table>"); if (npc != null) { for (RewardGroup g : npc.getTemplate().getRewardList(RewardType.SWEEP)) { double grate; double gmult; grate = Config.RATE_DROP_SPOIL * player.getRateSpoil(); if (g.notRate()) { grate = Math.min(mod, 1.0); } else { grate *= mod; } gmult = Math.ceil(grate); for (RewardData d : g.getItems()) { double imult = d.notRate() ? 1.0 : gmult; String icon = d.getItem().getIcon(); if (icon == null || icon.equals(StringUtils.EMPTY)) { icon = "icon.etc_question_mark_i00"; } result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<table border=0 cellspacing=4 cellpadding=3>"); result.append("<tr>"); result.append("<td FIXWIDTH=50 align=right valign=top>"); result.append("<img src=\"").append(icon).append("\" width=32 height=32>"); result.append("</td>"); result.append("<td FIXWIDTH=671 align=left valign=top>"); result.append("<font color=\"0099FF\">Название предмета:</font> ").append(HtmlUtils.htmlItemName(d.getItemId())).append("<br1><font color=\"LEVEL\">Шанс выпадения:</font> ").append(pf.format(d.getChance() / RewardList.MAX_CHANCE)).append(" <font color=\"b09979\">[Min: ").append(d.getMinDrop()).append(" | Max: ").append(Math.round(d.getMaxDrop() * imult)).append("]</font>"); result.append("</td>"); result.append("</tr>"); result.append("</table>"); result.append("<table border=0 cellspacing=0 cellpadding=0>"); result.append("<tr>"); result.append("<td width=690>"); result.append("<img src=\"l2ui.squaregray\" width=\"690\" height=\"1\">"); result.append("</td>"); result.append("</tr>"); result.append("</table>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); count++; if (count == 5) { count = 0; page++; list3.put(page, result.toString()); result = new StringBuilder(); result.append("<table><tr><td><table width=270 border=0><tr><td><font color=\"aaccff\">Список спойла:</font></td></tr></table></td></tr></table>"); } } } } page++; list3.put(page, result.toString()); } @Override public void onWriteCommand(Player player, String bypass, String arg1, String arg2, String arg3, String arg4, String arg5) { } }
UTF-8
Java
58,508
java
CommunityBoardDropList.java
Java
[]
null
[]
package services.community; import java.text.NumberFormat; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; import l2p.gameserver.Config; import l2p.gameserver.data.htm.HtmCache; import l2p.gameserver.data.xml.holder.NpcHolder; import l2p.gameserver.handler.bbs.CommunityBoardManager; import l2p.gameserver.handler.bbs.ICommunityBoardHandler; import l2p.gameserver.model.GameObjectsStorage; import l2p.gameserver.model.Player; import l2p.gameserver.model.Spawner; import l2p.gameserver.model.base.Experience; import l2p.gameserver.model.instances.NpcInstance; import l2p.gameserver.model.instances.RaidBossInstance; import l2p.gameserver.model.reward.RewardData; import l2p.gameserver.model.reward.RewardGroup; import l2p.gameserver.model.reward.RewardList; import l2p.gameserver.model.reward.RewardType; import l2p.gameserver.serverpackets.ShowBoard; import l2p.gameserver.scripts.ScriptFile; import l2p.gameserver.stats.Stats; import l2p.gameserver.templates.npc.NpcTemplate; import l2p.gameserver.utils.HtmlUtils; import l2p.gameserver.utils.Language; import org.apache.commons.lang3.StringUtils; public class CommunityBoardDropList implements ScriptFile, ICommunityBoardHandler { private static CommunityBoardDropList _Instance = null; private static final NumberFormat pf = NumberFormat.getPercentInstance(Locale.ENGLISH); private static final NumberFormat df = NumberFormat.getInstance(Locale.ENGLISH); private static final Map<Integer, String> list = new HashMap<>(); private static final Map<Integer, String> list2 = new HashMap<>(); private static final Map<Integer, String> list3 = new HashMap<>(); private String val1 = ""; private String val2 = ""; private String val3 = ""; private String val4 = ""; static { pf.setMaximumFractionDigits(4); df.setMinimumFractionDigits(2); } public static CommunityBoardDropList getInstance() { if (_Instance == null) { _Instance = new CommunityBoardDropList(); } return _Instance; } @Override public void onLoad() { if (Config.COMMUNITYBOARD_ENABLED) { CommunityBoardManager.getInstance().registerHandler(this); } } @Override public void onReload() { if (Config.COMMUNITYBOARD_ENABLED) { CommunityBoardManager.getInstance().removeHandler(this); } } @Override public void onShutdown() { } @Override public String[] getBypassCommands() { return new String[]{ "_bbsdroplist", "_bbsrewardspage", "_bbsdropnpcnamepage", "_bbsdroppage", "_bbsdropid", "_bbsdropname", "_bbsdropnpcid", "_bbsdropnpcname", "_bbsrewards", "_bbsrewardradar"}; } @Override public void onBypassCommand(Player activeChar, String command) { StringTokenizer st = new StringTokenizer(command, " "); String cmd = st.nextToken(); val1 = ""; val2 = ""; val3 = ""; val4 = ""; if (st.countTokens() == 1) { val1 = st.nextToken(); } else if (st.countTokens() == 2) { val1 = st.nextToken(); val2 = st.nextToken(); } else if (st.countTokens() == 3) { val1 = st.nextToken(); val2 = st.nextToken(); val3 = st.nextToken(); } else if (st.countTokens() == 4) { val1 = st.nextToken(); val2 = st.nextToken(); val3 = st.nextToken(); val4 = st.nextToken(); } if (cmd.equalsIgnoreCase("_bbsdroplist")) { String content = HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "pages/rewards/list.htm", activeChar); content = content.replace("<?copyright?>", HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "block/copyright.htm", activeChar)); ShowBoard.separateAndSend(content, activeChar); } else if (cmd.equalsIgnoreCase("_bbsdropid")) { String content = HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "pages/rewards/rewards.htm", activeChar); content = content.replace("<?copyright?>", HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "block/copyright.htm", activeChar)); if (!val1.equals("")) { generateNpcList(activeChar, Integer.parseInt(val1)); String str = list.get(1); StringBuilder result2 = new StringBuilder(); content = content.replace("<?rewards?>", str); result2.append("<center><table width=690>"); result2.append("<tr>"); result2.append("<td WIDTH=690 align=center valign=top>"); result2.append("<center><button value=\""); result2.append(activeChar.getLanguage() == Language.RUSSIAN ? "Следущая страница" : "Next page"); result2.append("\" action=\"bypass _bbsdroppage " + 2 + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result2.append("</td>"); result2.append("</tr>"); result2.append("</table></center>"); content = content.replace("<?pagenext?>", list.get(2) != null ? result2.toString() : ""); ShowBoard.separateAndSend(content, activeChar); } else { activeChar.sendMessage("Please enter the Etc Item ID. Example: 57"); } } else if (cmd.equalsIgnoreCase("_bbsdropname")) { String content = HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "pages/rewards/rewards.htm", activeChar); content = content.replace("<?copyright?>", HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "block/copyright.htm", activeChar)); if (!val1.equals("")) { String str1 = null; if (!val1.equals("")) { str1 = val1; } if (!val2.equals("")) { str1 = val1 + " " + val2; } if (!val3.equals("")) { str1 = val1 + " " + val2 + " " + val3; } if (!val4.equals("")) { str1 = val1 + " " + val2 + " " + val3 + " " + val4; } generateNpcList(activeChar, str1); String str = list.get(1); StringBuilder result2 = new StringBuilder(); content = content.replace("<?rewards?>", str); result2.append("<center><table width=690>"); result2.append("<tr>"); result2.append("<td WIDTH=690 align=center valign=top>"); result2.append("<center><button value=\""); result2.append("Следущая страница"); result2.append("\" action=\"bypass _bbsdroppage " + 2 + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result2.append("</td>"); result2.append("</tr>"); result2.append("</table></center>"); content = content.replace("<?pagenext?>", result2.toString()); ShowBoard.separateAndSend(content, activeChar); } else { activeChar.sendMessage("Please enter Object Etc Item Name. Example: Animal Bone"); } } else if (cmd.equalsIgnoreCase("_bbsdroppage")) { int page = Integer.parseInt(val1); int backpage = page - 1; int nextpage = page + 1; String content = HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "pages/rewards/rewardspage.htm", activeChar); String str = list.get(page); StringBuilder result = new StringBuilder(); if (str != null) { content = content.replace("<?rewards?>", str); } content = content.replace("<?copyright?>", HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "block/copyright.htm", activeChar)); String strback = list.get(backpage); if (strback != null) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Предыдущая страница"); result.append("\" action=\"bypass _bbsdroppage ").append(backpage).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } content = content.replace("<?pageback?>", result.length() > 0 ? result.toString() : ""); result = new StringBuilder(); String strnext = list.get(nextpage); if (strnext != null) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Следущая страница"); result.append("\" action=\"bypass _bbsdroppage ").append(nextpage).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } content = content.replace("<?pagenext?>", result.length() > 0 ? result.toString() : ""); ShowBoard.separateAndSend(content, activeChar); } else if (cmd.equalsIgnoreCase("_bbsdropnpcid")) { if (!val1.equals("")) { String content = HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "pages/rewards/mobsid.htm", activeChar); content = content.replace("<?copyright?>", HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "block/copyright.htm", activeChar)); content = content.replace("<?mobs?>", generateDropListAll(activeChar, Integer.parseInt(val1))); ShowBoard.separateAndSend(content, activeChar); } else { activeChar.sendMessage("Please enter the monster ID!"); } } else if (cmd.equalsIgnoreCase("_bbsdropnpcname")) { String content = HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "pages/rewards/mobs.htm", activeChar); content = content.replace("<?copyright?>", HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "block/copyright.htm", activeChar)); if (!val1.equals("")) { String str1 = null; if (!val1.equals("")) { str1 = val1; } if (!val2.equals("")) { str1 = val1 + " " + val2; } if (!val3.equals("")) { str1 = val1 + " " + val2 + " " + val3; } if (!val4.equals("")) { str1 = val1 + " " + val2 + " " + val3 + " " + val4; } generateDropListAll(activeChar, str1); String str = list2.get(1); StringBuilder result2 = new StringBuilder(); content = content.replace("<?mobs?>", str); result2.append("<center><table width=690>"); result2.append("<tr>"); result2.append("<td WIDTH=690 align=center valign=top>"); result2.append("<center><button value=\""); result2.append("Следущая страница"); result2.append("\" action=\"bypass _bbsdropnpcnamepage " + 2 + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result2.append("</td>"); result2.append("</tr>"); result2.append("</table></center>"); result2.append("<center><table width=690>"); result2.append("<tr>"); result2.append("<td WIDTH=690 align=center valign=top>"); result2.append("<center><button value=\""); result2.append("Новый поиск"); result2.append("\" action=\"bypass _bbsdroplist" + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result2.append("</td>"); result2.append("</tr>"); result2.append("</table></center>"); content = content.replace("<?pagenext?>", list2.get(2) != null ? result2.toString() : ""); ShowBoard.separateAndSend(content, activeChar); } else { activeChar.sendMessage("Please Enter the Monster name!"); } } else if (cmd.equalsIgnoreCase("_bbsdropnpcnamepage")) { int page = Integer.parseInt(val1); int backpage = page - 1; int nextpage = page + 1; String content = HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "pages/rewards/mobspage.htm", activeChar); content = content.replace("<?copyright?>", HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "block/copyright.htm", activeChar)); String str = list2.get(page); StringBuilder result = new StringBuilder(); content = content.replace("<?mobs?>", str); String strback = list2.get(backpage); if (strback != null) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Предыдущая страница"); result.append("\" action=\"bypass _bbsdropnpcnamepage ").append(backpage).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } content = content.replace("<?pageback?>", result.length() > 0 ? result.toString() : ""); result = new StringBuilder(); String strnext = list2.get(nextpage); if (strnext != null) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Следущая страница"); result.append("\" action=\"bypass _bbsdropnpcnamepage ").append(nextpage).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } content = content.replace("<?pagenext?>", result.length() > 0 ? result.toString() : ""); ShowBoard.separateAndSend(content, activeChar); } else if (cmd.equalsIgnoreCase("_bbsrewards")) { String content = HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "pages/rewards/rewards.htm", activeChar); content = content.replace("<?copyright?>", HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "block/copyright.htm", activeChar)); RewardType type = RewardType.valueOf(val2); if (!val1.equals("")) { generateDropListAll(activeChar, Integer.parseInt(val1), type); String str = list3.get(1); StringBuilder result = new StringBuilder(); content = content.replace("<?rewards?>", str); result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append(activeChar.getLanguage() == Language.RUSSIAN ? "Следущая страница" : "Next page"); result.append("\" action=\"bypass _bbsrewardspage " + 2 + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Новый поиск"); result.append("\" action=\"bypass _bbsdroplist" + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); content = content.replace("<?pagenext?>", list3.get(2) != null ? result.toString() : ""); } ShowBoard.separateAndSend(content, activeChar); } else if (cmd.equalsIgnoreCase("_bbsrewardspage")) { int page = Integer.parseInt(val1); int backpage = page - 1; int nextpage = page + 1; String content = HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "pages/rewards/rewardspage.htm", activeChar); content = content.replace("<?copyright?>", HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "block/copyright.htm", activeChar)); String str = list3.get(page); StringBuilder result = new StringBuilder(); content = content.replace("<?rewards?>", str); result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append(activeChar.getLanguage() == Language.RUSSIAN ? "Назад" : "Back"); result.append("\" action=\"bypass _bbsdroplist" + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); String strback = list3.get(backpage); if (strback != null) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Предыдущая страница"); result.append("\" action=\"bypass _bbsrewardspage ").append(backpage).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } content = content.replace("<?pageback?>", result.length() > 0 ? result.toString() : ""); result = new StringBuilder(); String strnext = list3.get(nextpage); if (strnext != null) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Следущая страница"); result.append("\" action=\"bypass _bbsrewardspage ").append(nextpage).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } content = content.replace("<?pagenext?>", result.length() > 0 ? result.toString() : ""); ShowBoard.separateAndSend(content, activeChar); } else if (cmd.equalsIgnoreCase("_bbsrewardradar")) { String content = HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "pages/rewards/rewards.htm", activeChar); content = content.replace("<?copyright?>", HtmCache.getInstance().getHtml(Config.BBS_HOME_DIR + "block/copyright.htm", activeChar)); content = content.replace("<?rewards?>", generateDropListAll(activeChar, Integer.parseInt(val1))); content = content.replace("<?pagenext?>", ""); ShowBoard.separateAndSend(content, activeChar); NpcInstance npc = GameObjectsStorage.getByNpcId(Integer.parseInt(val1)); if (npc != null) { Spawner sp = npc.getSpawn(); if (sp != null) { for (NpcInstance spawn : sp.getAllSpawned()) { if (spawn != null) { activeChar.addRadar(spawn.getSpawnedLoc().getX(), spawn.getSpawnedLoc().getY(), spawn.getSpawnedLoc().getZ()); activeChar.addRadarWithMap(spawn.getSpawnedLoc().getX(), spawn.getSpawnedLoc().getY(), spawn.getSpawnedLoc().getZ()); break; } } } } } } /** * - Генерирует список всех монстров по ID предмета * * @param player * @param id * @return */ private void generateNpcList(Player player, int id) { list.clear(); StringBuilder result = new StringBuilder(); int count = 0; int count2 = 0; int page = 0; for (NpcTemplate npc : NpcHolder.getInstance().getAll()) { if (npc != null) { boolean next = false; if (npc.getRewards() == null || npc.getRewards().isEmpty() || npc.getRewards().isEmpty()) { continue; } for (Map.Entry<RewardType, RewardList> entry : npc.getRewards().entrySet()) { if (next) { break; } for (RewardGroup group : entry.getValue()) { if (next) { break; } if (group != null) { for (RewardData dat : group.getItems()) { if (dat.getItem().getItemId() == id) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append(npc.getName()); result.append("\" action=\"bypass _bbsdropnpcid ").append(npc.getNpcId()).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"><br1>").append(" Level: ").append(npc.level).append("</center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); count++; count2++; if (count == 5) { count = 0; page++; list.put(page, result.toString()); result = new StringBuilder(); } next = true; break; } } } } } } } if (count2 < 5 && count > 0) { page++; list.put(page, result.toString()); return; } if (list.isEmpty() || list == null || list.isEmpty()) { page++; result = new StringBuilder(); result.append("<table width=690><tr><td width=690><center><font name=\"hs12\" color=\"FF0000\">Предмет не найден</font></center></td></tr></table><br>"); result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Новый поиск"); result.append("\" action=\"bypass _bbsdroplist" + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); list.put(page, result.toString()); return; } list.put(page, result.toString()); } private void generateNpcList(Player player, String name) { list.clear(); StringBuilder result = new StringBuilder(); int count = 0; int count2 = 0; int page = 0; for (NpcTemplate npc : NpcHolder.getInstance().getAll()) { if (npc != null) { boolean next = false; if (npc.getRewards() == null || npc.getRewards().isEmpty() || npc.getRewards().isEmpty()) { continue; } for (Map.Entry<RewardType, RewardList> entry : npc.getRewards().entrySet()) { if (next) { break; } for (RewardGroup group : entry.getValue()) { if (next) { break; } if (group != null) { for (RewardData dat : group.getItems()) { if (dat.getItem().getName() != null && (dat.getItem().getName() == name || val2.equals("") ? dat.getItem().getName().startsWith(name) : dat.getItem().getName().contains(name) || dat.getItem().getName().equals(name) || dat.getItem().getName().equalsIgnoreCase(name))) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append(npc.getName()); result.append("\" action=\"bypass _bbsdropnpcid ").append(npc.getNpcId()).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"><br1>").append(" Level: ").append(npc.level).append("</center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); count++; count2++; if (count == 5) { count = 0; page++; list.put(page, result.toString()); result = new StringBuilder(); } next = true; break; } } } } } } } if (count2 < 5 && count > 0) { page++; list.put(page, result.toString()); return; } if (list.isEmpty() || list == null || list.isEmpty()) { page++; result = new StringBuilder(); result.append(player.getLanguage() == Language.RUSSIAN ? "<table width=690><tr><td width=690><center><font name=\"hs12\" color=\"FF0000\">Предмет не найден</font></center></td></tr></table><br>" : "<table width=690><tr><td width=690><center><font name=\"hs12\" color=\"FF0000\">Item not found</font></center></td></tr></table><br>"); result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Новый поиск"); result.append("\" action=\"bypass _bbsdroplist" + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); list.put(page, result.toString()); return; } list.put(page, result.toString()); } private String generateDropListAll(Player player, int id) { StringBuilder result = new StringBuilder(); NpcInstance npc = GameObjectsStorage.getByNpcId(id); if (npc != null) { if (npc.getTemplate().getRewardList(RewardType.RATED_GROUPED) != null && !npc.getTemplate().getRewardList(RewardType.RATED_GROUPED).isEmpty()) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Главная награда"); result.append("\" action=\"bypass _bbsrewards ").append(npc.getNpcId()).append(" ").append(RewardType.RATED_GROUPED).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } if (npc.getTemplate().getRewardList(RewardType.NOT_RATED_NOT_GROUPED) != null && !npc.getTemplate().getRewardList(RewardType.NOT_RATED_NOT_GROUPED).isEmpty()) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Дополнительная награда"); result.append("\" action=\"bypass _bbsrewards ").append(npc.getNpcId()).append(" ").append(RewardType.NOT_RATED_NOT_GROUPED).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } if (npc.getTemplate().getRewardList(RewardType.NOT_RATED_GROUPED) != null && !npc.getTemplate().getRewardList(RewardType.NOT_RATED_GROUPED).isEmpty()) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Хербы"); result.append("\" action=\"bypass _bbsrewards ").append(npc.getNpcId()).append(" ").append(RewardType.NOT_RATED_GROUPED).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } if (npc.getTemplate().getRewardList(RewardType.SWEEP) != null && !npc.getTemplate().getRewardList(RewardType.SWEEP).isEmpty()) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Спойл"); result.append("\" action=\"bypass _bbsrewards ").append(npc.getNpcId()).append(" ").append(RewardType.SWEEP).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Поставить радар"); result.append("\" action=\"bypass _bbsrewardradar ").append(npc.getNpcId()).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Новый поиск"); result.append("\" action=\"bypass _bbsdroplist" + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } else { result.append(player.getLanguage() == Language.RUSSIAN ? "<table width=690><tr><td width=690><center><font name=\"hs12\" color=\"FF0000\">Монстер не найден</font></center></td></tr></table><br>" : "<table width=690><tr><td width=690><center><font name=\"hs12\" color=\"FF0000\">Monster not found</font></center></td></tr></table><br>"); result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><button value=\""); result.append("Новый поиск"); result.append("\" action=\"bypass _bbsdroplist" + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } return result.toString(); } private void generateDropListAll(Player player, String name) { list2.clear(); StringBuilder result = new StringBuilder(); int count = 0; int count2 = 0; int page = 0; Language lang = player.getLanguage(); for (NpcTemplate npc : NpcHolder.getInstance().getAll()) { if (npc != null && (npc.getName() == name || val2.equals("") ? npc.getName().startsWith(name) : npc.getName().contains(name) || npc.getName().equals(name) || npc.getName().equalsIgnoreCase(name))) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><font color=\"b09979\">").append(npc.getName()).append("</font></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); if (npc.getRewardList(RewardType.RATED_GROUPED) != null && !npc.getRewardList(RewardType.RATED_GROUPED).isEmpty()) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><br><br><button value=\""); if (lang == Language.RUSSIAN) { result.append("Главная награда"); } else { result.append("Home reward"); } result.append("\" action=\"bypass _bbsrewards ").append(npc.getNpcId()).append(" ").append(RewardType.RATED_GROUPED).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } if (npc.getRewardList(RewardType.NOT_RATED_NOT_GROUPED) != null && !npc.getRewardList(RewardType.NOT_RATED_NOT_GROUPED).isEmpty()) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><br><br><button value=\""); if (lang == Language.RUSSIAN) { result.append("Дополнительная награда"); } else { result.append("More reward"); } result.append("\" action=\"bypass _bbsrewards ").append(npc.getNpcId()).append(" ").append(RewardType.NOT_RATED_NOT_GROUPED).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } if (npc.getRewardList(RewardType.NOT_RATED_GROUPED) != null && !npc.getRewardList(RewardType.NOT_RATED_GROUPED).isEmpty()) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><br><br><button value=\""); if (lang == Language.RUSSIAN) { result.append("Хербы"); } else { result.append("Herbs"); } result.append("\" action=\"bypass _bbsrewards ").append(npc.getNpcId()).append(" ").append(RewardType.NOT_RATED_GROUPED).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } if (npc.getRewardList(RewardType.SWEEP) != null && !npc.getRewardList(RewardType.SWEEP).isEmpty()) { result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><br><br><button value=\""); if (lang == Language.RUSSIAN) { result.append("Спойл"); } else { result.append("Spoil"); } result.append("\" action=\"bypass _bbsrewards ").append(npc.getNpcId()).append(" ").append(RewardType.SWEEP).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><br><br><button value=\""); if (lang == Language.RUSSIAN) { result.append("Поставить радар"); } else { result.append("Place the Radar"); } result.append("\" action=\"bypass _bbsrewardradar ").append(npc.getNpcId()).append("\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><br><br><button value=\""); result.append("Новый поиск"); result.append("\" action=\"bypass _bbsdroplist" + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); count++; count2++; if (count == 5) { count = 0; page++; list2.put(page, result.toString()); result = new StringBuilder(); } } } if (count2 < 5 && count > 0) { page++; list2.put(page, result.toString()); return; } if (list2.isEmpty() || list2 == null || list2.isEmpty()) { page++; result = new StringBuilder(); result.append(player.getLanguage() == Language.RUSSIAN ? "<table width=690><tr><td width=690><center><font name=\"hs12\" color=\"FF0000\">Монстер не найден</font></center></td></tr></table><br>" : "<table width=690><tr><td width=690><center><font name=\"hs12\" color=\"FF0000\">Monster not found</font></center></td></tr></table><br>"); result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<center><br><br><button value=\""); result.append("Новый поиск"); result.append("\" action=\"bypass _bbsdroplist" + "\" width=200 height=29 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); list2.put(page, result.toString()); return; } page++; list2.put(page, result.toString()); } private void generateDropListAll(Player player, int id, RewardType type) { list3.clear(); NpcInstance npc = GameObjectsStorage.getByNpcId(id); if (npc != null) { final int diff = npc.calculateLevelDiffForDrop(player.isInParty() ? player.getParty().getLevel() : player.getLevel()); double mod = npc.calcStat(Stats.REWARD_MULTIPLIER, 1., player, null); mod *= Experience.penaltyModifier(diff, 9); switch (type) { case RATED_GROUPED: generateDropList(player, npc, mod); break; case NOT_RATED_GROUPED: generateDropListContinue(player, npc, mod); break; case NOT_RATED_NOT_GROUPED: generateDropListHerbs(player, npc, mod); break; case SWEEP: generateSpoilList(player, npc, mod); break; } } } /** * - Генерирует список всех предметов у монстра * * @param player * @param id * @return */ private void generateDropList(Player player, NpcInstance npc, double mod) { list3.clear(); int page = 0; if (npc != null) { for (RewardGroup g : npc.getTemplate().getRewardList(RewardType.RATED_GROUPED)) { StringBuilder result = new StringBuilder(); double gchance = g.getChance(); double gmod = mod; double grate; double gmult; double rateDrop = npc instanceof RaidBossInstance ? Config.RATE_DROP_RAIDBOSS : npc.isSiegeGuard() ? Config.RATE_DROP_SIEGE_GUARD : Config.RATE_DROP_ITEMS * player.getRateItems(); double rateAdena = Config.RATE_DROP_ADENA * player.getRateAdena(); if (g.isAdena()) { if (rateAdena == 0) { continue; } grate = rateAdena; if (gmod > 5) { gmod *= gchance / RewardList.MAX_CHANCE; gchance = RewardList.MAX_CHANCE; } grate *= gmod; } else { if (rateDrop == 0) { continue; } grate = rateDrop; if (g.notRate()) { grate = Math.min(gmod, 1.0); } else { grate *= gmod; } } gmult = Math.ceil(grate); for (RewardData d : g.getItems()) { double imult = d.notRate() ? 1.0 : gmult; String icon = d.getItem().getIcon(); if (icon == null || icon.equals(StringUtils.EMPTY)) { icon = "icon.etc_question_mark_i00"; } result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<table border=0 cellspacing=4 cellpadding=3>"); result.append("<tr>"); result.append("<td FIXWIDTH=50 align=right valign=top>"); result.append("<img src=\"").append(icon).append("\" width=32 height=32>"); result.append("</td>"); result.append("<td FIXWIDTH=671 align=left valign=top>"); result.append("<font color=\"0099FF\">Название предмета:</font> ").append(HtmlUtils.htmlItemName(d.getItemId())).append("<br1><font color=\"LEVEL\">Шанс выпадения:</font> ").append(pf.format(d.getChance() / RewardList.MAX_CHANCE)).append(" <font color=\"b09979\">[Min: ").append(Math.round(d.getMinDrop() * (g.isAdena() ? gmult : 1.0))).append(" | Max: ").append(Math.round(d.getMaxDrop() * imult)).append("]</font>"); result.append("</td>"); result.append("</tr>"); result.append("</table>"); result.append("<table border=0 cellspacing=0 cellpadding=0>"); result.append("<tr>"); result.append("<td width=690>"); result.append("<img src=\"l2ui.squaregray\" width=\"690\" height=\"1\">"); result.append("</td>"); result.append("</tr>"); result.append("</table>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); } page++; list3.put(page, result.toString()); } } } public static void generateDropListContinue(Player player, NpcInstance npc, double mod) { list3.clear(); StringBuilder result = new StringBuilder(); int count = 0; int page = 0; if (npc != null) { for (RewardGroup g : npc.getTemplate().getRewardList(RewardType.NOT_RATED_GROUPED)) { double gchance = g.getChance(); result.append("<table><tr><td width=170><font color=\"a2a0a2\">Общий шанс группы: </font><font color=\"b09979\">").append(pf.format(gchance / RewardList.MAX_CHANCE)).append("</font></td></tr><table>"); for (RewardData d : g.getItems()) { String icon = d.getItem().getIcon(); if (icon == null || icon.equals(StringUtils.EMPTY)) { icon = "icon.etc_question_mark_i00"; } result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<table border=0 cellspacing=4 cellpadding=3>"); result.append("<tr>"); result.append("<td FIXWIDTH=50 align=right valign=top>"); result.append("<img src=\"").append(icon).append("\" width=32 height=32>"); result.append("</td>"); result.append("<td FIXWIDTH=671 align=left valign=top>"); result.append("<font color=\"0099FF\">Название предмета:</font> ").append(HtmlUtils.htmlItemName(d.getItemId())).append("<br1><font color=\"LEVEL\">Шанс выпадения:</font> ").append(pf.format(d.getChance() / RewardList.MAX_CHANCE)).append(" <font color=\"b09979\">[Min: ").append(Math.round(d.getMinDrop())).append(" | Max: ").append(Math.round(d.getMaxDrop())).append("]</font>"); result.append("</td>"); result.append("</tr>"); result.append("</table>"); result.append("<table border=0 cellspacing=0 cellpadding=0>"); result.append("<tr>"); result.append("<td width=690>"); result.append("<img src=\"l2ui.squaregray\" width=\"690\" height=\"1\">"); result.append("</td>"); result.append("</tr>"); result.append("</table>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); count++; if (count == 5) { count = 0; page++; list3.put(page, result.toString()); result = new StringBuilder(); result.append("<table><tr><td width=170><font color=\"a2a0a2\">Общий шанс группы: </font><font color=\"b09979\">").append(pf.format(gchance / RewardList.MAX_CHANCE)).append("</font></td></tr></table>"); } } } } page++; list3.put(page, result.toString()); } public static void generateDropListHerbs(Player player, NpcInstance npc, double mod) { list3.clear(); StringBuilder result = new StringBuilder(); int count = 0; int page = 0; if (npc != null) { for (RewardGroup g : npc.getTemplate().getRewardList(RewardType.NOT_RATED_NOT_GROUPED)) { double grate; double gmult; grate = 1; if (g.notRate()) { grate = Math.min(mod, 1.0); } else { grate *= mod; } gmult = Math.ceil(grate); for (RewardData d : g.getItems()) { double imult = d.notRate() ? 1.0 : gmult; String icon = d.getItem().getIcon(); if (icon == null || icon.equals(StringUtils.EMPTY)) { icon = "icon.etc_question_mark_i00"; } result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<table border=0 cellspacing=4 cellpadding=3>"); result.append("<tr>"); result.append("<td FIXWIDTH=50 align=right valign=top>"); result.append("<img src=\"").append(icon).append("\" width=32 height=32>"); result.append("</td>"); result.append("<td FIXWIDTH=671 align=left valign=top>"); result.append("<font color=\"0099FF\">Название предмета:</font> ").append(HtmlUtils.htmlItemName(d.getItemId())).append("<br1><font color=\"LEVEL\">Шанс выпадения:</font> ").append(pf.format(d.getChance() / RewardList.MAX_CHANCE)).append(" <font color=\"b09979\">[Min: ").append(Math.round(d.getMaxDrop() * imult)).append(" | Max: ").append(Math.round(d.getMaxDrop() * imult)).append("]</font>"); result.append("</td>"); result.append("</tr>"); result.append("</table>"); result.append("<table border=0 cellspacing=0 cellpadding=0>"); result.append("<tr>"); result.append("<td width=690>"); result.append("<img src=\"l2ui.squaregray\" width=\"690\" height=\"1\">"); result.append("</td>"); result.append("</tr>"); result.append("</table>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); count++; if (count == 5) { count = 0; page++; list3.put(page, result.toString()); result = new StringBuilder(); result.append("<table><tr><td><table width=270 border=0><tr><td><font color=\"aaccff\">Список хербов:</font></td></tr></table></td></tr></table>"); } } } } page++; list3.put(page, result.toString()); } public static void generateSpoilList(Player player, NpcInstance npc, double mod) { list3.clear(); StringBuilder result = new StringBuilder(); int count = 0; int page = 0; result.append("<table><tr><td><table width=270 border=0><tr><td><font color=\"aaccff\">Список спойла:</font></td></tr></table></td></tr></table>"); if (npc != null) { for (RewardGroup g : npc.getTemplate().getRewardList(RewardType.SWEEP)) { double grate; double gmult; grate = Config.RATE_DROP_SPOIL * player.getRateSpoil(); if (g.notRate()) { grate = Math.min(mod, 1.0); } else { grate *= mod; } gmult = Math.ceil(grate); for (RewardData d : g.getItems()) { double imult = d.notRate() ? 1.0 : gmult; String icon = d.getItem().getIcon(); if (icon == null || icon.equals(StringUtils.EMPTY)) { icon = "icon.etc_question_mark_i00"; } result.append("<center><table width=690>"); result.append("<tr>"); result.append("<td WIDTH=690 align=center valign=top>"); result.append("<table border=0 cellspacing=4 cellpadding=3>"); result.append("<tr>"); result.append("<td FIXWIDTH=50 align=right valign=top>"); result.append("<img src=\"").append(icon).append("\" width=32 height=32>"); result.append("</td>"); result.append("<td FIXWIDTH=671 align=left valign=top>"); result.append("<font color=\"0099FF\">Название предмета:</font> ").append(HtmlUtils.htmlItemName(d.getItemId())).append("<br1><font color=\"LEVEL\">Шанс выпадения:</font> ").append(pf.format(d.getChance() / RewardList.MAX_CHANCE)).append(" <font color=\"b09979\">[Min: ").append(d.getMinDrop()).append(" | Max: ").append(Math.round(d.getMaxDrop() * imult)).append("]</font>"); result.append("</td>"); result.append("</tr>"); result.append("</table>"); result.append("<table border=0 cellspacing=0 cellpadding=0>"); result.append("<tr>"); result.append("<td width=690>"); result.append("<img src=\"l2ui.squaregray\" width=\"690\" height=\"1\">"); result.append("</td>"); result.append("</tr>"); result.append("</table>"); result.append("</td>"); result.append("</tr>"); result.append("</table></center>"); count++; if (count == 5) { count = 0; page++; list3.put(page, result.toString()); result = new StringBuilder(); result.append("<table><tr><td><table width=270 border=0><tr><td><font color=\"aaccff\">Список спойла:</font></td></tr></table></td></tr></table>"); } } } } page++; list3.put(page, result.toString()); } @Override public void onWriteCommand(Player player, String bypass, String arg1, String arg2, String arg3, String arg4, String arg5) { } }
58,508
0.504133
0.486337
1,170
48.420513
48.91394
438
true
false
0
0
0
0
0
0
0.777778
false
false
7
910fa92cfe143785844be0cdf8f442eae7398ef9
32,427,003,131,407
b25bc27814268b64d937913c8286b416d78e6d37
/web/src/main/java/com/baidu/oped/apm/model/service/ApplicationService.java
c18f9f62c23aee77770955754ecf02332b9f1e9d
[]
no_license
masonmei/apm
https://github.com/masonmei/apm
d6a276ac79a5edeb6cfcac3ff5411b9577a3627b
d95c027113f7274d275adb0b9352a16aa76043f5
refs/heads/master
2020-05-17T21:45:53.292000
2015-12-01T11:04:46
2015-12-01T11:04:46
40,586,633
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.baidu.oped.apm.model.service; import static com.baidu.oped.apm.utils.TimeUtils.toMillisSecond; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import com.baidu.oped.apm.common.jpa.entity.Application; import com.baidu.oped.apm.common.jpa.entity.ApplicationStatistic; import com.baidu.oped.apm.common.jpa.entity.Instance; import com.baidu.oped.apm.common.jpa.entity.InstanceStatistic; import com.baidu.oped.apm.common.jpa.entity.QApplication; import com.baidu.oped.apm.common.jpa.entity.QApplicationStatistic; import com.baidu.oped.apm.common.jpa.entity.QInstance; import com.baidu.oped.apm.common.jpa.entity.QInstanceStatistic; import com.baidu.oped.apm.common.jpa.repository.ApplicationRepository; import com.baidu.oped.apm.common.jpa.repository.ApplicationStatisticRepository; import com.baidu.oped.apm.common.jpa.repository.InstanceRepository; import com.baidu.oped.apm.common.jpa.repository.InstanceStatisticRepository; import com.baidu.oped.apm.mvc.vo.TimeRange; import com.baidu.oped.apm.utils.PageUtils; import com.mysema.query.types.expr.BooleanExpression; /** * Created by mason on 8/12/15. */ @Service public class ApplicationService { @Autowired ApplicationRepository applicationRepository; @Autowired ApplicationStatisticRepository applicationStatisticRepository; @Autowired InstanceRepository instanceRepository; @Autowired InstanceStatisticRepository instanceStatisticRepository; public Page<Application> selectApplications(String userId, String orderBy, int pageSize, int pageNumber) { QApplication application = QApplication.application; BooleanExpression userEq = application.userId.eq(userId); Sort sort = PageUtils.toSort(orderBy); Pageable pageable = new PageRequest(pageNumber, pageSize, sort); return applicationRepository.findAll(userEq, pageable); } /** * @param timeRange * @param apps * @param period in Second * * @return */ public Iterable<ApplicationStatistic> selectApplicationStatistics(TimeRange timeRange, Iterable<Application> apps, Long period) { final long periodInMillis = period * 1000; List<Long> appIds = StreamSupport.stream(apps.spliterator(), false).map(Application::getId).collect(Collectors.toList()); QApplicationStatistic appStatistic = QApplicationStatistic.applicationStatistic; BooleanExpression timestampCondition = appStatistic.timestamp.between(toMillisSecond(timeRange.getFrom()), toMillisSecond(timeRange.getTo())); BooleanExpression appIdCondition = appStatistic.appId.in(appIds); BooleanExpression periodCondition = appStatistic.period.eq(periodInMillis); BooleanExpression whereCondition = timestampCondition.and(appIdCondition).and(periodCondition); return applicationStatisticRepository.findAll(whereCondition); } public Page<Instance> selectInstances(long appId, String orderBy, int pageSize, int pageNumber) { QInstance instance = QInstance.instance; Sort sort = PageUtils.toSort(orderBy); Pageable pageable = new PageRequest(pageNumber, pageSize, sort); return instanceRepository.findAll(instance.appId.eq(appId), pageable); } /** * @param timeRange * @param instances * @param period in Second * * @return */ public Iterable<InstanceStatistic> selectInstanceStatistics(TimeRange timeRange, List<Instance> instances, Long period) { final long periodInMillis = period * 1000; List<Long> instanceIds = StreamSupport.stream(instances.spliterator(), false).map(Instance::getId).collect(Collectors.toList()); QInstanceStatistic instanceStatistic = QInstanceStatistic.instanceStatistic; BooleanExpression timestampCondition = instanceStatistic.timestamp.between( toMillisSecond(timeRange.getFrom()), toMillisSecond(timeRange.getTo())); BooleanExpression instanceIdCondition = instanceStatistic.instanceId.in(instanceIds); BooleanExpression periodCondition = instanceStatistic.period.eq(periodInMillis); BooleanExpression whereCondition = instanceIdCondition.and(timestampCondition).and(periodCondition); return instanceStatisticRepository.findAll(whereCondition); } }
UTF-8
Java
4,761
java
ApplicationService.java
Java
[ { "context": "y.types.expr.BooleanExpression;\n\n/**\n * Created by mason on 8/12/15.\n */\n@Service\npublic class Application", "end": 1455, "score": 0.9993813633918762, "start": 1450, "tag": "USERNAME", "value": "mason" } ]
null
[]
package com.baidu.oped.apm.model.service; import static com.baidu.oped.apm.utils.TimeUtils.toMillisSecond; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import com.baidu.oped.apm.common.jpa.entity.Application; import com.baidu.oped.apm.common.jpa.entity.ApplicationStatistic; import com.baidu.oped.apm.common.jpa.entity.Instance; import com.baidu.oped.apm.common.jpa.entity.InstanceStatistic; import com.baidu.oped.apm.common.jpa.entity.QApplication; import com.baidu.oped.apm.common.jpa.entity.QApplicationStatistic; import com.baidu.oped.apm.common.jpa.entity.QInstance; import com.baidu.oped.apm.common.jpa.entity.QInstanceStatistic; import com.baidu.oped.apm.common.jpa.repository.ApplicationRepository; import com.baidu.oped.apm.common.jpa.repository.ApplicationStatisticRepository; import com.baidu.oped.apm.common.jpa.repository.InstanceRepository; import com.baidu.oped.apm.common.jpa.repository.InstanceStatisticRepository; import com.baidu.oped.apm.mvc.vo.TimeRange; import com.baidu.oped.apm.utils.PageUtils; import com.mysema.query.types.expr.BooleanExpression; /** * Created by mason on 8/12/15. */ @Service public class ApplicationService { @Autowired ApplicationRepository applicationRepository; @Autowired ApplicationStatisticRepository applicationStatisticRepository; @Autowired InstanceRepository instanceRepository; @Autowired InstanceStatisticRepository instanceStatisticRepository; public Page<Application> selectApplications(String userId, String orderBy, int pageSize, int pageNumber) { QApplication application = QApplication.application; BooleanExpression userEq = application.userId.eq(userId); Sort sort = PageUtils.toSort(orderBy); Pageable pageable = new PageRequest(pageNumber, pageSize, sort); return applicationRepository.findAll(userEq, pageable); } /** * @param timeRange * @param apps * @param period in Second * * @return */ public Iterable<ApplicationStatistic> selectApplicationStatistics(TimeRange timeRange, Iterable<Application> apps, Long period) { final long periodInMillis = period * 1000; List<Long> appIds = StreamSupport.stream(apps.spliterator(), false).map(Application::getId).collect(Collectors.toList()); QApplicationStatistic appStatistic = QApplicationStatistic.applicationStatistic; BooleanExpression timestampCondition = appStatistic.timestamp.between(toMillisSecond(timeRange.getFrom()), toMillisSecond(timeRange.getTo())); BooleanExpression appIdCondition = appStatistic.appId.in(appIds); BooleanExpression periodCondition = appStatistic.period.eq(periodInMillis); BooleanExpression whereCondition = timestampCondition.and(appIdCondition).and(periodCondition); return applicationStatisticRepository.findAll(whereCondition); } public Page<Instance> selectInstances(long appId, String orderBy, int pageSize, int pageNumber) { QInstance instance = QInstance.instance; Sort sort = PageUtils.toSort(orderBy); Pageable pageable = new PageRequest(pageNumber, pageSize, sort); return instanceRepository.findAll(instance.appId.eq(appId), pageable); } /** * @param timeRange * @param instances * @param period in Second * * @return */ public Iterable<InstanceStatistic> selectInstanceStatistics(TimeRange timeRange, List<Instance> instances, Long period) { final long periodInMillis = period * 1000; List<Long> instanceIds = StreamSupport.stream(instances.spliterator(), false).map(Instance::getId).collect(Collectors.toList()); QInstanceStatistic instanceStatistic = QInstanceStatistic.instanceStatistic; BooleanExpression timestampCondition = instanceStatistic.timestamp.between( toMillisSecond(timeRange.getFrom()), toMillisSecond(timeRange.getTo())); BooleanExpression instanceIdCondition = instanceStatistic.instanceId.in(instanceIds); BooleanExpression periodCondition = instanceStatistic.period.eq(periodInMillis); BooleanExpression whereCondition = instanceIdCondition.and(timestampCondition).and(periodCondition); return instanceStatisticRepository.findAll(whereCondition); } }
4,761
0.751943
0.749212
116
40.043102
34.520958
119
false
false
0
0
0
0
0
0
0.646552
false
false
7
9506247354a48a42dc88138685c534db7b80c15b
32,427,003,131,464
01aa5e006e647154bbfa00fecb7acebde30064fd
/web/java/kr/ac/sunmoon/mybatis/EmpDaoImpl.java
49806e221dc0aff2224b630e4a425821c2f425af
[]
no_license
ndporn12/testWeb
https://github.com/ndporn12/testWeb
1086313509e4b731f86d0b4b8f54ab5976a3b305
ba73437ca4555b41f579f4936c387e6b5b2e5ca1
refs/heads/master
2022-12-25T03:02:21.838000
2019-11-19T11:27:03
2019-11-19T11:27:03
222,679,779
0
0
null
false
2022-12-16T04:28:53
2019-11-19T11:24:54
2019-11-19T11:27:10
2022-12-16T04:28:49
28
0
0
6
Java
false
false
package kr.ac.sunmoon.mybatis; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.HashMap; import java.util.Map; public class EmpDaoImpl implements EmpDao{ public void insert(Map<String, String> parameter) { try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "mybatis", "mybatis$"); } catch (Exception e) { e.printStackTrace(); } } public Map<String, String> select(int no) { Map<String, String> map = new HashMap<String, String>(); String sql = "SELECT EMPNO, ENAME FROM EMP WHERE EMPNO=" + no; Connection connection = null; Statement statement =null; ResultSet resultSet = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "mybatis", "mybatis$"); statement = connection.prepareStatement(sql); resultSet = statement.executeQuery(sql); if(resultSet.next()) { String empNo = resultSet.getString("EMPNO"); String eName = resultSet.getString("ENAME"); map.put("EMPNO", empNo); map.put("ENAME", eName); } } catch (Exception e) { e.printStackTrace(); }finally { try { connection.close(); } catch (Exception e) { e.printStackTrace(); } } return map; } }
UTF-8
Java
1,489
java
EmpDaoImpl.java
Java
[]
null
[]
package kr.ac.sunmoon.mybatis; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.HashMap; import java.util.Map; public class EmpDaoImpl implements EmpDao{ public void insert(Map<String, String> parameter) { try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "mybatis", "mybatis$"); } catch (Exception e) { e.printStackTrace(); } } public Map<String, String> select(int no) { Map<String, String> map = new HashMap<String, String>(); String sql = "SELECT EMPNO, ENAME FROM EMP WHERE EMPNO=" + no; Connection connection = null; Statement statement =null; ResultSet resultSet = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "mybatis", "mybatis$"); statement = connection.prepareStatement(sql); resultSet = statement.executeQuery(sql); if(resultSet.next()) { String empNo = resultSet.getString("EMPNO"); String eName = resultSet.getString("ENAME"); map.put("EMPNO", empNo); map.put("ENAME", eName); } } catch (Exception e) { e.printStackTrace(); }finally { try { connection.close(); } catch (Exception e) { e.printStackTrace(); } } return map; } }
1,489
0.660846
0.655473
56
24.589285
24.346294
117
false
false
0
0
0
0
0
0
2.589286
false
false
7
92915d594a783c0d57c213eeb92692408d542345
6,365,141,570,955
dfb8c79b8cfc38a4c0e3ce8c4053870f610e9ca1
/java/learn-design-patterns/src/create/factory/simplefactory/SimpleFactory.java
f458e4f49fc682de7e859b341e060dc0305985b6
[ "Apache-2.0" ]
permissive
fendoudebb/learning
https://github.com/fendoudebb/learning
4c9bcaa57165e632527cb6262aaaa8f5df52665f
2cd9390687474f50caefb27ab8d2d0ecfbc22d2b
refs/heads/master
2022-10-23T02:04:41.785000
2022-10-20T01:03:20
2022-10-20T01:03:20
198,789,029
1
2
Apache-2.0
false
2022-10-26T08:02:38
2019-07-25T08:19:37
2022-01-10T23:51:18
2022-10-26T08:02:38
3,279
1
2
6
Java
false
false
package create.factory.simplefactory; import create.factory.bean.CheesePizza; import create.factory.bean.PepperPizza; import create.factory.bean.Pizza; /** * 简单工厂模式,也叫静态工厂模式 * @see java.util.Calendar#createCalendar 用到了简单工厂 */ public class SimpleFactory { public Pizza createPizza(String type) { Pizza pizza = null; switch (type) { case "cheese": pizza = new CheesePizza(); break; case "pepper": pizza = new PepperPizza(); break; default: break; } return pizza; } }
UTF-8
Java
673
java
SimpleFactory.java
Java
[]
null
[]
package create.factory.simplefactory; import create.factory.bean.CheesePizza; import create.factory.bean.PepperPizza; import create.factory.bean.Pizza; /** * 简单工厂模式,也叫静态工厂模式 * @see java.util.Calendar#createCalendar 用到了简单工厂 */ public class SimpleFactory { public Pizza createPizza(String type) { Pizza pizza = null; switch (type) { case "cheese": pizza = new CheesePizza(); break; case "pepper": pizza = new PepperPizza(); break; default: break; } return pizza; } }
673
0.562798
0.562798
29
20.689655
15.536616
49
false
false
0
0
0
0
0
0
0.37931
false
false
7
2536be236e5fd41c745a01cae08d342c8343d5ee
32,375,463,548,251
831da10dd66a0a57f69d30e53cf5186dd7276643
/server/src/main/java/org/sherman/geo/common/util/Maps.java
04b60fcae893cacc7b10e36a1ca3b9a2fb68949e
[]
no_license
MyWayToJavaJunior/geo-server
https://github.com/MyWayToJavaJunior/geo-server
8d63c40b7f2571ac4c1a43a7be96e9884b3e822a
ea87f7fb7f6915e03808238a2179aef1c683c800
refs/heads/master
2021-01-19T20:49:20.344000
2016-09-17T19:24:50
2016-09-17T19:24:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.sherman.geo.common.util; import org.jetbrains.annotations.NotNull; import java.util.concurrent.ConcurrentMap; public class Maps { private Maps() { } @NotNull public static <K, V> V atomicPut(@NotNull ConcurrentMap<K, V> map, @NotNull K key, @NotNull V value) { final V prev = map.putIfAbsent(key, value); if (prev != null) { return prev; } return value; } }
UTF-8
Java
438
java
Maps.java
Java
[]
null
[]
package org.sherman.geo.common.util; import org.jetbrains.annotations.NotNull; import java.util.concurrent.ConcurrentMap; public class Maps { private Maps() { } @NotNull public static <K, V> V atomicPut(@NotNull ConcurrentMap<K, V> map, @NotNull K key, @NotNull V value) { final V prev = map.putIfAbsent(key, value); if (prev != null) { return prev; } return value; } }
438
0.621005
0.621005
19
22.052631
25.257565
106
false
false
0
0
0
0
0
0
0.578947
false
false
7
5ffa96f3178f4df322eaac51b2290eb465211310
18,829,136,661,442
f55291d9c07ec157ae37938cc1951fd279447c21
/Tower Defense/src/logica/entidad/DirectorPowerUp/DirectorPowerUpAliado.java
a6a38425943400a5473b6e45b21582e467bfd222
[]
no_license
Doomlash/Margaritas-vs-orcos-voladores
https://github.com/Doomlash/Margaritas-vs-orcos-voladores
19a82bf4664ec8f13b831de94f66535a561c4ac3
9017d80e2c97ac2c762a02e910b127205de3a821
refs/heads/master
2021-01-19T18:05:32.475000
2017-11-18T02:06:27
2017-11-18T02:06:27
101,114,313
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package logica.entidad.DirectorPowerUp; import logica.entidad.aliado.*; import logica.modificador_PowerUp.*; import logica.comprables.*; public class DirectorPowerUpAliado extends DirectorPowerUp{ private Upgrade mejora; public DirectorPowerUpAliado(Aliado a){ super(a); } public void receive(RalentizadorAgua r){ } public void receive(Upgrade u){ if(mejora==null){ mejora=u; entidad.afectar(u); } else{ if(mejora==u){ mejora.kill(); mejora=null; } else{ mejora.kill(); mejora=u; entidad.afectar(u); } } } }
UTF-8
Java
569
java
DirectorPowerUpAliado.java
Java
[]
null
[]
package logica.entidad.DirectorPowerUp; import logica.entidad.aliado.*; import logica.modificador_PowerUp.*; import logica.comprables.*; public class DirectorPowerUpAliado extends DirectorPowerUp{ private Upgrade mejora; public DirectorPowerUpAliado(Aliado a){ super(a); } public void receive(RalentizadorAgua r){ } public void receive(Upgrade u){ if(mejora==null){ mejora=u; entidad.afectar(u); } else{ if(mejora==u){ mejora.kill(); mejora=null; } else{ mejora.kill(); mejora=u; entidad.afectar(u); } } } }
569
0.681898
0.681898
33
16.272728
14.885976
59
false
false
0
0
0
0
0
0
2.151515
false
false
7
6c777433da0f6bdf000ea410eb4010e74ecd1d9e
18,829,136,661,669
13c2d3db2d49c40c74c2e6420a9cd89377f1c934
/program_data/JavaProgramData/96/1120.java
fd273fddb68f430e89acd846e4eba3dcdd54e16c
[ "MIT" ]
permissive
qiuchili/ggnn_graph_classification
https://github.com/qiuchili/ggnn_graph_classification
c2090fefe11f8bf650e734442eb96996a54dc112
291ff02404555511b94a4f477c6974ebd62dcf44
refs/heads/master
2021-10-18T14:54:26.154000
2018-10-21T23:34:14
2018-10-21T23:34:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package <missing>; public class GlobalMembers { public static int Main() { String n = new String(new char[100]); int[] a = new int[100]; int[] b = new int[100]; int yu; int i; int j; int x; String tempVar = ConsoleInput.scanfRead(); if (tempVar != null) { n = tempVar.charAt(0); } x = n.length(); for (i = 0;i < x;i++) { a[i] = n.charAt(i) - '0'; } if (x == 1) { System.out.printf("0\n%d",a[0]); } else { if (x == 2 && (a[0] * 10 + a[1] < 13)) { System.out.printf("0\n%d",a[0] * 10 + a[1]); } else { b[0] = (10 * a[0] + a[1]) / 13; yu = (10 * a[0] + a[1]) % 13; if (b[0] != 0) { System.out.printf("%d",b[0]); for (i = 2;i < x;i++) { b[i - 1] = (yu * 10 + a[i]) / 13; yu = (yu * 10 + a[i]) % 13; } for (i = 1;i < x - 1;i++) { System.out.printf("%d",b[i]); } System.out.printf("\n%d",yu); } if (b[0] == 0) { b[0] = (100 * a[0] + 10 * a[1] + a[2]) / 13; yu = (100 * a[0] + 10 * a[1] + a[2]) % 13; System.out.printf("%d",b[0]); for (i = 3;i < x;i++) { b[i - 2] = (yu * 10 + a[i]) / 13; yu = (yu * 10 + a[i]) % 13; } for (i = 1;i < x - 2;i++) { System.out.printf("%d",b[i]); } System.out.printf("\n%d",yu); } } } return 0; } }
UTF-8
Java
1,200
java
1120.java
Java
[]
null
[]
package <missing>; public class GlobalMembers { public static int Main() { String n = new String(new char[100]); int[] a = new int[100]; int[] b = new int[100]; int yu; int i; int j; int x; String tempVar = ConsoleInput.scanfRead(); if (tempVar != null) { n = tempVar.charAt(0); } x = n.length(); for (i = 0;i < x;i++) { a[i] = n.charAt(i) - '0'; } if (x == 1) { System.out.printf("0\n%d",a[0]); } else { if (x == 2 && (a[0] * 10 + a[1] < 13)) { System.out.printf("0\n%d",a[0] * 10 + a[1]); } else { b[0] = (10 * a[0] + a[1]) / 13; yu = (10 * a[0] + a[1]) % 13; if (b[0] != 0) { System.out.printf("%d",b[0]); for (i = 2;i < x;i++) { b[i - 1] = (yu * 10 + a[i]) / 13; yu = (yu * 10 + a[i]) % 13; } for (i = 1;i < x - 1;i++) { System.out.printf("%d",b[i]); } System.out.printf("\n%d",yu); } if (b[0] == 0) { b[0] = (100 * a[0] + 10 * a[1] + a[2]) / 13; yu = (100 * a[0] + 10 * a[1] + a[2]) % 13; System.out.printf("%d",b[0]); for (i = 3;i < x;i++) { b[i - 2] = (yu * 10 + a[i]) / 13; yu = (yu * 10 + a[i]) % 13; } for (i = 1;i < x - 2;i++) { System.out.printf("%d",b[i]); } System.out.printf("\n%d",yu); } } } return 0; } }
1,200
0.446667
0.37
72
15.652778
14.088175
46
false
false
0
0
0
0
0
0
1.708333
false
false
7
237396ba9f429726b5ed6c1894be074f2fd289a4
6,365,141,550,111
7c55cd4e3496eba37fe43527ad3e8ed5a2ab7178
/src/main/java/com/qa/ims/persistence/domain/Order.java
8b2e13f766db308898873d384dcf1a059a320d64
[ "MIT" ]
permissive
BenSimonQA/IMSStarterBenQA
https://github.com/BenSimonQA/IMSStarterBenQA
b80cd9e6c0e0a97c77578921986c7032caaad56b
8cc7fd11c40bba9d48e467062ca96f9dde3bc471
refs/heads/main
2023-01-29T06:18:02.082000
2020-11-27T14:57:01
2020-11-27T14:57:01
316,462,758
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qa.ims.persistence.domain; import java.util.List; public class Order { private Long id; private Long customer_id; private List<Item> item_id; private Long item_price; public Order(Long customer_id) { this.customer_id = customer_id; } public Order(Long id, Long customer_id) { this.id = id; this.customer_id = customer_id; } public Order(Long id ,Long customer_id, List<Item> item_id) { this.id = id; this.customer_id = customer_id; this.item_id = item_id; } public Order(Long id ,Long customer_id, List<Item> item_id, Long item_price) { this.id = id; this.customer_id = customer_id; this.item_id = item_id; this.item_price = item_price; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getCustomerId() { return customer_id; } public void setCustomerId(Long customer_id) { this.customer_id = customer_id; } public List<Item> getItemId() { return item_id; } public void setItemId(List<Item> item_id) { this.item_id = item_id; } @Override public String toString() { return "id:" + id + " customer id:" + customer_id + " item_id:" + item_id + " total_price:" + item_price; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Order other = (Order) obj; if (customer_id == null) { if (other.customer_id != null) return false; } else if (!customer_id.equals(other.customer_id)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (item_id == null) { if (other.item_id != null) return false; } else if (!item_id.equals(other.item_id)) return false; return true; } }
UTF-8
Java
1,831
java
Order.java
Java
[]
null
[]
package com.qa.ims.persistence.domain; import java.util.List; public class Order { private Long id; private Long customer_id; private List<Item> item_id; private Long item_price; public Order(Long customer_id) { this.customer_id = customer_id; } public Order(Long id, Long customer_id) { this.id = id; this.customer_id = customer_id; } public Order(Long id ,Long customer_id, List<Item> item_id) { this.id = id; this.customer_id = customer_id; this.item_id = item_id; } public Order(Long id ,Long customer_id, List<Item> item_id, Long item_price) { this.id = id; this.customer_id = customer_id; this.item_id = item_id; this.item_price = item_price; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getCustomerId() { return customer_id; } public void setCustomerId(Long customer_id) { this.customer_id = customer_id; } public List<Item> getItemId() { return item_id; } public void setItemId(List<Item> item_id) { this.item_id = item_id; } @Override public String toString() { return "id:" + id + " customer id:" + customer_id + " item_id:" + item_id + " total_price:" + item_price; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Order other = (Order) obj; if (customer_id == null) { if (other.customer_id != null) return false; } else if (!customer_id.equals(other.customer_id)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (item_id == null) { if (other.item_id != null) return false; } else if (!item_id.equals(other.item_id)) return false; return true; } }
1,831
0.64118
0.64118
91
19.120878
18.367336
107
false
false
0
0
0
0
0
0
1.846154
false
false
7
b594bf514d90b00a1967262a93f8d550a2816421
23,733,989,279,079
1b133b266935e6651ccb255ccad3f37e3373e29a
/2.JavaCore/src/com/javarush/task/task18/task1823/Solution.java
833e38ea4451d04ec18275a807680f805f7082ce
[]
no_license
Sky53/JavaRushTasks
https://github.com/Sky53/JavaRushTasks
3fa05f8f85876a5ce15b22784ef5a4e1dbde7f13
cb546c799d2bd1983197096c316ae62ccf51337e
refs/heads/master
2020-04-11T12:27:08.727000
2018-12-14T12:21:15
2018-12-14T12:21:15
161,780,807
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.javarush.task.task18.task1823; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; /* Нити и байты */ public class Solution { public static Map<String, Integer> resultMap = new HashMap<String, Integer>(); public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String filename; while (!(filename = reader.readLine()).equals("exit")) { new ReadThread(filename).start(); } reader.close(); } public static class ReadThread extends Thread { String fileName; public ReadThread(String fileName) { //implement constructor body this.fileName = fileName; } // implement file reading here - реализуйте чтение из файла тут @Override public void run() { try { while (!interrupted()) { FileInputStream in = new FileInputStream(fileName); ArrayList<Integer> list = new ArrayList<>(); while (in.available() > 0) { list.add(in.read()); } int maxFrequancy = Collections.frequency(list, list.get(0)); int key = list.get(0); for (int i = 1; i < list.size(); i++) { int frequancy = Collections.frequency(list, list.get(i)); if (maxFrequancy < frequancy) { maxFrequancy = frequancy; key = list.get(i); } } resultMap.put(fileName, key); in.close(); Thread.currentThread().interrupt(); } } catch (Exception e) { System.out.println(e); } } } }
UTF-8
Java
2,150
java
Solution.java
Java
[ { "context": "ort java.util.HashMap;\nimport java.util.Map;\n\n/* \nНити и байты\n*/\n\npublic class Solution {\n public st", "end": 284, "score": 0.8302085995674133, "start": 280, "tag": "NAME", "value": "Нити" }, { "context": "va.util.HashMap;\nimport java.util.Map;\n\n/* \nНити и байты\n*/\n\npublic class Solution {\n public static Map", "end": 292, "score": 0.8968517184257507, "start": 287, "tag": "NAME", "value": "байты" } ]
null
[]
package com.javarush.task.task18.task1823; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; /* Нити и байты */ public class Solution { public static Map<String, Integer> resultMap = new HashMap<String, Integer>(); public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String filename; while (!(filename = reader.readLine()).equals("exit")) { new ReadThread(filename).start(); } reader.close(); } public static class ReadThread extends Thread { String fileName; public ReadThread(String fileName) { //implement constructor body this.fileName = fileName; } // implement file reading here - реализуйте чтение из файла тут @Override public void run() { try { while (!interrupted()) { FileInputStream in = new FileInputStream(fileName); ArrayList<Integer> list = new ArrayList<>(); while (in.available() > 0) { list.add(in.read()); } int maxFrequancy = Collections.frequency(list, list.get(0)); int key = list.get(0); for (int i = 1; i < list.size(); i++) { int frequancy = Collections.frequency(list, list.get(i)); if (maxFrequancy < frequancy) { maxFrequancy = frequancy; key = list.get(i); } } resultMap.put(fileName, key); in.close(); Thread.currentThread().interrupt(); } } catch (Exception e) { System.out.println(e); } } } }
2,150
0.523652
0.518921
68
30.07353
24.036318
85
false
false
0
0
0
0
0
0
0.514706
false
false
7
37ff18b5b562e2418e89044cccf91acb1f912b0d
4,020,089,453,619
e277e7ccc330c30cd0f694342b0fc931e72693d1
/src/uk/ac/imperial/simelec/OccupancyModel.java
d225641c13dab07dc0d4a2b57a86184c499272a4
[]
no_license
vcaballero-salle/simelec
https://github.com/vcaballero-salle/simelec
532640d5242eba3e9144d4a4f57fdf90f2634a41
12216200de3d4d2097cfe6dfd2f418ef841e0335
refs/heads/master
2020-06-04T07:37:12.318000
2019-06-14T13:30:39
2019-06-14T13:30:39
191,927,472
0
0
null
true
2019-06-14T10:53:25
2019-06-14T10:53:24
2014-05-21T10:04:24
2014-05-20T19:47:20
900
0
0
0
null
false
false
/* Domestic Active Occupancy Model - Simulation Example Code Copyright (C) 2008 Ian Richardson, Murray Thomson CREST (Centre for Renewable Energy Systems Technology), Department of Electronic and Electrical Engineering Loughborough University, Leicestershire LE11 3TU, UK Tel. +44 1509 635326. Email address: I.W.Richardson@lboro.ac.uk Java Implementation (c) 2014 James Keirstead Imperial College London j.keirstead@imperial.ac.uk This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.ac.imperial.simelec; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import au.com.bytecode.opencsv.CSVReader; import au.com.bytecode.opencsv.CSVWriter; /** * Simulates the number of active occupants within a household for a single day * at ten-minute intervals. * * @author James Keirstead * */ public class OccupancyModel { // Class variables private int nResidents; private boolean weekend; private String out_dir; private File out_file; private boolean has_run = false; // Data variables private static String start_states_weekend = "/data/occ_start_states_weekend.csv"; private static String start_states_weekday = "/data/occ_start_states_weekday.csv"; private static String template = "/data/tpm_%d_%s.csv"; /** * Simulates the number of active occupants within a household for a single * day at ten-minute intervals. * * @param args * a String array specifying the number of residents, a * two-letter code for weekend (<code>we</code>) or weekday ( * <code>wd</code>), and a String giving the output directory for * the results. An optional fourth argument can be specified, an * int giving a random number seed. If these are not specified, * the default is to simulate two occupants for a weekday with * results saved in the current directory. */ public static void main(String[] args) { int residents; boolean weekend; String output_dir; // Check the inputs if (args.length == 3 || args.length == 4) { residents = Integer.valueOf(args[0]); weekend = args[1].equals("we") ? true : false; output_dir = args[2]; if (args.length == 4) { DiscretePDF.setSeed(Integer.valueOf(args[3])); } } else { System.out.printf( "%d arguments detected. Using default arguments.%n", args.length); residents = 2; weekend = false; output_dir = "."; } // Build the model OccupancyModel model = new OccupancyModel(residents, weekend, output_dir); // Run the model try { model.run(); } catch (IOException e) { e.printStackTrace(); } } /** * Create a new OccupancyModel with a specified number of residents, * simulation day, and output directory * * @param residents * an int between 1 and 5 giving the number of residents * @param weekend * a boolean indicating whether to simulate a weekday ( * <code>false</code>) or weekend (<code>true</code>) * @param dir * a String giving the output directory */ public OccupancyModel(int residents, boolean weekend, String dir) { this.nResidents = SimElec.validateResidents(residents); this.weekend = weekend; this.out_dir = dir; this.out_file = OccupancyModel.getOutputFile(dir); } /** * Gets the preferred output file for an OccupancyModel running in a specified directory. * * @param dir the output directory * @return the output File */ protected static File getOutputFile(String dir) { return new File(dir, "occupancy_output.csv"); } /** * Simulate the number of active occupants in a domestic dwelling for a * single day at ten-minute intervals. * * @throws IOException */ public void run() throws IOException { // System.out.print("Running occupancy model..."); // Ensure the output directory exists File dir = new File(this.out_dir); if (!dir.isDirectory()) dir.mkdirs(); // Step 2: Determine the active occupancy start state between 00:00 and // 00:10 // Load in the start state data from occ_start_states String filename = weekend ? start_states_weekend : start_states_weekday; InputStream is = this.getClass().getResourceAsStream(filename); CSVReader reader = new CSVReader(new InputStreamReader(is), ',', '\'', 2); List<String[]> myEntries = reader.readAll(); reader.close(); double[] vector = new double[myEntries.size()]; // vector = n rows int j = 0; for (String[] s : myEntries) { vector[j] = Float.valueOf(s[nResidents]); j++; } // Draw from the cumulative distribution DiscretePDF pdf = new DiscretePDF(vector); int initialState = pdf.getRandomIndex(); // Step 3: Determine the active occupancy transitions for each ten // minute period of the day. // First load in the correct file filename = String.format(template, nResidents, weekend ? "weekend" : "weekday"); is = this.getClass().getResourceAsStream(filename); reader = new CSVReader(new InputStreamReader(is), ',', '\'', 1); myEntries = reader.readAll(); reader.close(); // Create a list to save the results List<String[]> results = new ArrayList<String[]>(144); String[] tmp = { "1", String.valueOf(initialState) }; results.add(tmp); // Already have initial state; so iterate over remaining entries for (int t = 1; t < 144; t++) { // First calculate the row int rowID = (t - 1) * 7 + initialState; String[] row = myEntries.get(rowID); // Grab the vector of transition probabilities vector = new double[row.length - 2]; for (int i = 2; i < row.length - 2; i++) { vector[i - 2] = Float.valueOf(row[i]); } // Draw for the probability pdf = new DiscretePDF(vector); int newState = pdf.getRandomIndex(); String[] tmp2 = { String.valueOf(t + 1), String.valueOf(newState) }; results.add(tmp2); initialState = newState; } // Save the result to a CSV file CSVWriter writer = new CSVWriter(new FileWriter(out_file), ',', '\0'); writer.writeAll(results); writer.close(); has_run = true; // System.out.println("done."); } /** * Retrieves occupancy data calculated by this OccupancyModel. * * @return an array of 144 int values giving the occupancy at ten-minute * intervals during the day * @throws IOException */ public int[] getOccupancy() throws IOException { if (!has_run) this.run(); CSVReader reader = new CSVReader(new FileReader(out_file)); List<String[]> myEntries = reader.readAll(); reader.close(); int[] result = new int[myEntries.size()]; for (int i = 0; i < myEntries.size(); i++) { result[i] = Integer.valueOf(myEntries.get(i)[1]); } return (result); } }
UTF-8
Java
7,484
java
OccupancyModel.java
Java
[ { "context": " - Simulation Example Code\n\n Copyright (C) 2008 Ian Richardson, Murray Thomson\n CREST (Centre for Renewable E", "end": 102, "score": 0.9998807907104492, "start": 88, "tag": "NAME", "value": "Ian Richardson" }, { "context": "ample Code\n\n Copyright (C) 2008 Ian Richardson, Murray Thomson\n CREST (Centre for Renewable Energy Systems Te", "end": 118, "score": 0.9998816847801208, "start": 104, "tag": "NAME", "value": "Murray Thomson" }, { "context": "1 3TU, UK\n Tel. +44 1509 635326. Email address: I.W.Richardson@lboro.ac.uk\n\n\tJava Implementation (c) 2014 James Keirstead\n\tI", "end": 359, "score": 0.9999297261238098, "start": 333, "tag": "EMAIL", "value": "I.W.Richardson@lboro.ac.uk" }, { "context": "hardson@lboro.ac.uk\n\n\tJava Implementation (c) 2014 James Keirstead\n\tImperial College London\n\tj.keirstead@imperial.ac", "end": 406, "score": 0.9999023079872131, "start": 391, "tag": "NAME", "value": "James Keirstead" }, { "context": "c) 2014 James Keirstead\n\tImperial College London\n\tj.keirstead@imperial.ac.uk\n\t\n This program is free software: you can redi", "end": 459, "score": 0.9999352097511292, "start": 433, "tag": "EMAIL", "value": "j.keirstead@imperial.ac.uk" }, { "context": "gle day\n * at ten-minute intervals.\n * \n * @author James Keirstead\n * \n */\npublic class OccupancyModel {\n\n\t// Class ", "end": 1595, "score": 0.9998999834060669, "start": 1580, "tag": "NAME", "value": "James Keirstead" } ]
null
[]
/* Domestic Active Occupancy Model - Simulation Example Code Copyright (C) 2008 <NAME>, <NAME> CREST (Centre for Renewable Energy Systems Technology), Department of Electronic and Electrical Engineering Loughborough University, Leicestershire LE11 3TU, UK Tel. +44 1509 635326. Email address: <EMAIL> Java Implementation (c) 2014 <NAME> Imperial College London <EMAIL> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.ac.imperial.simelec; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import au.com.bytecode.opencsv.CSVReader; import au.com.bytecode.opencsv.CSVWriter; /** * Simulates the number of active occupants within a household for a single day * at ten-minute intervals. * * @author <NAME> * */ public class OccupancyModel { // Class variables private int nResidents; private boolean weekend; private String out_dir; private File out_file; private boolean has_run = false; // Data variables private static String start_states_weekend = "/data/occ_start_states_weekend.csv"; private static String start_states_weekday = "/data/occ_start_states_weekday.csv"; private static String template = "/data/tpm_%d_%s.csv"; /** * Simulates the number of active occupants within a household for a single * day at ten-minute intervals. * * @param args * a String array specifying the number of residents, a * two-letter code for weekend (<code>we</code>) or weekday ( * <code>wd</code>), and a String giving the output directory for * the results. An optional fourth argument can be specified, an * int giving a random number seed. If these are not specified, * the default is to simulate two occupants for a weekday with * results saved in the current directory. */ public static void main(String[] args) { int residents; boolean weekend; String output_dir; // Check the inputs if (args.length == 3 || args.length == 4) { residents = Integer.valueOf(args[0]); weekend = args[1].equals("we") ? true : false; output_dir = args[2]; if (args.length == 4) { DiscretePDF.setSeed(Integer.valueOf(args[3])); } } else { System.out.printf( "%d arguments detected. Using default arguments.%n", args.length); residents = 2; weekend = false; output_dir = "."; } // Build the model OccupancyModel model = new OccupancyModel(residents, weekend, output_dir); // Run the model try { model.run(); } catch (IOException e) { e.printStackTrace(); } } /** * Create a new OccupancyModel with a specified number of residents, * simulation day, and output directory * * @param residents * an int between 1 and 5 giving the number of residents * @param weekend * a boolean indicating whether to simulate a weekday ( * <code>false</code>) or weekend (<code>true</code>) * @param dir * a String giving the output directory */ public OccupancyModel(int residents, boolean weekend, String dir) { this.nResidents = SimElec.validateResidents(residents); this.weekend = weekend; this.out_dir = dir; this.out_file = OccupancyModel.getOutputFile(dir); } /** * Gets the preferred output file for an OccupancyModel running in a specified directory. * * @param dir the output directory * @return the output File */ protected static File getOutputFile(String dir) { return new File(dir, "occupancy_output.csv"); } /** * Simulate the number of active occupants in a domestic dwelling for a * single day at ten-minute intervals. * * @throws IOException */ public void run() throws IOException { // System.out.print("Running occupancy model..."); // Ensure the output directory exists File dir = new File(this.out_dir); if (!dir.isDirectory()) dir.mkdirs(); // Step 2: Determine the active occupancy start state between 00:00 and // 00:10 // Load in the start state data from occ_start_states String filename = weekend ? start_states_weekend : start_states_weekday; InputStream is = this.getClass().getResourceAsStream(filename); CSVReader reader = new CSVReader(new InputStreamReader(is), ',', '\'', 2); List<String[]> myEntries = reader.readAll(); reader.close(); double[] vector = new double[myEntries.size()]; // vector = n rows int j = 0; for (String[] s : myEntries) { vector[j] = Float.valueOf(s[nResidents]); j++; } // Draw from the cumulative distribution DiscretePDF pdf = new DiscretePDF(vector); int initialState = pdf.getRandomIndex(); // Step 3: Determine the active occupancy transitions for each ten // minute period of the day. // First load in the correct file filename = String.format(template, nResidents, weekend ? "weekend" : "weekday"); is = this.getClass().getResourceAsStream(filename); reader = new CSVReader(new InputStreamReader(is), ',', '\'', 1); myEntries = reader.readAll(); reader.close(); // Create a list to save the results List<String[]> results = new ArrayList<String[]>(144); String[] tmp = { "1", String.valueOf(initialState) }; results.add(tmp); // Already have initial state; so iterate over remaining entries for (int t = 1; t < 144; t++) { // First calculate the row int rowID = (t - 1) * 7 + initialState; String[] row = myEntries.get(rowID); // Grab the vector of transition probabilities vector = new double[row.length - 2]; for (int i = 2; i < row.length - 2; i++) { vector[i - 2] = Float.valueOf(row[i]); } // Draw for the probability pdf = new DiscretePDF(vector); int newState = pdf.getRandomIndex(); String[] tmp2 = { String.valueOf(t + 1), String.valueOf(newState) }; results.add(tmp2); initialState = newState; } // Save the result to a CSV file CSVWriter writer = new CSVWriter(new FileWriter(out_file), ',', '\0'); writer.writeAll(results); writer.close(); has_run = true; // System.out.println("done."); } /** * Retrieves occupancy data calculated by this OccupancyModel. * * @return an array of 144 int values giving the occupancy at ten-minute * intervals during the day * @throws IOException */ public int[] getOccupancy() throws IOException { if (!has_run) this.run(); CSVReader reader = new CSVReader(new FileReader(out_file)); List<String[]> myEntries = reader.readAll(); reader.close(); int[] result = new int[myEntries.size()]; for (int i = 0; i < myEntries.size(); i++) { result[i] = Integer.valueOf(myEntries.get(i)[1]); } return (result); } }
7,412
0.679984
0.670631
244
29.672131
25.130297
90
false
false
0
0
0
0
0
0
1.819672
false
false
7
439c2e08eafe608e5ee963842f1e25d5b75ff01d
4,020,089,453,814
a38b6c77f69408bce40fcf23a13264f37a96b015
/learn-mybatis/src/main/java/com/learning/spring/service/UserService.java
d817a41c7a4a7d8fb1b81fdcac9cf62cc2d7bb55
[ "MIT" ]
permissive
DeveloperCry/java-learning
https://github.com/DeveloperCry/java-learning
67546b4cd8d5f3719ea2da94f22a3e8b3e8884ad
28bdee1b21f00817cc3984e17729f570177a3bce
refs/heads/master
2022-12-27T21:40:39.405000
2022-11-20T05:44:58
2022-11-20T05:44:58
228,860,206
0
0
MIT
false
2022-12-16T04:23:19
2019-12-18T14:43:35
2022-11-20T05:45:15
2022-12-16T04:23:16
859
0
0
20
Java
false
false
/** * */ package com.learning.spring.service; import com.learning.spring.enity.User; /** * @author Xiong.Liu * */ public interface UserService { public User getUserById(Integer id); }
UTF-8
Java
196
java
UserService.java
Java
[ { "context": "rt com.learning.spring.enity.User;\n\n/**\n * @author Xiong.Liu\n *\n */\npublic interface UserService {\n\t\n\tpublic U", "end": 114, "score": 0.9997646808624268, "start": 105, "tag": "NAME", "value": "Xiong.Liu" } ]
null
[]
/** * */ package com.learning.spring.service; import com.learning.spring.enity.User; /** * @author Xiong.Liu * */ public interface UserService { public User getUserById(Integer id); }
196
0.678571
0.678571
16
11.25
14.652218
38
false
false
0
0
0
0
0
0
0.3125
false
false
7