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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
de74d8f88dbea167af925654aa608285cd95a7bb | 5,231,270,226,968 | 7b1921d30aa141e8ba9c78bcd223dce77da93f18 | /src/main/java/com/suchaos/time/Java8TimeTest3.java | a3d524f70d41e36103ebdb91b93c5f0e1faa6d5a | []
| no_license | suchaos/jdk8 | https://github.com/suchaos/jdk8 | f2875620527ebd70ed24dd98b20913d6effbbe85 | 97414100ec8befac4acc6ba32a517a5c4ab8cc67 | refs/heads/master | 2020-06-09T08:53:40.296000 | 2019-06-20T02:29:41 | 2019-06-20T02:29:41 | 193,412,822 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.suchaos.time;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.util.Set;
import java.util.TreeSet;
/**
* instant
*
* @author suchao
* @date 2019/6/19
*/
public class Java8TimeTest3 {
public static void main(String[] args) {
System.out.println(Instant.now());
}
}
| UTF-8 | Java | 320 | java | Java8TimeTest3.java | Java | [
{
"context": "t java.util.TreeSet;\n\n/**\n * instant\n *\n * @author suchao\n * @date 2019/6/19\n */\npublic class Java8TimeTest",
"end": 169,
"score": 0.9994743466377258,
"start": 163,
"tag": "USERNAME",
"value": "suchao"
}
]
| null | []
| package com.suchaos.time;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.util.Set;
import java.util.TreeSet;
/**
* instant
*
* @author suchao
* @date 2019/6/19
*/
public class Java8TimeTest3 {
public static void main(String[] args) {
System.out.println(Instant.now());
}
}
| 320 | 0.675 | 0.646875 | 19 | 15.842105 | 14.426814 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.315789 | false | false | 14 |
80e0eb5f5ed8f027794624479fc3a82afbc562f1 | 4,647,154,663,641 | 00835cbf6d616800246112bd3d2602c0436b1ead | /spring-aop-test/src/main/java/com/othmen/springtest/aop/test2/Interface1.java | 2e1cafe0ba018c788978f97ec413c3b000c39a6b | []
| no_license | influence160/spring-cerification-samples-2 | https://github.com/influence160/spring-cerification-samples-2 | ba62a4658464191d80464dd365368cc886827d30 | 2d1fa1d7f9c2475433975a42f28bc3f4f478b835 | refs/heads/main | 2023-01-12T13:36:50.456000 | 2020-11-21T14:18:28 | 2020-11-21T14:18:28 | 314,812,311 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.othmen.springtest.aop.test2;
public interface Interface1 {
public void test1();
}
| UTF-8 | Java | 99 | java | Interface1.java | Java | []
| null | []
| package com.othmen.springtest.aop.test2;
public interface Interface1 {
public void test1();
}
| 99 | 0.747475 | 0.717172 | 7 | 13.142858 | 15.468203 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 14 |
b1f9177fe6e9076f04dd26d0e0f5463b4fd74fd7 | 22,136,261,493,806 | b1eee7989acdad29096ef323a7609b5af2828792 | /AppDyC/PjDevolucion/src/main/java/mx/gob/sat/siat/dyc/catalogo/service/impl/DyccInfoARequerirServiceImpl.java | 8f5adefce0e257c44685df130a37915834b74f8d | []
| no_license | xtaticzero/AppDyC | https://github.com/xtaticzero/AppDyC | 2185e5d25840ddbb73d0de6c6c0d61a497a6cdfa | 1562a358558323ef6adb84fb0e70ba7560200bda | refs/heads/master | 2021-09-09T21:50:41.930000 | 2018-03-19T21:38:45 | 2018-03-19T21:38:45 | 73,757,634 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Todos los Derechos Reservados 2013 SAT.
* Servicio de Administracion Tributaria (SAT).
*
* Este software contiene informacion propiedad exclusiva del SAT considerada
* Confidencial. Queda totalmente prohibido su uso o divulgacion en forma
**/
package mx.gob.sat.siat.dyc.catalogo.service.impl;
import java.util.ArrayList;
import java.util.List;
import mx.gob.sat.siat.dyc.catalogo.service.DyccInfoARequerirService;
import mx.gob.sat.siat.dyc.dao.documento.DyccInfoARequerirDAO;
import mx.gob.sat.siat.dyc.domain.tipotramite.DyccInfoARequerirDTO;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @author Federico Chopin Gachuz
* @date Noviembre 22, 2013
*
* */
@Service("dyccInfoARequerirService")
@Transactional
public class DyccInfoARequerirServiceImpl implements DyccInfoARequerirService {
@Autowired
private DyccInfoARequerirDAO dyccInfoARequerirDAO;
private static final Logger LOG = Logger.getLogger(DyccInfoARequerirServiceImpl.class);
public DyccInfoARequerirServiceImpl() {
super();
}
/**
* Metodo de servicio para consulta de informacion a requerir
* @param int idTipoTramite
* @return Objeto <DyccInfoARequerirDTO>
*
* */
@Transactional(readOnly = true)
public List<DyccInfoARequerirDTO> buscarInfoARequerir(int idTipoTramite) {
List<DyccInfoARequerirDTO> lDyccInfoARequerirDTO = new ArrayList<DyccInfoARequerirDTO>();
try {
lDyccInfoARequerirDTO = dyccInfoARequerirDAO.buscarInfoARequerir(idTipoTramite);
} catch (DataAccessException e) {
LOG.error(e.getMessage());
}
return lDyccInfoARequerirDTO;
}
public void setDyccInfoARequerirDAO(DyccInfoARequerirDAO dyccInfoARequerirDAO) {
this.dyccInfoARequerirDAO = dyccInfoARequerirDAO;
}
public DyccInfoARequerirDAO getDyccInfoARequerirDAO() {
return dyccInfoARequerirDAO;
}
}
| UTF-8 | Java | 2,170 | java | DyccInfoARequerirServiceImpl.java | Java | [
{
"context": "saction.annotation.Transactional;\n\n\n/**\n * @author Federico Chopin Gachuz\n * @date Noviembre 22, 2013\n *\n * */\n @Service(\"d",
"end": 853,
"score": 0.9998707175254822,
"start": 831,
"tag": "NAME",
"value": "Federico Chopin Gachuz"
}
]
| null | []
| /*
* Todos los Derechos Reservados 2013 SAT.
* Servicio de Administracion Tributaria (SAT).
*
* Este software contiene informacion propiedad exclusiva del SAT considerada
* Confidencial. Queda totalmente prohibido su uso o divulgacion en forma
**/
package mx.gob.sat.siat.dyc.catalogo.service.impl;
import java.util.ArrayList;
import java.util.List;
import mx.gob.sat.siat.dyc.catalogo.service.DyccInfoARequerirService;
import mx.gob.sat.siat.dyc.dao.documento.DyccInfoARequerirDAO;
import mx.gob.sat.siat.dyc.domain.tipotramite.DyccInfoARequerirDTO;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @author <NAME>
* @date Noviembre 22, 2013
*
* */
@Service("dyccInfoARequerirService")
@Transactional
public class DyccInfoARequerirServiceImpl implements DyccInfoARequerirService {
@Autowired
private DyccInfoARequerirDAO dyccInfoARequerirDAO;
private static final Logger LOG = Logger.getLogger(DyccInfoARequerirServiceImpl.class);
public DyccInfoARequerirServiceImpl() {
super();
}
/**
* Metodo de servicio para consulta de informacion a requerir
* @param int idTipoTramite
* @return Objeto <DyccInfoARequerirDTO>
*
* */
@Transactional(readOnly = true)
public List<DyccInfoARequerirDTO> buscarInfoARequerir(int idTipoTramite) {
List<DyccInfoARequerirDTO> lDyccInfoARequerirDTO = new ArrayList<DyccInfoARequerirDTO>();
try {
lDyccInfoARequerirDTO = dyccInfoARequerirDAO.buscarInfoARequerir(idTipoTramite);
} catch (DataAccessException e) {
LOG.error(e.getMessage());
}
return lDyccInfoARequerirDTO;
}
public void setDyccInfoARequerirDAO(DyccInfoARequerirDAO dyccInfoARequerirDAO) {
this.dyccInfoARequerirDAO = dyccInfoARequerirDAO;
}
public DyccInfoARequerirDAO getDyccInfoARequerirDAO() {
return dyccInfoARequerirDAO;
}
}
| 2,154 | 0.7447 | 0.739631 | 72 | 29.138889 | 28.839743 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.291667 | false | false | 14 |
afd2e78e8c1893d8098022430da0a756da63835a | 343,597,443,553 | aafaa07305bb4639a3355fdfd3b59e03d820aa8a | /Stansa/src/main/java/com/stansa/util/CifrarUtil.java | 21bdf07d4ab120bd2e4c065c42918b3913bb8b2d | []
| no_license | SegundoLeiva/Stansa | https://github.com/SegundoLeiva/Stansa | 0dfa284da1802577d3fb70318756600ed0f91b0f | ad31db123fd6147ba1a68c494dc0169bc2a8d670 | refs/heads/master | 2021-01-18T16:09:30.290000 | 2017-10-07T04:18:07 | 2017-10-07T04:18:07 | 86,710,213 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.stansa.util;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CifrarUtil {
static final Logger logger=LoggerFactory.getLogger(CifrarUtil.class);
public static String cifrarClave(String clave){
String claveSeguridad = Constantes.claveSeguridad;
String claveCifrada = "";
byte[] raw = claveSeguridad.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher ecipher = null;
try {
ecipher = Cipher.getInstance("AES");
ecipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = ecipher.doFinal(clave.getBytes());
claveCifrada = new String(CifrarUtil.bytesToHexadecimal(encrypted));
} catch (NoSuchAlgorithmException e) {
logger.error(e.getLocalizedMessage());
claveCifrada = null;
} catch (NoSuchPaddingException e) {
logger.error(e.getLocalizedMessage());
claveCifrada = null;
} catch (InvalidKeyException e) {
logger.error(e.getLocalizedMessage());
claveCifrada = null;
} catch (IllegalBlockSizeException e) {
logger.error(e.getLocalizedMessage());
claveCifrada = null;
} catch (BadPaddingException e) {
logger.error(e.getLocalizedMessage());
claveCifrada = null;
}
return claveCifrada;
}
public static String descifrarClave(String claveCifrada){
String claveSeguridad = Constantes.claveSeguridad;
String claveDescifrada = "";
byte[] raw = claveSeguridad.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher dcipher;
try {
dcipher = Cipher.getInstance("AES");
dcipher.init(Cipher.DECRYPT_MODE, skeySpec);
char[] hexa = claveCifrada.toCharArray();
byte[] descifrado = dcipher.doFinal(CifrarUtil.hexadecimalToBytes(hexa));
claveDescifrada = new String(descifrado);
} catch (NoSuchAlgorithmException e) {
logger.error(e.getLocalizedMessage());
claveDescifrada = null;
} catch (NoSuchPaddingException e) {
logger.error(e.getLocalizedMessage());
claveDescifrada = null;
} catch (InvalidKeyException e) {
logger.error(e.getLocalizedMessage());
claveDescifrada = null;
} catch (IllegalBlockSizeException e) {
logger.error(e.getLocalizedMessage());
claveDescifrada = null;
} catch (BadPaddingException e) {
logger.error(e.getLocalizedMessage());
claveDescifrada = null;
}
return claveDescifrada;
}
public static String bytesToHexadecimal(byte[] buf){
int tamanio = buf.length;
StringBuilder strbuf = new StringBuilder(tamanio * 2);
for (int i = 0; i < tamanio; i++) {
if ((buf[i] & 0xFF) < 16) {
strbuf.append("0");
}
strbuf.append(Long.toString(buf[i] & 0xFF, 16));
}
return strbuf.toString();
}
public static byte[] hexadecimalToBytes(char[] hex) {
int length = hex.length / 2;
byte[] raw = new byte[length];
for (int i = 0; i < length; i++) {
int high = Character.digit(hex[(i * 2)], 16);
int low = Character.digit(hex[(i * 2 + 1)], 16);
int value = high << 4 | low;
if (value > 127) {
value -= 256;
}
raw[i] = ((byte)value);
}
return raw;
}
}
| UTF-8 | Java | 3,461 | java | CifrarUtil.java | Java | []
| null | []
| package com.stansa.util;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CifrarUtil {
static final Logger logger=LoggerFactory.getLogger(CifrarUtil.class);
public static String cifrarClave(String clave){
String claveSeguridad = Constantes.claveSeguridad;
String claveCifrada = "";
byte[] raw = claveSeguridad.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher ecipher = null;
try {
ecipher = Cipher.getInstance("AES");
ecipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = ecipher.doFinal(clave.getBytes());
claveCifrada = new String(CifrarUtil.bytesToHexadecimal(encrypted));
} catch (NoSuchAlgorithmException e) {
logger.error(e.getLocalizedMessage());
claveCifrada = null;
} catch (NoSuchPaddingException e) {
logger.error(e.getLocalizedMessage());
claveCifrada = null;
} catch (InvalidKeyException e) {
logger.error(e.getLocalizedMessage());
claveCifrada = null;
} catch (IllegalBlockSizeException e) {
logger.error(e.getLocalizedMessage());
claveCifrada = null;
} catch (BadPaddingException e) {
logger.error(e.getLocalizedMessage());
claveCifrada = null;
}
return claveCifrada;
}
public static String descifrarClave(String claveCifrada){
String claveSeguridad = Constantes.claveSeguridad;
String claveDescifrada = "";
byte[] raw = claveSeguridad.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher dcipher;
try {
dcipher = Cipher.getInstance("AES");
dcipher.init(Cipher.DECRYPT_MODE, skeySpec);
char[] hexa = claveCifrada.toCharArray();
byte[] descifrado = dcipher.doFinal(CifrarUtil.hexadecimalToBytes(hexa));
claveDescifrada = new String(descifrado);
} catch (NoSuchAlgorithmException e) {
logger.error(e.getLocalizedMessage());
claveDescifrada = null;
} catch (NoSuchPaddingException e) {
logger.error(e.getLocalizedMessage());
claveDescifrada = null;
} catch (InvalidKeyException e) {
logger.error(e.getLocalizedMessage());
claveDescifrada = null;
} catch (IllegalBlockSizeException e) {
logger.error(e.getLocalizedMessage());
claveDescifrada = null;
} catch (BadPaddingException e) {
logger.error(e.getLocalizedMessage());
claveDescifrada = null;
}
return claveDescifrada;
}
public static String bytesToHexadecimal(byte[] buf){
int tamanio = buf.length;
StringBuilder strbuf = new StringBuilder(tamanio * 2);
for (int i = 0; i < tamanio; i++) {
if ((buf[i] & 0xFF) < 16) {
strbuf.append("0");
}
strbuf.append(Long.toString(buf[i] & 0xFF, 16));
}
return strbuf.toString();
}
public static byte[] hexadecimalToBytes(char[] hex) {
int length = hex.length / 2;
byte[] raw = new byte[length];
for (int i = 0; i < length; i++) {
int high = Character.digit(hex[(i * 2)], 16);
int low = Character.digit(hex[(i * 2 + 1)], 16);
int value = high << 4 | low;
if (value > 127) {
value -= 256;
}
raw[i] = ((byte)value);
}
return raw;
}
}
| 3,461 | 0.681306 | 0.673505 | 118 | 27.330509 | 19.46664 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.508475 | false | false | 14 |
2a1e887186ff0a2d4c2511db3645313438d76f84 | 31,860,067,459,339 | 53613d7d02ae32168ac7748af87f8058e9af8dfe | /src/gui/MainWindow.java | 4a6dbff5a57dff1bf1cb874aa288fc10c9eb73fc | []
| no_license | omeredut/GIS-Pacman | https://github.com/omeredut/GIS-Pacman | 9b5ec5ca46f5227c3aac486c46caa641244fa12e | af3ffdef24e8b7de2b4031353b13a91534581d89 | refs/heads/master | 2020-04-13T03:11:20.981000 | 2018-12-23T12:39:56 | 2018-12-23T12:39:56 | 162,924,349 | 0 | 0 | null | true | 2018-12-23T21:15:22 | 2018-12-23T21:15:22 | 2018-12-23T12:39:58 | 2018-12-23T12:39:57 | 2,223 | 0 | 0 | 0 | null | false | null | package gui;
import java.awt.FileDialog;
import java.awt.Graphics;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import file_format.CsvReader;
import game.Fruit;
import game.Game;
import game.GameElement;
import game.Map;
import geom.Point3D;
public class MainWindow extends JFrame implements MouseListener {
public static BufferedImage myImage;
// private JMenuBar menuBar;
private MenuBar menuBar;
private Menu fileMenu, helpMenu, createGame, gameObjectsMenu, addObjects;
private MenuItem openItem, saveItem, mapItem, pacmanItem, fruitItem;
// private TextField textField;
// private int textFieldSize = 10;
private Game game=new Game();
private File file;
private int pacman = 0, fruit = 0;
public MainWindow() {
initComponents();
// createGui();
this.addMouseListener(this);
}
private void initComponents() {
menuBar = new MenuBar();
// Menu
fileMenu = new Menu("File");
helpMenu = new Menu("Help");
createGame = new Menu("Create new game");
gameObjectsMenu = new Menu("Game objects");
addObjects = new Menu("Add objects");
// Menu Items
openItem = new MenuItem("Open game");
saveItem = new MenuItem("Save");
mapItem = new MenuItem("Add map image");
pacmanItem = new MenuItem("Pacman");
fruitItem = new MenuItem("Fruit");
menuBar.add(fileMenu);
menuBar.add(helpMenu);
menuBar.add(gameObjectsMenu);
addObjects.add(pacmanItem);
addObjects.add(fruitItem);
gameObjectsMenu.add(addObjects);
createGame.add(mapItem);
fileMenu.add(createGame);
fileMenu.add(openItem);
fileMenu.add(saveItem);
this.setMenuBar(menuBar);
// textField = new TextField(textFieldSize);
// textField = new JTextField(textFieldSize);
// this.add(textField);
try {
file = new File("images\\ariel1.png");
myImage = ImageIO.read(file);
} catch (IOException e) {
e.printStackTrace();
}
}
public void createGui() {
/*
* mapItem.addActionListener(new ActionListener() {
*
* @Override public void actionPerformed(ActionEvent e) { file=new
* File("E:\\wifi\\Ariel1.png"); try { myImage = ImageIO.read(file); }
* catch (IOException e1) { e1.printStackTrace(); } } });
*/
pacmanItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fruit = 0;
pacman = 1;
}
});
fruitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pacman = 0;
fruit=1;
}
});
openItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
readFileDialog();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
});
saveItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
writeFileDialog();
}
});
}
public void readFileDialog() throws FileNotFoundException {
// try read from the file
FileDialog fd = new FileDialog(this, "Open csv file", FileDialog.LOAD);
fd.setFile("*.csv");
fd.setDirectory("C:\\");
fd.setFilenameFilter(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".csv");
}
});
fd.setVisible(true);
String folder = fd.getDirectory();
String fileName = fd.getFile();
try {
CsvReader csvReader = new CsvReader();
csvReader.init(folder + fileName, ",");
game = csvReader.read(1);
} catch (ParseException e) {
e.printStackTrace();
}
}
public void writeFileDialog() {
// try write to the file
FileDialog fd = new FileDialog(this, "Save the text file", FileDialog.SAVE);
fd.setFile("*.txt");
fd.setFilenameFilter(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
});
fd.setVisible(true);
String folder = fd.getDirectory();
String fileName = fd.getFile();
try {
FileWriter fw = new FileWriter(folder + fileName);
PrintWriter outs = new PrintWriter(fw);
outs.println("Why Java?\n" + "1. Java is small and beautiful\n" + "2. Java is object oriented\n" + "3. Java supports Internet\n" + "4. Java is platform independent\n"
+ "5. Java has libraries");
outs.close();
fw.close();
} catch (IOException ex) {
System.out.print("Error writing file " + ex);
}
}
int x = -1;
int y = -1;
public void paint(Graphics g) {
g.drawImage(myImage, 0, 0, this);
if (x != -1 && y != -1) {
int r = 10;
x = x - (r / 2);
y = y - (r / 2);
g.fillOval(x, y, r, r);
}
}
@Override
public void mouseClicked(MouseEvent arg) {
System.out.println("mouse Clicked");
System.out.println("(" + arg.getX() + "," + arg.getY() + ")");
x = arg.getX();
y = arg.getY();
if(fruit==1){
Fruit f=new Fruit(1,Map.pixel2Polar(new Point3D(x,y,0)),1);
game.add(new GameElement(f))
repaint();
}
}
@Override
public void mouseEntered(MouseEvent arg0) {
System.out.println("mouse entered");
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
| UTF-8 | Java | 6,006 | java | MainWindow.java | Java | []
| null | []
| package gui;
import java.awt.FileDialog;
import java.awt.Graphics;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import file_format.CsvReader;
import game.Fruit;
import game.Game;
import game.GameElement;
import game.Map;
import geom.Point3D;
public class MainWindow extends JFrame implements MouseListener {
public static BufferedImage myImage;
// private JMenuBar menuBar;
private MenuBar menuBar;
private Menu fileMenu, helpMenu, createGame, gameObjectsMenu, addObjects;
private MenuItem openItem, saveItem, mapItem, pacmanItem, fruitItem;
// private TextField textField;
// private int textFieldSize = 10;
private Game game=new Game();
private File file;
private int pacman = 0, fruit = 0;
public MainWindow() {
initComponents();
// createGui();
this.addMouseListener(this);
}
private void initComponents() {
menuBar = new MenuBar();
// Menu
fileMenu = new Menu("File");
helpMenu = new Menu("Help");
createGame = new Menu("Create new game");
gameObjectsMenu = new Menu("Game objects");
addObjects = new Menu("Add objects");
// Menu Items
openItem = new MenuItem("Open game");
saveItem = new MenuItem("Save");
mapItem = new MenuItem("Add map image");
pacmanItem = new MenuItem("Pacman");
fruitItem = new MenuItem("Fruit");
menuBar.add(fileMenu);
menuBar.add(helpMenu);
menuBar.add(gameObjectsMenu);
addObjects.add(pacmanItem);
addObjects.add(fruitItem);
gameObjectsMenu.add(addObjects);
createGame.add(mapItem);
fileMenu.add(createGame);
fileMenu.add(openItem);
fileMenu.add(saveItem);
this.setMenuBar(menuBar);
// textField = new TextField(textFieldSize);
// textField = new JTextField(textFieldSize);
// this.add(textField);
try {
file = new File("images\\ariel1.png");
myImage = ImageIO.read(file);
} catch (IOException e) {
e.printStackTrace();
}
}
public void createGui() {
/*
* mapItem.addActionListener(new ActionListener() {
*
* @Override public void actionPerformed(ActionEvent e) { file=new
* File("E:\\wifi\\Ariel1.png"); try { myImage = ImageIO.read(file); }
* catch (IOException e1) { e1.printStackTrace(); } } });
*/
pacmanItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fruit = 0;
pacman = 1;
}
});
fruitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pacman = 0;
fruit=1;
}
});
openItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
readFileDialog();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
});
saveItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
writeFileDialog();
}
});
}
public void readFileDialog() throws FileNotFoundException {
// try read from the file
FileDialog fd = new FileDialog(this, "Open csv file", FileDialog.LOAD);
fd.setFile("*.csv");
fd.setDirectory("C:\\");
fd.setFilenameFilter(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".csv");
}
});
fd.setVisible(true);
String folder = fd.getDirectory();
String fileName = fd.getFile();
try {
CsvReader csvReader = new CsvReader();
csvReader.init(folder + fileName, ",");
game = csvReader.read(1);
} catch (ParseException e) {
e.printStackTrace();
}
}
public void writeFileDialog() {
// try write to the file
FileDialog fd = new FileDialog(this, "Save the text file", FileDialog.SAVE);
fd.setFile("*.txt");
fd.setFilenameFilter(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
});
fd.setVisible(true);
String folder = fd.getDirectory();
String fileName = fd.getFile();
try {
FileWriter fw = new FileWriter(folder + fileName);
PrintWriter outs = new PrintWriter(fw);
outs.println("Why Java?\n" + "1. Java is small and beautiful\n" + "2. Java is object oriented\n" + "3. Java supports Internet\n" + "4. Java is platform independent\n"
+ "5. Java has libraries");
outs.close();
fw.close();
} catch (IOException ex) {
System.out.print("Error writing file " + ex);
}
}
int x = -1;
int y = -1;
public void paint(Graphics g) {
g.drawImage(myImage, 0, 0, this);
if (x != -1 && y != -1) {
int r = 10;
x = x - (r / 2);
y = y - (r / 2);
g.fillOval(x, y, r, r);
}
}
@Override
public void mouseClicked(MouseEvent arg) {
System.out.println("mouse Clicked");
System.out.println("(" + arg.getX() + "," + arg.getY() + ")");
x = arg.getX();
y = arg.getY();
if(fruit==1){
Fruit f=new Fruit(1,Map.pixel2Polar(new Point3D(x,y,0)),1);
game.add(new GameElement(f))
repaint();
}
}
@Override
public void mouseEntered(MouseEvent arg0) {
System.out.println("mouse entered");
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
| 6,006 | 0.656344 | 0.649517 | 236 | 23.449152 | 20.683695 | 169 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.211864 | false | false | 14 |
e0c53c9fa2958f6b99dfed44704d43b144592863 | 17,119,739,651,186 | 32e57954b6cfa73a323af28b8238f4899d4ab9fe | /DnBImporter/DnBWebServiceAccess/DBFullReportsClient/SubjectInformationDetailedType.java | 48f17149254546686d240778bbe63ac7a47a6e9e | []
| no_license | astacey/Test | https://github.com/astacey/Test | 52f278902115518ff0081f237fa76e302b0381d4 | e6d855d06fc1f166f219f59c07e33d630433831e | refs/heads/master | 2016-09-05T18:54:18.674000 | 2014-03-12T14:54:55 | 2014-03-12T14:54:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package DBFullReportsClient;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for SubjectInformationDetailedType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="SubjectInformationDetailedType">
* <complexContent>
* <extension base="{http://gateway.dnb.com/getProduct}SubjectInformationBaseType">
* <sequence>
* <element name="BusinessName" type="{http://gateway.dnb.com/getProduct}BusinessNameType" minOccurs="0"/>
* <element name="RegistrationNumber" type="{http://gateway.dnb.com/getProduct}RegistrationNumberType" minOccurs="0"/>
* <element name="RegistrationNumberTypeCode" type="{http://gateway.dnb.com/getProduct}RegistrationNumberTypeCodeType" minOccurs="0"/>
* <element name="Address" type="{http://gateway.dnb.com/getProduct}AddressBaseType" minOccurs="0"/>
* <element name="Communication" type="{http://gateway.dnb.com/getProduct}CommunicationBaseType" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SubjectInformationDetailedType", propOrder = {
"businessName",
"registrationNumber",
"registrationNumberTypeCode",
"address",
"communication"
})
public class SubjectInformationDetailedType
extends SubjectInformationBaseType
{
@XmlElement(name = "BusinessName")
protected String businessName;
@XmlElement(name = "RegistrationNumber")
protected String registrationNumber;
@XmlElement(name = "RegistrationNumberTypeCode")
protected String registrationNumberTypeCode;
@XmlElement(name = "Address")
protected AddressBaseType address;
@XmlElement(name = "Communication")
protected CommunicationBaseType communication;
/**
* Gets the value of the businessName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBusinessName() {
return businessName;
}
/**
* Sets the value of the businessName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBusinessName(String value) {
this.businessName = value;
}
/**
* Gets the value of the registrationNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRegistrationNumber() {
return registrationNumber;
}
/**
* Sets the value of the registrationNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRegistrationNumber(String value) {
this.registrationNumber = value;
}
/**
* Gets the value of the registrationNumberTypeCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRegistrationNumberTypeCode() {
return registrationNumberTypeCode;
}
/**
* Sets the value of the registrationNumberTypeCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRegistrationNumberTypeCode(String value) {
this.registrationNumberTypeCode = value;
}
/**
* Gets the value of the address property.
*
* @return
* possible object is
* {@link AddressBaseType }
*
*/
public AddressBaseType getAddress() {
return address;
}
/**
* Sets the value of the address property.
*
* @param value
* allowed object is
* {@link AddressBaseType }
*
*/
public void setAddress(AddressBaseType value) {
this.address = value;
}
/**
* Gets the value of the communication property.
*
* @return
* possible object is
* {@link CommunicationBaseType }
*
*/
public CommunicationBaseType getCommunication() {
return communication;
}
/**
* Sets the value of the communication property.
*
* @param value
* allowed object is
* {@link CommunicationBaseType }
*
*/
public void setCommunication(CommunicationBaseType value) {
this.communication = value;
}
}
| UTF-8 | Java | 4,711 | java | SubjectInformationDetailedType.java | Java | []
| null | []
|
package DBFullReportsClient;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for SubjectInformationDetailedType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="SubjectInformationDetailedType">
* <complexContent>
* <extension base="{http://gateway.dnb.com/getProduct}SubjectInformationBaseType">
* <sequence>
* <element name="BusinessName" type="{http://gateway.dnb.com/getProduct}BusinessNameType" minOccurs="0"/>
* <element name="RegistrationNumber" type="{http://gateway.dnb.com/getProduct}RegistrationNumberType" minOccurs="0"/>
* <element name="RegistrationNumberTypeCode" type="{http://gateway.dnb.com/getProduct}RegistrationNumberTypeCodeType" minOccurs="0"/>
* <element name="Address" type="{http://gateway.dnb.com/getProduct}AddressBaseType" minOccurs="0"/>
* <element name="Communication" type="{http://gateway.dnb.com/getProduct}CommunicationBaseType" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SubjectInformationDetailedType", propOrder = {
"businessName",
"registrationNumber",
"registrationNumberTypeCode",
"address",
"communication"
})
public class SubjectInformationDetailedType
extends SubjectInformationBaseType
{
@XmlElement(name = "BusinessName")
protected String businessName;
@XmlElement(name = "RegistrationNumber")
protected String registrationNumber;
@XmlElement(name = "RegistrationNumberTypeCode")
protected String registrationNumberTypeCode;
@XmlElement(name = "Address")
protected AddressBaseType address;
@XmlElement(name = "Communication")
protected CommunicationBaseType communication;
/**
* Gets the value of the businessName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBusinessName() {
return businessName;
}
/**
* Sets the value of the businessName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBusinessName(String value) {
this.businessName = value;
}
/**
* Gets the value of the registrationNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRegistrationNumber() {
return registrationNumber;
}
/**
* Sets the value of the registrationNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRegistrationNumber(String value) {
this.registrationNumber = value;
}
/**
* Gets the value of the registrationNumberTypeCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRegistrationNumberTypeCode() {
return registrationNumberTypeCode;
}
/**
* Sets the value of the registrationNumberTypeCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRegistrationNumberTypeCode(String value) {
this.registrationNumberTypeCode = value;
}
/**
* Gets the value of the address property.
*
* @return
* possible object is
* {@link AddressBaseType }
*
*/
public AddressBaseType getAddress() {
return address;
}
/**
* Sets the value of the address property.
*
* @param value
* allowed object is
* {@link AddressBaseType }
*
*/
public void setAddress(AddressBaseType value) {
this.address = value;
}
/**
* Gets the value of the communication property.
*
* @return
* possible object is
* {@link CommunicationBaseType }
*
*/
public CommunicationBaseType getCommunication() {
return communication;
}
/**
* Sets the value of the communication property.
*
* @param value
* allowed object is
* {@link CommunicationBaseType }
*
*/
public void setCommunication(CommunicationBaseType value) {
this.communication = value;
}
}
| 4,711 | 0.620463 | 0.619401 | 175 | 25.914286 | 26.019083 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.217143 | false | false | 14 |
98e314bd6856e260b297cf49d71fd76eb7bf9279 | 4,071,629,051,282 | dbb78416e0c79d6f9e137ba16a48a126014a1a82 | /app/src/main/java/com/njzhikejia/echohealth/healthlife/MainActivity.java | f3c64c830cacded06574a00cedf692697dbbbb05 | []
| no_license | ignorehuahua/HealthManager | https://github.com/ignorehuahua/HealthManager | e520c15466f04aca68ef820415970d6096bcd885 | 652e21cacaec6afeeed9359afb6cef9d213aae2f | refs/heads/master | 2020-09-05T23:22:45.050000 | 2018-09-27T08:51:27 | 2018-09-27T08:51:27 | 220,242,125 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.njzhikejia.echohealth.healthlife;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.content.FileProvider;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.os.Bundle;
import android.support.v7.graphics.drawable.DrawerArrowDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.google.gson.Gson;
import com.njzhikejia.echohealth.healthlife.adapter.MemberListAdapter;
import com.njzhikejia.echohealth.healthlife.entity.concern.Concerns;
import com.njzhikejia.echohealth.healthlife.entity.concern.MyFollowsData;
import com.njzhikejia.echohealth.healthlife.entity.rule.RuleResult;
import com.njzhikejia.echohealth.healthlife.entity.rule.WarnRule;
import com.njzhikejia.echohealth.healthlife.entity.user.UserDetailsResponse;
import com.njzhikejia.echohealth.healthlife.greendao.ConcernsDao;
import com.njzhikejia.echohealth.healthlife.greendao.DaoSession;
import com.njzhikejia.echohealth.healthlife.http.CommonRequest;
import com.njzhikejia.echohealth.healthlife.http.OKHttpClientManager;
import com.njzhikejia.echohealth.healthlife.util.ChineseCharComp;
import com.njzhikejia.echohealth.healthlife.util.ConstantValues;
import com.njzhikejia.echohealth.healthlife.util.ImageUtil;
import com.njzhikejia.echohealth.healthlife.util.Logger;
import com.njzhikejia.echohealth.healthlife.util.NetWorkUtils;
import com.njzhikejia.echohealth.healthlife.util.PreferenceUtil;
import com.njzhikejia.echohealth.healthlife.util.ToastUtil;
import com.njzhikejia.echohealth.healthlife.widget.BadgeDrawerArrowDrawable;
import com.njzhikejia.echohealth.healthlife.widget.banner.CycleViewPager;
import com.njzhikejia.echohealth.healthlife.widget.banner.ViewUtil;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class MainActivity extends BaseActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
private static final String TAG = "MainActivity";
private Toolbar mToolbar;
private NavigationView mNavigation;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private RecyclerView mRecycleView;
private MemberListAdapter mAdapter;
private List<Concerns> memberList;
private ImageView ivAvatar;
private static final int REQUEST_CODE_CHOOSE = 200;
private static final int LOAD_RELATIVES_SUCCESS = 28;
private static final int QUERY_USER_INFO_SUCCESS = 29;
private PopupWindow mPopupWindow;
private TextView tvGallery;
private TextView tvCamera;
private TextView tvCancel;
private Uri mImageUri;
private MainHandler mHandler;
private SwipeRefreshLayout mSwipeRefreshLayout;
private TextView tvName;
private TextView tvNumber;
private LocalBroadcastManager mLocalBroadcastManager;
private MainBroadcastReceiver mainBroadcastReceiver;
public static final String KEY_MEMBER = "key_member";
private DaoSession mDaoSession;
private ConcernsDao concernsDao;
private BadgeDrawerArrowDrawable badgeDrawerArrowDrawable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new MainHandler(this);
initDaoSession();
initView();
judgeNewConcerns();
loadRealtives();
getWarnRules();
initPopupWindow();
}
private void initDaoSession() {
HealthLifeApplication mApplication = (HealthLifeApplication) getApplication();
mDaoSession = mApplication.getDaoSession();
concernsDao = mDaoSession.getConcernsDao();
}
private void initView() {
Logger.d(TAG, "initView");
mLocalBroadcastManager = LocalBroadcastManager.getInstance(getApplicationContext());
mainBroadcastReceiver = new MainBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConstantValues.ACTION_EXIT_LOGIN);
intentFilter.addAction(ConstantValues.ACTION_CONCERN_REQUEST_RECEIVED);
intentFilter.addAction(ConstantValues.ACTION_CONCERN_REQUEST_FINISHED);
intentFilter.addAction(ConstantValues.ACTION_CONCERN_REQUEST_ACCEPTED);
mLocalBroadcastManager.registerReceiver(mainBroadcastReceiver, intentFilter);
mSwipeRefreshLayout = findViewById(R.id.refresh_layout);
mSwipeRefreshLayout.setColorSchemeResources(R.color.toolbar);
mSwipeRefreshLayout.setOnRefreshListener(this);
mToolbar = findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mNavigation = findViewById(R.id.bottom_navigation);
mDrawerLayout = findViewById(R.id.drawerLayout);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
mToolbar,0,0
);
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
mNavigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_meember_manager:
Logger.d(TAG, "menu member manager clicked");
Intent intentMember = new Intent(MainActivity.this, MemberManageActivity.class);
startActivity(intentMember);
break;
case R.id.menu_setting:
Logger.d(TAG, "menu system setting clicked");
Intent intentSetting = new Intent(MainActivity.this, SystemSettingActivity.class);
startActivity(intentSetting);
break;
case R.id.menu_msg_center:
Logger.d(TAG, "menu msg center clicked");
Intent intentMsg = new Intent(MainActivity.this, MessageCenterActivity.class);
startActivity(intentMsg);
break;
case R.id.menu_feedback:
Logger.d(TAG, "menu feedback clicked");
Intent intentFeedback = new Intent(MainActivity.this, FeedbackActivity.class);
startActivity(intentFeedback);
break;
case R.id.menu_about:
Intent intentAbout = new Intent(MainActivity.this, AboutActivity.class);
startActivity(intentAbout);
break;
}
mDrawerLayout.closeDrawer(mNavigation);
return false;
}
});
View headerLayout = mNavigation.getHeaderView(0);
ivAvatar= headerLayout.findViewById(R.id.iv_avatar);
tvName = headerLayout.findViewById(R.id.tv_header_name);
tvNumber = headerLayout.findViewById(R.id.tv_header_number);
updateName();
ivAvatar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// if (mPopupWindow == null) {
// return;
// }
// if (mPopupWindow.isShowing()) {
// closePopupWindow();
// } else {
// showPopupWindow();
// }
Intent intentDetails = new Intent(MainActivity.this, UserDetailsActivity.class);
Concerns user = new Concerns();
user.setUid(PreferenceUtil.getLoginUserUID(MainActivity.this));
user.setName(PreferenceUtil.getLoginUserName(MainActivity.this));
user.setPhone(PreferenceUtil.getLoginUserPhone(MainActivity.this));
intentDetails.putExtra(ConstantValues.KEY_USER_DETAILS, user);
startActivity(intentDetails);
}
});
mRecycleView = findViewById(R.id.recycle_view);
memberList = new ArrayList<>();
initBanner();
mAdapter = new MemberListAdapter(this, memberList);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
mRecycleView.setHasFixedSize(true);
mRecycleView.setLayoutManager(layoutManager);
mRecycleView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new MemberListAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
Concerns member = memberList.get(position);
Logger.d(TAG, "onItemClick member name is "+member.getName());
Intent intentMember = new Intent(view.getContext(), MeasureDataActivity.class);
intentMember.putExtra(KEY_MEMBER, member);
startActivity(intentMember);
}
});
}
private void judgeNewConcerns() {
if (PreferenceUtil.getNewConcern(this)) {
showSideUnread();
showMemberMenuUnread();
} else {
hideSideUnread();
hideMemberMenuUnread();
}
}
/**
* 显示成员管理小红点
*/
private void showMemberMenuUnread() {
if (mNavigation == null) {
mNavigation =findViewById(R.id.bottom_navigation);
}
LinearLayout linearLayout = (LinearLayout) mNavigation.getMenu().findItem(R.id.menu_meember_manager).getActionView();
if (linearLayout != null) {
TextView tv = linearLayout.findViewById(R.id.tv_unread);
tv.setVisibility(View.VISIBLE);
} else {
Logger.e(TAG, "LinearLayout == null");
}
}
/**
* 隐藏成员管理小红点
*/
private void hideMemberMenuUnread() {
if (mNavigation == null) {
mNavigation =findViewById(R.id.bottom_navigation);
}
LinearLayout linearLayout = (LinearLayout) mNavigation.getMenu().findItem(R.id.menu_meember_manager).getActionView();
if (linearLayout != null) {
TextView tv = linearLayout.findViewById(R.id.tv_unread);
tv.setVisibility(View.GONE);
} else {
Logger.e(TAG, "LinearLayout == null");
}
}
/**
* 显示消息中心小红点
*/
private void showMsgCenterMenuUnread() {
if (mNavigation == null) {
mNavigation =findViewById(R.id.bottom_navigation);
}
LinearLayout linearLayout = (LinearLayout) mNavigation.getMenu().findItem(R.id.menu_msg_center).getActionView();
if (linearLayout != null) {
TextView tv = linearLayout.findViewById(R.id.tv_unread);
tv.setVisibility(View.VISIBLE);
} else {
Logger.e(TAG, "LinearLayout == null");
}
}
/**
* 隐藏消息中心小红点
*/
private void hideMsgCenterMenuUnread() {
if (mNavigation == null) {
mNavigation =findViewById(R.id.bottom_navigation);
}
LinearLayout linearLayout = (LinearLayout) mNavigation.getMenu().findItem(R.id.menu_msg_center).getActionView();
if (linearLayout != null) {
TextView tv = linearLayout.findViewById(R.id.tv_unread);
tv.setVisibility(View.GONE);
} else {
Logger.e(TAG, "LinearLayout == null");
}
}
/**
* 显示toolbar左侧菜单键小红点
*/
private void showSideUnread() {
if (mDrawerToggle != null) {
if (badgeDrawerArrowDrawable == null) {
badgeDrawerArrowDrawable = new BadgeDrawerArrowDrawable(getSupportActionBar().getThemedContext());
}
mDrawerToggle.setDrawerArrowDrawable(badgeDrawerArrowDrawable);
}
}
/**
* 隐藏toolbar左侧菜单键小红点
*/
private void hideSideUnread() {
if (mDrawerToggle != null) {
mDrawerToggle.setDrawerArrowDrawable(new DrawerArrowDrawable(getSupportActionBar().getThemedContext()));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
class MainBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (ConstantValues.ACTION_EXIT_LOGIN.equals(intent.getAction())) {
finish();
} else if (ConstantValues.ACTION_CONCERN_REQUEST_RECEIVED.equals(intent.getAction())) {
showSideUnread();
showMemberMenuUnread();
} else if (ConstantValues.ACTION_CONCERN_REQUEST_FINISHED.equals(intent.getAction())) {
hideSideUnread();
hideMemberMenuUnread();
} else if (ConstantValues.ACTION_CONCERN_REQUEST_ACCEPTED.equals(intent.getAction())) {
loadRealtives();
}
}
}
@Override
public void onRefresh() {
Logger.d(TAG, "onRefresh");
loadRealtives();
mHandler.sendEmptyMessageDelayed(ConstantValues.MSG_REFRESH_TIME_OUT, ConstantValues.REFRESH_TIME_OUT);
}
private void stopRefresh() {
if (mSwipeRefreshLayout != null) {
mSwipeRefreshLayout.setRefreshing(false);
Logger.d(TAG, "stopRefresh!");
}
}
static class MainHandler extends Handler{
private WeakReference<MainActivity> weakReference;
public MainHandler(MainActivity mainActivity) {
weakReference = new WeakReference<MainActivity>(mainActivity);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case ConstantValues.MSG_REFRESH_TIME_OUT:
if (weakReference.get() != null) {
weakReference.get().stopRefresh();
}
break;
case LOAD_RELATIVES_SUCCESS:
if (weakReference.get() != null) {
weakReference.get().stopRefresh();
weakReference.get().mAdapter.setList(weakReference.get().memberList);
}
break;
case QUERY_USER_INFO_SUCCESS:
if (weakReference.get() != null) {
weakReference.get().updateName();
}
break;
}
}
}
private void updateName() {
tvName.setText(PreferenceUtil.getLoginUserName(MainActivity.this));
// tvNumber.setText(PreferenceUtil.getLoginUserPhone(MainActivity.this));
}
// 加载亲友列表
private void loadRealtives() {
if (!NetWorkUtils.isNetworkConnected(this)) {
ToastUtil.showShortToast(this, R.string.net_work_error);
stopRefresh();
loadDataFromDb();
return;
}
/**
OKHttpClientManager.getInstance().getAsync(CommonRequest.getRealtivesList(PreferenceUtil.getLoginUserUID(this)), new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Logger.e(TAG, "loadRelatives failure");
stopRefresh();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseContent = response.body().string();
Logger.d(TAG, "onResponse code = "+response.code() + "responseContent = "+responseContent);
if (response.code() == 200) {
Gson gson = new Gson();
RelativesData relativesData = gson.fromJson(responseContent, RelativesData.class);
memberList = relativesData.getData().getRelatives();
RelativesData.Data.Relatives me = new RelativesData.Data.Relatives();
me.setName(getString(R.string.me));
me.setPhone(PreferenceUtil.getLoginUserPhone(MainActivity.this));
me.setUid(PreferenceUtil.getLoginUserUID(MainActivity.this));
memberList.add(me);
Comparator cmp = new ChineseCharComp();
Collections.sort(memberList, cmp);
mHandler.sendEmptyMessage(LOAD_RELATIVES_SUCCESS);
}
}
}); */
OKHttpClientManager.getInstance().getAsync(CommonRequest.getMyFollows(PreferenceUtil.getLoginUserUID(this)), new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Logger.e(TAG, "onFailure");
stopRefresh();
loadDataFromDb();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseContent = response.body().string();
Logger.d(TAG, "onResponse code = "+response.code() + "content = "+responseContent);
if (response.code() == 200 && !TextUtils.isEmpty(responseContent)) {
Logger.d(TAG, "onRespone load my follows success");
Gson gson = new Gson();
MyFollowsData data = gson.fromJson(responseContent, MyFollowsData.class);
memberList = data.getData().getConcerns();
Comparator cmp = new ChineseCharComp();
Collections.sort(memberList, cmp);
Concerns me = new Concerns();
me.setName(getString(R.string.me));
me.setPhone(PreferenceUtil.getLoginUserPhone(MainActivity.this));
me.setUid(PreferenceUtil.getLoginUserUID(MainActivity.this));
memberList.add(0, me);
mHandler.sendEmptyMessage(LOAD_RELATIVES_SUCCESS);
concernsDao.deleteAll();
for (Concerns concerns : memberList) {
concernsDao.insert(concerns);
}
}
}
});
}
private void loadDataFromDb() {
memberList = concernsDao.loadAll();
mAdapter.setList(memberList);
}
/**
// 查询用户详情
private void queryUserInfo() {
if (!NetWorkUtils.isNetworkConnected(this)) {
ToastUtil.showShortToast(this, R.string.net_work_error);
return;
}
OKHttpClientManager.getInstance().getAsync(CommonRequest.getUserDetailsRequest(PreferenceUtil.getLoginUserUID(MainActivity.this)), new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Logger.e(TAG, "onFailure call = "+call.toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Logger.d(TAG, "getUserDetails onResponse code = "+response.code());
String resonseContent = response.body().string();
Logger.d(TAG, "responseContent = "+resonseContent);
if (response.code() == 200) {
Gson gson = new Gson();
UserDetailsResponse userDetailsResponse = gson.fromJson(resonseContent, UserDetailsResponse.class);
String name = userDetailsResponse.getData().getUser().getName();
PreferenceUtil.putLoginUserName(MainActivity.this, name);
mHandler.sendEmptyMessage(QUERY_USER_INFO_SUCCESS);
}
}
});
} */
private void getWarnRules() {
if (!NetWorkUtils.isNetworkConnected(this)) {
ToastUtil.showShortToast(this, R.string.net_work_error);
return;
}
OKHttpClientManager.getInstance().getAsync(CommonRequest.getWarnRuleRequest(PreferenceUtil.getLoginUserUID(this)), new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Logger.d(TAG, "get warn rules failure");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String content = response.body().string();
Logger.d(TAG, "code = "+response.code() + "content = "+content);
Gson gson = new Gson();
WarnRule warnRule = gson.fromJson(content, WarnRule.class);
String data = warnRule.getData().getRules().getData();
Logger.d(TAG, "data = "+data);
Gson gsonRule = new Gson();
RuleResult ruleResult = gsonRule.fromJson(data, RuleResult.class);
}
});
}
private void initBanner() {
List<View> views = new ArrayList<View>();
// 将最后一个view添加进来
views.add(ViewUtil.getView(this, R.drawable.photo_four));
views.add(ViewUtil.getView(this, R.drawable.photo_one));
views.add(ViewUtil.getView(this, R.drawable.photo_two));
views.add(ViewUtil.getView(this, R.drawable.photo_three));
views.add(ViewUtil.getView(this, R.drawable.photo_four));
// 将第一个view添加进来
views.add(ViewUtil.getView(this, R.drawable.photo_one));
final CycleViewPager cycleViewPager = (CycleViewPager) findViewById(R.id.banner);
cycleViewPager.setIndicatorCenter();
cycleViewPager.setIndicatorsSpace(8);
cycleViewPager.setData(views, true, true, 3000);
}
private void initPopupWindow() {
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.popwindow_avatar, null);
tvGallery = view.findViewById(R.id.pop_pic);
tvCamera = view.findViewById(R.id.pop_camera);
tvCancel = view.findViewById(R.id.pop_cancel);
tvGallery.setOnClickListener(this);
tvCamera.setOnClickListener(this);
tvCancel.setOnClickListener(this);
mPopupWindow = new PopupWindow(view, 660, ViewGroup.LayoutParams.WRAP_CONTENT);
mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
mPopupWindow.setOutsideTouchable(true);
mPopupWindow.setTouchable(true);
mPopupWindow.setFocusable(true);
mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
setBackgroundAlpha(1.0f);
}
});
}
private void setBackgroundAlpha(float alphaLevel) {
Window window = getWindow();
WindowManager.LayoutParams params = window.getAttributes();
params.alpha = alphaLevel;
window.setAttributes(params);
}
private void showPopupWindow() {
if (mPopupWindow != null) {
setBackgroundAlpha(0.6f);
mPopupWindow.showAsDropDown(ivAvatar, 0, 20);
}
}
private void closePopupWindow() {
if (mPopupWindow != null) {
mPopupWindow.dismiss();
Logger.d(TAG, "close popupWindow");
}
}
@Override
protected void onPause() {
super.onPause();
closePopupWindow();
stopRefresh();
}
/**
* 从相册选取
*/
private void choosePhoto() {
Intent intentPhoto = new Intent(Intent.ACTION_PICK);
intentPhoto.setType("image/*");
startActivityForResult(intentPhoto, ConstantValues.REQUEST_CODE_OF_GRLLERY);
}
/**
* 拍照
*/
private void takePhoto() {
//创建一个file,用来存储拍照后的照片
File imageFile = new File(this.getExternalCacheDir(),"output.png");
try {
if (imageFile.exists()){
imageFile.delete();//删除
}
imageFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= 24){
mImageUri = FileProvider.getUriForFile(MainActivity.this,
"com.njzhikejia.echohealth.healthlife.fileprovider",
imageFile);
}else{
mImageUri = Uri.fromFile(imageFile);
}
//启动相机程序
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT,mImageUri);
startActivityForResult(intent,ConstantValues.REQUEST_CODE_OF_CAMERA);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Logger.d(TAG, "onActivityResult resultCode = "+resultCode+" requestCode = "+requestCode);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case ConstantValues.REQUEST_CODE_OF_GRLLERY:
if (data == null) {
Logger.e(TAG, "no photo selected");
return;
}
setAvatar(data.getData());
break;
case ConstantValues.REQUEST_CODE_OF_CAMERA:
if (mImageUri == null) {
Logger.e(TAG, "take photo imageuri is null");
return;
}
setAvatar(mImageUri);
break;
}
}
}
private void setAvatar(Uri uri) {
Bitmap selectedPhoto = ImageUtil.decodeUri(MainActivity.this,uri,800, 480);
ivAvatar.setImageBitmap(selectedPhoto);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.pop_pic:
Logger.d(TAG, "choose photo from gallery");
choosePhoto();
closePopupWindow();
break;
case R.id.pop_camera:
Logger.d(TAG, "take photo");
takePhoto();
closePopupWindow();
break;
case R.id.pop_cancel:
Logger.d(TAG, "cancel select photo");
closePopupWindow();
break;
}
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
Logger.d(TAG, "onDestroy");
if (mLocalBroadcastManager != null) {
mLocalBroadcastManager.unregisterReceiver(mainBroadcastReceiver);
}
}
}
| UTF-8 | Java | 27,925 | java | MainActivity.java | Java | []
| null | []
| package com.njzhikejia.echohealth.healthlife;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.content.FileProvider;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.os.Bundle;
import android.support.v7.graphics.drawable.DrawerArrowDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.google.gson.Gson;
import com.njzhikejia.echohealth.healthlife.adapter.MemberListAdapter;
import com.njzhikejia.echohealth.healthlife.entity.concern.Concerns;
import com.njzhikejia.echohealth.healthlife.entity.concern.MyFollowsData;
import com.njzhikejia.echohealth.healthlife.entity.rule.RuleResult;
import com.njzhikejia.echohealth.healthlife.entity.rule.WarnRule;
import com.njzhikejia.echohealth.healthlife.entity.user.UserDetailsResponse;
import com.njzhikejia.echohealth.healthlife.greendao.ConcernsDao;
import com.njzhikejia.echohealth.healthlife.greendao.DaoSession;
import com.njzhikejia.echohealth.healthlife.http.CommonRequest;
import com.njzhikejia.echohealth.healthlife.http.OKHttpClientManager;
import com.njzhikejia.echohealth.healthlife.util.ChineseCharComp;
import com.njzhikejia.echohealth.healthlife.util.ConstantValues;
import com.njzhikejia.echohealth.healthlife.util.ImageUtil;
import com.njzhikejia.echohealth.healthlife.util.Logger;
import com.njzhikejia.echohealth.healthlife.util.NetWorkUtils;
import com.njzhikejia.echohealth.healthlife.util.PreferenceUtil;
import com.njzhikejia.echohealth.healthlife.util.ToastUtil;
import com.njzhikejia.echohealth.healthlife.widget.BadgeDrawerArrowDrawable;
import com.njzhikejia.echohealth.healthlife.widget.banner.CycleViewPager;
import com.njzhikejia.echohealth.healthlife.widget.banner.ViewUtil;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class MainActivity extends BaseActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
private static final String TAG = "MainActivity";
private Toolbar mToolbar;
private NavigationView mNavigation;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private RecyclerView mRecycleView;
private MemberListAdapter mAdapter;
private List<Concerns> memberList;
private ImageView ivAvatar;
private static final int REQUEST_CODE_CHOOSE = 200;
private static final int LOAD_RELATIVES_SUCCESS = 28;
private static final int QUERY_USER_INFO_SUCCESS = 29;
private PopupWindow mPopupWindow;
private TextView tvGallery;
private TextView tvCamera;
private TextView tvCancel;
private Uri mImageUri;
private MainHandler mHandler;
private SwipeRefreshLayout mSwipeRefreshLayout;
private TextView tvName;
private TextView tvNumber;
private LocalBroadcastManager mLocalBroadcastManager;
private MainBroadcastReceiver mainBroadcastReceiver;
public static final String KEY_MEMBER = "key_member";
private DaoSession mDaoSession;
private ConcernsDao concernsDao;
private BadgeDrawerArrowDrawable badgeDrawerArrowDrawable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new MainHandler(this);
initDaoSession();
initView();
judgeNewConcerns();
loadRealtives();
getWarnRules();
initPopupWindow();
}
private void initDaoSession() {
HealthLifeApplication mApplication = (HealthLifeApplication) getApplication();
mDaoSession = mApplication.getDaoSession();
concernsDao = mDaoSession.getConcernsDao();
}
private void initView() {
Logger.d(TAG, "initView");
mLocalBroadcastManager = LocalBroadcastManager.getInstance(getApplicationContext());
mainBroadcastReceiver = new MainBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConstantValues.ACTION_EXIT_LOGIN);
intentFilter.addAction(ConstantValues.ACTION_CONCERN_REQUEST_RECEIVED);
intentFilter.addAction(ConstantValues.ACTION_CONCERN_REQUEST_FINISHED);
intentFilter.addAction(ConstantValues.ACTION_CONCERN_REQUEST_ACCEPTED);
mLocalBroadcastManager.registerReceiver(mainBroadcastReceiver, intentFilter);
mSwipeRefreshLayout = findViewById(R.id.refresh_layout);
mSwipeRefreshLayout.setColorSchemeResources(R.color.toolbar);
mSwipeRefreshLayout.setOnRefreshListener(this);
mToolbar = findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mNavigation = findViewById(R.id.bottom_navigation);
mDrawerLayout = findViewById(R.id.drawerLayout);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
mToolbar,0,0
);
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
mNavigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_meember_manager:
Logger.d(TAG, "menu member manager clicked");
Intent intentMember = new Intent(MainActivity.this, MemberManageActivity.class);
startActivity(intentMember);
break;
case R.id.menu_setting:
Logger.d(TAG, "menu system setting clicked");
Intent intentSetting = new Intent(MainActivity.this, SystemSettingActivity.class);
startActivity(intentSetting);
break;
case R.id.menu_msg_center:
Logger.d(TAG, "menu msg center clicked");
Intent intentMsg = new Intent(MainActivity.this, MessageCenterActivity.class);
startActivity(intentMsg);
break;
case R.id.menu_feedback:
Logger.d(TAG, "menu feedback clicked");
Intent intentFeedback = new Intent(MainActivity.this, FeedbackActivity.class);
startActivity(intentFeedback);
break;
case R.id.menu_about:
Intent intentAbout = new Intent(MainActivity.this, AboutActivity.class);
startActivity(intentAbout);
break;
}
mDrawerLayout.closeDrawer(mNavigation);
return false;
}
});
View headerLayout = mNavigation.getHeaderView(0);
ivAvatar= headerLayout.findViewById(R.id.iv_avatar);
tvName = headerLayout.findViewById(R.id.tv_header_name);
tvNumber = headerLayout.findViewById(R.id.tv_header_number);
updateName();
ivAvatar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// if (mPopupWindow == null) {
// return;
// }
// if (mPopupWindow.isShowing()) {
// closePopupWindow();
// } else {
// showPopupWindow();
// }
Intent intentDetails = new Intent(MainActivity.this, UserDetailsActivity.class);
Concerns user = new Concerns();
user.setUid(PreferenceUtil.getLoginUserUID(MainActivity.this));
user.setName(PreferenceUtil.getLoginUserName(MainActivity.this));
user.setPhone(PreferenceUtil.getLoginUserPhone(MainActivity.this));
intentDetails.putExtra(ConstantValues.KEY_USER_DETAILS, user);
startActivity(intentDetails);
}
});
mRecycleView = findViewById(R.id.recycle_view);
memberList = new ArrayList<>();
initBanner();
mAdapter = new MemberListAdapter(this, memberList);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
mRecycleView.setHasFixedSize(true);
mRecycleView.setLayoutManager(layoutManager);
mRecycleView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new MemberListAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
Concerns member = memberList.get(position);
Logger.d(TAG, "onItemClick member name is "+member.getName());
Intent intentMember = new Intent(view.getContext(), MeasureDataActivity.class);
intentMember.putExtra(KEY_MEMBER, member);
startActivity(intentMember);
}
});
}
private void judgeNewConcerns() {
if (PreferenceUtil.getNewConcern(this)) {
showSideUnread();
showMemberMenuUnread();
} else {
hideSideUnread();
hideMemberMenuUnread();
}
}
/**
* 显示成员管理小红点
*/
private void showMemberMenuUnread() {
if (mNavigation == null) {
mNavigation =findViewById(R.id.bottom_navigation);
}
LinearLayout linearLayout = (LinearLayout) mNavigation.getMenu().findItem(R.id.menu_meember_manager).getActionView();
if (linearLayout != null) {
TextView tv = linearLayout.findViewById(R.id.tv_unread);
tv.setVisibility(View.VISIBLE);
} else {
Logger.e(TAG, "LinearLayout == null");
}
}
/**
* 隐藏成员管理小红点
*/
private void hideMemberMenuUnread() {
if (mNavigation == null) {
mNavigation =findViewById(R.id.bottom_navigation);
}
LinearLayout linearLayout = (LinearLayout) mNavigation.getMenu().findItem(R.id.menu_meember_manager).getActionView();
if (linearLayout != null) {
TextView tv = linearLayout.findViewById(R.id.tv_unread);
tv.setVisibility(View.GONE);
} else {
Logger.e(TAG, "LinearLayout == null");
}
}
/**
* 显示消息中心小红点
*/
private void showMsgCenterMenuUnread() {
if (mNavigation == null) {
mNavigation =findViewById(R.id.bottom_navigation);
}
LinearLayout linearLayout = (LinearLayout) mNavigation.getMenu().findItem(R.id.menu_msg_center).getActionView();
if (linearLayout != null) {
TextView tv = linearLayout.findViewById(R.id.tv_unread);
tv.setVisibility(View.VISIBLE);
} else {
Logger.e(TAG, "LinearLayout == null");
}
}
/**
* 隐藏消息中心小红点
*/
private void hideMsgCenterMenuUnread() {
if (mNavigation == null) {
mNavigation =findViewById(R.id.bottom_navigation);
}
LinearLayout linearLayout = (LinearLayout) mNavigation.getMenu().findItem(R.id.menu_msg_center).getActionView();
if (linearLayout != null) {
TextView tv = linearLayout.findViewById(R.id.tv_unread);
tv.setVisibility(View.GONE);
} else {
Logger.e(TAG, "LinearLayout == null");
}
}
/**
* 显示toolbar左侧菜单键小红点
*/
private void showSideUnread() {
if (mDrawerToggle != null) {
if (badgeDrawerArrowDrawable == null) {
badgeDrawerArrowDrawable = new BadgeDrawerArrowDrawable(getSupportActionBar().getThemedContext());
}
mDrawerToggle.setDrawerArrowDrawable(badgeDrawerArrowDrawable);
}
}
/**
* 隐藏toolbar左侧菜单键小红点
*/
private void hideSideUnread() {
if (mDrawerToggle != null) {
mDrawerToggle.setDrawerArrowDrawable(new DrawerArrowDrawable(getSupportActionBar().getThemedContext()));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
class MainBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (ConstantValues.ACTION_EXIT_LOGIN.equals(intent.getAction())) {
finish();
} else if (ConstantValues.ACTION_CONCERN_REQUEST_RECEIVED.equals(intent.getAction())) {
showSideUnread();
showMemberMenuUnread();
} else if (ConstantValues.ACTION_CONCERN_REQUEST_FINISHED.equals(intent.getAction())) {
hideSideUnread();
hideMemberMenuUnread();
} else if (ConstantValues.ACTION_CONCERN_REQUEST_ACCEPTED.equals(intent.getAction())) {
loadRealtives();
}
}
}
@Override
public void onRefresh() {
Logger.d(TAG, "onRefresh");
loadRealtives();
mHandler.sendEmptyMessageDelayed(ConstantValues.MSG_REFRESH_TIME_OUT, ConstantValues.REFRESH_TIME_OUT);
}
private void stopRefresh() {
if (mSwipeRefreshLayout != null) {
mSwipeRefreshLayout.setRefreshing(false);
Logger.d(TAG, "stopRefresh!");
}
}
static class MainHandler extends Handler{
private WeakReference<MainActivity> weakReference;
public MainHandler(MainActivity mainActivity) {
weakReference = new WeakReference<MainActivity>(mainActivity);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case ConstantValues.MSG_REFRESH_TIME_OUT:
if (weakReference.get() != null) {
weakReference.get().stopRefresh();
}
break;
case LOAD_RELATIVES_SUCCESS:
if (weakReference.get() != null) {
weakReference.get().stopRefresh();
weakReference.get().mAdapter.setList(weakReference.get().memberList);
}
break;
case QUERY_USER_INFO_SUCCESS:
if (weakReference.get() != null) {
weakReference.get().updateName();
}
break;
}
}
}
private void updateName() {
tvName.setText(PreferenceUtil.getLoginUserName(MainActivity.this));
// tvNumber.setText(PreferenceUtil.getLoginUserPhone(MainActivity.this));
}
// 加载亲友列表
private void loadRealtives() {
if (!NetWorkUtils.isNetworkConnected(this)) {
ToastUtil.showShortToast(this, R.string.net_work_error);
stopRefresh();
loadDataFromDb();
return;
}
/**
OKHttpClientManager.getInstance().getAsync(CommonRequest.getRealtivesList(PreferenceUtil.getLoginUserUID(this)), new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Logger.e(TAG, "loadRelatives failure");
stopRefresh();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseContent = response.body().string();
Logger.d(TAG, "onResponse code = "+response.code() + "responseContent = "+responseContent);
if (response.code() == 200) {
Gson gson = new Gson();
RelativesData relativesData = gson.fromJson(responseContent, RelativesData.class);
memberList = relativesData.getData().getRelatives();
RelativesData.Data.Relatives me = new RelativesData.Data.Relatives();
me.setName(getString(R.string.me));
me.setPhone(PreferenceUtil.getLoginUserPhone(MainActivity.this));
me.setUid(PreferenceUtil.getLoginUserUID(MainActivity.this));
memberList.add(me);
Comparator cmp = new ChineseCharComp();
Collections.sort(memberList, cmp);
mHandler.sendEmptyMessage(LOAD_RELATIVES_SUCCESS);
}
}
}); */
OKHttpClientManager.getInstance().getAsync(CommonRequest.getMyFollows(PreferenceUtil.getLoginUserUID(this)), new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Logger.e(TAG, "onFailure");
stopRefresh();
loadDataFromDb();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseContent = response.body().string();
Logger.d(TAG, "onResponse code = "+response.code() + "content = "+responseContent);
if (response.code() == 200 && !TextUtils.isEmpty(responseContent)) {
Logger.d(TAG, "onRespone load my follows success");
Gson gson = new Gson();
MyFollowsData data = gson.fromJson(responseContent, MyFollowsData.class);
memberList = data.getData().getConcerns();
Comparator cmp = new ChineseCharComp();
Collections.sort(memberList, cmp);
Concerns me = new Concerns();
me.setName(getString(R.string.me));
me.setPhone(PreferenceUtil.getLoginUserPhone(MainActivity.this));
me.setUid(PreferenceUtil.getLoginUserUID(MainActivity.this));
memberList.add(0, me);
mHandler.sendEmptyMessage(LOAD_RELATIVES_SUCCESS);
concernsDao.deleteAll();
for (Concerns concerns : memberList) {
concernsDao.insert(concerns);
}
}
}
});
}
private void loadDataFromDb() {
memberList = concernsDao.loadAll();
mAdapter.setList(memberList);
}
/**
// 查询用户详情
private void queryUserInfo() {
if (!NetWorkUtils.isNetworkConnected(this)) {
ToastUtil.showShortToast(this, R.string.net_work_error);
return;
}
OKHttpClientManager.getInstance().getAsync(CommonRequest.getUserDetailsRequest(PreferenceUtil.getLoginUserUID(MainActivity.this)), new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Logger.e(TAG, "onFailure call = "+call.toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Logger.d(TAG, "getUserDetails onResponse code = "+response.code());
String resonseContent = response.body().string();
Logger.d(TAG, "responseContent = "+resonseContent);
if (response.code() == 200) {
Gson gson = new Gson();
UserDetailsResponse userDetailsResponse = gson.fromJson(resonseContent, UserDetailsResponse.class);
String name = userDetailsResponse.getData().getUser().getName();
PreferenceUtil.putLoginUserName(MainActivity.this, name);
mHandler.sendEmptyMessage(QUERY_USER_INFO_SUCCESS);
}
}
});
} */
private void getWarnRules() {
if (!NetWorkUtils.isNetworkConnected(this)) {
ToastUtil.showShortToast(this, R.string.net_work_error);
return;
}
OKHttpClientManager.getInstance().getAsync(CommonRequest.getWarnRuleRequest(PreferenceUtil.getLoginUserUID(this)), new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Logger.d(TAG, "get warn rules failure");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String content = response.body().string();
Logger.d(TAG, "code = "+response.code() + "content = "+content);
Gson gson = new Gson();
WarnRule warnRule = gson.fromJson(content, WarnRule.class);
String data = warnRule.getData().getRules().getData();
Logger.d(TAG, "data = "+data);
Gson gsonRule = new Gson();
RuleResult ruleResult = gsonRule.fromJson(data, RuleResult.class);
}
});
}
private void initBanner() {
List<View> views = new ArrayList<View>();
// 将最后一个view添加进来
views.add(ViewUtil.getView(this, R.drawable.photo_four));
views.add(ViewUtil.getView(this, R.drawable.photo_one));
views.add(ViewUtil.getView(this, R.drawable.photo_two));
views.add(ViewUtil.getView(this, R.drawable.photo_three));
views.add(ViewUtil.getView(this, R.drawable.photo_four));
// 将第一个view添加进来
views.add(ViewUtil.getView(this, R.drawable.photo_one));
final CycleViewPager cycleViewPager = (CycleViewPager) findViewById(R.id.banner);
cycleViewPager.setIndicatorCenter();
cycleViewPager.setIndicatorsSpace(8);
cycleViewPager.setData(views, true, true, 3000);
}
private void initPopupWindow() {
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.popwindow_avatar, null);
tvGallery = view.findViewById(R.id.pop_pic);
tvCamera = view.findViewById(R.id.pop_camera);
tvCancel = view.findViewById(R.id.pop_cancel);
tvGallery.setOnClickListener(this);
tvCamera.setOnClickListener(this);
tvCancel.setOnClickListener(this);
mPopupWindow = new PopupWindow(view, 660, ViewGroup.LayoutParams.WRAP_CONTENT);
mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
mPopupWindow.setOutsideTouchable(true);
mPopupWindow.setTouchable(true);
mPopupWindow.setFocusable(true);
mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
setBackgroundAlpha(1.0f);
}
});
}
private void setBackgroundAlpha(float alphaLevel) {
Window window = getWindow();
WindowManager.LayoutParams params = window.getAttributes();
params.alpha = alphaLevel;
window.setAttributes(params);
}
private void showPopupWindow() {
if (mPopupWindow != null) {
setBackgroundAlpha(0.6f);
mPopupWindow.showAsDropDown(ivAvatar, 0, 20);
}
}
private void closePopupWindow() {
if (mPopupWindow != null) {
mPopupWindow.dismiss();
Logger.d(TAG, "close popupWindow");
}
}
@Override
protected void onPause() {
super.onPause();
closePopupWindow();
stopRefresh();
}
/**
* 从相册选取
*/
private void choosePhoto() {
Intent intentPhoto = new Intent(Intent.ACTION_PICK);
intentPhoto.setType("image/*");
startActivityForResult(intentPhoto, ConstantValues.REQUEST_CODE_OF_GRLLERY);
}
/**
* 拍照
*/
private void takePhoto() {
//创建一个file,用来存储拍照后的照片
File imageFile = new File(this.getExternalCacheDir(),"output.png");
try {
if (imageFile.exists()){
imageFile.delete();//删除
}
imageFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= 24){
mImageUri = FileProvider.getUriForFile(MainActivity.this,
"com.njzhikejia.echohealth.healthlife.fileprovider",
imageFile);
}else{
mImageUri = Uri.fromFile(imageFile);
}
//启动相机程序
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT,mImageUri);
startActivityForResult(intent,ConstantValues.REQUEST_CODE_OF_CAMERA);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Logger.d(TAG, "onActivityResult resultCode = "+resultCode+" requestCode = "+requestCode);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case ConstantValues.REQUEST_CODE_OF_GRLLERY:
if (data == null) {
Logger.e(TAG, "no photo selected");
return;
}
setAvatar(data.getData());
break;
case ConstantValues.REQUEST_CODE_OF_CAMERA:
if (mImageUri == null) {
Logger.e(TAG, "take photo imageuri is null");
return;
}
setAvatar(mImageUri);
break;
}
}
}
private void setAvatar(Uri uri) {
Bitmap selectedPhoto = ImageUtil.decodeUri(MainActivity.this,uri,800, 480);
ivAvatar.setImageBitmap(selectedPhoto);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.pop_pic:
Logger.d(TAG, "choose photo from gallery");
choosePhoto();
closePopupWindow();
break;
case R.id.pop_camera:
Logger.d(TAG, "take photo");
takePhoto();
closePopupWindow();
break;
case R.id.pop_cancel:
Logger.d(TAG, "cancel select photo");
closePopupWindow();
break;
}
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
Logger.d(TAG, "onDestroy");
if (mLocalBroadcastManager != null) {
mLocalBroadcastManager.unregisterReceiver(mainBroadcastReceiver);
}
}
}
| 27,925 | 0.614587 | 0.612602 | 710 | 38.005634 | 28.500406 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.66338 | false | false | 14 |
1bc39bb7ab2c32951915b3b57901b1c2d64e6c70 | 26,783,416,114,919 | 210181ada81b131805c79002e1df6673c70f44dc | /hashs/TablaHash.java | 35ee806df6b5d8b7eb70fbffb5135d86e88c28b7 | []
| no_license | Kzarama/estructuras | https://github.com/Kzarama/estructuras | ed653a8dc7c35a81630dd8bcefc33582eb1fdc2a | a4e7dba6cde1949a4e08438b5d66d3dad84d754b | refs/heads/master | 2021-06-26T20:44:22.326000 | 2020-11-07T18:50:16 | 2020-11-07T18:50:16 | 155,859,866 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hashs;
import java.util.NoSuchElementException;
public class TablaHash<T> {
private int tamanio;
private ItemHash<T>[] itemHash;
public TablaHash(int tamanio) {
this.tamanio = tamanio;
itemHash = new ItemHash[tamanio];
}
public int hashCodeValue(int key) {
return key % tamanio;
}
public void push(int key, T object) {
int hashPosition = hashCodeValue(key);
if(itemHash[hashPosition] == null) {
itemHash[hashPosition] = new ItemHash<T>(key, object);
} else {
ItemHash<T> hashItemCurrent = itemHash[hashPosition];
while(hashItemCurrent.getNextItemHash() != null) {
hashItemCurrent = hashItemCurrent.getNextItemHash();
}
hashItemCurrent.setNextItemHash(new ItemHash<T>(key, object));
}
}
public T search(int key) {
int hashPosition = hashCodeValue(key);
ItemHash<T> hashItemCurrent = itemHash[hashPosition];
while(hashItemCurrent != null && hashItemCurrent.getKey() != key) {
hashItemCurrent = hashItemCurrent.getNextItemHash();
}
if(itemHash[hashPosition] == null) {
throw new NoSuchElementException();
} else {
return hashItemCurrent.getItem();
}
}
public void delete(int key) {
int hashPosition = hashCodeValue(key);
while(itemHash[hashPosition] != null && itemHash[hashPosition].getNextItemHash().getKey() != key) {
itemHash[hashPosition] = itemHash[hashPosition].getNextItemHash();
}
if(itemHash[hashPosition] == null) {
throw new NoSuchElementException();
} else {
itemHash[hashPosition].setNextItemHash(itemHash[hashPosition].getNextItemHash().getNextItemHash());
}
}
}
| UTF-8 | Java | 1,590 | java | TablaHash.java | Java | []
| null | []
| package hashs;
import java.util.NoSuchElementException;
public class TablaHash<T> {
private int tamanio;
private ItemHash<T>[] itemHash;
public TablaHash(int tamanio) {
this.tamanio = tamanio;
itemHash = new ItemHash[tamanio];
}
public int hashCodeValue(int key) {
return key % tamanio;
}
public void push(int key, T object) {
int hashPosition = hashCodeValue(key);
if(itemHash[hashPosition] == null) {
itemHash[hashPosition] = new ItemHash<T>(key, object);
} else {
ItemHash<T> hashItemCurrent = itemHash[hashPosition];
while(hashItemCurrent.getNextItemHash() != null) {
hashItemCurrent = hashItemCurrent.getNextItemHash();
}
hashItemCurrent.setNextItemHash(new ItemHash<T>(key, object));
}
}
public T search(int key) {
int hashPosition = hashCodeValue(key);
ItemHash<T> hashItemCurrent = itemHash[hashPosition];
while(hashItemCurrent != null && hashItemCurrent.getKey() != key) {
hashItemCurrent = hashItemCurrent.getNextItemHash();
}
if(itemHash[hashPosition] == null) {
throw new NoSuchElementException();
} else {
return hashItemCurrent.getItem();
}
}
public void delete(int key) {
int hashPosition = hashCodeValue(key);
while(itemHash[hashPosition] != null && itemHash[hashPosition].getNextItemHash().getKey() != key) {
itemHash[hashPosition] = itemHash[hashPosition].getNextItemHash();
}
if(itemHash[hashPosition] == null) {
throw new NoSuchElementException();
} else {
itemHash[hashPosition].setNextItemHash(itemHash[hashPosition].getNextItemHash().getNextItemHash());
}
}
}
| 1,590 | 0.71195 | 0.71195 | 58 | 26.413794 | 25.506615 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.086207 | false | false | 14 |
16c8c115635d442a758829a9d6e7476d54df41f2 | 6,468,220,800,286 | 023b7a2e7fef27d19770ec8afa598a105d133483 | /app/src/main/java/com/gibi/walter/Main1Activity.java | c121dda7538cb472535b64e4da1b1b0e18b62469 | []
| no_license | Ayoub9412/ggg2 | https://github.com/Ayoub9412/ggg2 | 03b7c5d8aa030b54db029f53a15b3b3f64a6e06e | d615d12df12375e59f0fc9ac5f71c34b11c6bbde | refs/heads/master | 2020-03-20T06:18:54.029000 | 2018-06-13T15:52:12 | 2018-06-13T15:52:12 | 137,244,990 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gibi.walter;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
public class Main1Activity extends AppCompatActivity {
Button nextBtn;
Toolbar myToolbar;
AdView myAdView;
InterstitialAd myInterstitial;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
myToolbar=(Toolbar)findViewById(R.id.myToolbar);
myToolbar.setTitle("");
setSupportActionBar(myToolbar);
final Intent i = new Intent(Main1Activity.this,Main2Activity.class);
nextBtn=(Button)findViewById(R.id.myNextButton);
MobileAds.initialize(this,getResources().getString(R.string.admob_appid));
AdRequest adRequest= new AdRequest.Builder().build();
myAdView=(AdView)findViewById(R.id.adView);
myAdView.loadAd(adRequest);
myAdView.setAdListener(new AdListener(){
@Override
public void onAdFailedToLoad(int i) {
myAdView.loadAd(new AdRequest.Builder().build());
}
});
myInterstitial=new InterstitialAd(this);
myInterstitial.setAdUnitId(getResources().getString(R.string.admob_interstitial));
myInterstitial.loadAd(adRequest);
myInterstitial.setAdListener(new AdListener(){
@Override
public void onAdFailedToLoad(int i) {
myInterstitial.loadAd(new AdRequest.Builder().build());
}
@Override
public void onAdClosed() {
myInterstitial.loadAd(new AdRequest.Builder().build());
}
});
nextBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(i);
myInterstitial.show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id==R.id.privacy){
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.privacy_link))));
Toast.makeText(this, "سياسة الخصوصية", Toast.LENGTH_SHORT).show();
return true;
}else if (id==R.id.rateus){
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.rate_us_link))));
Toast.makeText(this, "خمس نجوم", Toast.LENGTH_SHORT).show();
return true;
}else return false;
}
}
| UTF-8 | Java | 3,401 | java | Main1Activity.java | Java | []
| null | []
| package com.gibi.walter;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
public class Main1Activity extends AppCompatActivity {
Button nextBtn;
Toolbar myToolbar;
AdView myAdView;
InterstitialAd myInterstitial;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
myToolbar=(Toolbar)findViewById(R.id.myToolbar);
myToolbar.setTitle("");
setSupportActionBar(myToolbar);
final Intent i = new Intent(Main1Activity.this,Main2Activity.class);
nextBtn=(Button)findViewById(R.id.myNextButton);
MobileAds.initialize(this,getResources().getString(R.string.admob_appid));
AdRequest adRequest= new AdRequest.Builder().build();
myAdView=(AdView)findViewById(R.id.adView);
myAdView.loadAd(adRequest);
myAdView.setAdListener(new AdListener(){
@Override
public void onAdFailedToLoad(int i) {
myAdView.loadAd(new AdRequest.Builder().build());
}
});
myInterstitial=new InterstitialAd(this);
myInterstitial.setAdUnitId(getResources().getString(R.string.admob_interstitial));
myInterstitial.loadAd(adRequest);
myInterstitial.setAdListener(new AdListener(){
@Override
public void onAdFailedToLoad(int i) {
myInterstitial.loadAd(new AdRequest.Builder().build());
}
@Override
public void onAdClosed() {
myInterstitial.loadAd(new AdRequest.Builder().build());
}
});
nextBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(i);
myInterstitial.show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id==R.id.privacy){
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.privacy_link))));
Toast.makeText(this, "سياسة الخصوصية", Toast.LENGTH_SHORT).show();
return true;
}else if (id==R.id.rateus){
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.rate_us_link))));
Toast.makeText(this, "خمس نجوم", Toast.LENGTH_SHORT).show();
return true;
}else return false;
}
}
| 3,401 | 0.662526 | 0.660751 | 106 | 30.896227 | 25.655529 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.622642 | false | false | 14 |
3994a15638b09ab8a3ce3a8ed6b68df84c9bc072 | 6,468,220,800,951 | 1d3bfaa5732c5df3320eb54106484608f6dd58e6 | /src/main/java/com/ebizprise/das/utilsweb/form/jwt/TokenKeyForm.java | 7c2be8c6636f90ac3bec8a89adbfe30c30059764 | []
| no_license | jackylee101/outsidemaster | https://github.com/jackylee101/outsidemaster | 6d145670db2ac0475bff874c3acf3f444ca8fa2b | ef61e629cedd39d98e7ec2ecd10944f38c8668db | refs/heads/master | 2022-09-15T07:54:43.257000 | 2019-08-12T02:35:01 | 2019-08-12T02:35:01 | 188,179,487 | 0 | 0 | null | false | 2022-09-01T23:07:19 | 2019-05-23T07:02:00 | 2019-08-12T02:35:08 | 2022-09-01T23:07:16 | 471 | 0 | 0 | 4 | Java | false | false | package com.ebizprise.das.utilsweb.form.jwt;
import java.io.Serializable;
/*
*
* @author maduar
* @date 09/07/2018 11:48 AM
* @email maduar@163.com
*
* */
public class TokenKeyForm implements Serializable {
private static final long serialVersionUID = 1L;
private String custId;
private String tokenKey;
public String getCustId() {
return custId;
}
public void setCustId(String custId) {
this.custId = custId;
}
public String getTokenKey() {
return tokenKey;
}
public void setTokenKey(String tokenKey) {
this.tokenKey = tokenKey;
}
public TokenKeyForm(String custId, String tokenKey) {
this.custId = custId;
this.tokenKey = tokenKey;
}
public TokenKeyForm() {
}
@Override
public String toString() {
return "TokenKeyForm{" +
"custId='" + custId + '\'' +
", tokenKey='" + tokenKey + '\'' +
'}';
}
}
| UTF-8 | Java | 990 | java | TokenKeyForm.java | Java | [
{
"context": "t;\n\nimport java.io.Serializable;\n\n/*\n *\n * @author maduar\n * @date 09/07/2018 11:48 AM\n * @email maduar@163",
"end": 99,
"score": 0.9994155764579773,
"start": 93,
"tag": "USERNAME",
"value": "maduar"
},
{
"context": "thor maduar\n * @date 09/07/2018 11:48 AM\n * @email maduar@163.com\n *\n * */\npublic class TokenKeyForm implements Ser",
"end": 153,
"score": 0.9999294281005859,
"start": 139,
"tag": "EMAIL",
"value": "maduar@163.com"
}
]
| null | []
| package com.ebizprise.das.utilsweb.form.jwt;
import java.io.Serializable;
/*
*
* @author maduar
* @date 09/07/2018 11:48 AM
* @email <EMAIL>
*
* */
public class TokenKeyForm implements Serializable {
private static final long serialVersionUID = 1L;
private String custId;
private String tokenKey;
public String getCustId() {
return custId;
}
public void setCustId(String custId) {
this.custId = custId;
}
public String getTokenKey() {
return tokenKey;
}
public void setTokenKey(String tokenKey) {
this.tokenKey = tokenKey;
}
public TokenKeyForm(String custId, String tokenKey) {
this.custId = custId;
this.tokenKey = tokenKey;
}
public TokenKeyForm() {
}
@Override
public String toString() {
return "TokenKeyForm{" +
"custId='" + custId + '\'' +
", tokenKey='" + tokenKey + '\'' +
'}';
}
}
| 983 | 0.582828 | 0.566667 | 50 | 18.799999 | 17.568153 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.28 | false | false | 14 |
80f5b9562297ad4b58fdfccc999f9ba6c2724838 | 28,046,136,446,540 | 2420b2758b726ebbe84e3aeb7f59884c95d5fccc | /SOFTWARE ENGINEERING/SEC_Reservation_System/src/ButtonListener.java | 0903efaad744b66227f1bfc6d8226d545ba9d02a | []
| no_license | Sriramwall/MASTER_CS_PROJECTS | https://github.com/Sriramwall/MASTER_CS_PROJECTS | 35d5fe4b7ef1dfd42e8831a41f57f34635373336 | 4585e5630b7bdb757d8947e4b6a9da68c8ce0157 | refs/heads/master | 2020-05-30T13:56:15.430000 | 2019-06-01T20:11:07 | 2019-06-01T20:11:07 | 189,770,362 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public interface ButtonListener {
public void actionEmitted (String action);
}
| UTF-8 | Java | 81 | java | ButtonListener.java | Java | []
| null | []
|
public interface ButtonListener {
public void actionEmitted (String action);
}
| 81 | 0.790123 | 0.790123 | 3 | 25.666666 | 17.913372 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 14 |
3db9325527204f30a6658f0ed203fdaf916e95c8 | 24,996,709,725,118 | 52800224373458a9877276c8da03d3e0a0da0351 | /src/main/java/com/User/User.java | 48c43048c70864b501156f4bd339810ab68a1eca | []
| no_license | Abyetc/offerlineBilling | https://github.com/Abyetc/offerlineBilling | a98f358d3a44f15676ebc2b9497619637bf55806 | 1bc6cc966f23cea16c20f10dcbff31cf50ae9d7c | refs/heads/master | 2016-09-13T08:17:49.999000 | 2016-08-04T17:50:51 | 2016-08-04T17:50:51 | 64,955,495 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.User;
import java.util.HashMap;
/*
* 主要是统计用户在各个规则内的使用情况
*
*/
public class User {
private String phoneNumber; // 用户的电话号码
private HashMap<String, Long> ruleHashMap = new HashMap<String, Long>(); // 用户使用情况
private UserDataTraffic userDataTraffic;
public User(String pNumber, UserDataTraffic userDataTraffic){
this.userDataTraffic = userDataTraffic;
this.phoneNumber = pNumber;
}
// public User(String pNumber, List<String> ruleList) {
// phoneNumber = pNumber;
// for (String string : ruleList) {
// ruleHashMap.put(string, 0L);
// }
// }
public String getPhoneNumber() {
return phoneNumber;
}
public UserDataTraffic getUserDataTraffic() {
return userDataTraffic;
}
public void setUserDataTraffic(UserDataTraffic userDataTraffic) {
this.userDataTraffic = userDataTraffic;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public HashMap<String, Long> getRuleHashMap() {
return ruleHashMap;
}
public void setRuleHashMap(HashMap<String, Long> ruleHashMap) {
this.ruleHashMap = ruleHashMap;
}
//
// /**
// * 将匹配到的指定规则下的流量项相加
// * @param name
// * @param quantity
// */
// public void addTraffic(String name, String quantity) {
// long value = ruleHashMap.get(name);
// value += FormatConvert.getKB(quantity);
// ruleHashMap.put(name, value);
// }
//
//
//
// /**
// * 利用drools匹配完规则之后,更新用户使用数据(包括流量、语音、短信)
// * @param key 相关计费规则的名字
// * @param value 该计费规则对应的计费数量
// */
// public void updateMessage(String key, Long value) {
// long v = ruleHashMap.get(key);
// v += value;
// ruleHashMap.put(key, v);
// }
// public static void main(String[] args) {
// System.out.println(Usermessage.getKB("1G1M570KB"));
//
// }
}
| UTF-8 | Java | 1,938 | java | User.java | Java | []
| null | []
| package com.User;
import java.util.HashMap;
/*
* 主要是统计用户在各个规则内的使用情况
*
*/
public class User {
private String phoneNumber; // 用户的电话号码
private HashMap<String, Long> ruleHashMap = new HashMap<String, Long>(); // 用户使用情况
private UserDataTraffic userDataTraffic;
public User(String pNumber, UserDataTraffic userDataTraffic){
this.userDataTraffic = userDataTraffic;
this.phoneNumber = pNumber;
}
// public User(String pNumber, List<String> ruleList) {
// phoneNumber = pNumber;
// for (String string : ruleList) {
// ruleHashMap.put(string, 0L);
// }
// }
public String getPhoneNumber() {
return phoneNumber;
}
public UserDataTraffic getUserDataTraffic() {
return userDataTraffic;
}
public void setUserDataTraffic(UserDataTraffic userDataTraffic) {
this.userDataTraffic = userDataTraffic;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public HashMap<String, Long> getRuleHashMap() {
return ruleHashMap;
}
public void setRuleHashMap(HashMap<String, Long> ruleHashMap) {
this.ruleHashMap = ruleHashMap;
}
//
// /**
// * 将匹配到的指定规则下的流量项相加
// * @param name
// * @param quantity
// */
// public void addTraffic(String name, String quantity) {
// long value = ruleHashMap.get(name);
// value += FormatConvert.getKB(quantity);
// ruleHashMap.put(name, value);
// }
//
//
//
// /**
// * 利用drools匹配完规则之后,更新用户使用数据(包括流量、语音、短信)
// * @param key 相关计费规则的名字
// * @param value 该计费规则对应的计费数量
// */
// public void updateMessage(String key, Long value) {
// long v = ruleHashMap.get(key);
// v += value;
// ruleHashMap.put(key, v);
// }
// public static void main(String[] args) {
// System.out.println(Usermessage.getKB("1G1M570KB"));
//
// }
}
| 1,938 | 0.685993 | 0.682549 | 84 | 19.738094 | 20.70031 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.464286 | false | false | 14 |
f7a6047d01d853eb8450133f5b8cf9555e410fea | 33,200,097,235,375 | fb1fa116afb644c95cf21c296469943a91b1c64d | /VirtualCampusServer/src/common/AppointInfo.java | ab0afde807f8aa96f047fa34e43eff34601f6603 | []
| no_license | Silence-Rain/SEU_VirtualCampus | https://github.com/Silence-Rain/SEU_VirtualCampus | c0fcd2183cfde5b186d88058bd34f89e630779be | 087d9c58669a043cb73436a4ce6b5e8140b03018 | refs/heads/master | 2021-01-20T12:16:50.350000 | 2018-05-24T17:47:26 | 2018-05-24T17:47:26 | 101,707,858 | 10 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package common;
import java.io.Serializable;
/**
* 场馆预约项目信息
* (即tbAppoint表的结构)
*
* @author Silence
*
*/
public class AppointInfo implements Serializable{
private static final long serialVersionUID = 6;
/**
* 项目名称
*/
private String item;
/**
* 用二维数组保存各个时间段剩余场次
*/
private String itemRemain[][];
public AppointInfo(String item, String itemRemain) {
this.item = item;
setItemRemain(itemRemain);
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
/**
* 返回二维数组形式的剩余场次(给客户端)
*
* @return 二维数组形式的剩余场次
*/
public String[][] getItemRemain(){
return itemRemain;
}
/**
* 返回字符串形式的剩余场次(给数据库)
* 字符串格式:不同日期之间以";"分隔,一天不同时段之间以"&"分隔
*
* @return 字符串形式的剩余场次
*/
public String getItemRemainStr() {
String temp = "";
for (int i = 0; i < itemRemain.length; i++) {
for (int j = 0; j < itemRemain[i].length; j++) {
temp += itemRemain[i][j] + "&";
}
temp += ";";
}
return temp;
}
/**
* 用字符串形式设置二维数组形式
*
* @param itemRemain 字符串形式剩余场次
*/
public void setItemRemain(String itemRemain) {
String temp[] = itemRemain.split(";");
String res[][] = new String [temp.length][];
for (int i = 0; i < temp.length; i++) {
res[i] = temp[i].split("&");
}
this.itemRemain = res;
}
}
| GB18030 | Java | 1,761 | java | AppointInfo.java | Java | [
{
"context": "\n * 场馆预约项目信息\r\n * (即tbAppoint表的结构)\r\n * \r\n * @author Silence\r\n *\r\n */\r\npublic class AppointInfo implements Ser",
"end": 113,
"score": 0.9967727065086365,
"start": 106,
"tag": "NAME",
"value": "Silence"
}
]
| null | []
| package common;
import java.io.Serializable;
/**
* 场馆预约项目信息
* (即tbAppoint表的结构)
*
* @author Silence
*
*/
public class AppointInfo implements Serializable{
private static final long serialVersionUID = 6;
/**
* 项目名称
*/
private String item;
/**
* 用二维数组保存各个时间段剩余场次
*/
private String itemRemain[][];
public AppointInfo(String item, String itemRemain) {
this.item = item;
setItemRemain(itemRemain);
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
/**
* 返回二维数组形式的剩余场次(给客户端)
*
* @return 二维数组形式的剩余场次
*/
public String[][] getItemRemain(){
return itemRemain;
}
/**
* 返回字符串形式的剩余场次(给数据库)
* 字符串格式:不同日期之间以";"分隔,一天不同时段之间以"&"分隔
*
* @return 字符串形式的剩余场次
*/
public String getItemRemainStr() {
String temp = "";
for (int i = 0; i < itemRemain.length; i++) {
for (int j = 0; j < itemRemain[i].length; j++) {
temp += itemRemain[i][j] + "&";
}
temp += ";";
}
return temp;
}
/**
* 用字符串形式设置二维数组形式
*
* @param itemRemain 字符串形式剩余场次
*/
public void setItemRemain(String itemRemain) {
String temp[] = itemRemain.split(";");
String res[][] = new String [temp.length][];
for (int i = 0; i < temp.length; i++) {
res[i] = temp[i].split("&");
}
this.itemRemain = res;
}
}
| 1,761 | 0.538983 | 0.536271 | 81 | 16.209877 | 16.724134 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.283951 | false | false | 14 |
cef63f09956374e67f742877f44604ebec316a4a | 33,200,097,234,614 | 53b61f55711c19184ef6b4bb63d28ba628a60596 | /DiaryClocking/app/src/main/java/com/example/mine/CardFragment.java | 65cab4bb14e6ee92289f21d2591483ad04809158 | []
| no_license | Jack234740898/PartTimeJobAndroid | https://github.com/Jack234740898/PartTimeJobAndroid | 346990b8ecb21d8e0fb00efe3582ba9015141aa9 | d89d6c8543339f56ef4b24498f3425d7f61486ca | refs/heads/master | 2021-03-17T11:02:13.665000 | 2019-07-08T11:39:52 | 2019-07-08T11:39:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.mine;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.dao.HabitDao;
import com.example.model.Habit;
import com.example.myapp.R;
import com.example.utils.DateUtil;
import com.example.utils.SPUtil;
import java.util.List;
public class CardFragment extends Fragment {
private TextView mTvWeek;
private TextView mTvDate;
private String mCurrentDate;
private TextView mTvGetCard;
private HabitDao mHabitDao;
private View mLlCard;
public CardFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_mine, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mHabitDao = new HabitDao(getContext());
mLlCard = view.findViewById(R.id.ll_card);
initViewStatus();
mTvGetCard = view.findViewById(R.id.tv_get_card);
mTvWeek = view.findViewById(R.id.tv_week);
mTvWeek.setText(DateUtil.getWeek());
mTvDate = view.findViewById(R.id.tv_date);
mCurrentDate = DateUtil.getFormatDate();
mTvDate.setText(mCurrentDate);
initCardGet();
}
private void initCardGet() {
boolean hasGetCard = SPUtil.getBoolean(mCurrentDate, false);
if (!hasGetCard) {
mTvGetCard.setText("领取今日卡片");
mTvGetCard.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
getCard();
}
});
} else {
mTvGetCard.setText("已领取");
mLlCard.setVisibility(View.VISIBLE);
}
}
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
initViewStatus();
initCardGet();
}
private void initViewStatus() {
int todayAllCardTimes = 0;
List<Habit> list = mHabitDao.queryAllHabits();
if (list != null) {
for (Habit habit : list) {
String lastCardDate = habit.lastCardDate;
String today = DateUtil.getFormatDate();
if (TextUtils.equals(today, lastCardDate)) {
todayAllCardTimes++;
}
}
}
if (todayAllCardTimes > 0) {
mLlCard.setVisibility(View.VISIBLE);
} else {
mLlCard.setVisibility(View.GONE);
}
}
private void getCard() {
Toast.makeText(getContext(), "今日卡片已领取", Toast.LENGTH_SHORT).show();
mTvGetCard.setText("已领取");
SPUtil.putBoolean(mCurrentDate, true);
}
}
| UTF-8 | Java | 3,295 | java | CardFragment.java | Java | []
| null | []
| package com.example.mine;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.dao.HabitDao;
import com.example.model.Habit;
import com.example.myapp.R;
import com.example.utils.DateUtil;
import com.example.utils.SPUtil;
import java.util.List;
public class CardFragment extends Fragment {
private TextView mTvWeek;
private TextView mTvDate;
private String mCurrentDate;
private TextView mTvGetCard;
private HabitDao mHabitDao;
private View mLlCard;
public CardFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_mine, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mHabitDao = new HabitDao(getContext());
mLlCard = view.findViewById(R.id.ll_card);
initViewStatus();
mTvGetCard = view.findViewById(R.id.tv_get_card);
mTvWeek = view.findViewById(R.id.tv_week);
mTvWeek.setText(DateUtil.getWeek());
mTvDate = view.findViewById(R.id.tv_date);
mCurrentDate = DateUtil.getFormatDate();
mTvDate.setText(mCurrentDate);
initCardGet();
}
private void initCardGet() {
boolean hasGetCard = SPUtil.getBoolean(mCurrentDate, false);
if (!hasGetCard) {
mTvGetCard.setText("领取今日卡片");
mTvGetCard.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
getCard();
}
});
} else {
mTvGetCard.setText("已领取");
mLlCard.setVisibility(View.VISIBLE);
}
}
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
initViewStatus();
initCardGet();
}
private void initViewStatus() {
int todayAllCardTimes = 0;
List<Habit> list = mHabitDao.queryAllHabits();
if (list != null) {
for (Habit habit : list) {
String lastCardDate = habit.lastCardDate;
String today = DateUtil.getFormatDate();
if (TextUtils.equals(today, lastCardDate)) {
todayAllCardTimes++;
}
}
}
if (todayAllCardTimes > 0) {
mLlCard.setVisibility(View.VISIBLE);
} else {
mLlCard.setVisibility(View.GONE);
}
}
private void getCard() {
Toast.makeText(getContext(), "今日卡片已领取", Toast.LENGTH_SHORT).show();
mTvGetCard.setText("已领取");
SPUtil.putBoolean(mCurrentDate, true);
}
}
| 3,295 | 0.63187 | 0.630949 | 102 | 30.931372 | 20.110605 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.647059 | false | false | 14 |
819b9930cc77e3d9df03d3ae05aa6951603b8268 | 23,055,384,448,539 | db7b4b3003f0068225f04ab0b5fdf81315d125ae | /src/com/zjh/designpatterns/builder/concrete/XmlBuilder.java | 98bd11d1e6ee8c20c70f90a4099a9fa9c0b00c63 | []
| no_license | PrometheusH/DesignPattern | https://github.com/PrometheusH/DesignPattern | bd88efb96c010e6ff0252ae7a1dc40dc7b85fb84 | 7220a0b43e861349e77c888a353ae40f2778b0e8 | refs/heads/master | 2021-07-09T05:35:17.313000 | 2020-12-18T02:56:45 | 2020-12-18T02:56:45 | 216,313,223 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zjh.designpatterns.builder.concrete;
import java.util.Collection;
import java.util.Map;
public class XmlBuilder implements Builder {
StringBuffer buf = new StringBuffer();
@Override
public void builderHeader(ExportHeaderModel ehm) {
buf.append("<?xml version=1.0 encoding='gb2312'?>\n");
buf.append("<Report>\n");
buf.append(" <Header>\n");
buf.append(" <DepId>" + ehm.getDepId() + "</DepId>\n");
buf.append(" <ExportData>" + ehm.getExportDate() + "</ExportData>\n");
buf.append(" </Header>\n");
}
@Override
public void builderData(Map<String, Collection<ExportDataModel>> mapData) {
buf.append(" <Body>\n");
for (String tbName : mapData.keySet()) {
buf.append(" <Datas TableName=\"" + tbName + "\">\n");
for (ExportDataModel edm : mapData.get(tbName)) {
buf.append(" <Data>\n");
buf.append(" <ProductId>" + edm.getProductId() + "</ProductId>\n");
buf.append(" <Price>" + edm.getPrice() + "</Price>\n");
buf.append(" <Amount>" + edm.getAmount() + "</Amount>\n");
buf.append(" </Data>\n");
}
buf.append(" </Datas>\n");
}
buf.append(" </Body>\n");
}
@Override
public void builderFooter(ExportFooterModel efm) {
buf.append(" <Footer>\n");
buf.append(" <ExportUser>" + efm.getExportUser() + "</ExportUser>\n");
buf.append(" </Footer>\n");
buf.append("</Report>\n");
}
@Override
public void printFormatData() {
System.out.println("输出Xml文件的内容:\n" + buf);
}
}
| UTF-8 | Java | 1,721 | java | XmlBuilder.java | Java | []
| null | []
| package com.zjh.designpatterns.builder.concrete;
import java.util.Collection;
import java.util.Map;
public class XmlBuilder implements Builder {
StringBuffer buf = new StringBuffer();
@Override
public void builderHeader(ExportHeaderModel ehm) {
buf.append("<?xml version=1.0 encoding='gb2312'?>\n");
buf.append("<Report>\n");
buf.append(" <Header>\n");
buf.append(" <DepId>" + ehm.getDepId() + "</DepId>\n");
buf.append(" <ExportData>" + ehm.getExportDate() + "</ExportData>\n");
buf.append(" </Header>\n");
}
@Override
public void builderData(Map<String, Collection<ExportDataModel>> mapData) {
buf.append(" <Body>\n");
for (String tbName : mapData.keySet()) {
buf.append(" <Datas TableName=\"" + tbName + "\">\n");
for (ExportDataModel edm : mapData.get(tbName)) {
buf.append(" <Data>\n");
buf.append(" <ProductId>" + edm.getProductId() + "</ProductId>\n");
buf.append(" <Price>" + edm.getPrice() + "</Price>\n");
buf.append(" <Amount>" + edm.getAmount() + "</Amount>\n");
buf.append(" </Data>\n");
}
buf.append(" </Datas>\n");
}
buf.append(" </Body>\n");
}
@Override
public void builderFooter(ExportFooterModel efm) {
buf.append(" <Footer>\n");
buf.append(" <ExportUser>" + efm.getExportUser() + "</ExportUser>\n");
buf.append(" </Footer>\n");
buf.append("</Report>\n");
}
@Override
public void printFormatData() {
System.out.println("输出Xml文件的内容:\n" + buf);
}
}
| 1,721 | 0.536657 | 0.533138 | 48 | 34.520832 | 26.016012 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.520833 | false | false | 14 |
d9cc8c625dbac0ccb61c5dec9354e9e905657061 | 21,191,368,703,769 | 136023557ded02fc59bc4b871b4c5f273b6cdf7a | /MessageCore1/src/test/java/ltj/message/task/OpenBoTest.java | 2e65b93e31d69f132200b8796bb57dfdb286a41f | []
| no_license | jack4226/message-core | https://github.com/jack4226/message-core | b81a09ae075aef8c34c32c835b2f2e3a744e9504 | ba01ded75fb883d0d9fccc50057ac136eb27102a | refs/heads/master | 2021-12-28T07:13:04.003000 | 2021-12-13T22:45:25 | 2021-12-13T22:45:25 | 35,954,651 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ltj.message.task;
import static org.junit.Assert.assertEquals;
import java.util.Date;
import java.util.Random;
import javax.annotation.Resource;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import ltj.message.bean.MessageBean;
import ltj.message.bo.task.TaskBaseBo;
import ltj.message.bo.test.BoTestBase;
import ltj.message.constant.StatusId;
import ltj.message.dao.inbox.MsgInboxDao;
import ltj.message.vo.inbox.MsgInboxVo;
public class OpenBoTest extends BoTestBase {
@Resource
private TaskBaseBo openBo;
@Resource
private MsgInboxDao inboxDao;
@Test
public void close() throws Exception {
MessageBean mBean = new MessageBean();
String digits = StringUtils.leftPad("" + new Random().nextInt(100), 2, "0");
String fromaddr = "user" + digits + "@localhost";
String toaddr = "watched_maibox@domain.com";
try {
mBean.setFrom(InternetAddress.parse(fromaddr, false));
mBean.setTo(InternetAddress.parse(toaddr, false));
}
catch (AddressException e) {
logger.error("AddressException caught", e);
}
mBean.setSubject("A Exception occured");
mBean.setValue(new Date()+ " Test body message.");
mBean.setMailboxUser("testUser");
MsgInboxVo minbox = inboxDao.getRandomRecord();
if (StatusId.OPENED.value().equals(minbox.getStatusId())) {
minbox.setStatusId(StatusId.CLOSED.value());
inboxDao.update(minbox);
}
mBean.setMsgId(minbox.getMsgId());
if (isDebugEnabled) {
logger.debug("MessageBean created:" + LF + mBean);
}
openBo.process(mBean);
// verify results
MsgInboxVo minbox2 = inboxDao.getByPrimaryKey(mBean.getMsgId());
assertEquals(StatusId.OPENED.value(), minbox2.getStatusId());
}
}
| UTF-8 | Java | 1,845 | java | OpenBoTest.java | Java | [
{
"context": "ser\" + digits + \"@localhost\";\r\n\t\tString toaddr = \"watched_maibox@domain.com\";\r\n\t\ttry {\r\n\t\t\tmBean.setFrom(InternetAddress.pars",
"end": 976,
"score": 0.9994378089904785,
"start": 951,
"tag": "EMAIL",
"value": "watched_maibox@domain.com"
},
{
"context": " \" Test body message.\");\r\n\t\tmBean.setMailboxUser(\"testUser\");\r\n\t\tMsgInboxVo minbox = inboxDao.getRandomRecor",
"end": 1323,
"score": 0.9995795488357544,
"start": 1315,
"tag": "USERNAME",
"value": "testUser"
}
]
| null | []
| package ltj.message.task;
import static org.junit.Assert.assertEquals;
import java.util.Date;
import java.util.Random;
import javax.annotation.Resource;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import ltj.message.bean.MessageBean;
import ltj.message.bo.task.TaskBaseBo;
import ltj.message.bo.test.BoTestBase;
import ltj.message.constant.StatusId;
import ltj.message.dao.inbox.MsgInboxDao;
import ltj.message.vo.inbox.MsgInboxVo;
public class OpenBoTest extends BoTestBase {
@Resource
private TaskBaseBo openBo;
@Resource
private MsgInboxDao inboxDao;
@Test
public void close() throws Exception {
MessageBean mBean = new MessageBean();
String digits = StringUtils.leftPad("" + new Random().nextInt(100), 2, "0");
String fromaddr = "user" + digits + "@localhost";
String toaddr = "<EMAIL>";
try {
mBean.setFrom(InternetAddress.parse(fromaddr, false));
mBean.setTo(InternetAddress.parse(toaddr, false));
}
catch (AddressException e) {
logger.error("AddressException caught", e);
}
mBean.setSubject("A Exception occured");
mBean.setValue(new Date()+ " Test body message.");
mBean.setMailboxUser("testUser");
MsgInboxVo minbox = inboxDao.getRandomRecord();
if (StatusId.OPENED.value().equals(minbox.getStatusId())) {
minbox.setStatusId(StatusId.CLOSED.value());
inboxDao.update(minbox);
}
mBean.setMsgId(minbox.getMsgId());
if (isDebugEnabled) {
logger.debug("MessageBean created:" + LF + mBean);
}
openBo.process(mBean);
// verify results
MsgInboxVo minbox2 = inboxDao.getByPrimaryKey(mBean.getMsgId());
assertEquals(StatusId.OPENED.value(), minbox2.getStatusId());
}
}
| 1,827 | 0.720325 | 0.715989 | 62 | 27.758064 | 21.038893 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.822581 | false | false | 14 |
ef802006f1f0c45947bec2b98b202f51a85d22a6 | 21,483,426,442,669 | 6cb1bb259cbe62abf1abc62f2b5d47633d8ae72c | /design_pattern/src/desingPatterns/AbstractFactory/Factory.java | dcb0b4e9ecaeb03b42e05747258f9ad790b28a7d | []
| no_license | HoodyH/POO-Uni | https://github.com/HoodyH/POO-Uni | e953dbce438c0c54ded84926692a89f7a295c16c | 84d8d9ab47f592cc24c41943467972e53db6e198 | refs/heads/master | 2023-04-05T20:32:15.489000 | 2021-04-17T17:14:19 | 2021-04-17T17:14:19 | 192,770,951 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package desingPatterns.AbstractFactory;
import java.util.Objects;
public class Factory {
Color color;
Animal animal;
public Factory(String animal, String color){
Objects.requireNonNull(animal);
Objects.requireNonNull(color);
this.animal = new AnimalFactory().createAnimal(animal);
this.color = new ColorFactory().createColor(color);
}
}
| UTF-8 | Java | 392 | java | Factory.java | Java | []
| null | []
| package desingPatterns.AbstractFactory;
import java.util.Objects;
public class Factory {
Color color;
Animal animal;
public Factory(String animal, String color){
Objects.requireNonNull(animal);
Objects.requireNonNull(color);
this.animal = new AnimalFactory().createAnimal(animal);
this.color = new ColorFactory().createColor(color);
}
}
| 392 | 0.688776 | 0.688776 | 19 | 19.631578 | 21.315205 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.473684 | false | false | 14 |
67e302b5f044ee02cd26f5a755489f354e80777e | 32,195,074,918,608 | afbfec917806147e5d9b021f23c8f51ce371c764 | /src/com/esm/service/IncomeService.java | d3c9bf3417b8712e5a8bd574b600373ad7abf319 | []
| no_license | NINGYECHUN/abby | https://github.com/NINGYECHUN/abby | db56d187fd870cfdedccd26f843c67c0d3165656 | 2762fc9ada4e9824cdfc773baf9d5f727be85339 | refs/heads/master | 2021-07-22T15:46:10.769000 | 2017-11-07T14:42:11 | 2017-11-07T14:42:11 | 104,996,145 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.esm.service;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import com.esm.model.Income;
import com.esm.util.ListView;
import com.esm.util.PageInfo;
public interface IncomeService{
/**
* 分页查询所有订单数据.
* @param condition
* @return
*/
public ListView<HashMap<String,Object>> queryByGroup(Map<String,Object> condition, PageInfo pageInfo);
/**
* 计算佣金.
* @param mediaName
* @param commissionAmount
* @return
* @throws Exception
*/
JSONObject doCal(String mediaName, Double commissionAmount, String seqExcel, String status) throws Exception;
/**
* 扣除可结算金额.
* @param userId
* @param amount
* @throws Exception
*/
void doDeal(Long userId, Double amount) throws Exception;
}
| UTF-8 | Java | 841 | java | IncomeService.java | Java | []
| null | []
| package com.esm.service;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import com.esm.model.Income;
import com.esm.util.ListView;
import com.esm.util.PageInfo;
public interface IncomeService{
/**
* 分页查询所有订单数据.
* @param condition
* @return
*/
public ListView<HashMap<String,Object>> queryByGroup(Map<String,Object> condition, PageInfo pageInfo);
/**
* 计算佣金.
* @param mediaName
* @param commissionAmount
* @return
* @throws Exception
*/
JSONObject doCal(String mediaName, Double commissionAmount, String seqExcel, String status) throws Exception;
/**
* 扣除可结算金额.
* @param userId
* @param amount
* @throws Exception
*/
void doDeal(Long userId, Double amount) throws Exception;
}
| 841 | 0.68836 | 0.68836 | 36 | 21.194445 | 24.694601 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.694444 | false | false | 14 |
00c35e2568db1dc28f6165875d55dcd5b3590216 | 18,743,237,322,784 | aa6d41aa15b86d7e743531dc64f0b8eec09bdca1 | /Ori/src/main/java/com/origami/activity/adapter/SelectPlaceAdapter.java | c357740451f612f006b4528ff767a86296ba45f0 | []
| no_license | origa-byx/origami | https://github.com/origa-byx/origami | 6e196e6395025ca4364382f677e52f4fe5c1dcda | 6297075bfc5408fced7fe723acb846d43918e62e | refs/heads/master | 2022-11-06T19:21:37.272000 | 2022-05-25T07:00:47 | 2022-05-25T07:00:47 | 271,731,284 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.origami.activity.adapter;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.origami.activity.OriImageSelect;
import com.origami.origami.R;
import java.util.List;
/**
* @by: origami
* @date: {2021-08-06}
* @info:
**/
public class SelectPlaceAdapter extends RecyclerView.Adapter<SelectPlaceAdapter.ViewHolder> {
public static class AdapterData{
public String text;
public String image;
public int num;
}
final OriImageSelect context;
final List<AdapterData> dates;
public SelectPlaceAdapter(OriImageSelect context, List<AdapterData> dates) {
this.context = context;
this.dates = dates;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout._adapter_ori_select_place, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
context.closeSelect();
int position = viewHolder.getAdapterPosition();
context.refreshBySelect(dates.get(position).text, viewHolder.textView.getText().toString());
}
});
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
AdapterData adapterData = dates.get(position);
Glide.with(context).load(adapterData.image).into(holder.imageView);
String name;
if(TextUtils.isEmpty(adapterData.text)){
name = "最近图片";
}else if(adapterData.text.equalsIgnoreCase("Screenshots")){
name = "屏幕截图";
}else if(adapterData.text.equalsIgnoreCase("Camera")){
name = "相机";
}else if(adapterData.text.equalsIgnoreCase("QQ_Images")){
name = "QQ图片";
}else if(adapterData.text.equalsIgnoreCase("WeiXin")){
name = "微信图片";
}else {
name = adapterData.text;
}
holder.numView.setText(String.format("(%s)", adapterData.num));
holder.textView.setText(name);
}
@Override
public int getItemCount() {
return dates.size();
}
static class ViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
TextView textView, numView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.__ori_show_image);
textView = itemView.findViewById(R.id.__ori_show_text);
numView = itemView.findViewById(R.id.__ori_show_num);
}
}
}
| UTF-8 | Java | 3,164 | java | SelectPlaceAdapter.java | Java | [
{
"context": "mi.origami.R;\n\nimport java.util.List;\n\n/**\n * @by: origami\n * @date: {2021-08-06}\n * @info:\n **/\npublic clas",
"end": 574,
"score": 0.9996384382247925,
"start": 567,
"tag": "USERNAME",
"value": "origami"
}
]
| null | []
| package com.origami.activity.adapter;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.origami.activity.OriImageSelect;
import com.origami.origami.R;
import java.util.List;
/**
* @by: origami
* @date: {2021-08-06}
* @info:
**/
public class SelectPlaceAdapter extends RecyclerView.Adapter<SelectPlaceAdapter.ViewHolder> {
public static class AdapterData{
public String text;
public String image;
public int num;
}
final OriImageSelect context;
final List<AdapterData> dates;
public SelectPlaceAdapter(OriImageSelect context, List<AdapterData> dates) {
this.context = context;
this.dates = dates;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout._adapter_ori_select_place, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
context.closeSelect();
int position = viewHolder.getAdapterPosition();
context.refreshBySelect(dates.get(position).text, viewHolder.textView.getText().toString());
}
});
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
AdapterData adapterData = dates.get(position);
Glide.with(context).load(adapterData.image).into(holder.imageView);
String name;
if(TextUtils.isEmpty(adapterData.text)){
name = "最近图片";
}else if(adapterData.text.equalsIgnoreCase("Screenshots")){
name = "屏幕截图";
}else if(adapterData.text.equalsIgnoreCase("Camera")){
name = "相机";
}else if(adapterData.text.equalsIgnoreCase("QQ_Images")){
name = "QQ图片";
}else if(adapterData.text.equalsIgnoreCase("WeiXin")){
name = "微信图片";
}else {
name = adapterData.text;
}
holder.numView.setText(String.format("(%s)", adapterData.num));
holder.textView.setText(name);
}
@Override
public int getItemCount() {
return dates.size();
}
static class ViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
TextView textView, numView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.__ori_show_image);
textView = itemView.findViewById(R.id.__ori_show_text);
numView = itemView.findViewById(R.id.__ori_show_num);
}
}
}
| 3,164 | 0.659207 | 0.65665 | 98 | 30.918367 | 26.28093 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 14 |
585454606d32455fbe5da648a3a1027f29b5021a | 11,742,440,603,157 | 572ad5ec61e5b1bdc3174f21db7c70fa5fa527a9 | /code/icss-compiler/src/main/java/nl/han/ica/datastructures/HANLinkedList.java | 3771ab876280c87bada9038ac2d175bdeb2e7a05 | []
| no_license | jelmervanvugt/antlr-css-compiler | https://github.com/jelmervanvugt/antlr-css-compiler | 1764911a2a40df0d06752b1ac04572d28709dbf3 | e6399b581e71cf0fe5d97857093247fa216409f7 | refs/heads/main | 2022-12-30T03:10:25.922000 | 2020-10-16T14:53:51 | 2020-10-16T14:53:51 | 301,795,742 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package nl.han.ica.datastructures;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class HANLinkedList<T> implements IHANLinkedList<T> {
private Node<T> head;
private Node<T> tail;
private int size = 0;
@Override
public void addFirst(T value) {
add(value, true);
}
public void addLast(T value) {
add(value, false);
}
private void add(T value, boolean first) {
Node<T> node = new Node<>(value);
if (head == null) {
head = node;
tail = node;
} else {
if (first) {
node.setNext(head);
head = node;
} else {
tail.setNext(node);
tail = node;
}
}
size++;
}
@Override
public void clear() {
head = tail = null;
size = 0;
}
public boolean isEmpty() {
return head == null;
}
@Override
public void insert(int pos, T value) {
if (pos == 0) {
addFirst(value);
return;
} else if (pos == size - 1) {
addLast(value);
return;
}
OwnGenericLinkedListIterator iterator = new OwnGenericLinkedListIterator();
int index = 0;
Node<T> nToAdd = new Node<>(value);
Node<T> nBefore = null;
Node<T> nAfter = null;
while (index <= pos) {
if (index == pos - 1) {
nBefore = iterator.current;
} else if (index == pos) {
nAfter = iterator.current;
}
if (iterator.hasNext()) {
iterator.next();
} else {
throw new ArrayIndexOutOfBoundsException();
}
index++;
}
if (nBefore == null) throw new ArrayIndexOutOfBoundsException();
nBefore.setNext(nToAdd);
nToAdd.setNext(nAfter);
size++;
}
@Override
public void delete(int pos) {
if (pos == 0) {
removeFirst();
return;
}
OwnGenericLinkedListIterator iterator = new OwnGenericLinkedListIterator();
int index = 0;
Node<T> nBefore = iterator.current;
Node<T> nToRemove = null;
Node<T> nAfter = null;
while (index < pos) {
index++;
if (iterator.hasNext()) iterator.next();
else {
throw new ArrayIndexOutOfBoundsException();
}
if (index == pos - 1) {
nBefore = iterator.current;
} else if (index == pos) {
nToRemove = iterator.current;
}
}
if (iterator.hasNext()) nAfter = iterator.current.getNext();
if (nBefore == null || nToRemove == null) {
throw new ArrayIndexOutOfBoundsException();
}
if (nAfter == null) {
tail = nBefore;
tail.setNext(null);
} else {
nToRemove.setNext(null);
nBefore.setNext(nAfter);
}
size--;
}
@Override
public T get(int pos) {
OwnGenericLinkedListIterator iterator = new OwnGenericLinkedListIterator();
T value = head.getValue();
int i = 0;
while (i < pos) {
if (iterator.hasNext()) {
value = iterator.next();
} else {
throw new ArrayIndexOutOfBoundsException();
}
i++;
}
return value;
}
@Override
public void removeFirst() {
if (head != null && head.getNext() != null) {
head = head.getNext();
} else if (head != null && head.getNext() == null) {
head = null;
} else {
throw new ArrayIndexOutOfBoundsException();
}
size--;
}
@Override
public T getFirst() {
return head.getValue();
}
@Override
public int getSize() {
return size;
}
@Override
public Iterator<T> iterator() {
return new OwnGenericLinkedListIterator();
}
class OwnGenericLinkedListIterator implements Iterator<T> {
Node<T> current = head;
@Override
public boolean hasNext() {
if (current == null) {
return false;
} else {
return current.getNext() != null;
}
}
@Override
public T next() {
if (current == null || current.getNext() == null) {
throw new NoSuchElementException();
}
current = current.getNext();
return current.getValue();
}
}
}
| UTF-8 | Java | 4,724 | java | HANLinkedList.java | Java | []
| null | []
| package nl.han.ica.datastructures;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class HANLinkedList<T> implements IHANLinkedList<T> {
private Node<T> head;
private Node<T> tail;
private int size = 0;
@Override
public void addFirst(T value) {
add(value, true);
}
public void addLast(T value) {
add(value, false);
}
private void add(T value, boolean first) {
Node<T> node = new Node<>(value);
if (head == null) {
head = node;
tail = node;
} else {
if (first) {
node.setNext(head);
head = node;
} else {
tail.setNext(node);
tail = node;
}
}
size++;
}
@Override
public void clear() {
head = tail = null;
size = 0;
}
public boolean isEmpty() {
return head == null;
}
@Override
public void insert(int pos, T value) {
if (pos == 0) {
addFirst(value);
return;
} else if (pos == size - 1) {
addLast(value);
return;
}
OwnGenericLinkedListIterator iterator = new OwnGenericLinkedListIterator();
int index = 0;
Node<T> nToAdd = new Node<>(value);
Node<T> nBefore = null;
Node<T> nAfter = null;
while (index <= pos) {
if (index == pos - 1) {
nBefore = iterator.current;
} else if (index == pos) {
nAfter = iterator.current;
}
if (iterator.hasNext()) {
iterator.next();
} else {
throw new ArrayIndexOutOfBoundsException();
}
index++;
}
if (nBefore == null) throw new ArrayIndexOutOfBoundsException();
nBefore.setNext(nToAdd);
nToAdd.setNext(nAfter);
size++;
}
@Override
public void delete(int pos) {
if (pos == 0) {
removeFirst();
return;
}
OwnGenericLinkedListIterator iterator = new OwnGenericLinkedListIterator();
int index = 0;
Node<T> nBefore = iterator.current;
Node<T> nToRemove = null;
Node<T> nAfter = null;
while (index < pos) {
index++;
if (iterator.hasNext()) iterator.next();
else {
throw new ArrayIndexOutOfBoundsException();
}
if (index == pos - 1) {
nBefore = iterator.current;
} else if (index == pos) {
nToRemove = iterator.current;
}
}
if (iterator.hasNext()) nAfter = iterator.current.getNext();
if (nBefore == null || nToRemove == null) {
throw new ArrayIndexOutOfBoundsException();
}
if (nAfter == null) {
tail = nBefore;
tail.setNext(null);
} else {
nToRemove.setNext(null);
nBefore.setNext(nAfter);
}
size--;
}
@Override
public T get(int pos) {
OwnGenericLinkedListIterator iterator = new OwnGenericLinkedListIterator();
T value = head.getValue();
int i = 0;
while (i < pos) {
if (iterator.hasNext()) {
value = iterator.next();
} else {
throw new ArrayIndexOutOfBoundsException();
}
i++;
}
return value;
}
@Override
public void removeFirst() {
if (head != null && head.getNext() != null) {
head = head.getNext();
} else if (head != null && head.getNext() == null) {
head = null;
} else {
throw new ArrayIndexOutOfBoundsException();
}
size--;
}
@Override
public T getFirst() {
return head.getValue();
}
@Override
public int getSize() {
return size;
}
@Override
public Iterator<T> iterator() {
return new OwnGenericLinkedListIterator();
}
class OwnGenericLinkedListIterator implements Iterator<T> {
Node<T> current = head;
@Override
public boolean hasNext() {
if (current == null) {
return false;
} else {
return current.getNext() != null;
}
}
@Override
public T next() {
if (current == null || current.getNext() == null) {
throw new NoSuchElementException();
}
current = current.getNext();
return current.getValue();
}
}
}
| 4,724 | 0.481795 | 0.479678 | 202 | 22.386139 | 18.633766 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.415842 | false | false | 14 |
2381e070895778c4e1b1f1b3affdb8bc1cb25ad4 | 14,534,169,343,918 | 1e969cd6450aa2a181272abc7cd6b1ed392f3e7a | /src/main/java/mx/com/odraudek99/simple/MainAspectos.java | dd59044ff3019df2b307fb60bc4321d963483092 | []
| no_license | odraudek99/java-spring-aspects | https://github.com/odraudek99/java-spring-aspects | 006ae135527e318a829e96f703d04f16efaf4145 | f5c2a16f702fbe804ae15dfe2a6ccae619c6bf29 | refs/heads/master | 2020-07-11T06:57:27.817000 | 2016-11-17T07:54:52 | 2016-11-17T07:54:52 | 74,003,471 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mx.com.odraudek99.simple;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import mx.com.odraudek99.simple.neg.NegocioImpl;
public class MainAspectos {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/spring.xml");
NegocioImpl negocioImpl = (NegocioImpl) context.getBean(NegocioImpl.class);
negocioImpl.preAspectoMetodo();
System.out.println("-----------");
negocioImpl.postAspectoMetodo();
System.out.println("-----------");
negocioImpl.prePostAspectoMetodo();
System.out.println("-----------");
negocioImpl.metodoLog("Hola");
}
}
| UTF-8 | Java | 750 | java | MainAspectos.java | Java | []
| null | []
| package mx.com.odraudek99.simple;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import mx.com.odraudek99.simple.neg.NegocioImpl;
public class MainAspectos {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/spring.xml");
NegocioImpl negocioImpl = (NegocioImpl) context.getBean(NegocioImpl.class);
negocioImpl.preAspectoMetodo();
System.out.println("-----------");
negocioImpl.postAspectoMetodo();
System.out.println("-----------");
negocioImpl.prePostAspectoMetodo();
System.out.println("-----------");
negocioImpl.metodoLog("Hola");
}
}
| 750 | 0.714667 | 0.709333 | 28 | 24.785715 | 26.550972 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.25 | false | false | 14 |
210964c3286497d020a42a902ed2ccf8de2c1507 | 10,204,842,295,880 | a76e510183c21e9e53cd156e68aa96a4519ae359 | /CA_08_mzFoodDelivery/server/CA_08_mzFoodDelivery/src/main/java/ir/ac/ut/ie/CA_08_mzFoodDelivery/domain/MzFoodDelivery/User/UserManager.java | 2a0766c3e8cf0ca8e8d74c1f956c85d6f74cc56e | []
| no_license | zhpinkman/Internet_Engineering_Course | https://github.com/zhpinkman/Internet_Engineering_Course | b7f43dda5f8327869df9ae712f4fe418aa6e21e4 | 3bed95d32fb641337e59a063e30364091cd7f84c | refs/heads/master | 2023-03-17T22:28:02.825000 | 2022-05-20T22:34:09 | 2022-05-20T22:34:09 | 241,857,854 | 0 | 1 | null | false | 2023-03-08T00:56:49 | 2020-02-20T10:38:43 | 2022-05-20T22:29:28 | 2023-03-08T00:56:49 | 21,250 | 0 | 0 | 61 | Java | false | false | package ir.ac.ut.ie.CA_08_mzFoodDelivery.domain.MzFoodDelivery.User;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import ir.ac.ut.ie.CA_08_mzFoodDelivery.domain.MzFoodDelivery.Delivery.Order;
import ir.ac.ut.ie.CA_08_mzFoodDelivery.domain.MzFoodDelivery.Restaurant.Food;
import ir.ac.ut.ie.CA_08_mzFoodDelivery.domain.MzFoodDelivery.Restaurant.Location;
import ir.ac.ut.ie.CA_08_mzFoodDelivery.repository.MzRepository;
import org.springframework.security.core.context.SecurityContextHolder;
import java.sql.SQLException;
import java.util.List;
public class UserManager {
public UserManager() {
// System.out.println("mohsen here");
// User user = new User("Ehsan", "Khames", "ekhamespanah@yahoo.com", "1234","989123456789", new Location(0, 0), 0, 0);
// try {
// MzRepository.getInstance().insertUser(user);
//// System.out.println("zhivar here");
// } catch (SQLException ignored) {}
}
public void addToCart(CartItem cartItem) throws Exception {
User user = MzRepository.getInstance().getUser(SecurityContextHolder.getContext().getAuthentication().getName());
user.addToCart(cartItem);
}
public Location getLocation(String email) throws SQLException{
return MzRepository.getInstance().getUser(email).getLocation();
}
public List<CartItem> getCart() throws SQLException {
User user = MzRepository.getInstance().getUser(SecurityContextHolder.getContext().getAuthentication().getName());
return user.getUserCart();
}
public List<CartItem> getAllCarts() throws SQLException {
return MzRepository.getInstance().getAllCarts();
}
public String getBriefCartJson() throws SQLException {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement cartJsonElement = gson.toJsonTree(this.getCart());
JsonArray array = cartJsonElement.getAsJsonObject().get("cartItems").getAsJsonArray();
array.forEach(item -> {
item.getAsJsonObject().addProperty("foodName", item.getAsJsonObject().get("food").getAsJsonObject().get("name").getAsString());
item.getAsJsonObject().remove("food");
item.getAsJsonObject().remove("restaurant");
});
return gson.toJson(cartJsonElement);
}
public List<CartItem> finalizeOrder() throws Exception {
User user = MzRepository.getInstance().getUser(SecurityContextHolder.getContext().getAuthentication().getName());
double totalPrice = user.getCartTotalPrice();
if (user.getUserCartSize() == 0)
throw new Exception("user cart is empty");
if (totalPrice > user.getCredit())
throw new Exception("credit is not enough for finalizing your order");
if (foodRepoEmpty(user.getUserCart()))
throw new Exception("count of this offer is not enough for you to submit");
user.withdrawCredit(totalPrice);
return user.finalizeOrder();
}
public boolean foodRepoEmpty(List<CartItem> cartItems) throws SQLException {
for (CartItem cartItem : cartItems) {
Food food = MzRepository.getInstance().getFood(cartItem.getRestaurantId(), cartItem.getFoodName());
if (!food.hasEnoughAmount(cartItem.getQuantity()))
return true;
}
return false;
}
public int getUserCartSize() throws SQLException {
User user = MzRepository.getInstance().getUser(SecurityContextHolder.getContext().getAuthentication().getName());
return user.getUserCartSize();
}
public User getUser(String email) throws SQLException{
return MzRepository.getInstance().getUser(email);
}
public void chargeUserCredit(double amount) throws Exception {
User user = MzRepository.getInstance().getUser(SecurityContextHolder.getContext().getAuthentication().getName());
user.chargeUserCredit(amount);
}
public void deleteFromCart(String restaurantId, String foodName) throws Exception {
User user = MzRepository.getInstance().getUser(SecurityContextHolder.getContext().getAuthentication().getName());
user.deleteFromCart(restaurantId, foodName);
}
public Order getLatestOrder() throws SQLException {
List<Order> orders = MzRepository.getInstance().getAllOrders();
return orders.get(orders.size() - 1);
}
public List<Order> getOrders() throws SQLException {
return MzRepository.getInstance().getOrders(SecurityContextHolder.getContext().getAuthentication().getName());
}
public void addUser(String email, String firstName, String lastName, String password) throws Exception {
try {
User user = new User(firstName, lastName, email, password, "", new Location(0, 0), 0, 0);
MzRepository.getInstance().insertUser(user);
} catch (SQLException e) {
throw new Exception("email is already taken");
}
}
public User loginUser(String email, String password) throws Exception {
try {
User user = MzRepository.getInstance().getUser(email);
if (user.getPassword().equals(password))
return user;
else throw new Exception("passwords does not match");
} catch (SQLException e) {
throw new Exception("user not available");
}
}
}
| UTF-8 | Java | 5,471 | java | UserManager.java | Java | [
{
"context": "n(\"mohsen here\");\n// User user = new User(\"Ehsan\", \"Khames\", \"ekhamespanah@yahoo.com\", \"1234\",\"989",
"end": 776,
"score": 0.9989364147186279,
"start": 771,
"tag": "NAME",
"value": "Ehsan"
},
{
"context": " here\");\n// User user = new User(\"Ehsan\", \"Khames\", \"ekhamespanah@yahoo.com\", \"1234\",\"989123456789\"",
"end": 786,
"score": 0.9998060464859009,
"start": 780,
"tag": "NAME",
"value": "Khames"
},
{
"context": "/ User user = new User(\"Ehsan\", \"Khames\", \"ekhamespanah@yahoo.com\", \"1234\",\"989123456789\", new Location(0, 0), 0, 0",
"end": 812,
"score": 0.9999293088912964,
"start": 790,
"tag": "EMAIL",
"value": "ekhamespanah@yahoo.com"
},
{
"context": " }\n\n public void addUser(String email, String firstName, String lastName, String password) throws Excepti",
"end": 4719,
"score": 0.8311686515808105,
"start": 4710,
"tag": "NAME",
"value": "firstName"
},
{
"context": "oid addUser(String email, String firstName, String lastName, String password) throws Exception {\n try ",
"end": 4736,
"score": 0.8294626474380493,
"start": 4728,
"tag": "NAME",
"value": "lastName"
},
{
"context": " {\n try {\n User user = new User(firstName, lastName, email, password, \"\", new Location(0, 0",
"end": 4830,
"score": 0.7550301551818848,
"start": 4821,
"tag": "NAME",
"value": "firstName"
}
]
| null | []
| package ir.ac.ut.ie.CA_08_mzFoodDelivery.domain.MzFoodDelivery.User;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import ir.ac.ut.ie.CA_08_mzFoodDelivery.domain.MzFoodDelivery.Delivery.Order;
import ir.ac.ut.ie.CA_08_mzFoodDelivery.domain.MzFoodDelivery.Restaurant.Food;
import ir.ac.ut.ie.CA_08_mzFoodDelivery.domain.MzFoodDelivery.Restaurant.Location;
import ir.ac.ut.ie.CA_08_mzFoodDelivery.repository.MzRepository;
import org.springframework.security.core.context.SecurityContextHolder;
import java.sql.SQLException;
import java.util.List;
public class UserManager {
public UserManager() {
// System.out.println("mohsen here");
// User user = new User("Ehsan", "Khames", "<EMAIL>", "1234","989123456789", new Location(0, 0), 0, 0);
// try {
// MzRepository.getInstance().insertUser(user);
//// System.out.println("zhivar here");
// } catch (SQLException ignored) {}
}
public void addToCart(CartItem cartItem) throws Exception {
User user = MzRepository.getInstance().getUser(SecurityContextHolder.getContext().getAuthentication().getName());
user.addToCart(cartItem);
}
public Location getLocation(String email) throws SQLException{
return MzRepository.getInstance().getUser(email).getLocation();
}
public List<CartItem> getCart() throws SQLException {
User user = MzRepository.getInstance().getUser(SecurityContextHolder.getContext().getAuthentication().getName());
return user.getUserCart();
}
public List<CartItem> getAllCarts() throws SQLException {
return MzRepository.getInstance().getAllCarts();
}
public String getBriefCartJson() throws SQLException {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement cartJsonElement = gson.toJsonTree(this.getCart());
JsonArray array = cartJsonElement.getAsJsonObject().get("cartItems").getAsJsonArray();
array.forEach(item -> {
item.getAsJsonObject().addProperty("foodName", item.getAsJsonObject().get("food").getAsJsonObject().get("name").getAsString());
item.getAsJsonObject().remove("food");
item.getAsJsonObject().remove("restaurant");
});
return gson.toJson(cartJsonElement);
}
public List<CartItem> finalizeOrder() throws Exception {
User user = MzRepository.getInstance().getUser(SecurityContextHolder.getContext().getAuthentication().getName());
double totalPrice = user.getCartTotalPrice();
if (user.getUserCartSize() == 0)
throw new Exception("user cart is empty");
if (totalPrice > user.getCredit())
throw new Exception("credit is not enough for finalizing your order");
if (foodRepoEmpty(user.getUserCart()))
throw new Exception("count of this offer is not enough for you to submit");
user.withdrawCredit(totalPrice);
return user.finalizeOrder();
}
public boolean foodRepoEmpty(List<CartItem> cartItems) throws SQLException {
for (CartItem cartItem : cartItems) {
Food food = MzRepository.getInstance().getFood(cartItem.getRestaurantId(), cartItem.getFoodName());
if (!food.hasEnoughAmount(cartItem.getQuantity()))
return true;
}
return false;
}
public int getUserCartSize() throws SQLException {
User user = MzRepository.getInstance().getUser(SecurityContextHolder.getContext().getAuthentication().getName());
return user.getUserCartSize();
}
public User getUser(String email) throws SQLException{
return MzRepository.getInstance().getUser(email);
}
public void chargeUserCredit(double amount) throws Exception {
User user = MzRepository.getInstance().getUser(SecurityContextHolder.getContext().getAuthentication().getName());
user.chargeUserCredit(amount);
}
public void deleteFromCart(String restaurantId, String foodName) throws Exception {
User user = MzRepository.getInstance().getUser(SecurityContextHolder.getContext().getAuthentication().getName());
user.deleteFromCart(restaurantId, foodName);
}
public Order getLatestOrder() throws SQLException {
List<Order> orders = MzRepository.getInstance().getAllOrders();
return orders.get(orders.size() - 1);
}
public List<Order> getOrders() throws SQLException {
return MzRepository.getInstance().getOrders(SecurityContextHolder.getContext().getAuthentication().getName());
}
public void addUser(String email, String firstName, String lastName, String password) throws Exception {
try {
User user = new User(firstName, lastName, email, password, "", new Location(0, 0), 0, 0);
MzRepository.getInstance().insertUser(user);
} catch (SQLException e) {
throw new Exception("email is already taken");
}
}
public User loginUser(String email, String password) throws Exception {
try {
User user = MzRepository.getInstance().getUser(email);
if (user.getPassword().equals(password))
return user;
else throw new Exception("passwords does not match");
} catch (SQLException e) {
throw new Exception("user not available");
}
}
}
| 5,456 | 0.682508 | 0.675928 | 128 | 41.742188 | 36.375912 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.632813 | false | false | 14 |
40c9e23bf357c8af3796bb06382d36d8f2140f1e | 8,478,265,471,940 | ba3fc2027cb486a43dfb1a871b774c7d55be5e0d | /DBExample1.java | 80fb0c0ed212442911b974901e148832100db6bd | [
"MIT"
]
| permissive | stephensheridan/javamysqldemo | https://github.com/stephensheridan/javamysqldemo | bd675135d9466ca25c7171be68c002386e785dbf | 3bf5f7ea10577ebb8c4f53262f7e7953b81d1b0a | refs/heads/master | 2021-01-10T03:27:27.306000 | 2016-04-05T16:09:26 | 2016-04-05T16:09:26 | 55,500,897 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DBExample1 {
public static Connection conn;
// This methods wraps up all the code for making a database connection
public static void getDBConnection(){
try{
//Register the Driver
Class.forName("com.mysql.jdbc.Driver");
//Get a connection to the database
conn = DriverManager.getConnection("jdbc:mysql://localhost:8889/employee","root", "root");
print("Database connection successful.");
printNewline();
}
catch(Exception e){
// something went wrong with DB connection
print("Database Connection Error!");
printNewline();
e.printStackTrace();
}
}
// This method wraps up all the code for closing a database connection
public static void closeDBConnection(){
if (conn != null){
try{
conn.close();
print("Database closed successfully.");
printNewline();
}
catch(Exception e){
print("Error closing the DB");
}
}
}
// Execute a select statement to return all the employee information
public static void listEmployees(){
try{
// Create a statement object
Statement stmt = conn.createStatement();
//Execute a Query
String query = "SELECT * FROM emp";
print("[SQL QUERY] " + query);
ResultSet rs = stmt.executeQuery(query);
//Process the results set
print("*** Employees ***");
while (rs.next()){
String sout = rs.getInt("empno") + "," + rs.getString("empname") + "," +
rs.getString("empdob") + "," + rs.getFloat("empsalary");
print(sout);
}
printNewline();
rs.close();
stmt.close();
}
catch(Exception e){
print("Error executing SELECT statemennt");
}
}
public static void updateEmpSalary(int empno, float amount){
try{
// Create a statement object
Statement stmt = conn.createStatement();
//Execute a Query
String query = "UPDATE emp SET empsalary=" + amount + " WHERE empno=" + empno + ";";
print("[SQL QUERY] " + query);
int result = stmt.executeUpdate(query);
stmt.close();
print("Employee successfully updated.");
printNewline();
}
catch(Exception e){
print("Error executing UPDATE statemennt");
}
}
public static void insertEmployee(String name, String DOB, float salary){
try{
// Create a statement object
Statement stmt = conn.createStatement();
//Execute a Query
// NOTE: empno is my primary key and it is set to auto-increment in my database schema
// so we only need to insert empname, empdob, empsalary and MYSQL will look after a new empno value for us.
String query = "INSERT INTO emp(empname,empdob,empsalary) VALUES (";
query = query + "'" + name + "'" + ",'" + DOB + "'," + salary + ");";
print("[SQL QUERY] " + query);
int result = stmt.executeUpdate(query);
stmt.close();
print("New employee successfully inserted.");
printNewline();
}
catch(Exception e){
print("Error executing INSERT statemennt");
e.printStackTrace();
}
}
public static void deleteEmployee(String empname){
try{
// Create a statement object
Statement stmt = conn.createStatement();
//Execute a Query
String query = "DELETE FROM emp WHERE empname ='" + empname + "';";
print("[SQL QUERY] " + query);
int result = stmt.executeUpdate(query);
stmt.close();
print("New employee successfully deleted.");
printNewline();
}
catch(Exception e){
print("Error executing INSERT statemennt");
e.printStackTrace();
}
}
public static void print(String s){System.out.println(s);}
public static void printNewline(){System.out.println("");}
public static void main(String[] args) {
// Make a MySql database connection
getDBConnection();
// List all employees from DB
listEmployees();
print("Give Employee No. 1 a new salary");
// Update the salary of employee no. 1
updateEmpSalary(1, 200000.65f);
// List all employees from DB
listEmployees();
// Insert a new employee
print("Inserting a new employee called Mark Maguire...");
insertEmployee("Mark Maguire", "1967-04-23", 45000f);
// List all employees from DB
listEmployees();
// Delete an employee by name (NOTE: should use empno and name to ensure correct employee)
print("Delete Mark Maguire...");
deleteEmployee("Mark Maguire");
// List all employees from DB
listEmployees();
// Tidy up
closeDBConnection();
}
}
| UTF-8 | Java | 4,466 | java | DBExample1.java | Java | [
{
"context": " employee\n\t\tprint(\"Inserting a new employee called Mark Maguire...\");\n\t\tinsertEmployee(\"Mark Maguire\", \"1967-04-2",
"end": 4079,
"score": 0.9998660087585449,
"start": 4067,
"tag": "NAME",
"value": "Mark Maguire"
},
{
"context": "loyee called Mark Maguire...\");\n\t\tinsertEmployee(\"Mark Maguire\", \"1967-04-23\", 45000f);\n\t\t\n\t\t// List all employe",
"end": 4116,
"score": 0.9998922944068909,
"start": 4104,
"tag": "NAME",
"value": "Mark Maguire"
},
{
"context": "d name to ensure correct employee)\n\t\tprint(\"Delete Mark Maguire...\");\n\t\tdeleteEmployee(\"Mark Maguire\");\n\t\t\n\t\t// L",
"end": 4320,
"score": 0.9996679425239563,
"start": 4308,
"tag": "NAME",
"value": "Mark Maguire"
},
{
"context": "rint(\"Delete Mark Maguire...\");\n\t\tdeleteEmployee(\"Mark Maguire\");\n\t\t\n\t\t// List all employees from DB\n\t\tlistEmplo",
"end": 4357,
"score": 0.9998795390129089,
"start": 4345,
"tag": "NAME",
"value": "Mark Maguire"
}
]
| null | []
| import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DBExample1 {
public static Connection conn;
// This methods wraps up all the code for making a database connection
public static void getDBConnection(){
try{
//Register the Driver
Class.forName("com.mysql.jdbc.Driver");
//Get a connection to the database
conn = DriverManager.getConnection("jdbc:mysql://localhost:8889/employee","root", "root");
print("Database connection successful.");
printNewline();
}
catch(Exception e){
// something went wrong with DB connection
print("Database Connection Error!");
printNewline();
e.printStackTrace();
}
}
// This method wraps up all the code for closing a database connection
public static void closeDBConnection(){
if (conn != null){
try{
conn.close();
print("Database closed successfully.");
printNewline();
}
catch(Exception e){
print("Error closing the DB");
}
}
}
// Execute a select statement to return all the employee information
public static void listEmployees(){
try{
// Create a statement object
Statement stmt = conn.createStatement();
//Execute a Query
String query = "SELECT * FROM emp";
print("[SQL QUERY] " + query);
ResultSet rs = stmt.executeQuery(query);
//Process the results set
print("*** Employees ***");
while (rs.next()){
String sout = rs.getInt("empno") + "," + rs.getString("empname") + "," +
rs.getString("empdob") + "," + rs.getFloat("empsalary");
print(sout);
}
printNewline();
rs.close();
stmt.close();
}
catch(Exception e){
print("Error executing SELECT statemennt");
}
}
public static void updateEmpSalary(int empno, float amount){
try{
// Create a statement object
Statement stmt = conn.createStatement();
//Execute a Query
String query = "UPDATE emp SET empsalary=" + amount + " WHERE empno=" + empno + ";";
print("[SQL QUERY] " + query);
int result = stmt.executeUpdate(query);
stmt.close();
print("Employee successfully updated.");
printNewline();
}
catch(Exception e){
print("Error executing UPDATE statemennt");
}
}
public static void insertEmployee(String name, String DOB, float salary){
try{
// Create a statement object
Statement stmt = conn.createStatement();
//Execute a Query
// NOTE: empno is my primary key and it is set to auto-increment in my database schema
// so we only need to insert empname, empdob, empsalary and MYSQL will look after a new empno value for us.
String query = "INSERT INTO emp(empname,empdob,empsalary) VALUES (";
query = query + "'" + name + "'" + ",'" + DOB + "'," + salary + ");";
print("[SQL QUERY] " + query);
int result = stmt.executeUpdate(query);
stmt.close();
print("New employee successfully inserted.");
printNewline();
}
catch(Exception e){
print("Error executing INSERT statemennt");
e.printStackTrace();
}
}
public static void deleteEmployee(String empname){
try{
// Create a statement object
Statement stmt = conn.createStatement();
//Execute a Query
String query = "DELETE FROM emp WHERE empname ='" + empname + "';";
print("[SQL QUERY] " + query);
int result = stmt.executeUpdate(query);
stmt.close();
print("New employee successfully deleted.");
printNewline();
}
catch(Exception e){
print("Error executing INSERT statemennt");
e.printStackTrace();
}
}
public static void print(String s){System.out.println(s);}
public static void printNewline(){System.out.println("");}
public static void main(String[] args) {
// Make a MySql database connection
getDBConnection();
// List all employees from DB
listEmployees();
print("Give Employee No. 1 a new salary");
// Update the salary of employee no. 1
updateEmpSalary(1, 200000.65f);
// List all employees from DB
listEmployees();
// Insert a new employee
print("Inserting a new employee called <NAME>...");
insertEmployee("<NAME>", "1967-04-23", 45000f);
// List all employees from DB
listEmployees();
// Delete an employee by name (NOTE: should use empno and name to ensure correct employee)
print("Delete <NAME>...");
deleteEmployee("<NAME>");
// List all employees from DB
listEmployees();
// Tidy up
closeDBConnection();
}
}
| 4,442 | 0.661218 | 0.654725 | 161 | 26.73913 | 23.26502 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.782609 | false | false | 14 |
def98d67b714b09a54e455e15b05a3ec8d15c8b1 | 7,267,084,692,628 | a227e287c59d5c4bbbcd7cb901343730082e0da5 | /WeakMC-Lobby/src/de/Cypix/Lobby/inventar/InventarManager.java | 7d7a097bac26ed5dea4ef12ff605c8d5b3a13da8 | []
| no_license | CypixDev/AlphaMC | https://github.com/CypixDev/AlphaMC | 823248e20d692f9e1fb7fab4b3a76d241a84ead8 | 61d6090336ec49522f2d0d93dff32db7af98c2f3 | refs/heads/master | 2020-03-20T02:18:41.887000 | 2018-06-12T17:49:57 | 2018-06-12T17:49:57 | 137,107,919 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.Cypix.Lobby.inventar;
import de.Cypix.Lobby.Files.Var;
import de.Cypix.Lobby.Main.main;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import java.util.List;
public class InventarManager {
public static String InventarInv_Name = "§8➤ §bInventar", BootsInv_Name = "§8➤ §3Boots";
//boots:
//Feuer, Angry, water, redstone, cloud. tnt, love, happy, speed, sound, vanish, jetpack, ender
public static String Heads_Name = "§8➤ §bHüte", Pets_Name = "§8➤ §bPets", Gadgets_Name = "§8➤ §bGadgets", Boots_Name = "§8➤ §bBoots";
public static void openInv(Player p){
Inventory inv = Bukkit.createInventory(null, 6*9, InventarInv_Name);
inv.setItem(46, Item(Material.IRON_HELMET, Heads_Name, null));
inv.setItem(48, Item(Material.MOB_SPAWNER, Pets_Name, null));
inv.setItem(50, Item(Material.FIREBALL, Gadgets_Name, null));
inv.setItem(52, Item(Material.GOLD_BOOTS, Boots_Name, null));
if(p.getInventory().getHelmet() != null)inv.setItem(28, Item(Material.BARRIER, "Helm ausziehen ", null));
if(p.getInventory().getBoots() != null)inv.setItem(34, Item(Material.BARRIER, "Boots ausziehen", null));
setPlaceHolder(inv);
p.openInventory(inv);
p.playSound(p.getLocation(), Sound.CHEST_OPEN, 20 ,20);
}
private static void setPlaceHolder(Inventory inv){
inv.setItem(36, SlotHolder(7, 1));
inv.setItem(37, SlotHolder(7, 1));
inv.setItem(38, SlotHolder(7, 1));
inv.setItem(39, SlotHolder(7, 1));
inv.setItem(40, SlotHolder(7, 1));
inv.setItem(41, SlotHolder(7, 1));
inv.setItem(42, SlotHolder(7, 1));
inv.setItem(43, SlotHolder(7, 1));
inv.setItem(44, SlotHolder(7, 1));
}
public static ItemStack SlotHolder(int shortid, int amount){
ItemStack i = new ItemStack(Material.getMaterial(160), 1, (short)shortid);
ItemMeta im = i.getItemMeta();
im.setDisplayName(" ");
i.setItemMeta(im);
i.setAmount(amount);
return i;
}
private static ItemStack Item(Material material, String displayname, List<String> lore){
ItemStack i = new ItemStack(material);
ItemMeta im = i.getItemMeta();
if(displayname != null)im.setDisplayName(displayname);
if(lore != null)im.setLore(lore);
i.setItemMeta(im);
return i;
}
private static ItemStack LetherBoot(Color color, String displayname){
ItemStack i = new ItemStack(Material.LEATHER_BOOTS);
LeatherArmorMeta im = (LeatherArmorMeta) i.getItemMeta();
im.setDisplayName(displayname);
im.setColor(color);
i.setItemMeta(im);
return i;
}
}
| UTF-8 | Java | 3,044 | java | InventarManager.java | Java | [
{
"context": ")inv.setItem(34, Item(Material.BARRIER, \"Boots ausziehen\", null));\n\n setPlaceHolder(inv);\n\n\n ",
"end": 1461,
"score": 0.9994431734085083,
"start": 1455,
"tag": "NAME",
"value": "ziehen"
}
]
| null | []
| package de.Cypix.Lobby.inventar;
import de.Cypix.Lobby.Files.Var;
import de.Cypix.Lobby.Main.main;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import java.util.List;
public class InventarManager {
public static String InventarInv_Name = "§8➤ §bInventar", BootsInv_Name = "§8➤ §3Boots";
//boots:
//Feuer, Angry, water, redstone, cloud. tnt, love, happy, speed, sound, vanish, jetpack, ender
public static String Heads_Name = "§8➤ §bHüte", Pets_Name = "§8➤ §bPets", Gadgets_Name = "§8➤ §bGadgets", Boots_Name = "§8➤ §bBoots";
public static void openInv(Player p){
Inventory inv = Bukkit.createInventory(null, 6*9, InventarInv_Name);
inv.setItem(46, Item(Material.IRON_HELMET, Heads_Name, null));
inv.setItem(48, Item(Material.MOB_SPAWNER, Pets_Name, null));
inv.setItem(50, Item(Material.FIREBALL, Gadgets_Name, null));
inv.setItem(52, Item(Material.GOLD_BOOTS, Boots_Name, null));
if(p.getInventory().getHelmet() != null)inv.setItem(28, Item(Material.BARRIER, "Helm ausziehen ", null));
if(p.getInventory().getBoots() != null)inv.setItem(34, Item(Material.BARRIER, "Boots ausziehen", null));
setPlaceHolder(inv);
p.openInventory(inv);
p.playSound(p.getLocation(), Sound.CHEST_OPEN, 20 ,20);
}
private static void setPlaceHolder(Inventory inv){
inv.setItem(36, SlotHolder(7, 1));
inv.setItem(37, SlotHolder(7, 1));
inv.setItem(38, SlotHolder(7, 1));
inv.setItem(39, SlotHolder(7, 1));
inv.setItem(40, SlotHolder(7, 1));
inv.setItem(41, SlotHolder(7, 1));
inv.setItem(42, SlotHolder(7, 1));
inv.setItem(43, SlotHolder(7, 1));
inv.setItem(44, SlotHolder(7, 1));
}
public static ItemStack SlotHolder(int shortid, int amount){
ItemStack i = new ItemStack(Material.getMaterial(160), 1, (short)shortid);
ItemMeta im = i.getItemMeta();
im.setDisplayName(" ");
i.setItemMeta(im);
i.setAmount(amount);
return i;
}
private static ItemStack Item(Material material, String displayname, List<String> lore){
ItemStack i = new ItemStack(material);
ItemMeta im = i.getItemMeta();
if(displayname != null)im.setDisplayName(displayname);
if(lore != null)im.setLore(lore);
i.setItemMeta(im);
return i;
}
private static ItemStack LetherBoot(Color color, String displayname){
ItemStack i = new ItemStack(Material.LEATHER_BOOTS);
LeatherArmorMeta im = (LeatherArmorMeta) i.getItemMeta();
im.setDisplayName(displayname);
im.setColor(color);
i.setItemMeta(im);
return i;
}
}
| 3,044 | 0.65684 | 0.63531 | 90 | 32.544445 | 30.553837 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.277778 | false | false | 14 |
323bcee4c7a2a8717b389c6dcb1f5990a8b8d02c | 6,107,443,511,072 | db1d0a99ea57c7919f831d7b6ec3e0e4bfd5d483 | /kata_arab_to_roman/src/main/java/ArabRomanConverter.java | d8008de6ceba9b24671c4527fc85fe0db303647d | []
| no_license | zeyaReal/code_exercise | https://github.com/zeyaReal/code_exercise | 89ccb3a6a34dccdcbd0f398ad57de8d36fe870e3 | c5104eed2641732608e3d58279338525ac24434c | refs/heads/master | 2016-09-05T18:31:12.739000 | 2014-11-22T10:14:35 | 2014-11-22T10:14:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Comparator;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* Created by zeya on 14-10-8.
*/
public class ArabRomanConverter {
public static final int MAX_ROMAN_NUMBER = 3999;
private SortedMap<Integer, String> arabRomanMap = new TreeMap<>(Comparator.<Integer>reverseOrder());
public ArabRomanConverter() {
arabRomanMap.put(1, "I");
arabRomanMap.put(4, "IV");
arabRomanMap.put(5, "V");
arabRomanMap.put(9, "IX");
arabRomanMap.put(10, "X");
arabRomanMap.put(40, "XL");
arabRomanMap.put(50, "L");
arabRomanMap.put(90, "XC");
arabRomanMap.put(100, "C");
arabRomanMap.put(400, "CD");
arabRomanMap.put(500, "D");
arabRomanMap.put(900, "CM");
arabRomanMap.put(1000, "M");
}
public String convert(int number) {
if (number > MAX_ROMAN_NUMBER) {
throw new UnsupportedOperationException("too big input! max roman number is 3999. input=" + number);
}
return innerConvert(number);
}
private String innerConvert(int number) {
if (number == 0) return "";
int largestArbicNumberInMappingSmallThanNumber = arabRomanMap.tailMap(number).firstKey();
return arabRomanMap.get(largestArbicNumberInMappingSmallThanNumber) + innerConvert(number - largestArbicNumberInMappingSmallThanNumber);
}
}
| UTF-8 | Java | 1,405 | java | ArabRomanConverter.java | Java | [
{
"context": "dMap;\nimport java.util.TreeMap;\n\n/**\n * Created by zeya on 14-10-8.\n */\npublic class ArabRomanConverter {",
"end": 106,
"score": 0.9995048642158508,
"start": 102,
"tag": "USERNAME",
"value": "zeya"
}
]
| null | []
| import java.util.Comparator;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* Created by zeya on 14-10-8.
*/
public class ArabRomanConverter {
public static final int MAX_ROMAN_NUMBER = 3999;
private SortedMap<Integer, String> arabRomanMap = new TreeMap<>(Comparator.<Integer>reverseOrder());
public ArabRomanConverter() {
arabRomanMap.put(1, "I");
arabRomanMap.put(4, "IV");
arabRomanMap.put(5, "V");
arabRomanMap.put(9, "IX");
arabRomanMap.put(10, "X");
arabRomanMap.put(40, "XL");
arabRomanMap.put(50, "L");
arabRomanMap.put(90, "XC");
arabRomanMap.put(100, "C");
arabRomanMap.put(400, "CD");
arabRomanMap.put(500, "D");
arabRomanMap.put(900, "CM");
arabRomanMap.put(1000, "M");
}
public String convert(int number) {
if (number > MAX_ROMAN_NUMBER) {
throw new UnsupportedOperationException("too big input! max roman number is 3999. input=" + number);
}
return innerConvert(number);
}
private String innerConvert(int number) {
if (number == 0) return "";
int largestArbicNumberInMappingSmallThanNumber = arabRomanMap.tailMap(number).firstKey();
return arabRomanMap.get(largestArbicNumberInMappingSmallThanNumber) + innerConvert(number - largestArbicNumberInMappingSmallThanNumber);
}
}
| 1,405 | 0.643416 | 0.613523 | 44 | 30.931818 | 31.173559 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.840909 | false | false | 14 |
1def9fa1696ea8168c872bd8185f16ec2ce7609d | 25,323,127,177,465 | 1e88306b277918b95c8c2995d734c06e1e8b0e74 | /src/main/java/com/contract/system/repository/BookingRepository.java | 3367d0ce09cd781405a7bd6cba473e2f1596b10b | []
| no_license | vikash0439/ContractManagementApplication | https://github.com/vikash0439/ContractManagementApplication | 758a3df7cfeb9963001b1933096c5348e3129944 | 2f8211a4a95c9c4532d40813171b3202750e0243 | refs/heads/master | 2020-04-28T09:34:23.799000 | 2019-04-01T07:26:27 | 2019-04-01T07:26:27 | 175,171,567 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.contract.system.repository;
import java.util.List;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.contract.system.model.Booking;
@Repository
public interface BookingRepository extends CrudRepository<Booking, Integer>{
Booking findAllByBookingid(Long serviceid);
@Query(value = "select * from booking;", nativeQuery = true)
public List<String> findName();
@Query(value = "select bookingid from booking;", nativeQuery = true)
public List<Long> findBookingID();
@Query(value = "select bookingdates from booking;", nativeQuery = true)
public List<String> findBookingDates();
@Query(value = "select * from booking Order by contractid Desc;", nativeQuery = true)
List<Booking> findAllByOrder();
@Query(value = "select slot from booking WHERE servicedate = ?1 ;", nativeQuery = true)
String findByBookingdates(String date);
// @Query(value = "delete from booking b WHERE b.serviceid = ?1 ;", nativeQuery = true)
// public void deleteBooking(long serviceid);
@Transactional
@Modifying @Query(value = "delete from booking WHERE bookingid = ?1 ;", nativeQuery = true)
public void deleteByServiceid(Long serviceid);
}
| UTF-8 | Java | 1,445 | java | BookingRepository.java | Java | []
| null | []
| package com.contract.system.repository;
import java.util.List;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.contract.system.model.Booking;
@Repository
public interface BookingRepository extends CrudRepository<Booking, Integer>{
Booking findAllByBookingid(Long serviceid);
@Query(value = "select * from booking;", nativeQuery = true)
public List<String> findName();
@Query(value = "select bookingid from booking;", nativeQuery = true)
public List<Long> findBookingID();
@Query(value = "select bookingdates from booking;", nativeQuery = true)
public List<String> findBookingDates();
@Query(value = "select * from booking Order by contractid Desc;", nativeQuery = true)
List<Booking> findAllByOrder();
@Query(value = "select slot from booking WHERE servicedate = ?1 ;", nativeQuery = true)
String findByBookingdates(String date);
// @Query(value = "delete from booking b WHERE b.serviceid = ?1 ;", nativeQuery = true)
// public void deleteBooking(long serviceid);
@Transactional
@Modifying @Query(value = "delete from booking WHERE bookingid = ?1 ;", nativeQuery = true)
public void deleteByServiceid(Long serviceid);
}
| 1,445 | 0.748097 | 0.746021 | 40 | 34.125 | 30.269777 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.325 | false | false | 14 |
d2cb9e7470c3928983e27334c1a3e3169e9f0ee6 | 18,975,165,536,756 | 09551cdb23b2300d8fd105ac877ac23a2013bcfe | /src/main/java/com/king/blog/ArticleShowServlet.java | 2a2ad53654a42826cc404047570f79b0acfcb116 | []
| no_license | zgy59/king | https://github.com/zgy59/king | e6c83d87cbc489fea875221239a0393a685a1765 | d0cf99f49d7f986b8139ba9db8b5ba48706c10a4 | refs/heads/master | 2019-07-14T20:06:16.455000 | 2017-01-15T14:34:13 | 2017-01-15T14:34:13 | 56,650,972 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.king.blog;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 文章展示
* @author ZG
* 2015.11.10
*/
@WebServlet(name="ArticleShowServlet", urlPatterns={"/ArticleShowServlet.do"})
public class ArticleShowServlet extends HttpServlet
{
private static final long serialVersionUID = -8889862167627023229L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
this.doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String articleId = request.getParameter("id");
Article article = BlogManager.getInstance().getArticleById(articleId);
request.setAttribute("article", article);
request.setAttribute("content", BlogManager.getInstance().loadArticleContent(articleId));
request.getRequestDispatcher("/jsp/blog/ArticleTemplate.jsp").forward(request, response);
}
} | UTF-8 | Java | 1,180 | java | ArticleShowServlet.java | Java | [
{
"context": ".http.HttpServletResponse;\n\n/**\n * 文章展示\n * @author ZG\n * 2015.11.10\n */\n@WebServlet(name=\"ArticleShowSe",
"end": 293,
"score": 0.9988340139389038,
"start": 291,
"tag": "USERNAME",
"value": "ZG"
}
]
| null | []
| package com.king.blog;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 文章展示
* @author ZG
* 2015.11.10
*/
@WebServlet(name="ArticleShowServlet", urlPatterns={"/ArticleShowServlet.do"})
public class ArticleShowServlet extends HttpServlet
{
private static final long serialVersionUID = -8889862167627023229L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
this.doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String articleId = request.getParameter("id");
Article article = BlogManager.getInstance().getArticleById(articleId);
request.setAttribute("article", article);
request.setAttribute("content", BlogManager.getInstance().loadArticleContent(articleId));
request.getRequestDispatcher("/jsp/blog/ArticleTemplate.jsp").forward(request, response);
}
} | 1,180 | 0.796928 | 0.773891 | 38 | 29.868422 | 33.672707 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.236842 | false | false | 14 |
8947bbdadb907cca0c3a68979399f4e26d83ec0a | 22,900,765,640,948 | f619053630fc20de02f60d310607f1e7b5c094c5 | /src/main/java/week15/d05/Covid.java | c28851dc7a9948e12e08ccd56e3328fb331778a4 | []
| no_license | Herko3/training-solutions | https://github.com/Herko3/training-solutions | fc9ff67d2b8c3f8325f51ef3a27798dacfe0cce5 | 112f03aeaa2a6be147409f9252589968a526306c | refs/heads/master | 2023-03-16T22:07:49.601000 | 2021-03-16T14:16:22 | 2021-03-16T14:16:22 | 308,134,786 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package week15.d05;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Covid {
private Map<String, Country> countries = new HashMap<>();
public void readFromFile(InputStream is) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
String line;
reader.readLine();
while ((line = reader.readLine()) != null) {
if (line.contains("Bonaire, Saint Eustatius and Saba")) {
line = line.replace("Bonaire, Saint", "Bonaire Saint");
}
String[] parts = line.split(",");
modifyCountries(parts);
}
} catch (IOException ioe) {
throw new IllegalStateException("Cannot read file", ioe);
}
}
private void modifyCountries(String[] parts) {
if (!parts[7].isBlank()) {
String name = parts[4];
int number = Integer.parseInt(parts[2]);
int pop = Integer.parseInt(parts[7]);
if (!countries.containsKey(name)) {
countries.put(name, new Country(name, pop, number));
} else {
countries.get(name).addCases(number);
}
}
}
public List<Country> getMostCasePerPopulation(int numberOfCountry){
return countries.values()
.stream()
.sorted(Comparator.comparing(Country::casePerPopulation))
.limit(numberOfCountry)
.collect(Collectors.toList());
}
public Map<String, Country> getCountries() {
return countries;
}
}
| UTF-8 | Java | 1,837 | java | Covid.java | Java | []
| null | []
| package week15.d05;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Covid {
private Map<String, Country> countries = new HashMap<>();
public void readFromFile(InputStream is) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
String line;
reader.readLine();
while ((line = reader.readLine()) != null) {
if (line.contains("Bonaire, Saint Eustatius and Saba")) {
line = line.replace("Bonaire, Saint", "Bonaire Saint");
}
String[] parts = line.split(",");
modifyCountries(parts);
}
} catch (IOException ioe) {
throw new IllegalStateException("Cannot read file", ioe);
}
}
private void modifyCountries(String[] parts) {
if (!parts[7].isBlank()) {
String name = parts[4];
int number = Integer.parseInt(parts[2]);
int pop = Integer.parseInt(parts[7]);
if (!countries.containsKey(name)) {
countries.put(name, new Country(name, pop, number));
} else {
countries.get(name).addCases(number);
}
}
}
public List<Country> getMostCasePerPopulation(int numberOfCountry){
return countries.values()
.stream()
.sorted(Comparator.comparing(Country::casePerPopulation))
.limit(numberOfCountry)
.collect(Collectors.toList());
}
public Map<String, Country> getCountries() {
return countries;
}
}
| 1,837 | 0.582471 | 0.578116 | 58 | 30.672413 | 23.232252 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.586207 | false | false | 14 |
7a57891518cc0f12c035ccbb755c730afd50bd1d | 14,998,025,813,862 | 47f08f353b3995cec54aea22807f9d796c5dfe15 | /src/main/java/com/beta/app/decorator/FireDecorator.java | 7f610f0bf185daf98f7b0dcc0e7a34b2a87a9a15 | []
| no_license | MarsMuse/StreamMars | https://github.com/MarsMuse/StreamMars | dac915729540c2ee3e7114df94e57d8ad3cbd27a | 6f8760e6ae34d3002088e21cb96f6d6b299eacfa | refs/heads/master | 2021-01-19T22:04:39.901000 | 2017-07-31T03:24:26 | 2017-07-31T03:24:26 | 88,747,787 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.beta.app.decorator;
public abstract class FireDecorator implements Component {
protected Component component;
protected FireDecorator(Component component){
this.component = component;
}
}
| UTF-8 | Java | 235 | java | FireDecorator.java | Java | []
| null | []
| package com.beta.app.decorator;
public abstract class FireDecorator implements Component {
protected Component component;
protected FireDecorator(Component component){
this.component = component;
}
}
| 235 | 0.706383 | 0.706383 | 11 | 20.363636 | 20.981691 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false | 14 |
fe7ca9e3b883aa94b053ff1d52172f79f70c718f | 24,670,292,166,459 | 6eb95b84914959567a5614e11b53ef8c182b6b41 | /src/decibel/tests/TestRequests.java | ebce1d4f1eb8bcee96a5d400889daa42251cb721 | []
| no_license | musbel/DI | https://github.com/musbel/DI | 3d6d8f476bfd4bd1e93b234bb5efa4f51a1d4182 | 5879060526da57c8baf58e04022dfdc185fe5a5c | refs/heads/master | 2016-08-05T10:57:45.045000 | 2015-04-22T13:02:46 | 2015-04-22T13:02:46 | 34,390,363 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package decibel.tests;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class TestRequests
{
public static void runTest( String url, int numberOfTests, int numberOfThreads ) throws InterruptedException
{
ExecutorService threadPool = Executors.newFixedThreadPool( numberOfThreads );
for( int i = 0; i < numberOfTests; ++i )
{
threadPool.execute( new TestClient( url, i ) );
}
threadPool.shutdown();
// Wait for all the test threads to finish
threadPool.awaitTermination( Long.MAX_VALUE, TimeUnit.SECONDS );
}
}
| UTF-8 | Java | 618 | java | TestRequests.java | Java | []
| null | []
| package decibel.tests;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class TestRequests
{
public static void runTest( String url, int numberOfTests, int numberOfThreads ) throws InterruptedException
{
ExecutorService threadPool = Executors.newFixedThreadPool( numberOfThreads );
for( int i = 0; i < numberOfTests; ++i )
{
threadPool.execute( new TestClient( url, i ) );
}
threadPool.shutdown();
// Wait for all the test threads to finish
threadPool.awaitTermination( Long.MAX_VALUE, TimeUnit.SECONDS );
}
}
| 618 | 0.752427 | 0.750809 | 23 | 25.869566 | 29.308411 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.565217 | false | false | 14 |
d5589a1edfa1dd0d9620ebb2cf80ad039a6725e7 | 1,511,828,545,652 | 304e7e970469939a328eab4cbf91850267ece057 | /src/com/gaurav/Util.java | 05c900af6accbf1936d46f378f8c939c4fd87be0 | []
| no_license | gauravahujame/Fiddler | https://github.com/gauravahujame/Fiddler | 88f643023a45dfbff535bc4701c8a20648663745 | e8a894e140417e0d82754e44d06ece5bd7f98312 | refs/heads/master | 2021-01-23T05:50:25.860000 | 2017-03-27T10:49:00 | 2017-03-27T10:49:00 | 86,323,441 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gaurav;
import org.opencv.core.*;
import org.opencv.features2d.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.videoio.VideoCapture;
import org.opencv.videoio.Videoio;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.opencv.core.CvType.CV_32F;
/**
* Created by gaurav on 23/3/17.
*/
public class Util {
private static final int KNN = 2;
public static MatOfDMatch getGoodMatches(List<MatOfDMatch> matches, float nndrRatio, float threshold) {
//System.out.println("Calculating good match list...");
LinkedList<DMatch> goodMatchesList = new LinkedList<>();
MatOfDMatch goodMatches = new MatOfDMatch();
for (int i = 0; i < matches.size(); i++) {
MatOfDMatch matofDMatch = matches.get(i);
DMatch[] dmatcharray = matofDMatch.toArray();
DMatch m1 = dmatcharray[0];
DMatch m2 = dmatcharray[1];
if (m1.distance <= m2.distance * nndrRatio) {
goodMatchesList.add(m1);
}
}
if (goodMatchesList.size() >= threshold) {
System.out.println("Number of good matches in current frame : " + goodMatchesList.size());
goodMatches.fromList(goodMatchesList);
}
return goodMatches;
}
public static MatOfKeyPoint detectFeatures(Mat image){
//int minHessian = 400;
//System.out.println("Detecting key points...");
MatOfKeyPoint keypoints = new MatOfKeyPoint();
FeatureDetector surf = FeatureDetector.create(FeatureDetector.SURF);
surf.detect(image, keypoints);
if (keypoints.empty()) {
return null;
}
return keypoints;
}
public static MatOfKeyPoint computeDescriptors(Mat image, MatOfKeyPoint keypoints){
//System.out.println("Computing descriptors...");
MatOfKeyPoint descriptors = new MatOfKeyPoint();
DescriptorExtractor descriptorExtractor = DescriptorExtractor.create(DescriptorExtractor.SURF);
descriptorExtractor.compute(image,keypoints,descriptors);
return descriptors;
}
public static void drawKeypoints(Mat image, MatOfKeyPoint keypoints, String filename){
//System.out.println("Drawing key points on image...");
Scalar newKeypointColor = new Scalar(255, 0, 0);
Mat outputImage = new Mat(image.rows(), image.cols(), Imgcodecs.CV_LOAD_IMAGE_COLOR);
Features2d.drawKeypoints(image, keypoints, outputImage, newKeypointColor, 0);
Imgcodecs.imwrite("output/"+filename, outputImage);
}
public static List<MatOfDMatch> matchDescriptors(Mat descriptors1, Mat descriptors2){
//System.out.println("Matching original and test images...");
DescriptorMatcher flannMatcher = DescriptorMatcher.create(DescriptorMatcher.FLANNBASED);
List<MatOfDMatch> matches = new LinkedList<>();
descriptors1.convertTo(descriptors1, CV_32F);
descriptors2.convertTo(descriptors2, CV_32F);
if(descriptors1.empty() || descriptors2.empty())
{
return matches;
}
flannMatcher.knnMatch(descriptors1, descriptors2, matches, 2);
return matches;
}
public static List<Frame> getVideoFrames(String videoFile){
VideoCapture camera = new VideoCapture(videoFile);
List<Frame> frames = new LinkedList<>();
double fps = camera.get(Videoio.CAP_PROP_FPS);
double totalFrames = camera.get(Videoio.CAP_PROP_FRAME_COUNT);
double currentFrame = 0;
while(currentFrame < totalFrames){
camera.set(Videoio.CAP_PROP_POS_FRAMES, currentFrame);
//Mat frame = new Mat();
Frame frame = new Frame(camera.get(Videoio.CAP_PROP_POS_MSEC),currentFrame);
Mat rawFrame = new Mat();
camera.retrieve(rawFrame);
Imgproc.cvtColor(rawFrame,frame.image,Imgproc.COLOR_BGRA2GRAY);
if(Core.countNonZero(frame.image) > 1000){ //Detects blank frames
frames.add(frame);
}
//Imgcodecs.imwrite("output/frames/frame" + currentFrame + ".png", frame);
currentFrame = currentFrame + fps; //TODO: Breaks with some values eg. 10.0f
}
System.out.println("Retrieved frames from video : " + frames.size() + " Total frames : " + camera.get(Videoio.CAP_PROP_FRAME_COUNT));
if (camera.isOpened()){
camera.release();
}
return frames;
}
public static String getTimeFromMillis(double milliseconds){
//long millis = Double.doubleToLongBits(milliseconds);
int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
String result = String.format("%d min, %d sec", minutes, seconds);
return result;
}
}
| UTF-8 | Java | 5,005 | java | Util.java | Java | [
{
"context": " org.opencv.core.CvType.CV_32F;\n\n/**\n * Created by gaurav on 23/3/17.\n */\npublic class Util {\n private s",
"end": 390,
"score": 0.9980495572090149,
"start": 384,
"tag": "USERNAME",
"value": "gaurav"
}
]
| null | []
| package com.gaurav;
import org.opencv.core.*;
import org.opencv.features2d.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.videoio.VideoCapture;
import org.opencv.videoio.Videoio;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.opencv.core.CvType.CV_32F;
/**
* Created by gaurav on 23/3/17.
*/
public class Util {
private static final int KNN = 2;
public static MatOfDMatch getGoodMatches(List<MatOfDMatch> matches, float nndrRatio, float threshold) {
//System.out.println("Calculating good match list...");
LinkedList<DMatch> goodMatchesList = new LinkedList<>();
MatOfDMatch goodMatches = new MatOfDMatch();
for (int i = 0; i < matches.size(); i++) {
MatOfDMatch matofDMatch = matches.get(i);
DMatch[] dmatcharray = matofDMatch.toArray();
DMatch m1 = dmatcharray[0];
DMatch m2 = dmatcharray[1];
if (m1.distance <= m2.distance * nndrRatio) {
goodMatchesList.add(m1);
}
}
if (goodMatchesList.size() >= threshold) {
System.out.println("Number of good matches in current frame : " + goodMatchesList.size());
goodMatches.fromList(goodMatchesList);
}
return goodMatches;
}
public static MatOfKeyPoint detectFeatures(Mat image){
//int minHessian = 400;
//System.out.println("Detecting key points...");
MatOfKeyPoint keypoints = new MatOfKeyPoint();
FeatureDetector surf = FeatureDetector.create(FeatureDetector.SURF);
surf.detect(image, keypoints);
if (keypoints.empty()) {
return null;
}
return keypoints;
}
public static MatOfKeyPoint computeDescriptors(Mat image, MatOfKeyPoint keypoints){
//System.out.println("Computing descriptors...");
MatOfKeyPoint descriptors = new MatOfKeyPoint();
DescriptorExtractor descriptorExtractor = DescriptorExtractor.create(DescriptorExtractor.SURF);
descriptorExtractor.compute(image,keypoints,descriptors);
return descriptors;
}
public static void drawKeypoints(Mat image, MatOfKeyPoint keypoints, String filename){
//System.out.println("Drawing key points on image...");
Scalar newKeypointColor = new Scalar(255, 0, 0);
Mat outputImage = new Mat(image.rows(), image.cols(), Imgcodecs.CV_LOAD_IMAGE_COLOR);
Features2d.drawKeypoints(image, keypoints, outputImage, newKeypointColor, 0);
Imgcodecs.imwrite("output/"+filename, outputImage);
}
public static List<MatOfDMatch> matchDescriptors(Mat descriptors1, Mat descriptors2){
//System.out.println("Matching original and test images...");
DescriptorMatcher flannMatcher = DescriptorMatcher.create(DescriptorMatcher.FLANNBASED);
List<MatOfDMatch> matches = new LinkedList<>();
descriptors1.convertTo(descriptors1, CV_32F);
descriptors2.convertTo(descriptors2, CV_32F);
if(descriptors1.empty() || descriptors2.empty())
{
return matches;
}
flannMatcher.knnMatch(descriptors1, descriptors2, matches, 2);
return matches;
}
public static List<Frame> getVideoFrames(String videoFile){
VideoCapture camera = new VideoCapture(videoFile);
List<Frame> frames = new LinkedList<>();
double fps = camera.get(Videoio.CAP_PROP_FPS);
double totalFrames = camera.get(Videoio.CAP_PROP_FRAME_COUNT);
double currentFrame = 0;
while(currentFrame < totalFrames){
camera.set(Videoio.CAP_PROP_POS_FRAMES, currentFrame);
//Mat frame = new Mat();
Frame frame = new Frame(camera.get(Videoio.CAP_PROP_POS_MSEC),currentFrame);
Mat rawFrame = new Mat();
camera.retrieve(rawFrame);
Imgproc.cvtColor(rawFrame,frame.image,Imgproc.COLOR_BGRA2GRAY);
if(Core.countNonZero(frame.image) > 1000){ //Detects blank frames
frames.add(frame);
}
//Imgcodecs.imwrite("output/frames/frame" + currentFrame + ".png", frame);
currentFrame = currentFrame + fps; //TODO: Breaks with some values eg. 10.0f
}
System.out.println("Retrieved frames from video : " + frames.size() + " Total frames : " + camera.get(Videoio.CAP_PROP_FRAME_COUNT));
if (camera.isOpened()){
camera.release();
}
return frames;
}
public static String getTimeFromMillis(double milliseconds){
//long millis = Double.doubleToLongBits(milliseconds);
int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
String result = String.format("%d min, %d sec", minutes, seconds);
return result;
}
}
| 5,005 | 0.636364 | 0.623377 | 122 | 40.02459 | 31.079344 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.860656 | false | false | 14 |
a728e1ecd20680029c030510732b6ab2a0b6992e | 16,432,544,891,419 | c19cb77e3958a194046d6f84ca97547cc3a223c3 | /pkix/src/main/jdk1.1/org/bouncycastle/cms/jcajce/NamedJcaJceExtHelper.java | 1e056daaa098bba96bf1951c4c44a7d7f8ae1ad7 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | bcgit/bc-java | https://github.com/bcgit/bc-java | 1b6092bc5d2336ec26ebd6da6eeaea6600b4c70a | 62b03c0f704ebd243fe5f2d701aef4edd77bba6e | refs/heads/main | 2023-09-04T00:48:33.995000 | 2023-08-30T05:33:42 | 2023-08-30T05:33:42 | 10,416,648 | 1,984 | 1,021 | MIT | false | 2023-08-26T05:14:28 | 2013-06-01T02:38:42 | 2023-08-25T23:28:27 | 2023-08-24T12:11:48 | 66,399 | 2,000 | 1,072 | 224 | Java | false | false | package org.bouncycastle.cms.jcajce;
import java.security.PrivateKey;
import javax.crypto.SecretKey;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.jcajce.util.NamedJcaJceHelper;
import org.bouncycastle.operator.AsymmetricKeyUnwrapper;
import org.bouncycastle.operator.SymmetricKeyUnwrapper;
import org.bouncycastle.operator.jcajce.JceAsymmetricKeyUnwrapper;
import org.bouncycastle.operator.jcajce.JceKTSKeyUnwrapper;
import org.bouncycastle.operator.jcajce.JceSymmetricKeyUnwrapper;
class NamedJcaJceExtHelper
extends NamedJcaJceHelper
implements JcaJceExtHelper
{
public NamedJcaJceExtHelper(String providerName)
{
super(providerName);
}
public JceAsymmetricKeyUnwrapper createAsymmetricUnwrapper(AlgorithmIdentifier keyEncryptionAlgorithm, PrivateKey keyEncryptionKey)
{
keyEncryptionKey = CMSUtils.cleanPrivateKey(keyEncryptionKey);
return new JceAsymmetricKeyUnwrapper(keyEncryptionAlgorithm, keyEncryptionKey).setProvider(providerName);
}
public JceKTSKeyUnwrapper createAsymmetricUnwrapper(AlgorithmIdentifier keyEncryptionAlgorithm, PrivateKey keyEncryptionKey, byte[] partyUInfo, byte[] partyVInfo)
{
keyEncryptionKey = CMSUtils.cleanPrivateKey(keyEncryptionKey);
return new JceKTSKeyUnwrapper(keyEncryptionAlgorithm, keyEncryptionKey, partyUInfo, partyVInfo).setProvider(providerName);
}
public SymmetricKeyUnwrapper createSymmetricUnwrapper(AlgorithmIdentifier keyEncryptionAlgorithm, SecretKey keyEncryptionKey)
{
return new JceSymmetricKeyUnwrapper(keyEncryptionAlgorithm, keyEncryptionKey).setProvider(providerName);
}
public AsymmetricKeyUnwrapper createKEMUnwrapper(AlgorithmIdentifier keyEncryptionAlgorithm, PrivateKey keyEncryptionKey)
{
return null; //TOD:
}
}
| UTF-8 | Java | 1,846 | java | NamedJcaJceExtHelper.java | Java | []
| null | []
| package org.bouncycastle.cms.jcajce;
import java.security.PrivateKey;
import javax.crypto.SecretKey;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.jcajce.util.NamedJcaJceHelper;
import org.bouncycastle.operator.AsymmetricKeyUnwrapper;
import org.bouncycastle.operator.SymmetricKeyUnwrapper;
import org.bouncycastle.operator.jcajce.JceAsymmetricKeyUnwrapper;
import org.bouncycastle.operator.jcajce.JceKTSKeyUnwrapper;
import org.bouncycastle.operator.jcajce.JceSymmetricKeyUnwrapper;
class NamedJcaJceExtHelper
extends NamedJcaJceHelper
implements JcaJceExtHelper
{
public NamedJcaJceExtHelper(String providerName)
{
super(providerName);
}
public JceAsymmetricKeyUnwrapper createAsymmetricUnwrapper(AlgorithmIdentifier keyEncryptionAlgorithm, PrivateKey keyEncryptionKey)
{
keyEncryptionKey = CMSUtils.cleanPrivateKey(keyEncryptionKey);
return new JceAsymmetricKeyUnwrapper(keyEncryptionAlgorithm, keyEncryptionKey).setProvider(providerName);
}
public JceKTSKeyUnwrapper createAsymmetricUnwrapper(AlgorithmIdentifier keyEncryptionAlgorithm, PrivateKey keyEncryptionKey, byte[] partyUInfo, byte[] partyVInfo)
{
keyEncryptionKey = CMSUtils.cleanPrivateKey(keyEncryptionKey);
return new JceKTSKeyUnwrapper(keyEncryptionAlgorithm, keyEncryptionKey, partyUInfo, partyVInfo).setProvider(providerName);
}
public SymmetricKeyUnwrapper createSymmetricUnwrapper(AlgorithmIdentifier keyEncryptionAlgorithm, SecretKey keyEncryptionKey)
{
return new JceSymmetricKeyUnwrapper(keyEncryptionAlgorithm, keyEncryptionKey).setProvider(providerName);
}
public AsymmetricKeyUnwrapper createKEMUnwrapper(AlgorithmIdentifier keyEncryptionAlgorithm, PrivateKey keyEncryptionKey)
{
return null; //TOD:
}
}
| 1,846 | 0.815818 | 0.813651 | 45 | 40.022221 | 45.250164 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.622222 | false | false | 14 |
54749a5aafb00f15b8617cb1aaeb4d75653373ed | 26,792,006,010,749 | 9839eb78193f9c0285e5b9a3f5a16385c605438b | /src/kr/ac/kopo/day02/homework/ForIf1/Q1.java | 28b664c16a6febb700ec7d091385e3aaae0753c6 | []
| no_license | LeenaKim/Java_Lessons | https://github.com/LeenaKim/Java_Lessons | 91ef590915880be91c6dff2a467af6a631d25afd | 471cb1d1cfcc139340d81caf23c56c88132e4a3f | refs/heads/master | 2022-10-09T03:23:33.965000 | 2020-06-14T14:12:04 | 2020-06-14T14:12:04 | 254,899,000 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kr.ac.kopo.day02.homework.ForIf1;
public class Q1 {
public void q1 (char[] ch) {
System.out.println("-------------------");
System.out.println("영문자 모음의 아스키 코드 ");
System.out.println("-------------------");
// 영문자 모음 배열을 하나씩 순회하며 ascii 코드 값을 출력한다.
for(int i = 0; i < ch.length; i++) {
int num = ch[i];
System.out.printf("%c = %d\n", ch[i], num);
}
System.out.println("-------------------");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// 영문자 모음 배열 생성
char[] ch = {'A', 'E', 'I', 'O', 'U'};
// 객체 생성
Q1 test = new Q1();
// 메소드 호출
test.q1(ch);
}
} | UTF-8 | Java | 738 | java | Q1.java | Java | []
| null | []
| package kr.ac.kopo.day02.homework.ForIf1;
public class Q1 {
public void q1 (char[] ch) {
System.out.println("-------------------");
System.out.println("영문자 모음의 아스키 코드 ");
System.out.println("-------------------");
// 영문자 모음 배열을 하나씩 순회하며 ascii 코드 값을 출력한다.
for(int i = 0; i < ch.length; i++) {
int num = ch[i];
System.out.printf("%c = %d\n", ch[i], num);
}
System.out.println("-------------------");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// 영문자 모음 배열 생성
char[] ch = {'A', 'E', 'I', 'O', 'U'};
// 객체 생성
Q1 test = new Q1();
// 메소드 호출
test.q1(ch);
}
} | 738 | 0.511041 | 0.496845 | 27 | 22.518518 | 17.342669 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.148148 | false | false | 14 |
354f6fb0bec919c4eefa330f8e9e8b9d2230d49e | 644,245,105,118 | 75fc9a53ac0dbcc33be2e6ac8234f4710d522ff9 | /src/test/java/by/epamtc/payment/dao/impl/SQLUserDAOTest.java | 23e435a29bd64e9690c7875f2cbcad3e43cb0c08 | []
| no_license | 4ertya/Payment | https://github.com/4ertya/Payment | 7e5923afb1e1d2238415044b47f8d290fa40c1f8 | 1ba3d0799daeab28e263988e4c0b248d2eb84605 | refs/heads/master | 2023-04-05T05:04:53.508000 | 2021-04-22T05:44:24 | 2021-04-22T05:44:24 | 297,715,029 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package by.epamtc.payment.dao.impl;
import by.epamtc.payment.dao.connection.ConnectionPool;
import by.epamtc.payment.dao.exception.DAOException;
import by.epamtc.payment.dao.exception.DAOUserExistException;
import by.epamtc.payment.dao.exception.DAOUserNotFoundException;
import by.epamtc.payment.entity.*;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
class SQLUserDAOTest {
@BeforeEach
public void init() throws IOException, SQLException, URISyntaxException {
ConnectionPool connectionPool = ConnectionPool.getInstance();
Connection connection;
connection = connectionPool.takeConnection();
URL url1 = SQLUserDAOTest.class.getClassLoader()
.getResource("create_test_db.sql");
URL url2 = SQLUserDAOTest.class.getClassLoader()
.getResource("fill_in_test_db.sql");
assert url1 != null;
List<String> str1 = Files.readAllLines(Paths.get(url1.toURI()));
String sql1 = String.join("", str1);
assert url2 != null;
List<String> str2 = Files.readAllLines(Paths.get(url2.toURI()));
String sql2 = String.join("", str2);
Statement statement = connection.createStatement();
statement.executeUpdate(sql1);
statement.executeUpdate(sql2);
connectionPool.closeConnection(connection, statement);
}
@Test
void positiveLogin() throws DAOUserNotFoundException, DAOException {
SQLUserDAO sqlUserDAO = new SQLUserDAO();
AuthorizationData authorizationData = new AuthorizationData();
authorizationData.setLogin("admin");
authorizationData.setPassword("admin");
User expected = new User();
expected.setName("Dzmitry");
expected.setSurname("Palchynski");
expected.setId(1);
expected.setRole(Role.ADMIN);
expected.setStatus(Status.VERIFIED);
User actual = sqlUserDAO.login(authorizationData);
assertEquals(expected, actual);
}
@Test
void loginForNonexistentUser() {
SQLUserDAO sqlUserDAO = new SQLUserDAO();
AuthorizationData authorizationData = new AuthorizationData();
authorizationData.setLogin("nonexistent");
authorizationData.setPassword("nonexistent");
Assertions.assertThrows(DAOUserNotFoundException.class, () -> sqlUserDAO.login(authorizationData));
}
@Test
void registration() throws DAOUserExistException, DAOException, SQLException {
SQLUserDAO sqlUserDAO = new SQLUserDAO();
ConnectionPool connectionPool = ConnectionPool.getInstance();
Connection connection = connectionPool.takeConnection();
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
RegistrationData registrationData = new RegistrationData();
registrationData.setLogin("user");
registrationData.setPassword("password");
registrationData.setEmail("chertyac@gmail.com");
registrationData.setRole(Role.USER);
registrationData.setStatus(Status.NEW);
sqlUserDAO.registration(registrationData);
//language=MySQL
String sql = "SELECT * FROM users " +
"JOIN user_details USING (user_id) " +
"JOIN roles USING(role_id) " +
"JOIN user_statuses USING (user_status_id) " +
"WHERE login=? AND password=?;";
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, registrationData.getLogin());
preparedStatement.setString(2, registrationData.getPassword());
resultSet = preparedStatement.executeQuery();
String login = null;
String password = null;
String email = null;
Role role = null;
Status status = null;
if (resultSet.next()) {
login = resultSet.getString("login");
password = resultSet.getString("password");
email = resultSet.getString("email");
role = Role.valueOf(resultSet.getString("role"));
status = Status.valueOf(resultSet.getString("user_status"));
}
assertEquals(registrationData.getLogin(), login);
assertEquals(registrationData.getPassword(), password);
assertEquals(registrationData.getEmail(), email);
assertEquals(registrationData.getRole(), role);
assertEquals(registrationData.getStatus(), status);
} finally {
connectionPool.closeConnection(connection, preparedStatement, resultSet);
}
}
@Test
void registrationWithExistingData() {
SQLUserDAO sqlUserDAO = new SQLUserDAO();
RegistrationData registrationData = new RegistrationData();
registrationData.setLogin("admin");
registrationData.setPassword("admin");
registrationData.setEmail("palchmail@gmail.com");
registrationData.setRole(Role.ADMIN);
registrationData.setStatus(Status.VERIFIED);
Assertions.assertThrows(DAOUserExistException.class, () -> sqlUserDAO.registration(registrationData));
}
@Test
void getUserData() throws DAOException {
SQLUserDAO sqlUserDAO = new SQLUserDAO();
UserData actual = sqlUserDAO.getUserData(1L);
UserData expected = new UserData();
expected.setId(1);
expected.setEmail("palchmail@gmail.com");
expected.setLogin("admin");
expected.setRole(Role.ADMIN);
expected.setStatus(Status.VERIFIED);
assertEquals(expected, actual);
}
@Test
void getUserDetail() throws DAOException {
SQLUserDAO sqlUserDAO = new SQLUserDAO();
UserDetail expected = new UserDetail();
expected.setId(1L);
expected.setRuName("Дмитрий");
expected.setRuSurname("Пальчинский");
expected.setEnName("Dzmitry");
expected.setEnSurname("Palchynski");
expected.setGender("М");
expected.setPassportSeries("МР");
expected.setPassportNumber(2756569);
expected.setPhoneNumber("+375-29-593-67-98");
expected.setLocation("г.Минск ул.Славинского");
UserDetail actual = sqlUserDAO.getUserDetail(1L);
assertEquals(expected, actual);
}
@Test
void getAllUserDetails() throws DAOException {
SQLUserDAO sqlUserDAO = new SQLUserDAO();
List<UserDetail> expected = new ArrayList<>();
UserDetail userDetail = new UserDetail();
userDetail.setId(1L);
userDetail.setRuName("Дмитрий");
userDetail.setRuSurname("Пальчинский");
userDetail.setEnName("Dzmitry");
userDetail.setEnSurname("Palchynski");
userDetail.setGender("М");
userDetail.setPassportSeries("МР");
userDetail.setPassportNumber(2756569);
userDetail.setPhoneNumber("+375-29-593-67-98");
userDetail.setLocation("г.Минск ул.Славинского");
userDetail.setRole(Role.ADMIN);
userDetail.setStatus(Status.VERIFIED);
expected.add(userDetail);
List<UserDetail> actual = sqlUserDAO.getAllUserDetails();
assertEquals(expected, actual);
}
@Test
void updateUserDetails() throws DAOException, SQLException {
ConnectionPool connectionPool = ConnectionPool.getInstance();
Connection connection = connectionPool.takeConnection();
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
SQLUserDAO sqlUserDAO = new SQLUserDAO();
UserDetail actual = new UserDetail();
UserDetail expected = new UserDetail();
expected.setId(1L);
expected.setRuName("Дмитрий");
expected.setRuSurname("Пальчинский");
expected.setEnName("Dmitry");
expected.setEnSurname("Palchynski");
expected.setGender("М");
expected.setPassportSeries("МР");
expected.setPassportNumber(2756569);
expected.setPhoneNumber("+375-29-593-67-98");
expected.setLocation("г.Минск");
expected.setRole(Role.ADMIN);
expected.setStatus(Status.VERIFIED);
sqlUserDAO.updateUserDetails(expected);
//Language=MySQL
String sql = "SELECT ud.*, u.role_id,u.user_status_id, role, user_status FROM user_details ud " +
"JOIN users u USING(user_id) " +
"JOIN roles USING(role_id) " +
"JOIN user_statuses USING(user_status_id) " +
"WHERE user_id=?;";
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setLong(1, expected.getId());
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
actual.setId(resultSet.getLong("user_id"));
actual.setRuName(resultSet.getString("ru_name"));
actual.setRuSurname(resultSet.getString("ru_surname"));
actual.setEnName(resultSet.getString("en_name"));
actual.setEnSurname(resultSet.getString("en_surname"));
actual.setGender(resultSet.getString("gender"));
actual.setPassportSeries(resultSet.getString("passport_series"));
actual.setPassportNumber(resultSet.getInt("passport_number"));
actual.setPhoneNumber(resultSet.getString("phone_number"));
actual.setLocation(resultSet.getString("location"));
actual.setRole(Role.valueOf(resultSet.getString("role")));
actual.setStatus(Status.valueOf(resultSet.getString("user_status")));
}
} finally {
connectionPool.closeConnection(connection, preparedStatement, resultSet);
}
assertEquals(expected, actual);
}
} | UTF-8 | Java | 10,270 | java | SQLUserDAOTest.java | Java | [
{
"context": "(\"admin\");\n authorizationData.setPassword(\"admin\");\n\n User expected = new User();\n e",
"end": 1993,
"score": 0.999512791633606,
"start": 1988,
"tag": "PASSWORD",
"value": "admin"
},
{
"context": "xpected = new User();\n expected.setName(\"Dzmitry\");\n expected.setSurname(\"Palchynski\");\n ",
"end": 2067,
"score": 0.9857896566390991,
"start": 2062,
"tag": "NAME",
"value": "mitry"
},
{
"context": ".setName(\"Dzmitry\");\n expected.setSurname(\"Palchynski\");\n expected.setId(1);\n expected.se",
"end": 2110,
"score": 0.9991921186447144,
"start": 2100,
"tag": "NAME",
"value": "Palchynski"
},
{
"context": "xistent\");\n authorizationData.setPassword(\"nonexistent\");\n\n Assertions.assertThrows(DAOUserNotFou",
"end": 2602,
"score": 0.8703793883323669,
"start": 2591,
"tag": "PASSWORD",
"value": "nonexistent"
},
{
"context": "in(\"user\");\n registrationData.setPassword(\"password\");\n registrationData.setEmail(\"chertyac@gm",
"end": 3246,
"score": 0.9993957281112671,
"start": 3238,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "d(\"password\");\n registrationData.setEmail(\"chertyac@gmail.com\");\n registrationData.setRole(Role.USER);\n ",
"end": 3303,
"score": 0.9999271035194397,
"start": 3285,
"tag": "EMAIL",
"value": "chertyac@gmail.com"
},
{
"context": "trationData();\n registrationData.setLogin(\"admin\");\n registrationData.setPassword(\"admin\");",
"end": 5206,
"score": 0.9984304308891296,
"start": 5201,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "n(\"admin\");\n registrationData.setPassword(\"admin\");\n registrationData.setEmail(\"palchmail@g",
"end": 5253,
"score": 0.9993832111358643,
"start": 5248,
"tag": "PASSWORD",
"value": "admin"
},
{
"context": "word(\"admin\");\n registrationData.setEmail(\"palchmail@gmail.com\");\n registrationData.setRole(Role.ADMIN);\n",
"end": 5311,
"score": 0.9999250173568726,
"start": 5292,
"tag": "EMAIL",
"value": "palchmail@gmail.com"
},
{
"context": " expected.setId(1);\n expected.setEmail(\"palchmail@gmail.com\");\n expected.setLogin(\"admin\");\n ex",
"end": 5809,
"score": 0.999923825263977,
"start": 5790,
"tag": "EMAIL",
"value": "palchmail@gmail.com"
},
{
"context": "palchmail@gmail.com\");\n expected.setLogin(\"admin\");\n expected.setRole(Role.ADMIN);\n ",
"end": 5845,
"score": 0.9982494115829468,
"start": 5840,
"tag": "USERNAME",
"value": "admin"
},
{
"context": " expected.setId(1L);\n expected.setRuName(\"Дмитрий\");\n expected.setRuSurname(\"Пальчинский\");\n",
"end": 6197,
"score": 0.9996061325073242,
"start": 6190,
"tag": "NAME",
"value": "Дмитрий"
},
{
"context": "RuName(\"Дмитрий\");\n expected.setRuSurname(\"Пальчинский\");\n expected.setEnName(\"Dzmitry\");\n ",
"end": 6237,
"score": 0.8070867657661438,
"start": 6232,
"tag": "NAME",
"value": "Пальч"
},
{
"context": "rname(\"Пальчинский\");\n expected.setEnName(\"Dzmitry\");\n expected.setEnSurname(\"Palchynski\");\n ",
"end": 6282,
"score": 0.999569833278656,
"start": 6275,
"tag": "NAME",
"value": "Dzmitry"
},
{
"context": "EnName(\"Dzmitry\");\n expected.setEnSurname(\"Palchynski\");\n expected.setGender(\"М\");\n expec",
"end": 6327,
"score": 0.9993854761123657,
"start": 6317,
"tag": "NAME",
"value": "Palchynski"
},
{
"context": "erDetail.setId(1L);\n userDetail.setRuName(\"Дмитрий\");\n userDetail.setRuSurname(\"Пальчинский\")",
"end": 6951,
"score": 0.9997831583023071,
"start": 6944,
"tag": "NAME",
"value": "Дмитрий"
},
{
"context": "Name(\"Дмитрий\");\n userDetail.setRuSurname(\"Пальчинский\");\n userDetail.setEnName(\"Dzmitry\");\n ",
"end": 6995,
"score": 0.8346619606018066,
"start": 6988,
"tag": "NAME",
"value": "Пальчин"
},
{
"context": "итрий\");\n userDetail.setRuSurname(\"Пальчинский\");\n userDetail.setEnName(\"Dzmitry\");\n ",
"end": 6999,
"score": 0.6715137362480164,
"start": 6996,
"tag": "NAME",
"value": "кий"
},
{
"context": "ame(\"Пальчинский\");\n userDetail.setEnName(\"Dzmitry\");\n userDetail.setEnSurname(\"Palchynski\");",
"end": 7040,
"score": 0.9998156428337097,
"start": 7033,
"tag": "NAME",
"value": "Dzmitry"
},
{
"context": "Name(\"Dzmitry\");\n userDetail.setEnSurname(\"Palchynski\");\n userDetail.setGender(\"М\");\n use",
"end": 7087,
"score": 0.999777615070343,
"start": 7077,
"tag": "NAME",
"value": "Palchynski"
},
{
"context": " expected.setId(1L);\n expected.setRuName(\"Дмитрий\");\n expected.setRuSurname(\"Пальчинский\");\n",
"end": 8076,
"score": 0.999768853187561,
"start": 8069,
"tag": "NAME",
"value": "Дмитрий"
},
{
"context": "RuName(\"Дмитрий\");\n expected.setRuSurname(\"Пальчинский\");\n expected.setEnName(\"Dmitry\");\n ",
"end": 8122,
"score": 0.9078233242034912,
"start": 8111,
"tag": "NAME",
"value": "Пальчинский"
},
{
"context": "rname(\"Пальчинский\");\n expected.setEnName(\"Dmitry\");\n expected.setEnSurname(\"Palchynski\");\n ",
"end": 8160,
"score": 0.999788224697113,
"start": 8154,
"tag": "NAME",
"value": "Dmitry"
},
{
"context": "tEnName(\"Dmitry\");\n expected.setEnSurname(\"Palchynski\");\n expected.setGender(\"М\");\n expec",
"end": 8205,
"score": 0.999710738658905,
"start": 8195,
"tag": "NAME",
"value": "Palchynski"
}
]
| null | []
| package by.epamtc.payment.dao.impl;
import by.epamtc.payment.dao.connection.ConnectionPool;
import by.epamtc.payment.dao.exception.DAOException;
import by.epamtc.payment.dao.exception.DAOUserExistException;
import by.epamtc.payment.dao.exception.DAOUserNotFoundException;
import by.epamtc.payment.entity.*;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
class SQLUserDAOTest {
@BeforeEach
public void init() throws IOException, SQLException, URISyntaxException {
ConnectionPool connectionPool = ConnectionPool.getInstance();
Connection connection;
connection = connectionPool.takeConnection();
URL url1 = SQLUserDAOTest.class.getClassLoader()
.getResource("create_test_db.sql");
URL url2 = SQLUserDAOTest.class.getClassLoader()
.getResource("fill_in_test_db.sql");
assert url1 != null;
List<String> str1 = Files.readAllLines(Paths.get(url1.toURI()));
String sql1 = String.join("", str1);
assert url2 != null;
List<String> str2 = Files.readAllLines(Paths.get(url2.toURI()));
String sql2 = String.join("", str2);
Statement statement = connection.createStatement();
statement.executeUpdate(sql1);
statement.executeUpdate(sql2);
connectionPool.closeConnection(connection, statement);
}
@Test
void positiveLogin() throws DAOUserNotFoundException, DAOException {
SQLUserDAO sqlUserDAO = new SQLUserDAO();
AuthorizationData authorizationData = new AuthorizationData();
authorizationData.setLogin("admin");
authorizationData.setPassword("<PASSWORD>");
User expected = new User();
expected.setName("Dzmitry");
expected.setSurname("Palchynski");
expected.setId(1);
expected.setRole(Role.ADMIN);
expected.setStatus(Status.VERIFIED);
User actual = sqlUserDAO.login(authorizationData);
assertEquals(expected, actual);
}
@Test
void loginForNonexistentUser() {
SQLUserDAO sqlUserDAO = new SQLUserDAO();
AuthorizationData authorizationData = new AuthorizationData();
authorizationData.setLogin("nonexistent");
authorizationData.setPassword("<PASSWORD>");
Assertions.assertThrows(DAOUserNotFoundException.class, () -> sqlUserDAO.login(authorizationData));
}
@Test
void registration() throws DAOUserExistException, DAOException, SQLException {
SQLUserDAO sqlUserDAO = new SQLUserDAO();
ConnectionPool connectionPool = ConnectionPool.getInstance();
Connection connection = connectionPool.takeConnection();
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
RegistrationData registrationData = new RegistrationData();
registrationData.setLogin("user");
registrationData.setPassword("<PASSWORD>");
registrationData.setEmail("<EMAIL>");
registrationData.setRole(Role.USER);
registrationData.setStatus(Status.NEW);
sqlUserDAO.registration(registrationData);
//language=MySQL
String sql = "SELECT * FROM users " +
"JOIN user_details USING (user_id) " +
"JOIN roles USING(role_id) " +
"JOIN user_statuses USING (user_status_id) " +
"WHERE login=? AND password=?;";
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, registrationData.getLogin());
preparedStatement.setString(2, registrationData.getPassword());
resultSet = preparedStatement.executeQuery();
String login = null;
String password = null;
String email = null;
Role role = null;
Status status = null;
if (resultSet.next()) {
login = resultSet.getString("login");
password = resultSet.getString("password");
email = resultSet.getString("email");
role = Role.valueOf(resultSet.getString("role"));
status = Status.valueOf(resultSet.getString("user_status"));
}
assertEquals(registrationData.getLogin(), login);
assertEquals(registrationData.getPassword(), password);
assertEquals(registrationData.getEmail(), email);
assertEquals(registrationData.getRole(), role);
assertEquals(registrationData.getStatus(), status);
} finally {
connectionPool.closeConnection(connection, preparedStatement, resultSet);
}
}
@Test
void registrationWithExistingData() {
SQLUserDAO sqlUserDAO = new SQLUserDAO();
RegistrationData registrationData = new RegistrationData();
registrationData.setLogin("admin");
registrationData.setPassword("<PASSWORD>");
registrationData.setEmail("<EMAIL>");
registrationData.setRole(Role.ADMIN);
registrationData.setStatus(Status.VERIFIED);
Assertions.assertThrows(DAOUserExistException.class, () -> sqlUserDAO.registration(registrationData));
}
@Test
void getUserData() throws DAOException {
SQLUserDAO sqlUserDAO = new SQLUserDAO();
UserData actual = sqlUserDAO.getUserData(1L);
UserData expected = new UserData();
expected.setId(1);
expected.setEmail("<EMAIL>");
expected.setLogin("admin");
expected.setRole(Role.ADMIN);
expected.setStatus(Status.VERIFIED);
assertEquals(expected, actual);
}
@Test
void getUserDetail() throws DAOException {
SQLUserDAO sqlUserDAO = new SQLUserDAO();
UserDetail expected = new UserDetail();
expected.setId(1L);
expected.setRuName("Дмитрий");
expected.setRuSurname("Пальчинский");
expected.setEnName("Dzmitry");
expected.setEnSurname("Palchynski");
expected.setGender("М");
expected.setPassportSeries("МР");
expected.setPassportNumber(2756569);
expected.setPhoneNumber("+375-29-593-67-98");
expected.setLocation("г.Минск ул.Славинского");
UserDetail actual = sqlUserDAO.getUserDetail(1L);
assertEquals(expected, actual);
}
@Test
void getAllUserDetails() throws DAOException {
SQLUserDAO sqlUserDAO = new SQLUserDAO();
List<UserDetail> expected = new ArrayList<>();
UserDetail userDetail = new UserDetail();
userDetail.setId(1L);
userDetail.setRuName("Дмитрий");
userDetail.setRuSurname("Пальчинский");
userDetail.setEnName("Dzmitry");
userDetail.setEnSurname("Palchynski");
userDetail.setGender("М");
userDetail.setPassportSeries("МР");
userDetail.setPassportNumber(2756569);
userDetail.setPhoneNumber("+375-29-593-67-98");
userDetail.setLocation("г.Минск ул.Славинского");
userDetail.setRole(Role.ADMIN);
userDetail.setStatus(Status.VERIFIED);
expected.add(userDetail);
List<UserDetail> actual = sqlUserDAO.getAllUserDetails();
assertEquals(expected, actual);
}
@Test
void updateUserDetails() throws DAOException, SQLException {
ConnectionPool connectionPool = ConnectionPool.getInstance();
Connection connection = connectionPool.takeConnection();
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
SQLUserDAO sqlUserDAO = new SQLUserDAO();
UserDetail actual = new UserDetail();
UserDetail expected = new UserDetail();
expected.setId(1L);
expected.setRuName("Дмитрий");
expected.setRuSurname("Пальчинский");
expected.setEnName("Dmitry");
expected.setEnSurname("Palchynski");
expected.setGender("М");
expected.setPassportSeries("МР");
expected.setPassportNumber(2756569);
expected.setPhoneNumber("+375-29-593-67-98");
expected.setLocation("г.Минск");
expected.setRole(Role.ADMIN);
expected.setStatus(Status.VERIFIED);
sqlUserDAO.updateUserDetails(expected);
//Language=MySQL
String sql = "SELECT ud.*, u.role_id,u.user_status_id, role, user_status FROM user_details ud " +
"JOIN users u USING(user_id) " +
"JOIN roles USING(role_id) " +
"JOIN user_statuses USING(user_status_id) " +
"WHERE user_id=?;";
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setLong(1, expected.getId());
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
actual.setId(resultSet.getLong("user_id"));
actual.setRuName(resultSet.getString("ru_name"));
actual.setRuSurname(resultSet.getString("ru_surname"));
actual.setEnName(resultSet.getString("en_name"));
actual.setEnSurname(resultSet.getString("en_surname"));
actual.setGender(resultSet.getString("gender"));
actual.setPassportSeries(resultSet.getString("passport_series"));
actual.setPassportNumber(resultSet.getInt("passport_number"));
actual.setPhoneNumber(resultSet.getString("phone_number"));
actual.setLocation(resultSet.getString("location"));
actual.setRole(Role.valueOf(resultSet.getString("role")));
actual.setStatus(Status.valueOf(resultSet.getString("user_status")));
}
} finally {
connectionPool.closeConnection(connection, preparedStatement, resultSet);
}
assertEquals(expected, actual);
}
} | 10,246 | 0.65089 | 0.64292 | 266 | 37.210526 | 24.940094 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.766917 | false | false | 14 |
e012dccf3f62a8f7e2741a07a5a5bcea033a3352 | 7,876,970,080,048 | d5c9e9fe1dc9eb39e37e7b084ff497a3f453332c | /app/src/main/java/com/greenbotsite/uiGimmicks/FragmentTransitionActivity.java | 174a9b3ad49f60a713444022f8cf87b3a677e5e4 | []
| no_license | gaurav-mishra8/UIGimmicks | https://github.com/gaurav-mishra8/UIGimmicks | 441139ca619887c2f5140c76d801c1c0f3733653 | 6f6a45ca079f2c38e274ebcd4b1f51ee818675d1 | refs/heads/master | 2021-01-19T11:52:57.818000 | 2017-03-23T01:38:51 | 2017-03-23T01:38:51 | 82,270,379 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.greenbotsite.uiGimmicks;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
/**
* Created by gaurav on 17/2/17.
*/
public class FragmentTransitionActivity extends AppCompatActivity {
public static void startActivtiy(Context context) {
Intent intent = new Intent(context, FragmentTransitionActivity.class);
context.startActivity(intent);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, SourceFragment.newInstance(), SourceFragment.class.getSimpleName())
.commit();
}
}
}
| UTF-8 | Java | 905 | java | FragmentTransitionActivity.java | Java | [
{
"context": "pport.v7.app.AppCompatActivity;\n\n/**\n * Created by gaurav on 17/2/17.\n */\npublic class FragmentTransit",
"end": 240,
"score": 0.7232470512390137,
"start": 239,
"tag": "USERNAME",
"value": "g"
},
{
"context": "ort.v7.app.AppCompatActivity;\n\n/**\n * Created by gaurav on 17/2/17.\n */\npublic class FragmentTransitionAc",
"end": 245,
"score": 0.5751413702964783,
"start": 240,
"tag": "NAME",
"value": "aurav"
}
]
| null | []
| package com.greenbotsite.uiGimmicks;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
/**
* Created by gaurav on 17/2/17.
*/
public class FragmentTransitionActivity extends AppCompatActivity {
public static void startActivtiy(Context context) {
Intent intent = new Intent(context, FragmentTransitionActivity.class);
context.startActivity(intent);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, SourceFragment.newInstance(), SourceFragment.class.getSimpleName())
.commit();
}
}
}
| 905 | 0.703867 | 0.697238 | 31 | 28.193548 | 28.298431 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.419355 | false | false | 14 |
2a695ac1ca47aeaa4a7be08c229fcf5a2154b327 | 7,876,970,076,783 | 55d5a4f1d354922bfb20ca0bf68a1040454842ab | /src/main/java/com/zikool/edu/frame/common/PageDTO.java | 7a771ab0c46f853f5ca77204109e5c17df493c31 | []
| no_license | longyao/EduSystem | https://github.com/longyao/EduSystem | 615959a1c104d807c2b8d7ed0de1a9ee8b5b511d | edd9fe17b42e365e8a8725f9d163051588d4a32d | refs/heads/master | 2016-08-03T09:40:41.268000 | 2013-08-19T09:56:57 | 2013-08-19T09:56:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zikool.edu.frame.common;
import java.util.List;
import java.util.Map;
public class PageDTO<T> {
private long rowSize;
private List<T> data;
private Map<String,Object> otherData;
private int pageIndex = 1;
private int pageSize = GlobalConfigure.DEFAULT_PAGE_SIZE;
private long start;
private long end;
public PageDTO() {
}
public PageDTO(Integer pageIndex, Integer pageSize) {
if(pageIndex == null || pageIndex <= 0) {
pageIndex = 1;
}
if(pageSize == null || pageSize <= 0) {
pageSize = GlobalConfigure.DEFAULT_PAGE_SIZE;
}
if(GlobalConfigure.MAX_PAGE_SIZE < pageSize.intValue()){
pageSize = GlobalConfigure.MAX_PAGE_SIZE;
}
long first = (pageIndex - 1) * pageSize;
this.pageIndex = pageIndex.intValue();
this.pageSize = pageSize.intValue();
if(first < 0){
first = 0;
}
this.start = first;
this.end = pageIndex*pageSize;
}
public long getRowSize() {
return rowSize;
}
public void setRowSize(long rowSize) {
this.rowSize = rowSize;
}
public List<T> getData() {
return data;
}
public void setData(List<T> data) {
this.data = data;
}
public int getPageIndex() {
return pageIndex;
}
public void setPageIndex(int pageIndex) {
this.pageIndex = pageIndex;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public long getStart() {
return start;
}
public void setStart(long start) {
this.start = start;
}
public long getEnd() {
return end;
}
public void setEnd(long end) {
this.end = end;
}
public Map<String, Object> getOtherData() {
return otherData;
}
public void setOtherData(Map<String, Object> otherData) {
this.otherData = otherData;
}
}
| UTF-8 | Java | 1,894 | java | PageDTO.java | Java | []
| null | []
| package com.zikool.edu.frame.common;
import java.util.List;
import java.util.Map;
public class PageDTO<T> {
private long rowSize;
private List<T> data;
private Map<String,Object> otherData;
private int pageIndex = 1;
private int pageSize = GlobalConfigure.DEFAULT_PAGE_SIZE;
private long start;
private long end;
public PageDTO() {
}
public PageDTO(Integer pageIndex, Integer pageSize) {
if(pageIndex == null || pageIndex <= 0) {
pageIndex = 1;
}
if(pageSize == null || pageSize <= 0) {
pageSize = GlobalConfigure.DEFAULT_PAGE_SIZE;
}
if(GlobalConfigure.MAX_PAGE_SIZE < pageSize.intValue()){
pageSize = GlobalConfigure.MAX_PAGE_SIZE;
}
long first = (pageIndex - 1) * pageSize;
this.pageIndex = pageIndex.intValue();
this.pageSize = pageSize.intValue();
if(first < 0){
first = 0;
}
this.start = first;
this.end = pageIndex*pageSize;
}
public long getRowSize() {
return rowSize;
}
public void setRowSize(long rowSize) {
this.rowSize = rowSize;
}
public List<T> getData() {
return data;
}
public void setData(List<T> data) {
this.data = data;
}
public int getPageIndex() {
return pageIndex;
}
public void setPageIndex(int pageIndex) {
this.pageIndex = pageIndex;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public long getStart() {
return start;
}
public void setStart(long start) {
this.start = start;
}
public long getEnd() {
return end;
}
public void setEnd(long end) {
this.end = end;
}
public Map<String, Object> getOtherData() {
return otherData;
}
public void setOtherData(Map<String, Object> otherData) {
this.otherData = otherData;
}
}
| 1,894 | 0.62566 | 0.621964 | 101 | 16.752476 | 16.683071 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.366337 | false | false | 14 |
d0c6a8700c5434f058911ed27f7680f5793faa90 | 12,232,066,880,562 | 8d28224c517ab13d76a7cb3a5b10b41076fd6e96 | /app/src/main/java/th/ac/su/babykick/ShowActivity.java | 5b17b918598cbf2853e57ba6f99d5a40d8cdbad3 | []
| no_license | wisitrock/BabyKickUsingRoomDB | https://github.com/wisitrock/BabyKickUsingRoomDB | 1bf87291ae29d86afffe2b6e6bbe4786d3c4b9f6 | 8fc2874ae6678096f4b8380ef514ac837b2c77d8 | refs/heads/master | 2023-01-19T11:58:31.553000 | 2020-11-25T06:15:50 | 2020-11-25T06:15:50 | 315,087,539 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package th.ac.su.babykick;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.widget.BaseAdapter;
import android.widget.TextView;
import th.ac.su.babykick.adapter.BabyAdapter;
import th.ac.su.babykick.db.AppDatabase;
import th.ac.su.babykick.model.Babymodel;
import th.ac.su.babykick.util.AppExecutors;
public class ShowActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
mRecyclerView = findViewById(R.id.baby_count_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(ShowActivity.this)); // setLayout ให้กับ RecyclerView
final AppExecutors executors = new AppExecutors();
executors.diskIO().execute(new Runnable() {
@Override
public void run() {
AppDatabase db = AppDatabase.getInstance(ShowActivity.this);
final Babymodel[] Baby = db.userDao().getAllUser(); // get ข้อมูลจาก database แล้วนำไปเก็บใน array baby ซึ่งมี type เป็น class Babymodel
executors.mainThread().execute(new Runnable() {
@Override
public void run() {
BabyAdapter adapter = new BabyAdapter(ShowActivity.this, Baby); // สร้าง object adapter จาก class BabyAdapter
mRecyclerView.setAdapter(adapter); // setAdapter ให้กับ RecyclerView
}
});
}
});
}
} | UTF-8 | Java | 1,835 | java | ShowActivity.java | Java | []
| null | []
| package th.ac.su.babykick;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.widget.BaseAdapter;
import android.widget.TextView;
import th.ac.su.babykick.adapter.BabyAdapter;
import th.ac.su.babykick.db.AppDatabase;
import th.ac.su.babykick.model.Babymodel;
import th.ac.su.babykick.util.AppExecutors;
public class ShowActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
mRecyclerView = findViewById(R.id.baby_count_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(ShowActivity.this)); // setLayout ให้กับ RecyclerView
final AppExecutors executors = new AppExecutors();
executors.diskIO().execute(new Runnable() {
@Override
public void run() {
AppDatabase db = AppDatabase.getInstance(ShowActivity.this);
final Babymodel[] Baby = db.userDao().getAllUser(); // get ข้อมูลจาก database แล้วนำไปเก็บใน array baby ซึ่งมี type เป็น class Babymodel
executors.mainThread().execute(new Runnable() {
@Override
public void run() {
BabyAdapter adapter = new BabyAdapter(ShowActivity.this, Baby); // สร้าง object adapter จาก class BabyAdapter
mRecyclerView.setAdapter(adapter); // setAdapter ให้กับ RecyclerView
}
});
}
});
}
} | 1,835 | 0.668016 | 0.668016 | 46 | 36.608696 | 35.077232 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.521739 | false | false | 14 |
2fa2c2525a04550092eb8db1e84892d719f61dd3 | 12,764,642,823,615 | c923296a8804580457ed3a0781990bb0bf24a0f1 | /src/main/java/org/jwolfe/quetzal/algorithms/lc/CombinationSumIV.java | 8e279fecb8dd6e279f9e681c04aea873c073ff83 | []
| no_license | drjoewolfe/quetzal-algorithms | https://github.com/drjoewolfe/quetzal-algorithms | 653650fc16d953e629c0607289b8f037a90439f4 | af58cdc4fe2b59827a1285c0db9dd4ee9331a010 | refs/heads/master | 2023-09-01T00:02:42.870000 | 2023-08-29T18:44:53 | 2023-08-29T18:44:53 | 162,035,955 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.jwolfe.quetzal.algorithms.lc;
import java.util.Arrays;
public class CombinationSumIV {
class Solution {
public int combinationSum4(int[] nums, int target) {
if(nums == null || nums.length == 0) {
return 0;
}
int n = nums.length;
int[][] memo = new int[n][target + 1];
for(int[] row : memo) {
Arrays.fill(row, -1);
}
return combinationSum4(nums, target, 0, memo);
}
private int combinationSum4(int[] nums, int target, int index, int[][] memo) {
if(target < 0) {
return 0;
}
if(target == 0) {
return 1;
}
if(memo[index][target] != -1) {
return memo[index][target];
}
int count = 0;
for(int i = index; i < nums.length; i++) {
count += combinationSum4(nums, target - nums[i], index, memo);
}
memo[index][target] = count;
return count;
}
}
class Solution_Recursive {
public int combinationSum4(int[] nums, int target) {
if(nums == null || nums.length == 0) {
return 0;
}
return combinationSum4(nums, target, 0);
}
private int combinationSum4(int[] nums, int target, int index) {
if(target < 0) {
return 0;
}
if(target == 0) {
return 1;
}
int count = 0;
for(int i = index; i < nums.length; i++) {
count += combinationSum4(nums, target - nums[i], index);
}
return count;
}
}
// [1,2,3]
// 4
// [2,1,3]
// 35
}
// 377. Combination Sum IV
// Medium
//
// 2140
//
// 244
//
// Add to List
//
// Share
// Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.
//
// The answer is guaranteed to fit in a 32-bit integer.
//
//
//
// Example 1:
//
// Input: nums = [1,2,3], target = 4
// Output: 7
// Explanation:
// The possible combination ways are:
// (1, 1, 1, 1)
// (1, 1, 2)
// (1, 2, 1)
// (1, 3)
// (2, 1, 1)
// (2, 2)
// (3, 1)
// Note that different sequences are counted as different combinations.
// Example 2:
//
// Input: nums = [9], target = 3
// Output: 0
//
//
// Constraints:
//
// 1 <= nums.length <= 200
// 1 <= nums[i] <= 1000
// All the elements of nums are unique.
// 1 <= target <= 1000
//
//
// Follow up: What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
| UTF-8 | Java | 2,871 | java | CombinationSumIV.java | Java | []
| null | []
| package org.jwolfe.quetzal.algorithms.lc;
import java.util.Arrays;
public class CombinationSumIV {
class Solution {
public int combinationSum4(int[] nums, int target) {
if(nums == null || nums.length == 0) {
return 0;
}
int n = nums.length;
int[][] memo = new int[n][target + 1];
for(int[] row : memo) {
Arrays.fill(row, -1);
}
return combinationSum4(nums, target, 0, memo);
}
private int combinationSum4(int[] nums, int target, int index, int[][] memo) {
if(target < 0) {
return 0;
}
if(target == 0) {
return 1;
}
if(memo[index][target] != -1) {
return memo[index][target];
}
int count = 0;
for(int i = index; i < nums.length; i++) {
count += combinationSum4(nums, target - nums[i], index, memo);
}
memo[index][target] = count;
return count;
}
}
class Solution_Recursive {
public int combinationSum4(int[] nums, int target) {
if(nums == null || nums.length == 0) {
return 0;
}
return combinationSum4(nums, target, 0);
}
private int combinationSum4(int[] nums, int target, int index) {
if(target < 0) {
return 0;
}
if(target == 0) {
return 1;
}
int count = 0;
for(int i = index; i < nums.length; i++) {
count += combinationSum4(nums, target - nums[i], index);
}
return count;
}
}
// [1,2,3]
// 4
// [2,1,3]
// 35
}
// 377. Combination Sum IV
// Medium
//
// 2140
//
// 244
//
// Add to List
//
// Share
// Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.
//
// The answer is guaranteed to fit in a 32-bit integer.
//
//
//
// Example 1:
//
// Input: nums = [1,2,3], target = 4
// Output: 7
// Explanation:
// The possible combination ways are:
// (1, 1, 1, 1)
// (1, 1, 2)
// (1, 2, 1)
// (1, 3)
// (2, 1, 1)
// (2, 2)
// (3, 1)
// Note that different sequences are counted as different combinations.
// Example 2:
//
// Input: nums = [9], target = 3
// Output: 0
//
//
// Constraints:
//
// 1 <= nums.length <= 200
// 1 <= nums[i] <= 1000
// All the elements of nums are unique.
// 1 <= target <= 1000
//
//
// Follow up: What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
| 2,871 | 0.483455 | 0.451759 | 124 | 22.153225 | 26.734369 | 179 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.548387 | false | false | 14 |
dd45a4d2ea9a96033749ab88e3b9019b98983481 | 4,286,377,391,068 | 1b4fe0744596af21ff2d7dd90ba96de8d7417410 | /springboot-demo-web/src/main/java/com/jellen/springboot/web/controller/SysUserController.java | 59f540e8831a0cf891af5d6aecbfb0b28303eb3a | []
| no_license | KangJellen/springboot-demo | https://github.com/KangJellen/springboot-demo | 4b0a8852ab3c328b466ebf10876468a925bf94cb | 1d9bef69ca76b119a509d10b0146801dda7538d3 | refs/heads/master | 2021-02-04T11:48:31.046000 | 2020-04-02T14:35:08 | 2020-04-02T14:35:08 | 243,663,218 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jellen.springboot.web.controller;
import com.jellen.springboot.biz.manager.SysUserManager;
import com.jellen.springboot.model.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping("/sysUser")
public class SysUserController {
@Autowired
private SysUserManager sysUserManager;
@RequestMapping("test")
@ResponseBody
public String test(SysUser sysUser){
return "success";
}
@RequestMapping("insert")
@ResponseBody
public String insert(SysUser sysUser){
sysUserManager.insert(sysUser);
return "success";
}
@RequestMapping("queryUserById")
@ResponseBody
public SysUser queryUserById(long userId){
return sysUserManager.queryUserById(userId);
}
@RequestMapping("queryAllUserList")
@ResponseBody
public List<SysUser> queryAllUserList(){
return sysUserManager.queryAllUserList();
}
}
| UTF-8 | Java | 1,151 | java | SysUserController.java | Java | []
| null | []
| package com.jellen.springboot.web.controller;
import com.jellen.springboot.biz.manager.SysUserManager;
import com.jellen.springboot.model.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping("/sysUser")
public class SysUserController {
@Autowired
private SysUserManager sysUserManager;
@RequestMapping("test")
@ResponseBody
public String test(SysUser sysUser){
return "success";
}
@RequestMapping("insert")
@ResponseBody
public String insert(SysUser sysUser){
sysUserManager.insert(sysUser);
return "success";
}
@RequestMapping("queryUserById")
@ResponseBody
public SysUser queryUserById(long userId){
return sysUserManager.queryUserById(userId);
}
@RequestMapping("queryAllUserList")
@ResponseBody
public List<SysUser> queryAllUserList(){
return sysUserManager.queryAllUserList();
}
}
| 1,151 | 0.742832 | 0.742832 | 42 | 26.404762 | 20.000071 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 14 |
778ee67e376ca4fcf11d7882dcf24aff6db78435 | 22,419,729,325,019 | 87b5ebf496fa5dd96c211390fc442e10f20df264 | /Ejercicios/src/main/java/Java/Ejercicios/Ejercicio1_CadenaCaracter.java | 78a2e5551cff19d33214965589f56f8fe53e9952 | []
| no_license | MiguelAlvarezNadal/EjercicioInicio | https://github.com/MiguelAlvarezNadal/EjercicioInicio | e369507d69df23dd955b1d0fb56ec4027bad4a26 | a3b312595721460f02e2feca96a6970fcf6ec916 | refs/heads/master | 2020-06-02T21:22:47.216000 | 2017-06-12T15:01:05 | 2017-06-12T15:01:05 | 94,106,948 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Java.Ejercicios;
public class Ejercicio1_CadenaCaracter {
public static void metodo(char caracter, String cadena) {
String esta = "no";
for (int i = 0; i < cadena.length(); i++) {
if(caracter == cadena.charAt(i)){
esta = "si";
break;
}
else{
esta = "no";
}
}
System.out.println("La letra " + caracter + " " + esta + " está en la cadena '" + cadena + "'.");
}
}
| UTF-8 | Java | 424 | java | Ejercicio1_CadenaCaracter.java | Java | []
| null | []
| package Java.Ejercicios;
public class Ejercicio1_CadenaCaracter {
public static void metodo(char caracter, String cadena) {
String esta = "no";
for (int i = 0; i < cadena.length(); i++) {
if(caracter == cadena.charAt(i)){
esta = "si";
break;
}
else{
esta = "no";
}
}
System.out.println("La letra " + caracter + " " + esta + " está en la cadena '" + cadena + "'.");
}
}
| 424 | 0.555556 | 0.550827 | 18 | 21.5 | 25.281197 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.388889 | false | false | 14 |
d894fa5f3ad22ba055d2e3e49875a19213514954 | 2,104,534,040,126 | 966b27fc2d1addeb4539adfeb976833a7f88e3e5 | /app/src/main/java/com/example/felixidan/session6/SpecialQuoteActivity.java | 46010cea48dae7a411974248563ba0e46b875604 | []
| no_license | AndroidAcademy/Session6 | https://github.com/AndroidAcademy/Session6 | eb557439f94f105061015685af78b3143c714f13 | 9f6fc66b73d854e3082d72137c9487afc8dfd3fd | refs/heads/master | 2016-09-01T12:44:51.598000 | 2016-01-17T23:56:23 | 2016-01-17T23:56:23 | 49,509,244 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.felixidan.session6;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
public class SpecialQuoteActivity extends ActionBarActivity {
private static final String EXTRA_QUOTE_ID = "quote.id";
public static Intent openQuote(Context c, int id){
Intent i = new Intent(c, SpecialQuoteActivity.class);
i.putExtra(EXTRA_QUOTE_ID, id);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
return i;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_special_quote);
TextView tv = (TextView) findViewById(R.id.quote_textview);
Intent openingIntent = getIntent();
int quoteId = openingIntent.getIntExtra(EXTRA_QUOTE_ID, -1);
if (quoteId == -1) {
return;
}
String[] quotes = getResources().getStringArray(R.array.quotes);
String quote = quotes[quoteId];
String extendedQuote = quote.replace("—", "\n\n—");
tv.setText(extendedQuote);
}
}
| UTF-8 | Java | 1,241 | java | SpecialQuoteActivity.java | Java | [
{
"context": "package com.example.felixidan.session6;\n\nimport android.content.Context;\nimport",
"end": 29,
"score": 0.8882228136062622,
"start": 20,
"tag": "USERNAME",
"value": "felixidan"
}
]
| null | []
| package com.example.felixidan.session6;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
public class SpecialQuoteActivity extends ActionBarActivity {
private static final String EXTRA_QUOTE_ID = "quote.id";
public static Intent openQuote(Context c, int id){
Intent i = new Intent(c, SpecialQuoteActivity.class);
i.putExtra(EXTRA_QUOTE_ID, id);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
return i;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_special_quote);
TextView tv = (TextView) findViewById(R.id.quote_textview);
Intent openingIntent = getIntent();
int quoteId = openingIntent.getIntExtra(EXTRA_QUOTE_ID, -1);
if (quoteId == -1) {
return;
}
String[] quotes = getResources().getStringArray(R.array.quotes);
String quote = quotes[quoteId];
String extendedQuote = quote.replace("—", "\n\n—");
tv.setText(extendedQuote);
}
}
| 1,241 | 0.678254 | 0.67502 | 40 | 29.924999 | 25.566959 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.675 | false | false | 14 |
171d49dc3344f26cca529ab718836ef0c3e04fd5 | 12,137,577,617,803 | df502913cff3449294ed0e004ee3e2a0fdcc29be | /src/main/java/com/zc58s/creational/builder/impl/DeathKnight.java | 8fb2fdd5fe6a1a795f69688b5d0d9c09f9ea329e | []
| no_license | fujc-dev/DesignPattern | https://github.com/fujc-dev/DesignPattern | 0acf069b1ceb2c7cc354aa2479ad1472b698d2d3 | b381978c41c818246396668da7842d46123afe32 | refs/heads/master | 2023-02-04T15:19:25.981000 | 2020-12-23T07:54:29 | 2020-12-23T07:54:29 | 314,482,626 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zc58s.creational.builder.impl;
import com.zc58s.creational.builder.Builder;
/*
* @description :
*
* 死亡骑士
* @author : fjc.dane@gmail.com
* @create time : 2020/11/20 10:09
*/
public class DeathKnight extends Builder {
public String buildFace() {
return "死亡骑士脸";
}
public String buildClothes() {
return "死亡骑士服饰";
}
public String buildHairStyle() {
return "死亡骑士发型";
}
}
| UTF-8 | Java | 483 | java | DeathKnight.java | Java | [
{
"context": "\n/*\n * @description :\n *\n * 死亡骑士\n * @author : fjc.dane@gmail.com\n * @create time : 2020/11/20 10:09\n */\npublic cla",
"end": 158,
"score": 0.9999247789382935,
"start": 140,
"tag": "EMAIL",
"value": "fjc.dane@gmail.com"
}
]
| null | []
| package com.zc58s.creational.builder.impl;
import com.zc58s.creational.builder.Builder;
/*
* @description :
*
* 死亡骑士
* @author : <EMAIL>
* @create time : 2020/11/20 10:09
*/
public class DeathKnight extends Builder {
public String buildFace() {
return "死亡骑士脸";
}
public String buildClothes() {
return "死亡骑士服饰";
}
public String buildHairStyle() {
return "死亡骑士发型";
}
}
| 472 | 0.621315 | 0.585034 | 24 | 17.375 | 16.06708 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.208333 | false | false | 14 |
33b75e3dcbc6c1f2a2d131af2692b14b38afdcd0 | 17,617,955,870,902 | 163f7a27e6ac2a19968dbcdc68b7138d9b64f7ef | /Assembler/test/cohadar/assembler/constants/TestHexConstants.java | f41e93e0d515078f537ad8936b5edc76c3012b9f | [
"MIT"
]
| permissive | cohadar/parapascal | https://github.com/cohadar/parapascal | 98e6368a7d184bba0d4f6bd2079b72986871b9db | 863bc9b8d7f813dd3bbf8f6e7df36d70de8f5242 | refs/heads/master | 2020-03-21T18:18:42.497000 | 2018-06-27T13:17:51 | 2018-06-27T13:17:51 | 138,884,213 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cohadar.assembler.constants;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import cohadar.assembler.Assembler;
import cohadar.assembler.TestProgram;
import cohadar.interpreter.program.CCProgram;
public class TestHexConstants extends TestProgram {
@Override
public String getPath() {
return "test/cohadar/assembler/constants/";
}
@Test
public void test00() {
String text = slurpTest("hex00.asm");
CCProgram prog = Assembler.assemble(text);
run(prog, false);
;
assertEquals(0xFEDCBA98, p.pop());
assertEquals(0x12345678, p.pop());
assertEmptyStack();
}
}
| UTF-8 | Java | 643 | java | TestHexConstants.java | Java | []
| null | []
| package cohadar.assembler.constants;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import cohadar.assembler.Assembler;
import cohadar.assembler.TestProgram;
import cohadar.interpreter.program.CCProgram;
public class TestHexConstants extends TestProgram {
@Override
public String getPath() {
return "test/cohadar/assembler/constants/";
}
@Test
public void test00() {
String text = slurpTest("hex00.asm");
CCProgram prog = Assembler.assemble(text);
run(prog, false);
;
assertEquals(0xFEDCBA98, p.pop());
assertEquals(0x12345678, p.pop());
assertEmptyStack();
}
}
| 643 | 0.715397 | 0.690513 | 30 | 19.433332 | 18.112028 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.3 | false | false | 14 |
fbd9910f0c8b6d968f69ad1fcb66f5029e0a7e0c | 36,077,725,334,321 | ab122645e91bc205ed1292a40ce7827cf193b2c5 | /fund-service/src/main/java/com/spring/cloud/fund/controller/FeignController.java | 11bba9d398ca0af3ce013334f6000b990e6beb1b | []
| no_license | HuangKunping/springcloud-demo | https://github.com/HuangKunping/springcloud-demo | e8c6f57b372444b12153ad7a61a37feb8ca7ecc5 | bd99630afad71bcbcd409abae8a5cd5e3b7ef0e6 | refs/heads/main | 2023-02-15T00:05:43.505000 | 2021-01-10T13:22:31 | 2021-01-10T13:22:31 | 328,382,173 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.spring.cloud.fund.controller;
import com.spring.cloud.common.util.ThreadUtil;
import com.spring.cloud.common.vo.User;
import com.spring.cloud.fund.facade.UserFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.concurrent.Future;
@RestController
@RequestMapping("/feign")
public class FeignController {
@Autowired
private UserFacade userFacade;
@GetMapping("/user/{id}")
public User getUser(@PathVariable("id") Long id) {
return userFacade.getUser(id);
}
@GetMapping("/users/{timeout}")
public List<User> getUsers(@PathVariable("timeout") Long timeout) {
long start = System.currentTimeMillis();
try {
return userFacade.getUsers(timeout);
} finally {
System.out.println("cost: " + (System.currentTimeMillis() - start) / 1000);
}
}
@GetMapping("/all-users/{timeout}")
public List<User> getAllUsers(@PathVariable("timeout") Long timeout) {
long start = System.currentTimeMillis();
try {
Future<List<User>> users = userFacade.getAllUsers(timeout).queue();
ThreadUtil.sleep(1000);
try {
return users.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
} finally {
System.out.println("cost: " + (System.currentTimeMillis() - start) / 1000);
}
}
}
| UTF-8 | Java | 1,721 | java | FeignController.java | Java | []
| null | []
| package com.spring.cloud.fund.controller;
import com.spring.cloud.common.util.ThreadUtil;
import com.spring.cloud.common.vo.User;
import com.spring.cloud.fund.facade.UserFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.concurrent.Future;
@RestController
@RequestMapping("/feign")
public class FeignController {
@Autowired
private UserFacade userFacade;
@GetMapping("/user/{id}")
public User getUser(@PathVariable("id") Long id) {
return userFacade.getUser(id);
}
@GetMapping("/users/{timeout}")
public List<User> getUsers(@PathVariable("timeout") Long timeout) {
long start = System.currentTimeMillis();
try {
return userFacade.getUsers(timeout);
} finally {
System.out.println("cost: " + (System.currentTimeMillis() - start) / 1000);
}
}
@GetMapping("/all-users/{timeout}")
public List<User> getAllUsers(@PathVariable("timeout") Long timeout) {
long start = System.currentTimeMillis();
try {
Future<List<User>> users = userFacade.getAllUsers(timeout).queue();
ThreadUtil.sleep(1000);
try {
return users.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
} finally {
System.out.println("cost: " + (System.currentTimeMillis() - start) / 1000);
}
}
}
| 1,721 | 0.661243 | 0.654271 | 52 | 32.096153 | 24.675011 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.423077 | false | false | 4 |
b8b2e4b491691e61720143177e9f1bc3bfbeb8a4 | 19,877,108,709,726 | fd375d7579e946d5bd7eb95a3cca520a81b99f46 | /core/src/com/deeep/mblobber/entities/SplashActor.java | cabfa46f9037f662ff92ca85fe7511376c7b0f89 | []
| no_license | Kruhlmann/MegaBlobber | https://github.com/Kruhlmann/MegaBlobber | 2b9822a901309e405df5450c9b5870d831456be8 | 166058b8cb00e11243753fed159abf1c799a98b0 | refs/heads/master | 2021-01-12T09:04:22.364000 | 2020-07-16T22:34:31 | 2020-07-16T22:34:31 | 76,755,532 | 1 | 0 | null | true | 2020-07-16T22:34:33 | 2016-12-18T00:51:49 | 2020-02-21T11:24:10 | 2020-07-16T22:34:32 | 7,684 | 1 | 0 | 0 | Java | false | false | package com.deeep.mblobber.entities;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.actions.SequenceAction;
import com.badlogic.gdx.utils.Array;
import com.deeep.mblobber.AbstractGame;
/**
* Created by scanevaro on 09/12/2014.
*/
public class SplashActor extends Actor {
private Animation animation;
public float stateTime;
public SplashActor() {
Array<TextureAtlas.AtlasRegion> atlasRegions = new TextureAtlas(Gdx.files.internal("data/newLogo.pack")).getRegions();
animation = new Animation(0.5f, atlasRegions);
setActions();
stateTime = 0;
}
private void setActions() {
SequenceAction secAction = new SequenceAction();
secAction.addAction(Actions.fadeIn(0.5f));
// secAction.addAction(Actions.delay(2.5f));
// secAction.addAction(Actions.fadeOut(0.5f));
addAction(secAction);
}
@Override
public void draw(Batch batch, float parentAlpha) {
Color color = new Color(getColor().r, getColor().g,
getColor().b, getColor().a * parentAlpha);
batch.setColor(color);
batch.draw(animation.getKeyFrame(stateTime), 0, 55, AbstractGame.VIRTUAL_WIDTH, AbstractGame.VIRTUAL_HEIGHT - 55);
}
@Override
public void act(float delta) {
super.act(delta);
stateTime += delta;
}
} | UTF-8 | Java | 1,651 | java | SplashActor.java | Java | [
{
"context": "om.deeep.mblobber.AbstractGame;\n\n/**\n * Created by scanevaro on 09/12/2014.\n */\npublic class SplashActor exten",
"end": 520,
"score": 0.9996157288551331,
"start": 511,
"tag": "USERNAME",
"value": "scanevaro"
}
]
| null | []
| package com.deeep.mblobber.entities;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.actions.SequenceAction;
import com.badlogic.gdx.utils.Array;
import com.deeep.mblobber.AbstractGame;
/**
* Created by scanevaro on 09/12/2014.
*/
public class SplashActor extends Actor {
private Animation animation;
public float stateTime;
public SplashActor() {
Array<TextureAtlas.AtlasRegion> atlasRegions = new TextureAtlas(Gdx.files.internal("data/newLogo.pack")).getRegions();
animation = new Animation(0.5f, atlasRegions);
setActions();
stateTime = 0;
}
private void setActions() {
SequenceAction secAction = new SequenceAction();
secAction.addAction(Actions.fadeIn(0.5f));
// secAction.addAction(Actions.delay(2.5f));
// secAction.addAction(Actions.fadeOut(0.5f));
addAction(secAction);
}
@Override
public void draw(Batch batch, float parentAlpha) {
Color color = new Color(getColor().r, getColor().g,
getColor().b, getColor().a * parentAlpha);
batch.setColor(color);
batch.draw(animation.getKeyFrame(stateTime), 0, 55, AbstractGame.VIRTUAL_WIDTH, AbstractGame.VIRTUAL_HEIGHT - 55);
}
@Override
public void act(float delta) {
super.act(delta);
stateTime += delta;
}
} | 1,651 | 0.69473 | 0.677771 | 54 | 29.592592 | 27.598658 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 4 |
3491c893446207ed1bafc6ffe6ead942d97cf76c | 4,621,384,874,536 | 515b70bb0db7413716fac0fa8ead6667d2ad69b7 | /spk-cdi-persistencia/src/main/java/spk/persistencia/dao/sistema/ViewDao.java | 0b4f652227ae9028c3bdf531610b7153c1e25450 | []
| no_license | danielsava/spk-cdi | https://github.com/danielsava/spk-cdi | 096cf63c41c3a069662ffef200415698ed1dd339 | d6bfd8ff483b59445380f4f484386beee89bb54b | refs/heads/master | 2016-09-16T19:31:19.114000 | 2016-09-13T22:49:56 | 2016-09-13T22:49:56 | 40,675,472 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package spk.persistencia.dao.sistema;
import java.util.List;
import org.apache.deltaspike.data.api.Repository;
import com.querydsl.jpa.impl.JPAQuery;
import spk.persistencia.dao.PersistenciaSISTEMA;
import spk.persistencia.entidade.sistema.Funcionalidade;
import spk.persistencia.entidade.sistema.QFuncionalidade;
import spk.persistencia.entidade.sistema.QFuncionalidadeView;
import spk.persistencia.entidade.sistema.QView;
import spk.persistencia.entidade.sistema.View;
@Repository
public abstract class ViewDao extends PersistenciaSISTEMA<View> {
private QView qView = QView.view;
private QFuncionalidadeView qFuncionalidadeView = QFuncionalidadeView.funcionalidadeView;
public ViewDao() {
super(QView.view);
}
public List<Funcionalidade> consultarFuncionalidadesDaView(Long idView) {
JPAQuery<Funcionalidade> query = new JPAQuery<Funcionalidade>(getEntityManager());
return query.select(QFuncionalidade.funcionalidade).from(qFuncionalidadeView).where(qFuncionalidadeView.view.id.eq(idView)).fetch();
}
public View consultarPorIdComFuncionalidades(Long id) {
return queryPorGrafoWhere(View.GRAPH_FUNCIONALIDADESVIEW, qView.id.eq(id)).fetchOne();
}
public List<View> consultarPorLabelOuControllerContem(String labelController) {
return jpaQueryWhere(qView.label.containsIgnoreCase(labelController).or(qView.controller.containsIgnoreCase(labelController))).fetch();
}
public View consultarPorLabel(String label) {
return jpaQueryWhere(qView.label.eq(label)).fetchOne();
}
public View consultarPorLabelAndIdDiferente(String label, Long id) {
return jpaQueryWhere(qView.label.eq(label), qView.id.ne(id)).fetchOne();
}
}
| UTF-8 | Java | 1,716 | java | ViewDao.java | Java | []
| null | []
| package spk.persistencia.dao.sistema;
import java.util.List;
import org.apache.deltaspike.data.api.Repository;
import com.querydsl.jpa.impl.JPAQuery;
import spk.persistencia.dao.PersistenciaSISTEMA;
import spk.persistencia.entidade.sistema.Funcionalidade;
import spk.persistencia.entidade.sistema.QFuncionalidade;
import spk.persistencia.entidade.sistema.QFuncionalidadeView;
import spk.persistencia.entidade.sistema.QView;
import spk.persistencia.entidade.sistema.View;
@Repository
public abstract class ViewDao extends PersistenciaSISTEMA<View> {
private QView qView = QView.view;
private QFuncionalidadeView qFuncionalidadeView = QFuncionalidadeView.funcionalidadeView;
public ViewDao() {
super(QView.view);
}
public List<Funcionalidade> consultarFuncionalidadesDaView(Long idView) {
JPAQuery<Funcionalidade> query = new JPAQuery<Funcionalidade>(getEntityManager());
return query.select(QFuncionalidade.funcionalidade).from(qFuncionalidadeView).where(qFuncionalidadeView.view.id.eq(idView)).fetch();
}
public View consultarPorIdComFuncionalidades(Long id) {
return queryPorGrafoWhere(View.GRAPH_FUNCIONALIDADESVIEW, qView.id.eq(id)).fetchOne();
}
public List<View> consultarPorLabelOuControllerContem(String labelController) {
return jpaQueryWhere(qView.label.containsIgnoreCase(labelController).or(qView.controller.containsIgnoreCase(labelController))).fetch();
}
public View consultarPorLabel(String label) {
return jpaQueryWhere(qView.label.eq(label)).fetchOne();
}
public View consultarPorLabelAndIdDiferente(String label, Long id) {
return jpaQueryWhere(qView.label.eq(label), qView.id.ne(id)).fetchOne();
}
}
| 1,716 | 0.786713 | 0.786713 | 48 | 33.75 | 36.598328 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.208333 | false | false | 4 |
189d7e842acd61afbc452278a3907f788b36da34 | 9,148,280,389,207 | f7b7446975d8083765fd7f729d271b38846de206 | /数据库/shardingsphere-proxy/hmily-demo-springcloud/hmily-demo-order/src/main/java/pers/cocoadel/learning/hmily/order/client/ProductClient.java | 929ab6741affb138a1d88daae612b99013333b8f | []
| no_license | RONAN718/javalearn | https://github.com/RONAN718/javalearn | 295bfc900820966ba497cc996b6f5f877a4cf797 | c4f7700e3530918277c7867289e7dc2936716263 | refs/heads/master | 2023-08-25T18:21:00.944000 | 2021-10-11T09:59:40 | 2021-10-11T09:59:40 | 379,184,646 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pers.cocoadel.learning.hmily.order.client;
import org.dromara.hmily.annotation.Hmily;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import pers.cocoadel.learning.hmily.order.domain.Order;
import pers.cocoadel.learning.hmily.order.domain.Product;
@FeignClient(value = "CLOUD-PRODUCT")
public interface ProductClient {
@Hmily
@PostMapping("products/update_stock_by_order")
void updateProduct(@RequestBody Order order);
@GetMapping("products/{productId}")
Product findById(@PathVariable("productId") Long productId);
}
| UTF-8 | Java | 798 | java | ProductClient.java | Java | []
| null | []
| package pers.cocoadel.learning.hmily.order.client;
import org.dromara.hmily.annotation.Hmily;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import pers.cocoadel.learning.hmily.order.domain.Order;
import pers.cocoadel.learning.hmily.order.domain.Product;
@FeignClient(value = "CLOUD-PRODUCT")
public interface ProductClient {
@Hmily
@PostMapping("products/update_stock_by_order")
void updateProduct(@RequestBody Order order);
@GetMapping("products/{productId}")
Product findById(@PathVariable("productId") Long productId);
}
| 798 | 0.807018 | 0.807018 | 21 | 37 | 23.656269 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52381 | false | false | 4 |
aac2b81ed5126c5b44bd07fca4793b8a0f7caa44 | 25,555,055,462,132 | 44ec9e97504d29c45f836aadfd40298329612b63 | /archive/unsorted/2014/2014.07/2014.07.06 - Codeforces Round #254 (Div. 2)/TaskA.java | 554e1ab3c75758d8e2b094a3bac530c7ff74dffa | []
| no_license | toshif/chelper1 | https://github.com/toshif/chelper1 | bed49a6b7d7b7de053dd7109a98aacd92181c92d | 2572bb1ea1b5757c605833287b999c74109ac785 | refs/heads/master | 2021-06-12T06:47:36.962000 | 2021-04-20T20:38:16 | 2021-04-20T20:38:16 | 16,638,746 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fuku;
import java.util.Scanner;
import java.io.PrintWriter;
public class TaskA {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
in.nextLine();
for (int i = 0; i < n; i++) {
String s = in.nextLine();
char[] cs = s.toCharArray();
String os = "";
for (int j = 0; j < m; j++) {
char c = cs[j];
if (c == '-'){
os += '-';
} else {
if ((i + j) % 2 == 0){
os += "B";
} else {
os += "W";
}
}
}
out.println(os);
}
}
}
| UTF-8 | Java | 795 | java | TaskA.java | Java | []
| null | []
| package fuku;
import java.util.Scanner;
import java.io.PrintWriter;
public class TaskA {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
in.nextLine();
for (int i = 0; i < n; i++) {
String s = in.nextLine();
char[] cs = s.toCharArray();
String os = "";
for (int j = 0; j < m; j++) {
char c = cs[j];
if (c == '-'){
os += '-';
} else {
if ((i + j) % 2 == 0){
os += "B";
} else {
os += "W";
}
}
}
out.println(os);
}
}
}
| 795 | 0.337107 | 0.332075 | 33 | 23.09091 | 15.425999 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.606061 | false | false | 4 |
347ac9c4c9397e766ce87a4d9d90cd4de57b7b04 | 25,555,055,459,965 | a25f4a1bc2fd1faf61986acee6c2f844964027ee | /src/main/java/es/albarregas/servlets/Registro.java | ab5bbf1b4d283de5a8dec8c10019d17126e8b302 | []
| no_license | rodrigoglbq/PracticasAula | https://github.com/rodrigoglbq/PracticasAula | 6d269757b5486d98e1c1134cea366779fdd5c065 | 80f66297976c93fd761aeb62b66b478423722ec5 | refs/heads/master | 2020-03-30T02:23:01.713000 | 2018-10-10T10:01:07 | 2018-10-10T10:01:07 | 150,628,419 | 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 es.albarregas.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Rodrigo
*/
@WebServlet(name = "Registro", urlPatterns = {"/Registro"})
public class Registro extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<meta charset=\"UTF-8\">");
out.println("<link rel=\"stylesheet\" href=\"CSS/registroEstilo.css\">");
out.println("<title>Servlet registro</title>");
out.println("</head>");
out.println("<body>");
out.println("<ul>");
String[] error = new String[4];
if (request.getParameter("Nombre").equals("")) {
System.out.println("error nombre");
comprobar[0] = 0;
error[0] = "ERROR.Tiene que introducir un nombre.";
}
int year = Integer.parseInt(request.getParameter("Year"));
int month = Integer.parseInt(request.getParameter("Month"));
int day = Integer.parseInt(request.getParameter("Day"));
int[] meses = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
GregorianCalendar calendar = new GregorianCalendar();
if (calendar.isLeapYear(year)) {
meses[1] = 29;
System.out.println("calendario bisiesto");
}
if (meses[month] > day) {
System.out.println("comprobar fecha");
comprobar[1] = 1;
error[1] = "ERROR.Tiene que introducir una Fecha correcta";
}
if (request.getParameter("Usuario").equals("")) {
comprobar[2] = 2;
error[2] = "ERROR.Tiene que introducir un usuario.";
}
if (request.getParameter("Password").equals("")) {
comprobar[3] = 3;
error[3] = "ERROR.Tiene que introducir una contraseña";
}
if (comprobarError(request, response) == true) {
Map<String, String[]> miMapa = request.getParameterMap();
Iterator it = miMapa.entrySet().iterator();
while (it.hasNext()) {
Map.Entry e = (Map.Entry) it.next();
out.println("<li>");
out.println("<strong>" + e.getKey() + ": " + request.getParameter(e.getKey().toString()) + "</strong>");
out.println("</li>");
out.println("<br>");
}
} else {
for (String x : error) {
if (x != null) {
out.println("<h1>" + x + "</h1>");
}
}
out.println(" <form action=\"Registro\" method=\"post\">\n"
+ " <h1>Registro de Usuario</h1>\n"
+ " <fieldset>\n"
+ " <legend>Información Personal</legend>\n"
+ " <label for=\"nombre\">Nombre:</label>\n"
+ " <input type=\"text\" name=\"Nombre\" id=\"nombre\" value=" + request.getParameter("Nombre") + ">\n"
+ "\n"
+ " <br>\n"
+ " <br>\n"
+ "\n"
+ " <label for=\"apellido\">Apellidos</label>\n"
+ " <input type=\"text\" name=\"Apellidos\" id=\"apellido\" value=" + request.getParameter("Apellidos") + ">\n"
+ "\n"
+ " <br>\n"
+ " <br>\n"
+ "\n");
if (request.getParameter("Sexo") != null) {
out.println("<label for=\"sexo\">Sexo:</label> \n"
+ "\n"
+ " <label for=\"hombre\">Hombre</label>\n"
+ " <input type=\"radio\" name=\"Sexo\" id=\"sexo\" value=\"Hombre\" checked>\n"
+ "\n"
+ " <label for=\"sexo\">Mujer</label>\n"
+ " <input type=\"radio\" name=\"Sexo\" id=\"sexo\" value=\"Mujer\" checked>\n"
+ "\n"
+ " <br>\n"
+ " <br>\n"
+ "\n");
} else {
out.println("<label for=\"sexo\">Sexo:</label> \n"
+ "\n"
+ " <label for=\"hombre\">Hombre</label>\n"
+ " <input type=\"radio\" name=\"Sexo\" id=\"sexo\" value=\"Hombre\">\n"
+ "\n"
+ " <label for=\"sexo\">Mujer</label>\n"
+ " <input type=\"radio\" name=\"Sexo\" id=\"sexo\" value=\"Mujer\">\n"
+ "\n"
+ " <br>\n"
+ " <br>\n"
+ "\n");
}//Fin else
out.println("<label for=\"dia\">Fecha de Nacimineto</label>\n"
+ " <select name=\"Day\" id=\"dia\">\n"
+ " <option value=\"1\">1</option>\n"
+ " <option value=\"2\">2</option>\n"
+ " <option value=\"3\">3</option>\n"
+ " <option value=\"4\">4</option>\n"
+ " <option value=\"5\">5</option>\n"
+ " <option value=\"6\">6</option>\n"
+ " <option value=\"7\">7</option>\n"
+ " <option value=\"8\">8</option>\n"
+ " <option value=\"9\">9</option>\n"
+ " <option value=\"10\">10</option>\n"
+ " <option value=\"11\">11</option>\n"
+ " <option value=\"12\">12</option>\n"
+ " <option value=\"13\">13</option>\n"
+ " <option value=\"14\">14</option>\n"
+ " <option value=\"15\">15</option>\n"
+ " <option value=\"16\">16</option>\n"
+ " <option value=\"17\">17</option>\n"
+ " <option value=\"18\">18</option>\n"
+ " <option value=\"19\">19</option>\n"
+ " <option value=\"20\">20</option>\n"
+ " <option value=\"21\">21</option>\n"
+ " <option value=\"22\">22</option>\n"
+ " <option value=\"23\">23</option>\n"
+ " <option value=\"24\">24</option>\n"
+ " <option value=\"25\">25</option>\n"
+ " <option value=\"26\">26</option>\n"
+ " <option value=\"27\">27</option>\n"
+ " <option value=\"28\">28</option>\n"
+ " <option value=\"29\">29</option>\n"
+ " <option value=\"30\">30</option>\n"
+ " <option value=\"31\">31</option>\n"
+ " </select>\n"
+ "\n"
+ " <select name=\"Month\" id=\"mes\">\n"
+ " <option value=\"Enero\">Enero</option>\n"
+ " <option value=\"Febrero\">Febrero</option>\n"
+ " <option value=\"Marzo\">Marzo</option>\n"
+ " <option value=\"Abril\">Abril</option>\n"
+ " <option value=\"Mayo\">Mayo</option>\n"
+ " <option value=\"Junio\">Junio</option>\n"
+ " <option value=\"Julio\">Julio</option>\n"
+ " <option value=\"Agosto\">Agosto</option>\n"
+ " <option value=\"Sptiembre\">Sptiembre</option>\n"
+ " <option value=\"Octubre\">Octubre</option>\n"
+ " <option value=\"Noviembre\">Noviembre</option>\n"
+ " <option value=\"Diciembre\">Diciembre</option>\n"
+ " </select>\n"
+ "\n"
+ " <select name=\"Year\" id=\"anio\">\n"
+ " \n"
+ " <option value=\"2018\">2018</option>\n"
+ " <option value=\"2017\">2017</option>\n"
+ " <option value=\"2016\">2016</option>\n"
+ " <option value=\"2015\">2015</option>\n"
+ " <option value=\"2014\">2014</option>\n"
+ " <option value=\"2013\">2013</option>\n"
+ " <option value=\"2012\">2012</option>\n"
+ " <option value=\"2011\">2011</option>\n"
+ " <option value=\"2010\">2010</option>\n"
+ " <option value=\"2009\">2009</option>\n"
+ " <option value=\"2008\">2008</option>\n"
+ " <option value=\"2007\">2007</option>\n"
+ " <option value=\"2006\">2006</option>\n"
+ " <option value=\"2005\">2005</option>\n"
+ " <option value=\"2004\">2004</option>\n"
+ " <option value=\"2003\">2003</option>\n"
+ " <option value=\"2002\">2002</option>\n"
+ " <option value=\"2001\">2001</option>\n"
+ " <option value=\"2000\">2000</option>\n"
+ " <option value=\"1999\">1999</option>\n"
+ " <option value=\"1998\">1998</option>\n"
+ " <option value=\"1997\">1997</option>\n"
+ " <option value=\"1996\">1996</option>\n"
+ " <option value=\"1995\">1995</option>\n"
+ " <option value=\"1994\">1994</option>\n"
+ " <option value=\"1993\">1993</option>\n"
+ " <option value=\"1992\">1992</option>\n"
+ " <option value=\"1991\">1991</option>\n"
+ " <option value=\"1990\">1990</option>\n"
+ " <option value=\"1989\">1989</option>\n"
+ " <option value=\"1988\">1988</option>\n"
+ " <option value=\"1988\">1988</option>\n"
+ " <option value=\"1987\">1987</option>\n"
+ " <option value=\"1986\">1986</option>\n"
+ " <option value=\"1985\">1985</option>\n"
+ " <option value=\"1984\">1984</option>\n"
+ " <option value=\"1983\">1983</option>\n"
+ " <option value=\"1982\">1982</option>\n"
+ " <option value=\"1981\">1981</option>\n"
+ " <option value=\"1980\">1980</option>\n"
+ " <option value=\"1979\">1979</option>\n"
+ " <option value=\"1978\">1978</option>\n"
+ " <option value=\"1977\">1977</option>\n"
+ " <option value=\"1976\">1976</option>\n"
+ " <option value=\"1975\">1975</option>\n"
+ " <option value=\"1974\">1974</option>\n"
+ " <option value=\"1973\">1973</option>\n"
+ " <option value=\"1972\">1972</option>\n"
+ " <option value=\"1971\">1971</option>\n"
+ " <option value=\"1970\">1970</option>\n"
+ " <option value=\"1969\">1969</option>\n"
+ " <option value=\"1968\">1968</option>\n"
+ " <option value=\"1967\">1967</option>\n"
+ " <option value=\"1966\">1966</option>\n"
+ " <option value=\"1965\">1965</option>\n"
+ " <option value=\"1964\">1964</option>\n"
+ " <option value=\"1963\">1963</option>\n"
+ " <option value=\"1962\">1962</option>\n"
+ " <option value=\"1961\">1961</option>\n"
+ " <option value=\"1960\">1960</option>\n"
+ " <option value=\"1959\">1959</option>\n"
+ " <option value=\"1958\">1958</option>\n"
+ " <option value=\"1957\">1957</option>\n"
+ " <option value=\"1956\">1956</option>\n"
+ " <option value=\"1955\">1955</option>\n"
+ " <option value=\"1954\">1954</option>\n"
+ " <option value=\"1953\">1953</option>\n"
+ " <option value=\"1952\">1952</option>\n"
+ " <option value=\"1951\">1951</option>\n"
+ " <option value=\"1950\">1950</option>\n"
+ " <option value=\"1949\">1949</option>\n"
+ " <option value=\"1948\">1948</option>\n"
+ " <option value=\"1947\">1947</option>\n"
+ " <option value=\"1946\">1946</option>\n"
+ " <option value=\"1945\">1945</option>\n"
+ " <option value=\"1944\">1944</option>\n"
+ " <option value=\"1943\">1943</option>\n"
+ " <option value=\"1942\">1942</option>\n"
+ " <option value=\"1941\">1941</option>\n"
+ " <option value=\"1940\">1940</option>\n"
+ " <option value=\"1939\">1939</option>\n"
+ " <option value=\"1938\">1938</option>\n"
+ " <option value=\"1937\">1937</option>\n"
+ " <option value=\"1936\">1936</option>\n"
+ " <option value=\"1935\">1935</option>\n"
+ " <option value=\"1934\">1934</option>\n"
+ " <option value=\"1933\">1933</option>\n"
+ " <option value=\"1932\">1932</option>\n"
+ " <option value=\"1931\">1931</option>\n"
+ " <option value=\"1930\">1930</option>\n"
+ " <option value=\"1929\">1929</option>\n"
+ " <option value=\"1928\">1928</option>\n"
+ " \n"
+ " </select>\n"
+ " </fieldset>\n"
+ "\n"
+ " <fieldset>\n"
+ " <legend>Datos de Acceso</legend>\n"
+ "\n"
+ " <label for=\"usuario\">Usuario:</label>\n"
+ " <input type=\"text\" name=\"Usuario\" id=\"usuario\" value=" + request.getParameter("Usuario") + ">\n"
+ " <br>\n"
+ " <br>\n"
+ "\n"
+ " <label for=\"password\">Contraseña:</label>\n"
+ " <input type=\"password\" name=\"Password\" id=\"password\" value=" + request.getParameter("Password") + ">\n"
+ "\n"
+ " </fieldset>\n"
+ "\n"
+ " <fieldset>\n"
+ " <legend>Información general</legend>\n"
+ " <label for=\"preferencias\">Preferencias:</label> \n"
+ "\n"
+ " <label for=\"preferencias\">Deporte</label>\n");
if (request.getParameter("Preferencias") != null) {
out.println(" <input type=\"checkbox\" name=\"Preferencias\" id=\"preferencias\" value=\"Deporte\" checked>\n"
+ "\n"
+ " <label for=\"preferencias\">Lectura</label>\n"
+ " <input type=\"checkbox\" name=\"Preferencias\" id=\"preferencias\" value=\"Lectura\" checked>\n"
+ "\n"
+ " <label for=\"preferencias\">Cine</label>\n"
+ " <input type=\"checkbox\" name=\"Preferencias\" id=\"preferencias\" value=\"Cine\" cheked>\n"
+ "\n"
+ " <label for=\"preferencias\">Viajes</label>\n"
+ " <input type=\"checkbox\" name=\"Preferencias\" id=\"preferencias\" value=\"Viajes\" cheked>\n");
} else {
out.println(" <input type=\"checkbox\" name=\"Preferencias\" id=\"preferencias\" value=\"Deporte\" >\n"
+ "\n"
+ " <label for=\"preferencias\">Lectura</label>\n"
+ " <input type=\"checkbox\" name=\"Preferencias\" id=\"preferencias\" value=\"Lectura\" >\n"
+ "\n"
+ " <label for=\"preferencias\">Cine</label>\n"
+ " <input type=\"checkbox\" name=\"Preferencias\" id=\"preferencias\" value=\"Cine\" >\n"
+ "\n"
+ " <label for=\"preferencias\">Viajes</label>\n"
+ " <input type=\"checkbox\" name=\"Preferencias\" id=\"preferencias\" value=\"Viajes\" >\n");
}
out.println("\n"
+ " <br>\n"
+ " <br>\n"
+ " \n"
+ " <input class=\"boton\" type=\"submit\" name=\"enviar\" id=\"enviar\" value=\"Enviar\">\n"
+ " \n"
+ " \n"
+ " \n"
+ " <input class=\"boton\" type=\"reset\" name=\"limpiar\" id=\"limpiar\" value=\"Limpiar\">\n"
+ " </fieldset>\n"
+ "\n"
+ " </form>\n"
+ "");
out.println("<div class='menu'>");
out.println("<a href= index.html>Menú Principal</a>");
out.println("</div>");
}
out.println("</ul>");
out.println("</body>");
out.println("</html>");
}
}
static int[] comprobar = {-1, -1, -1, -1};
static boolean comprobarError(HttpServletRequest request, HttpServletResponse response) {
while (comprobar[0] == -1 || comprobar[1] == -1 || comprobar[2] == -1 || comprobar[3] == -1) {
}
return false;
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| UTF-8 | Java | 24,642 | java | Registro.java | Java | [
{
"context": "t.http.HttpServletResponse;\r\n\r\n/**\r\n *\r\n * @author Rodrigo\r\n */\r\n@WebServlet(name = \"Registro\", urlPatterns ",
"end": 674,
"score": 0.999785840511322,
"start": 667,
"tag": "NAME",
"value": "Rodrigo"
}
]
| 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 es.albarregas.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Rodrigo
*/
@WebServlet(name = "Registro", urlPatterns = {"/Registro"})
public class Registro extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<meta charset=\"UTF-8\">");
out.println("<link rel=\"stylesheet\" href=\"CSS/registroEstilo.css\">");
out.println("<title>Servlet registro</title>");
out.println("</head>");
out.println("<body>");
out.println("<ul>");
String[] error = new String[4];
if (request.getParameter("Nombre").equals("")) {
System.out.println("error nombre");
comprobar[0] = 0;
error[0] = "ERROR.Tiene que introducir un nombre.";
}
int year = Integer.parseInt(request.getParameter("Year"));
int month = Integer.parseInt(request.getParameter("Month"));
int day = Integer.parseInt(request.getParameter("Day"));
int[] meses = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
GregorianCalendar calendar = new GregorianCalendar();
if (calendar.isLeapYear(year)) {
meses[1] = 29;
System.out.println("calendario bisiesto");
}
if (meses[month] > day) {
System.out.println("comprobar fecha");
comprobar[1] = 1;
error[1] = "ERROR.Tiene que introducir una Fecha correcta";
}
if (request.getParameter("Usuario").equals("")) {
comprobar[2] = 2;
error[2] = "ERROR.Tiene que introducir un usuario.";
}
if (request.getParameter("Password").equals("")) {
comprobar[3] = 3;
error[3] = "ERROR.Tiene que introducir una contraseña";
}
if (comprobarError(request, response) == true) {
Map<String, String[]> miMapa = request.getParameterMap();
Iterator it = miMapa.entrySet().iterator();
while (it.hasNext()) {
Map.Entry e = (Map.Entry) it.next();
out.println("<li>");
out.println("<strong>" + e.getKey() + ": " + request.getParameter(e.getKey().toString()) + "</strong>");
out.println("</li>");
out.println("<br>");
}
} else {
for (String x : error) {
if (x != null) {
out.println("<h1>" + x + "</h1>");
}
}
out.println(" <form action=\"Registro\" method=\"post\">\n"
+ " <h1>Registro de Usuario</h1>\n"
+ " <fieldset>\n"
+ " <legend>Información Personal</legend>\n"
+ " <label for=\"nombre\">Nombre:</label>\n"
+ " <input type=\"text\" name=\"Nombre\" id=\"nombre\" value=" + request.getParameter("Nombre") + ">\n"
+ "\n"
+ " <br>\n"
+ " <br>\n"
+ "\n"
+ " <label for=\"apellido\">Apellidos</label>\n"
+ " <input type=\"text\" name=\"Apellidos\" id=\"apellido\" value=" + request.getParameter("Apellidos") + ">\n"
+ "\n"
+ " <br>\n"
+ " <br>\n"
+ "\n");
if (request.getParameter("Sexo") != null) {
out.println("<label for=\"sexo\">Sexo:</label> \n"
+ "\n"
+ " <label for=\"hombre\">Hombre</label>\n"
+ " <input type=\"radio\" name=\"Sexo\" id=\"sexo\" value=\"Hombre\" checked>\n"
+ "\n"
+ " <label for=\"sexo\">Mujer</label>\n"
+ " <input type=\"radio\" name=\"Sexo\" id=\"sexo\" value=\"Mujer\" checked>\n"
+ "\n"
+ " <br>\n"
+ " <br>\n"
+ "\n");
} else {
out.println("<label for=\"sexo\">Sexo:</label> \n"
+ "\n"
+ " <label for=\"hombre\">Hombre</label>\n"
+ " <input type=\"radio\" name=\"Sexo\" id=\"sexo\" value=\"Hombre\">\n"
+ "\n"
+ " <label for=\"sexo\">Mujer</label>\n"
+ " <input type=\"radio\" name=\"Sexo\" id=\"sexo\" value=\"Mujer\">\n"
+ "\n"
+ " <br>\n"
+ " <br>\n"
+ "\n");
}//Fin else
out.println("<label for=\"dia\">Fecha de Nacimineto</label>\n"
+ " <select name=\"Day\" id=\"dia\">\n"
+ " <option value=\"1\">1</option>\n"
+ " <option value=\"2\">2</option>\n"
+ " <option value=\"3\">3</option>\n"
+ " <option value=\"4\">4</option>\n"
+ " <option value=\"5\">5</option>\n"
+ " <option value=\"6\">6</option>\n"
+ " <option value=\"7\">7</option>\n"
+ " <option value=\"8\">8</option>\n"
+ " <option value=\"9\">9</option>\n"
+ " <option value=\"10\">10</option>\n"
+ " <option value=\"11\">11</option>\n"
+ " <option value=\"12\">12</option>\n"
+ " <option value=\"13\">13</option>\n"
+ " <option value=\"14\">14</option>\n"
+ " <option value=\"15\">15</option>\n"
+ " <option value=\"16\">16</option>\n"
+ " <option value=\"17\">17</option>\n"
+ " <option value=\"18\">18</option>\n"
+ " <option value=\"19\">19</option>\n"
+ " <option value=\"20\">20</option>\n"
+ " <option value=\"21\">21</option>\n"
+ " <option value=\"22\">22</option>\n"
+ " <option value=\"23\">23</option>\n"
+ " <option value=\"24\">24</option>\n"
+ " <option value=\"25\">25</option>\n"
+ " <option value=\"26\">26</option>\n"
+ " <option value=\"27\">27</option>\n"
+ " <option value=\"28\">28</option>\n"
+ " <option value=\"29\">29</option>\n"
+ " <option value=\"30\">30</option>\n"
+ " <option value=\"31\">31</option>\n"
+ " </select>\n"
+ "\n"
+ " <select name=\"Month\" id=\"mes\">\n"
+ " <option value=\"Enero\">Enero</option>\n"
+ " <option value=\"Febrero\">Febrero</option>\n"
+ " <option value=\"Marzo\">Marzo</option>\n"
+ " <option value=\"Abril\">Abril</option>\n"
+ " <option value=\"Mayo\">Mayo</option>\n"
+ " <option value=\"Junio\">Junio</option>\n"
+ " <option value=\"Julio\">Julio</option>\n"
+ " <option value=\"Agosto\">Agosto</option>\n"
+ " <option value=\"Sptiembre\">Sptiembre</option>\n"
+ " <option value=\"Octubre\">Octubre</option>\n"
+ " <option value=\"Noviembre\">Noviembre</option>\n"
+ " <option value=\"Diciembre\">Diciembre</option>\n"
+ " </select>\n"
+ "\n"
+ " <select name=\"Year\" id=\"anio\">\n"
+ " \n"
+ " <option value=\"2018\">2018</option>\n"
+ " <option value=\"2017\">2017</option>\n"
+ " <option value=\"2016\">2016</option>\n"
+ " <option value=\"2015\">2015</option>\n"
+ " <option value=\"2014\">2014</option>\n"
+ " <option value=\"2013\">2013</option>\n"
+ " <option value=\"2012\">2012</option>\n"
+ " <option value=\"2011\">2011</option>\n"
+ " <option value=\"2010\">2010</option>\n"
+ " <option value=\"2009\">2009</option>\n"
+ " <option value=\"2008\">2008</option>\n"
+ " <option value=\"2007\">2007</option>\n"
+ " <option value=\"2006\">2006</option>\n"
+ " <option value=\"2005\">2005</option>\n"
+ " <option value=\"2004\">2004</option>\n"
+ " <option value=\"2003\">2003</option>\n"
+ " <option value=\"2002\">2002</option>\n"
+ " <option value=\"2001\">2001</option>\n"
+ " <option value=\"2000\">2000</option>\n"
+ " <option value=\"1999\">1999</option>\n"
+ " <option value=\"1998\">1998</option>\n"
+ " <option value=\"1997\">1997</option>\n"
+ " <option value=\"1996\">1996</option>\n"
+ " <option value=\"1995\">1995</option>\n"
+ " <option value=\"1994\">1994</option>\n"
+ " <option value=\"1993\">1993</option>\n"
+ " <option value=\"1992\">1992</option>\n"
+ " <option value=\"1991\">1991</option>\n"
+ " <option value=\"1990\">1990</option>\n"
+ " <option value=\"1989\">1989</option>\n"
+ " <option value=\"1988\">1988</option>\n"
+ " <option value=\"1988\">1988</option>\n"
+ " <option value=\"1987\">1987</option>\n"
+ " <option value=\"1986\">1986</option>\n"
+ " <option value=\"1985\">1985</option>\n"
+ " <option value=\"1984\">1984</option>\n"
+ " <option value=\"1983\">1983</option>\n"
+ " <option value=\"1982\">1982</option>\n"
+ " <option value=\"1981\">1981</option>\n"
+ " <option value=\"1980\">1980</option>\n"
+ " <option value=\"1979\">1979</option>\n"
+ " <option value=\"1978\">1978</option>\n"
+ " <option value=\"1977\">1977</option>\n"
+ " <option value=\"1976\">1976</option>\n"
+ " <option value=\"1975\">1975</option>\n"
+ " <option value=\"1974\">1974</option>\n"
+ " <option value=\"1973\">1973</option>\n"
+ " <option value=\"1972\">1972</option>\n"
+ " <option value=\"1971\">1971</option>\n"
+ " <option value=\"1970\">1970</option>\n"
+ " <option value=\"1969\">1969</option>\n"
+ " <option value=\"1968\">1968</option>\n"
+ " <option value=\"1967\">1967</option>\n"
+ " <option value=\"1966\">1966</option>\n"
+ " <option value=\"1965\">1965</option>\n"
+ " <option value=\"1964\">1964</option>\n"
+ " <option value=\"1963\">1963</option>\n"
+ " <option value=\"1962\">1962</option>\n"
+ " <option value=\"1961\">1961</option>\n"
+ " <option value=\"1960\">1960</option>\n"
+ " <option value=\"1959\">1959</option>\n"
+ " <option value=\"1958\">1958</option>\n"
+ " <option value=\"1957\">1957</option>\n"
+ " <option value=\"1956\">1956</option>\n"
+ " <option value=\"1955\">1955</option>\n"
+ " <option value=\"1954\">1954</option>\n"
+ " <option value=\"1953\">1953</option>\n"
+ " <option value=\"1952\">1952</option>\n"
+ " <option value=\"1951\">1951</option>\n"
+ " <option value=\"1950\">1950</option>\n"
+ " <option value=\"1949\">1949</option>\n"
+ " <option value=\"1948\">1948</option>\n"
+ " <option value=\"1947\">1947</option>\n"
+ " <option value=\"1946\">1946</option>\n"
+ " <option value=\"1945\">1945</option>\n"
+ " <option value=\"1944\">1944</option>\n"
+ " <option value=\"1943\">1943</option>\n"
+ " <option value=\"1942\">1942</option>\n"
+ " <option value=\"1941\">1941</option>\n"
+ " <option value=\"1940\">1940</option>\n"
+ " <option value=\"1939\">1939</option>\n"
+ " <option value=\"1938\">1938</option>\n"
+ " <option value=\"1937\">1937</option>\n"
+ " <option value=\"1936\">1936</option>\n"
+ " <option value=\"1935\">1935</option>\n"
+ " <option value=\"1934\">1934</option>\n"
+ " <option value=\"1933\">1933</option>\n"
+ " <option value=\"1932\">1932</option>\n"
+ " <option value=\"1931\">1931</option>\n"
+ " <option value=\"1930\">1930</option>\n"
+ " <option value=\"1929\">1929</option>\n"
+ " <option value=\"1928\">1928</option>\n"
+ " \n"
+ " </select>\n"
+ " </fieldset>\n"
+ "\n"
+ " <fieldset>\n"
+ " <legend>Datos de Acceso</legend>\n"
+ "\n"
+ " <label for=\"usuario\">Usuario:</label>\n"
+ " <input type=\"text\" name=\"Usuario\" id=\"usuario\" value=" + request.getParameter("Usuario") + ">\n"
+ " <br>\n"
+ " <br>\n"
+ "\n"
+ " <label for=\"password\">Contraseña:</label>\n"
+ " <input type=\"password\" name=\"Password\" id=\"password\" value=" + request.getParameter("Password") + ">\n"
+ "\n"
+ " </fieldset>\n"
+ "\n"
+ " <fieldset>\n"
+ " <legend>Información general</legend>\n"
+ " <label for=\"preferencias\">Preferencias:</label> \n"
+ "\n"
+ " <label for=\"preferencias\">Deporte</label>\n");
if (request.getParameter("Preferencias") != null) {
out.println(" <input type=\"checkbox\" name=\"Preferencias\" id=\"preferencias\" value=\"Deporte\" checked>\n"
+ "\n"
+ " <label for=\"preferencias\">Lectura</label>\n"
+ " <input type=\"checkbox\" name=\"Preferencias\" id=\"preferencias\" value=\"Lectura\" checked>\n"
+ "\n"
+ " <label for=\"preferencias\">Cine</label>\n"
+ " <input type=\"checkbox\" name=\"Preferencias\" id=\"preferencias\" value=\"Cine\" cheked>\n"
+ "\n"
+ " <label for=\"preferencias\">Viajes</label>\n"
+ " <input type=\"checkbox\" name=\"Preferencias\" id=\"preferencias\" value=\"Viajes\" cheked>\n");
} else {
out.println(" <input type=\"checkbox\" name=\"Preferencias\" id=\"preferencias\" value=\"Deporte\" >\n"
+ "\n"
+ " <label for=\"preferencias\">Lectura</label>\n"
+ " <input type=\"checkbox\" name=\"Preferencias\" id=\"preferencias\" value=\"Lectura\" >\n"
+ "\n"
+ " <label for=\"preferencias\">Cine</label>\n"
+ " <input type=\"checkbox\" name=\"Preferencias\" id=\"preferencias\" value=\"Cine\" >\n"
+ "\n"
+ " <label for=\"preferencias\">Viajes</label>\n"
+ " <input type=\"checkbox\" name=\"Preferencias\" id=\"preferencias\" value=\"Viajes\" >\n");
}
out.println("\n"
+ " <br>\n"
+ " <br>\n"
+ " \n"
+ " <input class=\"boton\" type=\"submit\" name=\"enviar\" id=\"enviar\" value=\"Enviar\">\n"
+ " \n"
+ " \n"
+ " \n"
+ " <input class=\"boton\" type=\"reset\" name=\"limpiar\" id=\"limpiar\" value=\"Limpiar\">\n"
+ " </fieldset>\n"
+ "\n"
+ " </form>\n"
+ "");
out.println("<div class='menu'>");
out.println("<a href= index.html>Menú Principal</a>");
out.println("</div>");
}
out.println("</ul>");
out.println("</body>");
out.println("</html>");
}
}
static int[] comprobar = {-1, -1, -1, -1};
static boolean comprobarError(HttpServletRequest request, HttpServletResponse response) {
while (comprobar[0] == -1 || comprobar[1] == -1 || comprobar[2] == -1 || comprobar[3] == -1) {
}
return false;
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| 24,642 | 0.361611 | 0.32508 | 423 | 56.2435 | 33.402336 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.271868 | false | false | 4 |
42e827e99c249d7a4721378585dd38eac7d6ca07 | 15,659,450,765,724 | f02937f930cffd1adaa6f5789ef6b94c6d729d57 | /src/main/java/com/wolffsmod/entity/monolith/EntityPorsche.java | 541885bf560757350e9aa01126558254324b9033 | [
"MIT"
]
| permissive | AntonIT99/Flans-Mod-NPC-Vehicles | https://github.com/AntonIT99/Flans-Mod-NPC-Vehicles | 6203806798a7220a29ed0aca309006175d0824f8 | 8c2c30556afe249ccf74920a0688ae3a7c8a0795 | refs/heads/1.7.10-release | 2023-08-31T17:28:01.612000 | 2023-05-16T11:31:23 | 2023-05-16T11:31:23 | 147,932,702 | 4 | 2 | null | false | 2023-09-02T19:17:59 | 2018-09-08T12:47:31 | 2023-08-09T01:34:35 | 2023-09-02T19:17:58 | 135,779 | 2 | 2 | 2 | Java | false | false | package com.wolffsmod.entity.monolith;
import com.wolffsmod.entity.EntityFlanVehicleNPC;
import net.minecraft.world.World;
public class EntityPorsche extends EntityFlanVehicleNPC
{
public EntityPorsche(World w)
{
super(w);
setSize(4.5F, 3.5F);
}
@Override
public void setupConfig()
{
setTurnSpeed(0.25F);
setDriver("0 34 0 -360 360 -5 10");
setRotatedDriverOffset("-9 0 -9");
addShootPointPrimary("10 32 0 turret");
addShootPointSecondary("30 32 7 turret sevenMM");
}
}
| UTF-8 | Java | 571 | java | EntityPorsche.java | Java | []
| null | []
| package com.wolffsmod.entity.monolith;
import com.wolffsmod.entity.EntityFlanVehicleNPC;
import net.minecraft.world.World;
public class EntityPorsche extends EntityFlanVehicleNPC
{
public EntityPorsche(World w)
{
super(w);
setSize(4.5F, 3.5F);
}
@Override
public void setupConfig()
{
setTurnSpeed(0.25F);
setDriver("0 34 0 -360 360 -5 10");
setRotatedDriverOffset("-9 0 -9");
addShootPointPrimary("10 32 0 turret");
addShootPointSecondary("30 32 7 turret sevenMM");
}
}
| 571 | 0.635727 | 0.577933 | 25 | 21.84 | 19.228479 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.44 | false | false | 4 |
6fd088ec957b47c4bbeb8eb35e41defb5abe043a | 4,681,514,404,966 | 4d273a18f377ffcf894826d96ed6731ca1c81ef6 | /Module_4/case_study/src/main/java/com/example/furama_resort/model/repository/ICustomerTypeRepository.java | dceae50d50a5ca2b22393e93e40c445e5914eb86 | []
| no_license | DucDoan95/C0221G1-DoanMinhDuc | https://github.com/DucDoan95/C0221G1-DoanMinhDuc | 069aa119d1f74f8a37e4833aab6fd22cc5bad4e9 | aa077714f1d0fda45229da83f0834812ddc91330 | refs/heads/master | 2023-07-03T03:19:49.170000 | 2021-08-03T02:48:52 | 2021-08-03T02:48:52 | 342,118,376 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.furama_resort.model.repository;
import com.example.furama_resort.model.entity.CustomerType;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ICustomerTypeRepository extends PagingAndSortingRepository<CustomerType,Integer> {
}
| UTF-8 | Java | 349 | java | ICustomerTypeRepository.java | Java | []
| null | []
| package com.example.furama_resort.model.repository;
import com.example.furama_resort.model.entity.CustomerType;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ICustomerTypeRepository extends PagingAndSortingRepository<CustomerType,Integer> {
}
| 349 | 0.868195 | 0.868195 | 9 | 37.777779 | 34.093914 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 4 |
f5e3e153a89e067834cacea9375d45270dc307a9 | 25,469,156,121,865 | e948e17b4ebfe93f774c4ed337692e74625825f2 | /src/java/com/echothree/model/control/workflow/server/logic/WorkflowEntranceLogic.java | 423336648c36fc8ffc10825c2b318d3f4b2a3031 | [
"Apache-2.0",
"Apache-1.1",
"MIT"
]
| permissive | echothreellc/echothree.git | https://github.com/echothreellc/echothree.git | b979cc5590e05b90427f012e69394d65cb6f73c9 | 71bd3de6a46c55ebbe9e09bf0ad5a29d6d2883e6 | refs/heads/master | 2020-07-18T01:54:13.702000 | 2020-07-13T01:29:21 | 2020-07-13T01:29:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // --------------------------------------------------------------------------------
// Copyright 2002-2020 Echo Three, LLC
//
// 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.echothree.model.control.workflow.server.logic;
import com.echothree.model.control.party.server.logic.PartyLogic;
import com.echothree.model.control.security.server.logic.SecurityRoleLogic;
import com.echothree.model.control.selector.server.logic.SelectorLogic;
import com.echothree.model.control.workflow.common.exception.UnknownEntranceWorkflowNameException;
import com.echothree.model.control.workflow.common.exception.UnknownEntranceWorkflowStepNameException;
import com.echothree.model.control.workflow.common.exception.UnknownWorkflowDestinationStepException;
import com.echothree.model.control.workflow.common.exception.UnknownWorkflowEntrancePartyTypeException;
import com.echothree.model.control.workflow.common.exception.UnknownWorkflowEntranceSecurityRoleException;
import com.echothree.model.control.workflow.common.exception.UnknownWorkflowEntranceSelectorException;
import com.echothree.model.control.workflow.common.exception.UnknownWorkflowEntranceStepException;
import com.echothree.model.control.workflow.common.exception.UnknownWorkflowNameException;
import com.echothree.model.control.workflow.common.exception.WorkflowMissingSecurityRoleGroupException;
import com.echothree.model.control.workflow.common.exception.WorkflowMissingSelectorTypeException;
import com.echothree.model.control.workflow.server.WorkflowControl;
import com.echothree.model.data.party.server.entity.PartyType;
import com.echothree.model.data.workflow.server.entity.Workflow;
import com.echothree.model.data.workflow.server.entity.WorkflowDestination;
import com.echothree.model.data.workflow.server.entity.WorkflowDestinationStep;
import com.echothree.model.data.workflow.server.entity.WorkflowEntrance;
import com.echothree.model.data.workflow.server.entity.WorkflowEntrancePartyType;
import com.echothree.model.data.workflow.server.entity.WorkflowEntranceSecurityRole;
import com.echothree.model.data.workflow.server.entity.WorkflowEntranceSelector;
import com.echothree.model.data.workflow.server.entity.WorkflowEntranceStep;
import com.echothree.model.data.workflow.server.entity.WorkflowStep;
import com.echothree.util.common.message.ExecutionErrors;
import com.echothree.util.server.control.BaseLogic;
import com.echothree.util.server.message.ExecutionErrorAccumulator;
import com.echothree.util.server.persistence.EntityPermission;
import com.echothree.util.server.persistence.Session;
public class WorkflowEntranceLogic
extends BaseLogic {
private WorkflowEntranceLogic() {
super();
}
private static class WorkflowEntranceLogicHolder {
static WorkflowEntranceLogic instance = new WorkflowEntranceLogic();
}
public static WorkflowEntranceLogic getInstance() {
return WorkflowEntranceLogicHolder.instance;
}
public WorkflowEntrance getWorkflowEntranceByName(final ExecutionErrorAccumulator eea, final Workflow workflow,
final String workflowEntranceName) {
var workflowControl = (WorkflowControl)Session.getModelController(WorkflowControl.class);
WorkflowEntrance workflowEntrance = workflowControl.getWorkflowEntranceByName(workflow, workflowEntranceName);
if(workflowEntrance == null) {
handleExecutionError(UnknownWorkflowNameException.class, eea, ExecutionErrors.UnknownWorkflowEntranceName.name(),
workflow.getLastDetail().getWorkflowName(), workflowEntranceName);
}
return workflowEntrance;
}
public WorkflowEntrance getWorkflowEntranceByName(final ExecutionErrorAccumulator eea, final String workflowName,
final String workflowEntranceName) {
Workflow workflow = WorkflowLogic.getInstance().getWorkflowByName(eea, workflowName);
WorkflowEntrance workflowEntrance = null;
if(eea == null || !eea.hasExecutionErrors()) {
workflowEntrance = getWorkflowEntranceByName(eea, workflow, workflowEntranceName);
}
return workflowEntrance;
}
public WorkflowEntrancePartyType getWorkflowEntrancePartyType(final ExecutionErrorAccumulator eea, final WorkflowEntrance workflowEntrance,
final PartyType partyType, final EntityPermission entityPermission) {
WorkflowEntrancePartyType workflowEntrancePartyType = null;
if(eea == null || !eea.hasExecutionErrors()) {
var workflowControl = (WorkflowControl)Session.getModelController(WorkflowControl.class);
workflowEntrancePartyType = workflowControl.getWorkflowEntrancePartyType(workflowEntrance, partyType, entityPermission);
if(workflowEntrancePartyType == null) {
var workflowEntranceDetail = workflowEntrance.getLastDetail();
handleExecutionError(UnknownWorkflowEntrancePartyTypeException.class, eea, ExecutionErrors.UnknownWorkflowEntrancePartyType.name(),
workflowEntranceDetail.getWorkflow().getLastDetail().getWorkflowName(),
workflowEntranceDetail.getWorkflowEntranceName(), partyType.getPartyTypeName());
}
}
return workflowEntrancePartyType;
}
public WorkflowEntrancePartyType getWorkflowEntrancePartyType(final ExecutionErrorAccumulator eea, final WorkflowEntrance workflowEntrance,
final PartyType partyType) {
return getWorkflowEntrancePartyType(eea, workflowEntrance, partyType, EntityPermission.READ_ONLY);
}
public WorkflowEntrancePartyType getWorkflowEntrancePartyTypeForUpdate(final ExecutionErrorAccumulator eea, final WorkflowEntrance workflowEntrance,
final PartyType partyType) {
return getWorkflowEntrancePartyType(eea, workflowEntrance, partyType, EntityPermission.READ_WRITE);
}
public WorkflowEntrancePartyType getWorkflowEntrancePartyTypeByName(final ExecutionErrorAccumulator eea, final String workflowName,
final String workflowEntranceName, final String partyTypeName, final EntityPermission entityPermission) {
var workflowEntrance = getWorkflowEntranceByName(eea, workflowName, workflowEntranceName);
var partyType = PartyLogic.getInstance().getPartyTypeByName(eea, partyTypeName);
return getWorkflowEntrancePartyType(eea, workflowEntrance, partyType, entityPermission);
}
public WorkflowEntrancePartyType getWorkflowEntrancePartyTypeByName(final ExecutionErrorAccumulator eea, final String workflowName,
final String workflowEntranceName, final String partyTypeName) {
return getWorkflowEntrancePartyTypeByName(eea, workflowName, workflowEntranceName, partyTypeName,
EntityPermission.READ_ONLY);
}
public WorkflowEntrancePartyType getWorkflowEntrancePartyTypeByNameForUpdate(final ExecutionErrorAccumulator eea, final String workflowName,
final String workflowEntranceName, final String partyTypeName) {
return getWorkflowEntrancePartyTypeByName(eea, workflowName, workflowEntranceName, partyTypeName,
EntityPermission.READ_WRITE);
}
public WorkflowEntranceSecurityRole getWorkflowEntranceSecurityRoleByName(final ExecutionErrorAccumulator eea, final String workflowName,
final String workflowEntranceName, final String partyTypeName, final String securityRoleName,
final EntityPermission entityPermission) {
var workflowEntrance = getWorkflowEntranceByName(eea, workflowName, workflowEntranceName);
var partyType = PartyLogic.getInstance().getPartyTypeByName(eea, partyTypeName);
WorkflowEntranceSecurityRole workflowEntranceSecurityRole = null;
if(eea == null || !eea.hasExecutionErrors()) {
var securityRoleGroup = workflowEntrance.getLastDetail().getWorkflow().getLastDetail().getSecurityRoleGroup();
if(securityRoleGroup != null) {
var securityRole = SecurityRoleLogic.getInstance().getSecurityRoleByName(eea, securityRoleGroup, securityRoleName);
if(eea == null || !eea.hasExecutionErrors()) {
var workflowEntrancePartyType = getWorkflowEntrancePartyType(eea, workflowEntrance, partyType);
if(eea == null || !eea.hasExecutionErrors()) {
var workflowControl = (WorkflowControl) Session.getModelController(WorkflowControl.class);
workflowEntranceSecurityRole = workflowControl.getWorkflowEntranceSecurityRole(workflowEntrancePartyType,
securityRole, entityPermission);
if(workflowEntranceSecurityRole == null) {
var workflowEntranceDetail = workflowEntrance.getLastDetail();
var securityRoleDetail = securityRole.getLastDetail();
handleExecutionError(UnknownWorkflowEntranceSecurityRoleException.class, eea, ExecutionErrors.UnknownWorkflowEntranceSecurityRole.name(),
workflowEntranceDetail.getWorkflow().getLastDetail().getWorkflowName(),
workflowEntranceDetail.getWorkflowEntranceName(), partyType.getPartyTypeName(),
securityRoleDetail.getSecurityRole().getLastDetail().getSecurityRoleName());
}
}
}
} else {
var workflowEntranceDetail = workflowEntrance.getLastDetail();
handleExecutionError(WorkflowMissingSecurityRoleGroupException.class, eea, ExecutionErrors.WorkflowMissingSecurityRoleGroup.name(),
workflowEntranceDetail.getWorkflow().getLastDetail().getWorkflowName());
}
}
return workflowEntranceSecurityRole;
}
public WorkflowEntranceSecurityRole getWorkflowEntranceSecurityRoleByName(final ExecutionErrorAccumulator eea, final String workflowName,
final String workflowEntranceName, final String partyTypeName, final String securityRoleName) {
return getWorkflowEntranceSecurityRoleByName(eea, workflowName, workflowEntranceName, partyTypeName, securityRoleName,
EntityPermission.READ_ONLY);
}
public WorkflowEntranceSecurityRole getWorkflowEntranceSecurityRoleByNameForUpdate(final ExecutionErrorAccumulator eea, final String workflowName,
final String workflowEntranceName, final String partyTypeName, final String securityRoleName) {
return getWorkflowEntranceSecurityRoleByName(eea, workflowName, workflowEntranceName, partyTypeName, securityRoleName,
EntityPermission.READ_WRITE);
}
public WorkflowEntranceSelector getWorkflowEntranceSelectorByName(final ExecutionErrorAccumulator eea, final String workflowName,
final String workflowEntranceName, final String selectorName, final EntityPermission entityPermission) {
var workflowEntrance = getWorkflowEntranceByName(eea, workflowName, workflowEntranceName);
WorkflowEntranceSelector workflowEntranceSelector = null;
if(eea == null || !eea.hasExecutionErrors()) {
var selectorType = workflowEntrance.getLastDetail().getWorkflow().getLastDetail().getSelectorType();
if(selectorType != null) {
var selector = SelectorLogic.getInstance().getSelectorByName(eea, selectorType, selectorName);
if(eea == null || !eea.hasExecutionErrors()) {
var workflowControl = (WorkflowControl) Session.getModelController(WorkflowControl.class);
workflowEntranceSelector = workflowControl.getWorkflowEntranceSelector(workflowEntrance,
selector, entityPermission);
if(workflowEntranceSelector == null) {
var workflowEntranceDetail = workflowEntrance.getLastDetail();
var selectorDetail = selector.getLastDetail();
handleExecutionError(UnknownWorkflowEntranceSelectorException.class, eea, ExecutionErrors.UnknownWorkflowEntranceSelector.name(),
workflowEntranceDetail.getWorkflow().getLastDetail().getWorkflowName(),
workflowEntranceDetail.getWorkflowEntranceName(),
selectorDetail.getSelector().getLastDetail().getSelectorName());
}
}
} else {
var workflowEntranceDetail = workflowEntrance.getLastDetail();
handleExecutionError(WorkflowMissingSelectorTypeException.class, eea, ExecutionErrors.WorkflowMissingSelectorType.name(),
workflowEntranceDetail.getWorkflow().getLastDetail().getWorkflowName());
}
}
return workflowEntranceSelector;
}
public WorkflowEntranceSelector getWorkflowEntranceSelectorByName(final ExecutionErrorAccumulator eea, final String workflowName,
final String workflowEntranceName, final String selectorName) {
return getWorkflowEntranceSelectorByName(eea, workflowName, workflowEntranceName, selectorName,
EntityPermission.READ_ONLY);
}
public WorkflowEntranceSelector getWorkflowEntranceSelectorByNameForUpdate(final ExecutionErrorAccumulator eea, final String workflowName,
final String workflowEntranceName, final String selectorName) {
return getWorkflowEntranceSelectorByName(eea, workflowName, workflowEntranceName, selectorName,
EntityPermission.READ_WRITE);
}
public WorkflowStep getEntranceWorkflowStep(final ExecutionErrorAccumulator eea, final String entranceWorkflowName,
final String entranceWorkflowStepName) {
return WorkflowStepLogic.getInstance().getWorkflowStepByName(
UnknownEntranceWorkflowNameException.class, ExecutionErrors.UnknownEntranceWorkflowName,
UnknownEntranceWorkflowStepNameException.class, ExecutionErrors.UnknownEntranceWorkflowStepName,
eea, entranceWorkflowName, entranceWorkflowStepName);
}
public WorkflowEntranceStep getWorkflowEntranceStep(final ExecutionErrorAccumulator eea,
WorkflowEntrance workflowEntrance, WorkflowStep entranceWorkflowStep) {
var workflowControl = (WorkflowControl) Session.getModelController(WorkflowControl.class);
var workflowEntranceStep = workflowControl.getWorkflowEntranceStep(workflowEntrance, entranceWorkflowStep);
if(workflowEntranceStep == null) {
var workflowEntranceDetail = workflowEntrance.getLastDetail();
var entranceWorkflowStepDetail = entranceWorkflowStep.getLastDetail();
handleExecutionError(UnknownWorkflowEntranceStepException.class, eea, ExecutionErrors.UnknownWorkflowEntranceStep.name(),
workflowEntranceDetail.getWorkflow().getLastDetail().getWorkflowName(),
workflowEntranceDetail.getWorkflowEntranceName(),
entranceWorkflowStepDetail.getWorkflow().getLastDetail().getWorkflowName(),
entranceWorkflowStepDetail.getWorkflowStepName());
}
return workflowEntranceStep;
}
public WorkflowEntranceStep getWorkflowEntranceStepByName(final ExecutionErrorAccumulator eea,
final String workflowName, final String workflowEntranceName, final String entranceWorkflowName,
final String entranceWorkflowStepName) {
var workflowEntrance = getWorkflowEntranceByName(eea, workflowName, workflowEntranceName);
var entranceWorkflowStep = getEntranceWorkflowStep(eea, entranceWorkflowName, entranceWorkflowStepName);
WorkflowEntranceStep workflowEntranceStep = null;
if(eea == null || !eea.hasExecutionErrors()) {
workflowEntranceStep = getWorkflowEntranceStep(eea, workflowEntrance, entranceWorkflowStep);
}
return workflowEntranceStep;
}
}
| UTF-8 | Java | 16,745 | java | WorkflowEntranceLogic.java | Java | []
| null | []
| // --------------------------------------------------------------------------------
// Copyright 2002-2020 Echo Three, LLC
//
// 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.echothree.model.control.workflow.server.logic;
import com.echothree.model.control.party.server.logic.PartyLogic;
import com.echothree.model.control.security.server.logic.SecurityRoleLogic;
import com.echothree.model.control.selector.server.logic.SelectorLogic;
import com.echothree.model.control.workflow.common.exception.UnknownEntranceWorkflowNameException;
import com.echothree.model.control.workflow.common.exception.UnknownEntranceWorkflowStepNameException;
import com.echothree.model.control.workflow.common.exception.UnknownWorkflowDestinationStepException;
import com.echothree.model.control.workflow.common.exception.UnknownWorkflowEntrancePartyTypeException;
import com.echothree.model.control.workflow.common.exception.UnknownWorkflowEntranceSecurityRoleException;
import com.echothree.model.control.workflow.common.exception.UnknownWorkflowEntranceSelectorException;
import com.echothree.model.control.workflow.common.exception.UnknownWorkflowEntranceStepException;
import com.echothree.model.control.workflow.common.exception.UnknownWorkflowNameException;
import com.echothree.model.control.workflow.common.exception.WorkflowMissingSecurityRoleGroupException;
import com.echothree.model.control.workflow.common.exception.WorkflowMissingSelectorTypeException;
import com.echothree.model.control.workflow.server.WorkflowControl;
import com.echothree.model.data.party.server.entity.PartyType;
import com.echothree.model.data.workflow.server.entity.Workflow;
import com.echothree.model.data.workflow.server.entity.WorkflowDestination;
import com.echothree.model.data.workflow.server.entity.WorkflowDestinationStep;
import com.echothree.model.data.workflow.server.entity.WorkflowEntrance;
import com.echothree.model.data.workflow.server.entity.WorkflowEntrancePartyType;
import com.echothree.model.data.workflow.server.entity.WorkflowEntranceSecurityRole;
import com.echothree.model.data.workflow.server.entity.WorkflowEntranceSelector;
import com.echothree.model.data.workflow.server.entity.WorkflowEntranceStep;
import com.echothree.model.data.workflow.server.entity.WorkflowStep;
import com.echothree.util.common.message.ExecutionErrors;
import com.echothree.util.server.control.BaseLogic;
import com.echothree.util.server.message.ExecutionErrorAccumulator;
import com.echothree.util.server.persistence.EntityPermission;
import com.echothree.util.server.persistence.Session;
public class WorkflowEntranceLogic
extends BaseLogic {
private WorkflowEntranceLogic() {
super();
}
private static class WorkflowEntranceLogicHolder {
static WorkflowEntranceLogic instance = new WorkflowEntranceLogic();
}
public static WorkflowEntranceLogic getInstance() {
return WorkflowEntranceLogicHolder.instance;
}
public WorkflowEntrance getWorkflowEntranceByName(final ExecutionErrorAccumulator eea, final Workflow workflow,
final String workflowEntranceName) {
var workflowControl = (WorkflowControl)Session.getModelController(WorkflowControl.class);
WorkflowEntrance workflowEntrance = workflowControl.getWorkflowEntranceByName(workflow, workflowEntranceName);
if(workflowEntrance == null) {
handleExecutionError(UnknownWorkflowNameException.class, eea, ExecutionErrors.UnknownWorkflowEntranceName.name(),
workflow.getLastDetail().getWorkflowName(), workflowEntranceName);
}
return workflowEntrance;
}
public WorkflowEntrance getWorkflowEntranceByName(final ExecutionErrorAccumulator eea, final String workflowName,
final String workflowEntranceName) {
Workflow workflow = WorkflowLogic.getInstance().getWorkflowByName(eea, workflowName);
WorkflowEntrance workflowEntrance = null;
if(eea == null || !eea.hasExecutionErrors()) {
workflowEntrance = getWorkflowEntranceByName(eea, workflow, workflowEntranceName);
}
return workflowEntrance;
}
public WorkflowEntrancePartyType getWorkflowEntrancePartyType(final ExecutionErrorAccumulator eea, final WorkflowEntrance workflowEntrance,
final PartyType partyType, final EntityPermission entityPermission) {
WorkflowEntrancePartyType workflowEntrancePartyType = null;
if(eea == null || !eea.hasExecutionErrors()) {
var workflowControl = (WorkflowControl)Session.getModelController(WorkflowControl.class);
workflowEntrancePartyType = workflowControl.getWorkflowEntrancePartyType(workflowEntrance, partyType, entityPermission);
if(workflowEntrancePartyType == null) {
var workflowEntranceDetail = workflowEntrance.getLastDetail();
handleExecutionError(UnknownWorkflowEntrancePartyTypeException.class, eea, ExecutionErrors.UnknownWorkflowEntrancePartyType.name(),
workflowEntranceDetail.getWorkflow().getLastDetail().getWorkflowName(),
workflowEntranceDetail.getWorkflowEntranceName(), partyType.getPartyTypeName());
}
}
return workflowEntrancePartyType;
}
public WorkflowEntrancePartyType getWorkflowEntrancePartyType(final ExecutionErrorAccumulator eea, final WorkflowEntrance workflowEntrance,
final PartyType partyType) {
return getWorkflowEntrancePartyType(eea, workflowEntrance, partyType, EntityPermission.READ_ONLY);
}
public WorkflowEntrancePartyType getWorkflowEntrancePartyTypeForUpdate(final ExecutionErrorAccumulator eea, final WorkflowEntrance workflowEntrance,
final PartyType partyType) {
return getWorkflowEntrancePartyType(eea, workflowEntrance, partyType, EntityPermission.READ_WRITE);
}
public WorkflowEntrancePartyType getWorkflowEntrancePartyTypeByName(final ExecutionErrorAccumulator eea, final String workflowName,
final String workflowEntranceName, final String partyTypeName, final EntityPermission entityPermission) {
var workflowEntrance = getWorkflowEntranceByName(eea, workflowName, workflowEntranceName);
var partyType = PartyLogic.getInstance().getPartyTypeByName(eea, partyTypeName);
return getWorkflowEntrancePartyType(eea, workflowEntrance, partyType, entityPermission);
}
public WorkflowEntrancePartyType getWorkflowEntrancePartyTypeByName(final ExecutionErrorAccumulator eea, final String workflowName,
final String workflowEntranceName, final String partyTypeName) {
return getWorkflowEntrancePartyTypeByName(eea, workflowName, workflowEntranceName, partyTypeName,
EntityPermission.READ_ONLY);
}
public WorkflowEntrancePartyType getWorkflowEntrancePartyTypeByNameForUpdate(final ExecutionErrorAccumulator eea, final String workflowName,
final String workflowEntranceName, final String partyTypeName) {
return getWorkflowEntrancePartyTypeByName(eea, workflowName, workflowEntranceName, partyTypeName,
EntityPermission.READ_WRITE);
}
public WorkflowEntranceSecurityRole getWorkflowEntranceSecurityRoleByName(final ExecutionErrorAccumulator eea, final String workflowName,
final String workflowEntranceName, final String partyTypeName, final String securityRoleName,
final EntityPermission entityPermission) {
var workflowEntrance = getWorkflowEntranceByName(eea, workflowName, workflowEntranceName);
var partyType = PartyLogic.getInstance().getPartyTypeByName(eea, partyTypeName);
WorkflowEntranceSecurityRole workflowEntranceSecurityRole = null;
if(eea == null || !eea.hasExecutionErrors()) {
var securityRoleGroup = workflowEntrance.getLastDetail().getWorkflow().getLastDetail().getSecurityRoleGroup();
if(securityRoleGroup != null) {
var securityRole = SecurityRoleLogic.getInstance().getSecurityRoleByName(eea, securityRoleGroup, securityRoleName);
if(eea == null || !eea.hasExecutionErrors()) {
var workflowEntrancePartyType = getWorkflowEntrancePartyType(eea, workflowEntrance, partyType);
if(eea == null || !eea.hasExecutionErrors()) {
var workflowControl = (WorkflowControl) Session.getModelController(WorkflowControl.class);
workflowEntranceSecurityRole = workflowControl.getWorkflowEntranceSecurityRole(workflowEntrancePartyType,
securityRole, entityPermission);
if(workflowEntranceSecurityRole == null) {
var workflowEntranceDetail = workflowEntrance.getLastDetail();
var securityRoleDetail = securityRole.getLastDetail();
handleExecutionError(UnknownWorkflowEntranceSecurityRoleException.class, eea, ExecutionErrors.UnknownWorkflowEntranceSecurityRole.name(),
workflowEntranceDetail.getWorkflow().getLastDetail().getWorkflowName(),
workflowEntranceDetail.getWorkflowEntranceName(), partyType.getPartyTypeName(),
securityRoleDetail.getSecurityRole().getLastDetail().getSecurityRoleName());
}
}
}
} else {
var workflowEntranceDetail = workflowEntrance.getLastDetail();
handleExecutionError(WorkflowMissingSecurityRoleGroupException.class, eea, ExecutionErrors.WorkflowMissingSecurityRoleGroup.name(),
workflowEntranceDetail.getWorkflow().getLastDetail().getWorkflowName());
}
}
return workflowEntranceSecurityRole;
}
public WorkflowEntranceSecurityRole getWorkflowEntranceSecurityRoleByName(final ExecutionErrorAccumulator eea, final String workflowName,
final String workflowEntranceName, final String partyTypeName, final String securityRoleName) {
return getWorkflowEntranceSecurityRoleByName(eea, workflowName, workflowEntranceName, partyTypeName, securityRoleName,
EntityPermission.READ_ONLY);
}
public WorkflowEntranceSecurityRole getWorkflowEntranceSecurityRoleByNameForUpdate(final ExecutionErrorAccumulator eea, final String workflowName,
final String workflowEntranceName, final String partyTypeName, final String securityRoleName) {
return getWorkflowEntranceSecurityRoleByName(eea, workflowName, workflowEntranceName, partyTypeName, securityRoleName,
EntityPermission.READ_WRITE);
}
public WorkflowEntranceSelector getWorkflowEntranceSelectorByName(final ExecutionErrorAccumulator eea, final String workflowName,
final String workflowEntranceName, final String selectorName, final EntityPermission entityPermission) {
var workflowEntrance = getWorkflowEntranceByName(eea, workflowName, workflowEntranceName);
WorkflowEntranceSelector workflowEntranceSelector = null;
if(eea == null || !eea.hasExecutionErrors()) {
var selectorType = workflowEntrance.getLastDetail().getWorkflow().getLastDetail().getSelectorType();
if(selectorType != null) {
var selector = SelectorLogic.getInstance().getSelectorByName(eea, selectorType, selectorName);
if(eea == null || !eea.hasExecutionErrors()) {
var workflowControl = (WorkflowControl) Session.getModelController(WorkflowControl.class);
workflowEntranceSelector = workflowControl.getWorkflowEntranceSelector(workflowEntrance,
selector, entityPermission);
if(workflowEntranceSelector == null) {
var workflowEntranceDetail = workflowEntrance.getLastDetail();
var selectorDetail = selector.getLastDetail();
handleExecutionError(UnknownWorkflowEntranceSelectorException.class, eea, ExecutionErrors.UnknownWorkflowEntranceSelector.name(),
workflowEntranceDetail.getWorkflow().getLastDetail().getWorkflowName(),
workflowEntranceDetail.getWorkflowEntranceName(),
selectorDetail.getSelector().getLastDetail().getSelectorName());
}
}
} else {
var workflowEntranceDetail = workflowEntrance.getLastDetail();
handleExecutionError(WorkflowMissingSelectorTypeException.class, eea, ExecutionErrors.WorkflowMissingSelectorType.name(),
workflowEntranceDetail.getWorkflow().getLastDetail().getWorkflowName());
}
}
return workflowEntranceSelector;
}
public WorkflowEntranceSelector getWorkflowEntranceSelectorByName(final ExecutionErrorAccumulator eea, final String workflowName,
final String workflowEntranceName, final String selectorName) {
return getWorkflowEntranceSelectorByName(eea, workflowName, workflowEntranceName, selectorName,
EntityPermission.READ_ONLY);
}
public WorkflowEntranceSelector getWorkflowEntranceSelectorByNameForUpdate(final ExecutionErrorAccumulator eea, final String workflowName,
final String workflowEntranceName, final String selectorName) {
return getWorkflowEntranceSelectorByName(eea, workflowName, workflowEntranceName, selectorName,
EntityPermission.READ_WRITE);
}
public WorkflowStep getEntranceWorkflowStep(final ExecutionErrorAccumulator eea, final String entranceWorkflowName,
final String entranceWorkflowStepName) {
return WorkflowStepLogic.getInstance().getWorkflowStepByName(
UnknownEntranceWorkflowNameException.class, ExecutionErrors.UnknownEntranceWorkflowName,
UnknownEntranceWorkflowStepNameException.class, ExecutionErrors.UnknownEntranceWorkflowStepName,
eea, entranceWorkflowName, entranceWorkflowStepName);
}
public WorkflowEntranceStep getWorkflowEntranceStep(final ExecutionErrorAccumulator eea,
WorkflowEntrance workflowEntrance, WorkflowStep entranceWorkflowStep) {
var workflowControl = (WorkflowControl) Session.getModelController(WorkflowControl.class);
var workflowEntranceStep = workflowControl.getWorkflowEntranceStep(workflowEntrance, entranceWorkflowStep);
if(workflowEntranceStep == null) {
var workflowEntranceDetail = workflowEntrance.getLastDetail();
var entranceWorkflowStepDetail = entranceWorkflowStep.getLastDetail();
handleExecutionError(UnknownWorkflowEntranceStepException.class, eea, ExecutionErrors.UnknownWorkflowEntranceStep.name(),
workflowEntranceDetail.getWorkflow().getLastDetail().getWorkflowName(),
workflowEntranceDetail.getWorkflowEntranceName(),
entranceWorkflowStepDetail.getWorkflow().getLastDetail().getWorkflowName(),
entranceWorkflowStepDetail.getWorkflowStepName());
}
return workflowEntranceStep;
}
public WorkflowEntranceStep getWorkflowEntranceStepByName(final ExecutionErrorAccumulator eea,
final String workflowName, final String workflowEntranceName, final String entranceWorkflowName,
final String entranceWorkflowStepName) {
var workflowEntrance = getWorkflowEntranceByName(eea, workflowName, workflowEntranceName);
var entranceWorkflowStep = getEntranceWorkflowStep(eea, entranceWorkflowName, entranceWorkflowStepName);
WorkflowEntranceStep workflowEntranceStep = null;
if(eea == null || !eea.hasExecutionErrors()) {
workflowEntranceStep = getWorkflowEntranceStep(eea, workflowEntrance, entranceWorkflowStep);
}
return workflowEntranceStep;
}
}
| 16,745 | 0.734368 | 0.733652 | 290 | 56.741379 | 46.254303 | 165 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.944828 | false | false | 4 |
1724e4c721befcceb0e6bcbca1d48db40b90b48f | 584,115,572,362 | e15614c1ba7d074b04b6096a78c3bb3535adcc8a | /camellia-redis-proxy-hbase/src/main/java/com/netease/nim/camellia/redis/proxy/hbase/IRedisHBaseCommandProcessor.java | 547518804a1a0ff886bd17f1980e2c0a9d3d9ff6 | [
"MIT"
]
| permissive | gspandy/camellia | https://github.com/gspandy/camellia | c5331df47af99f012dc72daf71f4b7135f826777 | a3c47acfd2b5c6762cd248f361fdf9c34f228ba0 | refs/heads/master | 2023-08-09T16:20:32.552000 | 2020-06-18T07:41:30 | 2020-06-18T07:41:30 | 275,563,671 | 3 | 1 | MIT | true | 2020-06-28T10:45:44 | 2020-06-28T10:45:43 | 2020-06-24T17:49:52 | 2020-06-18T07:44:08 | 643 | 0 | 0 | 0 | null | false | false | package com.netease.nim.camellia.redis.proxy.hbase;
import com.netease.nim.camellia.redis.proxy.enums.CommandFinder;
import com.netease.nim.camellia.redis.proxy.enums.RedisCommand;
import com.netease.nim.camellia.redis.proxy.reply.*;
/**
*
* Created by caojiajun on 2020/2/25.
*/
public interface IRedisHBaseCommandProcessor {
@CommandFinder(RedisCommand.PING)
StatusReply ping();
@CommandFinder(RedisCommand.ECHO)
BulkReply echo(byte[] echo);
/**
* 数据库
*/
@CommandFinder(RedisCommand.DEL)
IntegerReply del(byte[][] keys);
@CommandFinder(RedisCommand.EXISTS)
IntegerReply exists(byte[][] keys);
@CommandFinder(RedisCommand.TYPE)
StatusReply type(byte[] key);
@CommandFinder(RedisCommand.EXPIRE)
IntegerReply expire(byte[] key, byte[] seconds);
@CommandFinder(RedisCommand.PEXPIRE)
IntegerReply pexpire(byte[] key, byte[] millis);
@CommandFinder(RedisCommand.EXPIREAT)
IntegerReply expireat(byte[] key, byte[] timestamp);
@CommandFinder(RedisCommand.PEXPIREAT)
IntegerReply pexpireat(byte[] key, byte[] timestamp);
@CommandFinder(RedisCommand.TTL)
IntegerReply ttl(byte[] key);
@CommandFinder(RedisCommand.PTTL)
IntegerReply pttl(byte[] key);
@CommandFinder(RedisCommand.PERSIST)
IntegerReply persist(byte[] key);
/**
* 有序集合
*/
@CommandFinder(RedisCommand.ZADD)
IntegerReply zadd(byte[] key, byte[][] args);
@CommandFinder(RedisCommand.ZSCORE)
BulkReply zscore(byte[] key, byte[] member);
@CommandFinder(RedisCommand.ZINCRBY)
BulkReply zincrby(byte[] key, byte[] increment, byte[] member);
@CommandFinder(RedisCommand.ZCARD)
IntegerReply zcard(byte[] key);
@CommandFinder(RedisCommand.ZCOUNT)
IntegerReply zcount(byte[] key, byte[] min, byte[] max);
@CommandFinder(RedisCommand.ZRANGE)
MultiBulkReply zrange(byte[] key, byte[] start, byte[] stop, byte[] withscores);
@CommandFinder(RedisCommand.ZREVRANGE)
MultiBulkReply zrevrange(byte[] key, byte[] start, byte[] stop, byte[] withscores);
@CommandFinder(RedisCommand.ZRANGEBYSCORE)
MultiBulkReply zrangebyscore(byte[] key, byte[] min, byte[] max, byte[][] args);
@CommandFinder(RedisCommand.ZREVRANGEBYSCORE)
MultiBulkReply zrevrangebyscore(byte[] key, byte[] min, byte[] max, byte[][] args);
@CommandFinder(RedisCommand.ZRANGEBYLEX)
MultiBulkReply zrangebylex(byte[] key, byte[] min, byte[] max, byte[][] args);
@CommandFinder(RedisCommand.ZREVRANGEBYLEX)
MultiBulkReply zrevrangebylex(byte[] key, byte[] min, byte[] max, byte[][] args);
@CommandFinder(RedisCommand.ZREMRANGEBYRANK)
IntegerReply zremrangebyrank(byte[] key, byte[] start, byte[] stop);
@CommandFinder(RedisCommand.ZREMRANGEBYSCORE)
IntegerReply zremrangebyscore(byte[] key, byte[] min, byte[] max);
@CommandFinder(RedisCommand.ZREMRANGEBYLEX)
IntegerReply zremrangebylex(byte[] key, byte[] min, byte[] max);
@CommandFinder(RedisCommand.ZRANK)
IntegerReply zrank(byte[] key, byte[] member);
@CommandFinder(RedisCommand.ZREVRANK)
IntegerReply zrevrank(byte[] key, byte[] member);
@CommandFinder(RedisCommand.ZREM)
IntegerReply zrem(byte[] key, byte[][] members);
@CommandFinder(RedisCommand.ZLEXCOUNT)
IntegerReply zlexcount(byte[] key, byte[] min, byte[] max);
}
| UTF-8 | Java | 3,397 | java | IRedisHBaseCommandProcessor.java | Java | [
{
"context": "amellia.redis.proxy.reply.*;\n\n/**\n *\n * Created by caojiajun on 2020/2/25.\n */\npublic interface IRedisHBaseCom",
"end": 266,
"score": 0.9996399879455566,
"start": 257,
"tag": "USERNAME",
"value": "caojiajun"
}
]
| null | []
| package com.netease.nim.camellia.redis.proxy.hbase;
import com.netease.nim.camellia.redis.proxy.enums.CommandFinder;
import com.netease.nim.camellia.redis.proxy.enums.RedisCommand;
import com.netease.nim.camellia.redis.proxy.reply.*;
/**
*
* Created by caojiajun on 2020/2/25.
*/
public interface IRedisHBaseCommandProcessor {
@CommandFinder(RedisCommand.PING)
StatusReply ping();
@CommandFinder(RedisCommand.ECHO)
BulkReply echo(byte[] echo);
/**
* 数据库
*/
@CommandFinder(RedisCommand.DEL)
IntegerReply del(byte[][] keys);
@CommandFinder(RedisCommand.EXISTS)
IntegerReply exists(byte[][] keys);
@CommandFinder(RedisCommand.TYPE)
StatusReply type(byte[] key);
@CommandFinder(RedisCommand.EXPIRE)
IntegerReply expire(byte[] key, byte[] seconds);
@CommandFinder(RedisCommand.PEXPIRE)
IntegerReply pexpire(byte[] key, byte[] millis);
@CommandFinder(RedisCommand.EXPIREAT)
IntegerReply expireat(byte[] key, byte[] timestamp);
@CommandFinder(RedisCommand.PEXPIREAT)
IntegerReply pexpireat(byte[] key, byte[] timestamp);
@CommandFinder(RedisCommand.TTL)
IntegerReply ttl(byte[] key);
@CommandFinder(RedisCommand.PTTL)
IntegerReply pttl(byte[] key);
@CommandFinder(RedisCommand.PERSIST)
IntegerReply persist(byte[] key);
/**
* 有序集合
*/
@CommandFinder(RedisCommand.ZADD)
IntegerReply zadd(byte[] key, byte[][] args);
@CommandFinder(RedisCommand.ZSCORE)
BulkReply zscore(byte[] key, byte[] member);
@CommandFinder(RedisCommand.ZINCRBY)
BulkReply zincrby(byte[] key, byte[] increment, byte[] member);
@CommandFinder(RedisCommand.ZCARD)
IntegerReply zcard(byte[] key);
@CommandFinder(RedisCommand.ZCOUNT)
IntegerReply zcount(byte[] key, byte[] min, byte[] max);
@CommandFinder(RedisCommand.ZRANGE)
MultiBulkReply zrange(byte[] key, byte[] start, byte[] stop, byte[] withscores);
@CommandFinder(RedisCommand.ZREVRANGE)
MultiBulkReply zrevrange(byte[] key, byte[] start, byte[] stop, byte[] withscores);
@CommandFinder(RedisCommand.ZRANGEBYSCORE)
MultiBulkReply zrangebyscore(byte[] key, byte[] min, byte[] max, byte[][] args);
@CommandFinder(RedisCommand.ZREVRANGEBYSCORE)
MultiBulkReply zrevrangebyscore(byte[] key, byte[] min, byte[] max, byte[][] args);
@CommandFinder(RedisCommand.ZRANGEBYLEX)
MultiBulkReply zrangebylex(byte[] key, byte[] min, byte[] max, byte[][] args);
@CommandFinder(RedisCommand.ZREVRANGEBYLEX)
MultiBulkReply zrevrangebylex(byte[] key, byte[] min, byte[] max, byte[][] args);
@CommandFinder(RedisCommand.ZREMRANGEBYRANK)
IntegerReply zremrangebyrank(byte[] key, byte[] start, byte[] stop);
@CommandFinder(RedisCommand.ZREMRANGEBYSCORE)
IntegerReply zremrangebyscore(byte[] key, byte[] min, byte[] max);
@CommandFinder(RedisCommand.ZREMRANGEBYLEX)
IntegerReply zremrangebylex(byte[] key, byte[] min, byte[] max);
@CommandFinder(RedisCommand.ZRANK)
IntegerReply zrank(byte[] key, byte[] member);
@CommandFinder(RedisCommand.ZREVRANK)
IntegerReply zrevrank(byte[] key, byte[] member);
@CommandFinder(RedisCommand.ZREM)
IntegerReply zrem(byte[] key, byte[][] members);
@CommandFinder(RedisCommand.ZLEXCOUNT)
IntegerReply zlexcount(byte[] key, byte[] min, byte[] max);
}
| 3,397 | 0.707952 | 0.705882 | 109 | 30.036697 | 26.065876 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.669725 | false | false | 4 |
7afb58dedfc54d50e2d9f73842dc2bdea9c59b75 | 31,645,319,061,952 | 9d3ac0ce1a8ec784b3e401dfca65daa4bcbdf32c | /app/src/test/java/com/example/natashaford/fruitmachine/BankTest.java | c843b7b8fda3c17327d62a4336c764b167e4c17c | []
| no_license | tashaford/fruit_machine | https://github.com/tashaford/fruit_machine | 04afb1179e8b83c5486817c0f12fe5a86b02ea4a | c328fb44f46d765b15babd7e81ab32844168774c | refs/heads/master | 2020-12-03T00:35:15.075000 | 2017-07-02T20:39:43 | 2017-07-02T20:39:43 | 96,047,124 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.natashaford.fruitmachine;
import org.junit.Before;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
/**
* Created by natashaford on 30/06/2017.
*/
public class BankTest {
Bank bank;
@Before
public void before(){
bank = new Bank(20);
}
@Test
public void testGetCredit() throws Exception {
assertEquals(20, bank.getCredit());
}
@Test
public void testAddToBank() throws Exception {
bank.addToBank(1);
assertEquals(21, bank.getCredit());
}
}
| UTF-8 | Java | 565 | java | BankTest.java | Java | [
{
"context": ".framework.Assert.assertEquals;\n\n/**\n * Created by natashaford on 30/06/2017.\n */\n\npublic class BankTest {\n\n ",
"end": 177,
"score": 0.9988949298858643,
"start": 166,
"tag": "USERNAME",
"value": "natashaford"
}
]
| null | []
| package com.example.natashaford.fruitmachine;
import org.junit.Before;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
/**
* Created by natashaford on 30/06/2017.
*/
public class BankTest {
Bank bank;
@Before
public void before(){
bank = new Bank(20);
}
@Test
public void testGetCredit() throws Exception {
assertEquals(20, bank.getCredit());
}
@Test
public void testAddToBank() throws Exception {
bank.addToBank(1);
assertEquals(21, bank.getCredit());
}
}
| 565 | 0.647788 | 0.621239 | 31 | 17.225807 | 17.844688 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.354839 | false | false | 4 |
10a4e3b4de057683da5195e9fd0cff1d8ab2472f | 8,469,675,515,800 | dca6932ddded76c14fa77fc4401feb54fb2b0d3e | /mango_etl/src/main/java/com/mangocity/etl/dao/OdsCruiseUOLMapper.java | 0ae0f0f09e81599376fe08e2b32aeb7cd78be535 | []
| no_license | yjyzsl/mangocity-data | https://github.com/yjyzsl/mangocity-data | ccff8acb85b58b3287544c0bdd386e7dd3f73888 | 2e9836e7bc8af9c244ae17b8252fc20de4880a86 | refs/heads/master | 2021-01-20T21:01:06.658000 | 2017-04-07T08:11:51 | 2017-04-07T08:11:51 | 60,222,587 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mangocity.etl.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.mangocity.etl.vo.OdsCruiseUOLVo;
@Repository("odsCruiseUOLMapper")
public interface OdsCruiseUOLMapper {
/**
* 新增
* @param odsCruiseUOLVo
* @return
*/
int insert(OdsCruiseUOLVo odsCruiseUOLVo);
/**
* 批量新增
* @param odsCruiseUOLVoList
* @return
*/
int batchInsert(List<OdsCruiseUOLVo> odsCruiseUOLVoList);
/**
* 查询最大的SourceRowId
* @return
*/
int findMaxFieldValue(String fieldName);
OdsCruiseUOLVo findById(Integer id);
}
| UTF-8 | Java | 631 | java | OdsCruiseUOLMapper.java | Java | []
| null | []
| package com.mangocity.etl.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.mangocity.etl.vo.OdsCruiseUOLVo;
@Repository("odsCruiseUOLMapper")
public interface OdsCruiseUOLMapper {
/**
* 新增
* @param odsCruiseUOLVo
* @return
*/
int insert(OdsCruiseUOLVo odsCruiseUOLVo);
/**
* 批量新增
* @param odsCruiseUOLVoList
* @return
*/
int batchInsert(List<OdsCruiseUOLVo> odsCruiseUOLVoList);
/**
* 查询最大的SourceRowId
* @return
*/
int findMaxFieldValue(String fieldName);
OdsCruiseUOLVo findById(Integer id);
}
| 631 | 0.689655 | 0.689655 | 33 | 16.454546 | 17.341648 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.878788 | false | false | 4 |
3e7a8c46b87d5c32bb1129f0982ab43df9f2f400 | 13,546,326,866,272 | e152790d8b329aa28e5df42af496763568a527ec | /BasicCoreJava/src/Filehandling/User.java | b0673020633bf6f71ed585d27c494997d1c251fb | []
| no_license | ranideshmukh123/Automation011920120 | https://github.com/ranideshmukh123/Automation011920120 | e1580e78b32bd5d85e5d1ee903020071f3c683d8 | 6f698d8dddfc9673f569cbf48f9bd57cf579d19b | refs/heads/master | 2020-12-14T20:12:27.908000 | 2020-03-14T08:26:18 | 2020-03-14T08:26:18 | 234,855,222 | 0 | 0 | null | false | 2020-10-13T20:21:06 | 2020-01-19T06:56:35 | 2020-03-14T08:39:03 | 2020-10-13T20:21:05 | 44,476 | 0 | 0 | 1 | HTML | false | false | package Filehandling;
public class User {
public static void main(String[] args) {
ClassA wb= new ClassA();
ClassB sheet=wb.temp();
sheet.sum(10, 20);
wb.temp().sum(10, 20);
}
}
| UTF-8 | Java | 203 | java | User.java | Java | []
| null | []
| package Filehandling;
public class User {
public static void main(String[] args) {
ClassA wb= new ClassA();
ClassB sheet=wb.temp();
sheet.sum(10, 20);
wb.temp().sum(10, 20);
}
}
| 203 | 0.605911 | 0.566502 | 16 | 11.6875 | 12.73636 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.5625 | false | false | 4 |
083319fd34aae1896cd7c5f43f9507283b1bee9f | 22,986,664,996,853 | cf209b4404229c728581e8d4009822d3ea37b254 | /src/java/app/controller/SignServlet.java | 1a8d36c657ce3657c361d6dc07ba34f0afb1eac7 | []
| no_license | ivannaht/EnergoAuV0New | https://github.com/ivannaht/EnergoAuV0New | f6a924e51499e8449861f6703cad9c726ea76840 | e2d5108ab4c0f4d11195aa5de77a24e753997094 | refs/heads/master | 2022-08-01T17:03:39.855000 | 2020-02-27T14:06:51 | 2020-02-27T14:06:51 | 241,333,074 | 0 | 0 | null | false | 2022-06-21T02:49:19 | 2020-02-18T10:28:23 | 2020-02-27T14:07:17 | 2022-06-21T02:49:18 | 697 | 0 | 0 | 2 | Java | false | false | package app.controller;
import app.dao.entity.Building;
import app.dao.entity.Institution;
import app.dao.entity.MainIndicators;
import app.dao.repository.BuildingRepository;
import app.dao.repository.InstitutionRepository;
import app.dao.repository.MainIndicatorsRepository;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
@WebServlet("/Sign")
public class SignServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html; charset=UTF-8");
String Login = req.getParameter("Login");
String Password = req.getParameter("Password");
System.out.println(Login + Password);
//from table institution
InstitutionRepository institutionRepository = new InstitutionRepository();
Institution institution = institutionRepository.getByLoginByPassword(Login, Password);
if (institution != null) {
System.out.println("Name_of_institution: " + institution.getName_of_institution());
String LoginUser = institution.getLogin();
String PasswordUser = institution.getPassword();
String Name_of_institutionUser = institution.getName_of_institution();
String Head_of_institutionUser = institution.getHead_of_institution();
String Phone_numberUser = institution.getPhone_number();
System.out.println(LoginUser + PasswordUser + Name_of_institutionUser + Head_of_institutionUser + Phone_numberUser);
req.setAttribute("LoginUser", LoginUser);
req.setAttribute("PasswordUser", PasswordUser);
req.setAttribute("Name_of_institutionUser", Name_of_institutionUser);
req.setAttribute("Head_of_institutionUser", Head_of_institutionUser);
req.setAttribute("Phone_numberUser", Phone_numberUser);
//from table dbilding_parameters
BuildingRepository buildingRepository = new BuildingRepository();
Building building = buildingRepository.getByLogin(Login);
String LocationsUser = building.getLocations();
String SettlementUser = building.getSettlement();
String RegionUser = building.getRegion();
String Functional_purposeUser = building.getFunctional_purpose();
String Year_of_commissioningUser = building.getYear_of_commissioning();
int Number_of_floorsUser = building.getNumber_of_floors();
String Photo_main_pathUser = building.getPhoto_main_path();
int Id_numberUser = building.getId_number();
req.setAttribute("LocationsUser", LocationsUser);
req.setAttribute("SettlementUser", SettlementUser);
req.setAttribute("RegionUser", RegionUser);
req.setAttribute("Functional_purposeUser",Functional_purposeUser);
req.setAttribute("Year_of_commissioningUser", Year_of_commissioningUser);
req.setAttribute("Number_of_floorsUser", Number_of_floorsUser);
req.setAttribute("Photo_main_pathUser", Photo_main_pathUser);
req.setAttribute("Id_numberUser", Id_numberUser);
//from table main_indicators_of_energy_efficiency
MainIndicatorsRepository mainIndicatorsRepository = new MainIndicatorsRepository();
MainIndicators mainIndicators = mainIndicatorsRepository.getByLogin(Login);
double Heated_areaUser = mainIndicators.getHeated_area();
double Heated_volumeUser = mainIndicators.getHeated_volume();
double Specific_energy_consumption_kWh_for_m3User = mainIndicators.getSpecific_energy_consumption_kWh_for_m3();
double Specific_consumption_of_primery_energyUser = mainIndicators.getSpecific_consumption_of_primery_energy();
double Specific_CO2_emissionsUser = mainIndicators.getSpecific_CO2_emissions();
String Energy_efficiency_classUser = mainIndicators.getEnergy_efficiency_class();
long Image_classUser = mainIndicators.getImage_class();
Date Date_of_data_entryUser = mainIndicators.getDate_of_data_entry();
req.setAttribute("Heated_areaUser", Heated_areaUser);
req.setAttribute("Heated_volumeUser", Heated_volumeUser);
req.setAttribute("Specific_energy_consumption_kWh_for_m3User", Specific_energy_consumption_kWh_for_m3User);
req.setAttribute("Specific_consumption_of_primery_energyUser", Specific_consumption_of_primery_energyUser);
req.setAttribute("Specific_CO2_emissionsUser", Specific_CO2_emissionsUser);
req.setAttribute("Energy_efficiency_classUser", Energy_efficiency_classUser);
req.setAttribute("Image_classUser", Image_classUser);
req.setAttribute("Date_of_data_entryUser", Date_of_data_entryUser);
//set auto location
req.setAttribute("location", Locale.getDefault());
RequestDispatcher view = req.getRequestDispatcher("userpage.jsp");
view.forward(req, resp);
} else {
resp.sendRedirect("index.jsp");
}
}
}
//PrintWriter out = resp.getWriter();
//req.getRequestDispatcher("/userpage.jsp").forward(req, resp);
//resp.sendRedirect("userpage.jsp");
/* System.out.println(LoginUser+ PasswordUser+Name_of_institutionUser+Head_of_institutionUser+Phone_numberUser);*/
/* HttpSession session = req.getSession(); session.setAttribute("name", Name_of_institutionUser); */
| UTF-8 | Java | 5,957 | java | SignServlet.java | Java | [
{
"context": "ser);\n req.setAttribute(\"PasswordUser\", PasswordUser);\n req.setAttribute(\"Name_of_instituti",
"end": 2112,
"score": 0.9177712202072144,
"start": 2100,
"tag": "PASSWORD",
"value": "PasswordUser"
}
]
| null | []
| package app.controller;
import app.dao.entity.Building;
import app.dao.entity.Institution;
import app.dao.entity.MainIndicators;
import app.dao.repository.BuildingRepository;
import app.dao.repository.InstitutionRepository;
import app.dao.repository.MainIndicatorsRepository;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
@WebServlet("/Sign")
public class SignServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html; charset=UTF-8");
String Login = req.getParameter("Login");
String Password = req.getParameter("Password");
System.out.println(Login + Password);
//from table institution
InstitutionRepository institutionRepository = new InstitutionRepository();
Institution institution = institutionRepository.getByLoginByPassword(Login, Password);
if (institution != null) {
System.out.println("Name_of_institution: " + institution.getName_of_institution());
String LoginUser = institution.getLogin();
String PasswordUser = institution.getPassword();
String Name_of_institutionUser = institution.getName_of_institution();
String Head_of_institutionUser = institution.getHead_of_institution();
String Phone_numberUser = institution.getPhone_number();
System.out.println(LoginUser + PasswordUser + Name_of_institutionUser + Head_of_institutionUser + Phone_numberUser);
req.setAttribute("LoginUser", LoginUser);
req.setAttribute("PasswordUser", <PASSWORD>);
req.setAttribute("Name_of_institutionUser", Name_of_institutionUser);
req.setAttribute("Head_of_institutionUser", Head_of_institutionUser);
req.setAttribute("Phone_numberUser", Phone_numberUser);
//from table dbilding_parameters
BuildingRepository buildingRepository = new BuildingRepository();
Building building = buildingRepository.getByLogin(Login);
String LocationsUser = building.getLocations();
String SettlementUser = building.getSettlement();
String RegionUser = building.getRegion();
String Functional_purposeUser = building.getFunctional_purpose();
String Year_of_commissioningUser = building.getYear_of_commissioning();
int Number_of_floorsUser = building.getNumber_of_floors();
String Photo_main_pathUser = building.getPhoto_main_path();
int Id_numberUser = building.getId_number();
req.setAttribute("LocationsUser", LocationsUser);
req.setAttribute("SettlementUser", SettlementUser);
req.setAttribute("RegionUser", RegionUser);
req.setAttribute("Functional_purposeUser",Functional_purposeUser);
req.setAttribute("Year_of_commissioningUser", Year_of_commissioningUser);
req.setAttribute("Number_of_floorsUser", Number_of_floorsUser);
req.setAttribute("Photo_main_pathUser", Photo_main_pathUser);
req.setAttribute("Id_numberUser", Id_numberUser);
//from table main_indicators_of_energy_efficiency
MainIndicatorsRepository mainIndicatorsRepository = new MainIndicatorsRepository();
MainIndicators mainIndicators = mainIndicatorsRepository.getByLogin(Login);
double Heated_areaUser = mainIndicators.getHeated_area();
double Heated_volumeUser = mainIndicators.getHeated_volume();
double Specific_energy_consumption_kWh_for_m3User = mainIndicators.getSpecific_energy_consumption_kWh_for_m3();
double Specific_consumption_of_primery_energyUser = mainIndicators.getSpecific_consumption_of_primery_energy();
double Specific_CO2_emissionsUser = mainIndicators.getSpecific_CO2_emissions();
String Energy_efficiency_classUser = mainIndicators.getEnergy_efficiency_class();
long Image_classUser = mainIndicators.getImage_class();
Date Date_of_data_entryUser = mainIndicators.getDate_of_data_entry();
req.setAttribute("Heated_areaUser", Heated_areaUser);
req.setAttribute("Heated_volumeUser", Heated_volumeUser);
req.setAttribute("Specific_energy_consumption_kWh_for_m3User", Specific_energy_consumption_kWh_for_m3User);
req.setAttribute("Specific_consumption_of_primery_energyUser", Specific_consumption_of_primery_energyUser);
req.setAttribute("Specific_CO2_emissionsUser", Specific_CO2_emissionsUser);
req.setAttribute("Energy_efficiency_classUser", Energy_efficiency_classUser);
req.setAttribute("Image_classUser", Image_classUser);
req.setAttribute("Date_of_data_entryUser", Date_of_data_entryUser);
//set auto location
req.setAttribute("location", Locale.getDefault());
RequestDispatcher view = req.getRequestDispatcher("userpage.jsp");
view.forward(req, resp);
} else {
resp.sendRedirect("index.jsp");
}
}
}
//PrintWriter out = resp.getWriter();
//req.getRequestDispatcher("/userpage.jsp").forward(req, resp);
//resp.sendRedirect("userpage.jsp");
/* System.out.println(LoginUser+ PasswordUser+Name_of_institutionUser+Head_of_institutionUser+Phone_numberUser);*/
/* HttpSession session = req.getSession(); session.setAttribute("name", Name_of_institutionUser); */
| 5,955 | 0.709921 | 0.70841 | 114 | 51.254387 | 34.801647 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.982456 | false | false | 4 |
54ac7978a53caf8c370db490847438c2fde80787 | 33,474,975,151,300 | fd4d5acd9e50e8131c9562a11aaa3c6b3bed3321 | /0.Java/0.JavaBase/1.Demo/AdvancedCode/day18/src/com/itheima/enumdemo/Gender.java | bcd6a3962f49539ab831d109d24d8d0f88ac46cf | []
| no_license | MultiCoke/Daily | https://github.com/MultiCoke/Daily | 418cbf73b6bae39da4cd7a489cd535722a3d1044 | bc2bd16aa67650c44009a17e5b6de331eee5ef4f | refs/heads/master | 2023-02-03T12:22:44.210000 | 2020-12-19T11:37:53 | 2020-12-19T11:37:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.itheima.enumdemo;
public enum Gender {
MAN, WOMEN;
} | UTF-8 | Java | 69 | java | Gender.java | Java | []
| null | []
| package com.itheima.enumdemo;
public enum Gender {
MAN, WOMEN;
} | 69 | 0.710145 | 0.710145 | 5 | 13 | 11.153475 | 29 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 4 |
86599ee716f130edbfb9a110dfeef4f484cd8b6a | 7,267,084,695,728 | 40e46eb35f9612d99ff8d0df2b8a322391b0dabd | /p1/G15P1/src/problems/floatProblems/Problem4Float.java | ceea84cc392da9bf058d90514c435559cd70e039 | []
| no_license | yhondri/PEV | https://github.com/yhondri/PEV | 62692fd3b68349dc4392c2fdba754b9b6520a493 | d3210f3e4b34a664380dc197d2ffd1f112913f6a | refs/heads/master | 2022-12-23T12:39:10.282000 | 2020-09-28T16:26:44 | 2020-09-28T16:26:44 | 273,943,558 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package problems.floatProblems;
import base.Utils;
import crossoveralgorithm.binaryCrossover.BinaryCrossoverAlgorithm;
import crossoveralgorithm.floatCrossover.FloatCrossoverAlgorithm;
import entities.BinaryChromosome;
import entities.Configuration;
import entities.FloatChromosome;
import entities.Solution;
import mutationalgorithm.binaryMutation.BinaryMutationAlgorithm;
import mutationalgorithm.floatMutation.FloatMutationAlgorithm;
import problems.FloatProblem;
import selection.SelectionAlgorithm;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Problem4Float extends FloatProblem {
double min = 0;
double max = Math.PI;
private int geneLength;
public Problem4Float(Configuration configuration, SelectionAlgorithm selectionAlgorithm, FloatCrossoverAlgorithm crossoverAlgorithm, FloatMutationAlgorithm mutationAlgorithm, Delegate delegate) {
super(configuration, selectionAlgorithm, crossoverAlgorithm, mutationAlgorithm, delegate);
geneLength = configuration.getnValue();
}
@Override
protected FloatChromosome getRandomChromosome() {
Random random = new Random();
FloatChromosome chromosome = new FloatChromosome();
double[] chromosomeArray = new double[geneLength];
for (int i = 0; i < chromosomeArray.length; i++) {
chromosomeArray[i] = min + random.nextDouble() * (max - min);
}
chromosome.setGenes(chromosomeArray);
return chromosome;
}
@Override
protected boolean isBetterFitness(double absoluteBest, double absBest) {
return absoluteBest < absBest;
}
@Override
protected void sortPopulation(List<FloatChromosome> population) {
Collections.sort(population, Collections.reverseOrder());
}
public double compareBest(Solution solution, double absBest) {
return Math.min(solution.getBestFitness(), absBest);
}
@Override
protected double getFitness(FloatChromosome chromosome) {
List<Double> phenotypeList = getPhenotype(chromosome.getGenes());
double result = 0;
for (int i = 1; i <= configuration.getnValue(); i++) {
double value = phenotypeList.get(i - 1);
double parentesis = Math.sin(((i + 1) * Math.pow(value, 2)) / Math.PI);
result += Math.sin(value) * Math.pow(parentesis, 20);
}
return -result;
}
@Override
public String getPhenotypeRepresentation(FloatChromosome chromosome) {
List<Double> phenotypeList = getPhenotype(chromosome.getGenes());
return phenotypeList.toString();
}
@Override
protected double getMin() {
return min;
}
@Override
protected double getMax() {
return max;
}
private List<Double> getPhenotype(double[] chromosome) {
List<Double> phenotype = new ArrayList<>(configuration.getnValue());
for (int i = 0; i < configuration.getnValue(); i++) {
phenotype.add(chromosome[i]);
}
return phenotype;
}
}
| UTF-8 | Java | 3,102 | java | Problem4Float.java | Java | []
| null | []
| package problems.floatProblems;
import base.Utils;
import crossoveralgorithm.binaryCrossover.BinaryCrossoverAlgorithm;
import crossoveralgorithm.floatCrossover.FloatCrossoverAlgorithm;
import entities.BinaryChromosome;
import entities.Configuration;
import entities.FloatChromosome;
import entities.Solution;
import mutationalgorithm.binaryMutation.BinaryMutationAlgorithm;
import mutationalgorithm.floatMutation.FloatMutationAlgorithm;
import problems.FloatProblem;
import selection.SelectionAlgorithm;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Problem4Float extends FloatProblem {
double min = 0;
double max = Math.PI;
private int geneLength;
public Problem4Float(Configuration configuration, SelectionAlgorithm selectionAlgorithm, FloatCrossoverAlgorithm crossoverAlgorithm, FloatMutationAlgorithm mutationAlgorithm, Delegate delegate) {
super(configuration, selectionAlgorithm, crossoverAlgorithm, mutationAlgorithm, delegate);
geneLength = configuration.getnValue();
}
@Override
protected FloatChromosome getRandomChromosome() {
Random random = new Random();
FloatChromosome chromosome = new FloatChromosome();
double[] chromosomeArray = new double[geneLength];
for (int i = 0; i < chromosomeArray.length; i++) {
chromosomeArray[i] = min + random.nextDouble() * (max - min);
}
chromosome.setGenes(chromosomeArray);
return chromosome;
}
@Override
protected boolean isBetterFitness(double absoluteBest, double absBest) {
return absoluteBest < absBest;
}
@Override
protected void sortPopulation(List<FloatChromosome> population) {
Collections.sort(population, Collections.reverseOrder());
}
public double compareBest(Solution solution, double absBest) {
return Math.min(solution.getBestFitness(), absBest);
}
@Override
protected double getFitness(FloatChromosome chromosome) {
List<Double> phenotypeList = getPhenotype(chromosome.getGenes());
double result = 0;
for (int i = 1; i <= configuration.getnValue(); i++) {
double value = phenotypeList.get(i - 1);
double parentesis = Math.sin(((i + 1) * Math.pow(value, 2)) / Math.PI);
result += Math.sin(value) * Math.pow(parentesis, 20);
}
return -result;
}
@Override
public String getPhenotypeRepresentation(FloatChromosome chromosome) {
List<Double> phenotypeList = getPhenotype(chromosome.getGenes());
return phenotypeList.toString();
}
@Override
protected double getMin() {
return min;
}
@Override
protected double getMax() {
return max;
}
private List<Double> getPhenotype(double[] chromosome) {
List<Double> phenotype = new ArrayList<>(configuration.getnValue());
for (int i = 0; i < configuration.getnValue(); i++) {
phenotype.add(chromosome[i]);
}
return phenotype;
}
}
| 3,102 | 0.697614 | 0.693746 | 97 | 30.979382 | 31.361866 | 199 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.649485 | false | false | 4 |
b850b34c6dc8423f841fbfcd6e53ad2d133e420a | 16,578,573,808,317 | 2917b8d58a7fadf9ad660efbe5c88d408e6a3568 | /App/src/test/java/edu/lmu/cmsi/Test/GridTest.java | b025055ee5cb27a8e0397696698cea824a7e0ec5 | []
| no_license | Kygre/CMSI-281 | https://github.com/Kygre/CMSI-281 | db07654a53d7d6d5069fbb1e28acc8b28e470fee | cb02382e76cd6b488ffa731fe0d966c4b1f4405f | refs/heads/master | 2020-05-20T11:52:53.228000 | 2015-04-25T20:00:33 | 2015-04-25T20:00:33 | 24,386,067 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.lmu.cmsi.Test;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import edu.lmu.cmsi.BetterGame.Drive;
import edu.lmu.cmsi.Core.Location;
import edu.lmu.cmsi.GameEngine.Grid;
import edu.lmu.cmsi.Sprite.Actor;
import edu.lmu.cmsi.Sprite.BigMonsterA;
import edu.lmu.cmsi.Sprite.BossK;
import edu.lmu.cmsi.Sprite.Rock;
import edu.lmu.cmsi.Sprite.SmallMonsterX;
import edu.lmu.cmsi.Sprite.Sprite;
import edu.lmu.cmsi.Sprite.Tree;
import edu.lmu.cmsi.Sprite.Wall;
/**
*
* @author kygre
* Test grids initliazed to all corners and moves counter-clockwise through array
*
*/
public class GridTest {
private Grid gr;
private static Grid rockGr, treeGr, smallMGr, BigMGr, BossGr, emptyGr;
private static int size = 5;
@Rule
public ExpectedException thrown = ExpectedException.none();
@BeforeClass
public static void initAllGridCases() {
// running tests allow for Debugging
Drive.debug = true;
}
private static Sprite[] addAll(Sprite[] a , Sprite[] b){
List<Sprite> myl = new ArrayList<Sprite>();
for(Sprite a1 : a){
myl.add(a1);
}
for(Sprite b1 : b){
myl.add(b1);
}
return myl.toArray(new Sprite[a.length + b.length]);
}
private static Grid initCorners(Sprite[] myl) {
int count = 0;
for (Sprite p : myl) {
Actor a = (Actor) p;
if (!Drive.debug) {
if (count == 0) {
} else {
a.setRender("" + count);
}
}
if (count == 0) {
a.setLoc(new Location(1, 1));
} else if (count == 1) {
a.setLoc(new Location(size - 2, 1));
} else if (count == 2) {
a.setLoc(new Location(1, size - 2));
} else if (count == 3) {
a.setLoc(new Location(size - 2, size - 2));
}
count++;
}
return new Grid(size, myl);
}
// helper method to act all sprites without rendering
private void add_Act(Grid gr, Sprite[] ins) {
gr.setSprites(addAll(gr.getSprites(), ins));
gr.update();
}
@Before
public void init_Grid() {
Sprite[] myl = { new Rock(1, 1), new Rock(size - 2, size - 2),
new Rock(1, size - 2), new Rock(size - 2, 1) };
rockGr = initCorners(myl);
Sprite[] myl1 = { new Tree(0, 0), new Tree(0, 0), new Tree(0, 0),
new Tree(0, 0) };
treeGr = initCorners(myl1);
Sprite[] myl2 = { new SmallMonsterX(0, 0, 0, 0),
new SmallMonsterX(0, 0, 0, 0), new SmallMonsterX(0, 0, 0, 0),
new SmallMonsterX(0, 0, 0, 0) };
smallMGr = initCorners(myl2);
Sprite[] myl4 = { new BigMonsterA(0, 0, 0, 0),
new BigMonsterA(0, 0, 0, 0), new BigMonsterA(0, 0, 0, 0),
new BigMonsterA(0, 0, 0, 0) };
BigMGr = initCorners(myl4);
Sprite[] myl6 = { new BossK(0, 0, 0, 0), new BossK(0, 0, 0, 0),
new BossK(0, 0, 0, 0), new BossK(0, 0, 0, 0) };
BossGr = initCorners(myl6);
}
@Test
public void testSpriteOutXGrid() {
Sprite a = new Actor(-10, 0, 0, 0, "p");
Sprite b = new Actor(2, -10, 0, 0, "p1");
Sprite c = new Actor(-10, 0, 0, 0, "p2");
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("< A Sprite is not inside your created " + size + " x " + size + " grid >");
Sprite[] myl = {a,b,c};
gr = new Grid(size, myl);
}
@Test
public void testSpriteOutYGrid() {
Sprite a = new Actor(2, 2, 0, 0, "p1");
Sprite b = new Actor(2, -10, 0, 0, "p2");
Sprite c = new Actor(-10, 0, 0, 0, "p3");
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("< A Sprite is not inside your created " + size + " x " + size + " grid >");
Sprite[] myl = {a,b,c};
gr = new Grid(size, myl);
}
@Test
public void testGridCreation() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Grid size must be greater than 1");
Sprite[] myl = { new Actor(1, 1, 1, 0, "p") };
gr = new Grid(-100, myl);
}
@Test
public void testGridFailSpriteNull() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("No Sprites have been added to Grid");
gr = new Grid(10, null);
}
@Test
public void testCheckHOrizontalCollisions() {
Sprite[] myl = { new Actor(5, 5, 1, 0, "p"),
new Actor(2, 2, -1, 0, "q"), new Rock(6, 5), new Tree(1, 2) };
gr = new Grid(10, myl);
gr.update();
Assert.assertTrue("Actor P did not hit Rock",
myl[0].collidesWith(myl[2]));
Assert.assertTrue("Actor Q did not hit Tree",
myl[1].collidesWith(myl[3]));
}
@Test
public void testCheckForVerticalCollisions() {
Sprite[] myl = { new Actor(5, 5, 0, 1, "p"),
new Actor(2, 2, 0, -1, "q"), new Rock(5, 6), new Tree(2, 1) };
gr = new Grid(10, myl);
gr.update();
Assert.assertTrue("Actor P did not hit Rock",
myl[0].collidesWith(myl[2]));
Assert.assertTrue("Actor Q did not hit Tree",
myl[1].collidesWith(myl[3]));
}
@Test
public void SimpleWallCollisionHorizontal() {
Actor a = new Actor(size - 3,size -2 ,1,0, "p");
Sprite[] ins = {a};
add_Act(rockGr, ins);
// act once
rockGr.update();
// check all wall collisions
Wall[] edges = rockGr.getEdges();
for(int k = 0; k < edges.length; k++){
if(a.collidesWith(edges[k])){
Assert.assertTrue(true);
}
}
Assert.assertFalse(false);
}
// Delta checked after frame has rendered
@Test
public void CheckBigMonsterSmallMonsterNoHpCollision() {
SmallMonsterX smx = new SmallMonsterX(size - 5 , size -2, 1, 0);
Sprite[] ins = {smx};
add_Act(BigMGr, ins);
// move twice
BigMGr.update();
BigMGr.update();
// Monsters do not interact, hp should remain zero
Actor a = (Actor) smx;
Assert.assertEquals(0, smx.getHp(), 0.000);
Assert.assertEquals(0, a.getHp(), 0.000);
}
// only checks collision not Hp
@Test
public void testDiagonalCollisionPlayerMonster() {
Actor a = new Actor(2, 2, -1, -1, "p");
Sprite[] ins = {a};
add_Act(BossGr, ins);
Assert.assertTrue("Diagonal Player - Boss did not collide", a.collidesWith(BossGr.getSprites()[0]));
}
@Test
public void CollisionPlayerBigMonster() {
Actor a = new Actor(1,2,0,-1,"p");
Sprite[] ins = {a};
add_Act(BigMGr, ins);
Assert.assertTrue("Actor is not in same space as ", BigMGr.getSprites()[0].collidesWith(a));
}
}
| UTF-8 | Java | 6,523 | java | GridTest.java | Java | [
{
"context": " edu.lmu.cmsi.Sprite.Wall;\r\n\r\n/**\r\n * \r\n * @author kygre\r\n *\tTest grids initliazed to all corners and move",
"end": 694,
"score": 0.9996247291564941,
"start": 689,
"tag": "USERNAME",
"value": "kygre"
}
]
| null | []
| package edu.lmu.cmsi.Test;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import edu.lmu.cmsi.BetterGame.Drive;
import edu.lmu.cmsi.Core.Location;
import edu.lmu.cmsi.GameEngine.Grid;
import edu.lmu.cmsi.Sprite.Actor;
import edu.lmu.cmsi.Sprite.BigMonsterA;
import edu.lmu.cmsi.Sprite.BossK;
import edu.lmu.cmsi.Sprite.Rock;
import edu.lmu.cmsi.Sprite.SmallMonsterX;
import edu.lmu.cmsi.Sprite.Sprite;
import edu.lmu.cmsi.Sprite.Tree;
import edu.lmu.cmsi.Sprite.Wall;
/**
*
* @author kygre
* Test grids initliazed to all corners and moves counter-clockwise through array
*
*/
public class GridTest {
private Grid gr;
private static Grid rockGr, treeGr, smallMGr, BigMGr, BossGr, emptyGr;
private static int size = 5;
@Rule
public ExpectedException thrown = ExpectedException.none();
@BeforeClass
public static void initAllGridCases() {
// running tests allow for Debugging
Drive.debug = true;
}
private static Sprite[] addAll(Sprite[] a , Sprite[] b){
List<Sprite> myl = new ArrayList<Sprite>();
for(Sprite a1 : a){
myl.add(a1);
}
for(Sprite b1 : b){
myl.add(b1);
}
return myl.toArray(new Sprite[a.length + b.length]);
}
private static Grid initCorners(Sprite[] myl) {
int count = 0;
for (Sprite p : myl) {
Actor a = (Actor) p;
if (!Drive.debug) {
if (count == 0) {
} else {
a.setRender("" + count);
}
}
if (count == 0) {
a.setLoc(new Location(1, 1));
} else if (count == 1) {
a.setLoc(new Location(size - 2, 1));
} else if (count == 2) {
a.setLoc(new Location(1, size - 2));
} else if (count == 3) {
a.setLoc(new Location(size - 2, size - 2));
}
count++;
}
return new Grid(size, myl);
}
// helper method to act all sprites without rendering
private void add_Act(Grid gr, Sprite[] ins) {
gr.setSprites(addAll(gr.getSprites(), ins));
gr.update();
}
@Before
public void init_Grid() {
Sprite[] myl = { new Rock(1, 1), new Rock(size - 2, size - 2),
new Rock(1, size - 2), new Rock(size - 2, 1) };
rockGr = initCorners(myl);
Sprite[] myl1 = { new Tree(0, 0), new Tree(0, 0), new Tree(0, 0),
new Tree(0, 0) };
treeGr = initCorners(myl1);
Sprite[] myl2 = { new SmallMonsterX(0, 0, 0, 0),
new SmallMonsterX(0, 0, 0, 0), new SmallMonsterX(0, 0, 0, 0),
new SmallMonsterX(0, 0, 0, 0) };
smallMGr = initCorners(myl2);
Sprite[] myl4 = { new BigMonsterA(0, 0, 0, 0),
new BigMonsterA(0, 0, 0, 0), new BigMonsterA(0, 0, 0, 0),
new BigMonsterA(0, 0, 0, 0) };
BigMGr = initCorners(myl4);
Sprite[] myl6 = { new BossK(0, 0, 0, 0), new BossK(0, 0, 0, 0),
new BossK(0, 0, 0, 0), new BossK(0, 0, 0, 0) };
BossGr = initCorners(myl6);
}
@Test
public void testSpriteOutXGrid() {
Sprite a = new Actor(-10, 0, 0, 0, "p");
Sprite b = new Actor(2, -10, 0, 0, "p1");
Sprite c = new Actor(-10, 0, 0, 0, "p2");
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("< A Sprite is not inside your created " + size + " x " + size + " grid >");
Sprite[] myl = {a,b,c};
gr = new Grid(size, myl);
}
@Test
public void testSpriteOutYGrid() {
Sprite a = new Actor(2, 2, 0, 0, "p1");
Sprite b = new Actor(2, -10, 0, 0, "p2");
Sprite c = new Actor(-10, 0, 0, 0, "p3");
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("< A Sprite is not inside your created " + size + " x " + size + " grid >");
Sprite[] myl = {a,b,c};
gr = new Grid(size, myl);
}
@Test
public void testGridCreation() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Grid size must be greater than 1");
Sprite[] myl = { new Actor(1, 1, 1, 0, "p") };
gr = new Grid(-100, myl);
}
@Test
public void testGridFailSpriteNull() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("No Sprites have been added to Grid");
gr = new Grid(10, null);
}
@Test
public void testCheckHOrizontalCollisions() {
Sprite[] myl = { new Actor(5, 5, 1, 0, "p"),
new Actor(2, 2, -1, 0, "q"), new Rock(6, 5), new Tree(1, 2) };
gr = new Grid(10, myl);
gr.update();
Assert.assertTrue("Actor P did not hit Rock",
myl[0].collidesWith(myl[2]));
Assert.assertTrue("Actor Q did not hit Tree",
myl[1].collidesWith(myl[3]));
}
@Test
public void testCheckForVerticalCollisions() {
Sprite[] myl = { new Actor(5, 5, 0, 1, "p"),
new Actor(2, 2, 0, -1, "q"), new Rock(5, 6), new Tree(2, 1) };
gr = new Grid(10, myl);
gr.update();
Assert.assertTrue("Actor P did not hit Rock",
myl[0].collidesWith(myl[2]));
Assert.assertTrue("Actor Q did not hit Tree",
myl[1].collidesWith(myl[3]));
}
@Test
public void SimpleWallCollisionHorizontal() {
Actor a = new Actor(size - 3,size -2 ,1,0, "p");
Sprite[] ins = {a};
add_Act(rockGr, ins);
// act once
rockGr.update();
// check all wall collisions
Wall[] edges = rockGr.getEdges();
for(int k = 0; k < edges.length; k++){
if(a.collidesWith(edges[k])){
Assert.assertTrue(true);
}
}
Assert.assertFalse(false);
}
// Delta checked after frame has rendered
@Test
public void CheckBigMonsterSmallMonsterNoHpCollision() {
SmallMonsterX smx = new SmallMonsterX(size - 5 , size -2, 1, 0);
Sprite[] ins = {smx};
add_Act(BigMGr, ins);
// move twice
BigMGr.update();
BigMGr.update();
// Monsters do not interact, hp should remain zero
Actor a = (Actor) smx;
Assert.assertEquals(0, smx.getHp(), 0.000);
Assert.assertEquals(0, a.getHp(), 0.000);
}
// only checks collision not Hp
@Test
public void testDiagonalCollisionPlayerMonster() {
Actor a = new Actor(2, 2, -1, -1, "p");
Sprite[] ins = {a};
add_Act(BossGr, ins);
Assert.assertTrue("Diagonal Player - Boss did not collide", a.collidesWith(BossGr.getSprites()[0]));
}
@Test
public void CollisionPlayerBigMonster() {
Actor a = new Actor(1,2,0,-1,"p");
Sprite[] ins = {a};
add_Act(BigMGr, ins);
Assert.assertTrue("Actor is not in same space as ", BigMGr.getSprites()[0].collidesWith(a));
}
}
| 6,523 | 0.604783 | 0.574122 | 281 | 21.213524 | 22.106438 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.231317 | false | false | 4 |
00ca6227cdd72ca24cde927eb3288e086c841eb5 | 3,418,794,009,769 | ceb995fdfccd8d2c6dc89a893edc7290a12d08d3 | /java/src/edu/chnu/patterns/abstractFactory/LabClassFactory.java | 50865c06109cd6fe1cd8776dbf7cd734bbd37620 | []
| no_license | RustyZzZ/gof-patterns | https://github.com/RustyZzZ/gof-patterns | d14f18bfd4bf381262af43e006847c8f4c0e29c4 | 699ff3b703d82a71f01ab388ddfc9c943932ab21 | refs/heads/master | 2023-01-27T13:47:11.968000 | 2020-11-29T18:20:04 | 2020-11-29T18:20:04 | 296,455,245 | 2 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.chnu.patterns.abstractFactory;
import edu.chnu.patterns.factoryMethod.LabClass;
public class LabClassFactory extends UniversityClassFactory{
protected LabClass createClass(String subject, Integer group) {
return new LabClass(subject, group);
}
@Override
protected Log createLog() {
return new GradeLog();
}
}
| UTF-8 | Java | 333 | java | LabClassFactory.java | Java | []
| null | []
| package edu.chnu.patterns.abstractFactory;
import edu.chnu.patterns.factoryMethod.LabClass;
public class LabClassFactory extends UniversityClassFactory{
protected LabClass createClass(String subject, Integer group) {
return new LabClass(subject, group);
}
@Override
protected Log createLog() {
return new GradeLog();
}
}
| 333 | 0.786787 | 0.786787 | 14 | 22.785715 | 23.00366 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.071429 | false | false | 4 |
bb0119d918a308d2041fd0f09ef3acc0a38d1e3c | 1,099,511,670,231 | 4523bfb3d1d2c75297d2dceb582fbd63e6663633 | /app/src/main/java/com/example/placetravel/place/GalleryAdapter.java | 5d34f26fd7f08f9817e9b0451abc13a51bb9bb05 | []
| no_license | boyskylake/place-travel | https://github.com/boyskylake/place-travel | 9fc07abc288c8610f3c2e0f17e42cccccd15c464 | 8b75c9e8dc9dd9d0367906bffec48d45d90615df | refs/heads/master | 2020-04-02T01:55:15.036000 | 2018-10-20T07:42:46 | 2018-10-20T07:42:46 | 153,881,870 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.placetravel.place;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.AppCompatImageView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.placetravel.R;
import com.example.placetravel.utils.ImageUtil;
import java.util.ArrayList;
import java.util.List;
class GalleryAdapter extends PagerAdapter {
private List<String> items = new ArrayList<>();
void setItems(List<String> newItems) {
items = newItems;
notifyDataSetChanged();
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((View) object);
}
public int getItemPosition(@NonNull Object object) {
return POSITION_NONE;
}
@Override
public int getCount() {
return items.size();
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup view, int position) {
View imageLayout = LayoutInflater.from(view.getContext()).inflate(R.layout.item_gallery, view, false);
final AppCompatImageView imageView = imageLayout.findViewById(R.id.image);
ImageUtil.loadImageFirebase(items.get(position), imageView);
view.addView(imageLayout, 0);
return imageLayout;
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view.equals(object);
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
@Override
public Parcelable saveState() {
return null;
}
}
| UTF-8 | Java | 1,728 | java | GalleryAdapter.java | Java | []
| null | []
| package com.example.placetravel.place;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.AppCompatImageView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.placetravel.R;
import com.example.placetravel.utils.ImageUtil;
import java.util.ArrayList;
import java.util.List;
class GalleryAdapter extends PagerAdapter {
private List<String> items = new ArrayList<>();
void setItems(List<String> newItems) {
items = newItems;
notifyDataSetChanged();
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((View) object);
}
public int getItemPosition(@NonNull Object object) {
return POSITION_NONE;
}
@Override
public int getCount() {
return items.size();
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup view, int position) {
View imageLayout = LayoutInflater.from(view.getContext()).inflate(R.layout.item_gallery, view, false);
final AppCompatImageView imageView = imageLayout.findViewById(R.id.image);
ImageUtil.loadImageFirebase(items.get(position), imageView);
view.addView(imageLayout, 0);
return imageLayout;
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view.equals(object);
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
@Override
public Parcelable saveState() {
return null;
}
}
| 1,728 | 0.707176 | 0.70544 | 63 | 26.428572 | 26.12468 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.539683 | false | false | 4 |
9ac65ca6229c8e7cad741d5db678c583aa2ebaa1 | 9,337,258,918,064 | c3ac60dd4d1ba474666831cddf8c7e0a4dbe8b5e | /dal/src/main/java/com/xinrong/dao/bid/mapper/HistoryDataDoMapper.java | a0e540a686fa95ab7811578cee7d34c2db6390f5 | []
| no_license | happy6eve/p2p | https://github.com/happy6eve/p2p | a74d87827cb0b260292d0b8884b4f80fe52c2f49 | 37ff8706a6a8c96f2dafdcae73cca20c89f36c81 | refs/heads/master | 2018-04-06T23:22:11.850000 | 2016-11-27T06:19:54 | 2016-11-27T06:19:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xinrong.dao.bid.mapper;
import com.xinrong.base.BaseDao;
import com.xinrong.entity.bid.HistoryDataDo;
public interface HistoryDataDoMapper extends BaseDao {
int deleteByPrimaryKey(Integer id);
int insert(HistoryDataDo record);
int insertSelective(HistoryDataDo record);
HistoryDataDo selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(HistoryDataDo record);
int updateByPrimaryKey(HistoryDataDo record);
} | UTF-8 | Java | 461 | java | HistoryDataDoMapper.java | Java | []
| null | []
| package com.xinrong.dao.bid.mapper;
import com.xinrong.base.BaseDao;
import com.xinrong.entity.bid.HistoryDataDo;
public interface HistoryDataDoMapper extends BaseDao {
int deleteByPrimaryKey(Integer id);
int insert(HistoryDataDo record);
int insertSelective(HistoryDataDo record);
HistoryDataDo selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(HistoryDataDo record);
int updateByPrimaryKey(HistoryDataDo record);
} | 461 | 0.793926 | 0.793926 | 18 | 24.666666 | 22.757172 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
dc5beea780e65ebfdce928125eee3315d19a69a7 | 6,107,443,533,076 | 19535f6db821473306c855ea2b74a16928d72f13 | /a2-lixun2/src/main/java/edu/toronto/csc301/GridRobot1.java | 67b1a3f6fc9f33703e50b78867ef71b8515c044e | []
| no_license | lixun94/csc301 | https://github.com/lixun94/csc301 | 8fd38608a31c80ab66a8fa4021bb2d0232440432 | c1425fb3f3646cc38d68d45a354681e4c5c5b60a | refs/heads/master | 2020-12-20T13:30:25.118000 | 2020-01-24T22:30:06 | 2020-01-24T22:30:06 | 236,092,760 | 0 | 0 | null | false | 2020-10-13T19:03:39 | 2020-01-24T22:15:47 | 2020-01-24T22:30:39 | 2020-10-13T19:03:38 | 1,232 | 0 | 0 | 2 | Java | false | false | <<<<<<< HEAD
/**package edu.toronto.csc301;
public class GridRobot1 implements IGridRobot {
private IBasicRobot basicRobot;
private int size;
public GridRobot1(IBasicRobot basicRobot, int size){
if(basicRobot == null){
throw new NullPointerException();
}
if (size <= 0){
throw new IllegalArgumentException();
}
if (basicRobot.getXCoordinate() != 0 || basicRobot.getYCoordinate() !=0){
if(Math.abs(basicRobot.getXCoordinate()) < size || Math.abs(basicRobot.getYCoordinate()) < size ){
throw new IllegalArgumentException();
}
}
if (basicRobot.getRotation() %90 != 0){
throw new IllegalArgumentException();
}
this.basicRobot = (BasicRobot)basicRobot;
this.size = size;
}
@Override
public GridCell getLocation() {
if (this.basicRobot.getXCoordinate() == 0 & this.basicRobot.getYCoordinate() ==0){
return GridCell.at(0,0);
}
else{
int a = (int) (this.basicRobot.getXCoordinate()/this.size);
int b = (int) (this.basicRobot.getYCoordinate()/this.size);
return GridCell.at(a,b);
}
}
@Override
public Direction getFacingDirection() {
switch (this.basicRobot.getRotation()) {
case 0:
return Direction.NORTH;
case 90:
return Direction.EAST;
case 180:
return Direction.SOUTH;
case 270:
return Direction.WEST;
default:
return null;
}
}
@Override
public void step(Direction direction) {
switch (direction) {
case NORTH:
((BasicRobot) this.basicRobot).setYCoordinate(size);
case SOUTH:
((BasicRobot) this.basicRobot).setYCoordinate(-1 * size);
case EAST:
((BasicRobot) this.basicRobot).setYCoordinate(size);
case WEST:
((BasicRobot) this.basicRobot).setYCoordinate(-1 * size);
}
}
@Override
public void face(Direction direction) {
switch (direction){
case NORTH:
((BasicRobot) this.basicRobot).setRotation(0);
case EAST:
((BasicRobot) this.basicRobot).setRotation(90);
case SOUTH:
((BasicRobot) this.basicRobot).setRotation(180);
case WEST:
((BasicRobot) this.basicRobot).setRotation(270);
}
}
}
**/
=======
>>>>>>> 30f159cefe79d9ff6ed56b91f9ab83180b662e2a
package edu.toronto.csc301;
public class GridRobot1 implements IGridRobot {
private IBasicRobot basicrobot;
private int cellsize;
public GridRobot1(IBasicRobot basicrobot, int cellsize){
if (basicrobot == null){
throw new NullPointerException();
}
if (cellsize <= 0){
throw new IllegalArgumentException();
}
if (basicrobot.getXCoordinate() != 0 || basicrobot.getYCoordinate() != 0){
if (Math.abs(basicrobot.getXCoordinate()) < cellsize || Math.abs(basicrobot.getYCoordinate()) < cellsize){
throw new IllegalArgumentException();
}
}
if (basicrobot.getRotation() % 90 != 0){
throw new IllegalArgumentException();
}
this.basicrobot = (BasicRobot)basicrobot;
this.cellsize = cellsize;
}
@Override
public GridCell getLocation() {
if (this.basicrobot.getXCoordinate() == 0 & this.basicrobot.getYCoordinate() == 0){
return GridCell.at(0,0);
}else{
int a = (int) (this.basicrobot.getXCoordinate()/this.cellsize);
int b = (int) (this.basicrobot.getYCoordinate()/this.cellsize);
return GridCell.at(a, b);
}
}
@Override
public Direction getFacingDirection() {
if (this.basicrobot.getRotation() == 0){
return Direction.NORTH;
}else if (this.basicrobot.getRotation() == 90){
return Direction.EAST;
}else if (this.basicrobot.getRotation() == 180){
return Direction.SOUTH;
}else if (this.basicrobot.getRotation() == 270){
return Direction.WEST;
}
return null;
}
@Override
public void step(Direction direction) {
if (direction == Direction.NORTH){
((BasicRobot) this.basicrobot).setYCoordinate(cellsize);
}else if (direction == Direction.SOUTH){
((BasicRobot) this.basicrobot).setYCoordinate(-1 * cellsize);
}else if (direction == Direction.EAST){
((BasicRobot) this.basicrobot).setXCoordinate(cellsize);
}else if (direction == Direction.WEST){
((BasicRobot) this.basicrobot).setXCoordinate(-1 * cellsize);
}
}
@Override
public void face(Direction direction) {
switch (direction) {
case NORTH:
((BasicRobot) this.basicrobot).setRotation(0);
break;
case EAST:
((BasicRobot) this.basicrobot).setRotation(90);;
break;
case SOUTH:
((BasicRobot) this.basicrobot).setRotation(180);;
break;
case WEST:
((BasicRobot) this.basicrobot).setRotation(270);;
break;
}
}
} | UTF-8 | Java | 5,809 | java | GridRobot1.java | Java | []
| null | []
| <<<<<<< HEAD
/**package edu.toronto.csc301;
public class GridRobot1 implements IGridRobot {
private IBasicRobot basicRobot;
private int size;
public GridRobot1(IBasicRobot basicRobot, int size){
if(basicRobot == null){
throw new NullPointerException();
}
if (size <= 0){
throw new IllegalArgumentException();
}
if (basicRobot.getXCoordinate() != 0 || basicRobot.getYCoordinate() !=0){
if(Math.abs(basicRobot.getXCoordinate()) < size || Math.abs(basicRobot.getYCoordinate()) < size ){
throw new IllegalArgumentException();
}
}
if (basicRobot.getRotation() %90 != 0){
throw new IllegalArgumentException();
}
this.basicRobot = (BasicRobot)basicRobot;
this.size = size;
}
@Override
public GridCell getLocation() {
if (this.basicRobot.getXCoordinate() == 0 & this.basicRobot.getYCoordinate() ==0){
return GridCell.at(0,0);
}
else{
int a = (int) (this.basicRobot.getXCoordinate()/this.size);
int b = (int) (this.basicRobot.getYCoordinate()/this.size);
return GridCell.at(a,b);
}
}
@Override
public Direction getFacingDirection() {
switch (this.basicRobot.getRotation()) {
case 0:
return Direction.NORTH;
case 90:
return Direction.EAST;
case 180:
return Direction.SOUTH;
case 270:
return Direction.WEST;
default:
return null;
}
}
@Override
public void step(Direction direction) {
switch (direction) {
case NORTH:
((BasicRobot) this.basicRobot).setYCoordinate(size);
case SOUTH:
((BasicRobot) this.basicRobot).setYCoordinate(-1 * size);
case EAST:
((BasicRobot) this.basicRobot).setYCoordinate(size);
case WEST:
((BasicRobot) this.basicRobot).setYCoordinate(-1 * size);
}
}
@Override
public void face(Direction direction) {
switch (direction){
case NORTH:
((BasicRobot) this.basicRobot).setRotation(0);
case EAST:
((BasicRobot) this.basicRobot).setRotation(90);
case SOUTH:
((BasicRobot) this.basicRobot).setRotation(180);
case WEST:
((BasicRobot) this.basicRobot).setRotation(270);
}
}
}
**/
=======
>>>>>>> 30f159cefe79d9ff6ed56b91f9ab83180b662e2a
package edu.toronto.csc301;
public class GridRobot1 implements IGridRobot {
private IBasicRobot basicrobot;
private int cellsize;
public GridRobot1(IBasicRobot basicrobot, int cellsize){
if (basicrobot == null){
throw new NullPointerException();
}
if (cellsize <= 0){
throw new IllegalArgumentException();
}
if (basicrobot.getXCoordinate() != 0 || basicrobot.getYCoordinate() != 0){
if (Math.abs(basicrobot.getXCoordinate()) < cellsize || Math.abs(basicrobot.getYCoordinate()) < cellsize){
throw new IllegalArgumentException();
}
}
if (basicrobot.getRotation() % 90 != 0){
throw new IllegalArgumentException();
}
this.basicrobot = (BasicRobot)basicrobot;
this.cellsize = cellsize;
}
@Override
public GridCell getLocation() {
if (this.basicrobot.getXCoordinate() == 0 & this.basicrobot.getYCoordinate() == 0){
return GridCell.at(0,0);
}else{
int a = (int) (this.basicrobot.getXCoordinate()/this.cellsize);
int b = (int) (this.basicrobot.getYCoordinate()/this.cellsize);
return GridCell.at(a, b);
}
}
@Override
public Direction getFacingDirection() {
if (this.basicrobot.getRotation() == 0){
return Direction.NORTH;
}else if (this.basicrobot.getRotation() == 90){
return Direction.EAST;
}else if (this.basicrobot.getRotation() == 180){
return Direction.SOUTH;
}else if (this.basicrobot.getRotation() == 270){
return Direction.WEST;
}
return null;
}
@Override
public void step(Direction direction) {
if (direction == Direction.NORTH){
((BasicRobot) this.basicrobot).setYCoordinate(cellsize);
}else if (direction == Direction.SOUTH){
((BasicRobot) this.basicrobot).setYCoordinate(-1 * cellsize);
}else if (direction == Direction.EAST){
((BasicRobot) this.basicrobot).setXCoordinate(cellsize);
}else if (direction == Direction.WEST){
((BasicRobot) this.basicrobot).setXCoordinate(-1 * cellsize);
}
}
@Override
public void face(Direction direction) {
switch (direction) {
case NORTH:
((BasicRobot) this.basicrobot).setRotation(0);
break;
case EAST:
((BasicRobot) this.basicrobot).setRotation(90);;
break;
case SOUTH:
((BasicRobot) this.basicrobot).setRotation(180);;
break;
case WEST:
((BasicRobot) this.basicrobot).setRotation(270);;
break;
}
}
} | 5,809 | 0.524187 | 0.508177 | 252 | 21.071428 | 25.102545 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.289683 | false | false | 4 |
687622a8a0a924dd06a0c0fae323e11ec09d156f | 13,091,060,366,973 | 933da9e44be32496f14d8fb806ca703e57fb2e1c | /Tugas/TugasLatihan/Yana/PrintedOddNumber.java | ef19330b9809542aa37048cf6b56a547be4587da | []
| no_license | Padepokan79/BootCampG7 | https://github.com/Padepokan79/BootCampG7 | de16a04512e5ee906b137bc4c358d257aee9bd64 | 4143c068b8a393b680bdc0394b9db6d73361de0e | refs/heads/master | 2020-03-14T09:21:16.175000 | 2018-06-29T10:18:49 | 2018-06-29T10:18:49 | 131,543,216 | 0 | 0 | null | false | 2018-06-29T10:18:50 | 2018-04-30T01:07:31 | 2018-06-29T10:18:30 | 2018-06-29T10:18:49 | 2,232 | 0 | 0 | 0 | Java | false | null | /*
Creted by : Yana
Time : 16 Mei 2018
*/
import java.util.Scanner;
public class PrintedOddNumber{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int start, end, angkaAwal;
System.out.println("Enter Start :");
start = keyboard.nextInt();
System.out.println("End Start :");
end = keyboard.nextInt();
for (angkaAwal = start ; angkaAwal < end ; angkaAwal++) {
if ( angkaAwal%2==1 ) {
System.out.println("\n" +angkaAwal);
}
}
}
}
/*
Make a program for user who want printed odd number.
Enter Start :
2
End Start :
10
Result
3
5
7
9
*/ | UTF-8 | Java | 611 | java | PrintedOddNumber.java | Java | [
{
"context": "/*\nCreted by\t: Yana\nTime\t\t: 16 Mei 2018\n*/\n\nimport java.util.Scanner;",
"end": 19,
"score": 0.9964781999588013,
"start": 15,
"tag": "NAME",
"value": "Yana"
}
]
| null | []
| /*
Creted by : Yana
Time : 16 Mei 2018
*/
import java.util.Scanner;
public class PrintedOddNumber{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int start, end, angkaAwal;
System.out.println("Enter Start :");
start = keyboard.nextInt();
System.out.println("End Start :");
end = keyboard.nextInt();
for (angkaAwal = start ; angkaAwal < end ; angkaAwal++) {
if ( angkaAwal%2==1 ) {
System.out.println("\n" +angkaAwal);
}
}
}
}
/*
Make a program for user who want printed odd number.
Enter Start :
2
End Start :
10
Result
3
5
7
9
*/ | 611 | 0.644845 | 0.620295 | 42 | 13.571428 | 16.889194 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.119048 | false | false | 4 |
e60e2ba21238379336407118b93c3d3d0628737a | 33,320,356,343,521 | e2c05272fec3169f48225a252c935db10c3e67b0 | /src/main/java/au/gov/qld/sir/service/dto/AvailabilityHoursDTO.java | d7dbe7620ff1ed4097771b72df77e419ec0efb77 | []
| no_license | BulkSecurityGeneratorProject/jhipSirAdmin | https://github.com/BulkSecurityGeneratorProject/jhipSirAdmin | 62a5fdc1bbe6fbd48913de1b8084920044ac9747 | d967e171e2e88846f7a91b767dedad2ac4a53331 | refs/heads/master | 2022-12-17T17:19:27.174000 | 2019-06-24T04:54:49 | 2019-06-24T04:54:49 | 296,549,176 | 0 | 0 | null | true | 2020-09-18T07:38:53 | 2020-09-18T07:38:52 | 2019-06-24T04:55:16 | 2020-07-02T07:30:41 | 2,108 | 0 | 0 | 0 | null | false | false | package au.gov.qld.sir.service.dto;
import java.time.Instant;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;
/**
* A DTO for the {@link au.gov.qld.sir.domain.AvailabilityHours} entity.
*/
public class AvailabilityHoursDTO implements Serializable {
private Long id;
@Size(max = 255)
private String createdBy;
private Instant createdDateTime;
@Size(max = 255)
private String modifiedBy;
private Instant modifiedDateTime;
private Long version;
@Size(max = 1)
private String available;
private Integer availabilityHoursId;
@Size(max = 255)
private String comments;
private Instant validFrom;
private Instant validTo;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Instant getCreatedDateTime() {
return createdDateTime;
}
public void setCreatedDateTime(Instant createdDateTime) {
this.createdDateTime = createdDateTime;
}
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
public Instant getModifiedDateTime() {
return modifiedDateTime;
}
public void setModifiedDateTime(Instant modifiedDateTime) {
this.modifiedDateTime = modifiedDateTime;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public String getAvailable() {
return available;
}
public void setAvailable(String available) {
this.available = available;
}
public Integer getAvailabilityHoursId() {
return availabilityHoursId;
}
public void setAvailabilityHoursId(Integer availabilityHoursId) {
this.availabilityHoursId = availabilityHoursId;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Instant getValidFrom() {
return validFrom;
}
public void setValidFrom(Instant validFrom) {
this.validFrom = validFrom;
}
public Instant getValidTo() {
return validTo;
}
public void setValidTo(Instant validTo) {
this.validTo = validTo;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AvailabilityHoursDTO availabilityHoursDTO = (AvailabilityHoursDTO) o;
if (availabilityHoursDTO.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), availabilityHoursDTO.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "AvailabilityHoursDTO{" +
"id=" + getId() +
", createdBy='" + getCreatedBy() + "'" +
", createdDateTime='" + getCreatedDateTime() + "'" +
", modifiedBy='" + getModifiedBy() + "'" +
", modifiedDateTime='" + getModifiedDateTime() + "'" +
", version=" + getVersion() +
", available='" + getAvailable() + "'" +
", availabilityHoursId=" + getAvailabilityHoursId() +
", comments='" + getComments() + "'" +
", validFrom='" + getValidFrom() + "'" +
", validTo='" + getValidTo() + "'" +
"}";
}
}
| UTF-8 | Java | 3,822 | java | AvailabilityHoursDTO.java | Java | []
| null | []
| package au.gov.qld.sir.service.dto;
import java.time.Instant;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;
/**
* A DTO for the {@link au.gov.qld.sir.domain.AvailabilityHours} entity.
*/
public class AvailabilityHoursDTO implements Serializable {
private Long id;
@Size(max = 255)
private String createdBy;
private Instant createdDateTime;
@Size(max = 255)
private String modifiedBy;
private Instant modifiedDateTime;
private Long version;
@Size(max = 1)
private String available;
private Integer availabilityHoursId;
@Size(max = 255)
private String comments;
private Instant validFrom;
private Instant validTo;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Instant getCreatedDateTime() {
return createdDateTime;
}
public void setCreatedDateTime(Instant createdDateTime) {
this.createdDateTime = createdDateTime;
}
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
public Instant getModifiedDateTime() {
return modifiedDateTime;
}
public void setModifiedDateTime(Instant modifiedDateTime) {
this.modifiedDateTime = modifiedDateTime;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public String getAvailable() {
return available;
}
public void setAvailable(String available) {
this.available = available;
}
public Integer getAvailabilityHoursId() {
return availabilityHoursId;
}
public void setAvailabilityHoursId(Integer availabilityHoursId) {
this.availabilityHoursId = availabilityHoursId;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Instant getValidFrom() {
return validFrom;
}
public void setValidFrom(Instant validFrom) {
this.validFrom = validFrom;
}
public Instant getValidTo() {
return validTo;
}
public void setValidTo(Instant validTo) {
this.validTo = validTo;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AvailabilityHoursDTO availabilityHoursDTO = (AvailabilityHoursDTO) o;
if (availabilityHoursDTO.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), availabilityHoursDTO.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "AvailabilityHoursDTO{" +
"id=" + getId() +
", createdBy='" + getCreatedBy() + "'" +
", createdDateTime='" + getCreatedDateTime() + "'" +
", modifiedBy='" + getModifiedBy() + "'" +
", modifiedDateTime='" + getModifiedDateTime() + "'" +
", version=" + getVersion() +
", available='" + getAvailable() + "'" +
", availabilityHoursId=" + getAvailabilityHoursId() +
", comments='" + getComments() + "'" +
", validFrom='" + getValidFrom() + "'" +
", validTo='" + getValidTo() + "'" +
"}";
}
}
| 3,822 | 0.597855 | 0.595238 | 164 | 22.304878 | 20.686798 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.365854 | false | false | 4 |
9a2dbd840990222e9afb4e0358fada465fa7f0cf | 33,208,687,149,263 | 1e46a5518ed4ef564ab1d537260f85516ab0ccba | /src/main/java/com/ccighgo/service/transport/partner/beans/partnerusers/PartnerUser.java | 0f1909d567b08c9f2c8226646a9c8f5ce22786bf | []
| no_license | reachvineetjain/testrepo | https://github.com/reachvineetjain/testrepo | c56ba3b7583c188d9dccd0c58920f39e601b5835 | 6ee8581cac7b420596b3c026515341e991f47614 | refs/heads/master | 2020-04-02T05:18:32.264000 | 2016-06-09T12:16:23 | 2016-06-09T12:16:23 | 60,774,146 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.03.01 at 04:10:33 PM IST
//
package com.ccighgo.service.transport.partner.beans.partnerusers;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for PartnerUser complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="PartnerUser">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="partnerUserId" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="partnerUserPhotoUrl" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="partnerUserFirstName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="partnerUserLastName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="isPrimary" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
* <element name="partnerUserLoginName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="partnerUserEmail" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="partnerUserStatus" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PartnerUser", propOrder = {
"partnerUserId",
"partnerUserPhotoUrl",
"partnerUserFirstName",
"partnerUserLastName",
"isPrimary",
"partnerUserLoginName",
"partnerUserEmail",
"partnerUserStatus",
"partnerGoId"
})
public class PartnerUser {
protected int partnerUserId;
@XmlElement(required = true)
protected String partnerUserPhotoUrl;
@XmlElement(required = true)
protected String partnerUserFirstName;
@XmlElement(required = true)
protected String partnerUserLastName;
protected boolean isPrimary;
@XmlElement(required = true)
protected String partnerUserLoginName;
@XmlElement(required = true)
protected String partnerUserEmail;
protected int partnerUserStatus;
protected int partnerGoId;
/**
* Gets the value of the partnerUserId property.
*
*/
public int getPartnerUserId() {
return partnerUserId;
}
/**
* Sets the value of the partnerUserId property.
*
*/
public void setPartnerUserId(int value) {
this.partnerUserId = value;
}
/**
* Gets the value of the partnerUserPhotoUrl property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPartnerUserPhotoUrl() {
return partnerUserPhotoUrl;
}
/**
* Sets the value of the partnerUserPhotoUrl property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPartnerUserPhotoUrl(String value) {
this.partnerUserPhotoUrl = value;
}
/**
* Gets the value of the partnerUserFirstName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPartnerUserFirstName() {
return partnerUserFirstName;
}
/**
* Sets the value of the partnerUserFirstName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPartnerUserFirstName(String value) {
this.partnerUserFirstName = value;
}
/**
* Gets the value of the partnerUserLastName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPartnerUserLastName() {
return partnerUserLastName;
}
/**
* Sets the value of the partnerUserLastName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPartnerUserLastName(String value) {
this.partnerUserLastName = value;
}
/**
* Gets the value of the isPrimary property.
*
*/
public boolean isIsPrimary() {
return isPrimary;
}
/**
* Sets the value of the isPrimary property.
*
*/
public void setIsPrimary(boolean value) {
this.isPrimary = value;
}
/**
* Gets the value of the partnerUserLoginName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPartnerUserLoginName() {
return partnerUserLoginName;
}
/**
* Sets the value of the partnerUserLoginName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPartnerUserLoginName(String value) {
this.partnerUserLoginName = value;
}
/**
* Gets the value of the partnerUserEmail property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPartnerUserEmail() {
return partnerUserEmail;
}
/**
* Sets the value of the partnerUserEmail property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPartnerUserEmail(String value) {
this.partnerUserEmail = value;
}
/**
* Gets the value of the partnerUserStatus property.
*
*/
public int getPartnerUserStatus() {
return partnerUserStatus;
}
/**
* Sets the value of the partnerUserStatus property.
*
*/
public void setPartnerUserStatus(int value) {
this.partnerUserStatus = value;
}
public int getPartnerGoId() {
return partnerGoId;
}
public void setPartnerGoId(int partnerGoId) {
this.partnerGoId = partnerGoId;
}
}
| UTF-8 | Java | 6,422 | java | PartnerUser.java | Java | []
| null | []
| //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.03.01 at 04:10:33 PM IST
//
package com.ccighgo.service.transport.partner.beans.partnerusers;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for PartnerUser complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="PartnerUser">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="partnerUserId" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="partnerUserPhotoUrl" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="partnerUserFirstName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="partnerUserLastName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="isPrimary" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
* <element name="partnerUserLoginName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="partnerUserEmail" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="partnerUserStatus" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PartnerUser", propOrder = {
"partnerUserId",
"partnerUserPhotoUrl",
"partnerUserFirstName",
"partnerUserLastName",
"isPrimary",
"partnerUserLoginName",
"partnerUserEmail",
"partnerUserStatus",
"partnerGoId"
})
public class PartnerUser {
protected int partnerUserId;
@XmlElement(required = true)
protected String partnerUserPhotoUrl;
@XmlElement(required = true)
protected String partnerUserFirstName;
@XmlElement(required = true)
protected String partnerUserLastName;
protected boolean isPrimary;
@XmlElement(required = true)
protected String partnerUserLoginName;
@XmlElement(required = true)
protected String partnerUserEmail;
protected int partnerUserStatus;
protected int partnerGoId;
/**
* Gets the value of the partnerUserId property.
*
*/
public int getPartnerUserId() {
return partnerUserId;
}
/**
* Sets the value of the partnerUserId property.
*
*/
public void setPartnerUserId(int value) {
this.partnerUserId = value;
}
/**
* Gets the value of the partnerUserPhotoUrl property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPartnerUserPhotoUrl() {
return partnerUserPhotoUrl;
}
/**
* Sets the value of the partnerUserPhotoUrl property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPartnerUserPhotoUrl(String value) {
this.partnerUserPhotoUrl = value;
}
/**
* Gets the value of the partnerUserFirstName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPartnerUserFirstName() {
return partnerUserFirstName;
}
/**
* Sets the value of the partnerUserFirstName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPartnerUserFirstName(String value) {
this.partnerUserFirstName = value;
}
/**
* Gets the value of the partnerUserLastName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPartnerUserLastName() {
return partnerUserLastName;
}
/**
* Sets the value of the partnerUserLastName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPartnerUserLastName(String value) {
this.partnerUserLastName = value;
}
/**
* Gets the value of the isPrimary property.
*
*/
public boolean isIsPrimary() {
return isPrimary;
}
/**
* Sets the value of the isPrimary property.
*
*/
public void setIsPrimary(boolean value) {
this.isPrimary = value;
}
/**
* Gets the value of the partnerUserLoginName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPartnerUserLoginName() {
return partnerUserLoginName;
}
/**
* Sets the value of the partnerUserLoginName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPartnerUserLoginName(String value) {
this.partnerUserLoginName = value;
}
/**
* Gets the value of the partnerUserEmail property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPartnerUserEmail() {
return partnerUserEmail;
}
/**
* Sets the value of the partnerUserEmail property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPartnerUserEmail(String value) {
this.partnerUserEmail = value;
}
/**
* Gets the value of the partnerUserStatus property.
*
*/
public int getPartnerUserStatus() {
return partnerUserStatus;
}
/**
* Sets the value of the partnerUserStatus property.
*
*/
public void setPartnerUserStatus(int value) {
this.partnerUserStatus = value;
}
public int getPartnerGoId() {
return partnerGoId;
}
public void setPartnerGoId(int partnerGoId) {
this.partnerGoId = partnerGoId;
}
}
| 6,422 | 0.610402 | 0.59919 | 249 | 24.791164 | 24.03805 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.232932 | false | false | 4 |
d2d5f0b3676bf5d00f339c7abb21d1300d900bc6 | 11,647,951,334,281 | f73b6add4080cf30191dfa2e33ff50eb51da3d71 | /Lab07/src/it/polito/tdp/poweroutages/PowerOutagesController.java | ea4d20b0a5b9c31b223d9a626de931f05b6070b7 | []
| no_license | ChiaraGhiringhelli/Lab07 | https://github.com/ChiaraGhiringhelli/Lab07 | 65b28fc8b33ff0be11a94ee9589959c88ce37d9f | fac32db681915a47e2bac512bd6c9aa0b3f8a1f5 | refs/heads/master | 2020-03-14T22:44:32.327000 | 2018-09-11T09:22:59 | 2018-09-11T09:22:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package it.polito.tdp.poweroutages;
import java.util.*;
import java.net.URL;
import java.util.ResourceBundle;
import it.polito.tdp.poweroutages.model.Model;
import it.polito.tdp.poweroutages.model.Nerc;
import it.polito.tdp.poweroutages.model.PowerOutageEvent;
import it.polito.tdp.poweroutages.model.PowerOutages;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
public class PowerOutagesController {
Model model;
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private ComboBox<Nerc> menuNerc;
@FXML
private TextField txtYears;
@FXML
private TextField txtHours;
@FXML
private Button btnWCA;
@FXML
private TextArea txtResult;
@FXML
void doAnalisi(ActionEvent event) {
try {
Nerc selectedNerc = menuNerc.getValue();
if (selectedNerc == null) {
txtResult.setText("Select a NERC (area identifier)");
return;
}
int maxY = Integer.parseInt(txtYears.getText());
int yearListSize = model.getYearList().size();
if (maxY <= 0 || maxY > yearListSize) {
txtResult.setText("Select a number of years in range [1, " + yearListSize + "]");
return;
}
int maxH = Integer.parseInt(txtHours.getText());
if (maxH <= 0) {
txtResult.setText("Select a number of hours greater than 0");
return;
}
txtResult.setText( String.format("Computing the worst case analysis... for %d hours and %d years", maxH, maxY));
model.setANNI_MAX(maxY);
model.setORE_MAX(maxH);
System.out.println("Sono qui");
List<PowerOutageEvent> worstCase = model.getWorstCase(selectedNerc);
System.out.println("Sono quiiiii");
txtResult.clear();
txtResult.appendText("Tot people affected: " + model.contaPersone(worstCase) + "\n");
txtResult.appendText("Tot hours of outage: " + model.contaOre(worstCase)+ "\n");
for (PowerOutageEvent ee : worstCase) {
txtResult.appendText(String.format("%d %s %s %d %d", ee.getYear(), ee.getOutageStart(),
ee.getOutageEnd(), ee.getOutageDuration(), ee.getAffectedPeople()));
txtResult.appendText("\n");
}
} catch (NumberFormatException e) {
txtResult.setText("Insert a valid number of years and of hours");
}
}
@FXML
void initialize() {
assert menuNerc != null : "fx:id=\"menuNerc\" was not injected: check your FXML file 'PowerOutages.fxml'.";
assert txtYears != null : "fx:id=\"txtYears\" was not injected: check your FXML file 'PowerOutages.fxml'.";
assert txtHours != null : "fx:id=\"txtHours\" was not injected: check your FXML file 'PowerOutages.fxml'.";
assert btnWCA != null : "fx:id=\"btnWCA\" was not injected: check your FXML file 'PowerOutages.fxml'.";
assert txtResult != null : "fx:id=\"txtResult\" was not injected: check your FXML file 'PowerOutages.fxml'.";
}
public void setModel(Model model) {
this.model = model;
menuNerc.getItems().addAll(model.getNercList());
}
}
| UTF-8 | Java | 3,135 | java | PowerOutagesController.java | Java | []
| null | []
| package it.polito.tdp.poweroutages;
import java.util.*;
import java.net.URL;
import java.util.ResourceBundle;
import it.polito.tdp.poweroutages.model.Model;
import it.polito.tdp.poweroutages.model.Nerc;
import it.polito.tdp.poweroutages.model.PowerOutageEvent;
import it.polito.tdp.poweroutages.model.PowerOutages;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
public class PowerOutagesController {
Model model;
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private ComboBox<Nerc> menuNerc;
@FXML
private TextField txtYears;
@FXML
private TextField txtHours;
@FXML
private Button btnWCA;
@FXML
private TextArea txtResult;
@FXML
void doAnalisi(ActionEvent event) {
try {
Nerc selectedNerc = menuNerc.getValue();
if (selectedNerc == null) {
txtResult.setText("Select a NERC (area identifier)");
return;
}
int maxY = Integer.parseInt(txtYears.getText());
int yearListSize = model.getYearList().size();
if (maxY <= 0 || maxY > yearListSize) {
txtResult.setText("Select a number of years in range [1, " + yearListSize + "]");
return;
}
int maxH = Integer.parseInt(txtHours.getText());
if (maxH <= 0) {
txtResult.setText("Select a number of hours greater than 0");
return;
}
txtResult.setText( String.format("Computing the worst case analysis... for %d hours and %d years", maxH, maxY));
model.setANNI_MAX(maxY);
model.setORE_MAX(maxH);
System.out.println("Sono qui");
List<PowerOutageEvent> worstCase = model.getWorstCase(selectedNerc);
System.out.println("Sono quiiiii");
txtResult.clear();
txtResult.appendText("Tot people affected: " + model.contaPersone(worstCase) + "\n");
txtResult.appendText("Tot hours of outage: " + model.contaOre(worstCase)+ "\n");
for (PowerOutageEvent ee : worstCase) {
txtResult.appendText(String.format("%d %s %s %d %d", ee.getYear(), ee.getOutageStart(),
ee.getOutageEnd(), ee.getOutageDuration(), ee.getAffectedPeople()));
txtResult.appendText("\n");
}
} catch (NumberFormatException e) {
txtResult.setText("Insert a valid number of years and of hours");
}
}
@FXML
void initialize() {
assert menuNerc != null : "fx:id=\"menuNerc\" was not injected: check your FXML file 'PowerOutages.fxml'.";
assert txtYears != null : "fx:id=\"txtYears\" was not injected: check your FXML file 'PowerOutages.fxml'.";
assert txtHours != null : "fx:id=\"txtHours\" was not injected: check your FXML file 'PowerOutages.fxml'.";
assert btnWCA != null : "fx:id=\"btnWCA\" was not injected: check your FXML file 'PowerOutages.fxml'.";
assert txtResult != null : "fx:id=\"txtResult\" was not injected: check your FXML file 'PowerOutages.fxml'.";
}
public void setModel(Model model) {
this.model = model;
menuNerc.getItems().addAll(model.getNercList());
}
}
| 3,135 | 0.684529 | 0.683254 | 106 | 28.575472 | 31.07749 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.773585 | false | false | 4 |
556b5c0b4040163d753d9e92fc47aa9445c9bb71 | 13,511,967,138,655 | efa7bd78138573da7227a5b5ee0cfe42e521a052 | /src/com/prikhodko/Collection/Collection.java | c02766f23db2086338503a63af63e5723ae41d32 | []
| no_license | ruslanPrih/java_courses | https://github.com/ruslanPrih/java_courses | c46007fe2f6f367a2745ade59dc03d1416052540 | 5762678b4f6c68542f8b0b0ada65c865fd570e46 | refs/heads/master | 2020-12-03T02:16:15.501000 | 2017-11-28T20:10:36 | 2017-11-28T20:10:36 | 95,919,523 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.prikhodko.Collection;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
public class Collection {
public static void main(String[] args) {
/* List<String> list = new ArrayList<>();
for (int i =0;i<5;i++){
Random random=new Random();
list.add("iterator"+random.nextInt(10000));
}
System.out.println(list);
System.out.println(list.get(4));
try {
System.out.println(list.get(10));
}catch (Exception e){
e.printStackTrace();
}
*/
/*
List<String>list=new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
Collection<String> list1=new ArrayList<>();
lis.add("1");
*/
/*
List<String> list = new LinkedList<>();
list.add("1");
*/
/*
Integer[]numbers
Set<Integer> set = new HashSet<Integer>(Arrays.asList(numbers));
*/
}
}
| UTF-8 | Java | 1,090 | java | Collection.java | Java | []
| null | []
| package com.prikhodko.Collection;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
public class Collection {
public static void main(String[] args) {
/* List<String> list = new ArrayList<>();
for (int i =0;i<5;i++){
Random random=new Random();
list.add("iterator"+random.nextInt(10000));
}
System.out.println(list);
System.out.println(list.get(4));
try {
System.out.println(list.get(10));
}catch (Exception e){
e.printStackTrace();
}
*/
/*
List<String>list=new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
Collection<String> list1=new ArrayList<>();
lis.add("1");
*/
/*
List<String> list = new LinkedList<>();
list.add("1");
*/
/*
Integer[]numbers
Set<Integer> set = new HashSet<Integer>(Arrays.asList(numbers));
*/
}
}
| 1,090 | 0.516514 | 0.5 | 48 | 21.666666 | 17.361755 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.520833 | false | false | 4 |
73fbb476ea8e8119395beb3cadfd431deb6040e1 | 25,881,472,960,494 | 3a1c2df0d041d92655a45f0f47643afbaaa2551a | /Archive/2013.10/2013.10.19 - TopCoder SRM #249/TableSeating.java | 860b434b6d559a0fba5e9f6d86a4e33e35d4e2db | []
| no_license | sriankit/coding | https://github.com/sriankit/coding | e034af5c7ca2cce1afddeffdd581d6c8c1ef1f6b | f03c626bbb99c77b34c854016b5cd03a0a9f892e | refs/heads/master | 2020-05-18T12:04:04.277000 | 2015-07-19T12:16:38 | 2015-07-19T12:16:38 | 20,114,276 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Tasks;
import java.util.Arrays;
public class TableSeating {
double p[];
double dp[];
int n;
double go(int mask) {
System.out.println("mask = " + mask);
if (dp[mask] < 0) {
int used = Integer.bitCount(mask);
double res = 0.0;
for (int i = 0; i < p.length; i++) {
int want = i + 1;
double prob = p[i];
boolean allOk = false;
for (int j = 0; j <= n - want; j++) {
boolean ok = true;
for (int k = 0; k < want; k++) {
if ((mask & (1 << (j + k))) == 1)
ok = false;
}
if (ok) {
allOk = true;
int pass = mask;
for (int k = 0; k < want; k++) {
pass |= (1 << (j + k));
}
res += p[i] * go(pass);
}
}
if (!allOk) res += p[i] * used;
}
dp[mask] = res;
}
return dp[mask];
}
public double getExpected(int numTables, int[] probs) {
n = numTables;
p = new double[probs.length];
dp = new double[1 << 13];
Arrays.fill(dp, -1);
for (int i = 0; i < probs.length; i++) {
p[i] = probs[i] / 100.0;
}
return go(0);
}
}
| UTF-8 | Java | 1,490 | java | TableSeating.java | Java | []
| null | []
| package Tasks;
import java.util.Arrays;
public class TableSeating {
double p[];
double dp[];
int n;
double go(int mask) {
System.out.println("mask = " + mask);
if (dp[mask] < 0) {
int used = Integer.bitCount(mask);
double res = 0.0;
for (int i = 0; i < p.length; i++) {
int want = i + 1;
double prob = p[i];
boolean allOk = false;
for (int j = 0; j <= n - want; j++) {
boolean ok = true;
for (int k = 0; k < want; k++) {
if ((mask & (1 << (j + k))) == 1)
ok = false;
}
if (ok) {
allOk = true;
int pass = mask;
for (int k = 0; k < want; k++) {
pass |= (1 << (j + k));
}
res += p[i] * go(pass);
}
}
if (!allOk) res += p[i] * used;
}
dp[mask] = res;
}
return dp[mask];
}
public double getExpected(int numTables, int[] probs) {
n = numTables;
p = new double[probs.length];
dp = new double[1 << 13];
Arrays.fill(dp, -1);
for (int i = 0; i < probs.length; i++) {
p[i] = probs[i] / 100.0;
}
return go(0);
}
}
| 1,490 | 0.341611 | 0.327517 | 51 | 28.215687 | 16.745281 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.764706 | false | false | 4 |
64a5ea4ce93c32742f80bd6dff9d08df3fa602db | 32,822,140,105,488 | 544cfadc742536618168fc80a5bd81a35a5f2c99 | /packages/apps/Bluetooth/src/com/android/bluetooth/telephony/BluetoothCall.java | 85a0b9a4aa6216db8e9067830e5cb3dced389648 | []
| no_license | ZYHGOD-1/Aosp11 | https://github.com/ZYHGOD-1/Aosp11 | 0400619993b559bf4380db2da0addfa9cccd698d | 78a61ca023cbf1a0cecfef8b97df2b274ac3a988 | refs/heads/main | 2023-04-21T20:13:54.629000 | 2021-05-22T05:28:21 | 2021-05-22T05:28:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (C) 2020 The Android Open Source Project
*
* 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.android.bluetooth.telephony;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.telecom.Call;
import android.telecom.GatewayInfo;
import android.telecom.InCallService;
import android.telecom.PhoneAccountHandle;
import com.android.internal.annotations.VisibleForTesting;
import java.util.ArrayList;
import java.util.List;
/**
* A proxy class of android.telecom.Call that
* 1) facilitates testing of the BluetoothInCallService class; We can't mock the final class
* Call directly;
* 2) Some helper functions, to let Call have same methods as com.android.server.telecom.Call
*
* This is necessary due to the "final" attribute of the Call class. In order to
* test the correct functioning of the BluetoothInCallService class, the final class must be put
* into a container that can be mocked correctly.
*/
@VisibleForTesting
public class BluetoothCall {
private Call mCall;
public Call getCall() {
return mCall;
}
public void setCall(Call call) {
mCall = call;
}
public BluetoothCall(Call call) {
mCall = call;
}
public String getRemainingPostDialSequence() {
return mCall.getRemainingPostDialSequence();
}
public void answer(int videoState) {
mCall.answer(videoState);
}
public void deflect(Uri address) {
mCall.deflect(address);
}
public void reject(boolean rejectWithMessage, String textMessage) {
mCall.reject(rejectWithMessage, textMessage);
}
public void disconnect() {
mCall.disconnect();
}
public void hold() {
mCall.hold();
}
public void unhold() {
mCall.unhold();
}
public void enterBackgroundAudioProcessing() {
mCall.enterBackgroundAudioProcessing();
}
public void exitBackgroundAudioProcessing(boolean shouldRing) {
mCall.exitBackgroundAudioProcessing(shouldRing);
}
public void playDtmfTone(char digit) {
mCall.playDtmfTone(digit);
}
public void stopDtmfTone() {
mCall.stopDtmfTone();
}
public void postDialContinue(boolean proceed) {
mCall.postDialContinue(proceed);
}
public void phoneAccountSelected(PhoneAccountHandle accountHandle, boolean setDefault) {
mCall.phoneAccountSelected(accountHandle, setDefault);
}
public void conference(BluetoothCall callToConferenceWith) {
if (callToConferenceWith != null) {
mCall.conference(callToConferenceWith.getCall());
}
}
public void splitFromConference() {
mCall.splitFromConference();
}
public void mergeConference() {
mCall.mergeConference();
}
public void swapConference() {
mCall.swapConference();
}
public void pullExternalCall() {
mCall.pullExternalCall();
}
public void sendCallEvent(String event, Bundle extras) {
mCall.sendCallEvent(event, extras);
}
public void sendRttRequest() {
mCall.sendRttRequest();
}
public void respondToRttRequest(int id, boolean accept) {
mCall.respondToRttRequest(id, accept);
}
public void handoverTo(PhoneAccountHandle toHandle, int videoState, Bundle extras) {
mCall.handoverTo(toHandle, videoState, extras);
}
public void stopRtt() {
mCall.stopRtt();
}
public void putExtras(Bundle extras) {
mCall.putExtras(extras);
}
public void putExtra(String key, boolean value) {
mCall.putExtra(key, value);
}
public void putExtra(String key, int value) {
mCall.putExtra(key, value);
}
public void putExtra(String key, String value) {
mCall.putExtra(key, value);
}
public void removeExtras(List<String> keys) {
mCall.removeExtras(keys);
}
public void removeExtras(String... keys) {
mCall.removeExtras(keys);
}
public String getParentId() {
Call parent = mCall.getParent();
if (parent != null) {
return parent.getDetails().getTelecomCallId();
}
return null;
}
public List<String> getChildrenIds() {
return getIds(mCall.getChildren());
}
public List<String> getConferenceableCalls() {
return getIds(mCall.getConferenceableCalls());
}
public int getState() {
return mCall.getState();
}
public List<String> getCannedTextResponses() {
return mCall.getCannedTextResponses();
}
public InCallService.VideoCall getVideoCall() {
return mCall.getVideoCall();
}
public Call.Details getDetails() {
return mCall.getDetails();
}
public Call.RttCall getRttCall() {
return mCall.getRttCall();
}
public boolean isRttActive() {
return mCall.isRttActive();
}
public void registerCallback(Call.Callback callback) {
mCall.registerCallback(callback);
}
public void registerCallback(Call.Callback callback, Handler handler) {
mCall.registerCallback(callback, handler);
}
public void unregisterCallback(Call.Callback callback) {
mCall.unregisterCallback(callback);
}
public String toString() {
String string = mCall.toString();
return string == null ? "" : string;
}
public void addListener(Call.Listener listener) {
mCall.addListener(listener);
}
public void removeListener(Call.Listener listener) {
mCall.removeListener(listener);
}
public String getGenericConferenceActiveChildCallId() {
return mCall.getGenericConferenceActiveChildCall().getDetails().getTelecomCallId();
}
public String getContactDisplayName() {
return mCall.getDetails().getContactDisplayName();
}
public PhoneAccountHandle getAccountHandle() {
return mCall.getDetails().getAccountHandle();
}
public int getVideoState() {
return mCall.getDetails().getVideoState();
}
public String getCallerDisplayName() {
return mCall.getDetails().getCallerDisplayName();
}
@Override
public boolean equals(Object o) {
if (o == null) {
return getCall() == null;
}
return o instanceof BluetoothCall && getCall() == ((BluetoothCall) o).getCall();
}
// helper functions
public boolean isSilentRingingRequested() {
return getDetails().getExtras() != null
&& getDetails().getExtras().getBoolean(Call.EXTRA_SILENT_RINGING_REQUESTED);
}
public boolean isConference() {
return getDetails().hasProperty(Call.Details.PROPERTY_CONFERENCE);
}
public boolean can(int capability) {
return getDetails().can(capability);
}
public Uri getHandle() {
return getDetails().getHandle();
}
public GatewayInfo getGatewayInfo() {
return getDetails().getGatewayInfo();
}
public boolean isIncoming() {
return getDetails().getCallDirection() == Call.Details.DIRECTION_INCOMING;
}
public boolean isExternalCall() {
return getDetails().hasProperty(Call.Details.PROPERTY_IS_EXTERNAL_CALL);
}
public String getTelecomCallId() {
return getDetails().getTelecomCallId();
}
public boolean wasConferencePreviouslyMerged() {
return can(Call.Details.CAPABILITY_SWAP_CONFERENCE) &&
!can(Call.Details.CAPABILITY_MERGE_CONFERENCE);
}
public static List<String> getIds(List<Call> calls) {
List<String> result = new ArrayList<>();
for (Call call : calls) {
if (call != null) {
result.add(call.getDetails().getTelecomCallId());
}
}
return result;
}
}
| UTF-8 | Java | 8,381 | java | BluetoothCall.java | Java | []
| null | []
| /*
* Copyright (C) 2020 The Android Open Source Project
*
* 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.android.bluetooth.telephony;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.telecom.Call;
import android.telecom.GatewayInfo;
import android.telecom.InCallService;
import android.telecom.PhoneAccountHandle;
import com.android.internal.annotations.VisibleForTesting;
import java.util.ArrayList;
import java.util.List;
/**
* A proxy class of android.telecom.Call that
* 1) facilitates testing of the BluetoothInCallService class; We can't mock the final class
* Call directly;
* 2) Some helper functions, to let Call have same methods as com.android.server.telecom.Call
*
* This is necessary due to the "final" attribute of the Call class. In order to
* test the correct functioning of the BluetoothInCallService class, the final class must be put
* into a container that can be mocked correctly.
*/
@VisibleForTesting
public class BluetoothCall {
private Call mCall;
public Call getCall() {
return mCall;
}
public void setCall(Call call) {
mCall = call;
}
public BluetoothCall(Call call) {
mCall = call;
}
public String getRemainingPostDialSequence() {
return mCall.getRemainingPostDialSequence();
}
public void answer(int videoState) {
mCall.answer(videoState);
}
public void deflect(Uri address) {
mCall.deflect(address);
}
public void reject(boolean rejectWithMessage, String textMessage) {
mCall.reject(rejectWithMessage, textMessage);
}
public void disconnect() {
mCall.disconnect();
}
public void hold() {
mCall.hold();
}
public void unhold() {
mCall.unhold();
}
public void enterBackgroundAudioProcessing() {
mCall.enterBackgroundAudioProcessing();
}
public void exitBackgroundAudioProcessing(boolean shouldRing) {
mCall.exitBackgroundAudioProcessing(shouldRing);
}
public void playDtmfTone(char digit) {
mCall.playDtmfTone(digit);
}
public void stopDtmfTone() {
mCall.stopDtmfTone();
}
public void postDialContinue(boolean proceed) {
mCall.postDialContinue(proceed);
}
public void phoneAccountSelected(PhoneAccountHandle accountHandle, boolean setDefault) {
mCall.phoneAccountSelected(accountHandle, setDefault);
}
public void conference(BluetoothCall callToConferenceWith) {
if (callToConferenceWith != null) {
mCall.conference(callToConferenceWith.getCall());
}
}
public void splitFromConference() {
mCall.splitFromConference();
}
public void mergeConference() {
mCall.mergeConference();
}
public void swapConference() {
mCall.swapConference();
}
public void pullExternalCall() {
mCall.pullExternalCall();
}
public void sendCallEvent(String event, Bundle extras) {
mCall.sendCallEvent(event, extras);
}
public void sendRttRequest() {
mCall.sendRttRequest();
}
public void respondToRttRequest(int id, boolean accept) {
mCall.respondToRttRequest(id, accept);
}
public void handoverTo(PhoneAccountHandle toHandle, int videoState, Bundle extras) {
mCall.handoverTo(toHandle, videoState, extras);
}
public void stopRtt() {
mCall.stopRtt();
}
public void putExtras(Bundle extras) {
mCall.putExtras(extras);
}
public void putExtra(String key, boolean value) {
mCall.putExtra(key, value);
}
public void putExtra(String key, int value) {
mCall.putExtra(key, value);
}
public void putExtra(String key, String value) {
mCall.putExtra(key, value);
}
public void removeExtras(List<String> keys) {
mCall.removeExtras(keys);
}
public void removeExtras(String... keys) {
mCall.removeExtras(keys);
}
public String getParentId() {
Call parent = mCall.getParent();
if (parent != null) {
return parent.getDetails().getTelecomCallId();
}
return null;
}
public List<String> getChildrenIds() {
return getIds(mCall.getChildren());
}
public List<String> getConferenceableCalls() {
return getIds(mCall.getConferenceableCalls());
}
public int getState() {
return mCall.getState();
}
public List<String> getCannedTextResponses() {
return mCall.getCannedTextResponses();
}
public InCallService.VideoCall getVideoCall() {
return mCall.getVideoCall();
}
public Call.Details getDetails() {
return mCall.getDetails();
}
public Call.RttCall getRttCall() {
return mCall.getRttCall();
}
public boolean isRttActive() {
return mCall.isRttActive();
}
public void registerCallback(Call.Callback callback) {
mCall.registerCallback(callback);
}
public void registerCallback(Call.Callback callback, Handler handler) {
mCall.registerCallback(callback, handler);
}
public void unregisterCallback(Call.Callback callback) {
mCall.unregisterCallback(callback);
}
public String toString() {
String string = mCall.toString();
return string == null ? "" : string;
}
public void addListener(Call.Listener listener) {
mCall.addListener(listener);
}
public void removeListener(Call.Listener listener) {
mCall.removeListener(listener);
}
public String getGenericConferenceActiveChildCallId() {
return mCall.getGenericConferenceActiveChildCall().getDetails().getTelecomCallId();
}
public String getContactDisplayName() {
return mCall.getDetails().getContactDisplayName();
}
public PhoneAccountHandle getAccountHandle() {
return mCall.getDetails().getAccountHandle();
}
public int getVideoState() {
return mCall.getDetails().getVideoState();
}
public String getCallerDisplayName() {
return mCall.getDetails().getCallerDisplayName();
}
@Override
public boolean equals(Object o) {
if (o == null) {
return getCall() == null;
}
return o instanceof BluetoothCall && getCall() == ((BluetoothCall) o).getCall();
}
// helper functions
public boolean isSilentRingingRequested() {
return getDetails().getExtras() != null
&& getDetails().getExtras().getBoolean(Call.EXTRA_SILENT_RINGING_REQUESTED);
}
public boolean isConference() {
return getDetails().hasProperty(Call.Details.PROPERTY_CONFERENCE);
}
public boolean can(int capability) {
return getDetails().can(capability);
}
public Uri getHandle() {
return getDetails().getHandle();
}
public GatewayInfo getGatewayInfo() {
return getDetails().getGatewayInfo();
}
public boolean isIncoming() {
return getDetails().getCallDirection() == Call.Details.DIRECTION_INCOMING;
}
public boolean isExternalCall() {
return getDetails().hasProperty(Call.Details.PROPERTY_IS_EXTERNAL_CALL);
}
public String getTelecomCallId() {
return getDetails().getTelecomCallId();
}
public boolean wasConferencePreviouslyMerged() {
return can(Call.Details.CAPABILITY_SWAP_CONFERENCE) &&
!can(Call.Details.CAPABILITY_MERGE_CONFERENCE);
}
public static List<String> getIds(List<Call> calls) {
List<String> result = new ArrayList<>();
for (Call call : calls) {
if (call != null) {
result.add(call.getDetails().getTelecomCallId());
}
}
return result;
}
}
| 8,381 | 0.657081 | 0.655888 | 318 | 25.355347 | 24.636148 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.345912 | false | false | 4 |
dfb6e2ef2a312b047960dc72d75596dd2fe95d28 | 6,846,177,912,836 | cbd10ae0006080b1fe8075e3afd808bdae86e225 | /App/controllers/Application.java | a68879da29fde4e96a2d004a3d9b5e608d49e4a0 | []
| no_license | Zahermah/Todo-list-PlayFramework | https://github.com/Zahermah/Todo-list-PlayFramework | 56125435764242a2a76902b600fcff9fee93ad52 | 70a692dae6076e9a6f7f635efce251a16f9391b4 | refs/heads/master | 2020-12-30T11:27:33.847000 | 2017-10-09T19:57:13 | 2017-10-09T19:57:13 | 91,555,113 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controllers;
import com.google.inject.Inject;
import models.Task;
import play.data.Form;
import play.data.FormFactory;
import play.mvc.*;
public class Application extends Controller {
@Inject
public FormFactory formFactory;
public Result index() {
return redirect(routes.Application.tasks());
}
public Result tasks() {
return ok(views.html.index.render(Task.all(), formFactory.form(Task.class))
);
}
public Result newTask() {
Form<Task> filledForm = formFactory.form(Task.class).bindFromRequest();
if (filledForm.hasErrors()) {
return badRequest(views.html.index.render(Task.all(), filledForm));
} else {
Task.create(filledForm.get());
return redirect(routes.Application.tasks());
}
}
public Result deleteTask(Long id) {
Task.delete(id);
return redirect(routes.Application.tasks());
}
} | UTF-8 | Java | 950 | java | Application.java | Java | []
| null | []
| package controllers;
import com.google.inject.Inject;
import models.Task;
import play.data.Form;
import play.data.FormFactory;
import play.mvc.*;
public class Application extends Controller {
@Inject
public FormFactory formFactory;
public Result index() {
return redirect(routes.Application.tasks());
}
public Result tasks() {
return ok(views.html.index.render(Task.all(), formFactory.form(Task.class))
);
}
public Result newTask() {
Form<Task> filledForm = formFactory.form(Task.class).bindFromRequest();
if (filledForm.hasErrors()) {
return badRequest(views.html.index.render(Task.all(), filledForm));
} else {
Task.create(filledForm.get());
return redirect(routes.Application.tasks());
}
}
public Result deleteTask(Long id) {
Task.delete(id);
return redirect(routes.Application.tasks());
}
} | 950 | 0.64 | 0.64 | 38 | 24.026316 | 23.424557 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.447368 | false | false | 4 |
4c6e105763baeb72b024272ef6b0cdd3439994c0 | 21,655,225,164,863 | da231adebb60e5fc0ee39ea61a699164286dac43 | /app/src/main/java/com/example/corona/Adapter.java | d28e51c6b5739c4da8c00ddbdc56d5d4fbe8a672 | []
| no_license | donataskitm/1darbas | https://github.com/donataskitm/1darbas | 6871a293380e6eb1022b1e098a87c4609b0fd638 | 4d2682b462c89d4517e68e555e615d7f72b9ee7b | refs/heads/master | 2023-04-14T03:45:03.972000 | 2021-04-26T16:10:10 | 2021-04-26T16:10:10 | 343,721,312 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.corona;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import android.content.Intent;
public class Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private LayoutInflater inflater;
List<Corona> data;
public static final String ENTRY = "com.example.corona.ENTRY";
// create constructor to initialize context and data sent from SearchActivity
public Adapter(Context context, List<Corona> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
// Inflate the layout when ViewHolder created
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.container_corona, parent, false);
MyHolder holder = new MyHolder(view);
return holder;
}
// Bind data
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// Get current position of item in RecyclerView to bind data and assign values from list
MyHolder myHolder = (MyHolder) holder;
Corona current = data.get(position);
myHolder.textKeyId.setText(current.getKeyId());
myHolder.textLastUpdate.setText("Last update: " + current.getLastUpdate());
myHolder.textConfirmed.setText("Confirmed: " + current.getConfirmed());
myHolder.textDeaths.setText("Deaths: " + current.getDeaths());
}
// return total item from List
@Override
public int getItemCount() {
return data.size();
}
class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView textKeyId;
TextView textLastUpdate;
TextView textConfirmed;
TextView textDeaths;
// create constructor to get widget reference
public MyHolder(View itemView) {
super(itemView);
textKeyId = (TextView) itemView.findViewById(R.id.textKeyId);
textLastUpdate = (TextView) itemView.findViewById(R.id.textLastUpdate);
textConfirmed = (TextView) itemView.findViewById(R.id.textConfirmed);
textDeaths = (TextView) itemView.findViewById(R.id.textDeaths);
itemView.setOnClickListener(this);
}
// Click event for all items
@Override
public void onClick(View v) {
// Intent goToNewEntryActivity = new Intent(context, NewEntryActivity.class);
// int itemPosition = getAdapterPosition();
// Corona corona = data.get(itemPosition);
// goToNewEntryActivity.putExtra(ENTRY,corona);
// context.startActivity(goToNewEntryActivity);
Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
}
}
}
| UTF-8 | Java | 3,089 | java | Adapter.java | Java | []
| null | []
| package com.example.corona;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import android.content.Intent;
public class Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private LayoutInflater inflater;
List<Corona> data;
public static final String ENTRY = "com.example.corona.ENTRY";
// create constructor to initialize context and data sent from SearchActivity
public Adapter(Context context, List<Corona> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
// Inflate the layout when ViewHolder created
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.container_corona, parent, false);
MyHolder holder = new MyHolder(view);
return holder;
}
// Bind data
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// Get current position of item in RecyclerView to bind data and assign values from list
MyHolder myHolder = (MyHolder) holder;
Corona current = data.get(position);
myHolder.textKeyId.setText(current.getKeyId());
myHolder.textLastUpdate.setText("Last update: " + current.getLastUpdate());
myHolder.textConfirmed.setText("Confirmed: " + current.getConfirmed());
myHolder.textDeaths.setText("Deaths: " + current.getDeaths());
}
// return total item from List
@Override
public int getItemCount() {
return data.size();
}
class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView textKeyId;
TextView textLastUpdate;
TextView textConfirmed;
TextView textDeaths;
// create constructor to get widget reference
public MyHolder(View itemView) {
super(itemView);
textKeyId = (TextView) itemView.findViewById(R.id.textKeyId);
textLastUpdate = (TextView) itemView.findViewById(R.id.textLastUpdate);
textConfirmed = (TextView) itemView.findViewById(R.id.textConfirmed);
textDeaths = (TextView) itemView.findViewById(R.id.textDeaths);
itemView.setOnClickListener(this);
}
// Click event for all items
@Override
public void onClick(View v) {
// Intent goToNewEntryActivity = new Intent(context, NewEntryActivity.class);
// int itemPosition = getAdapterPosition();
// Corona corona = data.get(itemPosition);
// goToNewEntryActivity.putExtra(ENTRY,corona);
// context.startActivity(goToNewEntryActivity);
Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
}
}
}
| 3,089 | 0.676594 | 0.676594 | 91 | 32.835163 | 28.97451 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 4 |
816832e05ead17e9a37edd528e5b2568290c8ceb | 28,011,776,755,494 | 4aac8eaf44e783bea65f74d864cbc69a244cd6f7 | /vfaproject/2/modules/dbtool_server/dbtool_server-service/src/main/java/com/dbtool/services/service/persistence/impl/LoaiSanPhamATTPPersistenceImpl.java | 307b0982d61096400d803480ab646325f85e7906 | []
| no_license | nguyenvquang/vfa2 | https://github.com/nguyenvquang/vfa2 | c176e9b2a5f9eb7fcba0c03e49037b5ead499587 | dddc7ddba177fae599df9793f2953a1868f6871d | refs/heads/master | 2018-09-19T21:57:25.679000 | 2017-06-13T17:44:27 | 2017-06-13T17:44:27 | 93,748,296 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.dbtool.services.service.persistence.impl;
import aQute.bnd.annotation.ProviderType;
import com.dbtool.services.exception.NoSuchLoaiSanPhamATTPException;
import com.dbtool.services.model.LoaiSanPhamATTP;
import com.dbtool.services.model.impl.LoaiSanPhamATTPImpl;
import com.dbtool.services.model.impl.LoaiSanPhamATTPModelImpl;
import com.dbtool.services.service.persistence.LoaiSanPhamATTPPersistence;
import com.liferay.portal.kernel.dao.orm.EntityCache;
import com.liferay.portal.kernel.dao.orm.FinderCache;
import com.liferay.portal.kernel.dao.orm.FinderPath;
import com.liferay.portal.kernel.dao.orm.Query;
import com.liferay.portal.kernel.dao.orm.QueryPos;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.service.ServiceContext;
import com.liferay.portal.kernel.service.ServiceContextThreadLocal;
import com.liferay.portal.kernel.service.persistence.CompanyProvider;
import com.liferay.portal.kernel.service.persistence.CompanyProviderWrapper;
import com.liferay.portal.kernel.service.persistence.impl.BasePersistenceImpl;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.SetUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.uuid.PortalUUIDUtil;
import com.liferay.portal.spring.extender.service.ServiceReference;
import java.io.Serializable;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* The persistence implementation for the loai san pham a t t p service.
*
* <p>
* Caching information and settings can be found in <code>portal.properties</code>
* </p>
*
* @author Brian Wing Shun Chan
* @see LoaiSanPhamATTPPersistence
* @see com.dbtool.services.service.persistence.LoaiSanPhamATTPUtil
* @generated
*/
@ProviderType
public class LoaiSanPhamATTPPersistenceImpl extends BasePersistenceImpl<LoaiSanPhamATTP>
implements LoaiSanPhamATTPPersistence {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify or reference this class directly. Always use {@link LoaiSanPhamATTPUtil} to access the loai san pham a t t p persistence. Modify <code>service.xml</code> and rerun ServiceBuilder to regenerate this class.
*/
public static final String FINDER_CLASS_NAME_ENTITY = LoaiSanPhamATTPImpl.class.getName();
public static final String FINDER_CLASS_NAME_LIST_WITH_PAGINATION = FINDER_CLASS_NAME_ENTITY +
".List1";
public static final String FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION = FINDER_CLASS_NAME_ENTITY +
".List2";
public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_ALL = new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, FINDER_CLASS_NAME_LIST_WITH_PAGINATION,
"findAll", new String[0]);
public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_ALL = new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findAll", new String[0]);
public static final FinderPath FINDER_PATH_COUNT_ALL = new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED, Long.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countAll", new String[0]);
public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_UUID = new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, FINDER_CLASS_NAME_LIST_WITH_PAGINATION,
"findByUuid",
new String[] {
String.class.getName(),
Integer.class.getName(), Integer.class.getName(),
OrderByComparator.class.getName()
});
public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID = new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByUuid",
new String[] { String.class.getName() },
LoaiSanPhamATTPModelImpl.UUID_COLUMN_BITMASK |
LoaiSanPhamATTPModelImpl.TENLOAI_COLUMN_BITMASK);
public static final FinderPath FINDER_PATH_COUNT_BY_UUID = new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED, Long.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByUuid",
new String[] { String.class.getName() });
/**
* Returns all the loai san pham a t t ps where uuid = ?.
*
* @param uuid the uuid
* @return the matching loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findByUuid(String uuid) {
return findByUuid(uuid, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
}
/**
* Returns a range of all the loai san pham a t t ps where uuid = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link LoaiSanPhamATTPModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param uuid the uuid
* @param start the lower bound of the range of loai san pham a t t ps
* @param end the upper bound of the range of loai san pham a t t ps (not inclusive)
* @return the range of matching loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findByUuid(String uuid, int start, int end) {
return findByUuid(uuid, start, end, null);
}
/**
* Returns an ordered range of all the loai san pham a t t ps where uuid = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link LoaiSanPhamATTPModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param uuid the uuid
* @param start the lower bound of the range of loai san pham a t t ps
* @param end the upper bound of the range of loai san pham a t t ps (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of matching loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findByUuid(String uuid, int start, int end,
OrderByComparator<LoaiSanPhamATTP> orderByComparator) {
return findByUuid(uuid, start, end, orderByComparator, true);
}
/**
* Returns an ordered range of all the loai san pham a t t ps where uuid = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link LoaiSanPhamATTPModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param uuid the uuid
* @param start the lower bound of the range of loai san pham a t t ps
* @param end the upper bound of the range of loai san pham a t t ps (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @param retrieveFromCache whether to retrieve from the finder cache
* @return the ordered range of matching loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findByUuid(String uuid, int start, int end,
OrderByComparator<LoaiSanPhamATTP> orderByComparator,
boolean retrieveFromCache) {
boolean pagination = true;
FinderPath finderPath = null;
Object[] finderArgs = null;
if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
(orderByComparator == null)) {
pagination = false;
finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID;
finderArgs = new Object[] { uuid };
}
else {
finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_UUID;
finderArgs = new Object[] { uuid, start, end, orderByComparator };
}
List<LoaiSanPhamATTP> list = null;
if (retrieveFromCache) {
list = (List<LoaiSanPhamATTP>)finderCache.getResult(finderPath,
finderArgs, this);
if ((list != null) && !list.isEmpty()) {
for (LoaiSanPhamATTP loaiSanPhamATTP : list) {
if (!Objects.equals(uuid, loaiSanPhamATTP.getUuid())) {
list = null;
break;
}
}
}
}
if (list == null) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(3 +
(orderByComparator.getOrderByFields().length * 2));
}
else {
query = new StringBundler(3);
}
query.append(_SQL_SELECT_LOAISANPHAMATTP_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_UUID_2);
}
if (orderByComparator != null) {
appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
orderByComparator);
}
else
if (pagination) {
query.append(LoaiSanPhamATTPModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
if (!pagination) {
list = (List<LoaiSanPhamATTP>)QueryUtil.list(q,
getDialect(), start, end, false);
Collections.sort(list);
list = Collections.unmodifiableList(list);
}
else {
list = (List<LoaiSanPhamATTP>)QueryUtil.list(q,
getDialect(), start, end);
}
cacheResult(list);
finderCache.putResult(finderPath, finderArgs, list);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return list;
}
/**
* Returns the first loai san pham a t t p in the ordered set where uuid = ?.
*
* @param uuid the uuid
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching loai san pham a t t p
* @throws NoSuchLoaiSanPhamATTPException if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP findByUuid_First(String uuid,
OrderByComparator<LoaiSanPhamATTP> orderByComparator)
throws NoSuchLoaiSanPhamATTPException {
LoaiSanPhamATTP loaiSanPhamATTP = fetchByUuid_First(uuid,
orderByComparator);
if (loaiSanPhamATTP != null) {
return loaiSanPhamATTP;
}
StringBundler msg = new StringBundler(4);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchLoaiSanPhamATTPException(msg.toString());
}
/**
* Returns the first loai san pham a t t p in the ordered set where uuid = ?.
*
* @param uuid the uuid
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching loai san pham a t t p, or <code>null</code> if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP fetchByUuid_First(String uuid,
OrderByComparator<LoaiSanPhamATTP> orderByComparator) {
List<LoaiSanPhamATTP> list = findByUuid(uuid, 0, 1, orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the last loai san pham a t t p in the ordered set where uuid = ?.
*
* @param uuid the uuid
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching loai san pham a t t p
* @throws NoSuchLoaiSanPhamATTPException if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP findByUuid_Last(String uuid,
OrderByComparator<LoaiSanPhamATTP> orderByComparator)
throws NoSuchLoaiSanPhamATTPException {
LoaiSanPhamATTP loaiSanPhamATTP = fetchByUuid_Last(uuid,
orderByComparator);
if (loaiSanPhamATTP != null) {
return loaiSanPhamATTP;
}
StringBundler msg = new StringBundler(4);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchLoaiSanPhamATTPException(msg.toString());
}
/**
* Returns the last loai san pham a t t p in the ordered set where uuid = ?.
*
* @param uuid the uuid
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching loai san pham a t t p, or <code>null</code> if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP fetchByUuid_Last(String uuid,
OrderByComparator<LoaiSanPhamATTP> orderByComparator) {
int count = countByUuid(uuid);
if (count == 0) {
return null;
}
List<LoaiSanPhamATTP> list = findByUuid(uuid, count - 1, count,
orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the loai san pham a t t ps before and after the current loai san pham a t t p in the ordered set where uuid = ?.
*
* @param loaiSanPhamId the primary key of the current loai san pham a t t p
* @param uuid the uuid
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the previous, current, and next loai san pham a t t p
* @throws NoSuchLoaiSanPhamATTPException if a loai san pham a t t p with the primary key could not be found
*/
@Override
public LoaiSanPhamATTP[] findByUuid_PrevAndNext(long loaiSanPhamId,
String uuid, OrderByComparator<LoaiSanPhamATTP> orderByComparator)
throws NoSuchLoaiSanPhamATTPException {
LoaiSanPhamATTP loaiSanPhamATTP = findByPrimaryKey(loaiSanPhamId);
Session session = null;
try {
session = openSession();
LoaiSanPhamATTP[] array = new LoaiSanPhamATTPImpl[3];
array[0] = getByUuid_PrevAndNext(session, loaiSanPhamATTP, uuid,
orderByComparator, true);
array[1] = loaiSanPhamATTP;
array[2] = getByUuid_PrevAndNext(session, loaiSanPhamATTP, uuid,
orderByComparator, false);
return array;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
}
protected LoaiSanPhamATTP getByUuid_PrevAndNext(Session session,
LoaiSanPhamATTP loaiSanPhamATTP, String uuid,
OrderByComparator<LoaiSanPhamATTP> orderByComparator, boolean previous) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(4 +
(orderByComparator.getOrderByConditionFields().length * 3) +
(orderByComparator.getOrderByFields().length * 3));
}
else {
query = new StringBundler(3);
}
query.append(_SQL_SELECT_LOAISANPHAMATTP_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_UUID_2);
}
if (orderByComparator != null) {
String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();
if (orderByConditionFields.length > 0) {
query.append(WHERE_AND);
}
for (int i = 0; i < orderByConditionFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByConditionFields[i]);
if ((i + 1) < orderByConditionFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN_HAS_NEXT);
}
else {
query.append(WHERE_LESSER_THAN_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN);
}
else {
query.append(WHERE_LESSER_THAN);
}
}
}
query.append(ORDER_BY_CLAUSE);
String[] orderByFields = orderByComparator.getOrderByFields();
for (int i = 0; i < orderByFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByFields[i]);
if ((i + 1) < orderByFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC_HAS_NEXT);
}
else {
query.append(ORDER_BY_DESC_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC);
}
else {
query.append(ORDER_BY_DESC);
}
}
}
}
else {
query.append(LoaiSanPhamATTPModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Query q = session.createQuery(sql);
q.setFirstResult(0);
q.setMaxResults(2);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
if (orderByComparator != null) {
Object[] values = orderByComparator.getOrderByConditionValues(loaiSanPhamATTP);
for (Object value : values) {
qPos.add(value);
}
}
List<LoaiSanPhamATTP> list = q.list();
if (list.size() == 2) {
return list.get(1);
}
else {
return null;
}
}
/**
* Removes all the loai san pham a t t ps where uuid = ? from the database.
*
* @param uuid the uuid
*/
@Override
public void removeByUuid(String uuid) {
for (LoaiSanPhamATTP loaiSanPhamATTP : findByUuid(uuid,
QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(loaiSanPhamATTP);
}
}
/**
* Returns the number of loai san pham a t t ps where uuid = ?.
*
* @param uuid the uuid
* @return the number of matching loai san pham a t t ps
*/
@Override
public int countByUuid(String uuid) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_UUID;
Object[] finderArgs = new Object[] { uuid };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(2);
query.append(_SQL_COUNT_LOAISANPHAMATTP_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_UUID_2);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
}
private static final String _FINDER_COLUMN_UUID_UUID_1 = "loaiSanPhamATTP.uuid IS NULL";
private static final String _FINDER_COLUMN_UUID_UUID_2 = "loaiSanPhamATTP.uuid = ?";
private static final String _FINDER_COLUMN_UUID_UUID_3 = "(loaiSanPhamATTP.uuid IS NULL OR loaiSanPhamATTP.uuid = '')";
public static final FinderPath FINDER_PATH_FETCH_BY_UUID_G = new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, FINDER_CLASS_NAME_ENTITY,
"fetchByUUID_G",
new String[] { String.class.getName(), Long.class.getName() },
LoaiSanPhamATTPModelImpl.UUID_COLUMN_BITMASK |
LoaiSanPhamATTPModelImpl.GROUPID_COLUMN_BITMASK);
public static final FinderPath FINDER_PATH_COUNT_BY_UUID_G = new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED, Long.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByUUID_G",
new String[] { String.class.getName(), Long.class.getName() });
/**
* Returns the loai san pham a t t p where uuid = ? and groupId = ? or throws a {@link NoSuchLoaiSanPhamATTPException} if it could not be found.
*
* @param uuid the uuid
* @param groupId the group ID
* @return the matching loai san pham a t t p
* @throws NoSuchLoaiSanPhamATTPException if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP findByUUID_G(String uuid, long groupId)
throws NoSuchLoaiSanPhamATTPException {
LoaiSanPhamATTP loaiSanPhamATTP = fetchByUUID_G(uuid, groupId);
if (loaiSanPhamATTP == null) {
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(", groupId=");
msg.append(groupId);
msg.append(StringPool.CLOSE_CURLY_BRACE);
if (_log.isDebugEnabled()) {
_log.debug(msg.toString());
}
throw new NoSuchLoaiSanPhamATTPException(msg.toString());
}
return loaiSanPhamATTP;
}
/**
* Returns the loai san pham a t t p where uuid = ? and groupId = ? or returns <code>null</code> if it could not be found. Uses the finder cache.
*
* @param uuid the uuid
* @param groupId the group ID
* @return the matching loai san pham a t t p, or <code>null</code> if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP fetchByUUID_G(String uuid, long groupId) {
return fetchByUUID_G(uuid, groupId, true);
}
/**
* Returns the loai san pham a t t p where uuid = ? and groupId = ? or returns <code>null</code> if it could not be found, optionally using the finder cache.
*
* @param uuid the uuid
* @param groupId the group ID
* @param retrieveFromCache whether to retrieve from the finder cache
* @return the matching loai san pham a t t p, or <code>null</code> if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP fetchByUUID_G(String uuid, long groupId,
boolean retrieveFromCache) {
Object[] finderArgs = new Object[] { uuid, groupId };
Object result = null;
if (retrieveFromCache) {
result = finderCache.getResult(FINDER_PATH_FETCH_BY_UUID_G,
finderArgs, this);
}
if (result instanceof LoaiSanPhamATTP) {
LoaiSanPhamATTP loaiSanPhamATTP = (LoaiSanPhamATTP)result;
if (!Objects.equals(uuid, loaiSanPhamATTP.getUuid()) ||
(groupId != loaiSanPhamATTP.getGroupId())) {
result = null;
}
}
if (result == null) {
StringBundler query = new StringBundler(4);
query.append(_SQL_SELECT_LOAISANPHAMATTP_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_G_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_G_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_G_UUID_2);
}
query.append(_FINDER_COLUMN_UUID_G_GROUPID_2);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
qPos.add(groupId);
List<LoaiSanPhamATTP> list = q.list();
if (list.isEmpty()) {
finderCache.putResult(FINDER_PATH_FETCH_BY_UUID_G,
finderArgs, list);
}
else {
LoaiSanPhamATTP loaiSanPhamATTP = list.get(0);
result = loaiSanPhamATTP;
cacheResult(loaiSanPhamATTP);
if ((loaiSanPhamATTP.getUuid() == null) ||
!loaiSanPhamATTP.getUuid().equals(uuid) ||
(loaiSanPhamATTP.getGroupId() != groupId)) {
finderCache.putResult(FINDER_PATH_FETCH_BY_UUID_G,
finderArgs, loaiSanPhamATTP);
}
}
}
catch (Exception e) {
finderCache.removeResult(FINDER_PATH_FETCH_BY_UUID_G, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
if (result instanceof List<?>) {
return null;
}
else {
return (LoaiSanPhamATTP)result;
}
}
/**
* Removes the loai san pham a t t p where uuid = ? and groupId = ? from the database.
*
* @param uuid the uuid
* @param groupId the group ID
* @return the loai san pham a t t p that was removed
*/
@Override
public LoaiSanPhamATTP removeByUUID_G(String uuid, long groupId)
throws NoSuchLoaiSanPhamATTPException {
LoaiSanPhamATTP loaiSanPhamATTP = findByUUID_G(uuid, groupId);
return remove(loaiSanPhamATTP);
}
/**
* Returns the number of loai san pham a t t ps where uuid = ? and groupId = ?.
*
* @param uuid the uuid
* @param groupId the group ID
* @return the number of matching loai san pham a t t ps
*/
@Override
public int countByUUID_G(String uuid, long groupId) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_UUID_G;
Object[] finderArgs = new Object[] { uuid, groupId };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(3);
query.append(_SQL_COUNT_LOAISANPHAMATTP_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_G_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_G_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_G_UUID_2);
}
query.append(_FINDER_COLUMN_UUID_G_GROUPID_2);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
qPos.add(groupId);
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
}
private static final String _FINDER_COLUMN_UUID_G_UUID_1 = "loaiSanPhamATTP.uuid IS NULL AND ";
private static final String _FINDER_COLUMN_UUID_G_UUID_2 = "loaiSanPhamATTP.uuid = ? AND ";
private static final String _FINDER_COLUMN_UUID_G_UUID_3 = "(loaiSanPhamATTP.uuid IS NULL OR loaiSanPhamATTP.uuid = '') AND ";
private static final String _FINDER_COLUMN_UUID_G_GROUPID_2 = "loaiSanPhamATTP.groupId = ?";
public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_UUID_C = new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, FINDER_CLASS_NAME_LIST_WITH_PAGINATION,
"findByUuid_C",
new String[] {
String.class.getName(), Long.class.getName(),
Integer.class.getName(), Integer.class.getName(),
OrderByComparator.class.getName()
});
public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID_C =
new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByUuid_C",
new String[] { String.class.getName(), Long.class.getName() },
LoaiSanPhamATTPModelImpl.UUID_COLUMN_BITMASK |
LoaiSanPhamATTPModelImpl.COMPANYID_COLUMN_BITMASK |
LoaiSanPhamATTPModelImpl.TENLOAI_COLUMN_BITMASK);
public static final FinderPath FINDER_PATH_COUNT_BY_UUID_C = new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED, Long.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByUuid_C",
new String[] { String.class.getName(), Long.class.getName() });
/**
* Returns all the loai san pham a t t ps where uuid = ? and companyId = ?.
*
* @param uuid the uuid
* @param companyId the company ID
* @return the matching loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findByUuid_C(String uuid, long companyId) {
return findByUuid_C(uuid, companyId, QueryUtil.ALL_POS,
QueryUtil.ALL_POS, null);
}
/**
* Returns a range of all the loai san pham a t t ps where uuid = ? and companyId = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link LoaiSanPhamATTPModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param uuid the uuid
* @param companyId the company ID
* @param start the lower bound of the range of loai san pham a t t ps
* @param end the upper bound of the range of loai san pham a t t ps (not inclusive)
* @return the range of matching loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findByUuid_C(String uuid, long companyId,
int start, int end) {
return findByUuid_C(uuid, companyId, start, end, null);
}
/**
* Returns an ordered range of all the loai san pham a t t ps where uuid = ? and companyId = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link LoaiSanPhamATTPModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param uuid the uuid
* @param companyId the company ID
* @param start the lower bound of the range of loai san pham a t t ps
* @param end the upper bound of the range of loai san pham a t t ps (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of matching loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findByUuid_C(String uuid, long companyId,
int start, int end, OrderByComparator<LoaiSanPhamATTP> orderByComparator) {
return findByUuid_C(uuid, companyId, start, end, orderByComparator, true);
}
/**
* Returns an ordered range of all the loai san pham a t t ps where uuid = ? and companyId = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link LoaiSanPhamATTPModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param uuid the uuid
* @param companyId the company ID
* @param start the lower bound of the range of loai san pham a t t ps
* @param end the upper bound of the range of loai san pham a t t ps (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @param retrieveFromCache whether to retrieve from the finder cache
* @return the ordered range of matching loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findByUuid_C(String uuid, long companyId,
int start, int end,
OrderByComparator<LoaiSanPhamATTP> orderByComparator,
boolean retrieveFromCache) {
boolean pagination = true;
FinderPath finderPath = null;
Object[] finderArgs = null;
if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
(orderByComparator == null)) {
pagination = false;
finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID_C;
finderArgs = new Object[] { uuid, companyId };
}
else {
finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_UUID_C;
finderArgs = new Object[] {
uuid, companyId,
start, end, orderByComparator
};
}
List<LoaiSanPhamATTP> list = null;
if (retrieveFromCache) {
list = (List<LoaiSanPhamATTP>)finderCache.getResult(finderPath,
finderArgs, this);
if ((list != null) && !list.isEmpty()) {
for (LoaiSanPhamATTP loaiSanPhamATTP : list) {
if (!Objects.equals(uuid, loaiSanPhamATTP.getUuid()) ||
(companyId != loaiSanPhamATTP.getCompanyId())) {
list = null;
break;
}
}
}
}
if (list == null) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(4 +
(orderByComparator.getOrderByFields().length * 2));
}
else {
query = new StringBundler(4);
}
query.append(_SQL_SELECT_LOAISANPHAMATTP_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_C_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_C_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_C_UUID_2);
}
query.append(_FINDER_COLUMN_UUID_C_COMPANYID_2);
if (orderByComparator != null) {
appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
orderByComparator);
}
else
if (pagination) {
query.append(LoaiSanPhamATTPModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
qPos.add(companyId);
if (!pagination) {
list = (List<LoaiSanPhamATTP>)QueryUtil.list(q,
getDialect(), start, end, false);
Collections.sort(list);
list = Collections.unmodifiableList(list);
}
else {
list = (List<LoaiSanPhamATTP>)QueryUtil.list(q,
getDialect(), start, end);
}
cacheResult(list);
finderCache.putResult(finderPath, finderArgs, list);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return list;
}
/**
* Returns the first loai san pham a t t p in the ordered set where uuid = ? and companyId = ?.
*
* @param uuid the uuid
* @param companyId the company ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching loai san pham a t t p
* @throws NoSuchLoaiSanPhamATTPException if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP findByUuid_C_First(String uuid, long companyId,
OrderByComparator<LoaiSanPhamATTP> orderByComparator)
throws NoSuchLoaiSanPhamATTPException {
LoaiSanPhamATTP loaiSanPhamATTP = fetchByUuid_C_First(uuid, companyId,
orderByComparator);
if (loaiSanPhamATTP != null) {
return loaiSanPhamATTP;
}
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(", companyId=");
msg.append(companyId);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchLoaiSanPhamATTPException(msg.toString());
}
/**
* Returns the first loai san pham a t t p in the ordered set where uuid = ? and companyId = ?.
*
* @param uuid the uuid
* @param companyId the company ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching loai san pham a t t p, or <code>null</code> if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP fetchByUuid_C_First(String uuid, long companyId,
OrderByComparator<LoaiSanPhamATTP> orderByComparator) {
List<LoaiSanPhamATTP> list = findByUuid_C(uuid, companyId, 0, 1,
orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the last loai san pham a t t p in the ordered set where uuid = ? and companyId = ?.
*
* @param uuid the uuid
* @param companyId the company ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching loai san pham a t t p
* @throws NoSuchLoaiSanPhamATTPException if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP findByUuid_C_Last(String uuid, long companyId,
OrderByComparator<LoaiSanPhamATTP> orderByComparator)
throws NoSuchLoaiSanPhamATTPException {
LoaiSanPhamATTP loaiSanPhamATTP = fetchByUuid_C_Last(uuid, companyId,
orderByComparator);
if (loaiSanPhamATTP != null) {
return loaiSanPhamATTP;
}
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(", companyId=");
msg.append(companyId);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchLoaiSanPhamATTPException(msg.toString());
}
/**
* Returns the last loai san pham a t t p in the ordered set where uuid = ? and companyId = ?.
*
* @param uuid the uuid
* @param companyId the company ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching loai san pham a t t p, or <code>null</code> if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP fetchByUuid_C_Last(String uuid, long companyId,
OrderByComparator<LoaiSanPhamATTP> orderByComparator) {
int count = countByUuid_C(uuid, companyId);
if (count == 0) {
return null;
}
List<LoaiSanPhamATTP> list = findByUuid_C(uuid, companyId, count - 1,
count, orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the loai san pham a t t ps before and after the current loai san pham a t t p in the ordered set where uuid = ? and companyId = ?.
*
* @param loaiSanPhamId the primary key of the current loai san pham a t t p
* @param uuid the uuid
* @param companyId the company ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the previous, current, and next loai san pham a t t p
* @throws NoSuchLoaiSanPhamATTPException if a loai san pham a t t p with the primary key could not be found
*/
@Override
public LoaiSanPhamATTP[] findByUuid_C_PrevAndNext(long loaiSanPhamId,
String uuid, long companyId,
OrderByComparator<LoaiSanPhamATTP> orderByComparator)
throws NoSuchLoaiSanPhamATTPException {
LoaiSanPhamATTP loaiSanPhamATTP = findByPrimaryKey(loaiSanPhamId);
Session session = null;
try {
session = openSession();
LoaiSanPhamATTP[] array = new LoaiSanPhamATTPImpl[3];
array[0] = getByUuid_C_PrevAndNext(session, loaiSanPhamATTP, uuid,
companyId, orderByComparator, true);
array[1] = loaiSanPhamATTP;
array[2] = getByUuid_C_PrevAndNext(session, loaiSanPhamATTP, uuid,
companyId, orderByComparator, false);
return array;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
}
protected LoaiSanPhamATTP getByUuid_C_PrevAndNext(Session session,
LoaiSanPhamATTP loaiSanPhamATTP, String uuid, long companyId,
OrderByComparator<LoaiSanPhamATTP> orderByComparator, boolean previous) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(5 +
(orderByComparator.getOrderByConditionFields().length * 3) +
(orderByComparator.getOrderByFields().length * 3));
}
else {
query = new StringBundler(4);
}
query.append(_SQL_SELECT_LOAISANPHAMATTP_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_C_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_C_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_C_UUID_2);
}
query.append(_FINDER_COLUMN_UUID_C_COMPANYID_2);
if (orderByComparator != null) {
String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();
if (orderByConditionFields.length > 0) {
query.append(WHERE_AND);
}
for (int i = 0; i < orderByConditionFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByConditionFields[i]);
if ((i + 1) < orderByConditionFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN_HAS_NEXT);
}
else {
query.append(WHERE_LESSER_THAN_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN);
}
else {
query.append(WHERE_LESSER_THAN);
}
}
}
query.append(ORDER_BY_CLAUSE);
String[] orderByFields = orderByComparator.getOrderByFields();
for (int i = 0; i < orderByFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByFields[i]);
if ((i + 1) < orderByFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC_HAS_NEXT);
}
else {
query.append(ORDER_BY_DESC_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC);
}
else {
query.append(ORDER_BY_DESC);
}
}
}
}
else {
query.append(LoaiSanPhamATTPModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Query q = session.createQuery(sql);
q.setFirstResult(0);
q.setMaxResults(2);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
qPos.add(companyId);
if (orderByComparator != null) {
Object[] values = orderByComparator.getOrderByConditionValues(loaiSanPhamATTP);
for (Object value : values) {
qPos.add(value);
}
}
List<LoaiSanPhamATTP> list = q.list();
if (list.size() == 2) {
return list.get(1);
}
else {
return null;
}
}
/**
* Removes all the loai san pham a t t ps where uuid = ? and companyId = ? from the database.
*
* @param uuid the uuid
* @param companyId the company ID
*/
@Override
public void removeByUuid_C(String uuid, long companyId) {
for (LoaiSanPhamATTP loaiSanPhamATTP : findByUuid_C(uuid, companyId,
QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(loaiSanPhamATTP);
}
}
/**
* Returns the number of loai san pham a t t ps where uuid = ? and companyId = ?.
*
* @param uuid the uuid
* @param companyId the company ID
* @return the number of matching loai san pham a t t ps
*/
@Override
public int countByUuid_C(String uuid, long companyId) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_UUID_C;
Object[] finderArgs = new Object[] { uuid, companyId };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(3);
query.append(_SQL_COUNT_LOAISANPHAMATTP_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_C_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_C_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_C_UUID_2);
}
query.append(_FINDER_COLUMN_UUID_C_COMPANYID_2);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
qPos.add(companyId);
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
}
private static final String _FINDER_COLUMN_UUID_C_UUID_1 = "loaiSanPhamATTP.uuid IS NULL AND ";
private static final String _FINDER_COLUMN_UUID_C_UUID_2 = "loaiSanPhamATTP.uuid = ? AND ";
private static final String _FINDER_COLUMN_UUID_C_UUID_3 = "(loaiSanPhamATTP.uuid IS NULL OR loaiSanPhamATTP.uuid = '') AND ";
private static final String _FINDER_COLUMN_UUID_C_COMPANYID_2 = "loaiSanPhamATTP.companyId = ?";
public LoaiSanPhamATTPPersistenceImpl() {
setModelClass(LoaiSanPhamATTP.class);
}
/**
* Caches the loai san pham a t t p in the entity cache if it is enabled.
*
* @param loaiSanPhamATTP the loai san pham a t t p
*/
@Override
public void cacheResult(LoaiSanPhamATTP loaiSanPhamATTP) {
entityCache.putResult(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, loaiSanPhamATTP.getPrimaryKey(),
loaiSanPhamATTP);
finderCache.putResult(FINDER_PATH_FETCH_BY_UUID_G,
new Object[] { loaiSanPhamATTP.getUuid(), loaiSanPhamATTP.getGroupId() },
loaiSanPhamATTP);
loaiSanPhamATTP.resetOriginalValues();
}
/**
* Caches the loai san pham a t t ps in the entity cache if it is enabled.
*
* @param loaiSanPhamATTPs the loai san pham a t t ps
*/
@Override
public void cacheResult(List<LoaiSanPhamATTP> loaiSanPhamATTPs) {
for (LoaiSanPhamATTP loaiSanPhamATTP : loaiSanPhamATTPs) {
if (entityCache.getResult(
LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class,
loaiSanPhamATTP.getPrimaryKey()) == null) {
cacheResult(loaiSanPhamATTP);
}
else {
loaiSanPhamATTP.resetOriginalValues();
}
}
}
/**
* Clears the cache for all loai san pham a t t ps.
*
* <p>
* The {@link EntityCache} and {@link FinderCache} are both cleared by this method.
* </p>
*/
@Override
public void clearCache() {
entityCache.clearCache(LoaiSanPhamATTPImpl.class);
finderCache.clearCache(FINDER_CLASS_NAME_ENTITY);
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
}
/**
* Clears the cache for the loai san pham a t t p.
*
* <p>
* The {@link EntityCache} and {@link FinderCache} are both cleared by this method.
* </p>
*/
@Override
public void clearCache(LoaiSanPhamATTP loaiSanPhamATTP) {
entityCache.removeResult(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, loaiSanPhamATTP.getPrimaryKey());
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
clearUniqueFindersCache((LoaiSanPhamATTPModelImpl)loaiSanPhamATTP);
}
@Override
public void clearCache(List<LoaiSanPhamATTP> loaiSanPhamATTPs) {
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
for (LoaiSanPhamATTP loaiSanPhamATTP : loaiSanPhamATTPs) {
entityCache.removeResult(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, loaiSanPhamATTP.getPrimaryKey());
clearUniqueFindersCache((LoaiSanPhamATTPModelImpl)loaiSanPhamATTP);
}
}
protected void cacheUniqueFindersCache(
LoaiSanPhamATTPModelImpl loaiSanPhamATTPModelImpl, boolean isNew) {
if (isNew) {
Object[] args = new Object[] {
loaiSanPhamATTPModelImpl.getUuid(),
loaiSanPhamATTPModelImpl.getGroupId()
};
finderCache.putResult(FINDER_PATH_COUNT_BY_UUID_G, args,
Long.valueOf(1));
finderCache.putResult(FINDER_PATH_FETCH_BY_UUID_G, args,
loaiSanPhamATTPModelImpl);
}
else {
if ((loaiSanPhamATTPModelImpl.getColumnBitmask() &
FINDER_PATH_FETCH_BY_UUID_G.getColumnBitmask()) != 0) {
Object[] args = new Object[] {
loaiSanPhamATTPModelImpl.getUuid(),
loaiSanPhamATTPModelImpl.getGroupId()
};
finderCache.putResult(FINDER_PATH_COUNT_BY_UUID_G, args,
Long.valueOf(1));
finderCache.putResult(FINDER_PATH_FETCH_BY_UUID_G, args,
loaiSanPhamATTPModelImpl);
}
}
}
protected void clearUniqueFindersCache(
LoaiSanPhamATTPModelImpl loaiSanPhamATTPModelImpl) {
Object[] args = new Object[] {
loaiSanPhamATTPModelImpl.getUuid(),
loaiSanPhamATTPModelImpl.getGroupId()
};
finderCache.removeResult(FINDER_PATH_COUNT_BY_UUID_G, args);
finderCache.removeResult(FINDER_PATH_FETCH_BY_UUID_G, args);
if ((loaiSanPhamATTPModelImpl.getColumnBitmask() &
FINDER_PATH_FETCH_BY_UUID_G.getColumnBitmask()) != 0) {
args = new Object[] {
loaiSanPhamATTPModelImpl.getOriginalUuid(),
loaiSanPhamATTPModelImpl.getOriginalGroupId()
};
finderCache.removeResult(FINDER_PATH_COUNT_BY_UUID_G, args);
finderCache.removeResult(FINDER_PATH_FETCH_BY_UUID_G, args);
}
}
/**
* Creates a new loai san pham a t t p with the primary key. Does not add the loai san pham a t t p to the database.
*
* @param loaiSanPhamId the primary key for the new loai san pham a t t p
* @return the new loai san pham a t t p
*/
@Override
public LoaiSanPhamATTP create(long loaiSanPhamId) {
LoaiSanPhamATTP loaiSanPhamATTP = new LoaiSanPhamATTPImpl();
loaiSanPhamATTP.setNew(true);
loaiSanPhamATTP.setPrimaryKey(loaiSanPhamId);
String uuid = PortalUUIDUtil.generate();
loaiSanPhamATTP.setUuid(uuid);
loaiSanPhamATTP.setCompanyId(companyProvider.getCompanyId());
return loaiSanPhamATTP;
}
/**
* Removes the loai san pham a t t p with the primary key from the database. Also notifies the appropriate model listeners.
*
* @param loaiSanPhamId the primary key of the loai san pham a t t p
* @return the loai san pham a t t p that was removed
* @throws NoSuchLoaiSanPhamATTPException if a loai san pham a t t p with the primary key could not be found
*/
@Override
public LoaiSanPhamATTP remove(long loaiSanPhamId)
throws NoSuchLoaiSanPhamATTPException {
return remove((Serializable)loaiSanPhamId);
}
/**
* Removes the loai san pham a t t p with the primary key from the database. Also notifies the appropriate model listeners.
*
* @param primaryKey the primary key of the loai san pham a t t p
* @return the loai san pham a t t p that was removed
* @throws NoSuchLoaiSanPhamATTPException if a loai san pham a t t p with the primary key could not be found
*/
@Override
public LoaiSanPhamATTP remove(Serializable primaryKey)
throws NoSuchLoaiSanPhamATTPException {
Session session = null;
try {
session = openSession();
LoaiSanPhamATTP loaiSanPhamATTP = (LoaiSanPhamATTP)session.get(LoaiSanPhamATTPImpl.class,
primaryKey);
if (loaiSanPhamATTP == null) {
if (_log.isDebugEnabled()) {
_log.debug(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
}
throw new NoSuchLoaiSanPhamATTPException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
primaryKey);
}
return remove(loaiSanPhamATTP);
}
catch (NoSuchLoaiSanPhamATTPException nsee) {
throw nsee;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
}
@Override
protected LoaiSanPhamATTP removeImpl(LoaiSanPhamATTP loaiSanPhamATTP) {
loaiSanPhamATTP = toUnwrappedModel(loaiSanPhamATTP);
Session session = null;
try {
session = openSession();
if (!session.contains(loaiSanPhamATTP)) {
loaiSanPhamATTP = (LoaiSanPhamATTP)session.get(LoaiSanPhamATTPImpl.class,
loaiSanPhamATTP.getPrimaryKeyObj());
}
if (loaiSanPhamATTP != null) {
session.delete(loaiSanPhamATTP);
}
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
if (loaiSanPhamATTP != null) {
clearCache(loaiSanPhamATTP);
}
return loaiSanPhamATTP;
}
@Override
public LoaiSanPhamATTP updateImpl(LoaiSanPhamATTP loaiSanPhamATTP) {
loaiSanPhamATTP = toUnwrappedModel(loaiSanPhamATTP);
boolean isNew = loaiSanPhamATTP.isNew();
LoaiSanPhamATTPModelImpl loaiSanPhamATTPModelImpl = (LoaiSanPhamATTPModelImpl)loaiSanPhamATTP;
if (Validator.isNull(loaiSanPhamATTP.getUuid())) {
String uuid = PortalUUIDUtil.generate();
loaiSanPhamATTP.setUuid(uuid);
}
ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();
Date now = new Date();
if (isNew && (loaiSanPhamATTP.getCreateDate() == null)) {
if (serviceContext == null) {
loaiSanPhamATTP.setCreateDate(now);
}
else {
loaiSanPhamATTP.setCreateDate(serviceContext.getCreateDate(now));
}
}
if (!loaiSanPhamATTPModelImpl.hasSetModifiedDate()) {
if (serviceContext == null) {
loaiSanPhamATTP.setModifiedDate(now);
}
else {
loaiSanPhamATTP.setModifiedDate(serviceContext.getModifiedDate(
now));
}
}
Session session = null;
try {
session = openSession();
if (loaiSanPhamATTP.isNew()) {
session.save(loaiSanPhamATTP);
loaiSanPhamATTP.setNew(false);
}
else {
loaiSanPhamATTP = (LoaiSanPhamATTP)session.merge(loaiSanPhamATTP);
}
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
if (isNew || !LoaiSanPhamATTPModelImpl.COLUMN_BITMASK_ENABLED) {
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
}
else {
if ((loaiSanPhamATTPModelImpl.getColumnBitmask() &
FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID.getColumnBitmask()) != 0) {
Object[] args = new Object[] {
loaiSanPhamATTPModelImpl.getOriginalUuid()
};
finderCache.removeResult(FINDER_PATH_COUNT_BY_UUID, args);
finderCache.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID,
args);
args = new Object[] { loaiSanPhamATTPModelImpl.getUuid() };
finderCache.removeResult(FINDER_PATH_COUNT_BY_UUID, args);
finderCache.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID,
args);
}
if ((loaiSanPhamATTPModelImpl.getColumnBitmask() &
FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID_C.getColumnBitmask()) != 0) {
Object[] args = new Object[] {
loaiSanPhamATTPModelImpl.getOriginalUuid(),
loaiSanPhamATTPModelImpl.getOriginalCompanyId()
};
finderCache.removeResult(FINDER_PATH_COUNT_BY_UUID_C, args);
finderCache.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID_C,
args);
args = new Object[] {
loaiSanPhamATTPModelImpl.getUuid(),
loaiSanPhamATTPModelImpl.getCompanyId()
};
finderCache.removeResult(FINDER_PATH_COUNT_BY_UUID_C, args);
finderCache.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID_C,
args);
}
}
entityCache.putResult(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, loaiSanPhamATTP.getPrimaryKey(),
loaiSanPhamATTP, false);
clearUniqueFindersCache(loaiSanPhamATTPModelImpl);
cacheUniqueFindersCache(loaiSanPhamATTPModelImpl, isNew);
loaiSanPhamATTP.resetOriginalValues();
return loaiSanPhamATTP;
}
protected LoaiSanPhamATTP toUnwrappedModel(LoaiSanPhamATTP loaiSanPhamATTP) {
if (loaiSanPhamATTP instanceof LoaiSanPhamATTPImpl) {
return loaiSanPhamATTP;
}
LoaiSanPhamATTPImpl loaiSanPhamATTPImpl = new LoaiSanPhamATTPImpl();
loaiSanPhamATTPImpl.setNew(loaiSanPhamATTP.isNew());
loaiSanPhamATTPImpl.setPrimaryKey(loaiSanPhamATTP.getPrimaryKey());
loaiSanPhamATTPImpl.setUuid(loaiSanPhamATTP.getUuid());
loaiSanPhamATTPImpl.setLoaiSanPhamId(loaiSanPhamATTP.getLoaiSanPhamId());
loaiSanPhamATTPImpl.setTenLoai(loaiSanPhamATTP.getTenLoai());
loaiSanPhamATTPImpl.setMoTa(loaiSanPhamATTP.getMoTa());
loaiSanPhamATTPImpl.setStatus(loaiSanPhamATTP.getStatus());
loaiSanPhamATTPImpl.setGroupId(loaiSanPhamATTP.getGroupId());
loaiSanPhamATTPImpl.setCompanyId(loaiSanPhamATTP.getCompanyId());
loaiSanPhamATTPImpl.setUserId(loaiSanPhamATTP.getUserId());
loaiSanPhamATTPImpl.setCreateDate(loaiSanPhamATTP.getCreateDate());
loaiSanPhamATTPImpl.setModifiedDate(loaiSanPhamATTP.getModifiedDate());
return loaiSanPhamATTPImpl;
}
/**
* Returns the loai san pham a t t p with the primary key or throws a {@link com.liferay.portal.kernel.exception.NoSuchModelException} if it could not be found.
*
* @param primaryKey the primary key of the loai san pham a t t p
* @return the loai san pham a t t p
* @throws NoSuchLoaiSanPhamATTPException if a loai san pham a t t p with the primary key could not be found
*/
@Override
public LoaiSanPhamATTP findByPrimaryKey(Serializable primaryKey)
throws NoSuchLoaiSanPhamATTPException {
LoaiSanPhamATTP loaiSanPhamATTP = fetchByPrimaryKey(primaryKey);
if (loaiSanPhamATTP == null) {
if (_log.isDebugEnabled()) {
_log.debug(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
}
throw new NoSuchLoaiSanPhamATTPException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
primaryKey);
}
return loaiSanPhamATTP;
}
/**
* Returns the loai san pham a t t p with the primary key or throws a {@link NoSuchLoaiSanPhamATTPException} if it could not be found.
*
* @param loaiSanPhamId the primary key of the loai san pham a t t p
* @return the loai san pham a t t p
* @throws NoSuchLoaiSanPhamATTPException if a loai san pham a t t p with the primary key could not be found
*/
@Override
public LoaiSanPhamATTP findByPrimaryKey(long loaiSanPhamId)
throws NoSuchLoaiSanPhamATTPException {
return findByPrimaryKey((Serializable)loaiSanPhamId);
}
/**
* Returns the loai san pham a t t p with the primary key or returns <code>null</code> if it could not be found.
*
* @param primaryKey the primary key of the loai san pham a t t p
* @return the loai san pham a t t p, or <code>null</code> if a loai san pham a t t p with the primary key could not be found
*/
@Override
public LoaiSanPhamATTP fetchByPrimaryKey(Serializable primaryKey) {
Serializable serializable = entityCache.getResult(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, primaryKey);
if (serializable == nullModel) {
return null;
}
LoaiSanPhamATTP loaiSanPhamATTP = (LoaiSanPhamATTP)serializable;
if (loaiSanPhamATTP == null) {
Session session = null;
try {
session = openSession();
loaiSanPhamATTP = (LoaiSanPhamATTP)session.get(LoaiSanPhamATTPImpl.class,
primaryKey);
if (loaiSanPhamATTP != null) {
cacheResult(loaiSanPhamATTP);
}
else {
entityCache.putResult(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, primaryKey, nullModel);
}
}
catch (Exception e) {
entityCache.removeResult(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, primaryKey);
throw processException(e);
}
finally {
closeSession(session);
}
}
return loaiSanPhamATTP;
}
/**
* Returns the loai san pham a t t p with the primary key or returns <code>null</code> if it could not be found.
*
* @param loaiSanPhamId the primary key of the loai san pham a t t p
* @return the loai san pham a t t p, or <code>null</code> if a loai san pham a t t p with the primary key could not be found
*/
@Override
public LoaiSanPhamATTP fetchByPrimaryKey(long loaiSanPhamId) {
return fetchByPrimaryKey((Serializable)loaiSanPhamId);
}
@Override
public Map<Serializable, LoaiSanPhamATTP> fetchByPrimaryKeys(
Set<Serializable> primaryKeys) {
if (primaryKeys.isEmpty()) {
return Collections.emptyMap();
}
Map<Serializable, LoaiSanPhamATTP> map = new HashMap<Serializable, LoaiSanPhamATTP>();
if (primaryKeys.size() == 1) {
Iterator<Serializable> iterator = primaryKeys.iterator();
Serializable primaryKey = iterator.next();
LoaiSanPhamATTP loaiSanPhamATTP = fetchByPrimaryKey(primaryKey);
if (loaiSanPhamATTP != null) {
map.put(primaryKey, loaiSanPhamATTP);
}
return map;
}
Set<Serializable> uncachedPrimaryKeys = null;
for (Serializable primaryKey : primaryKeys) {
Serializable serializable = entityCache.getResult(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, primaryKey);
if (serializable != nullModel) {
if (serializable == null) {
if (uncachedPrimaryKeys == null) {
uncachedPrimaryKeys = new HashSet<Serializable>();
}
uncachedPrimaryKeys.add(primaryKey);
}
else {
map.put(primaryKey, (LoaiSanPhamATTP)serializable);
}
}
}
if (uncachedPrimaryKeys == null) {
return map;
}
StringBundler query = new StringBundler((uncachedPrimaryKeys.size() * 2) +
1);
query.append(_SQL_SELECT_LOAISANPHAMATTP_WHERE_PKS_IN);
for (Serializable primaryKey : uncachedPrimaryKeys) {
query.append(String.valueOf(primaryKey));
query.append(StringPool.COMMA);
}
query.setIndex(query.index() - 1);
query.append(StringPool.CLOSE_PARENTHESIS);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
for (LoaiSanPhamATTP loaiSanPhamATTP : (List<LoaiSanPhamATTP>)q.list()) {
map.put(loaiSanPhamATTP.getPrimaryKeyObj(), loaiSanPhamATTP);
cacheResult(loaiSanPhamATTP);
uncachedPrimaryKeys.remove(loaiSanPhamATTP.getPrimaryKeyObj());
}
for (Serializable primaryKey : uncachedPrimaryKeys) {
entityCache.putResult(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, primaryKey, nullModel);
}
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
return map;
}
/**
* Returns all the loai san pham a t t ps.
*
* @return the loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findAll() {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
}
/**
* Returns a range of all the loai san pham a t t ps.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link LoaiSanPhamATTPModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param start the lower bound of the range of loai san pham a t t ps
* @param end the upper bound of the range of loai san pham a t t ps (not inclusive)
* @return the range of loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findAll(int start, int end) {
return findAll(start, end, null);
}
/**
* Returns an ordered range of all the loai san pham a t t ps.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link LoaiSanPhamATTPModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param start the lower bound of the range of loai san pham a t t ps
* @param end the upper bound of the range of loai san pham a t t ps (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findAll(int start, int end,
OrderByComparator<LoaiSanPhamATTP> orderByComparator) {
return findAll(start, end, orderByComparator, true);
}
/**
* Returns an ordered range of all the loai san pham a t t ps.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link LoaiSanPhamATTPModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param start the lower bound of the range of loai san pham a t t ps
* @param end the upper bound of the range of loai san pham a t t ps (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @param retrieveFromCache whether to retrieve from the finder cache
* @return the ordered range of loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findAll(int start, int end,
OrderByComparator<LoaiSanPhamATTP> orderByComparator,
boolean retrieveFromCache) {
boolean pagination = true;
FinderPath finderPath = null;
Object[] finderArgs = null;
if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
(orderByComparator == null)) {
pagination = false;
finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_ALL;
finderArgs = FINDER_ARGS_EMPTY;
}
else {
finderPath = FINDER_PATH_WITH_PAGINATION_FIND_ALL;
finderArgs = new Object[] { start, end, orderByComparator };
}
List<LoaiSanPhamATTP> list = null;
if (retrieveFromCache) {
list = (List<LoaiSanPhamATTP>)finderCache.getResult(finderPath,
finderArgs, this);
}
if (list == null) {
StringBundler query = null;
String sql = null;
if (orderByComparator != null) {
query = new StringBundler(2 +
(orderByComparator.getOrderByFields().length * 2));
query.append(_SQL_SELECT_LOAISANPHAMATTP);
appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
orderByComparator);
sql = query.toString();
}
else {
sql = _SQL_SELECT_LOAISANPHAMATTP;
if (pagination) {
sql = sql.concat(LoaiSanPhamATTPModelImpl.ORDER_BY_JPQL);
}
}
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
if (!pagination) {
list = (List<LoaiSanPhamATTP>)QueryUtil.list(q,
getDialect(), start, end, false);
Collections.sort(list);
list = Collections.unmodifiableList(list);
}
else {
list = (List<LoaiSanPhamATTP>)QueryUtil.list(q,
getDialect(), start, end);
}
cacheResult(list);
finderCache.putResult(finderPath, finderArgs, list);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return list;
}
/**
* Removes all the loai san pham a t t ps from the database.
*
*/
@Override
public void removeAll() {
for (LoaiSanPhamATTP loaiSanPhamATTP : findAll()) {
remove(loaiSanPhamATTP);
}
}
/**
* Returns the number of loai san pham a t t ps.
*
* @return the number of loai san pham a t t ps
*/
@Override
public int countAll() {
Long count = (Long)finderCache.getResult(FINDER_PATH_COUNT_ALL,
FINDER_ARGS_EMPTY, this);
if (count == null) {
Session session = null;
try {
session = openSession();
Query q = session.createQuery(_SQL_COUNT_LOAISANPHAMATTP);
count = (Long)q.uniqueResult();
finderCache.putResult(FINDER_PATH_COUNT_ALL, FINDER_ARGS_EMPTY,
count);
}
catch (Exception e) {
finderCache.removeResult(FINDER_PATH_COUNT_ALL,
FINDER_ARGS_EMPTY);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
}
@Override
public Set<String> getBadColumnNames() {
return _badColumnNames;
}
@Override
protected Map<String, Integer> getTableColumnsMap() {
return LoaiSanPhamATTPModelImpl.TABLE_COLUMNS_MAP;
}
/**
* Initializes the loai san pham a t t p persistence.
*/
public void afterPropertiesSet() {
}
public void destroy() {
entityCache.removeCache(LoaiSanPhamATTPImpl.class.getName());
finderCache.removeCache(FINDER_CLASS_NAME_ENTITY);
finderCache.removeCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
finderCache.removeCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
}
@ServiceReference(type = CompanyProviderWrapper.class)
protected CompanyProvider companyProvider;
@ServiceReference(type = EntityCache.class)
protected EntityCache entityCache;
@ServiceReference(type = FinderCache.class)
protected FinderCache finderCache;
private static final String _SQL_SELECT_LOAISANPHAMATTP = "SELECT loaiSanPhamATTP FROM LoaiSanPhamATTP loaiSanPhamATTP";
private static final String _SQL_SELECT_LOAISANPHAMATTP_WHERE_PKS_IN = "SELECT loaiSanPhamATTP FROM LoaiSanPhamATTP loaiSanPhamATTP WHERE loaiSanPhamId IN (";
private static final String _SQL_SELECT_LOAISANPHAMATTP_WHERE = "SELECT loaiSanPhamATTP FROM LoaiSanPhamATTP loaiSanPhamATTP WHERE ";
private static final String _SQL_COUNT_LOAISANPHAMATTP = "SELECT COUNT(loaiSanPhamATTP) FROM LoaiSanPhamATTP loaiSanPhamATTP";
private static final String _SQL_COUNT_LOAISANPHAMATTP_WHERE = "SELECT COUNT(loaiSanPhamATTP) FROM LoaiSanPhamATTP loaiSanPhamATTP WHERE ";
private static final String _ORDER_BY_ENTITY_ALIAS = "loaiSanPhamATTP.";
private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No LoaiSanPhamATTP exists with the primary key ";
private static final String _NO_SUCH_ENTITY_WITH_KEY = "No LoaiSanPhamATTP exists with the key {";
private static final Log _log = LogFactoryUtil.getLog(LoaiSanPhamATTPPersistenceImpl.class);
private static final Set<String> _badColumnNames = SetUtil.fromArray(new String[] {
"uuid"
});
} | UTF-8 | Java | 74,988 | java | LoaiSanPhamATTPPersistenceImpl.java | Java | [
{
"context": "ode>portal.properties</code>\n * </p>\n *\n * @author Brian Wing Shun Chan\n * @see LoaiSanPhamATTPPersistence\n * @see com.db",
"end": 2664,
"score": 0.9736416339874268,
"start": 2644,
"tag": "NAME",
"value": "Brian Wing Shun Chan"
}
]
| null | []
| /**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.dbtool.services.service.persistence.impl;
import aQute.bnd.annotation.ProviderType;
import com.dbtool.services.exception.NoSuchLoaiSanPhamATTPException;
import com.dbtool.services.model.LoaiSanPhamATTP;
import com.dbtool.services.model.impl.LoaiSanPhamATTPImpl;
import com.dbtool.services.model.impl.LoaiSanPhamATTPModelImpl;
import com.dbtool.services.service.persistence.LoaiSanPhamATTPPersistence;
import com.liferay.portal.kernel.dao.orm.EntityCache;
import com.liferay.portal.kernel.dao.orm.FinderCache;
import com.liferay.portal.kernel.dao.orm.FinderPath;
import com.liferay.portal.kernel.dao.orm.Query;
import com.liferay.portal.kernel.dao.orm.QueryPos;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.service.ServiceContext;
import com.liferay.portal.kernel.service.ServiceContextThreadLocal;
import com.liferay.portal.kernel.service.persistence.CompanyProvider;
import com.liferay.portal.kernel.service.persistence.CompanyProviderWrapper;
import com.liferay.portal.kernel.service.persistence.impl.BasePersistenceImpl;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.SetUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.uuid.PortalUUIDUtil;
import com.liferay.portal.spring.extender.service.ServiceReference;
import java.io.Serializable;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* The persistence implementation for the loai san pham a t t p service.
*
* <p>
* Caching information and settings can be found in <code>portal.properties</code>
* </p>
*
* @author <NAME>
* @see LoaiSanPhamATTPPersistence
* @see com.dbtool.services.service.persistence.LoaiSanPhamATTPUtil
* @generated
*/
@ProviderType
public class LoaiSanPhamATTPPersistenceImpl extends BasePersistenceImpl<LoaiSanPhamATTP>
implements LoaiSanPhamATTPPersistence {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify or reference this class directly. Always use {@link LoaiSanPhamATTPUtil} to access the loai san pham a t t p persistence. Modify <code>service.xml</code> and rerun ServiceBuilder to regenerate this class.
*/
public static final String FINDER_CLASS_NAME_ENTITY = LoaiSanPhamATTPImpl.class.getName();
public static final String FINDER_CLASS_NAME_LIST_WITH_PAGINATION = FINDER_CLASS_NAME_ENTITY +
".List1";
public static final String FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION = FINDER_CLASS_NAME_ENTITY +
".List2";
public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_ALL = new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, FINDER_CLASS_NAME_LIST_WITH_PAGINATION,
"findAll", new String[0]);
public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_ALL = new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findAll", new String[0]);
public static final FinderPath FINDER_PATH_COUNT_ALL = new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED, Long.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countAll", new String[0]);
public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_UUID = new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, FINDER_CLASS_NAME_LIST_WITH_PAGINATION,
"findByUuid",
new String[] {
String.class.getName(),
Integer.class.getName(), Integer.class.getName(),
OrderByComparator.class.getName()
});
public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID = new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByUuid",
new String[] { String.class.getName() },
LoaiSanPhamATTPModelImpl.UUID_COLUMN_BITMASK |
LoaiSanPhamATTPModelImpl.TENLOAI_COLUMN_BITMASK);
public static final FinderPath FINDER_PATH_COUNT_BY_UUID = new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED, Long.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByUuid",
new String[] { String.class.getName() });
/**
* Returns all the loai san pham a t t ps where uuid = ?.
*
* @param uuid the uuid
* @return the matching loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findByUuid(String uuid) {
return findByUuid(uuid, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
}
/**
* Returns a range of all the loai san pham a t t ps where uuid = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link LoaiSanPhamATTPModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param uuid the uuid
* @param start the lower bound of the range of loai san pham a t t ps
* @param end the upper bound of the range of loai san pham a t t ps (not inclusive)
* @return the range of matching loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findByUuid(String uuid, int start, int end) {
return findByUuid(uuid, start, end, null);
}
/**
* Returns an ordered range of all the loai san pham a t t ps where uuid = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link LoaiSanPhamATTPModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param uuid the uuid
* @param start the lower bound of the range of loai san pham a t t ps
* @param end the upper bound of the range of loai san pham a t t ps (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of matching loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findByUuid(String uuid, int start, int end,
OrderByComparator<LoaiSanPhamATTP> orderByComparator) {
return findByUuid(uuid, start, end, orderByComparator, true);
}
/**
* Returns an ordered range of all the loai san pham a t t ps where uuid = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link LoaiSanPhamATTPModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param uuid the uuid
* @param start the lower bound of the range of loai san pham a t t ps
* @param end the upper bound of the range of loai san pham a t t ps (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @param retrieveFromCache whether to retrieve from the finder cache
* @return the ordered range of matching loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findByUuid(String uuid, int start, int end,
OrderByComparator<LoaiSanPhamATTP> orderByComparator,
boolean retrieveFromCache) {
boolean pagination = true;
FinderPath finderPath = null;
Object[] finderArgs = null;
if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
(orderByComparator == null)) {
pagination = false;
finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID;
finderArgs = new Object[] { uuid };
}
else {
finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_UUID;
finderArgs = new Object[] { uuid, start, end, orderByComparator };
}
List<LoaiSanPhamATTP> list = null;
if (retrieveFromCache) {
list = (List<LoaiSanPhamATTP>)finderCache.getResult(finderPath,
finderArgs, this);
if ((list != null) && !list.isEmpty()) {
for (LoaiSanPhamATTP loaiSanPhamATTP : list) {
if (!Objects.equals(uuid, loaiSanPhamATTP.getUuid())) {
list = null;
break;
}
}
}
}
if (list == null) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(3 +
(orderByComparator.getOrderByFields().length * 2));
}
else {
query = new StringBundler(3);
}
query.append(_SQL_SELECT_LOAISANPHAMATTP_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_UUID_2);
}
if (orderByComparator != null) {
appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
orderByComparator);
}
else
if (pagination) {
query.append(LoaiSanPhamATTPModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
if (!pagination) {
list = (List<LoaiSanPhamATTP>)QueryUtil.list(q,
getDialect(), start, end, false);
Collections.sort(list);
list = Collections.unmodifiableList(list);
}
else {
list = (List<LoaiSanPhamATTP>)QueryUtil.list(q,
getDialect(), start, end);
}
cacheResult(list);
finderCache.putResult(finderPath, finderArgs, list);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return list;
}
/**
* Returns the first loai san pham a t t p in the ordered set where uuid = ?.
*
* @param uuid the uuid
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching loai san pham a t t p
* @throws NoSuchLoaiSanPhamATTPException if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP findByUuid_First(String uuid,
OrderByComparator<LoaiSanPhamATTP> orderByComparator)
throws NoSuchLoaiSanPhamATTPException {
LoaiSanPhamATTP loaiSanPhamATTP = fetchByUuid_First(uuid,
orderByComparator);
if (loaiSanPhamATTP != null) {
return loaiSanPhamATTP;
}
StringBundler msg = new StringBundler(4);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchLoaiSanPhamATTPException(msg.toString());
}
/**
* Returns the first loai san pham a t t p in the ordered set where uuid = ?.
*
* @param uuid the uuid
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching loai san pham a t t p, or <code>null</code> if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP fetchByUuid_First(String uuid,
OrderByComparator<LoaiSanPhamATTP> orderByComparator) {
List<LoaiSanPhamATTP> list = findByUuid(uuid, 0, 1, orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the last loai san pham a t t p in the ordered set where uuid = ?.
*
* @param uuid the uuid
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching loai san pham a t t p
* @throws NoSuchLoaiSanPhamATTPException if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP findByUuid_Last(String uuid,
OrderByComparator<LoaiSanPhamATTP> orderByComparator)
throws NoSuchLoaiSanPhamATTPException {
LoaiSanPhamATTP loaiSanPhamATTP = fetchByUuid_Last(uuid,
orderByComparator);
if (loaiSanPhamATTP != null) {
return loaiSanPhamATTP;
}
StringBundler msg = new StringBundler(4);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchLoaiSanPhamATTPException(msg.toString());
}
/**
* Returns the last loai san pham a t t p in the ordered set where uuid = ?.
*
* @param uuid the uuid
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching loai san pham a t t p, or <code>null</code> if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP fetchByUuid_Last(String uuid,
OrderByComparator<LoaiSanPhamATTP> orderByComparator) {
int count = countByUuid(uuid);
if (count == 0) {
return null;
}
List<LoaiSanPhamATTP> list = findByUuid(uuid, count - 1, count,
orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the loai san pham a t t ps before and after the current loai san pham a t t p in the ordered set where uuid = ?.
*
* @param loaiSanPhamId the primary key of the current loai san pham a t t p
* @param uuid the uuid
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the previous, current, and next loai san pham a t t p
* @throws NoSuchLoaiSanPhamATTPException if a loai san pham a t t p with the primary key could not be found
*/
@Override
public LoaiSanPhamATTP[] findByUuid_PrevAndNext(long loaiSanPhamId,
String uuid, OrderByComparator<LoaiSanPhamATTP> orderByComparator)
throws NoSuchLoaiSanPhamATTPException {
LoaiSanPhamATTP loaiSanPhamATTP = findByPrimaryKey(loaiSanPhamId);
Session session = null;
try {
session = openSession();
LoaiSanPhamATTP[] array = new LoaiSanPhamATTPImpl[3];
array[0] = getByUuid_PrevAndNext(session, loaiSanPhamATTP, uuid,
orderByComparator, true);
array[1] = loaiSanPhamATTP;
array[2] = getByUuid_PrevAndNext(session, loaiSanPhamATTP, uuid,
orderByComparator, false);
return array;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
}
protected LoaiSanPhamATTP getByUuid_PrevAndNext(Session session,
LoaiSanPhamATTP loaiSanPhamATTP, String uuid,
OrderByComparator<LoaiSanPhamATTP> orderByComparator, boolean previous) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(4 +
(orderByComparator.getOrderByConditionFields().length * 3) +
(orderByComparator.getOrderByFields().length * 3));
}
else {
query = new StringBundler(3);
}
query.append(_SQL_SELECT_LOAISANPHAMATTP_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_UUID_2);
}
if (orderByComparator != null) {
String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();
if (orderByConditionFields.length > 0) {
query.append(WHERE_AND);
}
for (int i = 0; i < orderByConditionFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByConditionFields[i]);
if ((i + 1) < orderByConditionFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN_HAS_NEXT);
}
else {
query.append(WHERE_LESSER_THAN_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN);
}
else {
query.append(WHERE_LESSER_THAN);
}
}
}
query.append(ORDER_BY_CLAUSE);
String[] orderByFields = orderByComparator.getOrderByFields();
for (int i = 0; i < orderByFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByFields[i]);
if ((i + 1) < orderByFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC_HAS_NEXT);
}
else {
query.append(ORDER_BY_DESC_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC);
}
else {
query.append(ORDER_BY_DESC);
}
}
}
}
else {
query.append(LoaiSanPhamATTPModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Query q = session.createQuery(sql);
q.setFirstResult(0);
q.setMaxResults(2);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
if (orderByComparator != null) {
Object[] values = orderByComparator.getOrderByConditionValues(loaiSanPhamATTP);
for (Object value : values) {
qPos.add(value);
}
}
List<LoaiSanPhamATTP> list = q.list();
if (list.size() == 2) {
return list.get(1);
}
else {
return null;
}
}
/**
* Removes all the loai san pham a t t ps where uuid = ? from the database.
*
* @param uuid the uuid
*/
@Override
public void removeByUuid(String uuid) {
for (LoaiSanPhamATTP loaiSanPhamATTP : findByUuid(uuid,
QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(loaiSanPhamATTP);
}
}
/**
* Returns the number of loai san pham a t t ps where uuid = ?.
*
* @param uuid the uuid
* @return the number of matching loai san pham a t t ps
*/
@Override
public int countByUuid(String uuid) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_UUID;
Object[] finderArgs = new Object[] { uuid };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(2);
query.append(_SQL_COUNT_LOAISANPHAMATTP_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_UUID_2);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
}
private static final String _FINDER_COLUMN_UUID_UUID_1 = "loaiSanPhamATTP.uuid IS NULL";
private static final String _FINDER_COLUMN_UUID_UUID_2 = "loaiSanPhamATTP.uuid = ?";
private static final String _FINDER_COLUMN_UUID_UUID_3 = "(loaiSanPhamATTP.uuid IS NULL OR loaiSanPhamATTP.uuid = '')";
public static final FinderPath FINDER_PATH_FETCH_BY_UUID_G = new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, FINDER_CLASS_NAME_ENTITY,
"fetchByUUID_G",
new String[] { String.class.getName(), Long.class.getName() },
LoaiSanPhamATTPModelImpl.UUID_COLUMN_BITMASK |
LoaiSanPhamATTPModelImpl.GROUPID_COLUMN_BITMASK);
public static final FinderPath FINDER_PATH_COUNT_BY_UUID_G = new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED, Long.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByUUID_G",
new String[] { String.class.getName(), Long.class.getName() });
/**
* Returns the loai san pham a t t p where uuid = ? and groupId = ? or throws a {@link NoSuchLoaiSanPhamATTPException} if it could not be found.
*
* @param uuid the uuid
* @param groupId the group ID
* @return the matching loai san pham a t t p
* @throws NoSuchLoaiSanPhamATTPException if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP findByUUID_G(String uuid, long groupId)
throws NoSuchLoaiSanPhamATTPException {
LoaiSanPhamATTP loaiSanPhamATTP = fetchByUUID_G(uuid, groupId);
if (loaiSanPhamATTP == null) {
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(", groupId=");
msg.append(groupId);
msg.append(StringPool.CLOSE_CURLY_BRACE);
if (_log.isDebugEnabled()) {
_log.debug(msg.toString());
}
throw new NoSuchLoaiSanPhamATTPException(msg.toString());
}
return loaiSanPhamATTP;
}
/**
* Returns the loai san pham a t t p where uuid = ? and groupId = ? or returns <code>null</code> if it could not be found. Uses the finder cache.
*
* @param uuid the uuid
* @param groupId the group ID
* @return the matching loai san pham a t t p, or <code>null</code> if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP fetchByUUID_G(String uuid, long groupId) {
return fetchByUUID_G(uuid, groupId, true);
}
/**
* Returns the loai san pham a t t p where uuid = ? and groupId = ? or returns <code>null</code> if it could not be found, optionally using the finder cache.
*
* @param uuid the uuid
* @param groupId the group ID
* @param retrieveFromCache whether to retrieve from the finder cache
* @return the matching loai san pham a t t p, or <code>null</code> if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP fetchByUUID_G(String uuid, long groupId,
boolean retrieveFromCache) {
Object[] finderArgs = new Object[] { uuid, groupId };
Object result = null;
if (retrieveFromCache) {
result = finderCache.getResult(FINDER_PATH_FETCH_BY_UUID_G,
finderArgs, this);
}
if (result instanceof LoaiSanPhamATTP) {
LoaiSanPhamATTP loaiSanPhamATTP = (LoaiSanPhamATTP)result;
if (!Objects.equals(uuid, loaiSanPhamATTP.getUuid()) ||
(groupId != loaiSanPhamATTP.getGroupId())) {
result = null;
}
}
if (result == null) {
StringBundler query = new StringBundler(4);
query.append(_SQL_SELECT_LOAISANPHAMATTP_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_G_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_G_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_G_UUID_2);
}
query.append(_FINDER_COLUMN_UUID_G_GROUPID_2);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
qPos.add(groupId);
List<LoaiSanPhamATTP> list = q.list();
if (list.isEmpty()) {
finderCache.putResult(FINDER_PATH_FETCH_BY_UUID_G,
finderArgs, list);
}
else {
LoaiSanPhamATTP loaiSanPhamATTP = list.get(0);
result = loaiSanPhamATTP;
cacheResult(loaiSanPhamATTP);
if ((loaiSanPhamATTP.getUuid() == null) ||
!loaiSanPhamATTP.getUuid().equals(uuid) ||
(loaiSanPhamATTP.getGroupId() != groupId)) {
finderCache.putResult(FINDER_PATH_FETCH_BY_UUID_G,
finderArgs, loaiSanPhamATTP);
}
}
}
catch (Exception e) {
finderCache.removeResult(FINDER_PATH_FETCH_BY_UUID_G, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
if (result instanceof List<?>) {
return null;
}
else {
return (LoaiSanPhamATTP)result;
}
}
/**
* Removes the loai san pham a t t p where uuid = ? and groupId = ? from the database.
*
* @param uuid the uuid
* @param groupId the group ID
* @return the loai san pham a t t p that was removed
*/
@Override
public LoaiSanPhamATTP removeByUUID_G(String uuid, long groupId)
throws NoSuchLoaiSanPhamATTPException {
LoaiSanPhamATTP loaiSanPhamATTP = findByUUID_G(uuid, groupId);
return remove(loaiSanPhamATTP);
}
/**
* Returns the number of loai san pham a t t ps where uuid = ? and groupId = ?.
*
* @param uuid the uuid
* @param groupId the group ID
* @return the number of matching loai san pham a t t ps
*/
@Override
public int countByUUID_G(String uuid, long groupId) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_UUID_G;
Object[] finderArgs = new Object[] { uuid, groupId };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(3);
query.append(_SQL_COUNT_LOAISANPHAMATTP_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_G_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_G_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_G_UUID_2);
}
query.append(_FINDER_COLUMN_UUID_G_GROUPID_2);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
qPos.add(groupId);
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
}
private static final String _FINDER_COLUMN_UUID_G_UUID_1 = "loaiSanPhamATTP.uuid IS NULL AND ";
private static final String _FINDER_COLUMN_UUID_G_UUID_2 = "loaiSanPhamATTP.uuid = ? AND ";
private static final String _FINDER_COLUMN_UUID_G_UUID_3 = "(loaiSanPhamATTP.uuid IS NULL OR loaiSanPhamATTP.uuid = '') AND ";
private static final String _FINDER_COLUMN_UUID_G_GROUPID_2 = "loaiSanPhamATTP.groupId = ?";
public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_UUID_C = new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, FINDER_CLASS_NAME_LIST_WITH_PAGINATION,
"findByUuid_C",
new String[] {
String.class.getName(), Long.class.getName(),
Integer.class.getName(), Integer.class.getName(),
OrderByComparator.class.getName()
});
public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID_C =
new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByUuid_C",
new String[] { String.class.getName(), Long.class.getName() },
LoaiSanPhamATTPModelImpl.UUID_COLUMN_BITMASK |
LoaiSanPhamATTPModelImpl.COMPANYID_COLUMN_BITMASK |
LoaiSanPhamATTPModelImpl.TENLOAI_COLUMN_BITMASK);
public static final FinderPath FINDER_PATH_COUNT_BY_UUID_C = new FinderPath(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPModelImpl.FINDER_CACHE_ENABLED, Long.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByUuid_C",
new String[] { String.class.getName(), Long.class.getName() });
/**
* Returns all the loai san pham a t t ps where uuid = ? and companyId = ?.
*
* @param uuid the uuid
* @param companyId the company ID
* @return the matching loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findByUuid_C(String uuid, long companyId) {
return findByUuid_C(uuid, companyId, QueryUtil.ALL_POS,
QueryUtil.ALL_POS, null);
}
/**
* Returns a range of all the loai san pham a t t ps where uuid = ? and companyId = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link LoaiSanPhamATTPModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param uuid the uuid
* @param companyId the company ID
* @param start the lower bound of the range of loai san pham a t t ps
* @param end the upper bound of the range of loai san pham a t t ps (not inclusive)
* @return the range of matching loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findByUuid_C(String uuid, long companyId,
int start, int end) {
return findByUuid_C(uuid, companyId, start, end, null);
}
/**
* Returns an ordered range of all the loai san pham a t t ps where uuid = ? and companyId = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link LoaiSanPhamATTPModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param uuid the uuid
* @param companyId the company ID
* @param start the lower bound of the range of loai san pham a t t ps
* @param end the upper bound of the range of loai san pham a t t ps (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of matching loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findByUuid_C(String uuid, long companyId,
int start, int end, OrderByComparator<LoaiSanPhamATTP> orderByComparator) {
return findByUuid_C(uuid, companyId, start, end, orderByComparator, true);
}
/**
* Returns an ordered range of all the loai san pham a t t ps where uuid = ? and companyId = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link LoaiSanPhamATTPModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param uuid the uuid
* @param companyId the company ID
* @param start the lower bound of the range of loai san pham a t t ps
* @param end the upper bound of the range of loai san pham a t t ps (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @param retrieveFromCache whether to retrieve from the finder cache
* @return the ordered range of matching loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findByUuid_C(String uuid, long companyId,
int start, int end,
OrderByComparator<LoaiSanPhamATTP> orderByComparator,
boolean retrieveFromCache) {
boolean pagination = true;
FinderPath finderPath = null;
Object[] finderArgs = null;
if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
(orderByComparator == null)) {
pagination = false;
finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID_C;
finderArgs = new Object[] { uuid, companyId };
}
else {
finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_UUID_C;
finderArgs = new Object[] {
uuid, companyId,
start, end, orderByComparator
};
}
List<LoaiSanPhamATTP> list = null;
if (retrieveFromCache) {
list = (List<LoaiSanPhamATTP>)finderCache.getResult(finderPath,
finderArgs, this);
if ((list != null) && !list.isEmpty()) {
for (LoaiSanPhamATTP loaiSanPhamATTP : list) {
if (!Objects.equals(uuid, loaiSanPhamATTP.getUuid()) ||
(companyId != loaiSanPhamATTP.getCompanyId())) {
list = null;
break;
}
}
}
}
if (list == null) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(4 +
(orderByComparator.getOrderByFields().length * 2));
}
else {
query = new StringBundler(4);
}
query.append(_SQL_SELECT_LOAISANPHAMATTP_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_C_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_C_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_C_UUID_2);
}
query.append(_FINDER_COLUMN_UUID_C_COMPANYID_2);
if (orderByComparator != null) {
appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
orderByComparator);
}
else
if (pagination) {
query.append(LoaiSanPhamATTPModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
qPos.add(companyId);
if (!pagination) {
list = (List<LoaiSanPhamATTP>)QueryUtil.list(q,
getDialect(), start, end, false);
Collections.sort(list);
list = Collections.unmodifiableList(list);
}
else {
list = (List<LoaiSanPhamATTP>)QueryUtil.list(q,
getDialect(), start, end);
}
cacheResult(list);
finderCache.putResult(finderPath, finderArgs, list);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return list;
}
/**
* Returns the first loai san pham a t t p in the ordered set where uuid = ? and companyId = ?.
*
* @param uuid the uuid
* @param companyId the company ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching loai san pham a t t p
* @throws NoSuchLoaiSanPhamATTPException if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP findByUuid_C_First(String uuid, long companyId,
OrderByComparator<LoaiSanPhamATTP> orderByComparator)
throws NoSuchLoaiSanPhamATTPException {
LoaiSanPhamATTP loaiSanPhamATTP = fetchByUuid_C_First(uuid, companyId,
orderByComparator);
if (loaiSanPhamATTP != null) {
return loaiSanPhamATTP;
}
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(", companyId=");
msg.append(companyId);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchLoaiSanPhamATTPException(msg.toString());
}
/**
* Returns the first loai san pham a t t p in the ordered set where uuid = ? and companyId = ?.
*
* @param uuid the uuid
* @param companyId the company ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching loai san pham a t t p, or <code>null</code> if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP fetchByUuid_C_First(String uuid, long companyId,
OrderByComparator<LoaiSanPhamATTP> orderByComparator) {
List<LoaiSanPhamATTP> list = findByUuid_C(uuid, companyId, 0, 1,
orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the last loai san pham a t t p in the ordered set where uuid = ? and companyId = ?.
*
* @param uuid the uuid
* @param companyId the company ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching loai san pham a t t p
* @throws NoSuchLoaiSanPhamATTPException if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP findByUuid_C_Last(String uuid, long companyId,
OrderByComparator<LoaiSanPhamATTP> orderByComparator)
throws NoSuchLoaiSanPhamATTPException {
LoaiSanPhamATTP loaiSanPhamATTP = fetchByUuid_C_Last(uuid, companyId,
orderByComparator);
if (loaiSanPhamATTP != null) {
return loaiSanPhamATTP;
}
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(", companyId=");
msg.append(companyId);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchLoaiSanPhamATTPException(msg.toString());
}
/**
* Returns the last loai san pham a t t p in the ordered set where uuid = ? and companyId = ?.
*
* @param uuid the uuid
* @param companyId the company ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching loai san pham a t t p, or <code>null</code> if a matching loai san pham a t t p could not be found
*/
@Override
public LoaiSanPhamATTP fetchByUuid_C_Last(String uuid, long companyId,
OrderByComparator<LoaiSanPhamATTP> orderByComparator) {
int count = countByUuid_C(uuid, companyId);
if (count == 0) {
return null;
}
List<LoaiSanPhamATTP> list = findByUuid_C(uuid, companyId, count - 1,
count, orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the loai san pham a t t ps before and after the current loai san pham a t t p in the ordered set where uuid = ? and companyId = ?.
*
* @param loaiSanPhamId the primary key of the current loai san pham a t t p
* @param uuid the uuid
* @param companyId the company ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the previous, current, and next loai san pham a t t p
* @throws NoSuchLoaiSanPhamATTPException if a loai san pham a t t p with the primary key could not be found
*/
@Override
public LoaiSanPhamATTP[] findByUuid_C_PrevAndNext(long loaiSanPhamId,
String uuid, long companyId,
OrderByComparator<LoaiSanPhamATTP> orderByComparator)
throws NoSuchLoaiSanPhamATTPException {
LoaiSanPhamATTP loaiSanPhamATTP = findByPrimaryKey(loaiSanPhamId);
Session session = null;
try {
session = openSession();
LoaiSanPhamATTP[] array = new LoaiSanPhamATTPImpl[3];
array[0] = getByUuid_C_PrevAndNext(session, loaiSanPhamATTP, uuid,
companyId, orderByComparator, true);
array[1] = loaiSanPhamATTP;
array[2] = getByUuid_C_PrevAndNext(session, loaiSanPhamATTP, uuid,
companyId, orderByComparator, false);
return array;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
}
protected LoaiSanPhamATTP getByUuid_C_PrevAndNext(Session session,
LoaiSanPhamATTP loaiSanPhamATTP, String uuid, long companyId,
OrderByComparator<LoaiSanPhamATTP> orderByComparator, boolean previous) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(5 +
(orderByComparator.getOrderByConditionFields().length * 3) +
(orderByComparator.getOrderByFields().length * 3));
}
else {
query = new StringBundler(4);
}
query.append(_SQL_SELECT_LOAISANPHAMATTP_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_C_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_C_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_C_UUID_2);
}
query.append(_FINDER_COLUMN_UUID_C_COMPANYID_2);
if (orderByComparator != null) {
String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();
if (orderByConditionFields.length > 0) {
query.append(WHERE_AND);
}
for (int i = 0; i < orderByConditionFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByConditionFields[i]);
if ((i + 1) < orderByConditionFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN_HAS_NEXT);
}
else {
query.append(WHERE_LESSER_THAN_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN);
}
else {
query.append(WHERE_LESSER_THAN);
}
}
}
query.append(ORDER_BY_CLAUSE);
String[] orderByFields = orderByComparator.getOrderByFields();
for (int i = 0; i < orderByFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByFields[i]);
if ((i + 1) < orderByFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC_HAS_NEXT);
}
else {
query.append(ORDER_BY_DESC_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC);
}
else {
query.append(ORDER_BY_DESC);
}
}
}
}
else {
query.append(LoaiSanPhamATTPModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Query q = session.createQuery(sql);
q.setFirstResult(0);
q.setMaxResults(2);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
qPos.add(companyId);
if (orderByComparator != null) {
Object[] values = orderByComparator.getOrderByConditionValues(loaiSanPhamATTP);
for (Object value : values) {
qPos.add(value);
}
}
List<LoaiSanPhamATTP> list = q.list();
if (list.size() == 2) {
return list.get(1);
}
else {
return null;
}
}
/**
* Removes all the loai san pham a t t ps where uuid = ? and companyId = ? from the database.
*
* @param uuid the uuid
* @param companyId the company ID
*/
@Override
public void removeByUuid_C(String uuid, long companyId) {
for (LoaiSanPhamATTP loaiSanPhamATTP : findByUuid_C(uuid, companyId,
QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(loaiSanPhamATTP);
}
}
/**
* Returns the number of loai san pham a t t ps where uuid = ? and companyId = ?.
*
* @param uuid the uuid
* @param companyId the company ID
* @return the number of matching loai san pham a t t ps
*/
@Override
public int countByUuid_C(String uuid, long companyId) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_UUID_C;
Object[] finderArgs = new Object[] { uuid, companyId };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(3);
query.append(_SQL_COUNT_LOAISANPHAMATTP_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_C_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_C_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_C_UUID_2);
}
query.append(_FINDER_COLUMN_UUID_C_COMPANYID_2);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
qPos.add(companyId);
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
}
private static final String _FINDER_COLUMN_UUID_C_UUID_1 = "loaiSanPhamATTP.uuid IS NULL AND ";
private static final String _FINDER_COLUMN_UUID_C_UUID_2 = "loaiSanPhamATTP.uuid = ? AND ";
private static final String _FINDER_COLUMN_UUID_C_UUID_3 = "(loaiSanPhamATTP.uuid IS NULL OR loaiSanPhamATTP.uuid = '') AND ";
private static final String _FINDER_COLUMN_UUID_C_COMPANYID_2 = "loaiSanPhamATTP.companyId = ?";
public LoaiSanPhamATTPPersistenceImpl() {
setModelClass(LoaiSanPhamATTP.class);
}
/**
* Caches the loai san pham a t t p in the entity cache if it is enabled.
*
* @param loaiSanPhamATTP the loai san pham a t t p
*/
@Override
public void cacheResult(LoaiSanPhamATTP loaiSanPhamATTP) {
entityCache.putResult(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, loaiSanPhamATTP.getPrimaryKey(),
loaiSanPhamATTP);
finderCache.putResult(FINDER_PATH_FETCH_BY_UUID_G,
new Object[] { loaiSanPhamATTP.getUuid(), loaiSanPhamATTP.getGroupId() },
loaiSanPhamATTP);
loaiSanPhamATTP.resetOriginalValues();
}
/**
* Caches the loai san pham a t t ps in the entity cache if it is enabled.
*
* @param loaiSanPhamATTPs the loai san pham a t t ps
*/
@Override
public void cacheResult(List<LoaiSanPhamATTP> loaiSanPhamATTPs) {
for (LoaiSanPhamATTP loaiSanPhamATTP : loaiSanPhamATTPs) {
if (entityCache.getResult(
LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class,
loaiSanPhamATTP.getPrimaryKey()) == null) {
cacheResult(loaiSanPhamATTP);
}
else {
loaiSanPhamATTP.resetOriginalValues();
}
}
}
/**
* Clears the cache for all loai san pham a t t ps.
*
* <p>
* The {@link EntityCache} and {@link FinderCache} are both cleared by this method.
* </p>
*/
@Override
public void clearCache() {
entityCache.clearCache(LoaiSanPhamATTPImpl.class);
finderCache.clearCache(FINDER_CLASS_NAME_ENTITY);
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
}
/**
* Clears the cache for the loai san pham a t t p.
*
* <p>
* The {@link EntityCache} and {@link FinderCache} are both cleared by this method.
* </p>
*/
@Override
public void clearCache(LoaiSanPhamATTP loaiSanPhamATTP) {
entityCache.removeResult(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, loaiSanPhamATTP.getPrimaryKey());
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
clearUniqueFindersCache((LoaiSanPhamATTPModelImpl)loaiSanPhamATTP);
}
@Override
public void clearCache(List<LoaiSanPhamATTP> loaiSanPhamATTPs) {
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
for (LoaiSanPhamATTP loaiSanPhamATTP : loaiSanPhamATTPs) {
entityCache.removeResult(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, loaiSanPhamATTP.getPrimaryKey());
clearUniqueFindersCache((LoaiSanPhamATTPModelImpl)loaiSanPhamATTP);
}
}
protected void cacheUniqueFindersCache(
LoaiSanPhamATTPModelImpl loaiSanPhamATTPModelImpl, boolean isNew) {
if (isNew) {
Object[] args = new Object[] {
loaiSanPhamATTPModelImpl.getUuid(),
loaiSanPhamATTPModelImpl.getGroupId()
};
finderCache.putResult(FINDER_PATH_COUNT_BY_UUID_G, args,
Long.valueOf(1));
finderCache.putResult(FINDER_PATH_FETCH_BY_UUID_G, args,
loaiSanPhamATTPModelImpl);
}
else {
if ((loaiSanPhamATTPModelImpl.getColumnBitmask() &
FINDER_PATH_FETCH_BY_UUID_G.getColumnBitmask()) != 0) {
Object[] args = new Object[] {
loaiSanPhamATTPModelImpl.getUuid(),
loaiSanPhamATTPModelImpl.getGroupId()
};
finderCache.putResult(FINDER_PATH_COUNT_BY_UUID_G, args,
Long.valueOf(1));
finderCache.putResult(FINDER_PATH_FETCH_BY_UUID_G, args,
loaiSanPhamATTPModelImpl);
}
}
}
protected void clearUniqueFindersCache(
LoaiSanPhamATTPModelImpl loaiSanPhamATTPModelImpl) {
Object[] args = new Object[] {
loaiSanPhamATTPModelImpl.getUuid(),
loaiSanPhamATTPModelImpl.getGroupId()
};
finderCache.removeResult(FINDER_PATH_COUNT_BY_UUID_G, args);
finderCache.removeResult(FINDER_PATH_FETCH_BY_UUID_G, args);
if ((loaiSanPhamATTPModelImpl.getColumnBitmask() &
FINDER_PATH_FETCH_BY_UUID_G.getColumnBitmask()) != 0) {
args = new Object[] {
loaiSanPhamATTPModelImpl.getOriginalUuid(),
loaiSanPhamATTPModelImpl.getOriginalGroupId()
};
finderCache.removeResult(FINDER_PATH_COUNT_BY_UUID_G, args);
finderCache.removeResult(FINDER_PATH_FETCH_BY_UUID_G, args);
}
}
/**
* Creates a new loai san pham a t t p with the primary key. Does not add the loai san pham a t t p to the database.
*
* @param loaiSanPhamId the primary key for the new loai san pham a t t p
* @return the new loai san pham a t t p
*/
@Override
public LoaiSanPhamATTP create(long loaiSanPhamId) {
LoaiSanPhamATTP loaiSanPhamATTP = new LoaiSanPhamATTPImpl();
loaiSanPhamATTP.setNew(true);
loaiSanPhamATTP.setPrimaryKey(loaiSanPhamId);
String uuid = PortalUUIDUtil.generate();
loaiSanPhamATTP.setUuid(uuid);
loaiSanPhamATTP.setCompanyId(companyProvider.getCompanyId());
return loaiSanPhamATTP;
}
/**
* Removes the loai san pham a t t p with the primary key from the database. Also notifies the appropriate model listeners.
*
* @param loaiSanPhamId the primary key of the loai san pham a t t p
* @return the loai san pham a t t p that was removed
* @throws NoSuchLoaiSanPhamATTPException if a loai san pham a t t p with the primary key could not be found
*/
@Override
public LoaiSanPhamATTP remove(long loaiSanPhamId)
throws NoSuchLoaiSanPhamATTPException {
return remove((Serializable)loaiSanPhamId);
}
/**
* Removes the loai san pham a t t p with the primary key from the database. Also notifies the appropriate model listeners.
*
* @param primaryKey the primary key of the loai san pham a t t p
* @return the loai san pham a t t p that was removed
* @throws NoSuchLoaiSanPhamATTPException if a loai san pham a t t p with the primary key could not be found
*/
@Override
public LoaiSanPhamATTP remove(Serializable primaryKey)
throws NoSuchLoaiSanPhamATTPException {
Session session = null;
try {
session = openSession();
LoaiSanPhamATTP loaiSanPhamATTP = (LoaiSanPhamATTP)session.get(LoaiSanPhamATTPImpl.class,
primaryKey);
if (loaiSanPhamATTP == null) {
if (_log.isDebugEnabled()) {
_log.debug(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
}
throw new NoSuchLoaiSanPhamATTPException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
primaryKey);
}
return remove(loaiSanPhamATTP);
}
catch (NoSuchLoaiSanPhamATTPException nsee) {
throw nsee;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
}
@Override
protected LoaiSanPhamATTP removeImpl(LoaiSanPhamATTP loaiSanPhamATTP) {
loaiSanPhamATTP = toUnwrappedModel(loaiSanPhamATTP);
Session session = null;
try {
session = openSession();
if (!session.contains(loaiSanPhamATTP)) {
loaiSanPhamATTP = (LoaiSanPhamATTP)session.get(LoaiSanPhamATTPImpl.class,
loaiSanPhamATTP.getPrimaryKeyObj());
}
if (loaiSanPhamATTP != null) {
session.delete(loaiSanPhamATTP);
}
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
if (loaiSanPhamATTP != null) {
clearCache(loaiSanPhamATTP);
}
return loaiSanPhamATTP;
}
@Override
public LoaiSanPhamATTP updateImpl(LoaiSanPhamATTP loaiSanPhamATTP) {
loaiSanPhamATTP = toUnwrappedModel(loaiSanPhamATTP);
boolean isNew = loaiSanPhamATTP.isNew();
LoaiSanPhamATTPModelImpl loaiSanPhamATTPModelImpl = (LoaiSanPhamATTPModelImpl)loaiSanPhamATTP;
if (Validator.isNull(loaiSanPhamATTP.getUuid())) {
String uuid = PortalUUIDUtil.generate();
loaiSanPhamATTP.setUuid(uuid);
}
ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();
Date now = new Date();
if (isNew && (loaiSanPhamATTP.getCreateDate() == null)) {
if (serviceContext == null) {
loaiSanPhamATTP.setCreateDate(now);
}
else {
loaiSanPhamATTP.setCreateDate(serviceContext.getCreateDate(now));
}
}
if (!loaiSanPhamATTPModelImpl.hasSetModifiedDate()) {
if (serviceContext == null) {
loaiSanPhamATTP.setModifiedDate(now);
}
else {
loaiSanPhamATTP.setModifiedDate(serviceContext.getModifiedDate(
now));
}
}
Session session = null;
try {
session = openSession();
if (loaiSanPhamATTP.isNew()) {
session.save(loaiSanPhamATTP);
loaiSanPhamATTP.setNew(false);
}
else {
loaiSanPhamATTP = (LoaiSanPhamATTP)session.merge(loaiSanPhamATTP);
}
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
if (isNew || !LoaiSanPhamATTPModelImpl.COLUMN_BITMASK_ENABLED) {
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
}
else {
if ((loaiSanPhamATTPModelImpl.getColumnBitmask() &
FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID.getColumnBitmask()) != 0) {
Object[] args = new Object[] {
loaiSanPhamATTPModelImpl.getOriginalUuid()
};
finderCache.removeResult(FINDER_PATH_COUNT_BY_UUID, args);
finderCache.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID,
args);
args = new Object[] { loaiSanPhamATTPModelImpl.getUuid() };
finderCache.removeResult(FINDER_PATH_COUNT_BY_UUID, args);
finderCache.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID,
args);
}
if ((loaiSanPhamATTPModelImpl.getColumnBitmask() &
FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID_C.getColumnBitmask()) != 0) {
Object[] args = new Object[] {
loaiSanPhamATTPModelImpl.getOriginalUuid(),
loaiSanPhamATTPModelImpl.getOriginalCompanyId()
};
finderCache.removeResult(FINDER_PATH_COUNT_BY_UUID_C, args);
finderCache.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID_C,
args);
args = new Object[] {
loaiSanPhamATTPModelImpl.getUuid(),
loaiSanPhamATTPModelImpl.getCompanyId()
};
finderCache.removeResult(FINDER_PATH_COUNT_BY_UUID_C, args);
finderCache.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID_C,
args);
}
}
entityCache.putResult(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, loaiSanPhamATTP.getPrimaryKey(),
loaiSanPhamATTP, false);
clearUniqueFindersCache(loaiSanPhamATTPModelImpl);
cacheUniqueFindersCache(loaiSanPhamATTPModelImpl, isNew);
loaiSanPhamATTP.resetOriginalValues();
return loaiSanPhamATTP;
}
protected LoaiSanPhamATTP toUnwrappedModel(LoaiSanPhamATTP loaiSanPhamATTP) {
if (loaiSanPhamATTP instanceof LoaiSanPhamATTPImpl) {
return loaiSanPhamATTP;
}
LoaiSanPhamATTPImpl loaiSanPhamATTPImpl = new LoaiSanPhamATTPImpl();
loaiSanPhamATTPImpl.setNew(loaiSanPhamATTP.isNew());
loaiSanPhamATTPImpl.setPrimaryKey(loaiSanPhamATTP.getPrimaryKey());
loaiSanPhamATTPImpl.setUuid(loaiSanPhamATTP.getUuid());
loaiSanPhamATTPImpl.setLoaiSanPhamId(loaiSanPhamATTP.getLoaiSanPhamId());
loaiSanPhamATTPImpl.setTenLoai(loaiSanPhamATTP.getTenLoai());
loaiSanPhamATTPImpl.setMoTa(loaiSanPhamATTP.getMoTa());
loaiSanPhamATTPImpl.setStatus(loaiSanPhamATTP.getStatus());
loaiSanPhamATTPImpl.setGroupId(loaiSanPhamATTP.getGroupId());
loaiSanPhamATTPImpl.setCompanyId(loaiSanPhamATTP.getCompanyId());
loaiSanPhamATTPImpl.setUserId(loaiSanPhamATTP.getUserId());
loaiSanPhamATTPImpl.setCreateDate(loaiSanPhamATTP.getCreateDate());
loaiSanPhamATTPImpl.setModifiedDate(loaiSanPhamATTP.getModifiedDate());
return loaiSanPhamATTPImpl;
}
/**
* Returns the loai san pham a t t p with the primary key or throws a {@link com.liferay.portal.kernel.exception.NoSuchModelException} if it could not be found.
*
* @param primaryKey the primary key of the loai san pham a t t p
* @return the loai san pham a t t p
* @throws NoSuchLoaiSanPhamATTPException if a loai san pham a t t p with the primary key could not be found
*/
@Override
public LoaiSanPhamATTP findByPrimaryKey(Serializable primaryKey)
throws NoSuchLoaiSanPhamATTPException {
LoaiSanPhamATTP loaiSanPhamATTP = fetchByPrimaryKey(primaryKey);
if (loaiSanPhamATTP == null) {
if (_log.isDebugEnabled()) {
_log.debug(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
}
throw new NoSuchLoaiSanPhamATTPException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
primaryKey);
}
return loaiSanPhamATTP;
}
/**
* Returns the loai san pham a t t p with the primary key or throws a {@link NoSuchLoaiSanPhamATTPException} if it could not be found.
*
* @param loaiSanPhamId the primary key of the loai san pham a t t p
* @return the loai san pham a t t p
* @throws NoSuchLoaiSanPhamATTPException if a loai san pham a t t p with the primary key could not be found
*/
@Override
public LoaiSanPhamATTP findByPrimaryKey(long loaiSanPhamId)
throws NoSuchLoaiSanPhamATTPException {
return findByPrimaryKey((Serializable)loaiSanPhamId);
}
/**
* Returns the loai san pham a t t p with the primary key or returns <code>null</code> if it could not be found.
*
* @param primaryKey the primary key of the loai san pham a t t p
* @return the loai san pham a t t p, or <code>null</code> if a loai san pham a t t p with the primary key could not be found
*/
@Override
public LoaiSanPhamATTP fetchByPrimaryKey(Serializable primaryKey) {
Serializable serializable = entityCache.getResult(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, primaryKey);
if (serializable == nullModel) {
return null;
}
LoaiSanPhamATTP loaiSanPhamATTP = (LoaiSanPhamATTP)serializable;
if (loaiSanPhamATTP == null) {
Session session = null;
try {
session = openSession();
loaiSanPhamATTP = (LoaiSanPhamATTP)session.get(LoaiSanPhamATTPImpl.class,
primaryKey);
if (loaiSanPhamATTP != null) {
cacheResult(loaiSanPhamATTP);
}
else {
entityCache.putResult(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, primaryKey, nullModel);
}
}
catch (Exception e) {
entityCache.removeResult(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, primaryKey);
throw processException(e);
}
finally {
closeSession(session);
}
}
return loaiSanPhamATTP;
}
/**
* Returns the loai san pham a t t p with the primary key or returns <code>null</code> if it could not be found.
*
* @param loaiSanPhamId the primary key of the loai san pham a t t p
* @return the loai san pham a t t p, or <code>null</code> if a loai san pham a t t p with the primary key could not be found
*/
@Override
public LoaiSanPhamATTP fetchByPrimaryKey(long loaiSanPhamId) {
return fetchByPrimaryKey((Serializable)loaiSanPhamId);
}
@Override
public Map<Serializable, LoaiSanPhamATTP> fetchByPrimaryKeys(
Set<Serializable> primaryKeys) {
if (primaryKeys.isEmpty()) {
return Collections.emptyMap();
}
Map<Serializable, LoaiSanPhamATTP> map = new HashMap<Serializable, LoaiSanPhamATTP>();
if (primaryKeys.size() == 1) {
Iterator<Serializable> iterator = primaryKeys.iterator();
Serializable primaryKey = iterator.next();
LoaiSanPhamATTP loaiSanPhamATTP = fetchByPrimaryKey(primaryKey);
if (loaiSanPhamATTP != null) {
map.put(primaryKey, loaiSanPhamATTP);
}
return map;
}
Set<Serializable> uncachedPrimaryKeys = null;
for (Serializable primaryKey : primaryKeys) {
Serializable serializable = entityCache.getResult(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, primaryKey);
if (serializable != nullModel) {
if (serializable == null) {
if (uncachedPrimaryKeys == null) {
uncachedPrimaryKeys = new HashSet<Serializable>();
}
uncachedPrimaryKeys.add(primaryKey);
}
else {
map.put(primaryKey, (LoaiSanPhamATTP)serializable);
}
}
}
if (uncachedPrimaryKeys == null) {
return map;
}
StringBundler query = new StringBundler((uncachedPrimaryKeys.size() * 2) +
1);
query.append(_SQL_SELECT_LOAISANPHAMATTP_WHERE_PKS_IN);
for (Serializable primaryKey : uncachedPrimaryKeys) {
query.append(String.valueOf(primaryKey));
query.append(StringPool.COMMA);
}
query.setIndex(query.index() - 1);
query.append(StringPool.CLOSE_PARENTHESIS);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
for (LoaiSanPhamATTP loaiSanPhamATTP : (List<LoaiSanPhamATTP>)q.list()) {
map.put(loaiSanPhamATTP.getPrimaryKeyObj(), loaiSanPhamATTP);
cacheResult(loaiSanPhamATTP);
uncachedPrimaryKeys.remove(loaiSanPhamATTP.getPrimaryKeyObj());
}
for (Serializable primaryKey : uncachedPrimaryKeys) {
entityCache.putResult(LoaiSanPhamATTPModelImpl.ENTITY_CACHE_ENABLED,
LoaiSanPhamATTPImpl.class, primaryKey, nullModel);
}
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
return map;
}
/**
* Returns all the loai san pham a t t ps.
*
* @return the loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findAll() {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
}
/**
* Returns a range of all the loai san pham a t t ps.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link LoaiSanPhamATTPModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param start the lower bound of the range of loai san pham a t t ps
* @param end the upper bound of the range of loai san pham a t t ps (not inclusive)
* @return the range of loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findAll(int start, int end) {
return findAll(start, end, null);
}
/**
* Returns an ordered range of all the loai san pham a t t ps.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link LoaiSanPhamATTPModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param start the lower bound of the range of loai san pham a t t ps
* @param end the upper bound of the range of loai san pham a t t ps (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findAll(int start, int end,
OrderByComparator<LoaiSanPhamATTP> orderByComparator) {
return findAll(start, end, orderByComparator, true);
}
/**
* Returns an ordered range of all the loai san pham a t t ps.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link LoaiSanPhamATTPModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param start the lower bound of the range of loai san pham a t t ps
* @param end the upper bound of the range of loai san pham a t t ps (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @param retrieveFromCache whether to retrieve from the finder cache
* @return the ordered range of loai san pham a t t ps
*/
@Override
public List<LoaiSanPhamATTP> findAll(int start, int end,
OrderByComparator<LoaiSanPhamATTP> orderByComparator,
boolean retrieveFromCache) {
boolean pagination = true;
FinderPath finderPath = null;
Object[] finderArgs = null;
if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
(orderByComparator == null)) {
pagination = false;
finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_ALL;
finderArgs = FINDER_ARGS_EMPTY;
}
else {
finderPath = FINDER_PATH_WITH_PAGINATION_FIND_ALL;
finderArgs = new Object[] { start, end, orderByComparator };
}
List<LoaiSanPhamATTP> list = null;
if (retrieveFromCache) {
list = (List<LoaiSanPhamATTP>)finderCache.getResult(finderPath,
finderArgs, this);
}
if (list == null) {
StringBundler query = null;
String sql = null;
if (orderByComparator != null) {
query = new StringBundler(2 +
(orderByComparator.getOrderByFields().length * 2));
query.append(_SQL_SELECT_LOAISANPHAMATTP);
appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
orderByComparator);
sql = query.toString();
}
else {
sql = _SQL_SELECT_LOAISANPHAMATTP;
if (pagination) {
sql = sql.concat(LoaiSanPhamATTPModelImpl.ORDER_BY_JPQL);
}
}
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
if (!pagination) {
list = (List<LoaiSanPhamATTP>)QueryUtil.list(q,
getDialect(), start, end, false);
Collections.sort(list);
list = Collections.unmodifiableList(list);
}
else {
list = (List<LoaiSanPhamATTP>)QueryUtil.list(q,
getDialect(), start, end);
}
cacheResult(list);
finderCache.putResult(finderPath, finderArgs, list);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return list;
}
/**
* Removes all the loai san pham a t t ps from the database.
*
*/
@Override
public void removeAll() {
for (LoaiSanPhamATTP loaiSanPhamATTP : findAll()) {
remove(loaiSanPhamATTP);
}
}
/**
* Returns the number of loai san pham a t t ps.
*
* @return the number of loai san pham a t t ps
*/
@Override
public int countAll() {
Long count = (Long)finderCache.getResult(FINDER_PATH_COUNT_ALL,
FINDER_ARGS_EMPTY, this);
if (count == null) {
Session session = null;
try {
session = openSession();
Query q = session.createQuery(_SQL_COUNT_LOAISANPHAMATTP);
count = (Long)q.uniqueResult();
finderCache.putResult(FINDER_PATH_COUNT_ALL, FINDER_ARGS_EMPTY,
count);
}
catch (Exception e) {
finderCache.removeResult(FINDER_PATH_COUNT_ALL,
FINDER_ARGS_EMPTY);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
}
@Override
public Set<String> getBadColumnNames() {
return _badColumnNames;
}
@Override
protected Map<String, Integer> getTableColumnsMap() {
return LoaiSanPhamATTPModelImpl.TABLE_COLUMNS_MAP;
}
/**
* Initializes the loai san pham a t t p persistence.
*/
public void afterPropertiesSet() {
}
public void destroy() {
entityCache.removeCache(LoaiSanPhamATTPImpl.class.getName());
finderCache.removeCache(FINDER_CLASS_NAME_ENTITY);
finderCache.removeCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
finderCache.removeCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
}
@ServiceReference(type = CompanyProviderWrapper.class)
protected CompanyProvider companyProvider;
@ServiceReference(type = EntityCache.class)
protected EntityCache entityCache;
@ServiceReference(type = FinderCache.class)
protected FinderCache finderCache;
private static final String _SQL_SELECT_LOAISANPHAMATTP = "SELECT loaiSanPhamATTP FROM LoaiSanPhamATTP loaiSanPhamATTP";
private static final String _SQL_SELECT_LOAISANPHAMATTP_WHERE_PKS_IN = "SELECT loaiSanPhamATTP FROM LoaiSanPhamATTP loaiSanPhamATTP WHERE loaiSanPhamId IN (";
private static final String _SQL_SELECT_LOAISANPHAMATTP_WHERE = "SELECT loaiSanPhamATTP FROM LoaiSanPhamATTP loaiSanPhamATTP WHERE ";
private static final String _SQL_COUNT_LOAISANPHAMATTP = "SELECT COUNT(loaiSanPhamATTP) FROM LoaiSanPhamATTP loaiSanPhamATTP";
private static final String _SQL_COUNT_LOAISANPHAMATTP_WHERE = "SELECT COUNT(loaiSanPhamATTP) FROM LoaiSanPhamATTP loaiSanPhamATTP WHERE ";
private static final String _ORDER_BY_ENTITY_ALIAS = "loaiSanPhamATTP.";
private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No LoaiSanPhamATTP exists with the primary key ";
private static final String _NO_SUCH_ENTITY_WITH_KEY = "No LoaiSanPhamATTP exists with the key {";
private static final Log _log = LogFactoryUtil.getLog(LoaiSanPhamATTPPersistenceImpl.class);
private static final Set<String> _badColumnNames = SetUtil.fromArray(new String[] {
"uuid"
});
} | 74,974 | 0.713567 | 0.710634 | 2,298 | 31.63229 | 63.842258 | 931 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.438642 | false | false | 4 |
fd0280773048ab334d80a56bded7018519ff1415 | 26,414,048,936,355 | 9d2c9f0075b9140988a10e6713f4b2071326a0ab | /src/main/java/cube8540/oauth/authentication/credentials/AbstractAuthority.java | c9cefed59691cf10c397115658ac9dc29c49a41e | []
| no_license | cube8540/oauth-authentication-server | https://github.com/cube8540/oauth-authentication-server | c349d7a76fdfa05de08d726eae7b61715c62a61f | 78b306adb6f9b2195bc36c4c83253f8072ec1041 | refs/heads/master | 2020-11-28T23:27:18.593000 | 2020-09-17T01:25:11 | 2020-09-17T01:25:11 | 229,946,328 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cube8540.oauth.authentication.credentials;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.domain.AbstractAggregateRoot;
import javax.persistence.AttributeOverride;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.MappedSuperclass;
@Getter
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@MappedSuperclass
public class AbstractAuthority extends AbstractAggregateRoot<AbstractAuthority> {
@EmbeddedId
@AttributeOverride(name = "value", column = @Column(name = "code", length = 32))
private AuthorityCode code;
@Setter
@Column(name = "description", length = 32)
private String description;
}
| UTF-8 | Java | 819 | java | AbstractAuthority.java | Java | []
| null | []
| package cube8540.oauth.authentication.credentials;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.domain.AbstractAggregateRoot;
import javax.persistence.AttributeOverride;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.MappedSuperclass;
@Getter
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@MappedSuperclass
public class AbstractAuthority extends AbstractAggregateRoot<AbstractAuthority> {
@EmbeddedId
@AttributeOverride(name = "value", column = @Column(name = "code", length = 32))
private AuthorityCode code;
@Setter
@Column(name = "description", length = 32)
private String description;
}
| 819 | 0.803419 | 0.793651 | 29 | 27.241379 | 23.122843 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.551724 | false | false | 4 |
6dd072d6e0687dd2d7522d0b532aa269b3f364b2 | 30,734,785,972,217 | 30ae2b17ec8ed47d0658914e0921ce41fc908f13 | /spring/springboot-demo/src/main/java/spring/demo/service/impl/PerformanceTestServiceImpl.java | 0668b3c805a76748d1019e8f08e469820cb8c873 | []
| no_license | jackwjh/demo | https://github.com/jackwjh/demo | 5bc2da0ebeb0a71dd96b79d77fed1b64a4d5215f | 76c0a089875e71fc3ca5cd15483a1ef7c672730e | refs/heads/master | 2021-09-01T17:34:45.489000 | 2017-11-07T03:49:19 | 2017-11-07T03:49:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package spring.demo.service.impl;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import spring.demo.constant.Constants;
import spring.demo.dto.request.PerformanceTestRequest;
import spring.demo.service.IPerformanceTestService;
import spring.demo.util.ExecutorFactory;
import spring.demo.websocket.MyWebSocket;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by facheng on 15.03.17.
*/
@Service
public class PerformanceTestServiceImpl implements IPerformanceTestService {
private static final Logger LOGGER = LoggerFactory.getLogger(PerformanceTestServiceImpl.class);
@Override
public void startTest(PerformanceTestRequest request) throws IOException {
LOGGER.info("start to performance test");
AtomicInteger atomicInteger = new AtomicInteger(0);
long start = System.currentTimeMillis();
ThreadPoolExecutor executor = ExecutorFactory.generateExecutor(request.getThreadCount());
List<Future<HttpResponse>> futureList = new ArrayList<>();
for (int i = 0; i < request.getTaskCount(); i++) {
futureList.add(executor.submit(() -> send(request, atomicInteger)));
}
try {
HttpResponse httpResponse;
for (Future<HttpResponse> future : futureList) {
httpResponse = future.get();
MyWebSocket.sendInfo("执行次数" + atomicInteger.incrementAndGet() + ";status = "
+ httpResponse.getStatusLine().getStatusCode() + ";response : "
+ EntityUtils.toString(httpResponse.getEntity(), Constants.DEFAULT_CHAR_SET));
}
MyWebSocket.sendInfo("cost time " + (System.currentTimeMillis() - start) + "ms");
} catch (InterruptedException e) {
LOGGER.error(e.getMessage(), e);
} catch (ExecutionException e) {
LOGGER.error(e.getMessage(), e);
}
}
protected HttpResponse send(PerformanceTestRequest request, AtomicInteger atomicInteger) {
if (request == null) {
return null;
}
HttpResponse response = null;
try {
HttpClient client = HttpClientBuilder.create().build();
HttpPost httpUriRequest = new HttpPost(request.getUrl());
HttpClientContext context = new HttpClientContext();
httpUriRequest.setEntity(new StringEntity(request.getParams(), ContentType.APPLICATION_JSON));
response = client.execute(httpUriRequest, context);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
return response;
}
}
| UTF-8 | Java | 3,267 | java | PerformanceTestServiceImpl.java | Java | [
{
"context": "oncurrent.atomic.AtomicInteger;\n\n/**\n * Created by facheng on 15.03.17.\n */\n\n@Service\npublic class Performan",
"end": 1023,
"score": 0.9984400868415833,
"start": 1016,
"tag": "USERNAME",
"value": "facheng"
}
]
| null | []
| package spring.demo.service.impl;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import spring.demo.constant.Constants;
import spring.demo.dto.request.PerformanceTestRequest;
import spring.demo.service.IPerformanceTestService;
import spring.demo.util.ExecutorFactory;
import spring.demo.websocket.MyWebSocket;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by facheng on 15.03.17.
*/
@Service
public class PerformanceTestServiceImpl implements IPerformanceTestService {
private static final Logger LOGGER = LoggerFactory.getLogger(PerformanceTestServiceImpl.class);
@Override
public void startTest(PerformanceTestRequest request) throws IOException {
LOGGER.info("start to performance test");
AtomicInteger atomicInteger = new AtomicInteger(0);
long start = System.currentTimeMillis();
ThreadPoolExecutor executor = ExecutorFactory.generateExecutor(request.getThreadCount());
List<Future<HttpResponse>> futureList = new ArrayList<>();
for (int i = 0; i < request.getTaskCount(); i++) {
futureList.add(executor.submit(() -> send(request, atomicInteger)));
}
try {
HttpResponse httpResponse;
for (Future<HttpResponse> future : futureList) {
httpResponse = future.get();
MyWebSocket.sendInfo("执行次数" + atomicInteger.incrementAndGet() + ";status = "
+ httpResponse.getStatusLine().getStatusCode() + ";response : "
+ EntityUtils.toString(httpResponse.getEntity(), Constants.DEFAULT_CHAR_SET));
}
MyWebSocket.sendInfo("cost time " + (System.currentTimeMillis() - start) + "ms");
} catch (InterruptedException e) {
LOGGER.error(e.getMessage(), e);
} catch (ExecutionException e) {
LOGGER.error(e.getMessage(), e);
}
}
protected HttpResponse send(PerformanceTestRequest request, AtomicInteger atomicInteger) {
if (request == null) {
return null;
}
HttpResponse response = null;
try {
HttpClient client = HttpClientBuilder.create().build();
HttpPost httpUriRequest = new HttpPost(request.getUrl());
HttpClientContext context = new HttpClientContext();
httpUriRequest.setEntity(new StringEntity(request.getParams(), ContentType.APPLICATION_JSON));
response = client.execute(httpUriRequest, context);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
return response;
}
}
| 3,267 | 0.69101 | 0.687941 | 92 | 34.423912 | 29.686489 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.630435 | false | false | 4 |
b7a984f7904fd95d5ba2d39a7ffaa95eff1371c4 | 24,446,953,898,305 | a9594a35578bd2eba0720d6cc92854b2783fc109 | /server/src/test/java/net/consensys/eventeumserver/integrationtest/ListenerBackedBroadcasterIT.java | a10c034f4b990de259fb5afe07255b747773684f | [
"Apache-2.0"
]
| permissive | stec0/eventeum | https://github.com/stec0/eventeum | 30443b79042ef83f2dc9fff4e93ec3280bdf12b6 | 92699adef4345b860ba1568b16d721988d470580 | refs/heads/master | 2020-04-10T18:03:59.269000 | 2018-12-07T12:30:45 | 2018-12-07T12:30:45 | 161,192,895 | 0 | 0 | Apache-2.0 | true | 2018-12-10T15:08:37 | 2018-12-10T15:08:37 | 2018-12-09T14:35:00 | 2018-12-07T13:24:20 | 268 | 0 | 0 | 0 | null | false | null | package net.consensys.eventeumserver.integrationtest;
import net.consensys.eventeum.dto.block.BlockDetails;
import net.consensys.eventeum.dto.event.ContractEventDetails;
import net.consensys.eventeum.dto.event.ContractEventStatus;
import net.consensys.eventeum.dto.event.filter.ContractEventFilter;
import net.consensys.eventeum.integration.broadcast.blockchain.BlockchainEventBroadcaster;
import net.consensys.eventeum.integration.broadcast.blockchain.ListenerInvokingBlockchainEventBroadcaster;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@TestPropertySource(locations = "classpath:application-test-db-listener.properties")
@Import(ListenerBackedBroadcasterIT.ListenerConfig.class)
public class ListenerBackedBroadcasterIT extends BaseIntegrationTest {
@Test
public void testBroadcastBlock() throws Exception {
triggerBlocks(1);
waitForBlockMessages(1);
assertTrue("No blocks received", getBroadcastBlockMessages().size() >= 1);
BlockDetails blockDetails = getBroadcastBlockMessages().get(0);
assertEquals(1, blockDetails.getNumber().compareTo(BigInteger.ZERO));
assertNotNull(blockDetails.getHash());
}
@Test
public void testBroadcastContractEvent() throws Exception {
final EventEmitter emitter = deployEventEmitterContract();
final ContractEventFilter registeredFilter = registerDummyEventFilter(emitter.getContractAddress());
emitter.emit(stringToBytes("BytesValue"), BigInteger.TEN, "StringValue").send();
waitForContractEventMessages(1);
assertEquals(1, getBroadcastContractEvents().size());
final ContractEventDetails eventDetails = getBroadcastContractEvents().get(0);
verifyDummyEventDetails(registeredFilter, eventDetails, ContractEventStatus.CONFIRMED);
}
@Override
protected List<BlockDetails> getBroadcastBlockMessages() {
return ListenerConfig.broadcastBlockMessages;
}
@Override
protected List<ContractEventDetails> getBroadcastContractEvents() {
return ListenerConfig.broadcastContractEvents;
}
@TestConfiguration
static class ListenerConfig {
private static List<BlockDetails> broadcastBlockMessages = new ArrayList<>();
private static List<ContractEventDetails> broadcastContractEvents = new ArrayList<>();
@Bean
public BlockchainEventBroadcaster listenerBroadcaster() {
return new ListenerInvokingBlockchainEventBroadcaster(new ListenerInvokingBlockchainEventBroadcaster.OnBlockchainEventListener() {
@Override
public void onNewBlock(BlockDetails block) {
broadcastBlockMessages.add(block);
}
@Override
public void onContractEvent(ContractEventDetails eventDetails) {
broadcastContractEvents.add(eventDetails);
}
});
}
}
}
| UTF-8 | Java | 3,765 | java | ListenerBackedBroadcasterIT.java | Java | []
| null | []
| package net.consensys.eventeumserver.integrationtest;
import net.consensys.eventeum.dto.block.BlockDetails;
import net.consensys.eventeum.dto.event.ContractEventDetails;
import net.consensys.eventeum.dto.event.ContractEventStatus;
import net.consensys.eventeum.dto.event.filter.ContractEventFilter;
import net.consensys.eventeum.integration.broadcast.blockchain.BlockchainEventBroadcaster;
import net.consensys.eventeum.integration.broadcast.blockchain.ListenerInvokingBlockchainEventBroadcaster;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@TestPropertySource(locations = "classpath:application-test-db-listener.properties")
@Import(ListenerBackedBroadcasterIT.ListenerConfig.class)
public class ListenerBackedBroadcasterIT extends BaseIntegrationTest {
@Test
public void testBroadcastBlock() throws Exception {
triggerBlocks(1);
waitForBlockMessages(1);
assertTrue("No blocks received", getBroadcastBlockMessages().size() >= 1);
BlockDetails blockDetails = getBroadcastBlockMessages().get(0);
assertEquals(1, blockDetails.getNumber().compareTo(BigInteger.ZERO));
assertNotNull(blockDetails.getHash());
}
@Test
public void testBroadcastContractEvent() throws Exception {
final EventEmitter emitter = deployEventEmitterContract();
final ContractEventFilter registeredFilter = registerDummyEventFilter(emitter.getContractAddress());
emitter.emit(stringToBytes("BytesValue"), BigInteger.TEN, "StringValue").send();
waitForContractEventMessages(1);
assertEquals(1, getBroadcastContractEvents().size());
final ContractEventDetails eventDetails = getBroadcastContractEvents().get(0);
verifyDummyEventDetails(registeredFilter, eventDetails, ContractEventStatus.CONFIRMED);
}
@Override
protected List<BlockDetails> getBroadcastBlockMessages() {
return ListenerConfig.broadcastBlockMessages;
}
@Override
protected List<ContractEventDetails> getBroadcastContractEvents() {
return ListenerConfig.broadcastContractEvents;
}
@TestConfiguration
static class ListenerConfig {
private static List<BlockDetails> broadcastBlockMessages = new ArrayList<>();
private static List<ContractEventDetails> broadcastContractEvents = new ArrayList<>();
@Bean
public BlockchainEventBroadcaster listenerBroadcaster() {
return new ListenerInvokingBlockchainEventBroadcaster(new ListenerInvokingBlockchainEventBroadcaster.OnBlockchainEventListener() {
@Override
public void onNewBlock(BlockDetails block) {
broadcastBlockMessages.add(block);
}
@Override
public void onContractEvent(ContractEventDetails eventDetails) {
broadcastContractEvents.add(eventDetails);
}
});
}
}
}
| 3,765 | 0.759363 | 0.756972 | 96 | 38.21875 | 33.364216 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.510417 | false | false | 4 |
dc317ba70764436ed21f1d1150f8f60a8125c7f1 | 31,782,758,000,471 | 32c3560ad1f49ade6ccc85526784440e92b7551f | /src/org/usfirst/frc/team1504/robot/Logger.java | afd0334f8ccf52d0f7bd889f715f247e413c0c73 | []
| no_license | 1504/2016_Robot_Framework | https://github.com/1504/2016_Robot_Framework | e8622d5168b94250f3c6442bc7f7874ca50dd7ac | 2b2e12348a1433b78a932bf17d567073fc026166 | refs/heads/master | 2021-01-09T07:31:01.764000 | 2016-02-04T00:50:14 | 2016-02-04T00:50:14 | 49,607,509 | 1 | 2 | null | true | 2016-02-02T16:07:55 | 2016-01-13T22:55:00 | 2016-01-13T22:55:35 | 2016-02-02T16:07:55 | 11,265 | 0 | 0 | 0 | Java | null | null | package org.usfirst.frc.team1504.robot;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Calendar;
import java.util.GregorianCalendar;
import edu.wpi.first.wpilibj.DriverStation;
public class Logger {
private File _outfile;
private FileOutputStream _file_output;
private DriverStation _ds = DriverStation.getInstance();
private long _start_time;
private volatile byte[][] _logged_data = null;
private volatile boolean _logging = false;
private static final Logger instance = new Logger();
protected Logger()
{
System.out.println("Log Leader, standing by.");
}
public static Logger getInstance()
{
return instance;
}
/**
* Start the logger
* @param prefix - The filename prefix to log under (Format: Prefix-Time.log)
*/
public void start(String prefix) {
Calendar cal = new GregorianCalendar();
String filetime = Long.toString(cal.getTimeInMillis());
_outfile = new File("/home/lvuser/log/" + prefix + "-" + filetime + ".log");
try {
_file_output = new FileOutputStream(_outfile);
} catch (FileNotFoundException e) {
System.out.println("Could not open logging file.\n" + _outfile);
//e.printStackTrace();
return;
}
_start_time = System.currentTimeMillis();
byte[] robot_start_time = new byte[8];
ByteBuffer.wrap(robot_start_time).putLong(IO.ROBOT_START_TIME);
try {
_file_output.write("Log-".getBytes());
_file_output.write(robot_start_time);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Logger started @ " + _start_time + " using \"~/log/" + prefix + "-" + filetime + ".log\"");
}
/**
* Stop the logger
*/
public void stop()
{
if (_file_output == null) {
System.out.println("disable called on null");
} else {
try {
_file_output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Logger Stopped");
}
/**
* Flush data to disk. Synchronize to prevent data being added in the middle of a file write.
*/
private void sync_flush()
{
_logging = true;
flush_data();
_logging = false;
}
/**
* Flush current data buffer to disk.
*/
private void flush_data()
{
if(_file_output == null)
return;
byte[][] data_buffer = _logged_data;
// Format: "^" literal (1) / Time (4) / Voltage (4) / Logged Classes (1) / Class data (#)
try {
_file_output.write(94); // ^
byte[] head = new byte[4+4];
ByteBuffer.wrap(head, 0, 4).putInt((int)(System.currentTimeMillis() - _start_time));
ByteBuffer.wrap(head, 4, 4).putFloat((float)_ds.getBatteryVoltage());
_file_output.write(head);
} catch (IOException e) {
e.printStackTrace();
return;
}
for(byte[] o : data_buffer)
{
if(o != null)
{
try {
_file_output.write(o);
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
}
/**
* Log data from logging classes to disk.
* @param logging_class - What class is currently logging
* @param data - The data to be logged
*/
public boolean log(Map.LOGGED_CLASSES logging_class, byte[] data)
{
if(logging_class == Map.LOGGED_CLASSES.SEMAPHORE)
{
if(_logged_data != null)
sync_flush();
_logged_data = new byte[Map.LOGGED_CLASSES.values().length][];
_logged_data[0] = new byte[]{0};
}
else if(_logging)
{
return false;
}
_logged_data[0][0] = (byte) (_logged_data[0][0] | 1 << logging_class.ordinal());
_logged_data[logging_class.ordinal() + 1] = data;
return true;
}
}
| UTF-8 | Java | 3,610 | java | Logger.java | Java | []
| null | []
| package org.usfirst.frc.team1504.robot;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Calendar;
import java.util.GregorianCalendar;
import edu.wpi.first.wpilibj.DriverStation;
public class Logger {
private File _outfile;
private FileOutputStream _file_output;
private DriverStation _ds = DriverStation.getInstance();
private long _start_time;
private volatile byte[][] _logged_data = null;
private volatile boolean _logging = false;
private static final Logger instance = new Logger();
protected Logger()
{
System.out.println("Log Leader, standing by.");
}
public static Logger getInstance()
{
return instance;
}
/**
* Start the logger
* @param prefix - The filename prefix to log under (Format: Prefix-Time.log)
*/
public void start(String prefix) {
Calendar cal = new GregorianCalendar();
String filetime = Long.toString(cal.getTimeInMillis());
_outfile = new File("/home/lvuser/log/" + prefix + "-" + filetime + ".log");
try {
_file_output = new FileOutputStream(_outfile);
} catch (FileNotFoundException e) {
System.out.println("Could not open logging file.\n" + _outfile);
//e.printStackTrace();
return;
}
_start_time = System.currentTimeMillis();
byte[] robot_start_time = new byte[8];
ByteBuffer.wrap(robot_start_time).putLong(IO.ROBOT_START_TIME);
try {
_file_output.write("Log-".getBytes());
_file_output.write(robot_start_time);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Logger started @ " + _start_time + " using \"~/log/" + prefix + "-" + filetime + ".log\"");
}
/**
* Stop the logger
*/
public void stop()
{
if (_file_output == null) {
System.out.println("disable called on null");
} else {
try {
_file_output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Logger Stopped");
}
/**
* Flush data to disk. Synchronize to prevent data being added in the middle of a file write.
*/
private void sync_flush()
{
_logging = true;
flush_data();
_logging = false;
}
/**
* Flush current data buffer to disk.
*/
private void flush_data()
{
if(_file_output == null)
return;
byte[][] data_buffer = _logged_data;
// Format: "^" literal (1) / Time (4) / Voltage (4) / Logged Classes (1) / Class data (#)
try {
_file_output.write(94); // ^
byte[] head = new byte[4+4];
ByteBuffer.wrap(head, 0, 4).putInt((int)(System.currentTimeMillis() - _start_time));
ByteBuffer.wrap(head, 4, 4).putFloat((float)_ds.getBatteryVoltage());
_file_output.write(head);
} catch (IOException e) {
e.printStackTrace();
return;
}
for(byte[] o : data_buffer)
{
if(o != null)
{
try {
_file_output.write(o);
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
}
/**
* Log data from logging classes to disk.
* @param logging_class - What class is currently logging
* @param data - The data to be logged
*/
public boolean log(Map.LOGGED_CLASSES logging_class, byte[] data)
{
if(logging_class == Map.LOGGED_CLASSES.SEMAPHORE)
{
if(_logged_data != null)
sync_flush();
_logged_data = new byte[Map.LOGGED_CLASSES.values().length][];
_logged_data[0] = new byte[]{0};
}
else if(_logging)
{
return false;
}
_logged_data[0][0] = (byte) (_logged_data[0][0] | 1 << logging_class.ordinal());
_logged_data[logging_class.ordinal() + 1] = data;
return true;
}
}
| 3,610 | 0.640997 | 0.634072 | 154 | 22.441559 | 23.347456 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.175325 | false | false | 4 |
647a539b764e02ad5313a964139065f3ac69124c | 19,464,791,788,307 | ea5c18ad38dfa4c3de97aa1537cd854e997e4327 | /AIRONE/core/src/com/airone/game/States/Score.java | 46289b2f764bbff842d7b8aaacaed2b461234e27 | []
| no_license | KrishnaGurum/AIRONE-Android-Game | https://github.com/KrishnaGurum/AIRONE-Android-Game | b74a4b9a95f8f8b6673fe5444b805be19fb08570 | b36076b47929864a715916d9c52e15bc4a096e2f | refs/heads/master | 2021-01-09T06:01:49.983000 | 2017-02-04T01:40:42 | 2017-02-04T01:40:42 | 80,879,533 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.airone.game.States;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class Score extends State
{
protected Score(GameStateManager gameStateManager) {
super(gameStateManager);
}
@Override
protected void Input() {
}
@Override
public void Update(float delta) {
}
@Override
public void render(SpriteBatch spriteBatch) {
}
@Override
public void dispose() {
}
}
| UTF-8 | Java | 450 | java | Score.java | Java | []
| null | []
| package com.airone.game.States;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class Score extends State
{
protected Score(GameStateManager gameStateManager) {
super(gameStateManager);
}
@Override
protected void Input() {
}
@Override
public void Update(float delta) {
}
@Override
public void render(SpriteBatch spriteBatch) {
}
@Override
public void dispose() {
}
}
| 450 | 0.653333 | 0.651111 | 30 | 14 | 17.080202 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.1 | false | false | 4 |
ccbd5aeee5eae2a313ae05351547f07c95c3721c | 4,818,953,353,442 | 52f64eb80a8e9c2dffaeb5b9aa61c00b9ff201fc | /src/main/java/urn/ietf/params/xml/ns/yang/nfvo/vnfd/rev150910/vnfd/descriptor/internal/vld/InternalConnectionPoint.java | 5414e56437cf83a3ada02fb7700c7b370f6f1d9e | [
"Apache-2.0"
]
| permissive | ctranoris/eu.5ginFIRE.riftioyangschema2java | https://github.com/ctranoris/eu.5ginFIRE.riftioyangschema2java | a96576ec37510833aca0942326e36ec97ce7408c | 46a0fe252fc72551dc52f1e23b115907fceb49fe | refs/heads/master | 2021-01-19T17:38:25.342000 | 2018-03-01T16:29:11 | 2018-03-01T16:29:11 | 101,077,357 | 0 | 1 | Apache-2.0 | false | 2018-03-01T16:29:11 | 2017-08-22T15:19:30 | 2017-08-22T15:34:21 | 2018-03-01T16:29:11 | 436 | 0 | 1 | 0 | Java | false | null | package urn.ietf.params.xml.ns.yang.nfvo.vnfd.rev150910.vnfd.descriptor.internal.vld;
import org.opendaylight.yangtools.yang.binding.Augmentable;
import org.opendaylight.yangtools.yang.binding.ChildOf;
import org.opendaylight.yangtools.yang.binding.Identifiable;
import org.opendaylight.yangtools.yang.common.QName;
import urn.ietf.params.xml.ns.yang.nfvo.vnfd.rev150910.vnfd.descriptor.InternalVld;
/**
* List of internal connection points in this VLD
*
* <p>This class represents the following YANG schema fragment defined in module <b>vnfd</b>
* <pre>
* list internal-connection-point {
* key "id-ref"
* leaf id-ref {
* type leafref;
* }
* }
* </pre>
* The schema path to identify an instance is
* <i>vnfd/vnfd-descriptor/internal-vld/internal-connection-point</i>
*
* <p>To create instances of this class use {@link urn.ietf.params.xml.ns.yang.nfvo.vnfd.rev150910.vnfd.descriptor.internal.vld.InternalConnectionPointBuilder}.
* @see urn.ietf.params.xml.ns.yang.nfvo.vnfd.rev150910.vnfd.descriptor.internal.vld.InternalConnectionPointBuilder
* @see urn.ietf.params.xml.ns.yang.nfvo.vnfd.rev150910.vnfd.descriptor.internal.vld.InternalConnectionPointKey
*
*/
public interface InternalConnectionPoint
extends
ChildOf<InternalVld>,
Augmentable<urn.ietf.params.xml.ns.yang.nfvo.vnfd.rev150910.vnfd.descriptor.internal.vld.InternalConnectionPoint>,
Identifiable<InternalConnectionPointKey>
{
public static final QName QNAME = org.opendaylight.yangtools.yang.common.QName.create("urn:ietf:params:xml:ns:yang:nfvo:vnfd",
"2015-09-10", "internal-connection-point").intern();
/**
* reference to the internal connection point id
*
*
*
* @return <code>java.lang.String</code> <code>idRef</code>, or <code>null</code> if not present
*/
java.lang.String getIdRef();
/**
* Returns Primary Key of Yang List Type
*
*
*
* @return <code>org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.nfvo.vnfd.rev150910.vnfd.descriptor.internal.vld.InternalConnectionPointKey</code> <code>key</code>, or <code>null</code> if not present
*/
InternalConnectionPointKey getKey();
}
| UTF-8 | Java | 2,276 | java | InternalConnectionPoint.java | Java | []
| null | []
| package urn.ietf.params.xml.ns.yang.nfvo.vnfd.rev150910.vnfd.descriptor.internal.vld;
import org.opendaylight.yangtools.yang.binding.Augmentable;
import org.opendaylight.yangtools.yang.binding.ChildOf;
import org.opendaylight.yangtools.yang.binding.Identifiable;
import org.opendaylight.yangtools.yang.common.QName;
import urn.ietf.params.xml.ns.yang.nfvo.vnfd.rev150910.vnfd.descriptor.InternalVld;
/**
* List of internal connection points in this VLD
*
* <p>This class represents the following YANG schema fragment defined in module <b>vnfd</b>
* <pre>
* list internal-connection-point {
* key "id-ref"
* leaf id-ref {
* type leafref;
* }
* }
* </pre>
* The schema path to identify an instance is
* <i>vnfd/vnfd-descriptor/internal-vld/internal-connection-point</i>
*
* <p>To create instances of this class use {@link urn.ietf.params.xml.ns.yang.nfvo.vnfd.rev150910.vnfd.descriptor.internal.vld.InternalConnectionPointBuilder}.
* @see urn.ietf.params.xml.ns.yang.nfvo.vnfd.rev150910.vnfd.descriptor.internal.vld.InternalConnectionPointBuilder
* @see urn.ietf.params.xml.ns.yang.nfvo.vnfd.rev150910.vnfd.descriptor.internal.vld.InternalConnectionPointKey
*
*/
public interface InternalConnectionPoint
extends
ChildOf<InternalVld>,
Augmentable<urn.ietf.params.xml.ns.yang.nfvo.vnfd.rev150910.vnfd.descriptor.internal.vld.InternalConnectionPoint>,
Identifiable<InternalConnectionPointKey>
{
public static final QName QNAME = org.opendaylight.yangtools.yang.common.QName.create("urn:ietf:params:xml:ns:yang:nfvo:vnfd",
"2015-09-10", "internal-connection-point").intern();
/**
* reference to the internal connection point id
*
*
*
* @return <code>java.lang.String</code> <code>idRef</code>, or <code>null</code> if not present
*/
java.lang.String getIdRef();
/**
* Returns Primary Key of Yang List Type
*
*
*
* @return <code>org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.nfvo.vnfd.rev150910.vnfd.descriptor.internal.vld.InternalConnectionPointKey</code> <code>key</code>, or <code>null</code> if not present
*/
InternalConnectionPointKey getKey();
}
| 2,276 | 0.708699 | 0.686292 | 59 | 36.542374 | 45.465324 | 214 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.271186 | false | false | 4 |
aa0774412ba01cadff34aa88ed0b99e52dc26b3a | 33,234,457,005,450 | e53b7a02300de2b71ac429d9ec619d12f21a97cc | /src/com/coda/efinance/schemas/common/TypeCapValueOrPercent.java | 4f0c700bb6efbbbdc2e953287ff3382ea3feb525 | []
| no_license | phi2039/coda_xmli | https://github.com/phi2039/coda_xmli | 2ad13c08b631d90a26cfa0a02c9c6c35416e796f | 4c391b9a88f776c2bf636e15d7fcc59b7fcb7531 | refs/heads/master | 2021-01-10T05:36:22.264000 | 2015-12-03T16:36:23 | 2015-12-03T16:36:23 | 47,346,047 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.12.03 at 01:45:22 AM EST
//
package com.coda.efinance.schemas.common;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for typeCapValueOrPercent.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="typeCapValueOrPercent">
* <restriction base="{http://www.coda.com/efinance/schemas/common}typeBaseEnum">
* <enumeration value="value"/>
* <enumeration value="percent"/>
* <enumeration value="none"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "typeCapValueOrPercent")
@XmlEnum
public enum TypeCapValueOrPercent {
/**
* Users can change the actual value calculated using an exchange rate.
*
*/
@XmlEnumValue("value")
VALUE("value"),
/**
* Users can change, by a specified percentage, the value calculated using an exchange rate.
*
*/
@XmlEnumValue("percent")
PERCENT("percent"),
/**
* Users cannot change any values caculated using an exchange rate.
*
*/
@XmlEnumValue("none")
NONE("none");
private final String value;
TypeCapValueOrPercent(String v) {
value = v;
}
public String value() {
return value;
}
public static TypeCapValueOrPercent fromValue(String v) {
for (TypeCapValueOrPercent c: TypeCapValueOrPercent.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| UTF-8 | Java | 1,993 | java | TypeCapValueOrPercent.java | Java | []
| null | []
| //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.12.03 at 01:45:22 AM EST
//
package com.coda.efinance.schemas.common;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for typeCapValueOrPercent.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="typeCapValueOrPercent">
* <restriction base="{http://www.coda.com/efinance/schemas/common}typeBaseEnum">
* <enumeration value="value"/>
* <enumeration value="percent"/>
* <enumeration value="none"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "typeCapValueOrPercent")
@XmlEnum
public enum TypeCapValueOrPercent {
/**
* Users can change the actual value calculated using an exchange rate.
*
*/
@XmlEnumValue("value")
VALUE("value"),
/**
* Users can change, by a specified percentage, the value calculated using an exchange rate.
*
*/
@XmlEnumValue("percent")
PERCENT("percent"),
/**
* Users cannot change any values caculated using an exchange rate.
*
*/
@XmlEnumValue("none")
NONE("none");
private final String value;
TypeCapValueOrPercent(String v) {
value = v;
}
public String value() {
return value;
}
public static TypeCapValueOrPercent fromValue(String v) {
for (TypeCapValueOrPercent c: TypeCapValueOrPercent.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| 1,993 | 0.649272 | 0.640241 | 76 | 25.223684 | 27.692675 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.381579 | false | false | 4 |
88466373b695580c0d33a7b183b204d4fa8a36f4 | 24,386,824,348,485 | a5972f3703f1479fb6b853c3b0934257e1b15cd9 | /src/com/seu/util/MailUtils.java | cb4fe73c5484737190586c5926cc4f9123214179 | []
| no_license | Amiedon/Finance | https://github.com/Amiedon/Finance | 6b5d62d213bafba91737cc012ad2543874d02793 | 2dc7567f18153bf5a8cce220c5b81057dbe6b5ba | refs/heads/master | 2021-01-21T10:59:19.028000 | 2017-03-09T03:26:59 | 2017-03-09T03:26:59 | 83,507,031 | 3 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.seu.util;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;
/**
* 邮件发送的工具类
* Created by Amie on 2017/3/2.
*/
public class MailUtils {
/**
*
* @param to 给谁发邮件
* @param code 邮件的激活码
*/
public static final String HOST = "smtp.163.com";
public static final String PROTOCOL = "smtp";
public static final int PORT = 25;
public static final String FROM = "18816298653@163.com";//发件人的email
public static final String PWD = "Finance123";//发件人密码
/**
* 获取session
* @return
*/
public static Session getSession()
{
Properties properties = new Properties();
properties.put("mail.smtp.host",HOST);
properties.put("mail.store.protocol" , PROTOCOL);//设置协议
properties.put("mail.smtp.port", PORT);//设置端口
properties.put("mail.smtp.auth" , true);
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(FROM, PWD);
}
};
Session session = Session.getDefaultInstance(properties , authenticator);
return session;
}
public static void sendMail(String to, String code) throws MessagingException {
Session session = getSession();
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(FROM));
message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
InetAddress addr = null;
try {
addr = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
String ip=addr.getHostAddress().toString();//获得本机IP
message.setSubject("来自校园金融的激活邮件");
message.setContent("<h1>来自校园金融的激活邮件,激活请点击以下链接:</h1><h3><a href='http://"+ip+":8080/Finance/servlet/ActiveServlet?code="+code+"'>http://"+ip+":8080/Finance/servlet/ActiveServlet?code="+code+"</a></h3>","text/html;charset=UTF-8");
Transport.send(message);
//0.邮箱服务器的用户名 密码
/*String E_username="";
String E_password="";
//1.创建连接对象
Properties properties = new Properties();
//properties.setProperty();主机名 本地省略
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(E_username,E_password);
}
});
//2.创建一个邮件对象
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(E_username));//发件人
message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));//收件人
message.setSubject("来自校园金融的激活邮件");
message.setContent("<h1>来自校园金融的激活邮件,激活请点击一下链接:</h1><h3><a href='http://localhost:8080/Finance/ActiveServlet?code="+code+"'>http://localhost:8080/Finance/ActiveServlet?code="+code+"</a></h3>","text/html;charset=UTF-8");
//3.发送一封激活邮件
Transport.send(message);*/
}
}
| UTF-8 | Java | 3,617 | java | MailUtils.java | Java | [
{
"context": "va.util.Properties;\n\n/**\n * 邮件发送的工具类\n * Created by Amie on 2017/3/2.\n */\npublic class MailUtils {\n /**",
"end": 304,
"score": 0.8292491436004639,
"start": 300,
"tag": "NAME",
"value": "Amie"
},
{
"context": "PORT = 25;\n public static final String FROM = \"18816298653@163.com\";//发件人的email\n public static final String PWD =",
"end": 621,
"score": 0.9985942840576172,
"start": 602,
"tag": "EMAIL",
"value": "18816298653@163.com"
},
{
"context": "//发件人的email\n public static final String PWD = \"Finance123\";//发件人密码\n\n /**\n * 获取session\n * @return",
"end": 683,
"score": 0.9994274973869324,
"start": 673,
"tag": "PASSWORD",
"value": "Finance123"
}
]
| null | []
| package com.seu.util;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;
/**
* 邮件发送的工具类
* Created by Amie on 2017/3/2.
*/
public class MailUtils {
/**
*
* @param to 给谁发邮件
* @param code 邮件的激活码
*/
public static final String HOST = "smtp.163.com";
public static final String PROTOCOL = "smtp";
public static final int PORT = 25;
public static final String FROM = "<EMAIL>";//发件人的email
public static final String PWD = "<PASSWORD>";//发件人密码
/**
* 获取session
* @return
*/
public static Session getSession()
{
Properties properties = new Properties();
properties.put("mail.smtp.host",HOST);
properties.put("mail.store.protocol" , PROTOCOL);//设置协议
properties.put("mail.smtp.port", PORT);//设置端口
properties.put("mail.smtp.auth" , true);
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(FROM, PWD);
}
};
Session session = Session.getDefaultInstance(properties , authenticator);
return session;
}
public static void sendMail(String to, String code) throws MessagingException {
Session session = getSession();
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(FROM));
message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
InetAddress addr = null;
try {
addr = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
String ip=addr.getHostAddress().toString();//获得本机IP
message.setSubject("来自校园金融的激活邮件");
message.setContent("<h1>来自校园金融的激活邮件,激活请点击以下链接:</h1><h3><a href='http://"+ip+":8080/Finance/servlet/ActiveServlet?code="+code+"'>http://"+ip+":8080/Finance/servlet/ActiveServlet?code="+code+"</a></h3>","text/html;charset=UTF-8");
Transport.send(message);
//0.邮箱服务器的用户名 密码
/*String E_username="";
String E_password="";
//1.创建连接对象
Properties properties = new Properties();
//properties.setProperty();主机名 本地省略
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(E_username,E_password);
}
});
//2.创建一个邮件对象
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(E_username));//发件人
message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));//收件人
message.setSubject("来自校园金融的激活邮件");
message.setContent("<h1>来自校园金融的激活邮件,激活请点击一下链接:</h1><h3><a href='http://localhost:8080/Finance/ActiveServlet?code="+code+"'>http://localhost:8080/Finance/ActiveServlet?code="+code+"</a></h3>","text/html;charset=UTF-8");
//3.发送一封激活邮件
Transport.send(message);*/
}
}
| 3,605 | 0.645638 | 0.628132 | 88 | 36.647728 | 38.033192 | 236 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.704545 | false | false | 4 |
af1b87aba2cd964051c7616f11311781a60051c1 | 18,537,078,914,163 | 05c649060c4261fa9bce6d5f8949e23d09f3aace | /core/src/main/java/cz/openwise/userpost/core/repository/configuration/WebClientConfiguration.java | 8c2a5e49ea195b5b16ec372302169033ebc09e50 | []
| no_license | filibor/user-post | https://github.com/filibor/user-post | 260102e0b3ae3b6cd740b5cd1ed9472189223177 | c490096b7013f076d0e9903b7ddb892b46cdfcaa | refs/heads/master | 2020-04-05T13:59:50.185000 | 2018-11-11T12:51:04 | 2018-11-11T12:51:04 | 156,919,125 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cz.openwise.userpost.core.repository.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
/**
* Configuration of WebClient for User posts master system.
*
* @author <a href="mailto:filip.borovec@openwise.cz">Filip Borovec</a>
*/
@Configuration
public class WebClientConfiguration {
@Bean
public WebClient getWebClient() {
return WebClient.builder()
.baseUrl("https://jsonplaceholder.typicode.com")
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.build();
}
}
| UTF-8 | Java | 819 | java | WebClientConfiguration.java | Java | [
{
"context": "osts master system.\n *\n * @author <a href=\"mailto:filip.borovec@openwise.cz\">Filip Borovec</a>\n */\n@Configuration\npublic clas",
"end": 449,
"score": 0.9997777938842773,
"start": 424,
"tag": "EMAIL",
"value": "filip.borovec@openwise.cz"
},
{
"context": "author <a href=\"mailto:filip.borovec@openwise.cz\">Filip Borovec</a>\n */\n@Configuration\npublic class WebClientConf",
"end": 464,
"score": 0.9998458623886108,
"start": 451,
"tag": "NAME",
"value": "Filip Borovec"
}
]
| null | []
| package cz.openwise.userpost.core.repository.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
/**
* Configuration of WebClient for User posts master system.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
@Configuration
public class WebClientConfiguration {
@Bean
public WebClient getWebClient() {
return WebClient.builder()
.baseUrl("https://jsonplaceholder.typicode.com")
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.build();
}
}
| 794 | 0.715507 | 0.715507 | 25 | 31.76 | 28.283253 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.32 | false | false | 4 |
4e2d324fd2e02a2e2154b10093d9a25178d91d9f | 18,949,395,720,582 | 847080c4f93b6a9047de34c073faa90e2871b3e2 | /src/main/java/pl/sw/Chapter7/Listing_7_8_TruckDemo/Vehicle.java | cc583df497d78c7c495345496c433396b558b04e | []
| no_license | sparrov/Playground | https://github.com/sparrov/Playground | 3fbcfd6f35d9ef73b2185e21d08f1a4d62d4bb10 | 960dcf0deda3034747d50af38cd0e8e5d6df30c9 | refs/heads/master | 2022-12-28T09:28:24.221000 | 2020-07-28T21:01:32 | 2020-07-28T21:01:32 | 282,984,387 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pl.sw.Chapter7.Listing_7_8_TruckDemo;
public class Vehicle {
private int passengers;
private int fuelCap;
private double lkm;
Vehicle(int passengers, int fuelCap, double lkm) {
this.passengers = passengers;
this.fuelCap = fuelCap;
this.lkm = lkm;
}
void setPassengers(int passengers) {
this.passengers = passengers;
}
void setFuelCap(int fuelCap) {
this.fuelCap = fuelCap;
}
void setLkm(double lkm) {
this.lkm = lkm;
}
int getPassengers() {
return passengers;
}
int getFuelCap() {
return fuelCap;
}
double getLkm() {
return lkm;
}
int range() {
return (int) (fuelCap / lkm * 100);
}
double fuelNeeded(int distance) {
return distance * lkm / 100;
}
}
| UTF-8 | Java | 841 | java | Vehicle.java | Java | []
| null | []
| package pl.sw.Chapter7.Listing_7_8_TruckDemo;
public class Vehicle {
private int passengers;
private int fuelCap;
private double lkm;
Vehicle(int passengers, int fuelCap, double lkm) {
this.passengers = passengers;
this.fuelCap = fuelCap;
this.lkm = lkm;
}
void setPassengers(int passengers) {
this.passengers = passengers;
}
void setFuelCap(int fuelCap) {
this.fuelCap = fuelCap;
}
void setLkm(double lkm) {
this.lkm = lkm;
}
int getPassengers() {
return passengers;
}
int getFuelCap() {
return fuelCap;
}
double getLkm() {
return lkm;
}
int range() {
return (int) (fuelCap / lkm * 100);
}
double fuelNeeded(int distance) {
return distance * lkm / 100;
}
}
| 841 | 0.570749 | 0.560048 | 46 | 17.282608 | 15.449305 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.369565 | false | false | 4 |
d57ffcd92bcb77a33435d09e157d33d745cb414c | 8,108,898,288,224 | ee14694a7b73e0e6280a688bac153c8c425f11bc | /SAC-OS/sac-os-model/src/main/java/net/easipay/cbp/model/SacFundTransferCmd.java | b3ae5ca96e263991dfdb78804929b9fcc5b13abf | []
| no_license | moutainhigh/sac | https://github.com/moutainhigh/sac | 8ee1368d2124bf496d71c3612d74b16d440d1dd0 | eebecdf879ef50d7f4127bc91d08c4ea327c972c | refs/heads/master | 2021-09-14T01:40:10.700000 | 2018-05-07T09:35:08 | 2018-05-07T09:45:13 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.easipay.cbp.model;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Entity;
/**
* @author sydai
*/
@Entity
public class SacFundTransferCmd implements Serializable {
private static final long serialVersionUID = 5128216952725189129L;
private long id;
private String trxSerialNo;
private String craccNo;
private String craccNodeCode;
private String draccNo;
private String draccNodeCode;
private String payCurrency;
private BigDecimal payAmount;
private String payWay;
private String memo;
private Date createTime;
private Date updateTime;
private String cmdState;
private String cmdMemo;
private String draccAreaCode;
private String craccAreaCode;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTrxSerialNo() {
return this.trxSerialNo;
}
public void setTrxSerialNo(String trxSerialNo) {
this.trxSerialNo = trxSerialNo;
}
public String getCraccNo() {
return this.craccNo;
}
public void setCraccNo(String craccNo) {
this.craccNo = craccNo;
}
public String getCraccNodeCode() {
return this.craccNodeCode;
}
public void setCraccNodeCode(String craccNodeCode) {
this.craccNodeCode = craccNodeCode;
}
public String getDraccNo() {
return this.draccNo;
}
public void setDraccNo(String draccNo) {
this.draccNo = draccNo;
}
public String getDraccNodeCode() {
return this.draccNodeCode;
}
public void setDraccNodeCode(String draccNodeCode) {
this.draccNodeCode = draccNodeCode;
}
public String getPayCurrency() {
return this.payCurrency;
}
public void setPayCurrency(String payCurrency) {
this.payCurrency = payCurrency;
}
public BigDecimal getPayAmount() {
return payAmount;
}
public void setPayAmount(BigDecimal payAmount) {
this.payAmount = payAmount;
}
public String getPayWay() {
return this.payWay;
}
public void setPayWay(String payWay) {
this.payWay = payWay;
}
public String getMemo() {
return this.memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public Date getCreateTime() {
return this.createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getCmdState() {
return this.cmdState;
}
public void setCmdState(String cmdState) {
this.cmdState = cmdState;
}
public String getCmdMemo() {
return this.cmdMemo;
}
public void setCmdMemo(String cmdMemo) {
this.cmdMemo = cmdMemo;
}
public String getDraccAreaCode() {
return draccAreaCode;
}
public void setDraccAreaCode(String draccAreaCode) {
this.draccAreaCode = draccAreaCode;
}
public String getCraccAreaCode() {
return craccAreaCode;
}
public void setCraccAreaCode(String craccAreaCode) {
this.craccAreaCode = craccAreaCode;
}
}
| UTF-8 | Java | 3,126 | java | SacFundTransferCmd.java | Java | [
{
"context": "\nimport javax.persistence.Entity;\n\n\n/**\n * @author sydai \n */\n@Entity\npublic class SacFundTransferCmd impl",
"end": 169,
"score": 0.9995532631874084,
"start": 164,
"tag": "USERNAME",
"value": "sydai"
}
]
| null | []
| package net.easipay.cbp.model;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Entity;
/**
* @author sydai
*/
@Entity
public class SacFundTransferCmd implements Serializable {
private static final long serialVersionUID = 5128216952725189129L;
private long id;
private String trxSerialNo;
private String craccNo;
private String craccNodeCode;
private String draccNo;
private String draccNodeCode;
private String payCurrency;
private BigDecimal payAmount;
private String payWay;
private String memo;
private Date createTime;
private Date updateTime;
private String cmdState;
private String cmdMemo;
private String draccAreaCode;
private String craccAreaCode;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTrxSerialNo() {
return this.trxSerialNo;
}
public void setTrxSerialNo(String trxSerialNo) {
this.trxSerialNo = trxSerialNo;
}
public String getCraccNo() {
return this.craccNo;
}
public void setCraccNo(String craccNo) {
this.craccNo = craccNo;
}
public String getCraccNodeCode() {
return this.craccNodeCode;
}
public void setCraccNodeCode(String craccNodeCode) {
this.craccNodeCode = craccNodeCode;
}
public String getDraccNo() {
return this.draccNo;
}
public void setDraccNo(String draccNo) {
this.draccNo = draccNo;
}
public String getDraccNodeCode() {
return this.draccNodeCode;
}
public void setDraccNodeCode(String draccNodeCode) {
this.draccNodeCode = draccNodeCode;
}
public String getPayCurrency() {
return this.payCurrency;
}
public void setPayCurrency(String payCurrency) {
this.payCurrency = payCurrency;
}
public BigDecimal getPayAmount() {
return payAmount;
}
public void setPayAmount(BigDecimal payAmount) {
this.payAmount = payAmount;
}
public String getPayWay() {
return this.payWay;
}
public void setPayWay(String payWay) {
this.payWay = payWay;
}
public String getMemo() {
return this.memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public Date getCreateTime() {
return this.createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getCmdState() {
return this.cmdState;
}
public void setCmdState(String cmdState) {
this.cmdState = cmdState;
}
public String getCmdMemo() {
return this.cmdMemo;
}
public void setCmdMemo(String cmdMemo) {
this.cmdMemo = cmdMemo;
}
public String getDraccAreaCode() {
return draccAreaCode;
}
public void setDraccAreaCode(String draccAreaCode) {
this.draccAreaCode = draccAreaCode;
}
public String getCraccAreaCode() {
return craccAreaCode;
}
public void setCraccAreaCode(String craccAreaCode) {
this.craccAreaCode = craccAreaCode;
}
}
| 3,126 | 0.706014 | 0.699936 | 180 | 16.366667 | 17.104223 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.044444 | false | false | 4 |
afcb72bcafe6abb0801c4c4536807325918d9ede | 31,817,117,731,336 | 6ba2e2e4adb512213435e24d80607f26009232e5 | /web-ops/src/main/java/com/lti/rest/RegisterDao.java | bc9c4233ea6f56a80d956fe90905ac0b588afa90 | []
| no_license | ritusu/spring-mvc | https://github.com/ritusu/spring-mvc | 8e25dc440324d3ace72d5e6757f6aeb90c2b9beb | 912db86ed127cb996f5bb0cf5136675fcd2b1409 | refs/heads/master | 2022-12-21T14:02:38.694000 | 2019-07-10T12:50:53 | 2019-07-10T12:50:53 | 196,203,063 | 0 | 0 | null | false | 2022-12-16T00:36:26 | 2019-07-10T12:40:15 | 2019-07-10T12:50:56 | 2022-12-16T00:36:26 | 1,517 | 0 | 0 | 9 | Java | false | false | package com.lti.rest;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import com.lti.entity.Register;
public class RegisterDao {
public void save(Register register){
Connection conn=null;
java.sql.PreparedStatement stmt = null;
try {
InputStream is = this.getClass().getClassLoader().getResourceAsStream("dev-db.properties");
Properties dbprops = new Properties();
dbprops.load(is);
Class.forName(dbprops.getProperty("driver"));
conn=DriverManager.getConnection(dbprops.getProperty("url"),
dbprops.getProperty("user"),
dbprops.getProperty("pass"));
String sql="insert into tbl_1 values(?,?,?,?)";
stmt=conn.prepareStatement(sql);
stmt.setString(1,register.getName());
stmt.setString(2,register.getEmail());
stmt.setString(3, register.getUsername());
stmt.setString(4, register.getPassword());
stmt.executeUpdate();
}
catch(ClassNotFoundException e) {
System.out.println("driver not found");
}
catch(SQLException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
conn.close();
}
catch(Exception e) {
}
}
}
}
| UTF-8 | Java | 1,473 | java | RegisterDao.java | Java | []
| null | []
| package com.lti.rest;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import com.lti.entity.Register;
public class RegisterDao {
public void save(Register register){
Connection conn=null;
java.sql.PreparedStatement stmt = null;
try {
InputStream is = this.getClass().getClassLoader().getResourceAsStream("dev-db.properties");
Properties dbprops = new Properties();
dbprops.load(is);
Class.forName(dbprops.getProperty("driver"));
conn=DriverManager.getConnection(dbprops.getProperty("url"),
dbprops.getProperty("user"),
dbprops.getProperty("pass"));
String sql="insert into tbl_1 values(?,?,?,?)";
stmt=conn.prepareStatement(sql);
stmt.setString(1,register.getName());
stmt.setString(2,register.getEmail());
stmt.setString(3, register.getUsername());
stmt.setString(4, register.getPassword());
stmt.executeUpdate();
}
catch(ClassNotFoundException e) {
System.out.println("driver not found");
}
catch(SQLException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
conn.close();
}
catch(Exception e) {
}
}
}
}
| 1,473 | 0.626612 | 0.623218 | 60 | 22.549999 | 22.516235 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.783333 | false | false | 4 |
20065c16ba4afc7bfb9fc133e9bd65144f34986e | 5,136,780,887,337 | 7304952f40d96163e8f58f014c5fd813a3be024c | /common/baselib/src/main/java/com/smartstudy/commonlib/ui/adapter/base/TreeRecyclerViewType.java | a937bed20a2caa41a73943acfd85c62451f40e23 | []
| no_license | lymluck/proj_abroad | https://github.com/lymluck/proj_abroad | c6268a5bb5e3af9a0117170ac9f18029c6d77d9e | d0c1ac1e3b85561dc2e49826b9db4aba09537254 | refs/heads/master | 2020-03-27T08:25:45.694000 | 2018-09-04T09:16:02 | 2018-09-04T09:16:02 | 146,253,422 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.smartstudy.commonlib.ui.adapter.base;
public enum TreeRecyclerViewType {
/**
* 显示所有,不可展开折叠
* 适用场景,多级的data数据展示,多type布局.
*/
SHOW_ALL,
/**
* 根据isExpand的状态显示展开与折叠,
* 适用场景,多级的data数据展示,多type布局.
*/
SHOW_EXPAND,
/**
* 默认显示,显示一级,点击展开,折叠不会影响子级展开折叠
* 适用场景,多级列表,保存展开状态
*/
SHOW_DEFUTAL,
}
| UTF-8 | Java | 536 | java | TreeRecyclerViewType.java | Java | []
| null | []
| package com.smartstudy.commonlib.ui.adapter.base;
public enum TreeRecyclerViewType {
/**
* 显示所有,不可展开折叠
* 适用场景,多级的data数据展示,多type布局.
*/
SHOW_ALL,
/**
* 根据isExpand的状态显示展开与折叠,
* 适用场景,多级的data数据展示,多type布局.
*/
SHOW_EXPAND,
/**
* 默认显示,显示一级,点击展开,折叠不会影响子级展开折叠
* 适用场景,多级列表,保存展开状态
*/
SHOW_DEFUTAL,
}
| 536 | 0.588889 | 0.588889 | 21 | 16.142857 | 13.687971 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 4 |
fdde75beb0875f2e25ff8b9ea6318d034b904f57 | 19,327,352,883,507 | 888f2fe2c594a2dddd003ff7bc8f0d7ab8c65c06 | /src/components/Gender.java | dadeac843b5b583ec481b7bda3ba2343c840768e | []
| no_license | alex4o/environment-sim | https://github.com/alex4o/environment-sim | d92f59d0a925c66c6d47a8d2cbf561aa00ab7a0a | 8ef1151fec1fc71d6799e94eeeca76ee63c6634d | refs/heads/master | 2021-09-08T01:41:05.325000 | 2018-03-05T11:57:39 | 2018-03-05T11:57:39 | 120,297,767 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package components;
import com.badlogic.ashley.core.Component;
public class Gender implements Component {
public enum GenderType {
Male,
Female
}
GenderType gender;
public Gender(GenderType gender) {
this.gender = gender;
}
public GenderType getGender() {
return gender;
}
public void setGender(GenderType gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Gender{" +
"gender=" + gender +
'}';
}
}
| UTF-8 | Java | 465 | java | Gender.java | Java | []
| null | []
| package components;
import com.badlogic.ashley.core.Component;
public class Gender implements Component {
public enum GenderType {
Male,
Female
}
GenderType gender;
public Gender(GenderType gender) {
this.gender = gender;
}
public GenderType getGender() {
return gender;
}
public void setGender(GenderType gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Gender{" +
"gender=" + gender +
'}';
}
}
| 465 | 0.686022 | 0.686022 | 31 | 14 | 14.158093 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.290323 | false | false | 4 |
32e2da2510058d8f137a4af7f372942ab146fbc4 | 13,950,053,778,840 | 837a494d33433a2729fd7cb1000a9f70bf89efa4 | /app/src/main/java/org/bluetooth/Service.java | 90014b7bb5d2711725fc9fb40770626aae635e7f | []
| no_license | ArunNKutty/RfDuino | https://github.com/ArunNKutty/RfDuino | 36829fa6cd06eea1738ed071a9340e317813b2b2 | 751b4967dc05abdf166962d334b20f8b46d1aa12 | refs/heads/master | 2021-01-16T21:54:25.928000 | 2016-08-07T09:00:37 | 2016-08-07T09:00:37 | 65,124,325 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.bluetooth;
/** This is a class of constants defined for easy reference from the Bluetooth Low Energy Developer's specification
* on GATT Service and Characteristics.
* https://developer.bluetooth.org/gatt/Pages/GATT-Specification-Documents.aspx
* @author adrienne
*
*/
public class Service {
public final int alert_notification = 0x1811 ;
public final int battery_service = 0x180F ;
public final int blood_pressure = 0x1810 ;
public final int current_time = 0x1805 ;
public final int cycling_power = 0x1818 ;
public final int cycling_speed_and_cadence = 0x1816 ;
public final int device_information = 0x180A ;
public final int generic_access = 0x1800 ;
public final int generic_attribute = 0x1801 ;
public final int glucose = 0x1808 ;
public final int health_thermometer = 0x1809 ;
public final int heart_rate = 0x180D ;
public final int human_interface_device = 0x1812 ;
public final int immediate_alert = 0x1802 ;
public final int link_loss = 0x1803 ;
public final int location_and_navigation = 0x1819 ;
public final int next_dst_change = 0x1807 ;
public final int phone_alert_status = 0x180E ;
public final int reference_time_update = 0x1806 ;
public final int running_speed_and_cadence = 0x1814 ;
public final int scan_parameters = 0x1813 ;
public final int tx_power = 0x1804;
//Characteristics:
} | UTF-8 | Java | 1,393 | java | Service.java | Java | [
{
"context": "Pages/GATT-Specification-Documents.aspx\n * @author adrienne\n *\n */\n\npublic class Service {\n\t\npublic final int",
"end": 279,
"score": 0.7076635956764221,
"start": 271,
"tag": "USERNAME",
"value": "adrienne"
}
]
| null | []
| package org.bluetooth;
/** This is a class of constants defined for easy reference from the Bluetooth Low Energy Developer's specification
* on GATT Service and Characteristics.
* https://developer.bluetooth.org/gatt/Pages/GATT-Specification-Documents.aspx
* @author adrienne
*
*/
public class Service {
public final int alert_notification = 0x1811 ;
public final int battery_service = 0x180F ;
public final int blood_pressure = 0x1810 ;
public final int current_time = 0x1805 ;
public final int cycling_power = 0x1818 ;
public final int cycling_speed_and_cadence = 0x1816 ;
public final int device_information = 0x180A ;
public final int generic_access = 0x1800 ;
public final int generic_attribute = 0x1801 ;
public final int glucose = 0x1808 ;
public final int health_thermometer = 0x1809 ;
public final int heart_rate = 0x180D ;
public final int human_interface_device = 0x1812 ;
public final int immediate_alert = 0x1802 ;
public final int link_loss = 0x1803 ;
public final int location_and_navigation = 0x1819 ;
public final int next_dst_change = 0x1807 ;
public final int phone_alert_status = 0x180E ;
public final int reference_time_update = 0x1806 ;
public final int running_speed_and_cadence = 0x1814 ;
public final int scan_parameters = 0x1813 ;
public final int tx_power = 0x1804;
//Characteristics:
} | 1,393 | 0.730797 | 0.654702 | 42 | 32.190475 | 25.848679 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.595238 | false | false | 4 |
5192e0580080689db5bec62e2a75e07ab43552de | 24,635,932,477,639 | f688d3598e16ba9757bc5891c9f2b1938559cbe3 | /TimeGallery/src/com/baozijuan/timegallery/action/ForgetPasswordAction.java | aec63f19e5d7d717889d08081884dd9fc0c495d4 | [
"Apache-2.0"
]
| permissive | emersonff/baozijuan.com | https://github.com/emersonff/baozijuan.com | b93acbcf8ab0eadebcb4da8d2abbe4ad210d89f9 | c80882d109ad0ef5ab51aaebef85e4e6c97cadcf | refs/heads/master | 2020-12-02T18:15:19.488000 | 2017-03-25T10:44:24 | 2017-03-25T10:44:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.baozijuan.timegallery.action;
import com.baozijuan.timegallery.action.base.UserBaseAction;
import com.baozijuan.timegallery.action.base.WebConstant;
import com.opensymphony.xwork2.ActionContext;
public class ForgetPasswordAction extends UserBaseAction {
private static final long serialVersionUID = 7936859495463025529L;
private static final String SEND_MAIL = "send_mail";
private String account;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
@Override
public String execute() throws Exception {
ActionContext actionContext = ActionContext.getContext();
if (account == null)
return ERROR;
if (userManager.isUserExist(getAccount())) {
actionContext.getSession().put(WebConstant.RESET_PASS, userManager.getUserByAccount(account));
return SEND_MAIL;
} else {
actionContext.getSession().put(WebConstant.INTERCEPT, "Account not exist");
return ERROR;
}
}
}
| UTF-8 | Java | 1,018 | java | ForgetPasswordAction.java | Java | []
| null | []
| package com.baozijuan.timegallery.action;
import com.baozijuan.timegallery.action.base.UserBaseAction;
import com.baozijuan.timegallery.action.base.WebConstant;
import com.opensymphony.xwork2.ActionContext;
public class ForgetPasswordAction extends UserBaseAction {
private static final long serialVersionUID = 7936859495463025529L;
private static final String SEND_MAIL = "send_mail";
private String account;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
@Override
public String execute() throws Exception {
ActionContext actionContext = ActionContext.getContext();
if (account == null)
return ERROR;
if (userManager.isUserExist(getAccount())) {
actionContext.getSession().put(WebConstant.RESET_PASS, userManager.getUserByAccount(account));
return SEND_MAIL;
} else {
actionContext.getSession().put(WebConstant.INTERCEPT, "Account not exist");
return ERROR;
}
}
}
| 1,018 | 0.740668 | 0.721022 | 37 | 25.513514 | 26.355801 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.513514 | false | false | 4 |
72709ffe578a38f66f8bda4969d37cb352aadaa6 | 17,093,969,841,264 | 1c2649de77ab28d3fa7f0f98e56b90aab98a3baf | /app/src/main/java/com/example/a83776/demo/model/Prefs/PreferencesHelper.java | 2e7dc32cb0ccee417f0a3f62308c18f67191f661 | []
| no_license | LonLove/Demo | https://github.com/LonLove/Demo | 91cbeee2e6884b7475af40ff547d27b720f22bfa | 3dc97ae2abc64e2c2ef23209d0658750932ff653 | refs/heads/master | 2020-03-24T20:55:31.663000 | 2018-07-31T12:11:49 | 2018-07-31T12:11:49 | 143,003,842 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.a83776.demo.model.Prefs;
/**
* description:sp
* author: GaoJie
* created at: 2018/6/29 10:39
*/
public interface PreferencesHelper {
//
boolean getNoImageState();
}
| UTF-8 | Java | 196 | java | PreferencesHelper.java | Java | [
{
"context": "demo.model.Prefs;\n/**\n * description:sp\n * author: GaoJie\n * created at: 2018/6/29 10:39\n*/\npublic interfac",
"end": 84,
"score": 0.9988114237785339,
"start": 78,
"tag": "NAME",
"value": "GaoJie"
}
]
| null | []
| package com.example.a83776.demo.model.Prefs;
/**
* description:sp
* author: GaoJie
* created at: 2018/6/29 10:39
*/
public interface PreferencesHelper {
//
boolean getNoImageState();
}
| 196 | 0.693878 | 0.612245 | 10 | 18.6 | 14.833745 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 4 |
e116b8b4452f7547365926c2e9b266cd5ca77e4d | 25,383,256,780,079 | 22cefaaae609e28545530de90c66df9b92a66197 | /app/src/main/java/com/cy/test/TouchDelegateFix.java | 02a81fd813569df0bb12510bc7187ae2bda82363 | []
| no_license | chenyan-master/TestSystemApiDemo | https://github.com/chenyan-master/TestSystemApiDemo | 9cb7468f5470d937758c147f09c9d091c2f85e8a | 823dcfdd4bf2fa7e2400dcdf7b2de109a4e7a7c9 | refs/heads/master | 2022-03-06T04:27:14.111000 | 2019-11-11T10:09:55 | 2019-11-11T10:09:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cy.test;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.TouchDelegate;
import android.view.View;
import android.view.ViewConfiguration;
/**
* @author chenyan@huobi.com
* @date 2019-11-11 17:27
* @desp 修复android 9.0以前使用TouchDelegate点击扩大区域后再点击父控件无法响应点击事件的bug
*/
public class TouchDelegateFix extends TouchDelegate {
/**
* View that should receive forwarded touch events
*/
private View mDelegateView;
/**
* Bounds in local coordinates of the containing view that should be mapped to the delegate
* view. This rect is used for initial hit testing.
*/
private Rect mBounds;
/**
* mBounds inflated to include some slop. This rect is to track whether the motion events
* should be considered to be within the delegate view.
*/
private Rect mSlopBounds;
/**
* True if the delegate had been targeted on a down event (intersected mBounds).
*/
private boolean mDelegateTargeted;
private int mSlop;
public TouchDelegateFix(Rect bounds, View delegateView) {
super(bounds, delegateView);
mBounds = bounds;
mSlop = ViewConfiguration.get(delegateView.getContext()).getScaledTouchSlop();
mSlopBounds = new Rect(bounds);
mSlopBounds.inset(-mSlop, -mSlop);
mDelegateView = delegateView;
}
/**
* Will forward touch events to the delegate view if the event is within the bounds
* specified in the constructor.
*
* @param event The touch event to forward
* @return True if the event was forwarded to the delegate, false otherwise.
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int)event.getX();
int y = (int)event.getY();
boolean sendToDelegate = false;
boolean hit = true;
boolean handled = false;
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mDelegateTargeted = mBounds.contains(x, y);//android 9.0之前mDelegateTargeted 没有复位
sendToDelegate = mDelegateTargeted;
break;
case MotionEvent.ACTION_POINTER_DOWN:
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_MOVE:
sendToDelegate = mDelegateTargeted;
if (sendToDelegate) {
Rect slopBounds = mSlopBounds;
if (!slopBounds.contains(x, y)) {
hit = false;
}
}
break;
case MotionEvent.ACTION_CANCEL:
sendToDelegate = mDelegateTargeted;
mDelegateTargeted = false;
break;
}
if (sendToDelegate) {
final View delegateView = mDelegateView;
if (hit) {
// Offset event coordinates to be inside the target view
event.setLocation(delegateView.getWidth() / 2, delegateView.getHeight() / 2);
} else {
// Offset event coordinates to be outside the target view (in case it does
// something like tracking pressed state)
int slop = mSlop;
event.setLocation(-(slop * 2), -(slop * 2));
}
handled = delegateView.dispatchTouchEvent(event);
}
return handled;
}
}
| UTF-8 | Java | 3,517 | java | TouchDelegateFix.java | Java | [
{
"context": "rt android.view.ViewConfiguration;\n\n/**\n * @author chenyan@huobi.com\n * @date 2019-11-11 17:27\n * @desp 修复android 9.0以",
"end": 218,
"score": 0.999916136264801,
"start": 201,
"tag": "EMAIL",
"value": "chenyan@huobi.com"
}
]
| null | []
| package com.cy.test;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.TouchDelegate;
import android.view.View;
import android.view.ViewConfiguration;
/**
* @author <EMAIL>
* @date 2019-11-11 17:27
* @desp 修复android 9.0以前使用TouchDelegate点击扩大区域后再点击父控件无法响应点击事件的bug
*/
public class TouchDelegateFix extends TouchDelegate {
/**
* View that should receive forwarded touch events
*/
private View mDelegateView;
/**
* Bounds in local coordinates of the containing view that should be mapped to the delegate
* view. This rect is used for initial hit testing.
*/
private Rect mBounds;
/**
* mBounds inflated to include some slop. This rect is to track whether the motion events
* should be considered to be within the delegate view.
*/
private Rect mSlopBounds;
/**
* True if the delegate had been targeted on a down event (intersected mBounds).
*/
private boolean mDelegateTargeted;
private int mSlop;
public TouchDelegateFix(Rect bounds, View delegateView) {
super(bounds, delegateView);
mBounds = bounds;
mSlop = ViewConfiguration.get(delegateView.getContext()).getScaledTouchSlop();
mSlopBounds = new Rect(bounds);
mSlopBounds.inset(-mSlop, -mSlop);
mDelegateView = delegateView;
}
/**
* Will forward touch events to the delegate view if the event is within the bounds
* specified in the constructor.
*
* @param event The touch event to forward
* @return True if the event was forwarded to the delegate, false otherwise.
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int)event.getX();
int y = (int)event.getY();
boolean sendToDelegate = false;
boolean hit = true;
boolean handled = false;
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mDelegateTargeted = mBounds.contains(x, y);//android 9.0之前mDelegateTargeted 没有复位
sendToDelegate = mDelegateTargeted;
break;
case MotionEvent.ACTION_POINTER_DOWN:
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_MOVE:
sendToDelegate = mDelegateTargeted;
if (sendToDelegate) {
Rect slopBounds = mSlopBounds;
if (!slopBounds.contains(x, y)) {
hit = false;
}
}
break;
case MotionEvent.ACTION_CANCEL:
sendToDelegate = mDelegateTargeted;
mDelegateTargeted = false;
break;
}
if (sendToDelegate) {
final View delegateView = mDelegateView;
if (hit) {
// Offset event coordinates to be inside the target view
event.setLocation(delegateView.getWidth() / 2, delegateView.getHeight() / 2);
} else {
// Offset event coordinates to be outside the target view (in case it does
// something like tracking pressed state)
int slop = mSlop;
event.setLocation(-(slop * 2), -(slop * 2));
}
handled = delegateView.dispatchTouchEvent(event);
}
return handled;
}
}
| 3,507 | 0.603653 | 0.597854 | 101 | 33.148514 | 25.636988 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.455446 | false | false | 4 |
2bf5fcfe714c98d209c1a45ee6a5205342ec1ba4 | 33,406,255,628,958 | 7ca77f13d6e847264f838c7332a217adec6764f1 | /neurus-core/src/test/java/org/neurus/evolution/LoggingEvolutionListenerTest.java | 3c60a45c28d542e408c06bb8540ebbda763bbe59 | []
| no_license | neurus/neurus | https://github.com/neurus/neurus | 34bd57c8781e347c3488a7f1aa98095b4c92cdfe | 1cbd0fb313e68e52020a46b6840fec724ed74598 | refs/heads/master | 2016-09-06T02:50:52.893000 | 2011-08-05T05:12:48 | 2011-08-05T05:12:48 | 1,568,615 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.neurus.evolution;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.neurus.testing.MoreAsserts.assertStringContains;
import java.util.logging.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.neurus.fitness.Fitness;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
@RunWith(PowerMockRunner.class)
public class LoggingEvolutionListenerTest {
private Logger logger;
private ArgumentCaptor<String> loggingCaptor;
@Before
public void setUp() {
logger = mock(Logger.class);
loggingCaptor = ArgumentCaptor.forClass(String.class);
Whitebox.setInternalState(LoggingEvolutionListener.class, "logger", logger);
}
@Test
public void testLoggingEvolutionListener() {
LoggingEvolutionListener listener = new LoggingEvolutionListener();
Population population = TestPopulations.populationWithFitnesses(0.25, 1.0, 1.25);
EvolutionSnapshot es = new EvolutionSnapshot(45, population, population.get(0), null);
listener.onNewGeneration(es);
verify(logger).info(loggingCaptor.capture());
assertStringContains("Generation: 45", loggingCaptor.getValue());
assertStringContains("Best Training: 0.250000", loggingCaptor.getValue());
}
@Test
public void testPrefix() {
LoggingEvolutionListener listener = new LoggingEvolutionListener("My Prefix. ");
Population population = TestPopulations.populationWithFitnesses(0.25, 1.0, 1.25);
EvolutionSnapshot es = new EvolutionSnapshot(45, population, population.get(0), null);
listener.onNewGeneration(es);
verify(logger).info(loggingCaptor.capture());
assertStringContains("My Prefix. ", loggingCaptor.getValue());
assertStringContains("Generation: 45", loggingCaptor.getValue());
assertStringContains("Best Training: 0.250000", loggingCaptor.getValue());
}
@Test
public void testLoggingWithValidationFitness() {
LoggingEvolutionListener listener = new LoggingEvolutionListener();
Population population = TestPopulations.populationWithFitnesses(0.25, 1.0, 1.25);
population.get(1).setValidationFitness(new Fitness(0.8345888888d));
EvolutionSnapshot es = new EvolutionSnapshot(45, population, population.get(0),
population.get(1));
listener.onNewGeneration(es);
verify(logger).info(loggingCaptor.capture());
assertStringContains("Generation: 45", loggingCaptor.getValue());
assertStringContains("Best Training: 0.250000", loggingCaptor.getValue());
assertStringContains("Best Validation: 0.834589", loggingCaptor.getValue());
}
}
| UTF-8 | Java | 2,694 | java | LoggingEvolutionListenerTest.java | Java | []
| null | []
| package org.neurus.evolution;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.neurus.testing.MoreAsserts.assertStringContains;
import java.util.logging.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.neurus.fitness.Fitness;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
@RunWith(PowerMockRunner.class)
public class LoggingEvolutionListenerTest {
private Logger logger;
private ArgumentCaptor<String> loggingCaptor;
@Before
public void setUp() {
logger = mock(Logger.class);
loggingCaptor = ArgumentCaptor.forClass(String.class);
Whitebox.setInternalState(LoggingEvolutionListener.class, "logger", logger);
}
@Test
public void testLoggingEvolutionListener() {
LoggingEvolutionListener listener = new LoggingEvolutionListener();
Population population = TestPopulations.populationWithFitnesses(0.25, 1.0, 1.25);
EvolutionSnapshot es = new EvolutionSnapshot(45, population, population.get(0), null);
listener.onNewGeneration(es);
verify(logger).info(loggingCaptor.capture());
assertStringContains("Generation: 45", loggingCaptor.getValue());
assertStringContains("Best Training: 0.250000", loggingCaptor.getValue());
}
@Test
public void testPrefix() {
LoggingEvolutionListener listener = new LoggingEvolutionListener("My Prefix. ");
Population population = TestPopulations.populationWithFitnesses(0.25, 1.0, 1.25);
EvolutionSnapshot es = new EvolutionSnapshot(45, population, population.get(0), null);
listener.onNewGeneration(es);
verify(logger).info(loggingCaptor.capture());
assertStringContains("My Prefix. ", loggingCaptor.getValue());
assertStringContains("Generation: 45", loggingCaptor.getValue());
assertStringContains("Best Training: 0.250000", loggingCaptor.getValue());
}
@Test
public void testLoggingWithValidationFitness() {
LoggingEvolutionListener listener = new LoggingEvolutionListener();
Population population = TestPopulations.populationWithFitnesses(0.25, 1.0, 1.25);
population.get(1).setValidationFitness(new Fitness(0.8345888888d));
EvolutionSnapshot es = new EvolutionSnapshot(45, population, population.get(0),
population.get(1));
listener.onNewGeneration(es);
verify(logger).info(loggingCaptor.capture());
assertStringContains("Generation: 45", loggingCaptor.getValue());
assertStringContains("Best Training: 0.250000", loggingCaptor.getValue());
assertStringContains("Best Validation: 0.834589", loggingCaptor.getValue());
}
}
| 2,694 | 0.765033 | 0.734967 | 67 | 39.208954 | 29.672609 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.985075 | false | false | 4 |
a1c0e94fc7261042b415e5984369fdce95a320be | 24,318,104,895,893 | 537d04ac5b8e060c96b66cec49e108bfb34b32e7 | /src/Victory.java | 39e1feb62af44256c22e26184f91c13f45680cd6 | []
| no_license | nikita-reva/star-rift | https://github.com/nikita-reva/star-rift | 91467797e8dc1f701a25faed787ae1ce7d4dc643 | 7c574439afc8159297e64f520916f53946d566c0 | refs/heads/main | 2023-01-04T19:15:57.941000 | 2020-11-02T10:51:16 | 2020-11-02T10:51:16 | 304,368,535 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Timer;
import java.util.TimerTask;
public class Victory {
Timer victory;
public Victory() {
victory = new Timer();
victory.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if(Var.victory) {
Var.gamerunning = false;
Var.btnrestart.setVisible(true);
Var.btnclose.setVisible(true);
Var.coinscollected = 0;
Var.crystalscollected = 0;
Var.shieldcharges = 0;
Var.timelapsesec = 10;
Var.timelapsems = 999;
Var.rockets = 10;
Var.lives = 3;
Var.maxlives = 5;
for(int i = 0; i < 5; i++) {
Var.enemyY[i] = -2000;
}
for(int i = 0; i < 3; i++) {
Var.crystalsY[i] = -2000;
}
for(int i = 0; i < 3; i++) {
Var.coinsY[i] = -2000;
}
}
}
}, 0, 15);
}
}
| UTF-8 | Java | 852 | java | Victory.java | Java | []
| null | []
| import java.util.Timer;
import java.util.TimerTask;
public class Victory {
Timer victory;
public Victory() {
victory = new Timer();
victory.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if(Var.victory) {
Var.gamerunning = false;
Var.btnrestart.setVisible(true);
Var.btnclose.setVisible(true);
Var.coinscollected = 0;
Var.crystalscollected = 0;
Var.shieldcharges = 0;
Var.timelapsesec = 10;
Var.timelapsems = 999;
Var.rockets = 10;
Var.lives = 3;
Var.maxlives = 5;
for(int i = 0; i < 5; i++) {
Var.enemyY[i] = -2000;
}
for(int i = 0; i < 3; i++) {
Var.crystalsY[i] = -2000;
}
for(int i = 0; i < 3; i++) {
Var.coinsY[i] = -2000;
}
}
}
}, 0, 15);
}
}
| 852 | 0.523474 | 0.484742 | 49 | 16.387754 | 12.764454 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.979592 | false | false | 4 |
e0b24de847caf1fc73f84ec49f44dd2a1e868281 | 13,606,456,455,681 | cb0acaee2fb15eb4d7ebcfe1a164c255b12dda08 | /Tickets/src/Main.java | 25cd03a9ca5ab101f3ea25ef37c703e8a871feab | []
| no_license | davidjunyent/java8 | https://github.com/davidjunyent/java8 | 251ffa24ce6b14c674583c618212763651dfdd3d | 527c5d8149e627aa70a39416acb37d7549cadf62 | refs/heads/master | 2020-03-31T00:50:11.525000 | 2018-11-24T11:45:51 | 2018-11-24T11:45:51 | 151,756,185 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.ArrayList;
import java.util.List;
import tickets.Ticket;
import tickets.TicketService;
import tickets.TicketStatus;
import tickets.dependencyinjection.DIProvider;
public class Main {
public static void main(String[] args) {
List<Ticket> tickets = new ArrayList<>();
TicketService ticketService = DIProvider.getDIProvider().geTicketService();
int totalWeight = 0;
int totalClosed = 0;
int totalOpened = 0;
System.out.println("------------------------");
while (ticketService.hasMoreTickets()) {
Ticket ticket=ticketService.getNextTicket();
TicketStatus ticketStatus = ticket.getStatus();
System.out.println("Ticket status: " + ticketStatus);
totalWeight = totalWeight + ticketStatus.getWeight();
switch (ticketStatus) {
case OPEN:
totalOpened++;
break;
case CLOSED:
totalClosed++;
break;
default:
break;
}
tickets.add(ticket);
}
System.out.println("------------------------");
System.out.println("Num tickets " + tickets.size());
tickets.removeIf(ticket ->ticket.getStatus().equals(TicketStatus.CLOSED));
System.out.println("Non closed Tickets " + tickets.size());
System.out.println("Total weight " + totalWeight);
System.out.println("Opened Tickets " + totalOpened);
System.out.println("Closed Tickets " + totalClosed);
}
}
| UTF-8 | Java | 1,412 | java | Main.java | Java | []
| null | []
| import java.util.ArrayList;
import java.util.List;
import tickets.Ticket;
import tickets.TicketService;
import tickets.TicketStatus;
import tickets.dependencyinjection.DIProvider;
public class Main {
public static void main(String[] args) {
List<Ticket> tickets = new ArrayList<>();
TicketService ticketService = DIProvider.getDIProvider().geTicketService();
int totalWeight = 0;
int totalClosed = 0;
int totalOpened = 0;
System.out.println("------------------------");
while (ticketService.hasMoreTickets()) {
Ticket ticket=ticketService.getNextTicket();
TicketStatus ticketStatus = ticket.getStatus();
System.out.println("Ticket status: " + ticketStatus);
totalWeight = totalWeight + ticketStatus.getWeight();
switch (ticketStatus) {
case OPEN:
totalOpened++;
break;
case CLOSED:
totalClosed++;
break;
default:
break;
}
tickets.add(ticket);
}
System.out.println("------------------------");
System.out.println("Num tickets " + tickets.size());
tickets.removeIf(ticket ->ticket.getStatus().equals(TicketStatus.CLOSED));
System.out.println("Non closed Tickets " + tickets.size());
System.out.println("Total weight " + totalWeight);
System.out.println("Opened Tickets " + totalOpened);
System.out.println("Closed Tickets " + totalClosed);
}
}
| 1,412 | 0.647309 | 0.645184 | 55 | 23.672728 | 22.243328 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.327273 | false | false | 4 |
06b2325e4999925b6394294a77b2808e1ebc9737 | 19,052,474,964,229 | af5b8b86b177811c22183d2ce48e297da43b762b | /src/main/java/geek/livingstone/problems/dp/BinomialCoefficient.java | 986f8454a28a784741d87c4f617a8a2b9547fcf0 | []
| no_license | vaishakhbn/datastructures | https://github.com/vaishakhbn/datastructures | 3b0ae11a7ae88e2be91395f218074166495950a7 | e615c1811e22adff49970befa4012e0ee74526af | refs/heads/master | 2021-01-15T12:20:08.398000 | 2015-10-07T03:19:04 | 2015-10-07T03:19:04 | 43,627,294 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package geek.livingstone.problems.dp;
/**
* Full problem at http://www.geeksforgeeks.org/dynamic-programming-set-9-binomial-coefficient/
*
* @author emmanuel
*
*/
public class BinomialCoefficient {
// C(n, k) = C(n-1, k-1) + C(n-1, k)
public static void binomialCoefficient(int n, int k) {
int[][] b = new int[n + 1][k + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= Math.min(k, i); j++) {
if (j == 0 || j == i)
b[i][j] = 1;
else
b[i][j] = b[i - 1][j - 1] + b[i - 1][j];
}
}
System.out.println(b[n][k]);
}
public static void main(String[] args) {
binomialCoefficient(4, 2);
binomialCoefficient(5, 2);
}
}
| UTF-8 | Java | 706 | java | BinomialCoefficient.java | Java | [
{
"context": "ramming-set-9-binomial-coefficient/\n * \n * @author emmanuel\n * \n */\npublic class BinomialCoefficient {\n // C",
"end": 162,
"score": 0.8192154765129089,
"start": 154,
"tag": "USERNAME",
"value": "emmanuel"
}
]
| null | []
| package geek.livingstone.problems.dp;
/**
* Full problem at http://www.geeksforgeeks.org/dynamic-programming-set-9-binomial-coefficient/
*
* @author emmanuel
*
*/
public class BinomialCoefficient {
// C(n, k) = C(n-1, k-1) + C(n-1, k)
public static void binomialCoefficient(int n, int k) {
int[][] b = new int[n + 1][k + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= Math.min(k, i); j++) {
if (j == 0 || j == i)
b[i][j] = 1;
else
b[i][j] = b[i - 1][j - 1] + b[i - 1][j];
}
}
System.out.println(b[n][k]);
}
public static void main(String[] args) {
binomialCoefficient(4, 2);
binomialCoefficient(5, 2);
}
}
| 706 | 0.522663 | 0.498584 | 28 | 24.214285 | 22.168764 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 4 |
764ff7a5e8b97a51be5aaa46fe6e34a952b83789 | 32,409,823,279,861 | 856286d40e0cf77f68e8ea67c27be16325cf193c | /src/br/com/finnances/test/TestBankTransition.java | c12fb6211d88749c375f3f90b55784122a9733c7 | []
| no_license | victoralc/databases | https://github.com/victoralc/databases | 54463848f5dcbb51c87f0f6ec2c2b07f6e8b44fe | 239c83dc0d1a784c3fbfcdb6ae93a1bce232f003 | refs/heads/master | 2018-04-05T23:51:37.007000 | 2017-08-02T01:18:35 | 2017-08-02T01:18:35 | 89,298,813 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.finnances.test;
import java.math.BigDecimal;
import java.time.LocalDate;
import javax.persistence.EntityManager;
import br.com.finnances.model.Account;
import br.com.finnances.model.BankTransition;
import br.com.finnances.model.TransitionType;
import br.com.finnances.util.JPAUtil;
public class TestBankTransition {
public static void main(String[] args) {
Account account = new Account();
account.setBank("Santander");
account.setBankBranch("544875");
account.setNumber("226549");
account.setOwner("Victor Alcantara");
BankTransition transition = new BankTransition();
transition.setDescription("Money Deposit");
transition.setDate(LocalDate.now());
transition.setType(TransitionType.OUT);
transition.setValue(new BigDecimal("200"));
transition.setAccount(account);
EntityManager em = new JPAUtil().getEntityManager();
em.getTransaction().begin();
em.persist(account);
em.persist(transition);
em.getTransaction().commit();
em.close();
}
}
| UTF-8 | Java | 1,002 | java | TestBankTransition.java | Java | [
{
"context": "\taccount.setNumber(\"226549\");\n\t\taccount.setOwner(\"Victor Alcantara\");\n\t\t\n\t\tBankTransition transition = new BankTrans",
"end": 547,
"score": 0.9998868703842163,
"start": 531,
"tag": "NAME",
"value": "Victor Alcantara"
}
]
| null | []
| package br.com.finnances.test;
import java.math.BigDecimal;
import java.time.LocalDate;
import javax.persistence.EntityManager;
import br.com.finnances.model.Account;
import br.com.finnances.model.BankTransition;
import br.com.finnances.model.TransitionType;
import br.com.finnances.util.JPAUtil;
public class TestBankTransition {
public static void main(String[] args) {
Account account = new Account();
account.setBank("Santander");
account.setBankBranch("544875");
account.setNumber("226549");
account.setOwner("<NAME>");
BankTransition transition = new BankTransition();
transition.setDescription("Money Deposit");
transition.setDate(LocalDate.now());
transition.setType(TransitionType.OUT);
transition.setValue(new BigDecimal("200"));
transition.setAccount(account);
EntityManager em = new JPAUtil().getEntityManager();
em.getTransaction().begin();
em.persist(account);
em.persist(transition);
em.getTransaction().commit();
em.close();
}
}
| 992 | 0.757485 | 0.742515 | 38 | 25.368422 | 17.573036 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.657895 | false | false | 4 |
14465763c603d50bb99947fd27c63dde7f5bea5a | 30,296,699,306,359 | 9a70020d409332b7db0e2e5e087f500a0e58217c | /BOJ/10162/Main.java | 72c39e2dd66b247fad4557b2acad6ab4e4adc72a | [
"MIT"
]
| permissive | ISKU/Algorithm | https://github.com/ISKU/Algorithm | daf5e9d5397eaf7dad2d6f7fb18c1c94d8f0246d | a51449e4757e07a9dcd1ff05f2ef4b53e25a9d2a | refs/heads/master | 2021-06-22T09:42:45.033000 | 2021-02-01T12:45:28 | 2021-02-01T12:45:28 | 62,798,871 | 55 | 12 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Author: Minho Kim (ISKU)
* Date: January 18, 2018
* E-mail: minho1a@hanmail.net
*
* https://github.com/ISKU/Algorithm
* https://www.acmicpc.net/problem/10162
*/
import java.util.*;
public class Main {
public static void main(String... args) {
int T = new Scanner(System.in).nextInt();
int[] button = new int[] { 300, 60, 10 };
int[] ans = new int[3];
for (int i = 0; i < 3; i++) {
ans[i] = T / button[i];
T %= button[i];
}
if (T > 0)
System.out.print(-1);
else
System.out.printf("%d %d %d", ans[0], ans[1], ans[2]);
}
} | UTF-8 | Java | 563 | java | Main.java | Java | [
{
"context": "/*\n * Author: Minho Kim (ISKU)\n * Date: January 18, 2018\n * E-mail: minho",
"end": 23,
"score": 0.9998248219490051,
"start": 14,
"tag": "NAME",
"value": "Minho Kim"
},
{
"context": "ho Kim (ISKU)\n * Date: January 18, 2018\n * E-mail: minho1a@hanmail.net\n *\n * https://github.com/ISKU/Algorithm\n * https:",
"end": 87,
"score": 0.999932050704956,
"start": 68,
"tag": "EMAIL",
"value": "minho1a@hanmail.net"
}
]
| null | []
| /*
* Author: <NAME> (ISKU)
* Date: January 18, 2018
* E-mail: <EMAIL>
*
* https://github.com/ISKU/Algorithm
* https://www.acmicpc.net/problem/10162
*/
import java.util.*;
public class Main {
public static void main(String... args) {
int T = new Scanner(System.in).nextInt();
int[] button = new int[] { 300, 60, 10 };
int[] ans = new int[3];
for (int i = 0; i < 3; i++) {
ans[i] = T / button[i];
T %= button[i];
}
if (T > 0)
System.out.print(-1);
else
System.out.printf("%d %d %d", ans[0], ans[1], ans[2]);
}
} | 548 | 0.57016 | 0.522202 | 28 | 19.142857 | 16.578201 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.571429 | false | false | 4 |
de5fb78799e52da2ff83eb4ff4a4c1dd53bc6c80 | 32,521,492,390,175 | 5ec00ecdf16340279c186c139b2f64ca4bed2295 | /main/java/edu/uci/ics/jiefengw/service/billing/models/ResponseModel_discount_apply.java | 02cfcd6b3a8cd54207763c7aef59b70e79b4d061 | []
| no_license | jeffwu0724/be4-movie | https://github.com/jeffwu0724/be4-movie | d44a869f05b87651367aa1bb6c03c3ee9138196d | e1646b4f6937e2a21611436a6e6a3f56e988c184 | refs/heads/master | 2023-09-03T00:16:21.301000 | 2021-11-15T01:08:38 | 2021-11-15T01:08:38 | 428,080,426 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.uci.ics.jiefengw.service.billing.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
public class ResponseModel_discount_apply extends ResponseModel {
@JsonProperty(value = "items")
private ArrayList<itemModel> items;
public ResponseModel_discount_apply(int resultCode, String message,ArrayList<itemModel> items) {
super(resultCode, message);
this.items = items;
}
public ResponseModel_discount_apply() { }
@JsonProperty("items")
public ArrayList<itemModel> getItems() {
return items;
}
@JsonProperty("items")
public void setItems(ArrayList<itemModel> items) {
this.items = items;
}
}
| UTF-8 | Java | 715 | java | ResponseModel_discount_apply.java | Java | []
| null | []
| package edu.uci.ics.jiefengw.service.billing.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
public class ResponseModel_discount_apply extends ResponseModel {
@JsonProperty(value = "items")
private ArrayList<itemModel> items;
public ResponseModel_discount_apply(int resultCode, String message,ArrayList<itemModel> items) {
super(resultCode, message);
this.items = items;
}
public ResponseModel_discount_apply() { }
@JsonProperty("items")
public ArrayList<itemModel> getItems() {
return items;
}
@JsonProperty("items")
public void setItems(ArrayList<itemModel> items) {
this.items = items;
}
}
| 715 | 0.704895 | 0.704895 | 24 | 28.791666 | 24.730175 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.458333 | false | false | 4 |
11b67fdbff1bb56735731ad192aacbc34f842b53 | 18,949,395,733,670 | 3353ee6bf5304d4fee9511af2691aa1830b4f663 | /src/silk/SilkV3Helper.java | 000ed9dc4d7390e870342559b793ee3b2e645aa2 | []
| no_license | FlyRocBoy/untitled | https://github.com/FlyRocBoy/untitled | b0a6e20974f6472719398363800040cd6af1a4b4 | 0d0ae8b26b7dbdcb8a20477b0b697470448c917e | refs/heads/master | 2021-07-14T17:39:12.345000 | 2017-10-20T07:54:37 | 2017-10-20T07:54:37 | 104,035,796 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package silk;
import java.io.*;
/**
* Created by gaopeng on 2017/10/20.
*/
public class SilkV3Helper {
//C:\Users\gaopeng\Downloads\silk2mp3\silk_v3_decoder
//C:\Users\gaopeng\Downloads\silk2mp3\silk_v3_encoder
private static String SILK_V3_DECODER_EXE="cmd /c echo y | C:\\Users\\gaopeng\\Downloads\\silk2mp3\\silk_v3_decoder";
private static String SILK_V3_ENCODER_EXE="cmd /c echo y | C:\\Users\\gaopeng\\Downloads\\silk2mp3\\silk_v3_encoder";
public static String getSilkV3DecoderExe() {
return SILK_V3_DECODER_EXE;
}
public static void setSilkV3DecoderExe(String silkV3DecoderExe) {
SILK_V3_DECODER_EXE = silkV3DecoderExe;
}
public static String getSilkV3EncoderExe() {
return SILK_V3_ENCODER_EXE;
}
public static void setSilkV3EncoderExe(String silkV3EncoderExe) {
SILK_V3_ENCODER_EXE = silkV3EncoderExe;
}
public static void silk2pcm(String silkPath,String pcmPath){
Runtime run= Runtime.getRuntime();
StringBuffer commond=new StringBuffer();
commond.append(getSilkV3DecoderExe());
commond.append(" "+silkPath);
commond.append(" "+pcmPath);
Process process=null;
try {
System.out.println(commond.toString());
process=run.exec(commond.toString());
outErrorStream(process.getErrorStream());
outInputStream(process.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}finally {
process.destroy();
}
}
private static void outInputStream(InputStream inputStream){
String line = null;
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader
(new InputStreamReader(inputStream));
try {
line=bufferedReader.readLine();
while (line != null) {
sb.append(line + "\n");
System.out.println(line);
line=bufferedReader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void outErrorStream(InputStream inputStream){
Thread t=new Thread(new InputStreamRunnable(inputStream,"errorStream"));
t.start();
}
}
/**读取InputStream的线程*/
class InputStreamRunnable implements Runnable
{
BufferedReader bReader=null;
String type=null;
public InputStreamRunnable(InputStream is, String _type)
{
try
{
bReader=new BufferedReader(new InputStreamReader(new BufferedInputStream(is),"UTF-8"));
type=_type;
}
catch(Exception ex)
{
}
}
public void run()
{
String line;
int lineNum=0;
try
{
line=bReader.readLine();
while(line!=null)
{
lineNum++;
System.out.println(line);
line=bReader.readLine();
}
bReader.close();
}
catch(Exception ex)
{
}
}
}
| UTF-8 | Java | 3,125 | java | SilkV3Helper.java | Java | [
{
"context": "ackage silk;\n\nimport java.io.*;\n\n/**\n * Created by gaopeng on 2017/10/20.\n */\npublic class SilkV3Helper {\n ",
"end": 59,
"score": 0.9996111392974854,
"start": 52,
"tag": "USERNAME",
"value": "gaopeng"
}
]
| null | []
| package silk;
import java.io.*;
/**
* Created by gaopeng on 2017/10/20.
*/
public class SilkV3Helper {
//C:\Users\gaopeng\Downloads\silk2mp3\silk_v3_decoder
//C:\Users\gaopeng\Downloads\silk2mp3\silk_v3_encoder
private static String SILK_V3_DECODER_EXE="cmd /c echo y | C:\\Users\\gaopeng\\Downloads\\silk2mp3\\silk_v3_decoder";
private static String SILK_V3_ENCODER_EXE="cmd /c echo y | C:\\Users\\gaopeng\\Downloads\\silk2mp3\\silk_v3_encoder";
public static String getSilkV3DecoderExe() {
return SILK_V3_DECODER_EXE;
}
public static void setSilkV3DecoderExe(String silkV3DecoderExe) {
SILK_V3_DECODER_EXE = silkV3DecoderExe;
}
public static String getSilkV3EncoderExe() {
return SILK_V3_ENCODER_EXE;
}
public static void setSilkV3EncoderExe(String silkV3EncoderExe) {
SILK_V3_ENCODER_EXE = silkV3EncoderExe;
}
public static void silk2pcm(String silkPath,String pcmPath){
Runtime run= Runtime.getRuntime();
StringBuffer commond=new StringBuffer();
commond.append(getSilkV3DecoderExe());
commond.append(" "+silkPath);
commond.append(" "+pcmPath);
Process process=null;
try {
System.out.println(commond.toString());
process=run.exec(commond.toString());
outErrorStream(process.getErrorStream());
outInputStream(process.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}finally {
process.destroy();
}
}
private static void outInputStream(InputStream inputStream){
String line = null;
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader
(new InputStreamReader(inputStream));
try {
line=bufferedReader.readLine();
while (line != null) {
sb.append(line + "\n");
System.out.println(line);
line=bufferedReader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void outErrorStream(InputStream inputStream){
Thread t=new Thread(new InputStreamRunnable(inputStream,"errorStream"));
t.start();
}
}
/**读取InputStream的线程*/
class InputStreamRunnable implements Runnable
{
BufferedReader bReader=null;
String type=null;
public InputStreamRunnable(InputStream is, String _type)
{
try
{
bReader=new BufferedReader(new InputStreamReader(new BufferedInputStream(is),"UTF-8"));
type=_type;
}
catch(Exception ex)
{
}
}
public void run()
{
String line;
int lineNum=0;
try
{
line=bReader.readLine();
while(line!=null)
{
lineNum++;
System.out.println(line);
line=bReader.readLine();
}
bReader.close();
}
catch(Exception ex)
{
}
}
}
| 3,125 | 0.588122 | 0.575602 | 106 | 28.367924 | 24.947615 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.443396 | false | false | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.