hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
922fc6a4534f2d2a76761644fe9e53e122bb8bb5
1,535
java
Java
patcher/src/lib/CertKeyStoreManager.java
bruwyvn/yggdrasil-backup-authserver
bebab8e9578afc172feecbc3c3a860f625d8eac0
[ "MIT" ]
34
2018-07-14T14:15:42.000Z
2022-02-11T16:09:11.000Z
patcher/src/lib/CertKeyStoreManager.java
bruwyvn/yggdrasil-backup-authserver
bebab8e9578afc172feecbc3c3a860f625d8eac0
[ "MIT" ]
12
2018-07-03T13:46:14.000Z
2021-12-29T18:06:38.000Z
patcher/src/lib/CertKeyStoreManager.java
robloxtester2/Mjolnir-Authentication-Server
12703df0248fd87479b92623152c3ebb6c1ab47f
[ "MIT" ]
20
2018-06-26T03:48:28.000Z
2022-03-23T13:21:04.000Z
30.7
120
0.656678
995,249
package lib; import java.io.*; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; public class CertKeyStoreManager { private final char[] PASSPHRASE = "changeit".toCharArray(); private KeyStore keyStore; public CertKeyStoreManager() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream in = new FileInputStream(getCacertsFile()); keyStore.load(in, PASSPHRASE); in.close(); } public KeyStore getKeyStore() { return keyStore; } public void writeKeyStore() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { OutputStream out = new FileOutputStream(getSecurityPath() + File.separatorChar + "jssecacerts"); keyStore.store(out, PASSPHRASE); out.close(); } private File getCacertsFile() { File file = new File("jssecacerts"); if (!file.isFile()) { File dir = new File(getSecurityPath()); file = new File(dir, "jssecacerts"); if (!file.isFile()) { file = new File(dir, "cacerts"); } } return file; } private String getSecurityPath() { return System.getProperty("java.home") + File.separatorChar + "lib" + File.separatorChar + "security"; } }
922fc73b73ce04f4af69ce2ffcc8015d2527814a
450
java
Java
MLN-Android/mlnservics/src/main/java/com/immomo/mls/adapter/ILoadLibAdapter.java
jinjinhuanglucky/MLN
7b6a6dd3d722affa160927c88549700bd848b161
[ "MIT" ]
1,615
2019-09-19T09:36:39.000Z
2022-03-31T13:05:47.000Z
MLN-Android/mlnservics/src/main/java/com/immomo/mls/adapter/ILoadLibAdapter.java
zhanghesheng/MLN
ecbcc26a6c0b54c885f86c5dfdf9cc3314b92220
[ "MIT" ]
193
2019-09-19T09:10:03.000Z
2022-02-23T02:48:02.000Z
MLN-Android/mlnservics/src/main/java/com/immomo/mls/adapter/ILoadLibAdapter.java
sun8801/MLN
cbc873e2a32109aa5014fb5b04845425e73392d1
[ "MIT" ]
203
2019-09-19T09:39:22.000Z
2022-03-27T12:18:44.000Z
23.684211
121
0.695556
995,250
/** * Created by MomoLuaNative. * Copyright (c) 2019, Momo Group. All rights reserved. * * This source code is licensed under the MIT. * For the full copyright and license information,please view the LICENSE file in the root directory of this source tree. */ package com.immomo.mls.adapter; /** * Created by Xiong.Fangyu on 2019-12-23 */ public interface ILoadLibAdapter { /** * 成功返回true */ boolean load(String libName); }
922fc7d0c09c6fa41c8d45f168bfee0f5dd62faf
452
java
Java
eureka-sever/src/main/java/com/lovnx/EurekaServer.java
lubingo/mymicro-service
98ace7bae15bb40cf2e1c58e99572b068164472a
[ "Apache-2.0" ]
2
2018-12-14T02:43:00.000Z
2018-12-14T06:12:03.000Z
eureka-sever/src/main/java/com/lovnx/EurekaServer.java
lubingo/mymicro-service
98ace7bae15bb40cf2e1c58e99572b068164472a
[ "Apache-2.0" ]
null
null
null
eureka-sever/src/main/java/com/lovnx/EurekaServer.java
lubingo/mymicro-service
98ace7bae15bb40cf2e1c58e99572b068164472a
[ "Apache-2.0" ]
null
null
null
26.588235
74
0.840708
995,251
package com.lovnx; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @EnableEurekaServer @SpringBootApplication public class EurekaServer { public static void main(String[] args) { SpringApplication.run(EurekaServer.class,args); } }
922fc9a47eb57caa56053d51c6e97339e08a2e8d
5,723
java
Java
src/main/java/com/scb/raar/MainArbol.java
Roddyar/prueba-desarrollo
23326a80b51210942a908f3bbcff8e2617de166f
[ "MIT" ]
null
null
null
src/main/java/com/scb/raar/MainArbol.java
Roddyar/prueba-desarrollo
23326a80b51210942a908f3bbcff8e2617de166f
[ "MIT" ]
null
null
null
src/main/java/com/scb/raar/MainArbol.java
Roddyar/prueba-desarrollo
23326a80b51210942a908f3bbcff8e2617de166f
[ "MIT" ]
null
null
null
44.023077
136
0.503932
995,252
package com.scb.raar; import com.scb.raar.arbol.archivos.OperacionesArchivos; import com.scb.raar.arbol.entidades.Persona; import com.scb.raar.arbol.exception.ArbolException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; /** * @author raruiz */ public class MainArbol { /** * @param args the command line arguments * @throws IOException */ public static void main(String[] args) throws IOException { int validar = 0, opcion; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { OperacionesArchivos<String, Persona> archivos = new OperacionesArchivos("src/db/", "personas", 1000); while (validar == 0) { printMenu(); String identificacion, nombres, apellidos; opcion = INT(br.readLine()); switch (opcion) { case 1: System.out.println("Ingrese el número de cédula de la persona: "); identificacion = br.readLine(); System.out.println("Ingrese los nombres"); nombres = br.readLine(); System.out.println("Ingrese los apellidos"); apellidos = br.readLine(); int val = archivos.agregar(identificacion, new Persona(identificacion, nombres, apellidos)); System.out.println("Persona agregada en la posición: " + val); break; case 2: System.out.println("Ingrese el número de cédula de la persona a modificar "); String cedulaModificar = br.readLine(); if (archivos.exists(cedulaModificar)) { System.out.println("Ingrese el nuevo número de cédula de la persona"); identificacion = br.readLine(); System.out.println("Ingrese los nuevos nombres"); nombres = br.readLine(); System.out.println("Ingrese los nuevos apellidos"); apellidos = br.readLine(); if (archivos.modificar(cedulaModificar, identificacion, new Persona(identificacion, nombres, apellidos))) System.out.println("Persona modificada!"); else System.out.println("No se pudo modificar la persona, favor comunicarse con el departamento de soporte"); } else { System.out.println("No existe persona con la cédula: " + cedulaModificar); } break; case 3: System.out.println("Ingrese el número de cédula de la persona a consultar"); identificacion = br.readLine(); if (archivos.exists(identificacion)) { Persona leerPersona = archivos.get(identificacion); System.out.println("Persona: " + leerPersona.toString()); } else { System.out.println("No existe persona con la cédula: " + identificacion); } break; case 4: List<Persona> lista = archivos.listar(); System.out.println("\nLista"); if (lista == null || lista.isEmpty()) System.out.println("No hay personas guardadas"); else lista.forEach((persona) -> System.out.println(persona.toString())); break; case 5: System.out.println("Ingrese el número de cédula de la persona a eliminar"); identificacion = br.readLine(); if (archivos.eliminar(identificacion)) System.out.println("Persona eliminada!"); else System.out.println("No existe persona con la cédula: " + identificacion); break; case 6: validar = 1; break; default: System.out.println("Sólo son permitidas las opciones del menú"); } } } catch (ArbolException ex) { System.out.println("Ha ocurrido un error: " + ex.getMessage()); } } public static int INT(String numero) { if (isNumeric(numero)) return Integer.parseInt(numero); else return 10; } public static boolean isNumeric(String strNum) { if (strNum == null) { return false; } try { double d = Double.parseDouble(strNum); } catch (NumberFormatException nfe) { return false; } return true; } public static void printMenu() { System.out.println("\nPRUEBA RODDY ARANA RUIZ"); System.out.println("USO ARBOL B+ CON ARCHIVOS DE TEXTO EN DISCO"); System.out.println("1.- Registrar una persona"); System.out.println("2.- Modificar una persona"); System.out.println("3.- Consultar persona por cédula"); System.out.println("4.- Listar todas las personas"); System.out.println("5.- Eliminar una persona"); System.out.println("6.- Salir"); } }
922fc9c30bde0e2aa9ec3dda32c5b678ae612c3b
3,918
java
Java
choerodon-starter-websocket/src/main/java/io/choerodon/websocket/helper/BrokerHelper.java
donbing007/choerodon-starters
ea4f91315c14e7e098afa5b7a29a0cd5a8a3abda
[ "Apache-2.0" ]
null
null
null
choerodon-starter-websocket/src/main/java/io/choerodon/websocket/helper/BrokerHelper.java
donbing007/choerodon-starters
ea4f91315c14e7e098afa5b7a29a0cd5a8a3abda
[ "Apache-2.0" ]
null
null
null
choerodon-starter-websocket/src/main/java/io/choerodon/websocket/helper/BrokerHelper.java
donbing007/choerodon-starters
ea4f91315c14e7e098afa5b7a29a0cd5a8a3abda
[ "Apache-2.0" ]
null
null
null
38.411765
144
0.68734
995,253
package io.choerodon.websocket.helper; import io.choerodon.websocket.exception.GetSelfSubChannelsFailedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Collections; import java.util.Optional; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @Component public class BrokerHelper { private static final Logger LOGGER = LoggerFactory.getLogger(BrokerHelper.class); private static final String REGISTER_PREFIX = "choerodon:msg:register:"; private Environment environment; private String selfSubChannel; private StringRedisTemplate redisTemplate; private String registerKey; @Value("${spring.application.name}") private String application; @Value("${choerodon.ws.heartBeatIntervalMs:10000}") private Long heartBeatIntervalMs; private ScheduledExecutorService scheduledExecutorService; public BrokerHelper(Environment environment, StringRedisTemplate redisTemplate) { this.scheduledExecutorService = Executors.newScheduledThreadPool(1); this.environment = environment; this.redisTemplate = redisTemplate; } @PostConstruct public void start() { this.registerKey = REGISTER_PREFIX + application; registerByBrokerName(); scheduledExecutorService.scheduleWithFixedDelay(() -> { try { String thisInstanceRegisterKey = REGISTER_PREFIX + brokerName(); redisTemplate.opsForSet().add(registerKey, brokerName()); redisTemplate.opsForValue().set(thisInstanceRegisterKey, Long.toString(System.currentTimeMillis())); Optional.ofNullable(redisTemplate.opsForSet().members(registerKey)).orElse(Collections.emptySet()).forEach(t -> { if (t.equals(brokerName())) { return; } String instanceRegisterKey = REGISTER_PREFIX + t; long lastUpdateTime = Long.parseLong(Optional.ofNullable(redisTemplate.opsForValue().get(instanceRegisterKey)).orElse("0")); if (System.currentTimeMillis() - lastUpdateTime > 2 * heartBeatIntervalMs) { removeDeathBroker(t); } }); } catch (Exception e) { LOGGER.error("error.redisRegister.heartBeat", e); } }, heartBeatIntervalMs, heartBeatIntervalMs, TimeUnit.MILLISECONDS); } public String brokerName() { try { if (this.selfSubChannel == null) { selfSubChannel = application + ":" + InetAddress.getLocalHost().getHostAddress() + ":" + environment.getProperty("server.port"); } return this.selfSubChannel; } catch (UnknownHostException e) { throw new GetSelfSubChannelsFailedException(e); } } public Set<String> getSurvivalBrokers() { return redisTemplate.opsForSet().members(registerKey); } private void registerByBrokerName() { redisTemplate.opsForSet().add(registerKey, brokerName()); String thisInstanceRegisterKey = REGISTER_PREFIX + brokerName(); redisTemplate.opsForValue().set(thisInstanceRegisterKey, System.currentTimeMillis() + ""); } private void removeDeathBroker(String channel) { redisTemplate.opsForSet().remove(registerKey, channel); redisTemplate.delete(channel); redisTemplate.delete(REGISTER_PREFIX + channel); } }
922fcaa56db67d35b8298c785f6089281f8b15de
2,858
java
Java
dev-java/dev-java-algorithm/src/main/java/com/sciatta/dev/java/algorithm/linear/queue/impl/BlockedArrayQueue.java
yxyuhz/dev
8cc809a20c8dfbe4e7bf313fdde2b0bdce7d4421
[ "Apache-2.0" ]
1
2021-12-15T10:16:51.000Z
2021-12-15T10:16:51.000Z
dev-java/dev-java-algorithm/src/main/java/com/sciatta/dev/java/algorithm/linear/queue/impl/BlockedArrayQueue.java
yxyuhz/dev
8cc809a20c8dfbe4e7bf313fdde2b0bdce7d4421
[ "Apache-2.0" ]
null
null
null
dev-java/dev-java-algorithm/src/main/java/com/sciatta/dev/java/algorithm/linear/queue/impl/BlockedArrayQueue.java
yxyuhz/dev
8cc809a20c8dfbe4e7bf313fdde2b0bdce7d4421
[ "Apache-2.0" ]
null
null
null
32.850575
131
0.519594
995,254
package com.sciatta.dev.java.algorithm.linear.queue.impl; /** * Created by yangxiaoyu on 2021/2/7<br> * All Rights Reserved(C) 2017 - 2021 SCIATTA<br><p/> * BlockedArrayQueue */ public class BlockedArrayQueue<T> extends CyclicArrayQueue<T> { private final Object lock; private final int retry; public BlockedArrayQueue(int capacity) { super(capacity); lock = new Object(); retry = 3; } @Override public boolean enqueue(T data) { int i = 0; synchronized (lock) { while (!super.enqueue(data)) { // 满 -> 当前线程阻塞 try { lock.wait(1000); // 阻塞&释放锁;等待1s后如果没有获得通知,则会重新获得锁 if (i++ < retry) { System.out.println("enqueue retry time: " + i + " current data is: " + data); } else { throw new BlockedArrayQueueException("enqueue retry time: " + i + " current data is: " + data); } } catch (InterruptedException e) { throw new BlockedArrayQueueException("the queue is full, not allow to enqueue"); } } lock.notify(); } return true; } @Override public T dequeue() { T ret; int i = 0; synchronized (lock) { while ((ret = super.dequeue()) == null) { // 空 -> 当前线程阻塞 try { lock.wait(1000); if (i++ < retry) { System.out.println("dequeue retry time: " + i + " current data is: " + ret); } else { throw new BlockedArrayQueueException("dequeue retry time: " + i + " current data is: " + ret); } } catch (InterruptedException e) { throw new BlockedArrayQueueException("the queue is empty, not allow to dequeue"); } } lock.notify(); } return ret; } static class BlockedArrayQueueException extends RuntimeException { private static final long serialVersionUID = -2611127523125605679L; public BlockedArrayQueueException() { } public BlockedArrayQueueException(String message) { super(message); } public BlockedArrayQueueException(String message, Throwable cause) { super(message, cause); } public BlockedArrayQueueException(Throwable cause) { super(cause); } public BlockedArrayQueueException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } } }
922fcae23dafa7616fdb06fc8cba9dd7e866a4cb
373
java
Java
src/main/java/dao/PaymentDao.java
PhilipOdhiambo/rent-management-app
a1496a64d1ed5a6e9d6f9081c77a5f0946c95650
[ "MIT" ]
null
null
null
src/main/java/dao/PaymentDao.java
PhilipOdhiambo/rent-management-app
a1496a64d1ed5a6e9d6f9081c77a5f0946c95650
[ "MIT" ]
null
null
null
src/main/java/dao/PaymentDao.java
PhilipOdhiambo/rent-management-app
a1496a64d1ed5a6e9d6f9081c77a5f0946c95650
[ "MIT" ]
null
null
null
16.217391
47
0.670241
995,255
package dao; import models.Payment; import java.util.List; public interface PaymentDao { //create public void add(Payment payment); // read public List<Payment> getAll(); public Payment getById (int id); // update public void update(Payment updatedPayment); //delete public void deleteById(int id); public void deleteAll(); }
922fcb68425c278932f8bbcbdfc43ae43a92e895
749
java
Java
src/main/java/com/kaushik/flightreservation/entities/User.java
kaushikbhadra/Flight_Reservation_Application
945e0bc72904a80ec544361764ec52d63df63e53
[ "MIT" ]
null
null
null
src/main/java/com/kaushik/flightreservation/entities/User.java
kaushikbhadra/Flight_Reservation_Application
945e0bc72904a80ec544361764ec52d63df63e53
[ "MIT" ]
null
null
null
src/main/java/com/kaushik/flightreservation/entities/User.java
kaushikbhadra/Flight_Reservation_Application
945e0bc72904a80ec544361764ec52d63df63e53
[ "MIT" ]
null
null
null
17.418605
47
0.734312
995,256
package com.kaushik.flightreservation.entities; import javax.persistence.Entity; @Entity public class User extends AbstractEntity{ private String firstName; private String lastName; private String email; private String password; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
922fccd814e2f2cac8e5668a44c9f783ec630257
20,557
java
Java
src/main/FileManager.java
gogobody/FileManager
aaf03f05f4e17cae6abd25020210ade75699861a
[ "MIT" ]
2
2020-05-06T07:38:23.000Z
2020-06-03T02:46:16.000Z
src/main/FileManager.java
gogobody/FileManager
aaf03f05f4e17cae6abd25020210ade75699861a
[ "MIT" ]
null
null
null
src/main/FileManager.java
gogobody/FileManager
aaf03f05f4e17cae6abd25020210ade75699861a
[ "MIT" ]
null
null
null
39.456814
141
0.507127
995,257
package main; //import view.FileNode; import component.circleprogressbar.CircleProgressBar; import component.circleprogressbar.Cpu; import config.Constant; import control.FileEncAndDec; import control.FileOperate; import control.ZipUtil; import org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper; import view.*; import javax.swing.*; import javax.swing.filechooser.FileSystemView; import javax.swing.plaf.FontUIResource; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.io.FileNotFoundException; import java.util.*; import java.util.List; import java.util.Timer; import org.hyperic.sigar.CpuInfo; import org.hyperic.sigar.CpuPerc; import org.hyperic.sigar.Mem; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.Swap; public class FileManager { public static String[] FILEPATH = {"文稿", "下载", "桌面", "文稿", "下载"}; public static String RButtonSelect = ""; public static String localPath = ""; private FileOperate operate = new FileOperate(); private static FileTree fileTree = new FileTree(); public JScrollPane scoll; private MouseRightPopup popup = new MouseRightPopup(); private String path1 = ""; //临时目录 private JPanel topPanel; private JButton new_file; private JButton back; private JButton forward; private JTextField input_filed; private JPanel rootPanel; private JPanel panel_right_al; private JPanel panel_right; private JPanel left_top_panel; private JPanel left_down_panel; private JPanel left_panel; private JSplitPane splitpanel; private JButton new_dir; private JLabel file_info; private JLabel enter; private JPanel midpanel; private TreePath mouseInPath; private FileManager(String str) throws Exception { init(str); } public static void main(String[] args) throws Exception { FileSystemView rootview = FileSystemView.getFileSystemView(); File root = rootview.getDefaultDirectory(); //获取初始系统默认 InitGlobalFont(new Font("微软雅黑", Font.PLAIN, 18)); try { org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF(); BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.translucencySmallShadow; org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF(); UIManager.put("RootPane.setupButtonVisible", false); //BeautyEyeLNFHelper.translucencyAtFrameInactive = false; //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.err.println("set skin fail!"); } JFrame frame = new JFrame("文件管理器"); frame.setContentPane(new FileManager(root.getPath()).rootPanel); Toolkit kit = Toolkit.getDefaultToolkit(); //拿到默认工具包 Dimension screen = kit.getScreenSize(); //获取屏幕大小 frame.setPreferredSize(new Dimension(screen.width / 2+400, screen.height / 2+400)); frame.setLocationByPlatform(true); //窗口出现在本机的默认位置 frame.setResizable(false);//不可以改变大小 frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // frame.pack(); frame.setVisible(true); } private void createUIComponents() { // TODO: place custom component creation code here } private void init(String str) throws Exception { panel_right.setPreferredSize(new Dimension(840, 600)); panel_right.setBackground(Color.WHITE); panel_right.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1)); // ImageIcon imageIcon = new ImageIcon("./image/key_return.png"); imageIcon.setImage(imageIcon.getImage().getScaledInstance(68, 68, Image.SCALE_DEFAULT)); enter.setIcon(imageIcon); // midpanel.setPreferredSize(new Dimension(midpanel.getSize().width,40)); //初始化显示右边文件 showFile(str); //初始化 jTree initJtree(); //左边树结构 鼠标 点击事件 mouseControlFilelist(); //右键菜单 mouseRightMenuFunction(); mouseControlFile(); //按钮初始化 BtnListenner(); //circleProgress circleProgress(); } private void initJtree() { //初始化 Jtree File[] root = FileSystemView.getFileSystemView().getRoots();//根目录节点 root[0] FileTreeModel model = new FileTreeModel(new DefaultMutableTreeNode(new FileNode("root", null, null, true)), root[0]); fileTree.setModel(model); fileTree.setCellRenderer(new FileTreeRenderer()); fileTree.expandRow(0); JScrollPane sp = new JScrollPane(fileTree); sp.setBorder(BorderFactory.createEtchedBorder(Color.white, new Color(148, 145, 140))); splitpanel.setDividerLocation(300); //设置面板左边大小 left_down_panel.add(sp); } //显示文件 private void showFile(String path) { panel_right.removeAll(); showpath(path); File f = new File(path); if (f.isDirectory()) { FILEPATH = f.list(); if (FILEPATH == null) { FILEPATH = new String[1]; FILEPATH[0] = ""; } else { List<JPanel> dirlist = new ArrayList<>(); List<JPanel> filelist = new ArrayList<>(); for (String aFILEPATH : FILEPATH) { JPanel panel_item = new JPanel(); ImageIcon icon = new ImageIcon("./image/wenjianjia.png"); ImageIcon icon_file = new ImageIcon("./image/wenjian.png"); JLabel label; File file = new File(path + "/" + aFILEPATH); if (file.isDirectory()) { label = new JLabel(icon); JLabel label1 = new JLabel(aFILEPATH); label1.setPreferredSize(new Dimension(50, 20)); panel_item.setLayout(new BorderLayout()); panel_item.setBackground(null); panel_item.add(label, BorderLayout.NORTH); panel_item.add(label1, BorderLayout.CENTER); label1.setHorizontalAlignment(SwingConstants.CENTER); dirlist.add(panel_item); } else { label = new JLabel(icon_file); JLabel label1 = new JLabel(aFILEPATH); label1.setPreferredSize(new Dimension(50, 20)); panel_item.setLayout(new BorderLayout()); panel_item.setBackground(null); panel_item.add(label, BorderLayout.NORTH); panel_item.add(label1, BorderLayout.CENTER); label1.setHorizontalAlignment(SwingConstants.CENTER); filelist.add(panel_item); } panel_item.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { super.mouseEntered(e); panel_item.setBackground(Color.lightGray); } @Override public void mouseExited(MouseEvent e) { super.mouseExited(e); panel_item.setBackground(null); } }); panel_item.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { //设置左键双击打开文件夹 if (e.getClickCount() == 1) { String length = null; String name = null; String time = null; name = file.getName(); if (file.length() > 1000 * 1000 * 1000){ length = file.length() / 1000000000 + "G "; } else if (file.length() > 1000 * 1000){ length = file.length() / 1000000 + "M "; } else if(file.length() > 1000){ length = file.length() / 1000 + "K "; } else{ length = file.length() + "B "; } time = new Date(file.lastModified()).toLocaleString(); file_info.setText(name+" "+length+" "+time+" "); } if (e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1) { JPanel item = (JPanel) e.getComponent(); JLabel la = (JLabel) item.getComponent(1); String str = la.getText(); showFile(localPath + File.separator + str); } //设置右键显示菜单 if (e.getButton() == MouseEvent.BUTTON3) { panel_item.setBackground(Color.lightGray); JPanel item = (JPanel) e.getComponent(); JLabel la = (JLabel) item.getComponent(1); RButtonSelect = la.getText(); popup.show(e.getComponent(), e.getX(), e.getY()); } } }); } for (JPanel label : dirlist) { panel_right.add(label); panel_right.updateUI(); } for (JPanel label : filelist) { panel_right.add(label); panel_right.updateUI(); } } localPath = path; } panel_right.repaint(); } //左边树结构 鼠标 点击事件 private void mouseControlFilelist() { fileTree.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { TreePath path = fileTree.getPathForLocation(e.getX(), e.getY()); if (SwingUtilities.isLeftMouseButton(e)) { if (path != null) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); FileNode filenode = (FileNode) node.getUserObject(); if (filenode.file.isDirectory()) { path1 = filenode.file.getAbsolutePath(); //更新显示 showFile(path1); } } } if (SwingUtilities.isRightMouseButton(e)) { if (path != null) { fileTree.flush(e); } } } } ); } //鼠标右键 private void mouseRightMenuFunction() { ActionListener itemAction = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO 自动生成的方法存根 String temp = e.getActionCommand(); if (temp.equals("打开")) { if (!RButtonSelect.equals("")) { showFile(localPath + File.separator + RButtonSelect); RButtonSelect = ""; showFile(localPath); panel_right.updateUI(); } else { JOptionPane.showMessageDialog(null, "没有文件或文件夹被选中", "提示", JOptionPane.WARNING_MESSAGE); } } if (temp.equals("删除")) { try { if (!RButtonSelect.equals("")) { operate.deleteFile(localPath + File.separator + RButtonSelect); RButtonSelect = ""; showFile(localPath); panel_right.updateUI(); } else { JOptionPane.showMessageDialog(null, "没有文件或文件夹被选中", "提示", JOptionPane.WARNING_MESSAGE); } } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } if (temp.equals("复制")) { Constant.COPYPARTH = localPath + File.separator + RButtonSelect; } if (temp.equals("粘贴")) { String fileName = operate.getFilenameFromPath(Constant.COPYPARTH); operate.copy(Constant.COPYPARTH, localPath + File.separator + operate.getFilenameFromPath(Constant.COPYPARTH)); showFile(localPath); panel_right.updateUI(); } if (temp.equals("压缩")) { String inputValue=(String) JOptionPane.showInputDialog("请输入压缩后的文件名"); ZipUtil.zip(localPath + File.separator + RButtonSelect); showFile(localPath); panel_right.updateUI(); } if (temp.equals("解压")) { ZipUtil.unzip(localPath + File.separator + RButtonSelect); showFile(localPath); panel_right.updateUI(); } if (temp.equals("加密")) { try { FileEncAndDec.EncFile(localPath + File.separator + RButtonSelect, localPath + File.separator + "加密" + RButtonSelect); showFile(localPath); panel_right.updateUI(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } if (temp.equals("解密")) { try { FileEncAndDec.DecFile(localPath + File.separator + RButtonSelect, localPath + File.separator + "解密" + RButtonSelect); showFile(localPath); panel_right.updateUI(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } if (temp.equals("刷新")) { showFile(localPath); panel_right.updateUI(); } } }; popup.addItemListener(0, itemAction); popup.addItemListener(1, itemAction); popup.addItemListener(2, itemAction); popup.addItemListener(3, itemAction); popup.addItemListener(4, itemAction); popup.addItemListener(5, itemAction); popup.addItemListener(6, itemAction); popup.addItemListener(7, itemAction); popup.addItemListener(8, itemAction); } private void mouseControlFile() { panel_right.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { //设置右键显示菜单 if (e.getButton() == MouseEvent.BUTTON3) { popup.show(e.getComponent(), e.getX(), e.getY()); } } }); } //显示字符串路径 private void showpath(String path) //显示路径字符串 { input_filed.setText(path); } //按钮初始化 private void BtnListenner() { back.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { showFile(operate.pathBackTo(localPath)); } }); forward.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { showFile(operate.pathForwardTo(localPath)); } }); new_dir.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { String inputValue = (String) JOptionPane.showInputDialog("请输入文件夹名"); if (inputValue.isEmpty()) JOptionPane.showMessageDialog(null, "标题【出错啦】", "输入不能为空", JOptionPane.ERROR_MESSAGE); else { operate.addDir(localPath + File.separator + inputValue); showFile(localPath); panel_right.updateUI(); } } }); new_file.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { String inputValue = (String) JOptionPane.showInputDialog("请输入文件名"); if (inputValue.isEmpty()) JOptionPane.showMessageDialog(null, "标题【出错啦】", "输入不能为空", JOptionPane.ERROR_MESSAGE); else { operate.addFile(localPath + File.separator + inputValue + ".txt"); showFile(localPath); panel_right.updateUI(); } } }); } //圆形进度条 //cpu 使用率 private void circleProgress() throws Exception { CircleProgressBar progressBar = new CircleProgressBar(); //实例化 progressBar.setMinimumProgress(0); //设置最小进度值 progressBar.setMaximumProgress(100); //设置最大进度值 int rate = Cpu.cpuRate(); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { try { int rate = Cpu.cpuRate(); progressBar.setProgress(rate); } catch (SigarException e) { e.printStackTrace(); } } },1000,1000); progressBar.setProgress(rate); //设置当前进度值 progressBar.setBackgroundColor(new Color(209, 206, 200)); //设置背景颜色 progressBar.setForegroundColor(new Color(0, 255, 0)); //设置前景颜色 progressBar.setDigitalColor(Color.BLACK); //设置数字颜色 progressBar.setSize(new Dimension(300, 400)); left_top_panel.add(progressBar,BorderLayout.CENTER); JLabel top = new JLabel("CPU利用率:"); top.setFont(new Font(null, Font.PLAIN, 20)); left_top_panel.add(top,BorderLayout.NORTH); JPanel nor = new JPanel(new GridLayout(3,1)); JLabel memory = new JLabel("Memory Total:" + Cpu.memoryTotal()); memory.setFont(new Font(null, Font.PLAIN, 20)); JLabel memoryused = new JLabel("Memory Used :" + Cpu.memoryUsed()); memoryused.setFont(new Font(null, Font.PLAIN, 20)); JLabel memoryfree = new JLabel("Memory Free :" + Cpu.memoryFree()); memoryfree.setFont(new Font(null, Font.PLAIN, 20)); nor.add(memory); nor.add(memoryused); nor.add(memoryfree); left_top_panel.add(nor,BorderLayout.SOUTH); } private static void InitGlobalFont(Font font) { FontUIResource fontRes = new FontUIResource(font); for (Enumeration<Object> keys = UIManager.getDefaults().keys(); keys.hasMoreElements();) { Object key = keys.nextElement(); Object value = UIManager.get(key); if (value instanceof FontUIResource) { UIManager.put(key, fontRes); } } } }
922fcd18b2635e9ca28d17403a991a3589953ea1
5,057
java
Java
languages/Natlab/src/natlab/backends/x10/codegen/x10Mapping.java
Sable/MiX10
9319a0eb87e3946d850d55ff57d314ff7fabb271
[ "Apache-2.0" ]
3
2015-12-27T18:45:11.000Z
2019-08-10T09:18:29.000Z
languages/Natlab/src/natlab/backends/x10/codegen/x10Mapping.java
Sable/MiX10
9319a0eb87e3946d850d55ff57d314ff7fabb271
[ "Apache-2.0" ]
2
2015-04-20T18:06:51.000Z
2015-04-20T18:18:34.000Z
languages/Natlab/src/natlab/backends/x10/codegen/x10Mapping.java
Sable/MiX10
9319a0eb87e3946d850d55ff57d314ff7fabb271
[ "Apache-2.0" ]
null
null
null
28.094444
92
0.721376
995,258
package natlab.backends.x10.codegen; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import natlab.backends.x10.IRx10.ast.Type; public class x10Mapping { private static HashMap<String, Type> x10TypeMap = new HashMap<String, Type>(); private static HashMap<String, String> x10BinOperatorMap = new HashMap<String, String>(); private static HashMap<String, String> x10UnOperatorMap = new HashMap<String, String>(); private static HashMap<String, String> x10DirectBuiltinMap = new HashMap<String, String>(); private static HashMap<String, String> x10BuiltinMap = new HashMap<String, String>(); private static HashMap<String, String> x10MethodMap = new HashMap<String, String>(); private static ArrayList<String> x10BuiltinList = new ArrayList<String>(); private static ArrayList<String> maybeX10BuiltinList = new ArrayList<String>(); private static String[] ArrayOfBuiltins; public x10Mapping() { makex10TypeMap(); /* * makex10BinOperatorMap(); makex10UnOperatorMap(); * makex10DirectBuiltinMap(); */ makex10BuiltinConstMap(); makex10MethodMap(); makex10BuiltinList(); makeMaybeX10BuiltinList(); } private void makeMaybeX10BuiltinList() { String listOfBuiltins = "rand,mtimes,times,rdivide,mrdivide," + "colon,sin,pi,mpower,zeros,ones,mean,fix,floor," + "round,abs,lt,le,uminus,and,i,randn,horzcat,vertcat," + "mean,sqrt,ceil,gt,ge"; ArrayOfBuiltins = listOfBuiltins.split(","); } private void makex10BuiltinList() { x10BuiltinList.add("plus"); x10BuiltinList.add("minus"); x10BuiltinList.add("gt"); x10BuiltinList.add("length"); x10BuiltinList.add("sqrt"); // x10BuiltinList.add("rand"); x10BuiltinList.add("horzcat"); // x10BuiltinList.add("mtimes"); // x10BuiltinList.add("times"); // x10BuiltinList.add("rdivide"); // x10BuiltinList.add("mrdivide"); x10BuiltinList.add("colon"); // x10BuiltinList.add("sin"); // x10BuiltinList.add("pi"); // x10BuiltinList.add("mpower"); // x10BuiltinList.add("zeros"); x10BuiltinList.add("ones"); // x10BuiltinList.add("mean"); x10BuiltinList.add("fix"); x10BuiltinList.add("floor"); // x10BuiltinList.add("round"); // x10BuiltinList.add("abs"); // x10BuiltinList.add("lt"); // x10BuiltinList.add("le"); // x10BuiltinList.add("uminus"); // x10BuiltinList.add("and"); // x10BuiltinList.add("i"); } private void makex10TypeMap() { x10TypeMap.put("char", new Type("Char")); x10TypeMap.put("double", new Type("Double")); x10TypeMap.put("single", new Type("Float")); x10TypeMap.put("int8", new Type("Byte")); x10TypeMap.put("int16", new Type("Short")); x10TypeMap.put("int32", new Type("Int")); x10TypeMap.put("int64", new Type("Long")); x10TypeMap.put("uint8", new Type("UByte")); x10TypeMap.put("uint16", new Type("UShort")); x10TypeMap.put("uint32", new Type("UInt")); x10TypeMap.put("uint64", new Type("ULong")); x10TypeMap.put("logical", new Type("Boolean")); x10TypeMap.put(null, new Type("Double")); /* This is the default type */ } private void makex10BuiltinConstMap() { // TODO create a categorical map here x10BuiltinMap.put("pi", "Math.PI"); } private void makex10MethodMap() { // TODO } public static Type getX10TypeMapping(String mclassasKey) { return x10TypeMap.get(mclassasKey); } public static Boolean isBinOperator(String expType) { if (true == x10BinOperatorMap.containsKey(expType)) return true; else return false; } public static String getX10BinOpMapping(String Operator) { return x10BinOperatorMap.get(Operator); } public static Boolean isUnOperator(String expType) { if (true == x10UnOperatorMap.containsKey(expType)) return true; else return false; } public static String getX10UnOpMapping(String Operator) { return x10UnOperatorMap.get(Operator); } public static Boolean isX10DirectBuiltin(String expType) { if (true == x10DirectBuiltinMap.containsKey(expType)) return true; else return false; } public static String getX10DirectBuiltinMapping(String BuiltinName) { return x10DirectBuiltinMap.get(BuiltinName); } public static Boolean isBuiltinConst(String expType) { if (true == x10BuiltinMap.containsKey(expType)) return true; else return false; } public static Boolean isBuiltin(String expType) { if (true == x10BuiltinList.contains(expType)) return true; else return false; } public static String getX10BuiltinConstMapping(String BuiltinName) { return x10BuiltinMap.get(BuiltinName); } public static Boolean isMethod(String expType) { if (true == x10MethodMap.containsKey(expType)) return true; else return false; } public static String getX10MethodMapping(String MethodName) { return x10MethodMap.get(MethodName); } public static boolean isMaybeBuiltin(String varName) { ArrayList<String> ArrayOfBuiltinsList = new ArrayList<String>(); Collections.addAll(ArrayOfBuiltinsList, ArrayOfBuiltins); if (ArrayOfBuiltinsList.contains(varName)) return true; else return false; } }
922fcd26432598365d74ca63a3ac9be5391f3056
1,538
java
Java
jretty-util/src/main/java/org/jretty/util/BasicCheckedException.java
jretty-org/jretty-util
d7bfc3ebfe2d9c105abe26b3cd3623d5dd11f910
[ "Apache-2.0" ]
2
2021-11-22T13:52:24.000Z
2022-02-07T17:01:45.000Z
jretty-util/src/main/java/org/jretty/util/BasicCheckedException.java
jretty-org/jretty-util
d7bfc3ebfe2d9c105abe26b3cd3623d5dd11f910
[ "Apache-2.0" ]
null
null
null
jretty-util/src/main/java/org/jretty/util/BasicCheckedException.java
jretty-org/jretty-util
d7bfc3ebfe2d9c105abe26b3cd3623d5dd11f910
[ "Apache-2.0" ]
2
2016-06-13T04:22:34.000Z
2016-11-21T09:34:49.000Z
28.962264
79
0.65798
995,259
/* * Copyright (C) 2013-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"). * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * Create by ZollTy on 2013-6-27 (http://blog.zollty.com/, ychag@example.com) */ package org.jretty.util; /** * 最基础的Checked异常类,所有其他的Checked异常都继承于本类 * * @author zollty * @since 2013-6-27 */ public class BasicCheckedException extends Exception { private static final long serialVersionUID = 6575977961100372966L; public BasicCheckedException() { super(); } /** * @param message 支持占位符{},例如 "error, userID={}, opt={}." * @param args 对应message占位符{}的值 */ public BasicCheckedException(String message, String... args) { super(StringUtils.replaceParams(message, args)); } /** * @param e 原始异常 */ public BasicCheckedException(Throwable e) { super(e); } /** * @param e 原始异常 * @param message 支持占位符{},例如 "error, userID={}, opt={}." * @param args 对应message占位符{}的值 */ public BasicCheckedException(Throwable e, String message, String... args) { super(StringUtils.replaceParams(message, args), e); } }
922fce8c30e568cf31d5e2c6a9d3054af679dc00
1,496
java
Java
src/main/java/com/blazemeter/jmeter/correlation/gui/CorrelationRulesTestElement.java
Blazemeter/SiebelPlugin
ae013f79c8bc16862f8e5c827d161c8936918245
[ "Apache-2.0" ]
12
2018-10-16T23:12:02.000Z
2020-10-27T17:30:15.000Z
src/main/java/com/blazemeter/jmeter/correlation/gui/CorrelationRulesTestElement.java
Blazemeter/SiebelPlugin
ae013f79c8bc16862f8e5c827d161c8936918245
[ "Apache-2.0" ]
null
null
null
src/main/java/com/blazemeter/jmeter/correlation/gui/CorrelationRulesTestElement.java
Blazemeter/SiebelPlugin
ae013f79c8bc16862f8e5c827d161c8936918245
[ "Apache-2.0" ]
2
2019-04-05T12:56:40.000Z
2020-01-22T09:58:00.000Z
29.92
92
0.768048
995,260
package com.blazemeter.jmeter.correlation.gui; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.jmeter.config.ConfigTestElement; import org.apache.jmeter.testelement.property.CollectionProperty; import org.apache.jmeter.testelement.property.JMeterProperty; import org.apache.jmeter.testelement.property.PropertyIterator; public class CorrelationRulesTestElement extends ConfigTestElement implements Serializable, Iterable<JMeterProperty> { public static final String RULES = "CorrelationRules.rules"; public CorrelationRulesTestElement() { this(new ArrayList<>()); } public CorrelationRulesTestElement(List<CorrelationRuleTestElement> rules) { setProperty(new CollectionProperty(RULES, rules)); } public List<CorrelationRuleTestElement> getRules() { PropertyIterator iter = getCollectionProperty().iterator(); List<CorrelationRuleTestElement> rules = new ArrayList<>(); while (iter.hasNext()) { rules.add((CorrelationRuleTestElement) iter.next().getObjectValue()); } return rules; } private CollectionProperty getCollectionProperty() { return (CollectionProperty) getProperty(RULES); } @Override public void clear() { super.clear(); setProperty(new CollectionProperty(RULES, new ArrayList<CorrelationRuleTestElement>())); } @Override public Iterator<JMeterProperty> iterator() { return getCollectionProperty().iterator(); } }
922fcf0489143224883ee424ade4173d780deb99
5,068
java
Java
src/TreeLayout/CParseTreeGraphBuilder.java
ssanyu/pamoja
7e99e4f3464937900c3146de09c2e4bdfe37b6cf
[ "Apache-2.0" ]
1
2021-01-07T07:08:43.000Z
2021-01-07T07:08:43.000Z
src/TreeLayout/CParseTreeGraphBuilder.java
ssanyu/PAMOJA
7e99e4f3464937900c3146de09c2e4bdfe37b6cf
[ "Apache-2.0" ]
null
null
null
src/TreeLayout/CParseTreeGraphBuilder.java
ssanyu/PAMOJA
7e99e4f3464937900c3146de09c2e4bdfe37b6cf
[ "Apache-2.0" ]
null
null
null
44.45614
148
0.546567
995,261
/* * 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 TreeLayout; import GrammarNotions.ECFGNodes.CECFGNode; import GrammarNotions.ECFGNodes.CECFGNodeCodes; import java.awt.Color; import java.util.ArrayList; /** * * @author Ssanyu */ public class CParseTreeGraphBuilder extends CTreeGraph { /** * * @param root */ public CParseTreeGraphBuilder(CTreeNode root) { super(root); } /** * * @param aNode * @return */ public CTreeNode ECFGNodetoTreeNode(CECFGNode aNode){ CTreeNode vResult=null; if(aNode!=null){ switch(aNode.sortCode()){ case CECFGNodeCodes.scEpsNode: vResult=new CTreeNode(CNodeStyle.RECTANGLE,CEdgeStyle.FAN,new Color(204,153,255),"\\Eps",new ArrayList<CTreeNode>()); break; case CECFGNodeCodes.scNonTermNode: CECFGNode vNode=(CECFGNode)aNode.getNode(0); ArrayList<CTreeNode> nt=new ArrayList<>(); nt.add(ECFGNodetoTreeNode(vNode)); vResult= new CTreeNode(CNodeStyle.RECTANGLE,CEdgeStyle.FAN,new Color(204,153,255),aNode.getData(2),nt); break; case CECFGNodeCodes.scTermValueNode: CTreeNode vt=new CTreeNode(CNodeStyle.NOFRAME,CEdgeStyle.ABSENT,Color.BLACK,aNode.getData(3),new ArrayList<CTreeNode>()); ArrayList<CTreeNode> nt1=new ArrayList<>(); nt1.add(vt); vResult= new CTreeNode(CNodeStyle.RECTANGLE,CEdgeStyle.FAN,new Color(255,153,255),aNode.getData(2),nt1); break; case CECFGNodeCodes.scTermNode: vResult= new CTreeNode(CNodeStyle.RECTANGLE,CEdgeStyle.FAN,new Color(255,153,255),aNode.getData(2),new ArrayList<CTreeNode>()); break; case CECFGNodeCodes.scMultiDotNode: ArrayList<CTreeNode> nt2=new ArrayList<>(); for(int i=0;i<aNode.count();i++){ CECFGNode mNode=(CECFGNode)aNode.getNode(i); nt2.add(ECFGNodetoTreeNode(mNode)); } vResult=new CTreeNode(CNodeStyle.OVAL,CEdgeStyle.FAN,new Color(204,204,255),".",nt2); break; case CECFGNodeCodes.scMultiStickNode: ArrayList<CTreeNode> nt3=new ArrayList<>(); for(int i=0;i<aNode.count();i++){ CECFGNode sNode=(CECFGNode)aNode.getNode(i); nt3.add(ECFGNodetoTreeNode(sNode)); } vResult=new CTreeNode(CNodeStyle.OVAL,CEdgeStyle.FAN,new Color(204,204,255),"|_"+aNode.getData(2),nt3); break; case CECFGNodeCodes.scAltNode: ArrayList<CTreeNode> nt4=new ArrayList<>(); for(int i=0;i<aNode.count();i++){ CECFGNode tNode=(CECFGNode)aNode.getNode(i); nt4.add(ECFGNodetoTreeNode(tNode)); } vResult=new CTreeNode(CNodeStyle.OVAL,CEdgeStyle.COMB,new Color(204,204,255),"%",nt4); break; case CECFGNodeCodes.scStarNode: ArrayList<CTreeNode> nt5=new ArrayList<>(); for(int i=0;i<aNode.count();i++){ CECFGNode stNode=(CECFGNode)aNode.getNode(i); nt5.add(ECFGNodetoTreeNode(stNode)); } vResult=new CTreeNode(CNodeStyle.OVAL,CEdgeStyle.COMB,new Color(204,204,255),"*",nt5); break; case CECFGNodeCodes.scOptionNode: ArrayList<CTreeNode> nt6=new ArrayList<>(); CECFGNode oNode=(CECFGNode)aNode.getNode(0); if(oNode!=null){ nt6.add(ECFGNodetoTreeNode(oNode)); vResult=new CTreeNode(CNodeStyle.OVAL,CEdgeStyle.COMB,new Color(204,204,255),"?",nt6); } else{ vResult=new CTreeNode(CNodeStyle.OVAL,CEdgeStyle.COMB,new Color(204,204,255),"?",new ArrayList<CTreeNode>()); } break; case CECFGNodeCodes.scPlusNode: ArrayList<CTreeNode> nt7=new ArrayList<>(); for(int i=0;i<aNode.count();i++){ CECFGNode pNode=(CECFGNode)aNode.getNode(i); nt7.add(ECFGNodetoTreeNode(pNode)); } vResult=new CTreeNode(CNodeStyle.OVAL,CEdgeStyle.COMB,new Color(204,204,255),"+",nt7); break; default: vResult=new CTreeNode(CNodeStyle.RECTANGLE,CEdgeStyle.FAN,Color.BLUE,"None",new ArrayList<CTreeNode>()); break; } } return vResult; } }
922fcfed46e672f87139c18b82fc53f8c6fd6667
120
java
Java
src/main/java/havis/llrpservice/sbc/rfc/message/Message.java
peramic/App.LLRP
c7b3da56757db7aabd775556f66cdf22694fd6d1
[ "Apache-2.0" ]
null
null
null
src/main/java/havis/llrpservice/sbc/rfc/message/Message.java
peramic/App.LLRP
c7b3da56757db7aabd775556f66cdf22694fd6d1
[ "Apache-2.0" ]
null
null
null
src/main/java/havis/llrpservice/sbc/rfc/message/Message.java
peramic/App.LLRP
c7b3da56757db7aabd775556f66cdf22694fd6d1
[ "Apache-2.0" ]
1
2021-07-26T14:17:22.000Z
2021-07-26T14:17:22.000Z
20
43
0.775
995,262
package havis.llrpservice.sbc.rfc.message; public interface Message { public MessageHeader getMessageHeader(); }
922fd12f6f8fa3468b57bfb7ab7e6e363a0e4974
1,580
java
Java
source/decisions/claim-xom/src/com/ibm/gse/dc/PolicyHolder.java
alok-acn/denim-compute
7079ea4c68ea6e7c38ecfd3f2d7dc307e848c12f
[ "Apache-2.0" ]
16
2019-10-03T13:21:15.000Z
2022-02-22T04:14:33.000Z
source/decisions/claim-xom/src/com/ibm/gse/dc/PolicyHolder.java
alok-acn/denim-compute
7079ea4c68ea6e7c38ecfd3f2d7dc307e848c12f
[ "Apache-2.0" ]
null
null
null
source/decisions/claim-xom/src/com/ibm/gse/dc/PolicyHolder.java
alok-acn/denim-compute
7079ea4c68ea6e7c38ecfd3f2d7dc307e848c12f
[ "Apache-2.0" ]
17
2019-08-07T16:09:43.000Z
2022-01-19T08:47:58.000Z
21.351351
69
0.736709
995,263
package com.ibm.gse.dc; /** * Policy holder personal information. * * @author PIERREBerlandier * */ public class PolicyHolder { private String firstName; // BPM -> Insured FName private String lastName; // BPM -> Insured LName private Location address; // BPM -> Insured Street, City, State, Zip private int monthlyIncome; // BPM -> Insured Monthly Income private String education; // BPM -> Insured Education private String maritalStatus; // BPM -> Insured Marital Status private String employmentStatus; // BPM -> Insured Employment Status public Location getAddress() { return address; } public String getEducation() { return education; } public String getEmploymentStatus() { return employmentStatus; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getMaritalStatus() { return maritalStatus; } public int getMonthlyIncome() { return monthlyIncome; } public void setAddress(Location address) { this.address = address; } public void setEducation(String education) { this.education = education; } public void setEmploymentStatus(String employmentStatus) { this.employmentStatus = employmentStatus; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public void setMaritalStatus(String maritalStatus) { this.maritalStatus = maritalStatus; } public void setMonthlyIncome(int monthlyIncome) { this.monthlyIncome = monthlyIncome; } }
922fd13acce217185a46cfe2683376625d337994
5,141
java
Java
app/common/dal/src/main/java/com/bbd/bdsso/common/dal/dataobject/SsoVisitHistoryDO.java
jinghuaaa/sso
9d00fecf6fd80d1788ef3eb3f4c1c9418ddc667c
[ "Apache-2.0" ]
null
null
null
app/common/dal/src/main/java/com/bbd/bdsso/common/dal/dataobject/SsoVisitHistoryDO.java
jinghuaaa/sso
9d00fecf6fd80d1788ef3eb3f4c1c9418ddc667c
[ "Apache-2.0" ]
null
null
null
app/common/dal/src/main/java/com/bbd/bdsso/common/dal/dataobject/SsoVisitHistoryDO.java
jinghuaaa/sso
9d00fecf6fd80d1788ef3eb3f4c1c9418ddc667c
[ "Apache-2.0" ]
null
null
null
24.716346
92
0.637619
995,264
/* * bbdservice.com Inc. * Copyright (c) 2017 All Rights Reserved. */ package com.bbd.bdsso.common.dal.dataobject; import java.io.Serializable; // auto generated imports import java.util.Date; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * A data object class directly models database table <tt>sso_visit_history</tt>. * * This file is generated by <tt>bdsso-bbdalgen</tt>, a DAL (Data Access Layer) * code generation utility specially developed for <tt>bdsso</tt> project. * * PLEASE DO NOT MODIFY THIS FILE MANUALLY, or else your modification may * be OVERWRITTEN by someone else. To modify the file, you should go to * directory <tt>(project-home)/bbdalgen</tt>, and * find the corresponding configuration file (<tt>tables/sso_visit_history.xml</tt>). * Modify the configuration file according to your needs, then run <tt>bdsso-bbdalgen</tt> * to generate this file. * * @author Byron Zhang * @version $Id: description-java.vm,v 1.1 2016/05/01 07:34:20 byron Exp $ */ public class SsoVisitHistoryDO implements Serializable { /** serialId */ private static final long serialVersionUID = 741231858441822688L; //========== properties ========== /** * This property corresponds to db column <tt>id</tt>. */ private Integer id; /** * This property corresponds to db column <tt>user_id</tt>. */ private Integer userId; /** * This property corresponds to db column <tt>last_login_date</tt>. */ private Date lastLoginDate; /** * This property corresponds to db column <tt>last_login_ip</tt>. */ private String lastLoginIp; /** * This property corresponds to db column <tt>description</tt>. */ private String description; /** * This property corresponds to db column <tt>gmt_create</tt>. */ private Date gmtCreate; /** * This property corresponds to db column <tt>gmt_modified</tt>. */ private Date gmtModified; //========== getters and setters ========== /** * Getter method for property <tt>id</tt>. * * @return property value of id */ public Integer getId() { return id; } /** * Setter method for property <tt>id</tt>. * * @param id value to be assigned to property id */ public void setId(Integer id) { this.id = id; } /** * Getter method for property <tt>userId</tt>. * * @return property value of userId */ public Integer getUserId() { return userId; } /** * Setter method for property <tt>userId</tt>. * * @param userId value to be assigned to property userId */ public void setUserId(Integer userId) { this.userId = userId; } /** * Getter method for property <tt>lastLoginDate</tt>. * * @return property value of lastLoginDate */ public Date getLastLoginDate() { return lastLoginDate; } /** * Setter method for property <tt>lastLoginDate</tt>. * * @param lastLoginDate value to be assigned to property lastLoginDate */ public void setLastLoginDate(Date lastLoginDate) { this.lastLoginDate = lastLoginDate; } /** * Getter method for property <tt>lastLoginIp</tt>. * * @return property value of lastLoginIp */ public String getLastLoginIp() { return lastLoginIp; } /** * Setter method for property <tt>lastLoginIp</tt>. * * @param lastLoginIp value to be assigned to property lastLoginIp */ public void setLastLoginIp(String lastLoginIp) { this.lastLoginIp = lastLoginIp; } /** * Getter method for property <tt>description</tt>. * * @return property value of description */ public String getDescription() { return description; } /** * Setter method for property <tt>description</tt>. * * @param description value to be assigned to property description */ public void setDescription(String description) { this.description = description; } /** * Getter method for property <tt>gmtCreate</tt>. * * @return property value of gmtCreate */ public Date getGmtCreate() { return gmtCreate; } /** * Setter method for property <tt>gmtCreate</tt>. * * @param gmtCreate value to be assigned to property gmtCreate */ public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } /** * Getter method for property <tt>gmtModified</tt>. * * @return property value of gmtModified */ public Date getGmtModified() { return gmtModified; } /** * Setter method for property <tt>gmtModified</tt>. * * @param gmtModified value to be assigned to property gmtModified */ public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } /** * @see java.lang.Object#toString() */ @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } }
922fd1459f5d686fed1c1ba7dd1700ef58d48c19
3,138
java
Java
metamorph-kafka-08/src/test/java/net/researchgate/kafka/metamorph/kafka08/Kafka08PartitionConsumerTest.java
researchgate/kafka-metamorph
bab5428d4f16b2a16cb46737bdc36a059bfa77a5
[ "Apache-2.0" ]
3
2016-05-12T09:54:06.000Z
2016-12-19T14:29:37.000Z
metamorph-kafka-08/src/test/java/net/researchgate/kafka/metamorph/kafka08/Kafka08PartitionConsumerTest.java
researchgate/kafka-metamorph
bab5428d4f16b2a16cb46737bdc36a059bfa77a5
[ "Apache-2.0" ]
2
2016-06-29T15:27:37.000Z
2016-07-02T17:17:44.000Z
metamorph-kafka-08/src/test/java/net/researchgate/kafka/metamorph/kafka08/Kafka08PartitionConsumerTest.java
researchgate/kafka-metamorph
bab5428d4f16b2a16cb46737bdc36a059bfa77a5
[ "Apache-2.0" ]
2
2016-06-24T10:05:52.000Z
2019-08-30T02:16:45.000Z
42.405405
156
0.74283
995,265
package net.researchgate.kafka.metamorph.kafka08; import kafka.serializer.StringDecoder; import kafka.utils.VerifiableProperties; import net.researchgate.kafka.metamorph.AbstractKafkaPartitionConsumerTest; import net.researchgate.kafka.metamorph.KafkaTestContext; import net.researchgate.kafka.metamorph.PartitionConsumer; import net.researchgate.kafka.metamorph.kafka08.utils.Kafka08TestContext; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.kafka.common.serialization.StringSerializer; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; public class Kafka08PartitionConsumerTest extends AbstractKafkaPartitionConsumerTest { @Override protected KafkaTestContext getContext() { return new Kafka08TestContext(); } @Override protected PartitionConsumer<String, String> initializeUnitUnderTest() { Kafka08PartitionConsumerConfig consumerConfig = new Kafka08PartitionConsumerConfig.Builder(context.getBootstrapServerString()).build(); return new Kafka08PartitionConsumer<>(consumerConfig, new StringDecoder(new VerifiableProperties()), new StringDecoder(new VerifiableProperties())); } private KafkaProducer<String, String> createProducer() { return createProducer(StringSerializer.class, StringSerializer.class); } private <K,V> KafkaProducer<K,V> createProducer(Class keySerializerClass , Class valueSerializerClass) { Properties props = new Properties(); props.put(org.apache.kafka.clients.producer.ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, context.getBootstrapServerString()); props.put(org.apache.kafka.clients.producer.ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, keySerializerClass); props.put(org.apache.kafka.clients.producer.ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, valueSerializerClass); return new KafkaProducer<>(props); } @Override protected void produceMessagesOrdered(String topic, int messageNum) throws ExecutionException, InterruptedException { KafkaProducer<String, String> producer = createProducer(); for (int i = 0; i < messageNum; i++) { Future<RecordMetadata> future = producer.send(new ProducerRecord<>(topic, "test-key-" + i, "test-value-" + i)); future.get(); } producer.close(); } @Override protected void produceMessagesUnordered(String topic, int messageNum) throws ExecutionException, InterruptedException { KafkaProducer<String, String> producer = createProducer(); List<Future<RecordMetadata>> futures = new ArrayList<>(); for (int i = 0; i < messageNum; i++) { Future<RecordMetadata> future = producer.send(new ProducerRecord<>(topic, "test-key-" + i, "test-value")); futures.add(future); } for (Future f : futures) { f.get(); } producer.close(); } }
922fd19d56a29f91b3b39eccece180e10cc6e647
398
java
Java
src/main/java/com/bath/tcpviz/dis/fileupload/property/FileStorageProperties.java
perrymant/TCPviz
37004f361905ba396d6c929fa75bbc9295c3aa99
[ "MIT" ]
null
null
null
src/main/java/com/bath/tcpviz/dis/fileupload/property/FileStorageProperties.java
perrymant/TCPviz
37004f361905ba396d6c929fa75bbc9295c3aa99
[ "MIT" ]
null
null
null
src/main/java/com/bath/tcpviz/dis/fileupload/property/FileStorageProperties.java
perrymant/TCPviz
37004f361905ba396d6c929fa75bbc9295c3aa99
[ "MIT" ]
null
null
null
23.411765
75
0.738693
995,266
package com.bath.tcpviz.dis.fileupload.property; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "file") public class FileStorageProperties { private String uploadDir; public String getUploadDir() { return uploadDir; } public void setUploadDir(String uploadDir) { this.uploadDir = uploadDir; } }
922fd1a365ab0248e2d8062a3f5d3a94ba91abd7
11,431
java
Java
backend/src/main/java/pt/ulisboa/tecnico/socialsoftware/tutor/tournament/TournamentService.java
ritosilva/quizzes-tutor
5995988ebbdee2699ce849e0b321d8cce9615167
[ "MIT" ]
31
2020-02-07T14:09:39.000Z
2022-03-31T21:49:46.000Z
backend/src/main/java/pt/ulisboa/tecnico/socialsoftware/tutor/tournament/TournamentService.java
ritosilva/quizzes-tutor
5995988ebbdee2699ce849e0b321d8cce9615167
[ "MIT" ]
280
2020-01-28T12:31:09.000Z
2022-03-31T21:14:16.000Z
backend/src/main/java/pt/ulisboa/tecnico/socialsoftware/tutor/tournament/TournamentService.java
ritosilva/quizzes-tutor
5995988ebbdee2699ce849e0b321d8cce9615167
[ "MIT" ]
66
2020-02-17T17:38:41.000Z
2022-03-16T13:57:05.000Z
43.965385
169
0.726971
995,267
package pt.ulisboa.tecnico.socialsoftware.tutor.tournament; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.retry.annotation.Backoff; import org.springframework.retry.annotation.Retryable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import pt.ulisboa.tecnico.socialsoftware.tutor.answer.AnswerService; import pt.ulisboa.tecnico.socialsoftware.tutor.answer.dto.StatementQuizDto; import pt.ulisboa.tecnico.socialsoftware.tutor.answer.dto.StatementTournamentCreationDto; import pt.ulisboa.tecnico.socialsoftware.tutor.exceptions.TutorException; import pt.ulisboa.tecnico.socialsoftware.tutor.execution.CourseExecutionService; import pt.ulisboa.tecnico.socialsoftware.tutor.execution.domain.CourseExecution; import pt.ulisboa.tecnico.socialsoftware.tutor.execution.repository.CourseExecutionRepository; import pt.ulisboa.tecnico.socialsoftware.tutor.question.domain.Topic; import pt.ulisboa.tecnico.socialsoftware.tutor.question.repository.TopicRepository; import pt.ulisboa.tecnico.socialsoftware.tutor.quiz.QuizService; import pt.ulisboa.tecnico.socialsoftware.tutor.quiz.domain.Quiz; import pt.ulisboa.tecnico.socialsoftware.tutor.quiz.dto.QuizDto; import pt.ulisboa.tecnico.socialsoftware.tutor.quiz.repository.QuizRepository; import pt.ulisboa.tecnico.socialsoftware.tutor.tournament.domain.Tournament; import pt.ulisboa.tecnico.socialsoftware.tutor.tournament.dto.TournamentDto; import pt.ulisboa.tecnico.socialsoftware.tutor.tournament.repository.TournamentRepository; import pt.ulisboa.tecnico.socialsoftware.tutor.user.domain.Student; import pt.ulisboa.tecnico.socialsoftware.tutor.user.dto.StudentDto; import pt.ulisboa.tecnico.socialsoftware.tutor.user.repository.StudentRepository; import pt.ulisboa.tecnico.socialsoftware.tutor.utils.DateHandler; import java.sql.SQLException; import java.time.LocalDateTime; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import static pt.ulisboa.tecnico.socialsoftware.tutor.exceptions.ErrorMessage.*; @Service public class TournamentService { @Autowired private CourseExecutionRepository courseExecutionRepository; @Autowired private QuizService quizService; @Autowired private CourseExecutionService courseExecutionService; @Autowired private QuizRepository quizRepository; @Autowired private AnswerService answerService; @Autowired private TopicRepository topicRepository; @Autowired private TournamentRepository tournamentRepository; @Autowired private StudentRepository studentRepository; @Retryable(value = { SQLException.class }, backoff = @Backoff(delay = 5000)) @Transactional(isolation = Isolation.REPEATABLE_READ) public TournamentDto createTournament(Integer userId, Integer executionId, Set<Integer> topicsId, TournamentDto tournamentDto) { checkInput(userId, topicsId, tournamentDto); Student student = studentRepository.findById(userId).orElseThrow(() -> new TutorException(USER_NOT_FOUND, userId)); CourseExecution courseExecution = courseExecutionRepository.findById(executionId).orElseThrow(() -> new TutorException(COURSE_EXECUTION_NOT_FOUND, executionId)); Set<Topic> topics = new HashSet<>(); for (Integer topicId : topicsId) { Topic topic = topicRepository.findById(topicId) .orElseThrow(() -> new TutorException(TOPIC_NOT_FOUND, topicId)); topics.add(topic); } if (topics.isEmpty()) { throw new TutorException(TOURNAMENT_MISSING_TOPICS); } Tournament tournament = new Tournament(student, courseExecution, topics, tournamentDto); tournamentRepository.save(tournament); return new TournamentDto(tournament); } @Retryable(value = { SQLException.class }, backoff = @Backoff(delay = 5000)) @Transactional(isolation = Isolation.REPEATABLE_READ) public List<TournamentDto> getTournamentsForCourseExecution(Integer executionId) { return tournamentRepository.getTournamentsForCourseExecution(executionId).stream().map(TournamentDto::new) .collect(Collectors.toList()); } @Retryable(value = { SQLException.class }, backoff = @Backoff(delay = 5000)) @Transactional(isolation = Isolation.REPEATABLE_READ) public List<TournamentDto> getOpenedTournamentsForCourseExecution(Integer executionId) { LocalDateTime now = DateHandler.now(); return tournamentRepository.getOpenedTournamentsForCourseExecution(executionId, now).stream().map(TournamentDto::new) .collect(Collectors.toList()); } @Retryable(value = { SQLException.class }, backoff = @Backoff(delay = 5000)) @Transactional(isolation = Isolation.REPEATABLE_READ) public List<TournamentDto> getClosedTournamentsForCourseExecution(Integer executionId) { LocalDateTime now = DateHandler.now(); return tournamentRepository.getClosedTournamentsForCourseExecution(executionId, now).stream().map(TournamentDto::new) .collect(Collectors.toList()); } @Retryable(value = { SQLException.class }, backoff = @Backoff(delay = 5000)) @Transactional(isolation = Isolation.REPEATABLE_READ) public TournamentDto getTournament(Integer tournamentId) { return tournamentRepository.findById(tournamentId) .map(TournamentDto::new) .orElseThrow(() -> new TutorException(TOURNAMENT_NOT_FOUND, tournamentId)); } @Retryable(value = { SQLException.class }, backoff = @Backoff(delay = 5000)) @Transactional(isolation = Isolation.REPEATABLE_READ) public void joinTournament(Integer userId, Integer tournamentId, String password) { Student student = studentRepository.findById(userId).orElseThrow(() -> new TutorException(USER_NOT_FOUND, userId)); Tournament tournament = checkTournament(tournamentId); tournament.addParticipant(student, password); } @Retryable(value = { SQLException.class }, backoff = @Backoff(delay = 5000)) @Transactional(isolation = Isolation.REPEATABLE_READ) public StatementQuizDto solveQuiz(Integer userId, Integer tournamentId) { Tournament tournament = checkTournament(tournamentId); if (!tournament.hasQuiz()) { createQuiz(tournament); } return answerService.startQuiz(userId, tournament.getQuiz().getId()); } @Retryable(value = { SQLException.class }, backoff = @Backoff(delay = 5000)) @Transactional(isolation = Isolation.REPEATABLE_READ) public void leaveTournament(Integer userId, Integer tournamentId) { Student student = studentRepository.findById(userId).orElseThrow(() -> new TutorException(USER_NOT_FOUND, userId)); Tournament tournament = checkTournament(tournamentId); tournament.removeParticipant(student); } @Retryable( value = { SQLException.class }, backoff = @Backoff(delay = 5000)) @Transactional(isolation = Isolation.READ_COMMITTED) public TournamentDto updateTournament(Set<Integer> topicsId, TournamentDto tournamentDto) { Tournament tournament = checkTournament(tournamentDto.getId()); Set<Topic> topics = new HashSet<>(); for (Integer topicId : topicsId) { Topic topic = topicRepository.findById(topicId) .orElseThrow(() -> new TutorException(TOPIC_NOT_FOUND, topicId)); topics.add(topic); } tournament.updateTournament(tournamentDto, topics); if (tournament.hasQuiz()) { // update current Quiz Quiz quiz = quizRepository.findById(tournamentDto.getQuizId()) .orElseThrow(() -> new TutorException(QUIZ_NOT_FOUND, tournamentDto.getQuizId())); QuizDto quizDto = quizService.findById(tournamentDto.getQuizId()); quizDto.setNumberOfQuestions(tournamentDto.getNumberOfQuestions()); quizService.updateQuiz(quiz.getId(), quizDto); } return new TournamentDto(tournament); } @Retryable(value = { SQLException.class }, backoff = @Backoff(delay = 5000)) @Transactional(isolation = Isolation.REPEATABLE_READ) public TournamentDto cancelTournament(Integer tournamentId) { Tournament tournament = checkTournament(tournamentId); tournament.cancel(); return new TournamentDto(tournament); } @Retryable(value = { SQLException.class }, backoff = @Backoff(delay = 5000)) @Transactional(isolation = Isolation.REPEATABLE_READ) public void removeTournament(Integer tournamentId) { Tournament tournament = checkTournament(tournamentId); tournament.remove(); tournamentRepository.delete(tournament); } @Retryable(value = { SQLException.class }, backoff = @Backoff(delay = 5000)) @Transactional(isolation = Isolation.REPEATABLE_READ) public List<StudentDto> getTournamentParticipants(TournamentDto tournamentDto) { Tournament tournament = checkTournament(tournamentDto.getId()); return tournament.getParticipants().stream().map(StudentDto::new).collect(Collectors.toList()); } private void checkInput(Integer userId, Set<Integer> topicsId, TournamentDto tournamentDto) { if (userId == null) { throw new TutorException(TOURNAMENT_MISSING_USER); } if (topicsId == null) { throw new TutorException(TOURNAMENT_MISSING_TOPICS); } if (tournamentDto.getStartTime() == null) { throw new TutorException(TOURNAMENT_MISSING_START_TIME); } if (tournamentDto.getEndTime() == null) { throw new TutorException(TOURNAMENT_MISSING_END_TIME); } if (tournamentDto.getNumberOfQuestions() == null) { throw new TutorException(TOURNAMENT_MISSING_NUMBER_OF_QUESTIONS); } } private Tournament checkTournament(Integer tournamentId) { return tournamentRepository.findById(tournamentId) .orElseThrow(() -> new TutorException(TOURNAMENT_NOT_FOUND, tournamentId)); } private void createQuiz(Tournament tournament) { StatementTournamentCreationDto quizForm = new StatementTournamentCreationDto(tournament); StatementQuizDto statementQuizDto = answerService.generateTournamentQuiz(tournament.getCreator().getId(), tournament.getCourseExecution().getId(), quizForm, tournament); Quiz quiz = quizRepository.findById(statementQuizDto.getId()).orElse(null); tournament.setQuiz(quiz); } @Retryable( value = { SQLException.class }, backoff = @Backoff(delay = 5000)) @Transactional(isolation = Isolation.READ_COMMITTED) public void resetDemoTournaments() { tournamentRepository.getTournamentsForCourseExecution(courseExecutionService.getDemoCourse().getCourseExecutionId()) .forEach(tournament -> { tournament.getParticipants().forEach(user -> user.removeTournament(tournament)); if (tournament.getQuiz() != null) { tournament.getQuiz().setTournament(null); } tournamentRepository.delete(tournament); }); } }
922fd1c22080ea06d7e1c33c7712405cfe5c6830
10,465
java
Java
main/plugins/org.talend.designer.components.libs/libs_src/crm4client/com/microsoft/schemas/crm/_2007/webservices/ArrayOfsalesorderdetail.java
bgunics-talend/tdi-studio-se
3f54f55acb4d214f2d02532667bae98420068170
[ "Apache-2.0" ]
114
2015-03-05T15:34:59.000Z
2022-02-22T03:48:44.000Z
main/plugins/org.talend.designer.components.libs/libs_src/crm4client/com/microsoft/schemas/crm/_2007/webservices/ArrayOfsalesorderdetail.java
bgunics-talend/tdi-studio-se
3f54f55acb4d214f2d02532667bae98420068170
[ "Apache-2.0" ]
1,137
2015-03-04T01:35:42.000Z
2022-03-29T06:03:17.000Z
main/plugins/org.talend.designer.components.libs/libs_src/crm4client/com/microsoft/schemas/crm/_2007/webservices/ArrayOfsalesorderdetail.java
bgunics-talend/tdi-studio-se
3f54f55acb4d214f2d02532667bae98420068170
[ "Apache-2.0" ]
219
2015-01-21T10:42:18.000Z
2022-02-17T07:57:20.000Z
76.386861
280
0.748113
995,268
/* * XML Type: ArrayOfsalesorderdetail * Namespace: http://schemas.microsoft.com/crm/2007/WebServices * Java type: com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail * * Automatically generated - do not modify. */ package com.microsoft.schemas.crm._2007.webservices; /** * An XML ArrayOfsalesorderdetail(@http://schemas.microsoft.com/crm/2007/WebServices). * * This is a complex type. */ public interface ArrayOfsalesorderdetail extends org.apache.xmlbeans.XmlObject { public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType) org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(ArrayOfsalesorderdetail.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.sE3DFDC56E75679F2AF264CA469AD5996").resolveHandle("arrayofsalesorderdetail258ftype"); /** * Gets array of all "salesorderdetail" elements */ com.microsoft.schemas.crm._2007.webservices.Salesorderdetail[] getSalesorderdetailArray(); /** * Gets ith "salesorderdetail" element */ com.microsoft.schemas.crm._2007.webservices.Salesorderdetail getSalesorderdetailArray(int i); /** * Returns number of "salesorderdetail" element */ int sizeOfSalesorderdetailArray(); /** * Sets array of all "salesorderdetail" element */ void setSalesorderdetailArray(com.microsoft.schemas.crm._2007.webservices.Salesorderdetail[] salesorderdetailArray); /** * Sets ith "salesorderdetail" element */ void setSalesorderdetailArray(int i, com.microsoft.schemas.crm._2007.webservices.Salesorderdetail salesorderdetail); /** * Inserts and returns a new empty value (as xml) as the ith "salesorderdetail" element */ com.microsoft.schemas.crm._2007.webservices.Salesorderdetail insertNewSalesorderdetail(int i); /** * Appends and returns a new empty value (as xml) as the last "salesorderdetail" element */ com.microsoft.schemas.crm._2007.webservices.Salesorderdetail addNewSalesorderdetail(); /** * Removes the ith "salesorderdetail" element */ void removeSalesorderdetail(int i); /** * A factory class with static methods for creating instances * of this type. */ public static final class Factory { public static com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail newInstance() { return (com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); } public static com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail newInstance(org.apache.xmlbeans.XmlOptions options) { return (com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); } /** @param xmlAsString the string value to parse */ public static com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException { return (com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); } public static com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); } /** @param file the file from which to load an xml document */ public static com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); } public static com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); } public static com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); } public static com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); } public static com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); } public static com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); } public static com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); } public static com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); } public static com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException { return (com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); } public static com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); } public static com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { return (com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); } public static com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ public static com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return (com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ public static com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return (com.microsoft.schemas.crm._2007.webservices.ArrayOfsalesorderdetail) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } private Factory() { } // No instance of this class allowed } }
922fd222e986f086d924de50be8976519f5312e6
2,949
java
Java
src/main/java/io/swagger/client/model/Target.java
atehrani/api-client-java
64034071238de636302cab26edc37af3b12471fc
[ "Apache-2.0" ]
null
null
null
src/main/java/io/swagger/client/model/Target.java
atehrani/api-client-java
64034071238de636302cab26edc37af3b12471fc
[ "Apache-2.0" ]
null
null
null
src/main/java/io/swagger/client/model/Target.java
atehrani/api-client-java
64034071238de636302cab26edc37af3b12471fc
[ "Apache-2.0" ]
null
null
null
23.275591
125
0.669486
995,269
/* * LaunchDarkly REST API * Build custom integrations with the LaunchDarkly REST API * * OpenAPI spec version: 2.0.0 * Contact: kenaa@example.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package io.swagger.client.model; import java.util.Objects; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Target */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-10-17T14:52:38.201-07:00") public class Target { @SerializedName("values") private List<String> values = null; @SerializedName("variation") private Integer variation = null; public Target values(List<String> values) { this.values = values; return this; } public Target addValuesItem(String valuesItem) { if (this.values == null) { this.values = new ArrayList<String>(); } this.values.add(valuesItem); return this; } /** * Get values * @return values **/ @ApiModelProperty(value = "") public List<String> getValues() { return values; } public void setValues(List<String> values) { this.values = values; } public Target variation(Integer variation) { this.variation = variation; return this; } /** * Get variation * @return variation **/ @ApiModelProperty(value = "") public Integer getVariation() { return variation; } public void setVariation(Integer variation) { this.variation = variation; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Target target = (Target) o; return Objects.equals(this.values, target.values) && Objects.equals(this.variation, target.variation); } @Override public int hashCode() { return Objects.hash(values, variation); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Target {\n"); sb.append(" values: ").append(toIndentedString(values)).append("\n"); sb.append(" variation: ").append(toIndentedString(variation)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
922fd30dee3c2073b57db9e626168ef3516df28e
7,205
java
Java
src/main/java/com/xmomen/module/base/model/ItemModel.java
xmomen/dms-webapp
96fcd1bc0b60389c339be18c30fea385196825f4
[ "MIT" ]
53
2016-03-16T04:37:08.000Z
2022-03-22T07:05:44.000Z
src/main/java/com/xmomen/module/base/model/ItemModel.java
maguohao2017/Delivery
c0609fccff79a1dfb4fe2eef645e1c0bab064bb7
[ "MIT" ]
6
2016-05-12T16:21:07.000Z
2020-10-09T15:37:58.000Z
src/main/java/com/xmomen/module/base/model/ItemModel.java
xmomen/dms-webapp
96fcd1bc0b60389c339be18c30fea385196825f4
[ "MIT" ]
49
2016-03-16T04:36:47.000Z
2022-03-28T09:26:14.000Z
18.194444
64
0.601804
995,270
package com.xmomen.module.base.model; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; public class ItemModel implements Serializable { private Integer id; /** * 产品编号 */ private String itemCode; /** * 产品归属的类别 */ private Integer cdCategoryId; private String categoryName; /** * 产品名称 */ private String itemName; /** * 产品描述 */ private String itemDescribe; /** * 产品类型 */ private Integer itemType; /** * 生产地 */ private String yieldly; /** * 产品规格 */ private String spec; /** * 基础价格 */ private BigDecimal basePrice; /** * 会员价格 */ private BigDecimal memberPrice; /** * 计价方式 */ private String pricingManner; /** * 0-下架 1-上架 */ private Integer sellStatus; /** * 销售单位 */ private String sellUnit; /** * 销售金额 */ private BigDecimal sellPrice; /** * 折扣价格 */ private BigDecimal discountPrice; /** * 0-未审核,1-审核 */ private Integer isAudit; /** * 录入时间 */ private Date createDateTime; /** * 录入人 */ private String createUserCode; /** * 采摘人 */ private String caizaiUser; /** * 检测人 */ private String jianceUser; /** * 农残率 */ private String nongCanLv; /** * 营养成分 */ private String yiYangChenFen; /** * 保质期 */ private Integer baoZhiQi; /** * 适应人群 */ private String shiYiRenQun; /** * 限时抢购 */ private Integer xianShiQiangGou; /** * 新品尝鲜 */ private Integer xinPinChangXian; /** * 热卖推荐 */ private Integer reMaiTuiJian; private Integer itemDetailId; private String itemDetailContent; //库存 private Integer stockNum; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getItemCode() { return itemCode; } public void setItemCode(String itemCode) { this.itemCode = itemCode; } public Integer getCdCategoryId() { return cdCategoryId; } public void setCdCategoryId(Integer cdCategoryId) { this.cdCategoryId = cdCategoryId; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public String getItemDescribe() { return itemDescribe; } public void setItemDescribe(String itemDescribe) { this.itemDescribe = itemDescribe; } public Integer getItemType() { return itemType; } public void setItemType(Integer itemType) { this.itemType = itemType; } public String getYieldly() { return yieldly; } public void setYieldly(String yieldly) { this.yieldly = yieldly; } public String getSpec() { return spec; } public void setSpec(String spec) { this.spec = spec; } public BigDecimal getBasePrice() { return basePrice; } public void setBasePrice(BigDecimal basePrice) { this.basePrice = basePrice; } public BigDecimal getMemberPrice() { return memberPrice; } public void setMemberPrice(BigDecimal memberPrice) { this.memberPrice = memberPrice; } public String getPricingManner() { return pricingManner; } public void setPricingManner(String pricingManner) { this.pricingManner = pricingManner; } public Integer getSellStatus() { return sellStatus; } public void setSellStatus(Integer sellStatus) { this.sellStatus = sellStatus; } public String getSellUnit() { return sellUnit; } public void setSellUnit(String sellUnit) { this.sellUnit = sellUnit; } public BigDecimal getSellPrice() { return sellPrice; } public void setSellPrice(BigDecimal sellPrice) { this.sellPrice = sellPrice; } public Integer getIsAudit() { return isAudit; } public void setIsAudit(Integer isAudit) { this.isAudit = isAudit; } public Date getCreateDateTime() { return createDateTime; } public void setCreateDateTime(Date createDateTime) { this.createDateTime = createDateTime; } public String getCreateUserCode() { return createUserCode; } public void setCreateUserCode(String createUserCode) { this.createUserCode = createUserCode; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public BigDecimal getDiscountPrice() { return discountPrice; } public void setDiscountPrice(BigDecimal discountPrice) { this.discountPrice = discountPrice; } public String getCaizaiUser() { return caizaiUser; } public void setCaizaiUser(String caizaiUser) { this.caizaiUser = caizaiUser; } public String getJianceUser() { return jianceUser; } public void setJianceUser(String jianceUser) { this.jianceUser = jianceUser; } public String getNongCanLv() { return nongCanLv; } public void setNongCanLv(String nongCanLv) { this.nongCanLv = nongCanLv; } public String getYiYangChenFen() { return yiYangChenFen; } public void setYiYangChenFen(String yiYangChenFen) { this.yiYangChenFen = yiYangChenFen; } public Integer getBaoZhiQi() { return baoZhiQi; } public void setBaoZhiQi(Integer baoZhiQi) { this.baoZhiQi = baoZhiQi; } public String getShiYiRenQun() { return shiYiRenQun; } public void setShiYiRenQun(String shiYiRenQun) { this.shiYiRenQun = shiYiRenQun; } public Integer getXianShiQiangGou() { return xianShiQiangGou; } public void setXianShiQiangGou(Integer xianShiQiangGou) { this.xianShiQiangGou = xianShiQiangGou; } public Integer getXinPinChangXian() { return xinPinChangXian; } public void setXinPinChangXian(Integer xinPinChangXian) { this.xinPinChangXian = xinPinChangXian; } public Integer getReMaiTuiJian() { return reMaiTuiJian; } public void setReMaiTuiJian(Integer reMaiTuiJian) { this.reMaiTuiJian = reMaiTuiJian; } public Integer getItemDetailId() { return itemDetailId; } public void setItemDetailId(Integer itemDetailId) { this.itemDetailId = itemDetailId; } public String getItemDetailContent() { return itemDetailContent; } public void setItemDetailContent(String itemDetailContent) { this.itemDetailContent = itemDetailContent; } public Integer getStockNum() { return stockNum; } public void setStockNum(Integer stockNum) { this.stockNum = stockNum; } }
922fd3c3c73efaddbc6125c2eecefc0bcba8d59a
560
java
Java
src/main/java/com/scalors/parser/JaxbParser.java
voksus/webparser
f1b0bfbbf2aa17238147cb9b32316cfb34fb9d7c
[ "Apache-2.0" ]
null
null
null
src/main/java/com/scalors/parser/JaxbParser.java
voksus/webparser
f1b0bfbbf2aa17238147cb9b32316cfb34fb9d7c
[ "Apache-2.0" ]
null
null
null
src/main/java/com/scalors/parser/JaxbParser.java
voksus/webparser
f1b0bfbbf2aa17238147cb9b32316cfb34fb9d7c
[ "Apache-2.0" ]
null
null
null
28
79
0.732143
995,271
package com.scalors.parser; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import java.io.File; /** * Created by voksus on 25.05.2017. */ public class JaxbParser { public static void saveObject(Object o, File file) throws JAXBException { JAXBContext context = JAXBContext.newInstance(o.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.marshal(o, file); } }
922fd540437ea599a256b9953f1bb2ca83bceff4
199
java
Java
src/main/java/com/youyu/leetcode/ListNode.java
glfmslf/leetcode
2bfafc6eca0f1f27796d7bf908f988bd548ca41c
[ "Apache-2.0" ]
null
null
null
src/main/java/com/youyu/leetcode/ListNode.java
glfmslf/leetcode
2bfafc6eca0f1f27796d7bf908f988bd548ca41c
[ "Apache-2.0" ]
null
null
null
src/main/java/com/youyu/leetcode/ListNode.java
glfmslf/leetcode
2bfafc6eca0f1f27796d7bf908f988bd548ca41c
[ "Apache-2.0" ]
null
null
null
14.214286
31
0.577889
995,272
package com.youyu.leetcode; /** * @author: youyu 工号:1552 * CREATED_DATE: 2019/6/5 11:52 */ public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
922fd6d288d94953537aea8e431479eee510cff2
1,209
java
Java
src/main/java/com/github/httpflowlabs/httpflow/console/session/ConsoleSession.java
soungminjoo/httpflow-console
dc3e7a4875ca750dcdb27f2b2c6e0762891a8cbd
[ "MIT" ]
null
null
null
src/main/java/com/github/httpflowlabs/httpflow/console/session/ConsoleSession.java
soungminjoo/httpflow-console
dc3e7a4875ca750dcdb27f2b2c6e0762891a8cbd
[ "MIT" ]
null
null
null
src/main/java/com/github/httpflowlabs/httpflow/console/session/ConsoleSession.java
soungminjoo/httpflow-console
dc3e7a4875ca750dcdb27f2b2c6e0762891a8cbd
[ "MIT" ]
null
null
null
29.487805
82
0.755997
995,273
package com.github.httpflowlabs.httpflow.console.session; import com.github.httpflowlabs.httpflow.HttpFlow; import com.github.httpflowlabs.httpflow.console.storage.FileWrapper; import com.github.httpflowlabs.httpflow.console.storage.LogicalFolderWrapper; import com.github.httpflowlabs.httpflow.console.storage.PhysicalDiskFolderWrapper; import com.github.httpflowlabs.httpflow.console.storage.FolderWrapper; import lombok.Getter; import lombok.Setter; @Getter @Setter public class ConsoleSession { public static final ConsoleSession INSTANCE = new ConsoleSession(); private HttpFlow httpFlow; private boolean isPhysicalDiskMode; private FolderWrapper navigatorPath; private FileWrapper fileViewerPath; private ConsoleSession() { setPhysicalDiskMode(false); } public void setPhysicalDiskMode(boolean isPhysicalDiskMode) { this.isPhysicalDiskMode = isPhysicalDiskMode; if (isPhysicalDiskMode) { navigatorPath = new PhysicalDiskFolderWrapper(); } else { navigatorPath = new LogicalFolderWrapper(); } } public boolean isNavigatorInRootFolder() { return navigatorPath.isRootFolder(); } }
922fd6ee4957ae49c238c5f2c7a8b4f47d578dcb
3,170
java
Java
xiaomaigou_manager_web/src/main/java/com/xiaomaigou/manager/controller/ItemCatController.java
xiaomaiyun/xiaomaigou_parent
321395c28f70c3ade7bc15bd6088b48999126891
[ "MIT" ]
null
null
null
xiaomaigou_manager_web/src/main/java/com/xiaomaigou/manager/controller/ItemCatController.java
xiaomaiyun/xiaomaigou_parent
321395c28f70c3ade7bc15bd6088b48999126891
[ "MIT" ]
null
null
null
xiaomaigou_manager_web/src/main/java/com/xiaomaigou/manager/controller/ItemCatController.java
xiaomaiyun/xiaomaigou_parent
321395c28f70c3ade7bc15bd6088b48999126891
[ "MIT" ]
2
2018-09-27T09:38:35.000Z
2019-12-31T02:08:15.000Z
23.308824
141
0.610726
995,274
package com.xiaomaigou.manager.controller; import com.alibaba.dubbo.config.annotation.Reference; import com.xiaomaigou.pojo.TbItemCat; import com.xiaomaigou.sellergoods.service.ItemCatService; import entity.PageResult; import entity.Result; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * Controller * * @author root */ //此处使用RestController,RestController相当于@Controller和@ResponseBody,这样就不用在每个方法上都写了@ResponseBody,这样可以少写很多代码,@ResponseBody表示该返回值为直接输出,如果不加则表示返回的是页面 @RestController @RequestMapping("/itemCat") public class ItemCatController { //注意:这里必须使用com.alibaba.dubbo.config.annotation.Reference;因为它远程调用,而不是本地调用,不能使用@Autowired注入,也叫远程注入 //测试过程中发现,该类中的saveItemCatToRedis方法由于要查询全部商品分类并写入缓存,花费时间较长,所以此处修改为50秒 @Reference(timeout = 50000) private ItemCatService itemCatService; /** * 返回全部列表 * * @return */ @RequestMapping("/findAll") public List<TbItemCat> findAll() { return itemCatService.findAll(); } /** * 返回全部列表 * * @return */ @RequestMapping("/findPage") public PageResult findPage(int page, int rows) { return itemCatService.findPage(page, rows); } /** * 增加 * * @param itemCat * @return */ @RequestMapping("/add") public Result add(@RequestBody TbItemCat itemCat) { try { itemCatService.add(itemCat); return new Result(true, "增加成功"); } catch (Exception e) { e.printStackTrace(); return new Result(false, "增加失败"); } } /** * 修改 * * @param itemCat * @return */ @RequestMapping("/update") public Result update(@RequestBody TbItemCat itemCat) { try { itemCatService.update(itemCat); return new Result(true, "修改成功"); } catch (Exception e) { e.printStackTrace(); return new Result(false, "修改失败"); } } /** * 获取实体 * * @param id * @return */ @RequestMapping("/findOne") public TbItemCat findOne(Long id) { return itemCatService.findOne(id); } /** * 批量删除 * * @param ids * @return */ @RequestMapping("/delete") public Result delete(Long[] ids) { try { itemCatService.delete(ids); return new Result(true, "删除成功"); } catch (Exception e) { e.printStackTrace(); return new Result(false, "删除失败"); } } /** * 查询+分页 * * @param page * @param rows * @return */ @RequestMapping("/search") public PageResult search(@RequestBody TbItemCat itemCat, int page, int rows) { return itemCatService.findPage(itemCat, page, rows); } /** * 根据上级ID查询商品分类列表 * @param parentId * @return */ @RequestMapping("/findByParentId") public List<TbItemCat> findByParentId(Long parentId){ return itemCatService.findByParentId(parentId); } }
922fd8e685d5e6485d31fb982b4c3dad989c3c1d
12,885
java
Java
aws-java-sdk-shield/src/main/java/com/amazonaws/services/shield/model/ListAttacksRequest.java
DamonTung/aws-sdk-java
e33012aea76a1cc18866120d0c53fd593b2cf550
[ "Apache-2.0" ]
1
2019-02-08T15:23:16.000Z
2019-02-08T15:23:16.000Z
aws-java-sdk-shield/src/main/java/com/amazonaws/services/shield/model/ListAttacksRequest.java
DamonTung/aws-sdk-java
e33012aea76a1cc18866120d0c53fd593b2cf550
[ "Apache-2.0" ]
1
2020-09-21T09:46:45.000Z
2020-09-21T09:46:45.000Z
aws-java-sdk-shield/src/main/java/com/amazonaws/services/shield/model/ListAttacksRequest.java
erbrito/aws-java-sdk
853b7e82d708465aca43c6013ab1221ce4d50852
[ "Apache-2.0" ]
2
2017-10-05T10:52:18.000Z
2018-10-19T09:13:12.000Z
33.123393
120
0.609313
995,275
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.shield.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/shield-2016-06-02/ListAttacks" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListAttacksRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The ARN (Amazon Resource Name) of the resource that was attacked. If this is left blank, all applicable resources * for this account will be included. * </p> */ private java.util.List<String> resourceArns; /** * <p> * The time period for the attacks. * </p> */ private TimeRange startTime; /** * <p> * The end of the time period for the attacks. * </p> */ private TimeRange endTime; /** * <p> * The <code>ListAttacksRequest.NextMarker</code> value from a previous call to <code>ListAttacksRequest</code>. * Pass null if this is the first call. * </p> */ private String nextToken; /** * <p> * The maximum number of <a>AttackSummary</a> objects to be returned. If this is left blank, the first 20 results * will be returned. * </p> */ private Integer maxResults; /** * <p> * The ARN (Amazon Resource Name) of the resource that was attacked. If this is left blank, all applicable resources * for this account will be included. * </p> * * @return The ARN (Amazon Resource Name) of the resource that was attacked. If this is left blank, all applicable * resources for this account will be included. */ public java.util.List<String> getResourceArns() { return resourceArns; } /** * <p> * The ARN (Amazon Resource Name) of the resource that was attacked. If this is left blank, all applicable resources * for this account will be included. * </p> * * @param resourceArns * The ARN (Amazon Resource Name) of the resource that was attacked. If this is left blank, all applicable * resources for this account will be included. */ public void setResourceArns(java.util.Collection<String> resourceArns) { if (resourceArns == null) { this.resourceArns = null; return; } this.resourceArns = new java.util.ArrayList<String>(resourceArns); } /** * <p> * The ARN (Amazon Resource Name) of the resource that was attacked. If this is left blank, all applicable resources * for this account will be included. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setResourceArns(java.util.Collection)} or {@link #withResourceArns(java.util.Collection)} if you want to * override the existing values. * </p> * * @param resourceArns * The ARN (Amazon Resource Name) of the resource that was attacked. If this is left blank, all applicable * resources for this account will be included. * @return Returns a reference to this object so that method calls can be chained together. */ public ListAttacksRequest withResourceArns(String... resourceArns) { if (this.resourceArns == null) { setResourceArns(new java.util.ArrayList<String>(resourceArns.length)); } for (String ele : resourceArns) { this.resourceArns.add(ele); } return this; } /** * <p> * The ARN (Amazon Resource Name) of the resource that was attacked. If this is left blank, all applicable resources * for this account will be included. * </p> * * @param resourceArns * The ARN (Amazon Resource Name) of the resource that was attacked. If this is left blank, all applicable * resources for this account will be included. * @return Returns a reference to this object so that method calls can be chained together. */ public ListAttacksRequest withResourceArns(java.util.Collection<String> resourceArns) { setResourceArns(resourceArns); return this; } /** * <p> * The time period for the attacks. * </p> * * @param startTime * The time period for the attacks. */ public void setStartTime(TimeRange startTime) { this.startTime = startTime; } /** * <p> * The time period for the attacks. * </p> * * @return The time period for the attacks. */ public TimeRange getStartTime() { return this.startTime; } /** * <p> * The time period for the attacks. * </p> * * @param startTime * The time period for the attacks. * @return Returns a reference to this object so that method calls can be chained together. */ public ListAttacksRequest withStartTime(TimeRange startTime) { setStartTime(startTime); return this; } /** * <p> * The end of the time period for the attacks. * </p> * * @param endTime * The end of the time period for the attacks. */ public void setEndTime(TimeRange endTime) { this.endTime = endTime; } /** * <p> * The end of the time period for the attacks. * </p> * * @return The end of the time period for the attacks. */ public TimeRange getEndTime() { return this.endTime; } /** * <p> * The end of the time period for the attacks. * </p> * * @param endTime * The end of the time period for the attacks. * @return Returns a reference to this object so that method calls can be chained together. */ public ListAttacksRequest withEndTime(TimeRange endTime) { setEndTime(endTime); return this; } /** * <p> * The <code>ListAttacksRequest.NextMarker</code> value from a previous call to <code>ListAttacksRequest</code>. * Pass null if this is the first call. * </p> * * @param nextToken * The <code>ListAttacksRequest.NextMarker</code> value from a previous call to * <code>ListAttacksRequest</code>. Pass null if this is the first call. */ public void setNextToken(String nextToken) { this.nextToken = nextToken; } /** * <p> * The <code>ListAttacksRequest.NextMarker</code> value from a previous call to <code>ListAttacksRequest</code>. * Pass null if this is the first call. * </p> * * @return The <code>ListAttacksRequest.NextMarker</code> value from a previous call to * <code>ListAttacksRequest</code>. Pass null if this is the first call. */ public String getNextToken() { return this.nextToken; } /** * <p> * The <code>ListAttacksRequest.NextMarker</code> value from a previous call to <code>ListAttacksRequest</code>. * Pass null if this is the first call. * </p> * * @param nextToken * The <code>ListAttacksRequest.NextMarker</code> value from a previous call to * <code>ListAttacksRequest</code>. Pass null if this is the first call. * @return Returns a reference to this object so that method calls can be chained together. */ public ListAttacksRequest withNextToken(String nextToken) { setNextToken(nextToken); return this; } /** * <p> * The maximum number of <a>AttackSummary</a> objects to be returned. If this is left blank, the first 20 results * will be returned. * </p> * * @param maxResults * The maximum number of <a>AttackSummary</a> objects to be returned. If this is left blank, the first 20 * results will be returned. */ public void setMaxResults(Integer maxResults) { this.maxResults = maxResults; } /** * <p> * The maximum number of <a>AttackSummary</a> objects to be returned. If this is left blank, the first 20 results * will be returned. * </p> * * @return The maximum number of <a>AttackSummary</a> objects to be returned. If this is left blank, the first 20 * results will be returned. */ public Integer getMaxResults() { return this.maxResults; } /** * <p> * The maximum number of <a>AttackSummary</a> objects to be returned. If this is left blank, the first 20 results * will be returned. * </p> * * @param maxResults * The maximum number of <a>AttackSummary</a> objects to be returned. If this is left blank, the first 20 * results will be returned. * @return Returns a reference to this object so that method calls can be chained together. */ public ListAttacksRequest withMaxResults(Integer maxResults) { setMaxResults(maxResults); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getResourceArns() != null) sb.append("ResourceArns: ").append(getResourceArns()).append(","); if (getStartTime() != null) sb.append("StartTime: ").append(getStartTime()).append(","); if (getEndTime() != null) sb.append("EndTime: ").append(getEndTime()).append(","); if (getNextToken() != null) sb.append("NextToken: ").append(getNextToken()).append(","); if (getMaxResults() != null) sb.append("MaxResults: ").append(getMaxResults()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListAttacksRequest == false) return false; ListAttacksRequest other = (ListAttacksRequest) obj; if (other.getResourceArns() == null ^ this.getResourceArns() == null) return false; if (other.getResourceArns() != null && other.getResourceArns().equals(this.getResourceArns()) == false) return false; if (other.getStartTime() == null ^ this.getStartTime() == null) return false; if (other.getStartTime() != null && other.getStartTime().equals(this.getStartTime()) == false) return false; if (other.getEndTime() == null ^ this.getEndTime() == null) return false; if (other.getEndTime() != null && other.getEndTime().equals(this.getEndTime()) == false) return false; if (other.getNextToken() == null ^ this.getNextToken() == null) return false; if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false; if (other.getMaxResults() == null ^ this.getMaxResults() == null) return false; if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getResourceArns() == null) ? 0 : getResourceArns().hashCode()); hashCode = prime * hashCode + ((getStartTime() == null) ? 0 : getStartTime().hashCode()); hashCode = prime * hashCode + ((getEndTime() == null) ? 0 : getEndTime().hashCode()); hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode()); hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode()); return hashCode; } @Override public ListAttacksRequest clone() { return (ListAttacksRequest) super.clone(); } }
922fd8fe8f19446984119986cfd9c1bb644681ac
2,504
java
Java
src/main/java/mcjty/immcraft/network/PacketHitBlock.java
Jorch72/ImmersiveCraft
7070b78ceca3ee6009267660098c37a3c90612ef
[ "MIT" ]
null
null
null
src/main/java/mcjty/immcraft/network/PacketHitBlock.java
Jorch72/ImmersiveCraft
7070b78ceca3ee6009267660098c37a3c90612ef
[ "MIT" ]
null
null
null
src/main/java/mcjty/immcraft/network/PacketHitBlock.java
Jorch72/ImmersiveCraft
7070b78ceca3ee6009267660098c37a3c90612ef
[ "MIT" ]
null
null
null
38.523077
155
0.713259
995,276
package mcjty.immcraft.network; import io.netty.buffer.ByteBuf; import mcjty.immcraft.blocks.generic.GenericBlockWithTE; import mcjty.immcraft.varia.BlockPosTools; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; public class PacketHitBlock implements IMessage { private BlockPos blockPos; private EnumFacing side; private Vec3 hitVec; @Override public void fromBytes(ByteBuf buf) { blockPos = new BlockPos(buf.readInt(), buf.readInt(), buf.readInt()); side = EnumFacing.values()[buf.readShort()]; hitVec = new Vec3(buf.readDouble(), buf.readDouble(), buf.readDouble()); } @Override public void toBytes(ByteBuf buf) { BlockPosTools.toBytes(blockPos, buf); buf.writeShort(side.ordinal()); buf.writeDouble(hitVec.xCoord); buf.writeDouble(hitVec.yCoord); buf.writeDouble(hitVec.zCoord); } public PacketHitBlock() { } public PacketHitBlock(MovingObjectPosition mouseOver) { blockPos = mouseOver.getBlockPos(); side = mouseOver.sideHit; hitVec = new Vec3(mouseOver.hitVec.xCoord - blockPos.getX(), mouseOver.hitVec.yCoord - blockPos.getY(), mouseOver.hitVec.zCoord - blockPos.getZ()); } public static class Handler implements IMessageHandler<PacketHitBlock, IMessage> { @Override public IMessage onMessage(PacketHitBlock message, MessageContext ctx) { MinecraftServer.getServer().addScheduledTask(() -> handle(message, ctx)); return null; } private void handle(PacketHitBlock message, MessageContext ctx) { EntityPlayerMP player = ctx.getServerHandler().playerEntity; Block block = player.worldObj.getBlockState(message.blockPos).getBlock(); if (block instanceof GenericBlockWithTE) { GenericBlockWithTE genericBlockWithTE = (GenericBlockWithTE) block; genericBlockWithTE.onClick(player.worldObj, message.blockPos, player, message.side, message.hitVec); } } } }
922fd9dfe1495caa2563d1646edebbda27c650f3
945
java
Java
Text Adventure/items/Scenery.java
manitscold123/Sentinel
d60e52ce9dcf4d753a4ead9b9657ce015f14ea27
[ "MIT" ]
1
2018-03-20T05:48:01.000Z
2018-03-20T05:48:01.000Z
Text Adventure/items/Scenery.java
manitscold123/sentinel
d60e52ce9dcf4d753a4ead9b9657ce015f14ea27
[ "MIT" ]
null
null
null
Text Adventure/items/Scenery.java
manitscold123/sentinel
d60e52ce9dcf4d753a4ead9b9657ce015f14ea27
[ "MIT" ]
null
null
null
30.483871
84
0.714286
995,277
package items; import textadventure.World; /** * Scenery objects are NON-TAKEABLE items meant to be added to rooms to match things * mentioned in a room description. For example, if the current room is "CITY PARK" * and the room description says * * "In the middle of the park stands a lonely tree. Off in the distance you see * icecaps on snowy mountain." * * then you should probably make a Scenery object for the Tree and a Scenery object * for the mountains so that the viewer can "examine" them but not interact with * them or pick them up. */ public class Scenery extends Item { /** * A Scenery object is an NON-TAKEABLE Item. See description above. */ public Scenery(World world, String name, int weight, String description) { super(world, name, weight, Item.NOT_TAKEABLE, description); } @Override public void doUse() { World.print("The " + getName() + " just sits there. Nothing happens.\n\n"); } }
922fdbbbead71ee0bd226f604b44033b83bbd2d1
248
java
Java
src/com/wildelake/battleship/Main.java
csivwildelake/battleship
697944b065499ee469c9ce46bfa8f57d888997f2
[ "MIT" ]
null
null
null
src/com/wildelake/battleship/Main.java
csivwildelake/battleship
697944b065499ee469c9ce46bfa8f57d888997f2
[ "MIT" ]
null
null
null
src/com/wildelake/battleship/Main.java
csivwildelake/battleship
697944b065499ee469c9ce46bfa8f57d888997f2
[ "MIT" ]
null
null
null
13.777778
42
0.612903
995,278
package com.wildelake.battleship; public class Main { public Main() { // TODO Auto-generated constructor stub } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } }
922fdcaad104ac11bad9b3fdcf5688f221c5bc75
1,268
java
Java
src/test/java/io/byzaneo/initializer/facet/GitHubTest.java
Byzaneo/initializer
fc931585cbb825d06049ff861ae0074aeacac514
[ "Apache-2.0" ]
null
null
null
src/test/java/io/byzaneo/initializer/facet/GitHubTest.java
Byzaneo/initializer
fc931585cbb825d06049ff861ae0074aeacac514
[ "Apache-2.0" ]
null
null
null
src/test/java/io/byzaneo/initializer/facet/GitHubTest.java
Byzaneo/initializer
fc931585cbb825d06049ff861ae0074aeacac514
[ "Apache-2.0" ]
null
null
null
25.877551
82
0.647476
995,279
package io.byzaneo.initializer.facet; import org.junit.Test; import static org.junit.Assert.assertEquals; public class GitHubTest { @Test public void testSlugOrganization() { assertEquals("my-org/my-repo", new GitHub("my-org", "my-repo").getSlug()); } @Test public void testSlugUsername() { assertEquals("me/my-repo", new GitHub("me", null, "my-repo").getSlug()); } @Test(expected = IllegalArgumentException.class) public void testSlugNone() { new GitHub().getSlug(); } @Test(expected = IllegalArgumentException.class) public void testSlugOrganizationAndNoName() { new GitHub("my-org", null).getSlug(); } @Test(expected = IllegalArgumentException.class) public void testSlugUsernameAndNoName() { new GitHub("me", null, null).getSlug(); } @Test(expected = IllegalArgumentException.class) public void testSlugNoUsername() { new GitHub(null, null, "any").getSlug(); } @Test(expected = IllegalArgumentException.class) public void testSlugNoOrganization() { new GitHub(null, "any").getSlug(); } @Test public void testToMap() { System.out.println(new GitHub("me", "secret", "repo").toProperties()); } }
922fdd6c31c81fd3ce078c8bed93e37df74660b3
2,411
java
Java
src/test/java/za/co/jesseleresche/controller/UserControllerTest.java
JesseLeresche/Playlistr
12d650baf190a203398ddaa4ecc3d3a08547630d
[ "Unlicense" ]
null
null
null
src/test/java/za/co/jesseleresche/controller/UserControllerTest.java
JesseLeresche/Playlistr
12d650baf190a203398ddaa4ecc3d3a08547630d
[ "Unlicense" ]
null
null
null
src/test/java/za/co/jesseleresche/controller/UserControllerTest.java
JesseLeresche/Playlistr
12d650baf190a203398ddaa4ecc3d3a08547630d
[ "Unlicense" ]
null
null
null
37.671875
110
0.779345
995,280
package za.co.jesseleresche.controller; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import za.co.jesseleresche.model.User; import za.co.jesseleresche.service.UserService; import static org.mockito.BDDMockito.given; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static za.co.jesseleresche.helper.DataCreationHelper.createUser; /** * This class tests the User Controller to ensure that it provides the required * responses to the various endpoints on available. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class UserControllerTest { private WebApplicationContext context; private MockMvc mockMvc; @MockBean private UserService userService; @Before public void setUp() throws Exception { mockMvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); } @Test public void testGetUser() throws Exception { User testUser = createUser(); given(userService.getUser()).willReturn(testUser); mockMvc.perform(get("/user/me").with(user("user."))) .andExpect(status().isOk()) .andExpect(model().attribute("user", testUser)) .andExpect(view().name("user")); } @Autowired public void setContext(WebApplicationContext context) { this.context = context; } }
922fdd8c23ccab25b60d6f1235e7800b9439506c
4,122
java
Java
ripple-openehr/src/main/java/org/rippleosi/patient/mdtreports/store/OpenEHRMDTReportStore.java
viktor219/Ripple-Middleware
e064c01155ab502e8df83a231e65b49a91932d24
[ "Apache-2.0" ]
1
2018-05-14T08:56:16.000Z
2018-05-14T08:56:16.000Z
ripple-openehr/src/main/java/org/rippleosi/patient/mdtreports/store/OpenEHRMDTReportStore.java
viktor219/Ripple-Middleware
e064c01155ab502e8df83a231e65b49a91932d24
[ "Apache-2.0" ]
null
null
null
ripple-openehr/src/main/java/org/rippleosi/patient/mdtreports/store/OpenEHRMDTReportStore.java
viktor219/Ripple-Middleware
e064c01155ab502e8df83a231e65b49a91932d24
[ "Apache-2.0" ]
null
null
null
46.840909
131
0.766133
995,281
/* * Copyright 2015 Ripple OSI * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.rippleosi.patient.mdtreports.store; import java.util.HashMap; import java.util.Map; import org.apache.camel.Consume; import org.rippleosi.common.service.AbstractOpenEhrService; import org.rippleosi.common.service.strategies.store.CreateStrategy; import org.rippleosi.common.service.strategies.store.DefaultStoreStrategy; import org.rippleosi.common.service.strategies.store.UpdateStrategy; import org.rippleosi.common.util.DateFormatter; import org.rippleosi.patient.mdtreports.model.MDTReportDetails; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; /** */ @Service public class OpenEHRMDTReportStore extends AbstractOpenEhrService implements MDTReportStore { @Value("${c4hOpenEHR.mdtReportTemplate}") private String mdtReportTemplate; @Override @Consume(uri = "activemq:Consumer.C4HOpenEHR.VirtualTopic.Marand.MDTReport.Create") public void create(String patientId, MDTReportDetails mdtReport) { Map<String, Object> content = createFlatJsonContent(mdtReport); CreateStrategy createStrategy = new DefaultStoreStrategy(patientId, mdtReportTemplate, content); createData(createStrategy); } @Override @Consume(uri = "activemq:Consumer.C4HOpenEHR.VirtualTopic.Marand.MDTReport.Update") public void update(String patientId, MDTReportDetails mdtReport) { Map<String, Object> content = createFlatJsonContent(mdtReport); UpdateStrategy updateStrategy = new DefaultStoreStrategy(mdtReport.getSourceId(), patientId, mdtReportTemplate, content); updateData(updateStrategy); } private Map<String, Object> createFlatJsonContent(MDTReportDetails mdtReport) { Map<String, Object> content = new HashMap<>(); content.put("ctx/language", "en"); content.put("ctx/territory", "GB"); String meetingTime = DateFormatter.combineDateTime(mdtReport.getDateOfMeeting(), mdtReport.getTimeOfMeeting()); content.put("mdt_output_report/history/question_to_mdt/question_to_mdt", mdtReport.getQuestion()); content.put("mdt_output_report/plan_and_requested_actions/recommendation/meeting_notes", mdtReport.getNotes()); content.put("mdt_output_report/context/start_time", DateFormatter.toString(mdtReport.getDateOfRequest())); content.put("mdt_output_report/referral_details/mdt_referral/narrative", "MDT Referral"); content.put("mdt_output_report/referral_details/mdt_referral/mdt_team", mdtReport.getServiceTeam()); content.put("mdt_output_report/referral_details/mdt_referral/request:0/service_requested", "MDT referral"); content.put("mdt_output_report/referral_details/mdt_referral/request:0/timing", meetingTime); content.put("mdt_output_report/referral_details/mdt_referral/request:0/timing|formalism", "timing"); content.put("mdt_output_report/referral_details/referral_tracking/referred_service", "MDT referral"); content.put("mdt_output_report/referral_details/referral_tracking/ism_transition/current_state|code", "526"); content.put("mdt_output_report/referral_details/referral_tracking/ism_transition/current_state|value", "planned"); content.put("mdt_output_report/referral_details/referral_tracking/ism_transition/careflow_step|code", "at0002"); content.put("mdt_output_report/referral_details/referral_tracking/ism_transition/careflow_step|value", "Referral planned"); return content; } }
922fde1b0b8c97774369305bdb6e8164808acd99
6,933
java
Java
Application/src/main/java/com/iss/android/wearable/datalayer/UserParameters.java
InformationServiceSystems/tukana_mobile
d020270684b16219799e35f2184e049db36521aa
[ "Apache-2.0" ]
null
null
null
Application/src/main/java/com/iss/android/wearable/datalayer/UserParameters.java
InformationServiceSystems/tukana_mobile
d020270684b16219799e35f2184e049db36521aa
[ "Apache-2.0" ]
null
null
null
Application/src/main/java/com/iss/android/wearable/datalayer/UserParameters.java
InformationServiceSystems/tukana_mobile
d020270684b16219799e35f2184e049db36521aa
[ "Apache-2.0" ]
null
null
null
27.843373
110
0.52416
995,282
package com.iss.android.wearable.datalayer; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import static com.iss.android.wearable.datalayer.DateTimeManager.getDateFromToday; /** * Created by Euler on 1/23/2016. */ public class UserParameters { public UserParameters(int timespan) { // load RPE if available // compute the timespan TimeSeries userRPE = new TimeSeries("User RPE"); TimeSeries userDALDA = new TimeSeries("User DALDA"); TimeSeries alpha = new TimeSeries("Alpha, all data"); TimeSeries alpha2min = new TimeSeries("Alpha, 2 min training"); TimeSeries userDS = new TimeSeries("Deep sleep"); for (int i = 0; i < timespan; i++) { try { int percent = i * 100 / timespan; Date date = getDateFromToday(i); DailyData dailyData = new DailyData(date); if (dailyData.getDALDA() != null) { userDALDA.AddFirstValue(date, dailyData.getDALDA()); } if (dailyData.getRPE() != null) { userRPE.AddFirstValue(date, dailyData.getRPE()); } if (dailyData.getAlpha2min() != null) { alpha2min.AddFirstValue(date, dailyData.getAlpha2min()); } if (dailyData.getAlphaAllData() != null) { alpha.AddFirstValue(date, dailyData.getAlphaAllData()); } if (dailyData.getDeepSleep() != null) { userDS.AddFirstValue(date, dailyData.getDeepSleep()); } } catch (Exception ex) { DataSyncService.OutputEventSq(ex.toString()); } //DataSyncService.OutputEventSq("100%"); } } // Deletes values in bins where counts is <=0 public void smoothenBins(double[] bins, double[] counts) { double cv = 0; for (int i = 0; i < bins.length; i++) { if (counts[i] > 0) { cv = bins[i]; } bins[i] = cv; } for (int i = bins.length - 1; i >= 0; i--) { if (counts[i] > 0) { cv = bins[i]; } bins[i] = cv; } } // Another method which only computes the date given a certain date and an offset. public Date offsetDate(Date input, int offset) { Calendar clnd = Calendar.getInstance(); clnd.setTime(input); clnd.add(Calendar.DAY_OF_MONTH, -offset); return clnd.getTime(); } // Produces a predictive TimeSeries given actual timeseries. public TimeSeries predictTimeSeries(TimeSeries xReq, TimeSeries xActual, TimeSeries yActual, int offset) { TimeSeries result = new TimeSeries(yActual.name + ", pred."); for (int i = 0; i < xReq.Values.size() - offset; i++) { Date date = xReq.Values.get(i).x; Double val = xReq.Values.get(i).y; TimeSeries xActBefore = xActual.beforeDate(date); TimeSeries yActBefore = yActual.beforeDate(date); if (xActBefore.Values.size() == 0) { continue; } HashMap<String, Double> predValues = yActBefore.toDictionary(); ArrayList<Double> xvalues = new ArrayList<>(); ArrayList<Double> yvalues = new ArrayList<>(); // generate training set for (int j = 0; j < xActBefore.Values.size(); j++) { Date locdate = offsetDate(xActBefore.Values.get(j).x, offset); double x = xActBefore.Values.get(j).y; if (!predValues.containsKey(TimeSeries.formatData(locdate))) { continue; } double y = predValues.get(TimeSeries.formatData(locdate)); xvalues.add(x); yvalues.add(y); } double prediction = predictRecovery(xvalues, yvalues, val); result.AddValue(offsetDate(date, offset), prediction); } return result; } // Predicts the recovery rate from history values. public double predictRecovery(ArrayList<Double> pastX, ArrayList<Double> pastY, Double futureX) { double result = -1; // collect values of past records into bins double[] bins = new double[11]; double[] counts = new double[11]; for (int i = 0; i < 11; i++) { bins[i] = 0; counts[i] = 0; } for (int i = 0; i < pastY.size(); i++) { if (pastX.get(i) < 0) { continue; } bins[((int) Math.round(pastX.get(i)))] += pastY.get(i); counts[((int) Math.round(pastX.get(i)))] += 1; } for (int i = 0; i < 11; i++) { if (counts[i] == 0) { continue; } bins[i] = bins[i] / counts[i]; } smoothenBins(bins, counts); result = bins[((int) Math.round(futureX))]; return result; } // Computes regulatory conformity of values to the requirements in a given timewindow private TimeSeries ComputeCompliences(TimeSeries requirements, TimeSeries values, int timewindow) { TimeSeries result = new TimeSeries(values.name + ", avg. divergence"); for (int i = 0; i < requirements.Values.size(); i++) { Date x = requirements.Values.get(i).x; TimeSeries req = requirements.beforeDate(x); TimeSeries vals = values.beforeDate(x); ArrayList<Double> seq1 = new ArrayList<>(); ArrayList<Double> seq2 = new ArrayList<>(); // construct data HashMap<String, Double> reqVals = req.toDictionary(); for (int j = 0; j < vals.Values.size(); j++) { int last = vals.Values.size() - j - 1; Date d = vals.Values.get(last).x; if (!reqVals.containsKey(TimeSeries.formatData(d))) continue; Double yp = reqVals.get(TimeSeries.formatData(d)); Double y = vals.Values.get(last).y; seq1.add(0, yp); seq2.add(0, y); if (seq1.size() >= timewindow) { break; } } if (seq1.size() == 0) { result.AddValue(x, -1); continue; } result.AddValue(x, ComplienceMeasure(seq1, seq2)); } return result; } private double ComplienceMeasure(ArrayList<Double> seq1, ArrayList<Double> seq2) { double result = 0; for (int i = 0; i < seq1.size(); i++) { result += Math.abs(seq1.get(i) - seq2.get(i)) / seq1.size(); } return result; } }
922fdf00ddc81d5fd7346251c683848521cfae11
2,307
java
Java
ood/hw/src/hw/hw3/DiningHall.java
rootulp/school
cdf7b3f261e9f0f6991a4740790c5f54747079b5
[ "MIT" ]
null
null
null
ood/hw/src/hw/hw3/DiningHall.java
rootulp/school
cdf7b3f261e9f0f6991a4740790c5f54747079b5
[ "MIT" ]
null
null
null
ood/hw/src/hw/hw3/DiningHall.java
rootulp/school
cdf7b3f261e9f0f6991a4740790c5f54747079b5
[ "MIT" ]
null
null
null
34.954545
111
0.597746
995,283
package hw.hw3; public class DiningHall { private static final int CUST_ARRIVAL_PCT = 19; // There is a 19% chance a customer arrives each second. private int NUM_NORMAL_REGISTERS; private int NUM_FAST_REGISTERS; private int NUM_TOTAL_REGISTERS; private ItemDistribution id; private CashRegister[] registers; public DiningHall(int numNormal, int numFast, ItemDistribution item) { NUM_NORMAL_REGISTERS = numNormal; NUM_FAST_REGISTERS = numFast; NUM_TOTAL_REGISTERS = numNormal + numFast; id = item; registers = new CashRegister[NUM_TOTAL_REGISTERS]; for (int r = 0; r < NUM_NORMAL_REGISTERS; r++) { Cashier normal = new NormalSpeed(); registers[r] = new CashRegister(normal); } for (int r = NUM_NORMAL_REGISTERS; r < NUM_TOTAL_REGISTERS; r++) { Cashier fast = new Fast(); registers[r] = new CashRegister(fast); } } public void elapseOneSecond(int t) { if (aCustomerArrives()) { // The new customer goes into the smaller line. int chosenRegister = shortestRegisterLine(); registers[chosenRegister].addCustomer(t, id); } for (int r = 0; r < NUM_TOTAL_REGISTERS; r++) registers[r].elapseOneSecond(t); // Simulate each register for one second. } public void printStatistics() { for (int r = 0; r < NUM_TOTAL_REGISTERS; r++) { CashRegister reg = registers[r]; System.out.println("Register " + r); System.out.println("\tNumber of arrivals = " + reg.customersServed()); System.out.println("\tAverage wait time = " + reg.avgWaitTime()); } } private boolean aCustomerArrives() { int n = (int) (Math.random() * 100); // an integer between 0 and 99 return n < CUST_ARRIVAL_PCT; } private int shortestRegisterLine() { int shortestRegister = 0; for (int r = 0; r < NUM_TOTAL_REGISTERS; r++) { //System.out.println("register: " + r + " size: " + registers[r].size()); if (registers[r].size() < registers[shortestRegister].size()) { shortestRegister = r; } } return shortestRegister; } }
922fdf696b53daaa6c6eef7829c3c7ed3f108d74
2,953
java
Java
aws-java-sdk-waf/src/main/java/com/amazonaws/services/waf/model/waf_regional/transform/CreateWebACLRequestMarshaller.java
DamonTung/aws-sdk-java
e33012aea76a1cc18866120d0c53fd593b2cf550
[ "Apache-2.0" ]
1
2019-10-17T14:03:43.000Z
2019-10-17T14:03:43.000Z
aws-java-sdk-waf/src/main/java/com/amazonaws/services/waf/model/waf_regional/transform/CreateWebACLRequestMarshaller.java
DamonTung/aws-sdk-java
e33012aea76a1cc18866120d0c53fd593b2cf550
[ "Apache-2.0" ]
null
null
null
aws-java-sdk-waf/src/main/java/com/amazonaws/services/waf/model/waf_regional/transform/CreateWebACLRequestMarshaller.java
DamonTung/aws-sdk-java
e33012aea76a1cc18866120d0c53fd593b2cf550
[ "Apache-2.0" ]
2
2017-10-05T10:52:18.000Z
2018-10-19T09:13:12.000Z
45.430769
154
0.754148
995,284
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.waf.model.waf_regional.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.waf.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * CreateWebACLRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class CreateWebACLRequestMarshaller { private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Name").build(); private static final MarshallingInfo<String> METRICNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("MetricName").build(); private static final MarshallingInfo<StructuredPojo> DEFAULTACTION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DefaultAction").build(); private static final MarshallingInfo<String> CHANGETOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ChangeToken").build(); private static final CreateWebACLRequestMarshaller instance = new CreateWebACLRequestMarshaller(); public static CreateWebACLRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(CreateWebACLRequest createWebACLRequest, ProtocolMarshaller protocolMarshaller) { if (createWebACLRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createWebACLRequest.getName(), NAME_BINDING); protocolMarshaller.marshall(createWebACLRequest.getMetricName(), METRICNAME_BINDING); protocolMarshaller.marshall(createWebACLRequest.getDefaultAction(), DEFAULTACTION_BINDING); protocolMarshaller.marshall(createWebACLRequest.getChangeToken(), CHANGETOKEN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
922fdfe5cea3cd6d644a5d12ff7acb774d5788fd
2,908
java
Java
src/main/java/ru/job4j/carssale/persistence/db/DBCarStoreController.java
sah-lob/job4j_hibernate
92723598c61ed6b19420892b2eb3b8641beee8cc
[ "Apache-2.0" ]
null
null
null
src/main/java/ru/job4j/carssale/persistence/db/DBCarStoreController.java
sah-lob/job4j_hibernate
92723598c61ed6b19420892b2eb3b8641beee8cc
[ "Apache-2.0" ]
4
2019-11-13T11:58:44.000Z
2021-01-21T02:51:15.000Z
src/main/java/ru/job4j/carssale/persistence/db/DBCarStoreController.java
sah-lob/job4j_hibernate
92723598c61ed6b19420892b2eb3b8641beee8cc
[ "Apache-2.0" ]
null
null
null
23.642276
100
0.669188
995,285
package ru.job4j.carssale.persistence.db; import ru.job4j.carssale.models.Car; import ru.job4j.carssale.models.CarFilter; import ru.job4j.carssale.models.Image; import ru.job4j.carssale.models.Person; import ru.job4j.carssale.persistence.interfaces.*; import java.util.List; public class DBCarStoreController implements CarStoreController { private final static DBCarStoreController DB_CAR_STORE_CONTROLLER = new DBCarStoreController(); public static DBCarStoreController getInstance() { return DB_CAR_STORE_CONTROLLER; } private BrandStore brandStore = DBBrandStore.getInstance(); private CarsStore carsStore = DBCarsStore.getInstance(); private ImageStore imageStore = DBImageStore.getInstance(); private UsersStore usersStore = DBUsersStore.getInstance(); @Override public void addData(Car car, String img) { addCar(car); addImg(new Image(car.getId(), img)); addBrand(car.getBrand(), car.getModel()); } // BrandStore @Override public List<String> getBrands() { return brandStore.getBrands(); } @Override public List<String> getModels(String brand) { return brandStore.getModels(brand); } @Override public void addBrand(String brand, String model) { brandStore.add(brand, model); } //ImageStore @Override public int imageSize() { return imageStore.size(); } @Override public String getImg(int id) { return imageStore.getImg(id); } @Override public void addImg(Image image) { imageStore.addImg(image); } //CarsStore @Override public void addCar(Car car) { carsStore.add(car); } @Override public Car findCar(int page, int id) { return carsStore.findCar(page, id); } @Override public int carSize() { return carsStore.size(); } @Override public List<Car> carsFindToPage(int page) { return carsStore.findToPage(page); } @Override public List<Car> carsParamFindPage(CarFilter carFilter) { return carsStore.paramFindPage(carFilter); } @Override public int carsGetParamFindPageSize(CarFilter carFilter) { return carsStore.getParamFindPageSize(carFilter); } //UsersStore @Override public boolean userIsExists(String login) { return usersStore.isExists(login); } @Override public void addPerson(Person person) { usersStore.add(person); } @Override public boolean validatePerson(Person person) { return usersStore.validatePerson(person); } @Override public Person getPerson(String login) { return usersStore.getPerson(login); } @Override public boolean editPerson(String login, String fio, String number) { return usersStore.editPerson(login, fio, number); } }
922fe0cbd177e337bfa939e8d85c95e6efa1d245
2,913
java
Java
Lab9/BankQueue/BankQueue.java
AnthonyM-ed/LabADAGrupoB
807cce1feb5c036e1e373208681df195d32379bc
[ "BSD-3-Clause" ]
null
null
null
Lab9/BankQueue/BankQueue.java
AnthonyM-ed/LabADAGrupoB
807cce1feb5c036e1e373208681df195d32379bc
[ "BSD-3-Clause" ]
null
null
null
Lab9/BankQueue/BankQueue.java
AnthonyM-ed/LabADAGrupoB
807cce1feb5c036e1e373208681df195d32379bc
[ "BSD-3-Clause" ]
null
null
null
35.52439
142
0.473395
995,286
/*Problema 3 Cuánto dinero en efectivo se puede obtener de las personas que están actualmente en la cola antes de que cierre el banco sirviendo como máximo a una persona por minuto. maxAmount(N personas, T minutos): Devuelve el máximo de dinero que se puede obtener. */ import java.util.*; public class BankQueue { private static class Person implements Comparable<Person> { //Clase Persona private int money; //monto a depositar private int time; //minutos disponibles public Person(int money, int time) { this.money = money; this.time = time; } @Override public int compareTo(Person person) { //Para poder realizar comparaciones int pm = person.money; int pt = person.time; if (money < pm) { return -1; } if (money > pm) { return 1; } if (time < pt) { return -1; } if (time > pt) { return 1; } return 0; } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N; int T; N = sc.nextInt(); T = sc.nextInt(); System.out.println(maxAmount(N, T)); } public static int maxAmount(int N, int T) { Scanner sc = new Scanner(System.in); int amount = 0; int index = 0; PriorityQueue<Person> queue = new PriorityQueue<>(N, Collections.reverseOrder()); //Cola de prioridad con comparador inverso for (int i = 0; i < N; i++) { //añadimos las personas queue.add(new Person(sc.nextInt(), sc.nextInt())); } boolean[] flags = new boolean[T]; //cada bandera representa un minuto del tiempo que estará abierto el banco Person auxPerson; while (index < N && !queue.isEmpty()) { //Recorremos las personas de la cola auxPerson = (Person) queue.poll(); //devuelve el elemento máximo de la cola int cont = auxPerson.time; //tiempo que la persona está disponible while (cont >= 0 && flags[cont]) { //Determina el tiempo que le queda a la persona cont--; } if (cont != -1) { //si la persona aún tiene tiempo index++; flags[cont] = true; //pasó un minuto amount += auxPerson.money; //se realiza el deposito } } return amount; } }
922fe2d5b00c9649302cf0e9b17c35607424249d
894
java
Java
src/main/java/com/stratio/qa/models/BaseResponseList.java
cfuertes-stratio/bdt
d25039ddee0d15c45bf9b1aea4a1d66da061de7b
[ "Apache-2.0" ]
38
2017-03-02T08:59:35.000Z
2021-08-08T21:20:08.000Z
src/main/java/com/stratio/qa/models/BaseResponseList.java
cfuertes-stratio/bdt
d25039ddee0d15c45bf9b1aea4a1d66da061de7b
[ "Apache-2.0" ]
478
2017-02-09T14:48:49.000Z
2022-03-09T15:33:04.000Z
src/main/java/com/stratio/qa/models/BaseResponseList.java
cfuertes-stratio/bdt
d25039ddee0d15c45bf9b1aea4a1d66da061de7b
[ "Apache-2.0" ]
51
2017-02-09T12:02:00.000Z
2022-03-29T10:55:48.000Z
27.090909
75
0.696868
995,287
/* * Copyright (C) 2014 Stratio (http://stratio.com) * * 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.stratio.qa.models; import java.util.List; public class BaseResponseList<T> extends BaseResponse { private List<T> list; public List<T> getList() { return list; } public void setList(List<T> list) { this.list = list; } }
922fe31c78c9232dfed87d00182045dfff77f2a2
3,271
java
Java
ApkerTest/apker/src/main/java/com/ss/android/apker/download/DownLoadService.java
LifengMr/apker
8c7d425e9ea36623823cf5fd8c6fca2c2e8a1ea3
[ "Apache-2.0" ]
4
2016-07-26T02:10:27.000Z
2016-08-02T03:45:24.000Z
ApkerTest/apker/src/main/java/com/ss/android/apker/download/DownLoadService.java
LifengMr/apker
8c7d425e9ea36623823cf5fd8c6fca2c2e8a1ea3
[ "Apache-2.0" ]
null
null
null
ApkerTest/apker/src/main/java/com/ss/android/apker/download/DownLoadService.java
LifengMr/apker
8c7d425e9ea36623823cf5fd8c6fca2c2e8a1ea3
[ "Apache-2.0" ]
null
null
null
31.152381
88
0.622745
995,288
package com.ss.android.apker.download; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import com.ss.android.apker.Apker; import com.ss.android.apker.api.ApkerFlow; import com.ss.android.apker.api.FlowCallback; import com.ss.android.apker.database.PluginDAO; import com.ss.android.apker.entity.ApkBean; import com.ss.android.apker.entity.ApkEntity; import com.ss.android.apker.helper.JLog; import com.ss.android.apker.helper.JavaHelper; import com.ss.android.apker.volley.VolleyError; import java.util.Map; public class DownLoadService extends Service implements FlowCallback<ApkBean> { public static final String TAG = DownLoadService.class.getName(); private ApkerFlow mFlow; private Map<String, ApkEntity> mPluginsMap; @Override public void onCreate() { super.onCreate(); DownLoadManager.ins().setDownLoadListener(mDownLoadListener); DownLoadManager.ins().restartTasks(this); PluginDAO pluginDAO = new PluginDAO(this); mFlow = new ApkerFlow(this); mPluginsMap = pluginDAO.getPluginsMap(); mFlow.requestPlugins(this); } @Override public void onFlowSuccess(ApkBean data) { if (mPluginsMap == null || data == null || JavaHelper.isListEmpty(data.apks)) { return; } for (ApkEntity entity : data.apks) { ApkEntity originEntity = mPluginsMap.get(entity.packageName); if (originEntity != null && originEntity.version >= entity.version) { continue; } DownLoadManager.ins().addTask(this, entity); } } @Override public void onFlowError(VolleyError error) { } @Override public void onDestroy() { super.onDestroy(); mFlow.onDestroy(); DownLoadManager.ins().stopAllTask(); DownLoadManager.ins().onDestroy(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } private DownLoadListener mDownLoadListener = new DownLoadListener() { @Override public void onStart(String taskID) { JLog.i(DownLoadManager.TAG, "onStart taskID=" + taskID); } @Override public void onProgress(ApkEntity downLoadInfo) { JLog.i(DownLoadManager.TAG, "onProgress getTaskID=" + downLoadInfo.taskID + ",getDownloadSize=" + downLoadInfo.downloadSize + ",getFilePath=" + downLoadInfo.filePath); } @Override public void onStop(String taskID) { JLog.i(DownLoadManager.TAG, "onStop taskID=" + taskID); } @Override public void onError(ApkEntity downLoadInfo) { JLog.i(DownLoadManager.TAG, "onError taskID=" + downLoadInfo.taskID); } @Override public void onSuccess(ApkEntity downLoadInfo) { JLog.i(DownLoadManager.TAG, "onSuccess taskID=" + downLoadInfo.taskID); if (downLoadInfo != null) { Apker.ins().installPlugin(downLoadInfo); } } }; }
922fe4377f49583aaf2975ee79ce25d1e6b35cc5
616
java
Java
src/main/java/com/github/draylar/betterbees/mixin/PointOfInterestTypeAccessor.java
Yoghurt4C/better-bees
fce0a0856d80cbe8adfd77b99c7f32430f2cd4f6
[ "MIT" ]
null
null
null
src/main/java/com/github/draylar/betterbees/mixin/PointOfInterestTypeAccessor.java
Yoghurt4C/better-bees
fce0a0856d80cbe8adfd77b99c7f32430f2cd4f6
[ "MIT" ]
null
null
null
src/main/java/com/github/draylar/betterbees/mixin/PointOfInterestTypeAccessor.java
Yoghurt4C/better-bees
fce0a0856d80cbe8adfd77b99c7f32430f2cd4f6
[ "MIT" ]
null
null
null
25.666667
100
0.761364
995,289
package com.github.draylar.betterbees.mixin; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.village.PointOfInterestType; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Invoker; import java.util.Set; @Mixin(PointOfInterestType.class) public interface PointOfInterestTypeAccessor { @Invoker public static PointOfInterestType invokeRegister(String id, Set<BlockState> set, int i, int j) { return null; } @Invoker public static Set<BlockState> getGetAllStatesOf(Block block) { return null; } }
922fe4429a7a49894b88334106f7c68631803346
4,066
java
Java
hamster-selenium-component-html/src/main/java/com/github/grossopa/selenium/component/html/HtmlSelect.java
grossopa/hamster-selenium
e8fe83d91507b4e878f2771f7842ca4932e6662f
[ "MIT" ]
null
null
null
hamster-selenium-component-html/src/main/java/com/github/grossopa/selenium/component/html/HtmlSelect.java
grossopa/hamster-selenium
e8fe83d91507b4e878f2771f7842ca4932e6662f
[ "MIT" ]
14
2020-12-11T05:41:46.000Z
2021-11-15T13:13:07.000Z
hamster-selenium-component-html/src/main/java/com/github/grossopa/selenium/component/html/HtmlSelect.java
grossopa/hamster-selenium
e8fe83d91507b4e878f2771f7842ca4932e6662f
[ "MIT" ]
1
2020-10-13T19:36:27.000Z
2020-10-13T19:36:27.000Z
29.678832
96
0.6879
995,290
/* * Copyright © 2021 the original author or authors. * * Licensed under the The MIT License (MIT) (the "License"); * You may obtain a copy of the License at * * https://mit-license.org/ * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the “Software”), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.github.grossopa.selenium.component.html; import com.github.grossopa.selenium.core.ComponentWebDriver; import com.github.grossopa.selenium.core.component.DefaultWebComponent; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ISelect; import org.openqa.selenium.support.ui.Select; import java.util.List; import java.util.Objects; /** * the simple HTML Select elements delegates selenium {@link Select}. * * @author Jack Yin * @since 1.0 */ public class HtmlSelect extends DefaultWebComponent implements ISelect { private final ISelect selectComponent; /** * Constructs an instance with element and driver. * * @param element the web element to wrap with, should be with tag select. * @param driver the current web driver */ public HtmlSelect(WebElement element, ComponentWebDriver driver) { super(element, driver); selectComponent = new Select(element); } @Override public boolean isMultiple() { return selectComponent.isMultiple(); } @Override public List<WebElement> getOptions() { return selectComponent.getOptions(); } @Override public List<WebElement> getAllSelectedOptions() { return selectComponent.getAllSelectedOptions(); } @Override public WebElement getFirstSelectedOption() { return selectComponent.getFirstSelectedOption(); } @Override public void selectByVisibleText(String text) { selectComponent.selectByVisibleText(text); } @Override public void selectByIndex(int index) { selectComponent.selectByIndex(index); } @Override public void selectByValue(String value) { selectComponent.selectByValue(value); } @Override public void deselectAll() { selectComponent.deselectAll(); } @Override public void deselectByValue(String value) { selectComponent.deselectByValue(value); } @Override public void deselectByIndex(int index) { selectComponent.deselectByIndex(index); } @Override public void deselectByVisibleText(String text) { selectComponent.deselectByVisibleText(text); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof HtmlSelect)) { return false; } if (!super.equals(o)) { return false; } HtmlSelect that = (HtmlSelect) o; return element.equals(that.element); } @Override public int hashCode() { return Objects.hash(super.hashCode(), element); } @Override public String toString() { return "HtmlSelect{" + "element=" + element + '}'; } }
922fe5245df23f2eb8e441f021203b2ded391139
40,479
java
Java
web-template/src/test/java/org/ehrbase/webtemplate/parser/OPTParserTest.java
ehrbase/ehrbase_client_library
dfff21cb197005b719118525347a714cb8c0354e
[ "Apache-2.0" ]
5
2020-03-10T11:25:47.000Z
2020-06-05T07:52:40.000Z
web-template/src/test/java/org/ehrbase/webtemplate/parser/OPTParserTest.java
ehrbase/ehrbase_client_library
dfff21cb197005b719118525347a714cb8c0354e
[ "Apache-2.0" ]
22
2019-12-28T07:29:05.000Z
2020-06-08T10:36:10.000Z
web-template/src/test/java/org/ehrbase/webtemplate/parser/OPTParserTest.java
ehrbase/ehrbase_client_library
dfff21cb197005b719118525347a714cb8c0354e
[ "Apache-2.0" ]
6
2019-10-15T20:37:54.000Z
2020-05-14T09:55:34.000Z
53.543651
593
0.641048
995,291
/* * Copyright (c) 2020-2022 vitasystems GmbH and Hannover Medical School. * * This file is part of project openEHR_SDK * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ehrbase.webtemplate.parser; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatNoException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.xmlbeans.XmlException; import org.assertj.core.api.SoftAssertions; import org.assertj.core.groups.Tuple; import org.ehrbase.test_data.operationaltemplate.OperationalTemplateTestData; import org.ehrbase.test_data.webtemplate.WebTemplateTestData; import org.ehrbase.webtemplate.filter.Filter; import org.ehrbase.webtemplate.model.*; import org.junit.Test; import org.openehr.schemas.v1.OPERATIONALTEMPLATE; import org.openehr.schemas.v1.TemplateDocument; /** * @author Stefan Spiska * @since 1.0 */ public class OPTParserTest { @Test public void parseCoronaAnamnese() throws IOException, XmlException { OPERATIONALTEMPLATE template = TemplateDocument.Factory.parse( OperationalTemplateTestData.CORONA_ANAMNESE.getStream()) .getTemplate(); OPTParser cut = new OPTParser(template); WebTemplate actual = cut.parse(); actual = new Filter().filter(actual); assertThat(actual).isNotNull(); ObjectMapper objectMapper = new ObjectMapper(); WebTemplate expected = objectMapper.readValue( IOUtils.toString(WebTemplateTestData.CORONA.getStream(), StandardCharsets.UTF_8), WebTemplate.class); List<String> errors = compareWebTemplate(actual, expected); checkErrors(errors, new String[] { "LocalizedNames not equal [de=event] != [de=] in inputValue.code:433 id=category aql=/category", "InContext not equal null != true in id=math_function aql=/content[openEHR-EHR-SECTION.adhoc.v1 and name/value='Risikogebiet']/items[openEHR-EHR-OBSERVATION.travel_event.v0]/data[at0001]/events[at0002]/math_function", "InContext not equal null != true in id=width aql=/content[openEHR-EHR-SECTION.adhoc.v1 and name/value='Risikogebiet']/items[openEHR-EHR-OBSERVATION.travel_event.v0]/data[at0001]/events[at0002]/width" }); } @Test public void parseTestingTemplateN() throws IOException, XmlException { OPERATIONALTEMPLATE template = TemplateDocument.Factory.parse( OperationalTemplateTestData.TESTING_TEMPLATE_N.getStream()) .getTemplate(); OPTParser cut = new OPTParser(template); WebTemplate actual = cut.parse(); actual = new Filter().filter(actual); assertThat(actual).isNotNull(); ObjectMapper objectMapper = new ObjectMapper(); WebTemplate expected = objectMapper.readValue( IOUtils.toString(WebTemplateTestData.TESTING_TEMPLATE_N.getStream(), StandardCharsets.UTF_8), WebTemplate.class); List<String> errors = compareWebTemplate(actual, expected); checkErrors(errors, new String[] { "Extra Node id=external_terminology aql=/content[openEHR-EHR-OBSERVATION.testing.v1]/data[at0001]/events[at0002]/data[at0003]/items[openEHR-EHR-CLUSTER.testing.v1]/items[at0016]/value", "Missing Node id=external_terminology aql=/content[openEHR-EHR-OBSERVATION.testing.v1]/data[at0001]/events[at0002]/data[at0003]/items[openEHR-EHR-CLUSTER.testing.v1]/items[at0016 and name/value='External terminology']/value", "InputValue not equal 1234:Hello world != 1234:null in id=testing_dv_text aql=/content[openEHR-EHR-OBSERVATION.testing.v1]/data[at0001]/events[at0002]/data[at0003]/items[openEHR-EHR-CLUSTER.testing.v1]/items[at0026]/value", "LocalizedNames not equal [en=event] != [en=event, sl=] in inputValue.code:433 id=category aql=/category", "LocalizedNames not equal [en=Hello world] != [en=, sl=] in inputValue.code:1234 id=testing_dv_text aql=/content[openEHR-EHR-OBSERVATION.testing.v1]/data[at0001]/events[at0002]/data[at0003]/items[openEHR-EHR-CLUSTER.testing.v1]/items[at0026]/value", "LocalizedDescriptions not equal {en=} != {} in inputValue.code:1234 id=testing_dv_text aql=/content[openEHR-EHR-OBSERVATION.testing.v1]/data[at0001]/events[at0002]/data[at0003]/items[openEHR-EHR-CLUSTER.testing.v1]/items[at0026]/value", "DefaultValue not equal null != 1234 in input.suffix:code id=testing_dv_text aql=/content[openEHR-EHR-OBSERVATION.testing.v1]/data[at0001]/events[at0002]/data[at0003]/items[openEHR-EHR-CLUSTER.testing.v1]/items[at0026]/value" }); } @Test public void parseGECCODiagnose() throws IOException, XmlException { OPERATIONALTEMPLATE template = TemplateDocument.Factory.parse( OperationalTemplateTestData.GECCO_DIAGNOSE.getStream()) .getTemplate(); OPTParser cut = new OPTParser(template); WebTemplate actual = cut.parse(); actual = new Filter().filter(actual); ObjectMapper objectMapper = new ObjectMapper(); WebTemplate expected = objectMapper.readValue( IOUtils.toString(WebTemplateTestData.GECCO_DIAGNOSE.getStream(), StandardCharsets.UTF_8), WebTemplate.class); List<String> errors = compareWebTemplate(actual, expected).stream() .filter(f -> !f.startsWith("LocalizedDescriptions not equal") && !f.startsWith("LocalizedNames not equal") && !f.startsWith("Annotations not equal")) .collect(Collectors.toList()); checkErrors(errors, new String[] { "Extra Input code:TEXT in id=name_des_problems_der_diagnose aql=/content[openEHR-EHR-EVALUATION.problem_diagnosis.v1 and name/value='Vorliegende Diagnose']/data[at0001]/items[at0002]/value", "Extra Input value:TEXT in id=name_des_problems_der_diagnose aql=/content[openEHR-EHR-EVALUATION.problem_diagnosis.v1 and name/value='Vorliegende Diagnose']/data[at0001]/items[at0002]/value", "Missing Input null:TEXT in id=name_des_problems_der_diagnose aql=/content[openEHR-EHR-EVALUATION.problem_diagnosis.v1 and name/value='Vorliegende Diagnose']/data[at0001]/items[at0002]/value" }); } @Test public void parseAltEvents() throws IOException, XmlException { OPERATIONALTEMPLATE template = TemplateDocument.Factory.parse( OperationalTemplateTestData.ALT_EVENTS.getStream()) .getTemplate(); OPTParser cut = new OPTParser(template); WebTemplate actual = cut.parse(); actual = new Filter().filter(actual); assertThat(actual).isNotNull(); ObjectMapper objectMapper = new ObjectMapper(); WebTemplate expected = objectMapper.readValue( IOUtils.toString(WebTemplateTestData.ALTERNATIVE_EVENTS.getStream(), StandardCharsets.UTF_8), WebTemplate.class); List<String> errors = compareWebTemplate(actual, expected); // Nodes wich are generated by the parser but are not in the example checkErrors(errors, new String[] { "LocalizedNames not equal [de=event] != [de=] in inputValue.code:433 id=category aql=/category", "Validation not equal WebTemplateValidation{precision=null, range=WebTemplateValidationInterval{min=0.0, minOp=GT_EQ, max=1000000.0, maxOp=LT_EQ}, pattern='null'} != WebTemplateValidation{precision=null, range=WebTemplateValidationInterval{min=0, minOp=GT_EQ, max=1000000, maxOp=LT_EQ}, pattern='null'} in inputValue.code:g id=gewicht aql=/content[openEHR-EHR-OBSERVATION.body_weight.v2]/data[at0002]/events[at0026]/data[at0001]/items[at0004]/value", "Validation not equal WebTemplateValidation{precision=null, range=WebTemplateValidationInterval{min=0.0, minOp=GT_EQ, max=1000.0, maxOp=LT_EQ}, pattern='null'} != WebTemplateValidation{precision=null, range=WebTemplateValidationInterval{min=0, minOp=GT_EQ, max=1000, maxOp=LT_EQ}, pattern='null'} in inputValue.code:kg id=gewicht aql=/content[openEHR-EHR-OBSERVATION.body_weight.v2]/data[at0002]/events[at0026]/data[at0001]/items[at0004]/value", "Validation not equal WebTemplateValidation{precision=null, range=WebTemplateValidationInterval{min=0.0, minOp=GT_EQ, max=2000.0, maxOp=LT_EQ}, pattern='null'} != WebTemplateValidation{precision=null, range=WebTemplateValidationInterval{min=0, minOp=GT_EQ, max=2000, maxOp=LT_EQ}, pattern='null'} in inputValue.code:[lb_av] id=gewicht aql=/content[openEHR-EHR-OBSERVATION.body_weight.v2]/data[at0002]/events[at0026]/data[at0001]/items[at0004]/value", "Validation not equal WebTemplateValidation{precision=null, range=WebTemplateValidationInterval{min=0.0, minOp=GT_EQ, max=1000000.0, maxOp=LT_EQ}, pattern='null'} != WebTemplateValidation{precision=null, range=WebTemplateValidationInterval{min=0, minOp=GT_EQ, max=1000000, maxOp=LT_EQ}, pattern='null'} in inputValue.code:g id=gewicht aql=/content[openEHR-EHR-OBSERVATION.body_weight.v2]/data[at0002]/events[at0003]/data[at0001]/items[at0004]/value", "Validation not equal WebTemplateValidation{precision=null, range=WebTemplateValidationInterval{min=0.0, minOp=GT_EQ, max=1000.0, maxOp=LT_EQ}, pattern='null'} != WebTemplateValidation{precision=null, range=WebTemplateValidationInterval{min=0, minOp=GT_EQ, max=1000, maxOp=LT_EQ}, pattern='null'} in inputValue.code:kg id=gewicht aql=/content[openEHR-EHR-OBSERVATION.body_weight.v2]/data[at0002]/events[at0003]/data[at0001]/items[at0004]/value", "Validation not equal WebTemplateValidation{precision=null, range=WebTemplateValidationInterval{min=0.0, minOp=GT_EQ, max=2000.0, maxOp=LT_EQ}, pattern='null'} != WebTemplateValidation{precision=null, range=WebTemplateValidationInterval{min=0, minOp=GT_EQ, max=2000, maxOp=LT_EQ}, pattern='null'} in inputValue.code:[lb_av] id=gewicht aql=/content[openEHR-EHR-OBSERVATION.body_weight.v2]/data[at0002]/events[at0003]/data[at0001]/items[at0004]/value" }); } @Test public void parseMultiOccurrence() throws IOException, XmlException { OPERATIONALTEMPLATE template = TemplateDocument.Factory.parse( OperationalTemplateTestData.MULTI_OCCURRENCE.getStream()) .getTemplate(); OPTParser cut = new OPTParser(template); WebTemplate actual = cut.parse(); actual = new Filter().filter(actual); assertThat(actual).isNotNull(); ObjectMapper objectMapper = new ObjectMapper(); WebTemplate expected = objectMapper.readValue( IOUtils.toString(WebTemplateTestData.MULTI_OCCURRENCE.getStream(), StandardCharsets.UTF_8), WebTemplate.class); List<String> errors = compareWebTemplate(actual, expected); checkErrors(errors, new String[] { "Validation not equal WebTemplateValidation{precision=WebTemplateValidationInterval{min=1, minOp=GT_EQ, max=1, maxOp=LT_EQ}, range=WebTemplateValidationInterval{min=0.0, minOp=GT_EQ, max=100.0, maxOp=LT}, pattern='null'} != WebTemplateValidation{precision=WebTemplateValidationInterval{min=1, minOp=GT_EQ, max=1, maxOp=LT_EQ}, range=WebTemplateValidationInterval{min=0, minOp=GT_EQ, max=100, maxOp=LT}, pattern='null'} in inputValue.code:Cel id=temperature aql=/content[openEHR-EHR-OBSERVATION.body_temperature.v2]/data[at0002]/events[at0003]/data[at0001]/items[at0004]/value", "Validation not equal WebTemplateValidation{precision=WebTemplateValidationInterval{min=1, minOp=GT_EQ, max=1, maxOp=LT_EQ}, range=WebTemplateValidationInterval{min=30.0, minOp=GT_EQ, max=200.0, maxOp=LT}, pattern='null'} != WebTemplateValidation{precision=WebTemplateValidationInterval{min=1, minOp=GT_EQ, max=1, maxOp=LT_EQ}, range=WebTemplateValidationInterval{min=30, minOp=GT_EQ, max=200, maxOp=LT}, pattern='null'} in inputValue.code:[degF] id=temperature aql=/content[openEHR-EHR-OBSERVATION.body_temperature.v2]/data[at0002]/events[at0003]/data[at0001]/items[at0004]/value" }); } @Test public void parseAny() throws IOException, XmlException { OPERATIONALTEMPLATE template = TemplateDocument.Factory.parse( OperationalTemplateTestData.GECCO_SEROLOGISCHER_BEFUND.getStream()) .getTemplate(); OPTParser cut = new OPTParser(template); WebTemplate actual = cut.parse(); actual = new Filter().filter(actual); assertThat(actual).isNotNull(); ObjectMapper objectMapper = new ObjectMapper(); WebTemplate expected = objectMapper.readValue( IOUtils.toString(WebTemplateTestData.GECCO_SEROLOGISCHER_BEFUND.getStream(), StandardCharsets.UTF_8), WebTemplate.class); List<String> errors = compareWebTemplate(actual, expected); checkErrors( errors.stream() .filter(e -> Stream.of( "Annotations not equal", "InputValue not equal", "LocalizedNames not equal", "LocalizedDescriptions not equal") .noneMatch(e::startsWith)) .collect(Collectors.toList()), new String[] {}); } @Test public void parseInitialAssessment() throws IOException, XmlException { OPERATIONALTEMPLATE template = TemplateDocument.Factory.parse( OperationalTemplateTestData.INITIAL_ASSESSMENT.getStream()) .getTemplate(); OPTParser cut = new OPTParser(template); WebTemplate actual = cut.parse(); actual = new Filter().filter(actual); assertThat(actual).isNotNull(); ObjectMapper objectMapper = new ObjectMapper(); WebTemplate expected = objectMapper.readValue( IOUtils.toString(WebTemplateTestData.INITIAL_ASSESSMENT.getStream(), StandardCharsets.UTF_8), WebTemplate.class); List<String> errors = compareWebTemplate(actual, expected); checkErrors(errors, new String[] {}); } @Test public void parseAddiction() throws IOException, XmlException { OPERATIONALTEMPLATE template = TemplateDocument.Factory.parse(OperationalTemplateTestData.ADDICTION.getStream()) .getTemplate(); OPTParser cut = new OPTParser(template); WebTemplate actual = cut.parse(); actual = new Filter().filter(actual); assertThat(actual).isNotNull(); ObjectMapper objectMapper = new ObjectMapper(); WebTemplate expected = objectMapper.readValue( IOUtils.toString(WebTemplateTestData.ADDICTION.getStream(), StandardCharsets.UTF_8), WebTemplate.class); List<String> errors = compareWebTemplate(actual, expected); checkErrors(errors, new String[] { "LocalizedNames not equal [de=event] != [de=] in inputValue.code:433 id=category aql=/category" }); } @Test public void parseConstrainTest() throws IOException, XmlException { OPERATIONALTEMPLATE template = TemplateDocument.Factory.parse( OperationalTemplateTestData.CONSTRAIN_TEST.getStream()) .getTemplate(); OPTParser cut = new OPTParser(template); WebTemplate actual = cut.parse(); actual = new Filter().filter(actual); assertThat(actual).isNotNull(); ObjectMapper objectMapper = new ObjectMapper(); WebTemplate expected = objectMapper.readValue( IOUtils.toString(WebTemplateTestData.CONSTRAIN_TEST.getStream(), StandardCharsets.UTF_8), WebTemplate.class); List<String> errors = compareWebTemplate(actual, expected); checkErrors(errors, new String[] { "DefaultValue not equal 100.0 != null in input.suffix:denominator id=total_body_surface_area_tbsa_affected aql=/content[openEHR-EHR-OBSERVATION.affected_body_surface_area.v0]/data[at0001]/events[at0002]/data[at0003]/items[at0014]/value" }); } @Test public void parseLanguageTest() throws IOException, XmlException { OPERATIONALTEMPLATE template = TemplateDocument.Factory.parse( OperationalTemplateTestData.LANGUAGE_TEST.getStream()) .getTemplate(); OPTParser cut = new OPTParser(template); WebTemplate actual = cut.parse(); actual = new Filter().filter(actual); assertThat(actual).isNotNull(); ObjectMapper objectMapper = new ObjectMapper(); WebTemplate expected = objectMapper.readValue( IOUtils.toString(WebTemplateTestData.LANGUAGE_TEST.getStream(), StandardCharsets.UTF_8), WebTemplate.class); List<String> errors = compareWebTemplate(actual, expected); checkErrors(errors, new String[] { "InputValue not equal 146:mean != 146:Durchschnitt in id=math_function aql=/content[openEHR-EHR-OBSERVATION.blood_pressure.v2]/data[at0001]/events[at1042]/math_function", "LocalizedNames not equal [de=event, ar-sy=event, en=event, fi=event] != [de=, fi=, en=event, ar-sy=] in inputValue.code:433 id=category aql=/category", "LocalizedNames not equal [de=mean, ar-sy=mean, en=mean, fi=mean] != [de=Durchschnitt, fi=, en=mean, ar-sy=] in inputValue.code:146 id=math_function aql=/content[openEHR-EHR-OBSERVATION.blood_pressure.v2]/data[at0001]/events[at1042]/math_function" }); } @Test public void parseAllTypes() throws IOException, XmlException { OPERATIONALTEMPLATE template = TemplateDocument.Factory.parse(OperationalTemplateTestData.ALL_TYPES.getStream()) .getTemplate(); OPTParser cut = new OPTParser(template); WebTemplate actual = cut.parse(); actual = new Filter().filter(actual); assertThat(actual).isNotNull(); ObjectMapper objectMapper = new ObjectMapper(); WebTemplate expected = objectMapper.readValue( IOUtils.toString(WebTemplateTestData.ALL_TYPES.getStream(), StandardCharsets.UTF_8), WebTemplate.class); List<WebTemplateNode> dvOrdinalList = actual.getTree().findMatching(n -> n.getRmType().equals("DV_ORDINAL")); assertThat(dvOrdinalList).size().isEqualTo(1); assertThat(dvOrdinalList.get(0).getInputs()) .flatExtracting(WebTemplateInput::getList) .extracting( WebTemplateInputValue::getLabel, WebTemplateInputValue::getValue, WebTemplateInputValue::getOrdinal) .containsExactlyInAnyOrder( new Tuple("ord1", "at0014", 0), new Tuple("ord1", "at0015", 1), new Tuple("ord3", "at0016", 2)); List<WebTemplateNode> dvQuantityList = actual.getTree().findMatching(n -> n.getRmType().equals("DV_QUANTITY")); assertThat(dvQuantityList) .flatExtracting(WebTemplateNode::getInputs) .flatExtracting(WebTemplateInput::getList) .extracting(WebTemplateInputValue::getLabel, WebTemplateInputValue::getValue) .containsExactlyInAnyOrder( new Tuple("mg", "mg"), new Tuple("kg", "kg"), new Tuple("mm[H20]", "mm[H20]"), new Tuple("mm[Hg]", "mm[Hg]")); List<WebTemplateNode> dvCodedTextList = actual.getTree().findMatching(n -> n.getRmType().equals("DV_CODED_TEXT")); assertThat(dvCodedTextList) .flatExtracting(WebTemplateNode::getInputs) .extracting(WebTemplateInput::getTerminology, i -> i.getList().stream() .map(v -> v.getValue() + ":" + v.getLabel()) .collect(Collectors.joining(";"))) .containsExactlyInAnyOrder( new Tuple("openehr", "433:event"), new Tuple("local", "at0006:value1;at0007:value2;at0008:value3"), new Tuple("local", ""), new Tuple("local", ""), new Tuple("SNOMED-CT", ""), new Tuple("SNOMED-CT", ""), new Tuple("local", "at0003:Planned;at0004:Active;at0005:Completed"), new Tuple("openehr", "526:planned;245:active;532:completed"), new Tuple(null, ""), new Tuple(null, ""), new Tuple(null, ""), new Tuple(null, "")); List<String> errors = compareWebTemplate(actual, expected); checkErrors(errors, new String[] { "LocalizedNames not equal [en=active] != [] in inputValue.code:245 id=current_state aql=/content[openEHR-EHR-SECTION.test_all_types.v1]/items[at0001]/items[at0002]/items[openEHR-EHR-ACTION.test_all_types.v1]/ism_transition/current_state", "LocalizedNames not equal [en=completed] != [] in inputValue.code:532 id=current_state aql=/content[openEHR-EHR-SECTION.test_all_types.v1]/items[at0001]/items[at0002]/items[openEHR-EHR-ACTION.test_all_types.v1]/ism_transition/current_state", "LocalizedNames not equal [en=planned] != [] in inputValue.code:526 id=current_state aql=/content[openEHR-EHR-SECTION.test_all_types.v1]/items[at0001]/items[at0002]/items[openEHR-EHR-ACTION.test_all_types.v1]/ism_transition/current_state", "LocalizedDescriptions not equal {en=*} != {} in inputValue.code:at0005 id=careflow_step aql=/content[openEHR-EHR-SECTION.test_all_types.v1]/items[at0001]/items[at0002]/items[openEHR-EHR-ACTION.test_all_types.v1]/ism_transition/careflow_step", "LocalizedDescriptions not equal {en=*} != {} in inputValue.code:at0004 id=careflow_step aql=/content[openEHR-EHR-SECTION.test_all_types.v1]/items[at0001]/items[at0002]/items[openEHR-EHR-ACTION.test_all_types.v1]/ism_transition/careflow_step", "LocalizedDescriptions not equal {en=*} != {} in inputValue.code:at0003 id=careflow_step aql=/content[openEHR-EHR-SECTION.test_all_types.v1]/items[at0001]/items[at0002]/items[openEHR-EHR-ACTION.test_all_types.v1]/ism_transition/careflow_step", "InContext not equal true != null in id=action_archetype_id aql=/content[openEHR-EHR-SECTION.test_all_types.v1]/items[at0001]/items[at0002]/items[openEHR-EHR-INSTRUCTION.test_all_types.v1]/activities[at0001]/action_archetype_id" }); } @Test public void parseMultimediaTest() throws Exception { var optTemplate = TemplateDocument.Factory.parse(OperationalTemplateTestData.MULTIMEDIA_TEST.getStream()) .getTemplate(); var parser = new OPTParser(optTemplate); var webTemplate = parser.parse(); assertThat(webTemplate).isNotNull(); var nodes = webTemplate.getTree().findMatching(node -> node.getRmType().equals("PARTICIPATION")); assertThat(nodes).hasSize(2); } public void checkErrors(List<String> errors, String[] expectedErrors) { SoftAssertions softAssertions = new SoftAssertions(); softAssertions.assertThat(errors).containsAll(Arrays.asList(expectedErrors)); errors.removeAll(Arrays.asList(expectedErrors)); // Nodes which are generated by the parser but are not in the example softAssertions .assertThat(errors) .filteredOn(s -> s.startsWith("Extra Node")) .containsExactlyInAnyOrder(); // Inputs which are generated by the parser but are not in the example softAssertions .assertThat(errors) .filteredOn(s -> s.startsWith("Extra Input")) .containsExactlyInAnyOrder(); // Nodes which are in the example but are not generated by the parser softAssertions .assertThat(errors) .filteredOn(s -> s.startsWith("Missing Node")) .containsExactlyInAnyOrder(); // Inputs which are in the example but are not generated by the parser softAssertions .assertThat(errors) .filteredOn(s -> s.startsWith("Missing Input")) .containsExactlyInAnyOrder(); // Non-equal validations softAssertions .assertThat(errors) .filteredOn(s -> s.startsWith("Validation not equal")) .containsExactlyInAnyOrder(); softAssertions .assertThat(errors) .filteredOn(s -> s.startsWith("ListOpen not equal")) .containsExactlyInAnyOrder(); softAssertions .assertThat(errors) .filteredOn(s -> s.startsWith("ProportionTypes not equal")) .containsExactlyInAnyOrder(); softAssertions .assertThat(errors) .filteredOn(s -> s.startsWith("InContext not equal")) .containsExactlyInAnyOrder(); softAssertions .assertThat(errors) .filteredOn(s -> s.startsWith("Annotations not equal")) .containsExactlyInAnyOrder(); softAssertions .assertThat(errors) .filteredOn(s -> s.startsWith("Cardinalities not equal")) .containsExactlyInAnyOrder(); // Non equal InputValue softAssertions .assertThat(errors) .filteredOn(s -> s.startsWith("Missing InputValue")) .containsExactlyInAnyOrder(); softAssertions .assertThat(errors) .filteredOn(s -> s.startsWith("Extra InputValue")) .containsExactlyInAnyOrder(); softAssertions .assertThat(errors) .filteredOn(s -> s.startsWith("InputValue not equal")) .containsExactlyInAnyOrder(); softAssertions .assertThat(errors) .filteredOn(s -> s.startsWith("DefaultValue not equal")) .containsExactlyInAnyOrder(); softAssertions .assertThat(errors) .filteredOn(s -> s.startsWith("LocalizedNames not equal")) .containsExactlyInAnyOrder(); softAssertions .assertThat(errors) .filteredOn(s -> s.startsWith("LocalizedDescriptions not equal")) .containsExactlyInAnyOrder(); softAssertions.assertAll(); } public List<String> compareWebTemplate(WebTemplate actual, WebTemplate expected) { return new ArrayList<>(compareNode(actual.getTree(), expected.getTree())); } public List<String> compareNodes(List<WebTemplateNode> actual, List<WebTemplateNode> expected) { List<String> errors = new ArrayList<>(); Map<ImmutablePair<String, String>, WebTemplateNode> actualMap = actual.stream() .collect( Collectors.toMap(n -> new ImmutablePair<>(n.getAqlPath(true), n.getId()), Function.identity())); Map<ImmutablePair<String, String>, WebTemplateNode> expectedMap = expected.stream() .collect( Collectors.toMap(n -> new ImmutablePair<>(n.getAqlPath(true), n.getId()), Function.identity())); for (ImmutablePair<String, String> pair : actualMap.keySet()) { if (expectedMap.containsKey(pair)) { errors.addAll(compareNode(actualMap.get(pair), expectedMap.get(pair))); } else { errors.add(String.format("Extra Node id=%s aql=%s", pair.getRight(), pair.getLeft())); } } for (ImmutablePair<String, String> pair : expectedMap.keySet()) { if (!actualMap.containsKey(pair)) { errors.add(String.format("Missing Node id=%s aql=%s", pair.getRight(), pair.getLeft())); } } return errors; } public List<String> compareNode(WebTemplateNode actual, WebTemplateNode expected) { List<String> errors = new ArrayList<>(); errors.addAll(compareNodes(actual.getChildren(), expected.getChildren())); errors.addAll(compereInputs(actual, actual.getInputs(), expected.getInputs())); if (!CollectionUtils.isEqualCollection(actual.getProportionTypes(), expected.getProportionTypes())) { errors.add(String.format( "ProportionTypes not equal %s != %s in id=%s aql=%s", actual.getProportionTypes(), expected.getProportionTypes(), actual.getId(), actual.getAqlPath())); } if (!Objects.equals(actual.getAnnotations(), expected.getAnnotations())) { errors.add(String.format( "Annotations not equal %s != %s in id=%s aql=%s", actual.getAnnotations(), expected.getAnnotations(), actual.getId(), actual.getAqlPath())); } if (!Objects.equals(actual.getCardinalities(), expected.getCardinalities())) { errors.add(String.format( "Cardinalities not equal %s != %s in id=%s aql=%s", actual.getCardinalities(), expected.getCardinalities(), actual.getId(), actual.getAqlPath())); } if (!CollectionUtils.isEqualCollection( actual.getLocalizedNames().entrySet(), expected.getLocalizedNames().entrySet())) { errors.add(String.format( "LocalizedNames not equal %s != %s in id=%s aql=%s", actual.getLocalizedNames().entrySet(), expected.getLocalizedNames().entrySet(), actual.getId(), actual.getAqlPath())); } if (!Objects.equals(actual.getInContext(), expected.getInContext())) { errors.add(String.format( "InContext not equal %s != %s in id=%s aql=%s", actual.getInContext(), expected.getInContext(), actual.getId(), actual.getAqlPath())); } if (!CollectionUtils.isEqualCollection( actual.getLocalizedDescriptions().entrySet(), expected.getLocalizedDescriptions().entrySet())) { errors.add(String.format( "LocalizedDescriptions not equal %s != %s in id=%s aql=%s", actual.getLocalizedDescriptions(), expected.getLocalizedDescriptions(), actual.getId(), actual.getAqlPath())); } return errors; } private Collection<String> compereInputs( WebTemplateNode node, List<WebTemplateInput> actual, List<WebTemplateInput> expected) { List<String> errors = new ArrayList<>(); Map<String, WebTemplateInput> actualMap = actual.stream() .collect(Collectors.toMap( webTemplateInput -> webTemplateInput.getSuffix() + ":" + webTemplateInput.getType(), Function.identity())); Map<String, WebTemplateInput> expectedMap = expected.stream() .collect(Collectors.toMap( webTemplateInput -> webTemplateInput.getSuffix() + ":" + webTemplateInput.getType(), Function.identity())); for (Map.Entry<String, WebTemplateInput> entry : actualMap.entrySet()) { if (!expectedMap.containsKey(entry.getKey())) { errors.add(String.format( "Extra Input %s in id=%s aql=%s", entry.getKey(), node.getId(), node.getAqlPath())); } else { errors.addAll(compareInput(node, entry.getValue(), expectedMap.get(entry.getKey()))); } } for (Map.Entry<String, WebTemplateInput> entry : expectedMap.entrySet()) { if (!actualMap.containsKey(entry.getKey())) { errors.add(String.format( "Missing Input %s in id=%s aql=%s", entry.getKey(), node.getId(), node.getAqlPath())); } } return errors; } private List<String> compareInput(WebTemplateNode node, WebTemplateInput actual, WebTemplateInput expected) { List<String> errors = new ArrayList<>(); if (!Objects.equals(actual.getValidation(), expected.getValidation())) { errors.add(String.format( "Validation not equal %s != %s in input.suffix:%s id=%s aql=%s", actual.getValidation(), expected.getValidation(), actual.getSuffix(), node.getId(), node.getAqlPath())); } if (!Objects.equals(actual.getListOpen(), expected.getListOpen())) { errors.add(String.format( "ListOpen not equal %s != %s in input.suffix:%s id=%s aql=%s", actual.getListOpen(), expected.getListOpen(), actual.getSuffix(), node.getId(), node.getAqlPath())); } if (!Objects.equals(actual.getDefaultValue(), expected.getDefaultValue())) { errors.add(String.format( "DefaultValue not equal %s != %s in input.suffix:%s id=%s aql=%s", actual.getDefaultValue(), expected.getDefaultValue(), actual.getSuffix(), node.getId(), node.getAqlPath())); } errors.addAll(compereInputValues(node, actual.getList(), expected.getList())); return errors; } private Collection<String> compereInputValues( WebTemplateNode node, List<WebTemplateInputValue> actual, List<WebTemplateInputValue> expected) { List<String> errors = new ArrayList<>(); Map<String, WebTemplateInputValue> actualMap = actual.stream().collect(Collectors.toMap(WebTemplateInputValue::getValue, Function.identity())); Map<String, WebTemplateInputValue> expectedMap = expected.stream().collect(Collectors.toMap(WebTemplateInputValue::getValue, Function.identity())); for (Map.Entry<String, WebTemplateInputValue> entry : actualMap.entrySet()) { if (!expectedMap.containsKey(entry.getKey())) { errors.add(String.format( "Extra InputValue %s in id=%s aql=%s", entry.getKey(), node.getId(), node.getAqlPath())); } else { errors.addAll(compareInputValue(node, entry.getValue(), expectedMap.get(entry.getKey()))); } } for (Map.Entry<String, WebTemplateInputValue> entry : expectedMap.entrySet()) { if (!actualMap.containsKey(entry.getKey())) { errors.add(String.format( "Missing InputValue %s in id=%s aql=%s", entry.getKey(), node.getId(), node.getAqlPath())); } } return errors; } private Collection<String> compareInputValue( WebTemplateNode node, WebTemplateInputValue actual, WebTemplateInputValue expected) { List<String> errors = new ArrayList<>(); if (!Objects.equals(actual.getValue(), expected.getValue()) || !Objects.equals(actual.getLabel(), expected.getLabel())) { errors.add(String.format( "InputValue not equal %s != %s in id=%s aql=%s", actual.getValue() + ":" + actual.getLabel(), expected.getValue() + ":" + expected.getLabel(), node.getId(), node.getAqlPath())); } if (!Objects.equals(actual.getValidation(), expected.getValidation())) { errors.add(String.format( "Validation not equal %s != %s in inputValue.code:%s id=%s aql=%s", actual.getValidation(), expected.getValidation(), actual.getValue(), node.getId(), node.getAqlPath())); } if (!CollectionUtils.isEqualCollection( actual.getLocalizedLabels().entrySet(), expected.getLocalizedLabels().entrySet())) { errors.add(String.format( "LocalizedNames not equal %s != %s in inputValue.code:%s id=%s aql=%s", actual.getLocalizedLabels().entrySet(), expected.getLocalizedLabels().entrySet(), actual.getValue(), node.getId(), node.getAqlPath())); } if (!CollectionUtils.isEqualCollection( actual.getLocalizedDescriptions().entrySet(), expected.getLocalizedDescriptions().entrySet())) { errors.add(String.format( "LocalizedDescriptions not equal %s != %s in inputValue.code:%s id=%s aql=%s", actual.getLocalizedDescriptions(), expected.getLocalizedDescriptions(), actual.getValue(), node.getId(), node.getAqlPath())); } return errors; } @Test public void testReadWrite() throws IOException, XmlException { var template = TemplateDocument.Factory.parse(OperationalTemplateTestData.CORONA_ANAMNESE.getStream()) .getTemplate(); var parser = new OPTParser(template); var webTemplate = parser.parse(); ObjectMapper objectMapper = new ObjectMapper(); assertThatNoException().isThrownBy(() -> objectMapper.writeValueAsString(webTemplate)); } @Test public void missingNodeIdAndAnnotationsTest() throws IOException, XmlException { OPERATIONALTEMPLATE template = TemplateDocument.Factory.parse(OperationalTemplateTestData.NULLID.getStream()) .getTemplate(); WebTemplate webTemplate = new OPTParser(template).parse(); assertThat(webTemplate).isNotNull(); List<WebTemplateNode> nodes = webTemplate.findAllByAqlPath( "[openEHR-EHR-COMPOSITION.encounter.v1]/content[openEHR-EHR-OBSERVATION.blood_pressure.v2]/data[at0001]/events[at0006]/data[at0003]/items[at0004]", true); assertThat(nodes).isNotNull(); assertThat(nodes.size()).isGreaterThan(0); WebTemplateNode node = nodes.get(0); assertThat(node).isNotNull(); assertThat(node.getNodeId()).isNotNull(); WebTemplateAnnotation annotation = node.getAnnotations(); assertThat(annotation).isNotNull(); assertThat(annotation.getOther()).isNotNull(); assertThat(annotation.getOther().size()).isEqualTo(3); webTemplate = new Filter().filter(webTemplate); nodes = webTemplate.findAllByAqlPath( "[openEHR-EHR-COMPOSITION.encounter.v1]/content[openEHR-EHR-OBSERVATION.blood_pressure.v2]/data[at0001]/events[at0006]/data[at0003]/items[at0004]/value", true); assertThat(nodes).isNotNull(); assertThat(nodes.size()).isGreaterThan(0); node = nodes.get(0); assertThat(node).isNotNull(); assertThat(node.getNodeId()).isNotNull(); annotation = node.getAnnotations(); assertThat(annotation).isNotNull(); assertThat(annotation.getOther()).isNotNull(); assertThat(annotation.getOther().size()).isEqualTo(3); } }
922fe58c83e32eff838021d826a57591c097362a
2,277
java
Java
concurrent-plus/src/com/concurrent/ch08/test2/AddArr.java
CembZy/java-bable
5642fd6511e19c21b78be2c8e09a3698fff67498
[ "AFL-3.0" ]
1
2021-03-06T14:22:02.000Z
2021-03-06T14:22:02.000Z
concurrent-plus/src/com/concurrent/ch08/test2/AddArr.java
CembZy/java-bable
5642fd6511e19c21b78be2c8e09a3698fff67498
[ "AFL-3.0" ]
null
null
null
concurrent-plus/src/com/concurrent/ch08/test2/AddArr.java
CembZy/java-bable
5642fd6511e19c21b78be2c8e09a3698fff67498
[ "AFL-3.0" ]
1
2021-03-06T14:21:54.000Z
2021-03-06T14:21:54.000Z
28.822785
105
0.555556
995,292
package com.concurrent.ch08.test2; import com.concurrent.SleepTools; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.concurrent.RecursiveTask; import java.util.concurrent.atomic.AtomicInteger; public class AddArr { public static final int[] SRC = MakeArray.makeArray(); public static final int POINT = SRC.length / 10; public static AtomicInteger num = new AtomicInteger(0); public static class SumTask extends RecursiveTask<Integer> { private int[] src; private int start; private int end; public SumTask(int[] src, int start, int end) { this.src = src; this.start = start; this.end = end; } @Override protected Integer compute() { if (end - start < POINT) { for (int i = start; i <= end; i++) { num.addAndGet(src[i]); // SleepTools.ms(1); } return num.get(); } else { int mid = (end + start) / 2; ForkJoinTask left = new SumTask(src, start, mid); ForkJoinTask right = new SumTask(src, mid + 1, end); invokeAll(left, right); return ((SumTask) left).join() + ((SumTask) right).join(); } } } private static void testForkJoin() { ForkJoinPool forkJoinPool = new ForkJoinPool(); SumTask sumTask = new SumTask(SRC, 0, SRC.length - 1); long startTime = System.currentTimeMillis(); forkJoinPool.invoke(sumTask); long endTime = System.currentTimeMillis(); System.out.println("采用forkjoin执行结果是:" + sumTask.join() + "---------用时:" + (endTime - startTime)); } private static void testFor() { long startTime = System.currentTimeMillis(); int count = 0; for (int i = 0; i < SRC.length; i++) { count += SRC[i]; // SleepTools.ms(1); } long endTime = System.currentTimeMillis(); System.out.println("采用for循环执行结果是:" + count + "---------用时:" + (endTime - startTime)); } public static void main(String[] args) { testForkJoin(); testFor(); } }
922fe7ba391376f27f9ff554cd31eec70458b276
2,829
java
Java
programacao-desktop/atividades/calculadora/eduardo-albano/src/projetoCalculadora/calculadora.java
guigon95/dctb-utfpr-2018-1
82939efafc52301b1723032a9649b933c30c5be3
[ "Apache-2.0" ]
24
2018-03-06T19:17:55.000Z
2020-12-11T03:58:24.000Z
programacao-desktop/atividades/calculadora/eduardo-albano/src/projetoCalculadora/calculadora.java
guigon95/dctb-utfpr-2018-1
82939efafc52301b1723032a9649b933c30c5be3
[ "Apache-2.0" ]
56
2018-03-15T19:24:03.000Z
2018-08-23T21:12:29.000Z
programacao-desktop/atividades/calculadora/eduardo-albano/src/projetoCalculadora/calculadora.java
guigon95/dctb-utfpr-2018-1
82939efafc52301b1723032a9649b933c30c5be3
[ "Apache-2.0" ]
375
2018-03-09T22:38:01.000Z
2020-06-05T20:16:53.000Z
33.282353
60
0.534464
995,293
package projetoCalculadora; import java.util.Scanner; public class calculadora { /*Declaração dos métodos*/ public int som(int num1, int num2) { return num1 + num2; } public int sub(int num1, int num2){ return num1 - num2; } public int div(int num1,int num2){ return num1 / num2; } public int mult(int num1, int num2){ return num1 - num2; } public static void main (String args[]){ //criando um objeto c a apartir do metodo calc calculadora c = new calculadora(); //declarando as varíaveis int opcao = 5; int num1; int num2; Scanner input = new Scanner(System.in); System.out.println("-Escolha uma opção-"); System.out.println("1. Soma"); System.out.println("2. Subtracao"); System.out.println("3. Multiplicacao"); System.out.println("4. Divisao"); System.out.println("0. Sair"); System.out.println("Operação: "); opcao = input.nextInt(); while (opcao != 0) { if (opcao == 1) { ///??????? /**Que outra maneira poderia ser recebido * os numeros, sem que se repita as próximas * linhas para todas operações**/ Scanner input1 = new Scanner(System.in); System.out.println("Qual o primeiro numero: "); num1 = input1.nextInt(); System.out.println("Qual o segundo numero: "); num2 = input1.nextInt(); /***/ int operacao = c.som(num1, num2); System.out.println(operacao); break; } if (opcao == 2) { Scanner input1 = new Scanner(System.in); System.out.println("Qual o primeiro numero: "); num1 = input1.nextInt(); System.out.println("Qual o segundo numero: "); num2 = input1.nextInt(); int operacao = c.sub(num1, num2); System.out.println(operacao); break; } if (opcao == 3) { Scanner input1 = new Scanner(System.in); System.out.println("Qual o primeiro numero: "); num1 = input1.nextInt(); System.out.println("Qual o segundo numero: "); num2 = input1.nextInt(); int operacao = c.mult(num1, num2); System.out.println(operacao); break; } if (opcao == 4) { Scanner input1 = new Scanner(System.in); System.out.println("Qual o primeiro numero: "); num1 = input1.nextInt(); System.out.println("Qual o segundo numero: "); num2 = input1.nextInt(); int operacao = c.div(num1, num2); System.out.println(operacao); break; } else{ System.out.println("????"); break; } } } }
922fe816ff89f2acbf7a912df6badfea3500e59a
22,274
java
Java
HW7 - JAVA/src/DriverClass.java
muratyldzxc/CSE241
35b3fb6de1fa0aebe3f77353c1e4e4256fd2e36b
[ "MIT" ]
null
null
null
HW7 - JAVA/src/DriverClass.java
muratyldzxc/CSE241
35b3fb6de1fa0aebe3f77353c1e4e4256fd2e36b
[ "MIT" ]
null
null
null
HW7 - JAVA/src/DriverClass.java
muratyldzxc/CSE241
35b3fb6de1fa0aebe3f77353c1e4e4256fd2e36b
[ "MIT" ]
null
null
null
48.00431
144
0.591856
995,294
import HW7.*; import java.io.*; /** * @author murat * @since 15.01.2020 * */ /** * To test {@link AbstractBoard} , {@link BoardArray1D}, {@link BoardArray2D} * @see {@link AbstractBoard} , {@link BoardArray1D}, {@link BoardArray2D} */ public class DriverClass { /** * Takes AbstractBoard reference array and test it whether is a solution sequence or not * @param AbstractBoard_Array Takes AbstractBoard reference array which will be tested * @param size Takes size of AbstractBoard reference array * @return If it is a valid sequence it returns true , otherwise returns false */ public static boolean test( AbstractBoard AbstractBoard_Array[], int size ){ int old_x_Ecell, old_y_Ecell, new_x_Ecell, new_y_Ecell ; old_x_Ecell = AbstractBoard_Array[0].getX_Ecell() ; old_y_Ecell = AbstractBoard_Array[0].getY_Ecell() ; new_x_Ecell = AbstractBoard_Array[1].getX_Ecell() ; new_y_Ecell = AbstractBoard_Array[1].getY_Ecell() ; if( AbstractBoard_Array[ size - 1 ].isSolved() ){ // if the final board is a solution for (int i = 1; i < size - 1 ; ++i){ if( old_x_Ecell != new_x_Ecell || old_y_Ecell != new_y_Ecell ){ // if prevBoard and afterBoard empty cell cordinates are not the same for (int row = 0; row < AbstractBoard_Array[0].getRow(); ++row){ for (int column = 0; column < AbstractBoard_Array[0].getColumn(); ++column) { // checks are the two board same if( AbstractBoard_Array[ i-1 ].cell( row, column ) != AbstractBoard_Array[ i ].cell( row, column ) ){ if ( AbstractBoard_Array[ i-1 ].cell( row, column ) != AbstractBoard_Array[ i ].cell( new_y_Ecell, new_x_Ecell ) && AbstractBoard_Array[ i-1 ].cell( row, column ) != AbstractBoard_Array[ i ].cell( old_y_Ecell, old_x_Ecell ) ) { System.out.printf("\n\n distance between board %d board %d more than one move" + " , the sequence corrupted \n\n", i, i+1 ) ; return false ; } } } } } else{ System.out.printf("\n\n board %d board %d are same boards , the sequence corrupted \n\n", i, i+1 ) ; return false ; } old_x_Ecell = AbstractBoard_Array[i].getX_Ecell() ; old_y_Ecell = AbstractBoard_Array[i].getY_Ecell() ; new_x_Ecell = AbstractBoard_Array[i+1].getX_Ecell() ; new_y_Ecell = AbstractBoard_Array[i+1].getY_Ecell() ; } } else{ System.out.printf("\n\n it is not solved because last board is not a solution\n\n" ) ; return false ; } return true ; } /** * To test {@link AbstractBoard} , {@link BoardArray1D}, {@link BoardArray2D} * @param args Command line argument * @throws IOException Throws exception if an invalid entry given */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub System.out.printf("\n\n Before calling any constructor number of Boards : %d", BoardArray2D.NumberOfBoards() ) ; System.out.printf( "\n\n*************************************************************************************************" ) ; System.out.printf( "\n\n TESTING BoardArray2D functions " ) ; System.out.printf( "\n\n*************************************************************************************************" ) ; BoardArray2D board2D = new BoardArray2D() ; //after constructor called System.out.printf( "\n\n After BoardArray2D constructor called \n\n There is no board configration yet.\n" ) ; System.out.println( board2D ) ; System.out.printf( "\n row: %d , column: %d \n", board2D.getRow(), board2D.getColumn() ) ; System.out.printf( " x_Ecell : %d , y_Ecell : %d \n", board2D.getX_Ecell(), board2D.getY_Ecell() ) ; System.out.printf( " last move : %c \n", board2D.lastMove() ) ; System.out.printf( " number of moves : %d \n", board2D.numberOfMoves() ) ; System.out.printf( " number of boards : %d \n", BoardArray2D.NumberOfBoards() ) ; File readFile = new File("txt_files//BoardArray2D_test.txt") ; board2D.readFromFile( readFile ); System.out.printf( "\n\n After BoardArray2D object readed from BoardArray2D_test.txt file \n\n " ) ; System.out.println( board2D ) ; System.out.printf( "\n row: %d , column: %d \n", board2D.getRow(), board2D.getColumn() ) ; System.out.printf( " x_Ecell : %d , y_Ecell : %d \n", board2D.getX_Ecell(), board2D.getY_Ecell() ) ; System.out.printf( " last move : %c \n", board2D.lastMove() ) ; System.out.printf( " number of moves : %d \n", board2D.numberOfMoves() ) ; System.out.printf( " number of boards : %d \n", BoardArray2D.NumberOfBoards() ) ; System.out.printf( "\n\n After BoardArray2D object moved up \n\n ") ; board2D.move( 'U' ) ; System.out.println( board2D ) ; System.out.printf( "\n row: %d , column: %d \n", board2D.getRow(), board2D.getColumn() ) ; System.out.printf( " x_Ecell : %d , y_Ecell : %d \n", board2D.getX_Ecell(), board2D.getY_Ecell() ) ; System.out.printf( " last move : %c \n", board2D.lastMove() ) ; System.out.printf( " number of moves : %d \n", board2D.numberOfMoves() ) ; System.out.printf( " number of boards : %d \n", BoardArray2D.NumberOfBoards() ) ; System.out.printf( "\n\n After BoardArray2D object moved left \n\n " ) ; board2D.move( 'L' ) ; System.out.println( board2D ) ; System.out.printf( "\n row: %d , column: %d \n", board2D.getRow(), board2D.getColumn() ) ; System.out.printf( " x_Ecell : %d , y_Ecell : %d \n", board2D.getX_Ecell(), board2D.getY_Ecell() ) ; System.out.printf( " last move : %c \n", board2D.lastMove() ) ; System.out.printf( " number of moves : %d \n", board2D.numberOfMoves() ) ; System.out.printf( " number of boards : %d \n", BoardArray2D.NumberOfBoards() ) ; System.out.printf( "\n\n After BoardArray2D object moved down \n\n " ) ; board2D.move( 'D' ) ; System.out.println( board2D ) ; System.out.printf( "\n row: %d , column: %d \n", board2D.getRow(), board2D.getColumn() ) ; System.out.printf( " x_Ecell : %d , y_Ecell : %d \n", board2D.getX_Ecell(), board2D.getY_Ecell() ) ; System.out.printf( " last move : %c \n", board2D.lastMove() ) ; System.out.printf( " number of moves : %d \n", board2D.numberOfMoves() ) ; System.out.printf( " number of boards : %d \n", BoardArray2D.NumberOfBoards() ) ; System.out.printf( "\n\n After BoardArray2D object moved right \n\n " ) ; board2D.move( 'R' ) ; System.out.println( board2D ) ; System.out.printf( "\n row: %d , column: %d \n", board2D.getRow(), board2D.getColumn() ) ; System.out.printf( " x_Ecell : %d , y_Ecell : %d \n", board2D.getX_Ecell(), board2D.getY_Ecell() ) ; System.out.printf( " last move : %c \n", board2D.lastMove() ) ; System.out.printf( " number of moves : %d \n", board2D.numberOfMoves() ) ; System.out.printf( " number of boards : %d \n", BoardArray2D.NumberOfBoards() ) ; System.out.printf( "\n\n After BoardArray2D object moved up \n\n ") ; board2D.move( 'U' ) ; System.out.println( board2D ) ; System.out.printf( "\n row: %d , column: %d \n", board2D.getRow(), board2D.getColumn() ) ; System.out.printf( " x_Ecell : %d , y_Ecell : %d \n", board2D.getX_Ecell(), board2D.getY_Ecell() ) ; System.out.printf( " last move : %c \n", board2D.lastMove() ) ; System.out.printf( " number of moves : %d \n", board2D.numberOfMoves() ) ; System.out.printf( " number of boards : %d \n", BoardArray2D.NumberOfBoards() ) ; File writeFile = new File("txt_files//BoardArray2D_restore.txt") ; board2D.writeToFile( writeFile ); System.out.printf( "\n\n After BoardArray2D object written to file BoardArray2D_restore.txt \n\n " ) ; System.out.println( board2D ) ; System.out.printf( "\n row: %d , column: %d \n", board2D.getRow(), board2D.getColumn() ) ; System.out.printf( " x_Ecell : %d , y_Ecell : %d \n", board2D.getX_Ecell(), board2D.getY_Ecell() ) ; System.out.printf( " last move : %c \n", board2D.lastMove() ) ; System.out.printf( " number of moves : %d \n", board2D.numberOfMoves() ) ; System.out.printf( " number of boards : %d \n", BoardArray2D.NumberOfBoards() ) ; board2D.reset(); System.out.printf( "\n\n After BoardArray2D object reset \n\n " ) ; System.out.println( board2D ) ; System.out.printf( "\n row: %d , column: %d \n", board2D.getRow(), board2D.getColumn() ) ; System.out.printf( " x_Ecell : %d , y_Ecell : %d \n", board2D.getX_Ecell(), board2D.getY_Ecell() ) ; System.out.printf( " last move : %c \n", board2D.lastMove() ) ; System.out.printf( " number of moves : %d \n", board2D.numberOfMoves() ) ; System.out.printf( " number of boards : %d \n", BoardArray2D.NumberOfBoards() ) ; System.out.printf( "\n\n*************************************************************************************************" ) ; System.out.printf( "\n\n TESTING BoardArray1D functions " ) ; System.out.printf( "\n\n*************************************************************************************************" ) ; BoardArray1D board1D = new BoardArray1D() ; //after constructor called System.out.printf( "\n\n After BoardArray1D constructor called \n\n There is no board configration yet.\n" ) ; System.out.println( board1D ) ; System.out.printf( "\n row: %d , column: %d \n", board1D.getRow(), board1D.getColumn() ) ; System.out.printf( " x_Ecell : %d , y_Ecell : %d \n", board1D.getX_Ecell(), board1D.getY_Ecell() ) ; System.out.printf( " last move : %c \n", board1D.lastMove() ) ; System.out.printf( " number of moves : %d \n", board1D.numberOfMoves() ) ; System.out.printf( " number of boards : %d \n", BoardArray1D.NumberOfBoards() ) ; readFile = new File("txt_files//BoardArray1D_test.txt") ; board1D.readFromFile( readFile ); System.out.printf( "\n\n After BoardArray1D object readed from BoardArray1D_test.txt file \n\n " ) ; System.out.println( board1D ) ; System.out.printf( "\n row: %d , column: %d \n", board1D.getRow(), board1D.getColumn() ) ; System.out.printf( " x_Ecell : %d , y_Ecell : %d \n", board1D.getX_Ecell(), board1D.getY_Ecell() ) ; System.out.printf( " last move : %c \n", board1D.lastMove() ) ; System.out.printf( " number of moves : %d \n", board1D.numberOfMoves() ) ; System.out.printf( " number of boards : %d \n", BoardArray1D.NumberOfBoards() ) ; System.out.printf( "\n\n After BoardArray1D object moved up \n\n ") ; board1D.move( 'U' ) ; System.out.println( board1D ) ; System.out.printf( "\n row: %d , column: %d \n", board1D.getRow(), board1D.getColumn() ) ; System.out.printf( " x_Ecell : %d , y_Ecell : %d \n", board1D.getX_Ecell(), board1D.getY_Ecell() ) ; System.out.printf( " last move : %c \n", board1D.lastMove() ) ; System.out.printf( " number of moves : %d \n", board1D.numberOfMoves() ) ; System.out.printf( " number of boards : %d \n", BoardArray1D.NumberOfBoards() ) ; System.out.printf( "\n\n After BoardArray1D object moved left \n\n " ) ; board1D.move( 'L' ) ; System.out.println( board1D ) ; System.out.printf( "\n row: %d , column: %d \n", board1D.getRow(), board1D.getColumn() ) ; System.out.printf( " x_Ecell : %d , y_Ecell : %d \n", board1D.getX_Ecell(), board1D.getY_Ecell() ) ; System.out.printf( " last move : %c \n", board1D.lastMove() ) ; System.out.printf( " number of moves : %d \n", board1D.numberOfMoves() ) ; System.out.printf( " number of boards : %d \n", BoardArray1D.NumberOfBoards() ) ; System.out.printf( "\n\n After BoardArray1D object moved down \n\n " ) ; board1D.move( 'D' ) ; System.out.println( board1D ) ; System.out.printf( "\n row: %d , column: %d \n", board1D.getRow(), board1D.getColumn() ) ; System.out.printf( " x_Ecell : %d , y_Ecell : %d \n", board1D.getX_Ecell(), board1D.getY_Ecell() ) ; System.out.printf( " last move : %c \n", board1D.lastMove() ) ; System.out.printf( " number of moves : %d \n", board1D.numberOfMoves() ) ; System.out.printf( " number of boards : %d \n", BoardArray1D.NumberOfBoards() ) ; System.out.printf( "\n\n After BoardArray1D object moved right \n\n " ) ; board1D.move( 'R' ) ; System.out.println( board1D ) ; System.out.printf( "\n row: %d , column: %d \n", board1D.getRow(), board1D.getColumn() ) ; System.out.printf( " x_Ecell : %d , y_Ecell : %d \n", board1D.getX_Ecell(), board1D.getY_Ecell() ) ; System.out.printf( " last move : %c \n", board1D.lastMove() ) ; System.out.printf( " number of moves : %d \n", board1D.numberOfMoves() ) ; System.out.printf( " number of boards : %d \n", BoardArray1D.NumberOfBoards() ) ; System.out.printf( "\n\n After BoardArray1D object moved up \n\n ") ; board1D.move( 'U' ) ; System.out.println( board1D ) ; System.out.printf( "\n row: %d , column: %d \n", board1D.getRow(), board1D.getColumn() ) ; System.out.printf( " x_Ecell : %d , y_Ecell : %d \n", board1D.getX_Ecell(), board1D.getY_Ecell() ) ; System.out.printf( " last move : %c \n", board1D.lastMove() ) ; System.out.printf( " number of moves : %d \n", board1D.numberOfMoves() ) ; System.out.printf( " number of boards : %d \n", BoardArray1D.NumberOfBoards() ) ; writeFile = new File("txt_files//BoardArray1D_restore.txt") ; board1D.writeToFile( writeFile ); System.out.printf( "\n\n After BoardArray1D object written to file BoardArray1D_restore.txt \n\n " ) ; System.out.println( board1D ) ; System.out.printf( "\n row: %d , column: %d \n", board1D.getRow(), board1D.getColumn() ) ; System.out.printf( " x_Ecell : %d , y_Ecell : %d \n", board1D.getX_Ecell(), board1D.getY_Ecell() ) ; System.out.printf( " last move : %c \n", board1D.lastMove() ) ; System.out.printf( " number of moves : %d \n", board1D.numberOfMoves() ) ; System.out.printf( " number of boards : %d \n", BoardArray1D.NumberOfBoards() ) ; board1D.reset(); System.out.printf( "\n\n After BoardArray1D object reset \n\n " ) ; System.out.println( board1D ) ; System.out.printf( "\n row: %d , column: %d \n", board1D.getRow(), board1D.getColumn() ) ; System.out.printf( " x_Ecell : %d , y_Ecell : %d \n", board1D.getX_Ecell(), board1D.getY_Ecell() ) ; System.out.printf( " last move : %c \n", board1D.lastMove() ) ; System.out.printf( " number of moves : %d \n", board1D.numberOfMoves() ) ; System.out.printf( " number of boards : %d \n", BoardArray1D.NumberOfBoards() ) ; // End of tested BoardArray1D System.out.printf( "\n\n*************************************************************************************************" ) ; System.out.printf( "\n\n TESTING for Equals() function between diffrent derived classes \n\n " ) ; System.out.printf( "\n\n*************************************************************************************************" ) ; // both of them read from equal.txt readFile = new File("txt_files//equal.txt") ; board2D.readFromFile(readFile); board1D.readFromFile(readFile); System.out.printf( "\n Board2D \n%s", board2D.toString() ) ; System.out.printf( "\n Board1D \n%s", board1D.toString() ) ; if( board2D.Equals( board1D ) ) System.out.printf( "\n\n board1D and board2D are equal \n\n" ) ; else System.out.printf( "\n\n board1D and board2D are not equal \n\n" ) ; // one of them readed from equal.txt , one of them read from notEqual.txt readFile = new File("txt_files//notEqual.txt") ; board2D.readFromFile(readFile); System.out.printf( "\n Board2D \n%s", board2D.toString() ) ; System.out.printf( "\n Board1D \n%s", board1D.toString() ) ; if( board2D.Equals( board1D ) ) System.out.printf( "\n\n board1D and board2D are equal \n\n" ) ; else System.out.printf( "\n\n board1D and board2D are not equal \n\n" ) ; System.out.printf( "\n\n*************************************************************************************************" ) ; System.out.printf( "\n\n TESTING for isSolved() function for diffrent derived classes \n\n " ) ; System.out.printf( "\n\n*************************************************************************************************" ) ; System.out.printf( "\n Board2D \n%s", board2D.toString() ) ; // for board2D it readed from equal.txt that has a solution board in it if( board2D.isSolved() ) System.out.printf( "\n\n board2D is solved \n\n" ) ; else System.out.printf( "\n\n board2D is not solved \n\n" ) ; System.out.printf( "\n Board1D \n%s", board1D.toString() ) ; // for board2D it readed from notEqual.txt that has no solution board in it if( board1D.isSolved() ) System.out.printf( "\n\n board1D is solved \n\n" ) ; else System.out.printf( "\n\n board1D is not solved \n\n" ) ; System.out.printf( "\n\n*************************************************************************************************" ) ; System.out.printf( "\n\n TESTING for setSize() function for 3 cases ( to make a bigger puzzle, smaller puzzle and smaller than 3*3 \n\n " ) ; System.out.printf( "\n\n*************************************************************************************************" ) ; // for board1D System.out.printf( "\n\n After board1D setSized 3*3 to 5*5 \n\n" ) ; board1D.setSize(5, 5); System.out.printf( "\n Board1D \n%s", board2D.toString() ) ; System.out.printf( "\n\n After board1D setSized 5*5 to 2*2 \n\n" ) ; board1D.setSize(2, 2); System.out.printf( "\n Board1D \n%s", board2D.toString() ) ; System.out.printf( "\n\n After board1D setSized 2*2 to 3*7 \n\n" ) ; board1D.setSize(3, 7); System.out.printf( "\n Board1D \n%s", board2D.toString() ) ; // for board2D System.out.printf( "\n\n After board2D setSized 3*3 to 5*5 \n\n" ) ; board2D.setSize(5, 5); System.out.printf( "\n board2D \n%s", board2D.toString() ) ; System.out.printf( "\n\n After board2D setSized 5*5 to 2*2 \n\n" ) ; board2D.setSize(2, 2); System.out.printf( "\n board2D \n%s", board2D.toString() ) ; System.out.printf( "\n\n After board2D setSized 2*2 to 3*7 \n\n" ) ; board2D.setSize(3, 7); System.out.printf( "\n board2D \n%s", board2D.toString() ) ; System.out.printf( "\n\n*************************************************************************************************" ) ; System.out.printf( "\n\n TESTING for GLOBAL TEST FUNCTION \n\n " ) ; System.out.printf( "\n\n*************************************************************************************************" ) ; AbstractBoard AbstractBoardArray_test1[] = new AbstractBoard [6] ; BoardArray1D board1D_1 = new BoardArray1D() ; BoardArray1D board1D_2 = new BoardArray1D() ; BoardArray1D board1D_3 = new BoardArray1D() ; BoardArray2D board2D_4 = new BoardArray2D() ; BoardArray2D board2D_5 = new BoardArray2D() ; BoardArray2D board2D_6 = new BoardArray2D() ; readFile = new File("txt_files//test_global_function//test1.txt"); board1D_1.readFromFile(readFile); readFile = new File("txt_files//test_global_function//test2.txt"); board1D_2.readFromFile(readFile); readFile = new File("txt_files//test_global_function//test3.txt"); board1D_3.readFromFile(readFile); readFile = new File("txt_files//test_global_function//test4.txt"); board2D_4.readFromFile(readFile); readFile = new File("txt_files//test_global_function//test5.txt"); board2D_5.readFromFile(readFile); readFile = new File("txt_files//test_global_function//test6.txt"); board2D_6.readFromFile(readFile); AbstractBoardArray_test1[0] = board1D_1 ; AbstractBoardArray_test1[1] = board1D_2 ; AbstractBoardArray_test1[2] = board1D_3 ; AbstractBoardArray_test1[3] = board2D_4 ; AbstractBoardArray_test1[4] = board2D_5 ; AbstractBoardArray_test1[5] = board2D_6 ; // test 1 System.out.printf( "\n\n****************** Test 1 ********************************\n\n" ) ; for (int i = 0; i < 6; ++i) { System.out.printf( "\n\n board %d\n\n %s", i+1, AbstractBoardArray_test1[i] ) ; } if( test( AbstractBoardArray_test1, 6 ) ) System.out.printf( "\n\n 1.test is valid\n\n" ) ; else System.out.printf( "\n\n 1.test is not valid\n\n" ) ; // test 2 AbstractBoardArray_test1[5] = board2D_5 ; System.out.printf( "\n\n****************** Test 2 ********************************\n\n" ) ; for (int i = 0; i < 6; ++i) { System.out.printf( "\n\n board %d\n\n %s", i+1, AbstractBoardArray_test1[i] ) ; } if( test( AbstractBoardArray_test1, 6 ) ) System.out.printf( "\n\n 2.test is valid\n\n" ) ; else System.out.printf( "\n\n 2.test is not valid\n\n" ) ; // test 3 AbstractBoardArray_test1[5] = board2D_6 ; AbstractBoardArray_test1[2] = board2D_5 ; System.out.printf( "\n\n****************** Test 3 ********************************\n\n" ) ; for (int i = 0; i < 6; ++i) { System.out.printf( "\n\n board %d\n\n %s", i+1, AbstractBoardArray_test1[i] ) ; } if( test( AbstractBoardArray_test1, 6 ) ) System.out.printf( "\n\n 3.test is valid\n\n" ) ; else System.out.printf( "\n\n 3.test is not valid\n\n" ) ; // test 4 AbstractBoardArray_test1[2] = board1D_3 ; System.out.printf( "\n\n****************** Test 4 ********************************\n\n" ) ; for (int i = 0; i < 6; ++i) { System.out.printf( "\n\n board %d\n\n %s", i+1, AbstractBoardArray_test1[i] ) ; } if( test( AbstractBoardArray_test1, 6 ) ) System.out.printf( "\n\n 4.test is valid\n\n" ) ; else System.out.printf( "\n\n 4.test is not valid\n\n" ) ; // test 5 AbstractBoardArray_test1[3] = board1D_3 ; System.out.printf( "\n\n****************** Test 5 ********************************\n\n" ) ; for (int i = 0; i < 6; ++i) { System.out.printf( "\n\n board %d\n\n %s", i+1, AbstractBoardArray_test1[i] ) ; } if( test( AbstractBoardArray_test1, 6 ) ) System.out.printf( "\n\n 5.test is valid\n\n" ) ; else System.out.printf( "\n\n 5.test is not valid\n\n" ) ; } }
922fe86acf6e82e806b6a7c7393f360845b12717
1,378
java
Java
yoma-core/src/main/java/com/github/yoma/core/domain/BaseDictDetail.java
msh01/yoma
50b46bccf3e0b2885d451badbeeacf56d4b82777
[ "Apache-2.0" ]
164
2021-03-13T14:53:56.000Z
2022-03-29T01:59:38.000Z
yoma-core/src/main/java/com/github/yoma/core/domain/BaseDictDetail.java
chenguomeng/yoma
50b46bccf3e0b2885d451badbeeacf56d4b82777
[ "Apache-2.0" ]
1
2021-05-11T16:06:05.000Z
2022-03-26T08:10:32.000Z
yoma-core/src/main/java/com/github/yoma/core/domain/BaseDictDetail.java
chenguomeng/yoma
50b46bccf3e0b2885d451badbeeacf56d4b82777
[ "Apache-2.0" ]
12
2021-04-09T04:57:04.000Z
2022-03-29T01:59:39.000Z
24.607143
96
0.707547
995,295
package com.github.yoma.core.domain; import java.time.LocalDateTime; import javax.persistence.*; import com.github.yoma.common.persistence.DataEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * 数据字典详情Entity 既是实体对象,又是数据传输对象(接收页面请求参数),同时又是值对象(为页面提供渲染所需数据) 基于lombok ,所以无需生成getter 和 setter方法 * * @author 马世豪 * @version 2020-12-15 */ @Data @Table(name = "base_dict_detail") @ApiModel(value = "BaseDictDetail", description = "数据字典详情") public class BaseDictDetail extends DataEntity<BaseDictDetail> { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") @ApiModelProperty(value = "ID") private Long id; @Column(name = "dict_id") @ApiModelProperty(value = "字典id") private Long dictId; @Column(name = "label") @ApiModelProperty(value = "字典标签") private String label; @Column(name = "value") @ApiModelProperty(value = "字典值") private String value; @Column(name = "dict_sort") @ApiModelProperty(value = "排序") private Integer dictSort; @Column(name = "create_time") @ApiModelProperty(value = "创建日期") private LocalDateTime createTime; @Column(name = "update_time") @ApiModelProperty(value = "更新时间") private LocalDateTime updateTime; }
922fe8c30a0c42c4fa9cb7c19def01fa6388900a
1,759
java
Java
app/src/main/java/es/urjc/LDMpiratas/androidimpl/AndroidInput.java
mtenrero/LPiratas7Mares
cd8b29ea72e4a93de11f972b42c47c28fedb93ea
[ "MIT" ]
null
null
null
app/src/main/java/es/urjc/LDMpiratas/androidimpl/AndroidInput.java
mtenrero/LPiratas7Mares
cd8b29ea72e4a93de11f972b42c47c28fedb93ea
[ "MIT" ]
null
null
null
app/src/main/java/es/urjc/LDMpiratas/androidimpl/AndroidInput.java
mtenrero/LPiratas7Mares
cd8b29ea72e4a93de11f972b42c47c28fedb93ea
[ "MIT" ]
null
null
null
24.09589
81
0.673678
995,296
package es.urjc.LDMpiratas.androidimpl; /** * Created by liliana.santacruz on 14/11/2016. */ import android.content.Context; import android.os.Build.VERSION; import android.view.View; import es.urjc.LDMpiratas.liliana.core.Input; import java.util.List; public class AndroidInput implements Input { AccelerometerHandler accelHandler; KeyboardHandler keyHandler; TouchHandler touchHandler; public AndroidInput(Context context, View view, float scaleX, float scaleY) { accelHandler = new AccelerometerHandler(context); keyHandler = new KeyboardHandler(view); if (Integer.parseInt(VERSION.SDK) < 5) touchHandler = new SingleTouchHandler(view, scaleX, scaleY); else touchHandler = new MultiTouchHandler(view, scaleX, scaleY); } @Override public boolean isKeyPressed(int keyCode) { return keyHandler.isKeyPressed(keyCode); } @Override public boolean isTouchDown(int pointer) { return touchHandler.isTouchDown(pointer); } @Override public int getTouchX(int pointer) { return touchHandler.getTouchX(pointer); } @Override public int getTouchY(int pointer) { return touchHandler.getTouchY(pointer); } @Override public float getAccelX() { return accelHandler.getAccelX(); } @Override public float getAccelY() { return accelHandler.getAccelY(); } @Override public float getAccelZ() { return accelHandler.getAccelZ(); } @Override public List<TouchEvent> getTouchEvents() { return touchHandler.getTouchEvents(); } @Override public List<KeyEvent> getKeyEvents() { return keyHandler.getKeyEvents(); } }
922fe8c7ea9dd7b1406da5eb80ece72657547afe
2,087
java
Java
sdk/src/main/java/com/hcaptcha/sdk/HCaptchaError.java
hCaptcha/hcaptcha-android-sdk
af109c5ad8b52b50922dc5d9116ed85b6599b52e
[ "MIT" ]
17
2021-04-11T17:06:59.000Z
2022-03-21T01:17:45.000Z
sdk/src/main/java/com/hcaptcha/sdk/HCaptchaError.java
coyotie24/hcaptcha-android-sdk
810bba17199093028303c568868dcf1b6e400b37
[ "MIT" ]
17
2021-01-26T01:13:35.000Z
2022-03-31T17:44:50.000Z
sdk/src/main/java/com/hcaptcha/sdk/HCaptchaError.java
coyotie24/hcaptcha-android-sdk
810bba17199093028303c568868dcf1b6e400b37
[ "MIT" ]
8
2021-04-11T16:42:13.000Z
2022-03-29T13:28:12.000Z
23.715909
155
0.61907
995,297
package com.hcaptcha.sdk; import androidx.annotation.NonNull; import java.io.Serializable; /** * Enum with all possible hCaptcha errors */ public enum HCaptchaError implements Serializable { /** * Internet connection is missing. * * Make sure AndroidManifest requires internet permission: {@code {@literal <}uses-permission android:name="android.permission.INTERNET" /{@literal >}} */ NETWORK_ERROR(7, "No internet connection"), /** * hCaptcha session timed out either the token or challenge expired */ SESSION_TIMEOUT(15, "Session Timeout"), /** * User closed the challenge by pressing `back` button or touching the outside of the dialog. */ CHALLENGE_CLOSED(30, "Challenge Closed"), /** * Rate limited due to too many tries. */ RATE_LIMITED(31, "Rate Limited"), /** * Generic error for unknown situations - should never happen. */ ERROR(29, "Unknown error"); private final int errorId; private final String message; HCaptchaError(final int errorId, final String message) { this.errorId = errorId; this.message = message; } /** * @return the integer encoding of the enum */ public int getErrorId() { return this.errorId; } /** * @return the error message */ public String getMessage() { return this.message; } @NonNull @Override public String toString() { return message; } /** * Finds the enum based on the integer encoding * * @param errorId the integer encoding * @return the {@link HCaptchaError} object * @throws RuntimeException when no match */ @NonNull public static HCaptchaError fromId(final int errorId) { final HCaptchaError[] errors = HCaptchaError.values(); for (final HCaptchaError error : errors) { if (error.errorId == errorId) { return error; } } throw new RuntimeException("Unsupported error id: " + errorId); } }
922fe9667627baa226d029fc5d58a327eedb9cd0
1,657
java
Java
app/src/main/java/com/ve/utils/SysUtils.java
GhodelApps/CodeEditor-1
5e785d20085ebfe92bf01bbbb599ab5326862c0a
[ "Apache-2.0" ]
16
2019-02-19T13:23:12.000Z
2022-01-07T01:01:14.000Z
app/src/main/java/com/ve/utils/SysUtils.java
GhodelApps/CodeEditor-1
5e785d20085ebfe92bf01bbbb599ab5326862c0a
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/ve/utils/SysUtils.java
GhodelApps/CodeEditor-1
5e785d20085ebfe92bf01bbbb599ab5326862c0a
[ "Apache-2.0" ]
2
2020-11-26T09:04:16.000Z
2022-02-28T19:54:22.000Z
35.255319
127
0.633072
995,298
package com.ve.utils; import android.annotation.SuppressLint; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.view.View; import android.view.inputmethod.InputMethodManager; public class SysUtils { public static void showInputMethod(View view, boolean show) { InputMethodManager im = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); if (show) { im.showSoftInput(view, 0); im.restartInput(view); } else { im.hideSoftInputFromWindow(view.getWindowToken(), 0); } } public static boolean isInputMethodShow(View view) { InputMethodManager im = (InputMethodManager) view.getContext() .getSystemService(Context.INPUT_METHOD_SERVICE); return im.isActive(); } public static boolean isNetworkAvailable(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager == null) { return false; } else { @SuppressLint("MissingPermission") NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo(); if (networkInfo != null && networkInfo.length > 0) { for (int i = 0; i < networkInfo.length; i++) { // 判断当前网络状态是否为连接状态 if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; } }
922fe9de6cb07964d84a9c69b9f38ba29605c11f
1,997
java
Java
app/src/main/java/com/mr_mo/fragmenttabhostdemo/ui/MainActivity.java
MrxMo/FragmentTabHostDemo
02d4cc5e638eb455e66e900698bab085a46c1d14
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/mr_mo/fragmenttabhostdemo/ui/MainActivity.java
MrxMo/FragmentTabHostDemo
02d4cc5e638eb455e66e900698bab085a46c1d14
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/mr_mo/fragmenttabhostdemo/ui/MainActivity.java
MrxMo/FragmentTabHostDemo
02d4cc5e638eb455e66e900698bab085a46c1d14
[ "Apache-2.0" ]
null
null
null
36.309091
133
0.725588
995,299
package com.mr_mo.fragmenttabhostdemo.ui; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTabHost; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TabHost.TabSpec; import android.widget.TextView; import com.mr_mo.fragmenttabhostdemo.R; import com.mr_mo.fragmenttabhostdemo.ui.EndFragment; import com.mr_mo.fragmenttabhostdemo.ui.IndexFragment; import com.mr_mo.fragmenttabhostdemo.ui.MiddleFragment; /** * 首页 * Created by moguangjian on 15/8/11 13:47. */ public class MainActivity extends FragmentActivity { private FragmentTabHost tabHost; private Class fragmentArray[] = {IndexFragment.class, MiddleFragment.class, EndFragment.class}; private int iconArray[] = {R.drawable.sl_tab_bar_item_index, R.drawable.sl_tab_bar_item_middle, R.drawable.sl_tab_bar_item_end,}; private String titleArray[] = {"首页", "中页", "尾页"}; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initTabHost(); } private void initTabHost() { tabHost = (FragmentTabHost) findViewById(android.R.id.tabhost); tabHost.setup(this, getSupportFragmentManager(), R.id.content); int count = fragmentArray.length; for (int i = 0; i < count; i++) { TabSpec tabSpec = tabHost.newTabSpec(titleArray[i]).setIndicator(getTabBarItemView(i)); tabHost.addTab(tabSpec, fragmentArray[i], null); } } private View getTabBarItemView(int index) { View view = LayoutInflater.from(this).inflate(R.layout.tab_bar_item, null); ImageView imageView = (ImageView) view.findViewById(R.id.ivIcon); imageView.setImageResource(iconArray[index]); TextView textView = (TextView) view.findViewById(R.id.tvTitle); textView.setText(titleArray[index]); return view; } }
922fe9f21eeba8c9c692e29090fd4152f55f4c1e
1,230
java
Java
service-layer/src/main/java/com/iluwatar/servicelayer/hibernate/HibernateUtil.java
saifulazad/java-design-patterns
fbb22d56ccf5bcef36c10533796e9ac6973b0537
[ "MIT" ]
55
2015-12-16T06:47:54.000Z
2022-02-24T22:44:16.000Z
service-layer/src/main/java/com/iluwatar/servicelayer/hibernate/HibernateUtil.java
saifulazad/java-design-patterns
fbb22d56ccf5bcef36c10533796e9ac6973b0537
[ "MIT" ]
1
2022-01-21T23:49:16.000Z
2022-01-21T23:49:16.000Z
service-layer/src/main/java/com/iluwatar/servicelayer/hibernate/HibernateUtil.java
saifulazad/java-design-patterns
fbb22d56ccf5bcef36c10533796e9ac6973b0537
[ "MIT" ]
24
2015-09-16T15:50:19.000Z
2021-10-10T22:01:52.000Z
30
86
0.735772
995,300
package com.iluwatar.servicelayer.hibernate; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.iluwatar.servicelayer.servicelayer.spell.Spell; import com.iluwatar.servicelayer.spellbook.Spellbook; import com.iluwatar.servicelayer.wizard.Wizard; /** * * Produces the Hibernate SessionFactory. * */ public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { sessionFactory = new Configuration() .addAnnotatedClass(Wizard.class) .addAnnotatedClass(Spellbook.class) .addAnnotatedClass(Spell.class) .setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect") .setProperty("hibernate.connection.url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1") .setProperty("hibernate.current_session_context_class", "thread") .setProperty("hibernate.show_sql", "true") .setProperty("hibernate.hbm2ddl.auto", "create-drop") .buildSessionFactory(); } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }
922fea007b604fba657e50a7a013916f55c7e4aa
279
java
Java
socket-common-interface/src/main/java/com/xuhao/didi/socket/common/interfaces/common_interfacies/server/IServerManagerPrivate.java
Creky/OkSocket
8406170d3d9fff16ef6d71cfe5e6313b4a14419c
[ "MIT" ]
2,908
2017-10-12T17:35:43.000Z
2022-03-30T07:22:54.000Z
socket-common-interface/src/main/java/com/xuhao/didi/socket/common/interfaces/common_interfacies/server/IServerManagerPrivate.java
Creky/OkSocket
8406170d3d9fff16ef6d71cfe5e6313b4a14419c
[ "MIT" ]
196
2017-10-13T05:50:01.000Z
2022-03-10T09:39:20.000Z
socket-common-interface/src/main/java/com/xuhao/didi/socket/common/interfaces/common_interfacies/server/IServerManagerPrivate.java
Creky/OkSocket
8406170d3d9fff16ef6d71cfe5e6313b4a14419c
[ "MIT" ]
424
2017-10-13T01:42:29.000Z
2022-03-28T05:28:48.000Z
27.9
92
0.827957
995,301
package com.xuhao.didi.socket.common.interfaces.common_interfacies.server; import com.xuhao.didi.core.iocore.interfaces.IIOCoreOptions; public interface IServerManagerPrivate<E extends IIOCoreOptions> extends IServerManager<E> { void initServerPrivate(int serverPort); }
922fea5cc503c5f6d72d7fae7d205c151cc924d1
4,812
java
Java
core/src/test/java/com/linecorp/armeria/server/HttpServerTlsCorruptionTest.java
nvidyala/armeria
7231cee1a22942e1f0014ff36f543e89bca9b160
[ "Apache-2.0" ]
1
2021-12-21T17:43:39.000Z
2021-12-21T17:43:39.000Z
core/src/test/java/com/linecorp/armeria/server/HttpServerTlsCorruptionTest.java
nvidyala/armeria
7231cee1a22942e1f0014ff36f543e89bca9b160
[ "Apache-2.0" ]
1
2022-03-04T06:03:14.000Z
2022-03-04T06:03:14.000Z
core/src/test/java/com/linecorp/armeria/server/HttpServerTlsCorruptionTest.java
nvidyala/armeria
7231cee1a22942e1f0014ff36f543e89bca9b160
[ "Apache-2.0" ]
null
null
null
38.806452
100
0.589568
995,302
/* * Copyright 2021 LINE Corporation * * LINE Corporation licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://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.linecorp.armeria.server; import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadLocalRandom; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.linecorp.armeria.client.ClientFactory; import com.linecorp.armeria.client.WebClient; import com.linecorp.armeria.common.Flags; import com.linecorp.armeria.common.HttpData; import com.linecorp.armeria.common.HttpResponse; import com.linecorp.armeria.common.HttpResponseWriter; import com.linecorp.armeria.common.HttpStatus; import com.linecorp.armeria.common.ResponseHeaders; import com.linecorp.armeria.common.SessionProtocol; import com.linecorp.armeria.testing.junit5.server.ServerExtension; class HttpServerTlsCorruptionTest { private static final Logger logger = LoggerFactory.getLogger(HttpServerTlsCorruptionTest.class); private static final HttpData content; static { final byte[] data = new byte[1048576]; ThreadLocalRandom.current().nextBytes(data); content = HttpData.wrap(data); } @RegisterExtension static final ServerExtension server = new ServerExtension() { @Override protected void configure(ServerBuilder sb) throws Exception { sb.https(0); sb.tlsSelfSigned(); sb.service("/", (ctx, req) -> { // Use a streaming response to generate HTTP chunks. final HttpResponseWriter res = HttpResponse.streaming(); res.write(ResponseHeaders.of(200)); for (int i = 0; i < content.length();) { final int chunkSize = Math.min(32768, content.length() - i); res.write(HttpData.wrap(content.array(), i, chunkSize)); i += chunkSize; } res.close(); return res; }); } }; /** * Makes sure Armeria is unaffected by https://github.com/netty/netty/issues/11792 */ @Test void test() throws Throwable { final int numEventLoops = Flags.numCommonWorkers(); final ClientFactory clientFactory = ClientFactory.builder() .tlsNoVerify() .maxNumEventLoopsPerEndpoint(numEventLoops) .maxNumEventLoopsPerHttp1Endpoint(numEventLoops) .build(); final WebClient client = WebClient.builder(server.uri(SessionProtocol.H1)) .factory(clientFactory) .build(); final Semaphore semaphore = new Semaphore(numEventLoops); final BlockingQueue<Throwable> caughtExceptions = new LinkedBlockingDeque<>(); int i = 0; try { for (; i < 1000; i++) { server.requestContextCaptor().clear(); semaphore.acquire(); client.get("/") .aggregate() .handle((res, cause) -> { semaphore.release(); if (cause != null) { caughtExceptions.add(cause); } else { try { assertThat(res.status()).isSameAs(HttpStatus.OK); assertThat(res.content()).isEqualTo(content); } catch (Throwable t) { caughtExceptions.add(t); } } return null; }); final Throwable cause = caughtExceptions.poll(); if (cause != null) { throw cause; } } } catch (Throwable cause) { logger.warn("Received a corrupt response after {} request(s)", i); throw cause; } clientFactory.close(); } }
922fea798266c079809391600a736e157860edc6
1,064
java
Java
src/main/java/weibo4j/model/StatusVisible.java
qqxadyy/weibo-openapi-4java
775a09058b804131a1a70bc2fe87dce0c9586f30
[ "MIT" ]
null
null
null
src/main/java/weibo4j/model/StatusVisible.java
qqxadyy/weibo-openapi-4java
775a09058b804131a1a70bc2fe87dce0c9586f30
[ "MIT" ]
null
null
null
src/main/java/weibo4j/model/StatusVisible.java
qqxadyy/weibo-openapi-4java
775a09058b804131a1a70bc2fe87dce0c9586f30
[ "MIT" ]
null
null
null
30.4
85
0.694549
995,303
/* * Copyright © 2021 pengjianqiang * All rights reserved. * 项目名称:微博开放平台API-JAVA SDK * 项目描述:基于微博开放平台官网的weibo4j-oauth2-beta3.1.1包及新版接口做二次开发 * 项目地址:https://github.com/qqxadyy/weibo-openapi-4java * 许可证信息:见下文 * * ====================================================================== * * src/main/java/weibo4j下的文件是从weibo4j-oauth2-beta3.1.1.zip中复制出来的 * 本项目对这个目录下的部分源码做了重新改造 * 但是许可信息和"https://github.com/sunxiaowei2014/weibo4j-oauth2-beta3.1.1"或源码中已存在的保持一致 */ package weibo4j.model; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import pjq.weibo.openapi.support.WeiboJsonName; import weibo4j.org.json.JSONObject; @Data @EqualsAndHashCode(callSuper = false) @NoArgsConstructor @WeiboJsonName @SuppressWarnings("serial") public class StatusVisible extends WeiboResponse { private int type; // 微博的可见性及指定可见分组信息。0:普通微博,1:私密微博,3:指定分组微博,4:密友微博;list_id为分组的组号 private @WeiboJsonName("list_id") String listid; public StatusVisible(JSONObject json) { super(json); } }
922feb5f200458024e115ca0cda21b583a5a89db
3,074
java
Java
src/main/java/org/hzero/report/infra/util/XmlUtils.java
Bill2718/hzero-report
ce55f3d50f2ccea2537b20b38566191ccd3950cf
[ "Apache-2.0" ]
null
null
null
src/main/java/org/hzero/report/infra/util/XmlUtils.java
Bill2718/hzero-report
ce55f3d50f2ccea2537b20b38566191ccd3950cf
[ "Apache-2.0" ]
1
2020-12-14T09:31:14.000Z
2020-12-14T09:31:14.000Z
src/main/java/org/hzero/report/infra/util/XmlUtils.java
Bill2718/hzero-report
ce55f3d50f2ccea2537b20b38566191ccd3950cf
[ "Apache-2.0" ]
14
2020-09-23T07:57:08.000Z
2021-11-23T13:54:17.000Z
28.555556
92
0.668288
995,304
package org.hzero.report.infra.util; import java.io.File; import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * XmlUtil,封装了一些以DOM方式获得Xml对象的方法 。<br/> * <b>仅mulThreadParse方法是线程安全的</b> * * @author efpyi@example.com 2018年11月28日下午3:04:21 */ public class XmlUtils { private static final Logger logger = LoggerFactory.getLogger(XmlUtils.class); private static DocumentBuilder builder; private static final DocumentBuilderFactory FACTORY; private XmlUtils() throws IllegalAccessException { throw new IllegalAccessException(); } static { FACTORY = DocumentBuilderFactory.newInstance(); try { builder = FACTORY.newDocumentBuilder(); } catch (ParserConfigurationException e) { logger.error("error", e); } } /** * 通过一个InputSource来创建Xml文档对象 * * @param inputSource 包含Xml文本信息的InputSource * @return 文档对象 */ public static Document parse(InputSource inputSource) throws SAXException, IOException { return builder.parse(inputSource); } /** * 通过一个InputStream来创建Xml文档对象 * * @param inputStream 包含Xml文本信息的InputStream * @return Xml文档对象 */ public static Document parse(InputStream inputStream) throws SAXException, IOException { return builder.parse(inputStream); } /** * 通过一个File来创建Xml文档对象 * * @param file 包含Xml文本信息的File对象 * @return Xml文档对象 */ public static Document parse(File file) throws SAXException, IOException { return builder.parse(file); } /** * 通过一个url来创建Xml文档对象<br/> * <b style="color:red;">注意此方法不是解析String类型Xml文本的方法,若想解析,请将String对象转化为InputStream</b> * * @param url 获得Xml文本的URL * @return Xml文档对象 */ public static Document parse(String url) throws SAXException, IOException { return builder.parse(url.replace(" ", "%20")); } /** * 可用于线程安全的解析函数<br/> * <i>参数类型说明参考其他parse函数</i> * * @param param 参数,必须是String/File/InputStream/InputSource中的一种 * @return Xml文档对象 */ public static Document mulThreadParse(Object param) throws SAXException, IOException, ParserConfigurationException { if (param instanceof String) { return FACTORY.newDocumentBuilder().parse((String) param); } if (param instanceof File) { return FACTORY.newDocumentBuilder().parse((File) param); } if (param instanceof InputStream) { return FACTORY.newDocumentBuilder().parse((InputStream) param); } if (param instanceof InputSource) { return FACTORY.newDocumentBuilder().parse((InputSource) param); } throw new IllegalArgumentException("不接受此类型的参数"); } }
922feb7dcea78a7a460d4c8009a1036946ab95d9
1,512
java
Java
src/main/java/com/github/loki/afro/metallum/search/query/LabelSearchQuery.java
RefactoringBotUser/metalarchives
fbb62951bcaa00bf924786b5da5ff2257a531fc0
[ "Beerware" ]
null
null
null
src/main/java/com/github/loki/afro/metallum/search/query/LabelSearchQuery.java
RefactoringBotUser/metalarchives
fbb62951bcaa00bf924786b5da5ff2257a531fc0
[ "Beerware" ]
null
null
null
src/main/java/com/github/loki/afro/metallum/search/query/LabelSearchQuery.java
RefactoringBotUser/metalarchives
fbb62951bcaa00bf924786b5da5ff2257a531fc0
[ "Beerware" ]
null
null
null
30.24
131
0.721561
995,305
package com.github.loki.afro.metallum.search.query; import com.github.loki.afro.metallum.core.parser.search.AbstractSearchParser; import com.github.loki.afro.metallum.core.util.net.MetallumURL; import com.github.loki.afro.metallum.entity.Label; import com.github.loki.afro.metallum.search.AbstractSearchQuery; import com.github.loki.afro.metallum.search.SearchRelevance; import java.util.List; import java.util.SortedMap; public class LabelSearchQuery extends AbstractSearchQuery<Label> { public LabelSearchQuery() { // the zero does not matter here... super(new Label()); } public LabelSearchQuery(final Label inputLabel) { super(inputLabel); } public void setLabelName(final String name) { this.searchObject.setName(name); } @Override protected final String assembleSearchQuery(final int startPage) { final String labelName = this.searchObject.getName(); this.isAValidQuery = !labelName.isEmpty(); return MetallumURL.assembleLabelSearchURL(labelName, startPage); } @Override protected void setSpecialFieldsInParser(final AbstractSearchParser<Label> parser) { // there is nothing to set, because this is a simple query } @Override public void reset() { this.searchObject = new Label(); } @Override protected SortedMap<SearchRelevance, List<Label>> enrichParsedEntity(final SortedMap<SearchRelevance, List<Label>> resultMap) { return resultMap; } }
922feba7630ede04fa74beb83082a3862dc1fa3f
2,414
java
Java
pia/phyutility/src/jebl/evolution/align/AlignRepeat.java
MartinGuehmann/PIA2
d7af357f3f66ba45d7de50bd6701ef3a5ffd974e
[ "MIT" ]
null
null
null
pia/phyutility/src/jebl/evolution/align/AlignRepeat.java
MartinGuehmann/PIA2
d7af357f3f66ba45d7de50bd6701ef3a5ffd974e
[ "MIT" ]
null
null
null
pia/phyutility/src/jebl/evolution/align/AlignRepeat.java
MartinGuehmann/PIA2
d7af357f3f66ba45d7de50bd6701ef3a5ffd974e
[ "MIT" ]
2
2019-07-06T12:43:53.000Z
2020-03-02T18:31:44.000Z
27.123596
86
0.492543
995,306
package jebl.evolution.align; import jebl.evolution.align.scores.Scores; abstract class AlignRepeat extends Align { float[][] F; // the matrix used to compute the alignment TracebackSimple[][] B; // the traceback matrix int T; // threshold public AlignRepeat(Scores sub, float d, int T) { super(sub, d); this.T = T; } /** * Performs the alignment. Abstract. * * @param sq1 * @param sq2 */ public abstract void doAlignment(String sq1, String sq2); public void prepareAlignment(String sq1, String sq2) { this.n = sq1.length(); this.m = sq2.length(); this.seq1 = sq1; this.seq2 = sq2; //first time running this alignment. Create all new matrices. if(F == null) { F = new float[n+1][m+1]; B = new TracebackSimple[n+1][m+1]; for(int i = 0; i < n+1; i ++) { for(int j = 0; j < m+1; j++) B[i][j] = new TracebackSimple(0,0); } } //alignment already been run but matrices not big enough for new alignment. //create all new matrices. else if(sq1.length() > n || sq2.length() > m) { F = new float[n+1][m+1]; B = new TracebackSimple[n+1][m+1]; for(int i = 0; i < n+1; i ++) { for(int j = 0; j < m+1; j++) B[i][j] = new TracebackSimple(0,0); } } } public void setThreshold(int T) { this.T = T; } /** * Get the next state in the traceback * * @param tb current Traceback * @return next Traceback */ public Traceback next(Traceback tb) { TracebackSimple tb2 = (TracebackSimple)tb; if(tb.i == 0 && tb.j == 0 && B[tb2.i][tb2.j].i == 0 && B[tb2.i][tb2.j].j == 0) return null; else return B[tb2.i][tb2.j]; } /** * @return the score of the best alignment */ public float getScore() { return F[B0.i][B0.j]; } /** * Print matrix used to calculate this alignment. * * @param out Output to print to. */ public void printf(Output out) { for (int j=0; j<=m; j++) { for (float[] f : F) { out.print(padLeft(formatScore(f[j]), 5)); } out.println(); } } }
922fec1215d97b5337bd20ad68de8b121218b75f
766
java
Java
src/test/java/motoresdebusqueda/restoolApp/tareas/Decidido.java
chuckkznm911/PO-Screenplay-Practice
c0377131f14221694c91deaed46280233cd7aaed
[ "Apache-2.0" ]
null
null
null
src/test/java/motoresdebusqueda/restoolApp/tareas/Decidido.java
chuckkznm911/PO-Screenplay-Practice
c0377131f14221694c91deaed46280233cd7aaed
[ "Apache-2.0" ]
null
null
null
src/test/java/motoresdebusqueda/restoolApp/tareas/Decidido.java
chuckkznm911/PO-Screenplay-Practice
c0377131f14221694c91deaed46280233cd7aaed
[ "Apache-2.0" ]
null
null
null
27.357143
68
0.76893
995,307
package motoresdebusqueda.restoolApp.tareas; import motoresdebusqueda.restoolApp.constantes.Constantes; import motoresdebusqueda.restoolApp.navegacion.Navegar; import net.serenitybdd.screenplay.Actor; import net.serenitybdd.screenplay.Performable; import net.serenitybdd.screenplay.Task; import net.thucydides.core.annotations.Step; import static net.serenitybdd.screenplay.Tasks.instrumented; public class Decidido implements Task { public Decidido(){ } public static Performable abrirElNavegador(){ return instrumented(Decidido.class); } @Override @Step("{0} ha decidido dar de alta un ítem") public <T extends Actor> void performAs(T actor) { actor.attemptsTo(Navegar.hacia(Constantes.paginaPrincipal)); } }
922fed259cdf000e3c646f80e685dbf33b2b3902
2,351
java
Java
cdap-metadata-spi/src/main/java/io/cdap/cdap/spi/metadata/MetadataMutationCodec.java
aonischuk/cdap
0d7cbdf3a059549de4cca3f457ba81c37909f632
[ "Apache-2.0" ]
369
2018-12-11T08:30:05.000Z
2022-03-30T09:32:53.000Z
cdap-metadata-spi/src/main/java/io/cdap/cdap/spi/metadata/MetadataMutationCodec.java
aonischuk/cdap
0d7cbdf3a059549de4cca3f457ba81c37909f632
[ "Apache-2.0" ]
8,921
2015-01-01T16:40:44.000Z
2018-11-29T21:58:11.000Z
cdap-metadata-spi/src/main/java/io/cdap/cdap/spi/metadata/MetadataMutationCodec.java
aonischuk/cdap
0d7cbdf3a059549de4cca3f457ba81c37909f632
[ "Apache-2.0" ]
189
2018-11-30T20:11:08.000Z
2022-03-25T02:55:39.000Z
38.540984
119
0.723522
995,308
/* * Copyright © 2019 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.cdap.cdap.spi.metadata; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import java.lang.reflect.Type; /** * JSON codec for metadata mutations, this is needed to deserialize the correct subclasses of metadata mutataions. */ public class MetadataMutationCodec implements JsonSerializer<MetadataMutation>, JsonDeserializer<MetadataMutation> { @Override public MetadataMutation deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (!typeOfT.equals(MetadataMutation.class)) { return context.deserialize(json, typeOfT); } String type = json.getAsJsonObject().get("type").getAsString(); switch (MetadataMutation.Type.valueOf(type)) { case CREATE: return context.deserialize(json, MetadataMutation.Create.class); case REMOVE: return context.deserialize(json, MetadataMutation.Remove.class); case DROP: return context.deserialize(json, MetadataMutation.Drop.class); case UPDATE: return context.deserialize(json, MetadataMutation.Update.class); default: throw new IllegalArgumentException(String.format("Unsupported metadata mutation type %s, only " + "supported types are CREATE, REMOVE, DROP, UPDATE.", type)); } } @Override public JsonElement serialize(MetadataMutation src, Type typeOfSrc, JsonSerializationContext context) { return context.serialize(src); } }
922feda20924146bee0aa999199f08e0134b79b9
1,644
java
Java
DeepLinkActivity.java
debolabanks/HPD
92947cbfeb767cbda486c9df0faa77af9ed67f9d
[ "Apache-2.0" ]
null
null
null
DeepLinkActivity.java
debolabanks/HPD
92947cbfeb767cbda486c9df0faa77af9ed67f9d
[ "Apache-2.0" ]
null
null
null
DeepLinkActivity.java
debolabanks/HPD
92947cbfeb767cbda486c9df0faa77af9ed67f9d
[ "Apache-2.0" ]
null
null
null
29.890909
78
0.673966
995,309
package com.minimanager.enesihealthapp; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import com.google.android.gms.appinvite.AppInviteReferral; public class DeepLinkActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG = DeepLinkActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_deep_link); findViewById(R.id.button_ok).setOnClickListener(this); } @Override protected void onStart() { super.onStart(); Intent intent = getIntent(); if (AppInviteReferral.hasReferral(intent)) { processReferralIntent(intent); } } private void processReferralIntent(Intent intent) { String invitationId = AppInviteReferral.getInvitationId(intent); String deepLink = AppInviteReferral.getDeepLink(intent); Log.d(TAG, "Found Referral: " + invitationId + ":" + deepLink); ((TextView) findViewById(R.id.deep_link_text)) .setText(getString(R.string.deep_link_fmt, deepLink)); ((TextView) findViewById(R.id.invitation_id_text)) .setText(getString(R.string.invitation_id_fmt, invitationId)); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button_ok: finish(); break; } } }
922fedc676e0e3457df6ccc5efbd055c5ff8914e
1,446
java
Java
plugins/InspectionGadgets/testsrc/com/siyeh/ig/bugs/IgnoreResultOfCallInspectionTest.java
liveqmock/platform-tools-idea
1c4b76108add6110898a7e3f8f70b970e352d3d4
[ "Apache-2.0" ]
2
2015-05-08T15:07:10.000Z
2022-03-09T05:47:53.000Z
plugins/InspectionGadgets/testsrc/com/siyeh/ig/bugs/IgnoreResultOfCallInspectionTest.java
lshain-android-source/tools-idea
b37108d841684bcc2af45a2539b75dd62c4e283c
[ "Apache-2.0" ]
null
null
null
plugins/InspectionGadgets/testsrc/com/siyeh/ig/bugs/IgnoreResultOfCallInspectionTest.java
lshain-android-source/tools-idea
b37108d841684bcc2af45a2539b75dd62c4e283c
[ "Apache-2.0" ]
2
2017-04-24T15:48:40.000Z
2022-03-09T05:48:05.000Z
32.863636
104
0.589212
995,310
package com.siyeh.ig.bugs; import com.intellij.codeInspection.LocalInspectionTool; import com.siyeh.ig.LightInspectionTestCase; public class IgnoreResultOfCallInspectionTest extends LightInspectionTestCase { @Override protected LocalInspectionTool getInspection() { return new IgnoreResultOfCallInspection(); } @Override protected String[] getEnvironmentClasses() { return new String[]{ "package java.util.regex; public class Pattern {" + " public static Pattern compile(String regex) {return null;}" + " public Matcher matcher(CharSequence input) {return null;}" + "}", "package java.util.regex; public class Matcher {" + " public boolean find() {return true;}" + "}", }; } public void testObjectMethods() { doTest("class C {\n" + " void foo(Object o, String s) {\n" + " o./*Result of 'Object.equals()' is ignored*/equals/**/(s);\n" + " }\n" + "}\n"); } public void testMatcher() { doTest("class C {\n" + " void matcher() {\n" + " final java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(\"baaaa\");\n" + " final java.util.regex.Matcher matcher = pattern.matcher(\"babaaaaaaaa\");\n" + " matcher./*Result of 'Matcher.find()' is ignored*/find/**/();\n" + " matcher.notify();\n" + " }\n" + "}\n"); } }
922fede9eb05a27caf48dca6f7eea44567115d5e
37,746
java
Java
src/game/views/jpanels/GamePlayScreen.java
saitejaprasadam/DungeonsAndDragons
2dd65d01f5bdd4cb59c817791f439fa3e02065cb
[ "Apache-2.0" ]
null
null
null
src/game/views/jpanels/GamePlayScreen.java
saitejaprasadam/DungeonsAndDragons
2dd65d01f5bdd4cb59c817791f439fa3e02065cb
[ "Apache-2.0" ]
null
null
null
src/game/views/jpanels/GamePlayScreen.java
saitejaprasadam/DungeonsAndDragons
2dd65d01f5bdd4cb59c817791f439fa3e02065cb
[ "Apache-2.0" ]
null
null
null
42.221477
164
0.571451
995,311
package game.views.jpanels; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Observable; import java.util.Observer; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; import javax.swing.SwingConstants; import javax.swing.border.EmptyBorder; import javax.swing.border.EtchedBorder; import javax.swing.text.DefaultCaret; import game.GameLauncher; import game.components.Console; import game.components.Dice; import game.components.GameMechanics; import game.components.SharedVariables; import game.model.Campaign; import game.model.Map; import game.model.character.Backpack; import game.model.character.Character; import game.model.character.CharactersList; import game.model.character.strategyPattern.strategies.AggresiveNPC; import game.model.character.strategyPattern.strategies.ComputerPlayer; import game.model.character.strategyPattern.strategies.FriendlyNPC; import game.model.character.strategyPattern.strategies.HumanPlayer; import game.model.jaxb.CampaignJaxb; import game.model.jaxb.GamePlayJaxb; import game.model.onclickListeners.MapClickListener; import game.views.jdialogs.DialogHelper; import game.views.jdialogs.InventoryViewDialog; /** * This JPanel is the game play screen * * @author saiteja prasadam * @version 1.0.0 * @since 3/8/2017 */ @SuppressWarnings("serial") public class GamePlayScreen extends JPanel implements Observer{ public Character character; public Campaign campaign; public Map currentMap; public PlayerMomentMechanics playerMomentMechanics; private Thread gameplayThread; public static boolean isTesting; public static JTextArea console; public static JScrollPane consoleScrollPane; public JPanel mapJPanelArray[][]; public int currentMapNumber = 0; private JPanel characterDetailsPanel; private InventoryViewDialog inventoryViewDialog; private ArrayList<Character> charactersTurnBasedMechnaism; public volatile boolean isTurnFinished = false; /** * This is constructor method for this class * * @param camapaignName This is the campaign to be loaded * @param characterName This is the character to be loaded * @param isHuman This boolean states the player is human controlled or not */ public GamePlayScreen(String camapaignName, String characterName, boolean isHuman){ this.campaign = CampaignJaxb.getCampaignFromXml(camapaignName); this.character = CharactersList.getByName(characterName).clone(); this.character.setPlayerFlag(true); if(isHuman == true) this.character.setMomentStrategy(new HumanPlayer(this)); else this.character.setMomentStrategy(new ComputerPlayer(this)); this.playerMomentMechanics = new PlayerMomentMechanics(); if(campaign == null || character == null) DialogHelper.showBasicDialog("Error reading saved files"); else{ this.campaign.fetchMaps(); this.character.backpack = new Backpack(); this.currentMap = campaign.getMapList().get(currentMapNumber); this.currentMap.initalizeMapData(this.character.getName()); this.setMapLevel(); this.initComponents(); this.initalizeTurnBasedMechanism(); } } /** * This is constructor method for this class * * @param camapaignName This is the campaign to be loaded * @param characterName This is the character to be loaded * @param isHuman This boolean states the player is human controlled or not * @param isTesting in test case */ public GamePlayScreen(String camapaignName, String characterName, boolean isHuman, boolean isTesting){ this.campaign = CampaignJaxb.getCampaignFromXml(camapaignName); this.character = CharactersList.getByName(characterName).clone(); this.character.setPlayerFlag(true); GamePlayScreen.isTesting = isTesting; if(isHuman == true) this.character.setMomentStrategy(new HumanPlayer(this)); else this.character.setMomentStrategy(new ComputerPlayer(this)); this.playerMomentMechanics = new PlayerMomentMechanics(); if(campaign == null || character == null) DialogHelper.showBasicDialog("Error reading saved files"); else{ this.campaign.fetchMaps(); this.character.backpack = new Backpack(); this.currentMap = campaign.getMapList().get(currentMapNumber); this.currentMap.initalizeMapData(this.character.getName()); this.setMapLevel(); this.initComponents(); playerMomentMechanics.setKeyListeners(this); } } /** * This method set the level of the enemy and item using by players and enemies, matching to the player */ public void setMapLevel(){ Console.printInConsole("Player(" + character.getName() + ") entered map : " + currentMap.getMapName() + "\n"); for (int i = 0; i < currentMap.mapWidth; i++) for (int j = 0; j < currentMap.mapHeight; j++) if(currentMap.mapData[i][j] instanceof Character && (!((Character) currentMap.mapData[i][j]).isPlayer())){ Character tempCharacter = ((Character) currentMap.mapData[i][j]); tempCharacter.setLevel(character.getLevel()); if(tempCharacter.getIsFriendlyMonster()) tempCharacter.setMomentStrategy(new FriendlyNPC(GamePlayScreen.this, tempCharacter)); else tempCharacter.setMomentStrategy(new AggresiveNPC(GamePlayScreen.this, tempCharacter)); } } /** * This method initializes turn based mechanism */ public void initalizeTurnBasedMechanism(){ Console.printInConsole("Calculating turn based mechanism"); charactersTurnBasedMechnaism = new ArrayList<>(); for (int i = 0; i < currentMap.mapWidth; i++) for (int j = 0; j < currentMap.mapHeight; j++) if(currentMap.mapData[i][j] instanceof Character) charactersTurnBasedMechnaism.add((Character) currentMap.mapData[i][j]); for (Character character : charactersTurnBasedMechnaism) character.turnPoints = new Dice(1, 20, 1).getRollSum() + character.getDexterityModifier(); Collections.sort(charactersTurnBasedMechnaism, new Comparator<Character>(){ public int compare(Character s1, Character s2) { return s2.turnPoints - s1.turnPoints; } }); for (Character character : charactersTurnBasedMechnaism) Console.printInConsole(" *" + character.getName() + " -> " + character.turnPoints); Console.printInConsole(""); Console.printInConsole("Starting gameplay"); startGamePlay(); } /** * This method starts the game play */ private void startGamePlay() { gameplayThread = new Thread(new Runnable() { @Override public void run() { while(character.getHitScore() >= 1) for (Character character : charactersTurnBasedMechnaism) { if(character.getHitScore() < 1) continue; Console.printInConsole(""); if(character.isPlayer()){ Console.printInConsole(" *" + GamePlayScreen.this.character.getName() + "'s turn (" + GamePlayScreen.this.character.getHitScore() + "HP)"); GamePlayScreen.this.character.getMomentStrategy().playTurn(); if(GamePlayScreen.this.character.burningTurn > 0){ GamePlayScreen.this.character.hit(GamePlayScreen.this.character.bruningDamagePoints); Console.printInConsole(" => you are burning - " + GamePlayScreen.this.character.bruningDamagePoints + "hp"); GamePlayScreen.this.character.burningTurn--; } } else{ Console.printInConsole(" *" + character.getName() + "'s turn (" + character.getHitScore() + "HP)"); character.getMomentStrategy().playTurn(); if(character.burningTurn > 0){ character.hit(character.bruningDamagePoints); Console.printInConsole(" => " + character.getName() + " is burning - " + character.bruningDamagePoints + "hp"); character.burningTurn--; } } while (true) { if (isTurnFinished){ playerMomentMechanics.removeKeyListeners(GamePlayScreen.this); isTurnFinished = false; break; } } } if(character.getHitScore() < 1){ Console.printInConsole("\nYou are dead, you will be now redirected to launch screen"); DialogHelper.showBasicDialog("You are dead, you will be now redirected to launch screen"); GameLauncher.mainFrameObject.replaceJPanel(new LaunchScreen()); } } }); gameplayThread.setDaemon(true); gameplayThread.start(); } /** * This method initializes UI components */ public void initComponents(){ this.removeAll(); GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.columnWidths = new int[] { 0, 0, 0, 0, 0 }; gridBagLayout.rowHeights = new int[] { 0, 0, 0, 0, 0 }; gridBagLayout.columnWeights = new double[] { 1.0, 1.0, 1.0, 1.0, 0.5 }; gridBagLayout.rowWeights = new double[] { 1.0, 1.0, 1.0, 1.0, 1.0 }; setLayout(gridBagLayout); initMapPanel(); initControlPanel(); } /** * This method initializes map panel */ private void initMapPanel() { JPanel mapPanel = new JPanel(); mapPanel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, Color.GRAY, null)); mapPanel.setBackground(Color.WHITE); GridBagConstraints gbc_mapPanel = new GridBagConstraints(); gbc_mapPanel.gridwidth = 4; gbc_mapPanel.gridheight = 5; gbc_mapPanel.insets = new Insets(0, 0, 0, 5); gbc_mapPanel.fill = GridBagConstraints.BOTH; gbc_mapPanel.gridx = 0; gbc_mapPanel.gridy = 0; add(mapPanel, gbc_mapPanel); mapPanel.setLayout(new GridLayout(currentMap.mapWidth, currentMap.mapHeight)); mapJPanelArray = new JPanel[currentMap.mapWidth][currentMap.mapHeight]; for (int i = 0; i < currentMap.mapWidth; i++) for (int j = 0; j < currentMap.mapHeight; j++) { mapJPanelArray[i][j] = new JPanel(); mapJPanelArray[i][j] = GameMechanics.setMapCellDetailsFromMapObjectData(mapJPanelArray[i][j], currentMap.mapData[i][j]); mapJPanelArray[i][j].addMouseListener(new MapClickListener(this, currentMap.mapData[i][j])); mapJPanelArray[i][j].setBorder(BorderFactory.createLineBorder(Color.BLACK)); mapPanel.add(mapJPanelArray[i][j]); } } /** * Initializes Control panel */ private void initControlPanel() { JPanel designPanel = new JPanel(); { //Initialize Design panel designPanel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, Color.GRAY, null)); designPanel.setBackground(Color.WHITE); GridBagConstraints gbc_designPanel_1 = new GridBagConstraints(); gbc_designPanel_1.gridheight = 5; gbc_designPanel_1.fill = GridBagConstraints.BOTH; gbc_designPanel_1.gridx = 4; gbc_designPanel_1.gridy = 0; add(designPanel, gbc_designPanel_1); GridBagLayout gbl_designPanel_1 = new GridBagLayout(); gbl_designPanel_1.columnWidths = new int[] { 0 }; gbl_designPanel_1.rowHeights = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; gbl_designPanel_1.columnWeights = new double[] { 1.0 }; gbl_designPanel_1.rowWeights = new double[] { 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0 }; designPanel.setLayout(gbl_designPanel_1); } { //Initialize Game Details panel JPanel campaignDetailsPanel = new JPanel(); campaignDetailsPanel.setBackground(Color.WHITE); campaignDetailsPanel.setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(10, 10, 10, 10), new EtchedBorder())); GridBagConstraints gbc_mapNamePanel = new GridBagConstraints(); gbc_mapNamePanel.fill = GridBagConstraints.HORIZONTAL; gbc_mapNamePanel.anchor = GridBagConstraints.NORTH; gbc_mapNamePanel.insets = new Insets(0, 0, 5, 0); gbc_mapNamePanel.gridx = 0; gbc_mapNamePanel.gridy = 0; designPanel.add(campaignDetailsPanel, gbc_mapNamePanel); campaignDetailsPanel.setLayout(new GridLayout(0, 1, 0, 0)); for(int index = 0; index < 4; index++){ String key = "", value = ""; if(index == 0){ key = "Campaign Name : "; value = campaign.getCampaignName() + " (" + campaign.getMapNames().size() + " maps)"; } else if(index == 1){ key = "Character Name : "; value = character.getName(); } else if(index == 2){ key = "Current Map Name : "; value = currentMap.getMapName() + " (" + (currentMapNumber + 1) + " map out of " + campaign.getMapNames().size() + " maps)"; } else{ key = "Level : "; value = String.valueOf(character.getLevel()); } JPanel campaignNameJpanel = new JPanel(); campaignNameJpanel.setBackground(Color.WHITE); campaignNameJpanel.setBackground(Color.WHITE); campaignNameJpanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5)); JLabel campaginLabel = new JLabel(key); campaginLabel.setHorizontalAlignment(SwingConstants.CENTER); campaginLabel.setFont(new Font("Tahoma", Font.BOLD, 10)); campaignNameJpanel.add(campaginLabel); JLabel campaignNameValueLabel = new JLabel(value); campaignNameValueLabel.setHorizontalAlignment(SwingConstants.CENTER); campaignNameValueLabel.setFont(new Font("Tahoma", Font.PLAIN, 9)); campaignNameJpanel.add(campaignNameValueLabel); campaignDetailsPanel.add(campaignNameJpanel); } } { //Initialize Components panel JPanel componentsPanel = new JPanel(); componentsPanel.setBackground(Color.WHITE); componentsPanel.setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(10, 10, 10, 10), new EtchedBorder())); GridBagConstraints gbc_componentsPanel = new GridBagConstraints(); gbc_componentsPanel.gridheight = 2; gbc_componentsPanel.insets = new Insets(0, 0, 5, 0); gbc_componentsPanel.fill = GridBagConstraints.BOTH; gbc_componentsPanel.gridx = 0; gbc_componentsPanel.gridy = 1; designPanel.add(componentsPanel, gbc_componentsPanel); componentsPanel.setLayout(new GridLayout(0, 2)); // Wall JPanel wallJpanel = new JPanel(); wallJpanel.setBackground(SharedVariables.mapCellHashMap.get(SharedVariables.WALL_STRING)); JLabel wallLabel = new JLabel("Wall"); wallLabel.setFont(new Font("Tahoma", Font.BOLD, 12)); wallLabel.setHorizontalAlignment(SwingConstants.CENTER); componentsPanel.add(wallJpanel); componentsPanel.add(wallLabel); //Player JPanel playerJpanel = new JPanel(); playerJpanel.setBackground(Color.BLUE); JLabel playerLabel = new JLabel("Player"); playerLabel.setHorizontalAlignment(SwingConstants.CENTER); playerLabel.setFont(new Font("Tahoma", Font.BOLD, 12)); componentsPanel.add(playerJpanel); componentsPanel.add(playerLabel); // Monster JPanel monsterJpanel = new JPanel(); monsterJpanel.setBackground(SharedVariables.mapCellHashMap.get(SharedVariables.MONSTER_STRING)); JLabel monsterLabel = new JLabel("Monster"); monsterLabel.setFont(new Font("Tahoma", Font.BOLD, 12)); monsterLabel.setHorizontalAlignment(SwingConstants.CENTER); componentsPanel.add(monsterJpanel); componentsPanel.add(monsterLabel); // Entry door JPanel entryDoorJpanel = new JPanel(); entryDoorJpanel.setBackground(SharedVariables.mapCellHashMap.get(SharedVariables.ENTRY_DOOR_STRING)); JLabel entryDoorLabel = new JLabel("Entry door"); entryDoorLabel.setFont(new Font("Tahoma", Font.BOLD, 12)); entryDoorLabel.setHorizontalAlignment(SwingConstants.CENTER); componentsPanel.add(entryDoorJpanel); componentsPanel.add(entryDoorLabel); // Exit door JPanel exitDoorJpanel = new JPanel(); exitDoorJpanel.setBackground(SharedVariables.mapCellHashMap.get(SharedVariables.EXIT_DOOR_STRING)); JLabel exitDoorLabel = new JLabel("Exit door"); exitDoorLabel.setFont(new Font("Tahoma", Font.BOLD, 12)); exitDoorLabel.setHorizontalAlignment(SwingConstants.CENTER); componentsPanel.add(exitDoorJpanel); componentsPanel.add(exitDoorLabel); // Chest JPanel chestJpanel = new JPanel(); chestJpanel.setBackground(SharedVariables.mapCellHashMap.get(SharedVariables.CHEST_STRING)); JLabel chestLabel = new JLabel("Chest"); chestLabel.setFont(new Font("Tahoma", Font.BOLD, 12)); chestLabel.setHorizontalAlignment(SwingConstants.CENTER); componentsPanel.add(chestJpanel); componentsPanel.add(chestLabel); // Key JPanel keyJpanel = new JPanel(); keyJpanel.setBackground(SharedVariables.mapCellHashMap.get(SharedVariables.KEY_STRING)); JLabel keyLabel = new JLabel("Key"); keyLabel.setFont(new Font("Tahoma", Font.BOLD, 12)); keyLabel.setHorizontalAlignment(SwingConstants.CENTER); componentsPanel.add(keyJpanel); componentsPanel.add(keyLabel); } characterDetailsPanel = new JPanel(); characterDetailsPanel.setBackground(Color.WHITE); characterDetailsPanel.setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(10, 10, 10, 10), new EtchedBorder())); GridBagConstraints gbc_characterDetailsPanel = new GridBagConstraints(); gbc_characterDetailsPanel.insets = new Insets(0, 0, 5, 0); gbc_characterDetailsPanel.fill = GridBagConstraints.HORIZONTAL; gbc_characterDetailsPanel.anchor = GridBagConstraints.NORTH; gbc_characterDetailsPanel.gridx = 0; gbc_characterDetailsPanel.gridy = 3; designPanel.add(characterDetailsPanel, gbc_characterDetailsPanel); characterDetailsPanel.setLayout(new GridLayout(0, 1, 0, 0)); JPanel consoleJpanel = new JPanel(); GridBagConstraints gbc_consoleJpanel = new GridBagConstraints(); gbc_consoleJpanel.fill = GridBagConstraints.BOTH; gbc_consoleJpanel.gridx = 0; gbc_consoleJpanel.gridy = 4; designPanel.add(consoleJpanel, gbc_consoleJpanel); consoleJpanel.setLayout(new GridLayout(1, 0, 0, 0)); console = new JTextArea(); console.setFont(console.getFont().deriveFont(12f)); console.setSize(150, 1000); console.setEditable(false); console.setWrapStyleWord(true); DefaultCaret caret = (DefaultCaret) console.getCaret(); caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); consoleJpanel.setBackground(Color.WHITE); consoleJpanel.setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(10, 10, 10, 10), new EtchedBorder())); consoleScrollPane = new JScrollPane(console); consoleScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); consoleJpanel.add(consoleScrollPane); JPanel abort_saveButtonsJpanel = new JPanel(); GridBagConstraints gbc_panel = new GridBagConstraints(); gbc_panel.fill = GridBagConstraints.BOTH; gbc_panel.gridx = 0; gbc_panel.gridy = 11; designPanel.add(abort_saveButtonsJpanel, gbc_panel); abort_saveButtonsJpanel.setLayout(new GridLayout(1, 0, 0, 0)); JButton btnAbortButton = new JButton("Abort game"); btnAbortButton.setFont(new Font("Tahoma", Font.BOLD, 14)); btnAbortButton.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15)); btnAbortButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(gameplayThread != null) gameplayThread.interrupt(); GameLauncher.mainFrameObject.replaceJPanel(new LaunchScreen()); } }); abort_saveButtonsJpanel.add(btnAbortButton); JButton btnSaveButton = new JButton("Save and exit"); btnSaveButton.setFont(new Font("Tahoma", Font.BOLD, 14)); btnSaveButton.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15)); btnSaveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String fileNmae = JOptionPane.showInputDialog("Enter name of the file to be saved"); gameplayThread.interrupt(); gameplayThread = null; console = null; consoleScrollPane = null; consoleJpanel.removeAll(); designPanel.removeAll(); if(GamePlayJaxb.convertGameObjectToXml(fileNmae, GamePlayScreen.this)){ DialogHelper.showBasicDialog("Game saved successfully"); GameLauncher.mainFrameObject.replaceJPanel(new LaunchScreen()); } else DialogHelper.showBasicDialog("There was a issue saving the game"); } }); abort_saveButtonsJpanel.add(btnSaveButton); showPlayerDetails(character); } /** * This method displays the character details on the screen * * @param character Character object that needs to be displayed on the screen */ public void showPlayerDetails(Character character) { this.removePreviousObservables(); character.addObserver(this); characterDetailsPanel.removeAll(); for(int index = 0; index < 12; index++){ String key = "", value = ""; if(index == 0){ key = "Character Name : "; value = character.getName(); if(character.getWeaponObject() != null && character.getWeaponObject().itemClass.equalsIgnoreCase("Melee")) value += " (Melee weapon)"; else if(character.getWeaponObject() != null) value += " (Ranged weapon)"; } else if(index == 1){ key = "Type of character : "; if(character.isPlayer()) value = "Player"; else if(character.getIsFriendlyMonster() == true) value = "Monster (Friendly)"; else value = "Monster (Hostile)"; } else if(index == 2){ key = "Level : "; value = String.valueOf(character.getLevel()); } else if(index == 3){ key = "Hit points : "; value = String.valueOf(character.getHitScore() + "HP"); } else if(index == 4){ key = "Attack Bonus : "; value = String.valueOf(character.getAttackBonus()); } else if(index == 5){ key = "Damage bonus : "; value = String.valueOf(character.getDamageBonus()); } else if(index == 6){ key = "Strength modifier : "; value = String.valueOf(character.getStrengthModifier()); } else if(index == 7){ key = "Dexterity modifier : "; value = String.valueOf(character.getDexterityModifier()); } else if(index == 8){ key = "Constitution : "; value = String.valueOf(character.getConstitution()); } else if(index == 9){ key = "Constitution modifier : "; value = String.valueOf(character.getConstitutionModifier()); } else if(index == 10){ key = "Armor Class : "; value = String.valueOf(character.getArmorClass()); } else if(character.isPlayer()){ key = "Key collected : "; if(character.isKeyCollected()) value = "Yes"; else value = "No"; } JPanel campaignNameJpanel = new JPanel(); campaignNameJpanel.setBackground(Color.WHITE); campaignNameJpanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5)); JLabel campaginLabel = new JLabel(key); campaginLabel.setHorizontalAlignment(SwingConstants.CENTER); campaginLabel.setFont(new Font("Tahoma", Font.BOLD, 10)); campaignNameJpanel.add(campaginLabel); JLabel campaignNameValueLabel = new JLabel(value); campaignNameValueLabel.setHorizontalAlignment(SwingConstants.CENTER); campaignNameValueLabel.setFont(new Font("Tahoma", Font.PLAIN, 9)); campaignNameJpanel.add(campaignNameValueLabel); characterDetailsPanel.add(campaignNameJpanel); } JButton openInventory = new JButton("Open Inventory"); openInventory.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { inventoryViewDialog = new InventoryViewDialog(character); } }); characterDetailsPanel.add(openInventory); characterDetailsPanel.revalidate(); if(inventoryViewDialog != null) inventoryViewDialog.update(character, null); } /** * This method repaints the map after the action is completed */ public void repaintMap() { for (int i = 0; i < currentMap.mapWidth; i++) for (int j = 0; j < currentMap.mapHeight; j++) { for(MouseListener listener : mapJPanelArray[i][j].getMouseListeners()) mapJPanelArray[i][j].removeMouseListener(listener); mapJPanelArray[i][j].addMouseListener(new MapClickListener(this, currentMap.mapData[i][j])); mapJPanelArray[i][j] = GameMechanics.setMapCellDetailsFromMapObjectData(mapJPanelArray[i][j], currentMap.mapData[i][j]); } } /** * This class contains all the player moment mechanics classes and methods * * @author saiteja prasadm * @since 3/11/2017 * @version 1.0.0 */ public class PlayerMomentMechanics{ int playerMomentCount = 0; /** * This class actionPerformed is triggered when up or w is pressed by the user. * @author saiteja prasadam * @version 1.0.0 * @since 3/9/2017 * */ public class UP_PRESSED extends AbstractAction { /** * This method performs the action when key is pressed * @param e ActionEvent */ @Override public void actionPerformed(ActionEvent e) { int[] position = GameMechanics.getPlayerPosition(currentMap); int rowNumber = position[0]; int colNumber = position[1]; if(rowNumber != 0){ String message = " => " + character.getName() + " moving up"; character.getMomentStrategy().movePlayer(message, rowNumber, colNumber, rowNumber - 1, colNumber); } } } /** * This class actionPerformed is triggered when down or s is pressed by the user. * @author saiteja prasadam * @version 1.0.0 * @since 3/9/2017 * */ public class DOWN_PRESSED extends AbstractAction { /** * This method performs the action when key is pressed * @param e ActionEvent */ @Override public void actionPerformed(ActionEvent e) { int[] position = GameMechanics.getPlayerPosition(currentMap); int rowNumber = position[0]; int colNumber = position[1]; if(rowNumber < currentMap.mapHeight - 1){ String message = " => " + character.getName() + " moving down"; character.getMomentStrategy().movePlayer(message, rowNumber, colNumber, rowNumber + 1, colNumber); } } } /** * This class actionPerformed is triggered when left or a is pressed by the user. * @author saiteja prasadam * @version 1.0.0 * @since 3/9/2017 * */ public class LEFT_PRESSED extends AbstractAction { /** * This method performs the action when key is pressed * @param e ActionEvent */ @Override public void actionPerformed(ActionEvent e) { int[] position = GameMechanics.getPlayerPosition(currentMap); int rowNumber = position[0]; int colNumber = position[1]; if(colNumber != 0){ String message = " => " + character.getName() + " moving left"; character.getMomentStrategy().movePlayer(message, rowNumber, colNumber, rowNumber, colNumber - 1); } } } /** * This class actionPerformed is triggered when right or d is pressed by the user. * @author saiteja prasadam * @version 1.0.0 * @since 3/9/2017 * */ public class RIGHT_PRESSED extends AbstractAction { /** * This method performs the action when key is pressed * @param e ActionEvent */ @Override public void actionPerformed(ActionEvent e) { int[] position = GameMechanics.getPlayerPosition(currentMap); int rowNumber = position[0]; int colNumber = position[1]; if(colNumber < currentMap.mapWidth - 1){ String message = " => " + character.getName() + " moving right"; character.getMomentStrategy().movePlayer(message, rowNumber, colNumber, rowNumber, colNumber + 1); } } } /** * This method set's up key binding for player moments * @param jpanel parent jpanel */ public void setKeyListeners(JPanel jpanel){ jpanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("UP"), "UP_PRESSED"); jpanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("W"), "UP_PRESSED"); jpanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("DOWN"), "DOWN_PRESSED"); jpanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("S"), "DOWN_PRESSED"); jpanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("LEFT"), "LEFT_PRESSED"); jpanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("A"), "LEFT_PRESSED"); jpanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("RIGHT"), "RIGHT_PRESSED"); jpanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("D"), "RIGHT_PRESSED"); jpanel.getActionMap().put("UP_PRESSED", playerMomentMechanics.new UP_PRESSED()); jpanel.getActionMap().put("DOWN_PRESSED", playerMomentMechanics.new DOWN_PRESSED()); jpanel.getActionMap().put("LEFT_PRESSED", playerMomentMechanics.new LEFT_PRESSED()); jpanel.getActionMap().put("RIGHT_PRESSED", playerMomentMechanics.new RIGHT_PRESSED()); } /** * This method removes key binding to the parent jpanel * @param jpanel parent jpanel */ public void removeKeyListeners(JPanel jpanel){ jpanel.getActionMap().put("UP_PRESSED", null); jpanel.getActionMap().put("DOWN_PRESSED", null); jpanel.getActionMap().put("LEFT_PRESSED", null); jpanel.getActionMap().put("RIGHT_PRESSED", null); } } /** * This method is called when the selected character object gets updated * * @param arg0 Observable * @param arg1 Object */ @Override public void update(Observable arg0, Object arg1) { if(((Character) arg0).isPlayer()) this.showPlayerDetails(character); //else this.showPlayerDetails((Character) arg0); } /** * This method removes all the previous observable attached to the character object */ public void removePreviousObservables() { ArrayList<Character> characters = GameMechanics.getAllCharacterObjects(currentMap); for(Character characterObject : characters) characterObject.deleteObservers(); } /** * This method initializes the loaded game */ public void initLoadGame(){ this.initComponents(); this.startGamePlay(); } }
922fee8ae8a061d8aada457c7c6bc6b1fc1aa42c
1,223
java
Java
plugin/src/main/java/com/github/muehmar/gradle/openapi/util/Optionals.java
muehmar/gradle-openapi-schema
f5ac66e105042abb14bd19b3796c513dbba07887
[ "MIT" ]
2
2021-03-02T13:37:08.000Z
2021-11-22T09:26:14.000Z
plugin/src/main/java/com/github/muehmar/gradle/openapi/util/Optionals.java
muehmar/gradle-openapi-schema
f5ac66e105042abb14bd19b3796c513dbba07887
[ "MIT" ]
1
2022-01-07T10:34:02.000Z
2022-01-07T10:34:02.000Z
plugin/src/main/java/com/github/muehmar/gradle/openapi/util/Optionals.java
muehmar/gradle-openapi-schema
f5ac66e105042abb14bd19b3796c513dbba07887
[ "MIT" ]
1
2021-06-18T12:09:27.000Z
2021-06-18T12:09:27.000Z
28.44186
85
0.64677
995,312
package com.github.muehmar.gradle.openapi.util; import ch.bluecare.commons.data.PList; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; public class Optionals { private Optionals() {} @SafeVarargs public static <T> Optional<T> or(Optional<T>... optionals) { return or(PList.fromArray(optionals).map(optional -> () -> optional)); } @SafeVarargs public static <T> Optional<T> or(Supplier<Optional<T>>... suppliers) { return or(PList.fromArray(suppliers)); } public static <T> Optional<T> or(PList<Supplier<Optional<T>>> suppliers) { for (Supplier<Optional<T>> supplier : suppliers) { final Optional<T> optional = supplier.get(); if (optional.isPresent()) { return optional; } } return Optional.empty(); } public static <A, B, T> Optional<T> combine( Optional<A> a, Optional<B> b, Function<A, T> mapA, Function<B, T> mapB, BiFunction<A, B, T> combine) { return a.flatMap(a1 -> b.map(b1 -> combine.apply(a1, b1))) .map(Optional::of) .orElseGet(() -> a.map(mapA).map(Optional::of).orElseGet(() -> b.map(mapB))); } }
922feefcb1e7842137fa6ed160c86e9ffed927fe
348
java
Java
spring-docker/src/main/java/com/javaee/dockerizespringboot/DockerizeSpringBootApplication.java
1ucas/arq-java-tutoriais
d8aed1d2d33a07b7213a71b5a5f340d7bf892632
[ "MIT" ]
2
2019-02-08T12:17:48.000Z
2019-03-18T12:45:56.000Z
spring-docker/src/main/java/com/javaee/dockerizespringboot/DockerizeSpringBootApplication.java
1ucas/arq-java-tutoriais
d8aed1d2d33a07b7213a71b5a5f340d7bf892632
[ "MIT" ]
null
null
null
spring-docker/src/main/java/com/javaee/dockerizespringboot/DockerizeSpringBootApplication.java
1ucas/arq-java-tutoriais
d8aed1d2d33a07b7213a71b5a5f340d7bf892632
[ "MIT" ]
null
null
null
26.769231
68
0.841954
995,313
package com.javaee.dockerizespringboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DockerizeSpringBootApplication { public static void main(String[] args) { SpringApplication.run(DockerizeSpringBootApplication.class, args); } }
922fef55693684759b7097aecfcc5efa4e8db249
4,016
java
Java
app/src/main/java/com/a2big/booking/object/ReservationRowImte.java
jihun-kang/a2big_calendar
0ee1831d527fc442278f28cef738f441462325d4
[ "Apache-2.0" ]
1
2018-08-11T09:50:40.000Z
2018-08-11T09:50:40.000Z
app/src/main/java/com/a2big/booking/object/ReservationRowImte.java
jihun-kang/a2big_calendar
0ee1831d527fc442278f28cef738f441462325d4
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/a2big/booking/object/ReservationRowImte.java
jihun-kang/a2big_calendar
0ee1831d527fc442278f28cef738f441462325d4
[ "Apache-2.0" ]
null
null
null
29.529412
121
0.653635
995,314
package com.a2big.booking.object; /** * Created by a2big on 15. 6. 8.. */ import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.a2big.testcalendar.R; import com.a2big.booking.listener.OnRoomSelectionListener; /* import com.a2big.android.library.init.A2BigApp; import com.a2big.android.library.utils.DNetworkImageView; import com.a2big.android.library.utils.DevLog; import com.a2big.dragonhouse.calendar.OnRoomSelectionListener; import com.a2big.dragonhouse.calendar.RoomListItem; import com.android.volley.toolbox.ImageLoader; */ public class ReservationRowImte extends LinearLayout { Context mContext = null; // DNetworkImageView mImageView; TextView mText1,mText2; Button button; // ImageLoader imageLoader; private OnRoomSelectionListener selectionListener; private static final String androidns = "http://schemas.android.com/apk/res/android"; /** Called when the activity is first created. */ public ReservationRowImte(Context context, AttributeSet attrs) { super(context, attrs); String titlename1 = attrs.getAttributeValue(androidns, "text1"); String titlename2 = attrs.getAttributeValue(androidns, "text2"); // DevLog.defaultLogging("ReservationRowImte...." + titlename1 + " " + titlename2); RoomListItem root = new RoomListItem(0,"4인실 도미토리","남자", "http://www.dragon-house.co.kr/image/domitory.png",true); initcustomview(context,root); } public void setOnRoomSelectionListener(OnRoomSelectionListener listener){ this.selectionListener= listener; } public ReservationRowImte(Context context, RoomListItem t) { super(context); // imageLoader = A2BigApp.getApplication().getImageLoader(); initcustomview(context, t); } public void init(Integer id, String name, String sex, String url, boolean t){ button.setTag(id); mText1.setText(name); mText2.setText(sex); // mImageView.setImageUrl(url, imageLoader); if( t == true) { button.setText("예약가능"); } else{ button.setText("매진"); } } public void setRoomId(Integer n){ button.setTag(n); } public void setRoomName(String n){ mText1.setText(n); } public void setSex(String n){ mText2.setText(n); } // public void setRoomImage(String url){ // mImageView.setImageUrl(url, imageLoader); // } public void setButtonName(Boolean t){ if( t == true) { button.setText("예약가능"); } else{ button.setText("매진"); } } void initcustomview(Context context,RoomListItem t) { mContext = context; //if(imageLoader == null){ // imageLoader = A2BigApp.getApplication().getImageLoader(); // } String infService = Context.LAYOUT_INFLATER_SERVICE; LayoutInflater li = (LayoutInflater) getContext().getSystemService(infService); View v = li.inflate(R.layout.room_list_item, this, false); addView(v); // mImageView = (DNetworkImageView) findViewById(R.id.networkImageView); // mImageView.setImageUrl(t.getImageURL(), imageLoader); mText1 = (TextView)findViewById(R.id.text1); mText1.setText(t.getRoomType()); mText2 = (TextView)findViewById(R.id.text2); mText2.setText(t.getSex()); button = (Button)findViewById(R.id.btnMakeBook); button.setTag(t.getRoomID()); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { // DevLog.defaultLogging("Click button...."); if(selectionListener != null){ selectionListener.onDataSelected((int)button.getTag()); } } }); } }
922ff067668dfde4126c818e2b7f6eda5271b46f
2,040
java
Java
11/OneLevelCacheTest/src/org/fkit/test/TestOneLevelCache.java
yefengchun/springmvc-mybatis-v2
bd76dedac1b3129957e7fe09e6243a5fa149c24b
[ "Apache-2.0" ]
null
null
null
11/OneLevelCacheTest/src/org/fkit/test/TestOneLevelCache.java
yefengchun/springmvc-mybatis-v2
bd76dedac1b3129957e7fe09e6243a5fa149c24b
[ "Apache-2.0" ]
null
null
null
11/OneLevelCacheTest/src/org/fkit/test/TestOneLevelCache.java
yefengchun/springmvc-mybatis-v2
bd76dedac1b3129957e7fe09e6243a5fa149c24b
[ "Apache-2.0" ]
null
null
null
26.153846
59
0.736275
995,315
package org.fkit.test; import org.apache.ibatis.session.SqlSession; import org.fkit.domain.User; import org.fkit.factory.FKSqlSessionFactory; import org.fkit.mapper.UserMapper; public class TestOneLevelCache { public static void main(String[] args) throws Exception { TestOneLevelCache t = new TestOneLevelCache(); t.testCache1(); // t.testCache2(); // t.testCache3(); } /* * 一级缓存: 也就Session级的缓存(默认开启) */ public void testCache1 (){ // 使用工厂类获得SqlSession对象 SqlSession session = FKSqlSessionFactory.getSqlSession(); // 获得UserMapping对象 UserMapper um = session.getMapper(UserMapper.class); // 查询id为1的User对象,会执行select语句 User user = um.selectUserById(1); System.out.println(user); // 再次查询id为1的User对象,因为是同一个SqlSession,所以会从之前的一级缓存中查找数据 User user2 = um.selectUserById(1); System.out.println(user2); // 关闭SqlSession对象 session.close(); } public void testCache2 (){ // 使用工厂类获得SqlSession对象 SqlSession session = FKSqlSessionFactory.getSqlSession(); // 获得UserMapping对象 UserMapper um = session.getMapper(UserMapper.class); // 查询id为1的User对象,会执行select语句 User user = um.selectUserById(1); System.out.println(user); // 执行delete操作 um.deleteUserById(5); // commit提交 session.commit(); // 再次查询id为1的User对象,因为DML操作会清空SqlSession缓存,所以会再次执行select语句 User user2 = um.selectUserById(1); System.out.println(user2); // 关闭SqlSession对象 session.close(); } public void testCache3 (){ // 使用工厂类获得SqlSession对象 SqlSession session = FKSqlSessionFactory.getSqlSession(); // 获得UserMapping对象 UserMapper um = session.getMapper(UserMapper.class); // 查询id为1的User对象,会执行select语句 User user = um.selectUserById(1); System.out.println(user); // 关闭一级缓存 session.close(); // 再次访问,需要再次获取一级缓存,然后才能查找数据,否则会抛出异常 session = FKSqlSessionFactory.getSqlSession(); // 再次获得UserMapping对象 um = session.getMapper(UserMapper.class); // 再次访问,因为现在使用的是一个新的SqlSession对象,所以会再次执行select语句 User user2 = um.selectUserById(1); System.out.println(user2); // 关闭SqlSession对象 session.close(); } }
922ff0ec4b758eb1bef477514378b67dc9c9d1ff
3,341
java
Java
jans-scim/server/src/main/java/io/jans/scim/ws/rs/scim2/ScimConfigurationWS.java
nikdavnik/jans
5e9abc74cca766a066512eab2aca6563ce480bff
[ "Apache-2.0" ]
18
2022-01-13T13:45:13.000Z
2022-03-30T04:41:18.000Z
jans-scim/server/src/main/java/io/jans/scim/ws/rs/scim2/ScimConfigurationWS.java
nikdavnik/jans
5e9abc74cca766a066512eab2aca6563ce480bff
[ "Apache-2.0" ]
604
2022-01-13T12:32:50.000Z
2022-03-31T20:27:36.000Z
jans-scim/server/src/main/java/io/jans/scim/ws/rs/scim2/ScimConfigurationWS.java
nikdavnik/jans
5e9abc74cca766a066512eab2aca6563ce480bff
[ "Apache-2.0" ]
8
2022-01-28T00:23:25.000Z
2022-03-16T05:12:12.000Z
33.747475
123
0.720443
995,316
package io.jans.scim.ws.rs.scim2; import java.util.Collections; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import org.slf4j.Logger; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.annotations.ApiResponse; import com.wordnik.swagger.annotations.ApiResponses; import io.jans.scim.ScimConfiguration; import io.jans.service.JsonService; /** * This class implements the endpoint at which the requester can obtain SCIM metadata configuration. Similar to the SCIM * /ServiceProviderConfig endpoint */ @ApplicationScoped @Path("/scim-configuration") @Api(value = "/.well-known/scim-configuration", description = "The SCIM server endpoint that provides configuration data.") public class ScimConfigurationWS { @Inject private Logger log; @Inject private JsonService jsonService; @Inject private UserWebService userService; @Inject private GroupWebService groupService; @Inject private FidoDeviceWebService fidoService; @Inject private Fido2DeviceWebService fido2Service; @Inject private BulkWebService bulkService; @Inject private ServiceProviderConfigWS serviceProviderService; @Inject private ResourceTypeWS resourceTypeService; @Inject private SchemaWebService schemaService; @GET @Produces(MediaType.APPLICATION_JSON) @ApiOperation( value = "Provides metadata as json document. It contains options and endpoints supported by the SCIM server.", response = ScimConfiguration.class ) @ApiResponses(value = { @ApiResponse(code = 500, message = "Failed to build SCIM configuration json object.") }) public Response getConfiguration() { try { final ScimConfiguration c2 = new ScimConfiguration(); c2.setVersion("2.0"); c2.setAuthorizationSupported(Collections.singletonList("oauth2")); c2.setUserEndpoint(userService.getEndpointUrl()); c2.setGroupEndpoint(groupService.getEndpointUrl()); c2.setFidoDevicesEndpoint(fidoService.getEndpointUrl()); c2.setFido2DevicesEndpoint(fido2Service.getEndpointUrl()); c2.setBulkEndpoint(bulkService.getEndpointUrl()); c2.setServiceProviderEndpoint(serviceProviderService.getEndpointUrl()); c2.setResourceTypesEndpoint(resourceTypeService.getEndpointUrl()); c2.setSchemasEndpoint(schemaService.getEndpointUrl()); // Convert manually to avoid possible conflicts between resteasy providers, e.g. jettison, jackson final String entity = jsonService.objectToPerttyJson(Collections.singletonList(c2)); log.info("SCIM configuration: {}", entity); return Response.ok(entity).build(); } catch (Exception e) { log.error(e.getMessage(), e); throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity("Failed to generate SCIM configuration").build()); } } }
922ff11d9be718931aea715b70448472b800395a
615
java
Java
Prg31_Jukebox/src/main/java/dal/CanzoneDAO.java
ggarone/Java-Projects
8a73fd27c8c4025a446a89f96739a3c748245cef
[ "MIT" ]
1
2022-01-09T18:49:53.000Z
2022-01-09T18:49:53.000Z
Prg31_Jukebox/src/main/java/dal/CanzoneDAO.java
ggarone/JavaProjects
8a73fd27c8c4025a446a89f96739a3c748245cef
[ "MIT" ]
null
null
null
Prg31_Jukebox/src/main/java/dal/CanzoneDAO.java
ggarone/JavaProjects
8a73fd27c8c4025a446a89f96739a3c748245cef
[ "MIT" ]
null
null
null
24.6
90
0.679675
995,317
package dal; import java.sql.SQLException; import java.util.List; import model.Cantante; import model.Canzone; public interface CanzoneDAO { String TAB = "canzoni"; String ALL = "select * from " + TAB + " "; String ONE = "select * from " + TAB + " WHERE id= "; String INSERT = "insert into " + TAB + " (titolo,cantante,genere,anno) values(?,?,?,?)"; void addCanzone(Canzone c) throws SQLException; Canzone getCanzoneById(int id) throws SQLException; List<Canzone> getCanzoni() throws SQLException; List<Canzone> getCanzoniByCantante(Cantante c) throws SQLException; }
922ff12cbb2acc28d62a63659839edc87205ce83
55
java
Java
idea/testData/refactoring/safeDelete/deleteFunction/kotlinFunctionWithJava/implement2.java
Dimat112/kotlin
0c463d3260bb78afd8da308849e430162aab6cd9
[ "ECL-2.0", "Apache-2.0" ]
337
2020-05-14T00:40:10.000Z
2022-02-16T23:39:07.000Z
idea/testData/refactoring/safeDelete/deleteFunction/kotlinFunctionWithJava/implement2.java
Dimat112/kotlin
0c463d3260bb78afd8da308849e430162aab6cd9
[ "ECL-2.0", "Apache-2.0" ]
92
2020-06-10T23:17:42.000Z
2020-09-25T10:50:13.000Z
idea/testData/refactoring/safeDelete/deleteFunction/kotlinFunctionWithJava/implement2.java
Dimat112/kotlin
0c463d3260bb78afd8da308849e430162aab6cd9
[ "ECL-2.0", "Apache-2.0" ]
54
2016-02-29T16:27:38.000Z
2020-12-26T15:02:23.000Z
11
23
0.545455
995,318
class B implements A { public void foo() { } }
922ff49ffd8580d0ed8048dd44a395184f51caf5
842
java
Java
src/main/java/com/example/todoorganizer/config/JwtTokenConfigurer.java
JarekDziuraDev/ToDoOrganizer
a9547ec8e0a53f95553d13322cff1a2d5356c774
[ "Unlicense" ]
null
null
null
src/main/java/com/example/todoorganizer/config/JwtTokenConfigurer.java
JarekDziuraDev/ToDoOrganizer
a9547ec8e0a53f95553d13322cff1a2d5356c774
[ "Unlicense" ]
null
null
null
src/main/java/com/example/todoorganizer/config/JwtTokenConfigurer.java
JarekDziuraDev/ToDoOrganizer
a9547ec8e0a53f95553d13322cff1a2d5356c774
[ "Unlicense" ]
null
null
null
40.095238
111
0.832542
995,319
package com.example.todoorganizer.config; import org.springframework.security.config.annotation.SecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.DefaultSecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; public class JwtTokenConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> { private JwtTokenProvider jwtTokenProvider; public JwtTokenConfigurer(JwtTokenProvider tokenProvider) { this.jwtTokenProvider = tokenProvider; } @Override public void configure(HttpSecurity http) throws Exception { http.addFilterBefore(new JwtTokenFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); } }
922ff582dd5bf309027037977588c01a03e4ca40
1,438
java
Java
app/src/main/java/kkkj/android/revgoods/bean/Cumulative.java
netbicq/QMES_Android
ee5cfc8d5f0d3d16bcfbf4cac894b249f28b4160
[ "Apache-2.0" ]
null
null
null
app/src/main/java/kkkj/android/revgoods/bean/Cumulative.java
netbicq/QMES_Android
ee5cfc8d5f0d3d16bcfbf4cac894b249f28b4160
[ "Apache-2.0" ]
null
null
null
app/src/main/java/kkkj/android/revgoods/bean/Cumulative.java
netbicq/QMES_Android
ee5cfc8d5f0d3d16bcfbf4cac894b249f28b4160
[ "Apache-2.0" ]
null
null
null
15.136842
48
0.538943
995,320
package kkkj.android.revgoods.bean; import org.litepal.LitePal; import org.litepal.crud.LitePalSupport; /** * 累计 */ public class Cumulative extends LitePalSupport { private int id; /** * 是否已保存为单据 默认-1;未保存 */ private int hasBill = -1; private int count; /** * 类别 */ private String category; /** * 重量 */ private String weight; /** * 记录时间 */ private String time; /** * 所属单据 */ private Bill bill; public String getTime() { return time; } public void setTime(String time) { this.time = time; } public int isHasBill() { return hasBill; } public void setHasBill(int hasBill) { this.hasBill = hasBill; } public Bill getBill() { return bill; } public void setBill(Bill bill) { this.bill = bill; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getWeight() { return weight; } public void setWeight(String weight) { this.weight = weight; } }
922ff5d553c727117854589c6e5f942adfee0285
607
java
Java
src/main/java/com/stalern/designpattern/abstractfactory/factory/ImageReaderFactory.java
stalern/MyDesignPattern
265af67c11241dc49cbd49363d7e52bfd0831ec7
[ "MIT" ]
2
2019-12-07T02:06:03.000Z
2020-01-29T06:16:27.000Z
src/main/java/com/stalern/designpattern/abstractfactory/factory/ImageReaderFactory.java
stalern/MyDesignPattern
265af67c11241dc49cbd49363d7e52bfd0831ec7
[ "MIT" ]
null
null
null
src/main/java/com/stalern/designpattern/abstractfactory/factory/ImageReaderFactory.java
stalern/MyDesignPattern
265af67c11241dc49cbd49363d7e52bfd0831ec7
[ "MIT" ]
null
null
null
22.481481
76
0.721582
995,321
package com.stalern.designpattern.abstractfactory.factory; import com.stalern.designpattern.abstractfactory.product.ForwardImageReader; import com.stalern.designpattern.abstractfactory.product.ReverseImageReader; /** * 会新增一些产品结构用来适应抽象工厂方法 * 当只有一个产品等级结构时,会退化为工厂方法模式 * @author stalern * @date 2019/10/9--20:26 */ public interface ImageReaderFactory { /** * 属于一个产品等级结构 * 正序读取图片接口 * @return imageReader */ ForwardImageReader getForwardImageReader(); /** * 属于另一个产品等级结构 * 逆序读取图片接口 * @return voiceLis */ ReverseImageReader getReverseImageReader(); }
922ff5e34d95532811acea190af173f7f2522a97
1,578
java
Java
src/main/java/gov/nih/ncats/common/util/SingleThreadCounter.java
ncats/ncats-common
c9a53a8582e8658ba32aed949750f23be50025ca
[ "Apache-2.0" ]
null
null
null
src/main/java/gov/nih/ncats/common/util/SingleThreadCounter.java
ncats/ncats-common
c9a53a8582e8658ba32aed949750f23be50025ca
[ "Apache-2.0" ]
null
null
null
src/main/java/gov/nih/ncats/common/util/SingleThreadCounter.java
ncats/ncats-common
c9a53a8582e8658ba32aed949750f23be50025ca
[ "Apache-2.0" ]
1
2020-06-22T14:13:41.000Z
2020-06-22T14:13:41.000Z
22.869565
78
0.627376
995,322
/* * NCATS-COMMON * * Copyright 2020 NIH/NCATS * * 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 gov.nih.ncats.common.util; /** * Created by katzelda on 6/20/17. */ public final class SingleThreadCounter { private long count; public SingleThreadCounter(){ } public SingleThreadCounter(long initialValue){ this.count = initialValue; } public SingleThreadCounter increment(){ count++; return this; } public SingleThreadCounter increment(long amount){ count+=amount; return this; } public SingleThreadCounter decrement(){ count--; return this; } public SingleThreadCounter decrement(long amount){ count-=amount; return this; } public int getAsInt(){ return (int) count; } public long getAsLong(){ return count; } @Override public String toString() { return "SingleThreadCounter{" + "count=" + count + '}'; } }
922ff6989195827306263f1f21ab499fbc7680d7
11,081
java
Java
bmc-datacatalog/src/main/java/com/oracle/bmc/datacatalog/model/GlossarySummary.java
mkelkarbv/oci-java-sdk
ccc4f103c588cfd6c1c07db9a43e8a0a98bd88ae
[ "UPL-1.0", "Apache-2.0" ]
1
2021-04-09T18:17:14.000Z
2021-04-09T18:17:14.000Z
bmc-datacatalog/src/main/java/com/oracle/bmc/datacatalog/model/GlossarySummary.java
mkelkarbv/oci-java-sdk
ccc4f103c588cfd6c1c07db9a43e8a0a98bd88ae
[ "UPL-1.0", "Apache-2.0" ]
null
null
null
bmc-datacatalog/src/main/java/com/oracle/bmc/datacatalog/model/GlossarySummary.java
mkelkarbv/oci-java-sdk
ccc4f103c588cfd6c1c07db9a43e8a0a98bd88ae
[ "UPL-1.0", "Apache-2.0" ]
null
null
null
40.441606
246
0.655988
995,323
/** * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. * This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. */ package com.oracle.bmc.datacatalog.model; /** * Summary of a glossary. A glossary of business terms, such as 'Customer', 'Account', 'Contact', 'Address', * or 'Product', with definitions, used to provide common meaning across disparate data assets. Business glossaries * may be hierarchical where some terms may contain child terms to allow them to be used as 'taxonomies'. * By linking data assets, data entities, and attributes to glossaries and glossary terms, the glossary can act as a * way of organizing data catalog objects in a hierarchy to make a large number of objects more navigable and easier to * consume. Objects in the data catalog, such as data assets or data entities, may be linked to any level in the * glossary, so that the glossary can be used to browse the available data according to the business model of the * organization. * * <br/> * Note: Objects should always be created or deserialized using the {@link Builder}. This model distinguishes fields * that are {@code null} because they are unset from fields that are explicitly set to {@code null}. This is done in * the setter methods of the {@link Builder}, which maintain a set of all explicitly set fields called * {@link #__explicitlySet__}. The {@link #hashCode()} and {@link #equals(Object)} methods are implemented to take * {@link #__explicitlySet__} into account. The constructor, on the other hand, does not set {@link #__explicitlySet__} * (since the constructor cannot distinguish explicit {@code null} from unset {@code null}). **/ @javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20190325") @lombok.AllArgsConstructor(onConstructor = @__({@Deprecated})) @lombok.Value @com.fasterxml.jackson.databind.annotation.JsonDeserialize(builder = GlossarySummary.Builder.class) @com.fasterxml.jackson.annotation.JsonFilter(com.oracle.bmc.http.internal.ExplicitlySetFilter.NAME) @lombok.Builder(builderClassName = "Builder", toBuilder = true) public class GlossarySummary { @com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder(withPrefix = "") @lombok.experimental.Accessors(fluent = true) public static class Builder { @com.fasterxml.jackson.annotation.JsonProperty("key") private String key; public Builder key(String key) { this.key = key; this.__explicitlySet__.add("key"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("displayName") private String displayName; public Builder displayName(String displayName) { this.displayName = displayName; this.__explicitlySet__.add("displayName"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("catalogId") private String catalogId; public Builder catalogId(String catalogId) { this.catalogId = catalogId; this.__explicitlySet__.add("catalogId"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("timeCreated") private java.util.Date timeCreated; public Builder timeCreated(java.util.Date timeCreated) { this.timeCreated = timeCreated; this.__explicitlySet__.add("timeCreated"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("description") private String description; public Builder description(String description) { this.description = description; this.__explicitlySet__.add("description"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("uri") private String uri; public Builder uri(String uri) { this.uri = uri; this.__explicitlySet__.add("uri"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("workflowStatus") private TermWorkflowStatus workflowStatus; public Builder workflowStatus(TermWorkflowStatus workflowStatus) { this.workflowStatus = workflowStatus; this.__explicitlySet__.add("workflowStatus"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("lifecycleState") private LifecycleState lifecycleState; public Builder lifecycleState(LifecycleState lifecycleState) { this.lifecycleState = lifecycleState; this.__explicitlySet__.add("lifecycleState"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("importJobDefinitionKey") private String importJobDefinitionKey; public Builder importJobDefinitionKey(String importJobDefinitionKey) { this.importJobDefinitionKey = importJobDefinitionKey; this.__explicitlySet__.add("importJobDefinitionKey"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("importJobKey") private String importJobKey; public Builder importJobKey(String importJobKey) { this.importJobKey = importJobKey; this.__explicitlySet__.add("importJobKey"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("latestImportJobExecutionKey") private String latestImportJobExecutionKey; public Builder latestImportJobExecutionKey(String latestImportJobExecutionKey) { this.latestImportJobExecutionKey = latestImportJobExecutionKey; this.__explicitlySet__.add("latestImportJobExecutionKey"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("latestImportJobExecutionStatus") private String latestImportJobExecutionStatus; public Builder latestImportJobExecutionStatus(String latestImportJobExecutionStatus) { this.latestImportJobExecutionStatus = latestImportJobExecutionStatus; this.__explicitlySet__.add("latestImportJobExecutionStatus"); return this; } @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set<String> __explicitlySet__ = new java.util.HashSet<String>(); public GlossarySummary build() { GlossarySummary __instance__ = new GlossarySummary( key, displayName, catalogId, timeCreated, description, uri, workflowStatus, lifecycleState, importJobDefinitionKey, importJobKey, latestImportJobExecutionKey, latestImportJobExecutionStatus); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } @com.fasterxml.jackson.annotation.JsonIgnore public Builder copy(GlossarySummary o) { Builder copiedBuilder = key(o.getKey()) .displayName(o.getDisplayName()) .catalogId(o.getCatalogId()) .timeCreated(o.getTimeCreated()) .description(o.getDescription()) .uri(o.getUri()) .workflowStatus(o.getWorkflowStatus()) .lifecycleState(o.getLifecycleState()) .importJobDefinitionKey(o.getImportJobDefinitionKey()) .importJobKey(o.getImportJobKey()) .latestImportJobExecutionKey(o.getLatestImportJobExecutionKey()) .latestImportJobExecutionStatus(o.getLatestImportJobExecutionStatus()); copiedBuilder.__explicitlySet__.retainAll(o.__explicitlySet__); return copiedBuilder; } } /** * Create a new builder. */ public static Builder builder() { return new Builder(); } /** * Unique glossary key that is immutable. **/ @com.fasterxml.jackson.annotation.JsonProperty("key") String key; /** * A user-friendly display name. Does not have to be unique, and it's changeable. * Avoid entering confidential information. * **/ @com.fasterxml.jackson.annotation.JsonProperty("displayName") String displayName; /** * The data catalog's OCID. **/ @com.fasterxml.jackson.annotation.JsonProperty("catalogId") String catalogId; /** * The date and time the glossary was created, in the format defined by [RFC3339](https://tools.ietf.org/html/rfc3339). * Example: `2019-03-25T21:10:29.600Z` * **/ @com.fasterxml.jackson.annotation.JsonProperty("timeCreated") java.util.Date timeCreated; /** * Detailed description of the glossary. **/ @com.fasterxml.jackson.annotation.JsonProperty("description") String description; /** * URI to the glossary instance in the API. **/ @com.fasterxml.jackson.annotation.JsonProperty("uri") String uri; /** * Status of the approval process workflow for this business glossary. **/ @com.fasterxml.jackson.annotation.JsonProperty("workflowStatus") TermWorkflowStatus workflowStatus; /** * State of the Glossary. **/ @com.fasterxml.jackson.annotation.JsonProperty("lifecycleState") LifecycleState lifecycleState; /** * The unique key of the job definition resource that was used in the Glossary import. **/ @com.fasterxml.jackson.annotation.JsonProperty("importJobDefinitionKey") String importJobDefinitionKey; /** * The unique key of the job policy for Glossary import. **/ @com.fasterxml.jackson.annotation.JsonProperty("importJobKey") String importJobKey; /** * The unique key of the parent job execution for which the log resource was created. **/ @com.fasterxml.jackson.annotation.JsonProperty("latestImportJobExecutionKey") String latestImportJobExecutionKey; /** * Status of the latest glossary import job execution, such as running, paused, or completed. * This may include additional information like time import started , import file size and % of completion * **/ @com.fasterxml.jackson.annotation.JsonProperty("latestImportJobExecutionStatus") String latestImportJobExecutionStatus; @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set<String> __explicitlySet__ = new java.util.HashSet<String>(); }
922ff92d001dba70edfa9aca4c090123c8961393
2,072
java
Java
vmidentity/sts/src/main/java/com/vmware/identity/sts/util/JAXBExtractor.java
wfu8/lightwave
cf6a7417cd9807bfcf9bcd99c43c5b2eecf2d298
[ "Apache-2.0" ]
357
2015-04-20T00:16:30.000Z
2022-03-17T05:34:09.000Z
vmidentity/sts/src/main/java/com/vmware/identity/sts/util/JAXBExtractor.java
WestCope/lightwave
baae9b03ddeeb6299ab891f9c1e2957b86d37cc5
[ "Apache-2.0" ]
38
2015-11-19T05:20:53.000Z
2022-03-31T07:21:59.000Z
vmidentity/sts/src/main/java/com/vmware/identity/sts/util/JAXBExtractor.java
WestCope/lightwave
baae9b03ddeeb6299ab891f9c1e2957b86d37cc5
[ "Apache-2.0" ]
135
2015-04-21T15:23:21.000Z
2022-03-30T11:46:36.000Z
37
99
0.646718
995,324
/* * Copyright (c) 2012-2015 VMware, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, without * warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the * License for the specific language governing permissions and limitations * under the License. */ package com.vmware.identity.sts.util; import javax.xml.bind.JAXBElement; import org.oasis_open.docs.wss._2004._01.oasis_200401_wss_wssecurity_secext_1_0.SecurityHeaderType; import org.oasis_open.docs.wss._2004._01.oasis_200401_wss_wssecurity_secext_1_0.UsernameTokenType; public class JAXBExtractor { @SuppressWarnings("unchecked") public static <T> T extractFromSecurityHeader(SecurityHeaderType securityHeader, Class<T> c) { assert securityHeader != null; // only extract one occurrence of a specified class value. for (Object o : securityHeader.getAny()) { if (o instanceof JAXBElement<?>) { JAXBElement<?> jaxb = (JAXBElement<?>) o; if (jaxb.getDeclaredType().equals(c)) { return (T) jaxb.getValue(); } } } return null; } @SuppressWarnings("unchecked") public static <T> T extractFromUsernameToken(UsernameTokenType usernameToken, Class<T> c) { assert usernameToken != null; // only extract one occurrence of a specified class value. for (Object o : usernameToken.getAny()) { if (o instanceof JAXBElement<?>) { JAXBElement<?> jaxb = (JAXBElement<?>) o; if (jaxb.getDeclaredType().equals(c)) { return (T) jaxb.getValue(); } } } return null; } }
922ff9d13a4828fd0487368a74e80e55c2f6699d
1,292
java
Java
api/src/main/java/com/mlmstorenow/api/models/Receipt.java
wayne-christian-somers/project-2
e36492f0a2edb78b0637f535800844da78d5245e
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
api/src/main/java/com/mlmstorenow/api/models/Receipt.java
wayne-christian-somers/project-2
e36492f0a2edb78b0637f535800844da78d5245e
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
api/src/main/java/com/mlmstorenow/api/models/Receipt.java
wayne-christian-somers/project-2
e36492f0a2edb78b0637f535800844da78d5245e
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
21.898305
90
0.791796
995,325
package com.mlmstorenow.api.models; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotBlank; import org.hibernate.annotations.CreationTimestamp; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Entity @Table(name = "receipt") @Data @AllArgsConstructor @NoArgsConstructor @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") public class Receipt { @Id @Column(name = "order_id") @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = "item_name") @NotBlank private String itemname; @Column(name = "cost") @NotBlank private int cost; @Column(name = "tax") @NotBlank private int tax; @Column(name = "total") @NotBlank private int tot; @CreationTimestamp @Temporal(TemporalType.TIMESTAMP) @Column(name = "receipt_date") private Date date; }
922ff9e8e50b540b7a1c1212c95919edf87c7a9f
4,250
java
Java
bundles/org.insilico.sbmlsheets/src/org/insilico/sbmlsheets/editor/SheetProjectView.java
MariettaHa/SBMLSheets2
b985d82b364601305158677ae349d625890c3a80
[ "MIT" ]
null
null
null
bundles/org.insilico.sbmlsheets/src/org/insilico/sbmlsheets/editor/SheetProjectView.java
MariettaHa/SBMLSheets2
b985d82b364601305158677ae349d625890c3a80
[ "MIT" ]
null
null
null
bundles/org.insilico.sbmlsheets/src/org/insilico/sbmlsheets/editor/SheetProjectView.java
MariettaHa/SBMLSheets2
b985d82b364601305158677ae349d625890c3a80
[ "MIT" ]
null
null
null
34.552846
143
0.717882
995,326
package org.insilico.sbmlsheets.editor; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.util.Collections; import java.util.Iterator; import java.util.regex.Pattern; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar; import javafx.scene.control.ComboBox; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuButton; import javafx.scene.control.MenuItem; import javafx.scene.control.ScrollPane; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.scene.text.TextAlignment; import javafx.scene.text.TextBoundsType; import javafx.stage.FileChooser; import javafx.stage.Modality; import javafx.stage.Screen; import javafx.stage.Stage; import javafx.stage.StageStyle; import javafx.stage.Window; import javafx.stage.FileChooser.ExtensionFilter; import javax.annotation.PostConstruct; import javax.inject.Inject; import org.insilico.sbmlsheets.core.HelpContent; import org.insilico.sbmlsheets.core.SBMLUtils; import org.insilico.sbmlsheets.core.TableEditor; import org.insilico.sbmlsheets.core.SheetWriter; public class SheetProjectView { @Inject TableEditor project; ObservableList<String> pathsInDir; private final int PREF_WIDTH = 400; private final int PREF_HEIGHT_SCROLL = 700; @PostConstruct private void init(BorderPane parent) { this.makeView(parent); } private BorderPane makeView(BorderPane parent) { this.pathsInDir = FXCollections.observableArrayList(this.project.readFilesInDir(new File(this.project.getUri().replace(".sheets", "")))); MenuBar bar = new MenuBar(); TabPane pane = new TabPane(); Tab tab1 = new Tab("Start SBML Sheets Project"); pane.getTabs().add(tab1); Menu fileMenu = new Menu("File"); MenuItem b = new MenuItem("Create New Table"); MenuItem open1 = new MenuItem("Open Table File"); MenuItem closeWindow = new MenuItem("Close InSilico"); fileMenu.getItems().addAll(b, open1, closeWindow); bar.getMenus().add(fileMenu); BorderPane bPane = new BorderPane(); bPane.setTop(bar); TextArea textArea = new TextArea(HelpContent.getStartText()); textArea.setEditable(false); bPane.setCenter(textArea); tab1.setContent(bPane); open1.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { FileChooser fileChooser = new FileChooser(); fileChooser.getExtensionFilters().addAll( new ExtensionFilter("CSV files", "*.csv"), new ExtensionFilter("TAB files", "*.tab"), new ExtensionFilter("TSV files", "*tsv")); File file = fileChooser.showOpenDialog(new Stage()); if(file != null){ TableEditorView newEditorTab = new TableEditorView("Editor ("+file.getName()+")", file.getAbsolutePath());//, project.getUri()); pane.getTabs().add(newEditorTab); }else { new QuickInfoPopup("Import failed", "File could not be imported, check for text property!"); } } }); b.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { TableEditorView newEditorTab = new TableEditorView("New Editor ("+pane.getTabs().size()+")");//, project.getUri()); pane.getTabs().add(newEditorTab); } }); parent.setCenter(pane); return parent; } }
922ff9f4f054905ab1367f0c722b772af7be6de8
1,033
java
Java
src/main/java/vazkii/botania/common/components/NarslimmusComponent.java
aquila-zyy/Botania
bfe646c42ddf93aa7805068123abb540d95c4b6d
[ "MIT" ]
null
null
null
src/main/java/vazkii/botania/common/components/NarslimmusComponent.java
aquila-zyy/Botania
bfe646c42ddf93aa7805068123abb540d95c4b6d
[ "MIT" ]
null
null
null
src/main/java/vazkii/botania/common/components/NarslimmusComponent.java
aquila-zyy/Botania
bfe646c42ddf93aa7805068123abb540d95c4b6d
[ "MIT" ]
null
null
null
25.825
72
0.778316
995,327
/* * This class is distributed as part of the Botania Mod. * Get the Source Code in github: * https://github.com/Vazkii/Botania * * Botania is Open Source and distributed under the * Botania License: http://botaniamod.net/license.php */ package vazkii.botania.common.components; import dev.onyxstudios.cca.api.v3.component.Component; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.entity.monster.Slime; public class NarslimmusComponent implements Component { public static final String TAG_WORLD_SPAWNED = "botania:world_spawned"; private boolean naturalSpawned = false; public NarslimmusComponent(Slime e) {} @Override public void readFromNbt(CompoundTag tag) { naturalSpawned = tag.getBoolean(TAG_WORLD_SPAWNED); } @Override public void writeToNbt(CompoundTag tag) { tag.putBoolean(TAG_WORLD_SPAWNED, naturalSpawned); } public boolean isNaturalSpawned() { return naturalSpawned; } public void setNaturalSpawn(boolean naturalSpawned) { this.naturalSpawned = naturalSpawned; } }
922ffa0e4f94d2abbc2cfd8ea602a9bac42c4e88
576
java
Java
src/main/java/me/breakofday/calculate/MathUtil.java
DayBreak365/Calculate
cabf571e994d43d9c0f615a93477a286d6370f85
[ "MIT" ]
null
null
null
src/main/java/me/breakofday/calculate/MathUtil.java
DayBreak365/Calculate
cabf571e994d43d9c0f615a93477a286d6370f85
[ "MIT" ]
null
null
null
src/main/java/me/breakofday/calculate/MathUtil.java
DayBreak365/Calculate
cabf571e994d43d9c0f615a93477a286d6370f85
[ "MIT" ]
null
null
null
26.181818
85
0.720486
995,328
package me.breakofday.calculate; import com.google.common.math.BigIntegerMath; public class MathUtil { private MathUtil() {} public static double divide(double a, double b) { if (b == 0.0) throw new ArithmeticException("Divided by zero"); return a / b; } public static double factorial(double a) { if (a == Math.floor(a)) { if (!Double.isInfinite(a)) return BigIntegerMath.factorial((int) a).doubleValue(); else throw new ArithmeticException("Factorial of infinite value"); } else throw new ArithmeticException("Factorial of non natural number"); } }
922ffd0c9a7186525ce0e43dc45a113a371ecada
3,412
java
Java
src/main/java/org/recyclall/recyclegram/controllers/RequestMB.java
habeascorpse/recyclegram
f297dc5af0d348f0eb2d142eef3411ae4739b377
[ "MIT" ]
null
null
null
src/main/java/org/recyclall/recyclegram/controllers/RequestMB.java
habeascorpse/recyclegram
f297dc5af0d348f0eb2d142eef3411ae4739b377
[ "MIT" ]
null
null
null
src/main/java/org/recyclall/recyclegram/controllers/RequestMB.java
habeascorpse/recyclegram
f297dc5af0d348f0eb2d142eef3411ae4739b377
[ "MIT" ]
null
null
null
24.371429
79
0.677608
995,329
/* * 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 org.recyclall.recyclegram.controllers; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.Serializable; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import org.primefaces.model.DefaultStreamedContent; import org.primefaces.model.StreamedContent; import org.recyclall.recyclegram.services.MaterialRequestService; import org.recyclall.recyclegram.services.MaterialService; import org.recyclall.recyclegram.services.UFService; import org.recyclall.recyclegram2.domain.Material; import org.recyclall.recyclegram2.domain.MaterialRequest; import org.recyclall.recyclegram2.domain.UF; /** * * @author habeas */ @Named @ViewScoped public class RequestMB implements Serializable { private MaterialRequest request; private List<MaterialRequest> requestList; private String pesquisaMaterial; private Material selectedMaterial; private List<Material> materialList; private UF selectedUF; @Inject private DashboardMB dashboard; @EJB private MaterialRequestService materialRequestEJB; @EJB private MaterialService materialEJB; @EJB private UFService ufEJB; public RequestMB() { } @PostConstruct public void init() { requestList = materialRequestEJB.findAll(); request = new MaterialRequest(); } public MaterialRequest getRequest() { return request; } public void setRequest(MaterialRequest request) { this.request = request; } public void pesquisar() { if (selectedUF != null) { requestList = materialRequestEJB.findByUF(selectedUF); } else { requestList = materialRequestEJB.findAll(); } } public List<MaterialRequest> getRequestList() { return requestList; } public String getPesquisaMaterial() { return pesquisaMaterial; } public void setPesquisaMaterial(String pesquisaMaterial) { this.pesquisaMaterial = pesquisaMaterial; } public Material getSelectedMaterial() { return selectedMaterial; } public void setSelectedMaterial(Material selectedMaterial) { this.selectedMaterial = selectedMaterial; } public List<Material> getMaterialList() { return materialList; } public List<UF> getUFList() { return ufEJB.findAll(); } public void pesquisarMaterial() { materialList = materialEJB.findByDescription(pesquisaMaterial); selectedMaterial = null; } public void newRequest() { request = new MaterialRequest(); } public UF getSelectedUF() { return selectedUF; } public void setSelectedUF(UF selectedUF) { this.selectedUF = selectedUF; } public void save() { request.setUser(dashboard.getUser()); request.setMaterial(selectedMaterial); materialRequestEJB.create(request); request = null; pesquisaMaterial = ""; pesquisar(); } }
922ffd35db0d0b14e2960159b1a0b288cd05db0c
12,470
java
Java
src/test/java/com/exasol/adapter/dialects/sqlserver/SQLServerSqlGenerationVisitorTest.java
exasol/sqlserver-virtual-schema
f0b726ae0c2a710241e9699c0031d7a2eb90fd9f
[ "MIT" ]
null
null
null
src/test/java/com/exasol/adapter/dialects/sqlserver/SQLServerSqlGenerationVisitorTest.java
exasol/sqlserver-virtual-schema
f0b726ae0c2a710241e9699c0031d7a2eb90fd9f
[ "MIT" ]
7
2021-01-14T09:56:57.000Z
2021-10-12T10:42:51.000Z
src/test/java/com/exasol/adapter/dialects/sqlserver/SQLServerSqlGenerationVisitorTest.java
exasol/sqlserver-virtual-schema
f0b726ae0c2a710241e9699c0031d7a2eb90fd9f
[ "MIT" ]
null
null
null
52.175732
120
0.618284
995,330
package com.exasol.adapter.dialects.sqlserver; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import com.exasol.adapter.AdapterException; import com.exasol.adapter.AdapterProperties; import com.exasol.adapter.adapternotes.ColumnAdapterNotes; import com.exasol.adapter.adapternotes.ColumnAdapterNotesJsonConverter; import com.exasol.adapter.dialects.SqlDialect; import com.exasol.adapter.dialects.SqlDialectFactory; import com.exasol.adapter.dialects.rewriting.SqlGenerationContext; import com.exasol.adapter.metadata.*; import com.exasol.adapter.sql.*; class SQLServerSqlGenerationVisitorTest { private SQLServerSqlGenerationVisitor visitor; @BeforeEach void beforeEach() { final SqlDialectFactory factory = new SQLServerSqlDialectFactory(); final SqlDialect dialect = factory.createSqlDialect(null, AdapterProperties.emptyProperties()); final SqlGenerationContext context = new SqlGenerationContext("test_catalog", "test_schema", false); this.visitor = new SQLServerSqlGenerationVisitor(dialect, context); } @Test void testVisitSqlSelectListAnyValue() throws AdapterException { final SqlSelectList sqlSelectList = SqlSelectList.createAnyValueSelectList(); assertThat(this.visitor.visit(sqlSelectList), equalTo("true")); } @Test void testVisitSqlStatementSelect() throws AdapterException { final SqlStatementSelect select = (SqlStatementSelect) getTestSqlNode(); assertThat(this.visitor.visit(select), // equalTo("SELECT TOP 10 [USER_ID], COUNT_BIG([URL])" // + " FROM [test_catalog].[test_schema].[CLICKS]" // + " WHERE 1 < [USER_ID]" // + " GROUP BY [USER_ID] HAVING 1 < COUNT_BIG([URL])" // + " ORDER BY [USER_ID] NULLS LAST")); } @CsvSource({ "ADD_DAYS, DAY", // "ADD_HOURS, HOUR", // "ADD_MINUTES, MINUTE", // "ADD_SECONDS, SECOND", // "ADD_YEARS, YEAR", // "ADD_WEEKS, WEEK" }) @ParameterizedTest void testVisitSqlFunctionScalarAddDate(final ScalarFunction scalarFunction, final String expected) throws AdapterException { final SqlFunctionScalar sqlFunctionScalar = createSqlFunctionScalarForDateTest(scalarFunction); assertThat(this.visitor.visit(sqlFunctionScalar), equalTo("DATEADD(" + expected + ",10,[test_column])")); } private SqlFunctionScalar createSqlFunctionScalarForDateTest(final ScalarFunction scalarFunction) { final List<SqlNode> arguments = new ArrayList<>(); arguments.add(new SqlColumn(1, ColumnMetadata.builder().name("test_column") .adapterNotes("{\"jdbcDataType\":93, " + "\"typeName\":\"TIMESTAMP\"}") .type(DataType.createChar(20, DataType.ExaCharset.UTF8)).build())); arguments.add(new SqlLiteralExactnumeric(new BigDecimal(10))); return new SqlFunctionScalar(scalarFunction, arguments); } @CsvSource({ "SECONDS_BETWEEN, SECOND", // "MINUTES_BETWEEN, MINUTE", // "HOURS_BETWEEN, HOUR", // "DAYS_BETWEEN, DAY", // "MONTHS_BETWEEN, MONTH", // "YEARS_BETWEEN, YEAR" }) @ParameterizedTest void testVisitSqlFunctionScalarTimeBetween(final ScalarFunction scalarFunction, final String expected) throws AdapterException { final SqlFunctionScalar sqlFunctionScalar = createSqlFunctionScalarForDateTest(scalarFunction); assertThat(this.visitor.visit(sqlFunctionScalar), equalTo("DATEDIFF(" + expected + ",10,[test_column])")); } @CsvSource({ "CURRENT_DATE, CAST(GETDATE() AS DATE)", // "CURRENT_TIMESTAMP, GETDATE()", // "SYSDATE, CAST(SYSDATETIME() AS DATE)", // "SYSTIMESTAMP, SYSDATETIME()" }) @ParameterizedTest void testVisitSqlFunctionScalarWithoutArguments(final ScalarFunction scalarFunction, final String expected) throws AdapterException { final SqlFunctionScalar sqlFunctionScalar = new SqlFunctionScalar(scalarFunction, null); assertThat(this.visitor.visit(sqlFunctionScalar), equalTo(expected)); } @CsvSource(value = { "INSTR : CHARINDEX('test2', 'test', 'test3')", // "LPAD : RIGHT ( REPLICATE('test3','test2') + LEFT('test','test2'),'test2')", // "RPAD : LEFT(RIGHT('test','test2') + REPLICATE('test3','test2'),'test2')" // }, delimiter = ':') @ParameterizedTest void testVisitSqlFunctionScalarWithThreeArguments(final ScalarFunction scalarFunction, final String expected) throws AdapterException { final List<SqlNode> arguments = new ArrayList<>(); arguments.add(new SqlLiteralString("test")); arguments.add(new SqlLiteralString("test2")); arguments.add(new SqlLiteralString("test3")); final SqlFunctionScalar sqlFunctionScalar = new SqlFunctionScalar(scalarFunction, arguments); assertThat(this.visitor.visit(sqlFunctionScalar), equalTo(expected)); } @CsvSource(value = { "ST_X : 'left'.STX", // "ST_Y : 'left'.STY", // "ST_ENDPOINT : CAST('left'.STEndPoint() AS VARCHAR(8000))", // "ST_ISCLOSED : 'left'.STIsClosed()", // "ST_ISRING : 'left'.STIsRing()", // "ST_LENGTH : 'left'.STLength()", // "ST_NUMPOINTS : 'left'.STNumPoints()", // "ST_POINTN : CAST('left'.STPointN('right') AS VARCHAR(8000))", // "ST_STARTPOINT : CAST('left'.STStartPoint() AS VARCHAR(8000))", // "ST_AREA : 'left'.STArea()", // "ST_EXTERIORRING : CAST('left'.STExteriorRing() AS VARCHAR(8000))", // "ST_INTERIORRINGN : CAST('left'.STInteriorRingN ('right') AS VARCHAR(8000))", // "ST_NUMINTERIORRINGS : 'left'.STNumInteriorRing()", // "ST_GEOMETRYN : CAST('left'.STGeometryN('right') AS VARCHAR(8000))", // "ST_NUMGEOMETRIES : 'left'.STNumGeometries()", // "ST_BOUNDARY : CAST('left'.STBoundary() AS VARCHAR(8000))", // "ST_BUFFER : CAST('left'.STBuffer('right') AS VARCHAR(8000))", // "ST_CENTROID : CAST('left'.STCentroid() AS VARCHAR(8000))", // "ST_CONTAINS : 'left'.STContains('right')", // "ST_CONVEXHULL : CAST('left'.STConvexHull() AS VARCHAR(8000))", // "ST_CROSSES : 'left'.STCrosses('right')", // "ST_DIFFERENCE : CAST('left'.STDifference('right') AS VARCHAR(8000))", // "ST_DIMENSION : 'left'.STDimension()", // "ST_DISJOINT : CAST('left'.STDisjoint('right') AS VARCHAR(8000))", // "ST_DISTANCE : 'left'.STDistance('right')", // "ST_ENVELOPE : CAST('left'.STEnvelope() AS VARCHAR(8000))", // "ST_EQUALS : 'left'.STEquals('right')", // "ST_GEOMETRYTYPE : 'left'.STGeometryType()", // "ST_INTERSECTION : CAST('left'.STIntersection('right') AS VARCHAR(8000))", // "ST_INTERSECTS : 'left'.STIntersects('right')", // "ST_ISEMPTY : 'left'.STIsEmpty()", // "ST_ISSIMPLE : 'left'.STIsSimple()", // "ST_OVERLAPS : 'left'.STOverlaps('right')", // "ST_SYMDIFFERENCE : CAST('left'.STSymDifference ('right') AS VARCHAR(8000))", // "ST_TOUCHES : 'left'.STTouches('right')", // "ST_UNION : CAST('left'.STUnion('right') AS VARCHAR(8000))", // "ST_WITHIN : 'left'.STWithin('right')", // "BIT_AND : 'left' & '" + "" + "right'", // "BIT_OR : 'left' | 'right'", // "BIT_XOR : 'left' ^ 'right'", // "BIT_NOT : ~ 'left'", // "HASH_MD5 : CONVERT(Char, HASHBYTES('MD5','left'), 2)", // "HASH_SHA1 : CONVERT(Char, HASHBYTES('SHA1','left'), 2)", // "ZEROIFNULL : ISNULL('left',0)" // }, delimiter = ':') @ParameterizedTest void testVisitSqlFunctionScalarWithTwoArguments(final ScalarFunction scalarFunction, final String expected) throws AdapterException { final List<SqlNode> arguments = List.of(new SqlLiteralString("left"), new SqlLiteralString("right")); final SqlFunctionScalar sqlFunctionScalar = new SqlFunctionScalar(scalarFunction, arguments); assertThat(this.visitor.visit(sqlFunctionScalar), equalTo(expected)); } private static SqlNode getTestSqlNode() { return new DialectTestData().getTestSqlNode(); } private static class DialectTestData { private SqlNode getTestSqlNode() { // SELECT USER_ID, count(URL) FROM CLICKS // WHERE 1 < USER_ID // GROUP BY USER_ID // HAVING 1 < COUNT(URL) // ORDER BY USER_ID // LIMIT 10; final TableMetadata clicksMeta = getClicksTableMetadata(); final SqlTable fromClause = new SqlTable("CLICKS", clicksMeta); final SqlSelectList selectList = SqlSelectList.createRegularSelectList(List.of( new SqlColumn(0, clicksMeta.getColumns().get(0)), new SqlFunctionAggregate(AggregateFunction.COUNT, List.of(new SqlColumn(1, clicksMeta.getColumns().get(1))), false))); final SqlNode whereClause = new SqlPredicateLess(new SqlLiteralExactnumeric(BigDecimal.ONE), new SqlColumn(0, clicksMeta.getColumns().get(0))); final SqlExpressionList groupBy = new SqlGroupBy(List.of(new SqlColumn(0, clicksMeta.getColumns().get(0)))); final SqlNode countUrl = new SqlFunctionAggregate(AggregateFunction.COUNT, List.of(new SqlColumn(1, clicksMeta.getColumns().get(1))), false); final SqlNode having = new SqlPredicateLess(new SqlLiteralExactnumeric(BigDecimal.ONE), countUrl); final SqlOrderBy orderBy = new SqlOrderBy(List.of(new SqlColumn(0, clicksMeta.getColumns().get(0))), List.of(true), List.of(true)); final SqlLimit limit = new SqlLimit(10); return SqlStatementSelect.builder().selectList(selectList).fromClause(fromClause).whereClause(whereClause) .groupBy(groupBy).having(having).orderBy(orderBy).limit(limit).build(); } private TableMetadata getClicksTableMetadata() { final ColumnAdapterNotesJsonConverter converter = ColumnAdapterNotesJsonConverter.getInstance(); final List<ColumnMetadata> columns = new ArrayList<>(); final ColumnAdapterNotes decimalAdapterNotes = ColumnAdapterNotes.builder() // .jdbcDataType(3) // .typeName("DECIMAL") // .build(); final ColumnAdapterNotes varcharAdapterNotes = ColumnAdapterNotes.builder() // .jdbcDataType(12) // .typeName("VARCHAR") // .build(); columns.add(ColumnMetadata.builder() // .name("USER_ID") // .adapterNotes(converter.convertToJson(decimalAdapterNotes)).type(DataType.createDecimal(18, 0)) // .nullable(true) // .identity(false) // .defaultValue("") // .comment("") // .build()); columns.add(ColumnMetadata.builder() // .name("URL") // .adapterNotes(converter.convertToJson(varcharAdapterNotes)) // .type(DataType.createVarChar(10000, DataType.ExaCharset.UTF8)) // .nullable(true) // .identity(false) // .defaultValue("") // .comment("") // .build()); return new TableMetadata("CLICKS", "", columns, ""); } } @Test void testVisitLiteralBoolTrue() { assertThat(this.visitor.visit(new SqlLiteralBool(true)), equalTo("1 = 1")); } @Test void testVisitLiteralBoolFalse() { assertThat(this.visitor.visit(new SqlLiteralBool(false)), equalTo("1 = 0")); } }
922ffd42ac39ae61e2fd4714233a9c589ced5f19
5,984
java
Java
src/test/java/com/reposify/client/ReposifyClientTest.java
reposify/reposify-java
ab6248bcf889376c7dbbb6b58954beda9716671c
[ "MIT" ]
null
null
null
src/test/java/com/reposify/client/ReposifyClientTest.java
reposify/reposify-java
ab6248bcf889376c7dbbb6b58954beda9716671c
[ "MIT" ]
null
null
null
src/test/java/com/reposify/client/ReposifyClientTest.java
reposify/reposify-java
ab6248bcf889376c7dbbb6b58954beda9716671c
[ "MIT" ]
null
null
null
46.75
119
0.685829
995,331
package com.reposify.client; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.common.base.Charsets; import com.google.common.io.Resources; import com.reposify.client.ReposifyClient; import com.reposify.client.domain.account.AccountStatusResponse; import com.reposify.client.domain.discovery.ScanResponse; import com.reposify.client.domain.discovery.StatusResponse; import com.reposify.client.domain.insights.InsightsCountResponse; import com.reposify.client.domain.insights.InsightsSearchResponse; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.IOException; import static com.github.tomakehurst.wiremock.client.WireMock.*; public class ReposifyClientTest { @Rule public WireMockRule reposifyApi = new WireMockRule(); private ReposifyClient reposifyClient; @Before public void init() throws IOException { reposifyClient = new ReposifyClient("http://localhost:8080/", "TEST_TOKEN"); // Mock account status response reposifyApi.stubFor(get(urlEqualTo("/v1/account/status?token=TEST_TOKEN")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody(Resources.toString(Resources.getResource("account_status.json"), Charsets.UTF_8)))); // Mock search insights response reposifyApi.stubFor(get(urlEqualTo("/v1/insights/search?page=1&token=TEST_TOKEN")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody(Resources.toString(Resources.getResource("insights_search.json"), Charsets.UTF_8)))); // Mock count insights response reposifyApi.stubFor(get(urlEqualTo("/v1/insights/count?token=TEST_TOKEN")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody(Resources.toString(Resources.getResource("insights_count.json"), Charsets.UTF_8)))); // Mock scan status response reposifyApi.stubFor(get(urlEqualTo("/v1/scan/status?token=TEST_TOKEN")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody(Resources.toString(Resources.getResource("scan_status.json"), Charsets.UTF_8)))); // Mock scan internet response reposifyApi.stubFor(post(urlEqualTo("/v1/scan/internet?token=TEST_TOKEN")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody(Resources.toString(Resources.getResource("scan_internet.json"), Charsets.UTF_8)))); // Mock scan host response reposifyApi.stubFor(post(urlEqualTo("/v1/scan/host?token=TEST_TOKEN")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody(Resources.toString(Resources.getResource("scan_host.json"), Charsets.UTF_8)))); } @Test public void testGetAccountStatus() { //reposifyClient.scanHost(); //reposifyClient.scanInternet(); AccountStatusResponse accountStatus = reposifyClient.getAccountStatus(); Assert.assertNotNull(accountStatus); Assert.assertEquals(java.util.Optional.of(0).get(), accountStatus.getHostDiscoveryCredits()); Assert.assertEquals(java.util.Optional.of(0).get(), accountStatus.getInternetDiscoveryCredits()); Assert.assertEquals(java.util.Optional.of(0).get(), accountStatus.getExportCredits()); Assert.assertEquals(java.util.Optional.of(1000).get(), accountStatus.getQueryCredits()); Assert.assertEquals("Free", accountStatus.getPlan()); } @Test public void testSearchInsights() { InsightsSearchResponse insightsSearchResponse = reposifyClient.searchInsights(null, null, 1); Assert.assertNotNull(insightsSearchResponse); Assert.assertNotNull(insightsSearchResponse.getDevices()); Assert.assertNotNull(insightsSearchResponse.getPagination()); Assert.assertNotNull(insightsSearchResponse.getTotalCount()); Assert.assertEquals(java.util.Optional.of(0).get(), insightsSearchResponse.getTotalCount()); } @Test public void testGetInsightCount() { InsightsCountResponse response = reposifyClient.getInsightsCount(null, null); Assert.assertNotNull(response); Assert.assertEquals(java.util.Optional.of(10).get(), response.getTotalCount()); } @Test public void testScanStatus() { StatusResponse response = reposifyClient.scanStatus(null); Assert.assertNotNull(response); Assert.assertEquals("6c506856-2d74-4329-b9bc-95257afb2264", response.getJobId()); Assert.assertEquals("processing", response.getStatus()); Assert.assertEquals("172.16.17.32", response.getLastIpScanned()); Assert.assertEquals("2017-03-01T16:50:08.906Z", response.getCreatedDate()); Assert.assertEquals(java.util.Optional.of(256).get(), response.getIpsLeftToBeScanned()); } @Test public void testScanHost() { ScanResponse response = reposifyClient.scanHost("1.1.1.1", null); Assert.assertNotNull(response); Assert.assertEquals("7448dc4d-5313-400f-bc02-17f40ebf2f84", response.getJobId()); Assert.assertEquals("208.130.29.0/24", response.getIps()); Assert.assertEquals("pending", response.getStatus()); } @Test public void testScanInternet() { ScanResponse response = reposifyClient.scanInternet(null, null); Assert.assertNotNull(response); Assert.assertEquals("7448dc4d-5313-400f-bc02-17f40ebf2f84", response.getJobId()); Assert.assertEquals("208.130.29.0/24", response.getIps()); Assert.assertEquals("pending", response.getStatus()); } }
922ffe84696542244609b4bdb53bf5931a07fe83
2,704
java
Java
tools/unicodetools/com/ibm/rbm/RBJavaImporter.java
ionsphere/icu-cmake
ba3750c592a4f221da9bb80b9145d09f21279adc
[ "Apache-2.0" ]
null
null
null
tools/unicodetools/com/ibm/rbm/RBJavaImporter.java
ionsphere/icu-cmake
ba3750c592a4f221da9bb80b9145d09f21279adc
[ "Apache-2.0" ]
null
null
null
tools/unicodetools/com/ibm/rbm/RBJavaImporter.java
ionsphere/icu-cmake
ba3750c592a4f221da9bb80b9145d09f21279adc
[ "Apache-2.0" ]
null
null
null
31.811765
96
0.543639
995,332
/* ***************************************************************************** * Copyright (C) 2000-2007, International Business Machines Corporation and * * others. All Rights Reserved. * ***************************************************************************** */ package com.ibm.rbm; import java.io.*; import com.ibm.rbm.gui.RBManagerGUI; import java.util.*; import java.net.*; /** * This is the super class for all importer plug-in classes. As of yet, there * is little contained in this class. * * @author Jared Jackson * @see com.ibm.rbm.RBManager */ public class RBJavaImporter extends RBImporter { public RBJavaImporter(String title, RBManager rbm, RBManagerGUI gui) { super(title, rbm, gui); } protected void setupFileChooser() { chooser.setFileFilter(new javax.swing.filechooser.FileFilter(){ public boolean accept(File f) { if (f.isDirectory()) return true; if (f.getName().endsWith(".class") && f.getName().indexOf("_") < 0) return true; return false; } public String getDescription() { return Resources.getTranslation("import_java_file_description"); } }); } protected void beginImport() throws IOException { super.beginImport(); ListResourceBundle base_lrb = null; URLClassLoader urlLoader = null; try { File baseFile = getChosenFile(); URL baseURL = baseFile.toURL(); URL urls[] = new URL[1]; urls[0] = baseURL; urlLoader = new URLClassLoader(urls); String baseName = baseFile.getName(); baseName = baseName.substring(0, baseName.indexOf(".class")); Class baseClass = urlLoader.loadClass(baseName); base_lrb = (ListResourceBundle)baseClass.newInstance(); } catch (Exception e) { RBManagerGUI.debugMsg(e.toString()); RBManagerGUI.debugMsg(e.getMessage()); e.printStackTrace(System.err); } if (base_lrb != null) { Enumeration keys = base_lrb.getKeys(); while (keys.hasMoreElements()) { String key = keys.nextElement().toString(); RBManagerGUI.debugMsg("Resource -> " + key + " = " + base_lrb.getString(key)); } } } } /* class myClassLoader extends ClassLoader { public myClassLoader() { super(); } public Class myDefineClass(String name, byte array[], int off, int len) { return super.defineClass(name, array, off, len); } } */
922ffefce2d45b7b1c692431f9709ff6a1b84e76
410
java
Java
pp/PPIndividuais/src/enums/EItens.java
Viniciusalopes/ads20192-modulo3
84ac340e0d0c6a3e4f2126935a6d58b4c4e93fa4
[ "MIT" ]
null
null
null
pp/PPIndividuais/src/enums/EItens.java
Viniciusalopes/ads20192-modulo3
84ac340e0d0c6a3e4f2126935a6d58b4c4e93fa4
[ "MIT" ]
null
null
null
pp/PPIndividuais/src/enums/EItens.java
Viniciusalopes/ads20192-modulo3
84ac340e0d0c6a3e4f2126935a6d58b4c4e93fa4
[ "MIT" ]
1
2020-11-18T20:21:57.000Z
2020-11-18T20:21:57.000Z
18.636364
79
0.7
995,333
/* * 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 enums; /** * * @author vovomint */ public enum EItens { TCurso_Enfase_Nome, TCurso_Nome, TEnfase_Curso_Nome, TEnfase_Nome, TNome, TSituacao_Curso_nome, TSituacao_Nome, TSobrenome }
922fff3517cbe562dc08b796de65a9909f779f53
2,086
java
Java
src/app/src/main/java/com/example/qr_go/activities/BaseActivity.java
CMPUT301W22T16/QR-Go
f8169050d5bba54e18a86afe3cfdc80bcca22403
[ "Apache-2.0" ]
null
null
null
src/app/src/main/java/com/example/qr_go/activities/BaseActivity.java
CMPUT301W22T16/QR-Go
f8169050d5bba54e18a86afe3cfdc80bcca22403
[ "Apache-2.0" ]
50
2022-02-07T02:25:20.000Z
2022-03-30T21:42:31.000Z
src/app/src/main/java/com/example/qr_go/activities/BaseActivity.java
CMPUT301W22T16/QR-Go
f8169050d5bba54e18a86afe3cfdc80bcca22403
[ "Apache-2.0" ]
1
2022-01-11T19:03:46.000Z
2022-01-11T19:03:46.000Z
42.571429
120
0.651965
995,334
package com.example.qr_go.activities; import android.content.Intent; import android.os.Build; import android.view.MenuItem; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.fragment.app.FragmentActivity; import com.example.qr_go.R; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.navigation.NavigationBarView; public class BaseActivity extends FragmentActivity { protected void initializeNavbar() { // Set onClick for BottomNavigation nav items BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_nav_view); bottomNavigationView.getMenu().setGroupCheckable(0, false, true); // make navbar uncheckable (un-highlightable) bottomNavigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() { @RequiresApi(api = Build.VERSION_CODES.O) @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { int id = item.getItemId(); Intent intent = new Intent(BaseActivity.this, MapsActivity.class); if (id == R.id.nav_search) intent = new Intent(BaseActivity.this, SearchActivity.class); else if (id == R.id.nav_my_codes) intent = new Intent(BaseActivity.this, MyQRCodesActivity.class); else if (id == R.id.nav_scan_code) intent = new Intent(BaseActivity.this, QRCodeScannerActivity.class); else if (id == R.id.nav_my_account) intent = new Intent(BaseActivity.this, PlayerProfileActivity.class); else if (id == R.id.nav_home) intent = new Intent(BaseActivity.this, MapsActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); // bring up the already opened activity startActivity(intent); return true; } }); } }
92300163f6e6225f07a290ffe0f647afa87ef438
1,041
java
Java
src/attic/attic-java/com/metaos/spot/Spot.java
K0414/metaos
be36c88d3c22fd2f0968edd1fba03c2f2353e4e8
[ "MIT" ]
3
2017-04-10T16:23:32.000Z
2020-07-04T07:59:25.000Z
src/attic/attic-java/com/metaos/spot/Spot.java
K0414/metaos
be36c88d3c22fd2f0968edd1fba03c2f2353e4e8
[ "MIT" ]
null
null
null
src/attic/attic-java/com/metaos/spot/Spot.java
K0414/metaos
be36c88d3c22fd2f0968edd1fba03c2f2353e4e8
[ "MIT" ]
6
2017-10-25T10:12:27.000Z
2020-07-04T07:59:27.000Z
24.209302
72
0.705091
995,335
/* * Copyright 2011 - 2012 * All rights reserved. License and terms according to LICENSE.txt file. * The LICENSE.txt file and this header must be included or referenced * in each piece of code derived from this project. */ package com.metaos.spot; import java.io.*; import java.net.*; import java.text.*; import java.util.*; import java.util.logging.Logger; import com.metaos.market.*; import com.metaos.Instrument; /** * Spot products. */ public abstract class Spot implements Instrument { protected Market market; public void setMarket(final Market market) { this.market = market; } public double getPrice(final Calendar date) { throw new UnsupportedOperationException(); } public double getAcquisitionPrice() { throw new UnsupportedOperationException(); } public double getAcquisitionCosts() { throw new UnsupportedOperationException(); } public double getReleaseCosts(final Calendar date) { throw new UnsupportedOperationException(); } }
923001790b773e8b900f5e85719febfc90bed79e
9,293
java
Java
src/org/araneaframework/uilib/form/control/FloatControl.java
nortal/araneaframework
35c3bab56b3f2c6f12f85299355efa86399b8e75
[ "Apache-2.0" ]
3
2017-06-19T18:36:00.000Z
2018-04-08T07:39:30.000Z
src/org/araneaframework/uilib/form/control/FloatControl.java
nortal/araneaframework
35c3bab56b3f2c6f12f85299355efa86399b8e75
[ "Apache-2.0" ]
null
null
null
src/org/araneaframework/uilib/form/control/FloatControl.java
nortal/araneaframework
35c3bab56b3f2c6f12f85299355efa86399b8e75
[ "Apache-2.0" ]
5
2015-04-28T12:51:22.000Z
2021-07-01T15:18:37.000Z
32.368056
121
0.676893
995,336
/* * Copyright 2006 Webmedia Group Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.araneaframework.uilib.form.control; import java.math.BigDecimal; import java.text.NumberFormat; import org.apache.commons.lang.StringUtils; import org.araneaframework.core.Assert; import org.araneaframework.uilib.form.FilteredInputControl; import org.araneaframework.uilib.form.control.inputfilter.InputFilter; import org.araneaframework.uilib.support.DataType; import org.araneaframework.uilib.support.UiLibMessages; /** * This class represents a text box control that accepts only valid floating-point numbers. * <p> * This class does not support localization. It does not use {@link NumberFormat} class to parse and format * {@link BigDecimal} objects because {@link NumberFormat} would convert {@link BigDecimal} objects into doubles. * <p> * To customize parsing and formatting one could create a subclass of it and override {@link #createBigDecimal(String)} * and {@link #toString(BigDecimal)} methods. To use the subclass in JSPs, also another JSP Tag must be created to use * this implementation and configure validation script. * * @author Jevgeni Kabanov (anpch@example.com) * @author Rein Raudjärv (upchh@example.com) */ public class FloatControl extends BlankStringNullableControl<BigDecimal> implements FilteredInputControl<BigDecimal> { private InputFilter inputFilter; private BigDecimal minValue; private BigDecimal maxValue; private Integer maxScale; /** * Default and empty constructor. */ public FloatControl() {} /** * Makes a <code>BigDecimal</code> control that has both minimum and maximum values and the maximum scale. * * @param minValue The minimum permitted value. * @param maxValue The maximum permitted value. * @param maxScale The maximum permitted scale. */ public FloatControl(BigDecimal minValue, BigDecimal maxValue, Integer maxScale) { setMinValue(minValue); setMaxValue(maxValue); setMaxScale(maxScale); } /** * Makes a <code>BigDecimal</code> control that has both minimum and maximum values. * * @param minValue The minimum permitted value. * @param maxValue The maximum permitted value. */ public FloatControl(BigDecimal minValue, BigDecimal maxValue) { this(minValue, maxValue, null); } /** * Sets the maximum value that this control accepts. If <code>maxValue</code> is <code>null</code> then no maximum * value check will be done. * * @param maxValue The maximum value or <code>null</code>. */ public void setMaxValue(BigDecimal maxValue) { this.maxValue = maxValue; } /** * Sets the minimum value that this control accepts. If <code>minValue</code> is <code>null</code> then no minimum * value check will be done. * * @param minValue The minimum value or <code>null</code>. */ public void setMinValue(BigDecimal minValue) { this.minValue = minValue; } /** * Sets the maximum scale that this control accepts. If <code>maxScale</code> is <code>null</code> then no scale check * will be done. * * @param maxScale The maximum scale or <code>null</code>. */ public void setMaxScale(Integer maxScale) { Assert.isTrue(maxScale == null || maxScale.intValue() >= 0, "Maximum scale cannot be negative"); this.maxScale = maxScale; } /** * Returns the maximum input value allowed or <code>null</code>, if none is specified. * * @return The maximum input value allowed or <code>null</code>, if none is specified. */ public BigDecimal getMaxValue() { return this.maxValue; } /** * Returns the minimum input value allowed or <code>null</code>, if none is specified. * * @return The minimum input value allowed or <code>null</code>, if none is specified. */ public BigDecimal getMinValue() { return this.minValue; } /** * Returns the maximum scale value allowed or <code>null</code>, if none is specified. * * @return The maximum scale value allowed or <code>null</code>, if none is specified. */ public Integer getMaxScale() { return this.maxScale; } public DataType getRawValueType() { return new DataType(BigDecimal.class); } public InputFilter getInputFilter() { return this.inputFilter; } public void setInputFilter(InputFilter inputFilter) { this.inputFilter = inputFilter; } /** * Checks that the submitted data is a valid floating-point number. * */ @Override protected BigDecimal fromRequest(String parameterValue) { BigDecimal result = null; try { result = createBigDecimal(parameterValue); } catch (NumberFormatException e) { addErrorWithLabel(UiLibMessages.NOT_A_NUMBER); } if (getInputFilter() != null && !StringUtils.containsOnly(parameterValue, getInputFilter().getCharacterFilter())) { addErrorWithLabel(getInputFilter().getInvalidInputMessage(), getInputFilter().getCharacterFilter()); } return result; } @Override protected <E extends BigDecimal> String toResponse(E controlValue) { return toString(controlValue); } /** * Converts BigDecimal into String. This method can be overridden in subclasses. * * @param dec The <code>BigDecimal</code> object to convert. * @return The <code>String</code> representation of <code>dec</code> or <code>null</code>, when <code>dec</code> is * <code>null</code>. */ protected String toString(BigDecimal dec) { return dec == null ? null : dec.toString(); } /** * Converts String into BigDecimal. This method can be overrided in subclasses. * * @param str String object * @return BigDecimal object * @throws NumberFormatException <tt>str</tt> is not a valid representation of a BigDecimal */ protected BigDecimal createBigDecimal(String str) throws NumberFormatException { return str == null ? null : new BigDecimal(str); } /** * Checks that the submitted value is in permitted range. */ @Override protected void validateNotNull() { boolean lessThanMin = this.minValue == null ? false : getRawValue().compareTo(this.minValue) == -1; boolean greaterThanMax = this.maxValue == null ? false : getRawValue().compareTo(this.maxValue) == 1; // minimum and maximum permitted values if (lessThanMin || greaterThanMax) { addErrorWithLabel(UiLibMessages.NUMBER_NOT_BETWEEN, this.minValue, this.maxValue); } else if (lessThanMin) { addErrorWithLabel(UiLibMessages.NUMBER_NOT_GREATER, this.minValue); } else if (greaterThanMax) { addErrorWithLabel(UiLibMessages.NUMBER_NOT_LESS, this.maxValue); } // maximum permitted scale if (this.maxScale != null && getRawValue().scale() > this.maxScale.intValue()) { addErrorWithLabel(UiLibMessages.SCALE_NOT_LESS, this.maxScale); } } @Override public ViewModel getViewModel() { return new ViewModel(); } /** * The view model implementation of <code>BigDecimalControl</code>. The view model provides the data for tags to * render the control. * * @author Jevgeni Kabanov (anpch@example.com) */ public class ViewModel extends StringArrayRequestControl<BigDecimal>.ViewModel { private InputFilter inputFilter; private BigDecimal maxValue; private BigDecimal minValue; private Integer maxScale; /** * Takes an outer class snapshot. */ public ViewModel() { this.maxValue = FloatControl.this.getMaxValue(); this.minValue = FloatControl.this.getMinValue(); this.maxScale = FloatControl.this.getMaxScale(); this.inputFilter = FloatControl.this.getInputFilter(); } /** * Returns maximum permitted value. * * @return maximum permitted value. */ public BigDecimal getMaxValue() { return this.maxValue; } /** * Returns minimum permitted value. * * @return minimum permitted value. */ public BigDecimal getMinValue() { return this.minValue; } /** * Returns maximum permitted scale. * * @return maximum permitted scale. */ public Integer getMaxScale() { return this.maxScale; } /** * Provides the input filter settings of this control, or <code>null</code>, if not provided. * * @return The input filter settings, or <code>null</code>, if not provided. */ public InputFilter getInputFilter() { return this.inputFilter; } } }
923001e05d6c9cfa3a946ca46a320c7920b7e0fc
1,109
java
Java
core-console/src/main/java/examples/antlr4/game/Game.java
caveman-frak/java-core
dc03eec37075b369f72063eeea7acd41ce309a5d
[ "Apache-2.0" ]
null
null
null
core-console/src/main/java/examples/antlr4/game/Game.java
caveman-frak/java-core
dc03eec37075b369f72063eeea7acd41ce309a5d
[ "Apache-2.0" ]
null
null
null
core-console/src/main/java/examples/antlr4/game/Game.java
caveman-frak/java-core
dc03eec37075b369f72063eeea7acd41ce309a5d
[ "Apache-2.0" ]
null
null
null
20.537037
93
0.599639
995,337
/** * Copyright 2015, <a href="http://bluegecko.co.uk/java-core">Blue Gecko Limited</a> */ package examples.antlr4.game; import java.util.Map; import java.util.Scanner; public class Game { private final String name; private final Map< String, Integer > points; private final String[][] grid; private int score = 0; public Game( final String name, final Map< String, Integer > points, final String[][] grid ) { this.name = name; this.points = points; this.grid = grid; } public void play() { try (final Scanner in = new Scanner( System.in )) { System.out.println( "You're playing " + name + "." ); while ( true ) { System.out.println( "Where do you want to dig (enter x then y)?" ); final int x = in.nextInt(); final int y = in.nextInt(); if ( grid[x][y] != null ) { final String treasure = grid[x][y]; score += points.get( treasure ); grid[x][y] = null; System.out.println( "You found " + treasure + "! Your score is " + score + "." ); } else { System.out.println( "Sorry, nothing there!" ); } } } } }
9230020ca655af4995cc116e7ed84275cd970fba
1,126
java
Java
app/src/main/java/cn/kiway/mp/adapter/MainPagerAdapter.java
ZHENGZX123/KiwayMarketplace
a7acdeb8dfb3bd0a44043a616ceb5e3cd8d5a716
[ "Apache-2.0" ]
null
null
null
app/src/main/java/cn/kiway/mp/adapter/MainPagerAdapter.java
ZHENGZX123/KiwayMarketplace
a7acdeb8dfb3bd0a44043a616ceb5e3cd8d5a716
[ "Apache-2.0" ]
null
null
null
app/src/main/java/cn/kiway/mp/adapter/MainPagerAdapter.java
ZHENGZX123/KiwayMarketplace
a7acdeb8dfb3bd0a44043a616ceb5e3cd8d5a716
[ "Apache-2.0" ]
null
null
null
25.022222
106
0.726465
995,338
package cn.kiway.mp.adapter; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import java.util.List; import cn.kiway.mp.bean.TitleBean; import cn.kiway.mp.factory.FragmentFactory; import cn.kiway.mp.ui.fragment.AppFragment; public class MainPagerAdapter extends FragmentPagerAdapter { private List<TitleBean.DataBean.ListBean> listBean; private List<AppFragment> appFragments; public MainPagerAdapter(List<TitleBean.DataBean.ListBean> listBean, FragmentManager fragmentManager) { super(fragmentManager); this.listBean = listBean; } @Override public Fragment getItem(int position) { return FragmentFactory.getInstance().getFragment(position, listBean.get(position)); } @Override public int getCount() { return listBean.size(); } @Override public CharSequence getPageTitle(int position) { return listBean.get(position).getName(); } @Override public void notifyDataSetChanged() { super.notifyDataSetChanged(); } }
9230031d0b66f1eccba34db2b7493b46cb5be827
1,319
java
Java
src/main/java/org/springframework/samples/petclinic/model/Donation.java
javivm17/PSG2-2021-G2-21-2
446a69c3ffa9b65d6ac495d33123afcbe13c48b2
[ "Apache-2.0" ]
1
2021-04-13T21:41:10.000Z
2021-04-13T21:41:10.000Z
src/main/java/org/springframework/samples/petclinic/model/Donation.java
gii-is-psg2/PSG2-2021-G2-21
446a69c3ffa9b65d6ac495d33123afcbe13c48b2
[ "Apache-2.0" ]
94
2021-04-09T06:50:19.000Z
2021-05-30T23:51:46.000Z
src/main/java/org/springframework/samples/petclinic/model/Donation.java
javivm17/PSG2-2021-G2-21
446a69c3ffa9b65d6ac495d33123afcbe13c48b2
[ "Apache-2.0" ]
2
2021-03-11T11:14:52.000Z
2021-03-11T11:22:21.000Z
15.517647
60
0.723275
995,339
package org.springframework.samples.petclinic.model; import java.time.LocalDate; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.validation.constraints.NotBlank; import org.springframework.format.annotation.DateTimeFormat; @Entity @Table(name="donations") public class Donation extends BaseEntity{ //atributos @Column(name = "donation_date") @DateTimeFormat(pattern = "yyyy/MM/dd") private LocalDate date; @Column(name = "amount") @NotBlank(message = "Campo requerido") private String amount; //relaciones @JoinColumn(name = "cause_id") @ManyToOne private Cause cause; @JoinColumn(name = "owner_id") @ManyToOne private Owner owner; public LocalDate getDate() { return this.date; } public void setDate(final LocalDate date) { this.date = date; } public String getAmount() { return this.amount; } public void setAmount(final String amount) { this.amount = amount; } public Cause getCause() { return this.cause; } public void setCause(final Cause cause) { this.cause = cause; } public Owner getOwner() { return this.owner; } public void setOwner(final Owner owner) { this.owner = owner; } }
9230037c7ebecb3ca88eb707aabd5a3ce7559abd
1,550
java
Java
src/simpleChat/SimpleChat.java
rub3z/my-java-programs
576a559cf1f4856baeb5fae43ae45a146a265533
[ "MIT" ]
null
null
null
src/simpleChat/SimpleChat.java
rub3z/my-java-programs
576a559cf1f4856baeb5fae43ae45a146a265533
[ "MIT" ]
null
null
null
src/simpleChat/SimpleChat.java
rub3z/my-java-programs
576a559cf1f4856baeb5fae43ae45a146a265533
[ "MIT" ]
null
null
null
28.181818
81
0.554839
995,340
//package simpleChat; /** // * // * @author rubes // */ //import java.io.BufferedReader; //import java.io.InputStreamReader; //import org.jgroups.JChannel; //import org.jgroups.Message; //import org.jgroups.ReceiverAdapter; //import org.jgroups.View; // //public class SimpleChat extends ReceiverAdapter { // // JChannel channel; // String user_name = System.getProperty("user.name", "n/a"); // // private void start() throws Exception { // channel = new JChannel(); // channel.setReceiver(this); // channel.connect("ChatCluster"); // eventLoop(); // channel.close(); // } // // private void eventLoop() { // BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // while (true) { // try { // System.out.print("> "); // System.out.flush(); // String line = in.readLine().toLowerCase(); // if (line.startsWith("quit") || line.startsWith("exit")) { // break; // } // line = "[" + user_name + "] " + line; // Message msg = new Message(null, null, line); // channel.send(msg); // } catch (Exception e) { // } // } // } // // public void viewAccepted(View new_view) { // System.out.println("** view: " + new_view); // } // // public void receive(Message msg) { // System.out.println(msg.getSrc() + ": " + msg.getObject()); // } // // public static void main(String[] args) throws Exception { // new SimpleChat().start(); // } //}
9230039cedfb8d36275e32a2307a0bdc81e85c35
475
java
Java
dk-game-core/src/main/java/cn/laoshini/dk/server/channel/JsonMessageChannelReader.java
fagarine/dangkang
de48d5107172d61df8a37d5f597c1140ac0637e6
[ "Apache-2.0" ]
11
2019-10-22T11:49:23.000Z
2021-06-29T16:27:05.000Z
dk-game-core/src/main/java/cn/laoshini/dk/server/channel/JsonMessageChannelReader.java
fagarine/dangkang
de48d5107172d61df8a37d5f597c1140ac0637e6
[ "Apache-2.0" ]
null
null
null
dk-game-core/src/main/java/cn/laoshini/dk/server/channel/JsonMessageChannelReader.java
fagarine/dangkang
de48d5107172d61df8a37d5f597c1140ac0637e6
[ "Apache-2.0" ]
5
2020-03-21T08:07:07.000Z
2021-02-03T04:09:45.000Z
22.619048
85
0.747368
995,341
package cn.laoshini.dk.server.channel; import io.netty.channel.ChannelHandlerContext; import cn.laoshini.dk.domain.msg.ReqMessage; /** * JSON格式消息到达读取处理 * * @author fagarine */ public class JsonMessageChannelReader implements INettyChannelReader<ReqMessage<?>> { private LastChannelReader delegate = new LastChannelReader(); @Override public void channelRead(ChannelHandlerContext ctx, ReqMessage<?> msg) { delegate.channelRead(ctx, msg); } }
9230046885a5dc71bba9624ae5409f5340bc6f0e
245
java
Java
SampleProject/src/main/java/com/api/javademo/dao/GetAccountDetailsPMRepo.java
chendra0108/ramrepo
fc64372d0a73af2ca7bec64612cd94572e73bf5c
[ "Unlicense" ]
null
null
null
SampleProject/src/main/java/com/api/javademo/dao/GetAccountDetailsPMRepo.java
chendra0108/ramrepo
fc64372d0a73af2ca7bec64612cd94572e73bf5c
[ "Unlicense" ]
1
2022-03-31T20:10:41.000Z
2022-03-31T20:10:41.000Z
SampleProject/src/main/java/com/api/javademo/dao/GetAccountDetailsPMRepo.java
chendra0108/ramrepo
fc64372d0a73af2ca7bec64612cd94572e73bf5c
[ "Unlicense" ]
null
null
null
30.625
92
0.861224
995,342
package com.api.javademo.dao; import org.springframework.data.mongodb.repository.MongoRepository; import com.api.javademo.model.GetAccountDetailsP; public interface GetAccountDetailsPMRepo extends MongoRepository<GetAccountDetailsP,String>{ }
923007337bb43f1420b2cad976e5bda293167943
8,601
java
Java
infra/schema/src/test/java/com/evolveum/midpoint/schema/path/ItemPathCanonicalizationTest.java
valtri/midpoint
7ea177966318dea24346a20af82140e96c6f08b2
[ "Apache-2.0" ]
1
2019-06-25T16:11:25.000Z
2019-06-25T16:11:25.000Z
infra/schema/src/test/java/com/evolveum/midpoint/schema/path/ItemPathCanonicalizationTest.java
valtri/midpoint
7ea177966318dea24346a20af82140e96c6f08b2
[ "Apache-2.0" ]
null
null
null
infra/schema/src/test/java/com/evolveum/midpoint/schema/path/ItemPathCanonicalizationTest.java
valtri/midpoint
7ea177966318dea24346a20af82140e96c6f08b2
[ "Apache-2.0" ]
null
null
null
49.716763
202
0.712126
995,343
/* * Copyright (c) 2010-2015 Evolveum * * 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.evolveum.midpoint.schema.path; import static com.evolveum.midpoint.prism.util.PrismTestUtil.getPrismContext; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import com.evolveum.midpoint.prism.Containerable; import com.evolveum.midpoint.prism.impl.path.CanonicalItemPathImpl; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.MidPointPrismContextFactory; import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.util.exception.SchemaException; import java.io.IOException; import javax.xml.namespace.QName; import org.xml.sax.SAXException; public class ItemPathCanonicalizationTest { public ItemPathCanonicalizationTest() { } @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } @Test public void testCanonicalizationEmpty() { assertCanonical(null, null, ""); assertCanonical(getPrismContext().emptyPath(), null, ""); } private static final String COMMON = "${common}3"; private static final String ICFS = "${icf}1/connector-schema-3"; private static final String ICF = "${icf}1"; private static final String ZERO = "${0}"; private static final String ONE = "${1}"; @Test public void testCanonicalizationSimple() { ItemPath path = UserType.F_NAME; assertCanonical(path, null, "\\" + COMMON + "#name"); } @Test public void testCanonicalizationSimpleNoNs() { ItemPath path = ItemPath.create(UserType.F_NAME.getLocalPart()); assertCanonical(path, null, "\\#name"); assertCanonical(path, UserType.class, "\\" + COMMON + "#name"); } @Test public void testCanonicalizationMulti() { ItemPath path = ItemPath.create(UserType.F_ASSIGNMENT, 1234, AssignmentType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS); assertCanonical(path, null, "\\" + COMMON + "#assignment", "\\" + COMMON + "#assignment\\" + ZERO + "#activation", "\\" + COMMON + "#assignment\\" + ZERO + "#activation\\" + ZERO + "#administrativeStatus"); } @Test public void testCanonicalizationMultiNoNs() { ItemPath path = ItemPath.create(UserType.F_ASSIGNMENT.getLocalPart(), 1234, AssignmentType.F_ACTIVATION.getLocalPart(), ActivationType.F_ADMINISTRATIVE_STATUS.getLocalPart()); assertCanonical(path, null, "\\#assignment", "\\#assignment\\#activation", "\\#assignment\\#activation\\#administrativeStatus"); assertCanonical(path, UserType.class, "\\" + COMMON + "#assignment", "\\" + COMMON + "#assignment\\" + ZERO + "#activation", "\\" + COMMON + "#assignment\\" + ZERO + "#activation\\" + ZERO + "#administrativeStatus"); } @Test public void testCanonicalizationMixedNs() { ItemPath path = ItemPath.create(UserType.F_ASSIGNMENT.getLocalPart(), 1234, AssignmentType.F_EXTENSION, new QName("http://piracy.org/inventory", "store"), new QName("http://piracy.org/inventory", "shelf"), new QName("x"), ActivationType.F_ADMINISTRATIVE_STATUS); assertCanonical(path, null, "\\#assignment", "\\#assignment\\" + COMMON + "#extension", "\\#assignment\\" + COMMON + "#extension\\http://piracy.org/inventory#store", "\\#assignment\\" + COMMON + "#extension\\http://piracy.org/inventory#store\\" + ONE + "#shelf", "\\#assignment\\" + COMMON + "#extension\\http://piracy.org/inventory#store\\" + ONE + "#shelf\\#x", "\\#assignment\\" + COMMON + "#extension\\http://piracy.org/inventory#store\\" + ONE + "#shelf\\#x\\" + ZERO + "#administrativeStatus"); assertCanonical(path, UserType.class, "\\" + COMMON + "#assignment", "\\" + COMMON + "#assignment\\" + ZERO + "#extension", "\\" + COMMON + "#assignment\\" + ZERO + "#extension\\http://piracy.org/inventory#store", "\\" + COMMON + "#assignment\\" + ZERO + "#extension\\http://piracy.org/inventory#store\\" + ONE + "#shelf", "\\" + COMMON + "#assignment\\" + ZERO + "#extension\\http://piracy.org/inventory#store\\" + ONE + "#shelf\\#x", "\\" + COMMON + "#assignment\\" + ZERO + "#extension\\http://piracy.org/inventory#store\\" + ONE + "#shelf\\#x\\" + ZERO + "#administrativeStatus"); } @Test public void testCanonicalizationMixedNs2() { ItemPath path = ItemPath.create(UserType.F_ASSIGNMENT.getLocalPart(), 1234, AssignmentType.F_EXTENSION.getLocalPart(), new QName("http://piracy.org/inventory", "store"), new QName("http://piracy.org/inventory", "shelf"), AssignmentType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS); assertCanonical(path, null, "\\#assignment", "\\#assignment\\#extension", "\\#assignment\\#extension\\http://piracy.org/inventory#store", "\\#assignment\\#extension\\http://piracy.org/inventory#store\\" + ZERO + "#shelf", "\\#assignment\\#extension\\http://piracy.org/inventory#store\\" + ZERO + "#shelf\\" + COMMON + "#activation", "\\#assignment\\#extension\\http://piracy.org/inventory#store\\" + ZERO + "#shelf\\" + COMMON + "#activation\\" + ONE + "#administrativeStatus"); assertCanonical(path, UserType.class, "\\" + COMMON + "#assignment", "\\" + COMMON + "#assignment\\" + ZERO + "#extension", "\\" + COMMON + "#assignment\\" + ZERO + "#extension\\http://piracy.org/inventory#store", "\\" + COMMON + "#assignment\\" + ZERO + "#extension\\http://piracy.org/inventory#store\\" + ONE + "#shelf", "\\" + COMMON + "#assignment\\" + ZERO + "#extension\\http://piracy.org/inventory#store\\" + ONE + "#shelf\\" + ZERO + "#activation", "\\" + COMMON + "#assignment\\" + ZERO + "#extension\\http://piracy.org/inventory#store\\" + ONE + "#shelf\\" + ZERO + "#activation\\" + ZERO + "#administrativeStatus"); } // from IntegrationTestTools private static final String NS_RESOURCE_DUMMY_CONFIGURATION = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.icf.dummy/com.evolveum.icf.dummy.connector.DummyConnector"; private static final QName RESOURCE_DUMMY_CONFIGURATION_USELESS_STRING_ELEMENT_NAME = new QName(NS_RESOURCE_DUMMY_CONFIGURATION ,"uselessString"); @Test public void testCanonicalizationLong() { ItemPath path = ItemPath.create(ResourceType.F_CONNECTOR_CONFIGURATION, SchemaConstants.ICF_CONFIGURATION_PROPERTIES, RESOURCE_DUMMY_CONFIGURATION_USELESS_STRING_ELEMENT_NAME); assertCanonical(path, null, "\\" + COMMON + "#connectorConfiguration", "\\" + COMMON + "#connectorConfiguration\\" + ICFS + "#configurationProperties", "\\" + COMMON + "#connectorConfiguration\\" + ICFS + "#configurationProperties\\" + ICF + "/bundle/com.evolveum.icf.dummy/com.evolveum.icf.dummy.connector.DummyConnector#uselessString"); } private void assertCanonical(ItemPath path, Class<? extends Containerable> clazz, String... representations) { CanonicalItemPathImpl canonicalItemPath = CanonicalItemPathImpl.create(path, clazz, getPrismContext()); System.out.println(path + " => " + canonicalItemPath.asString() + " (" + clazz + ")"); for (int i = 0; i < representations.length; i++) { String c = canonicalItemPath.allUpToIncluding(i).asString(); assertEquals("Wrong string representation of length " + (i+1), representations[i], c); } assertEquals("Wrong string representation ", representations[representations.length-1], canonicalItemPath.asString()); } }
923007421b2b6bc5b69e1e17e7540f0e2aa3d5d7
2,275
java
Java
_src/Chapter05/gdp/src/main/java/com/nilangpatel/web/rest/GenericRestResource.java
paullewallencom/spring-978-1-7883-9041-5
d73f33b9881261aaab51a178ca1ab8d0084f19ba
[ "Apache-2.0" ]
41
2019-02-23T15:25:23.000Z
2022-03-01T23:01:57.000Z
Chapter05/gdp/src/main/java/com/nilangpatel/web/rest/GenericRestResource.java
hocyadav/Spring-5.0-Projects
3ae4f71c060eb56241cfa1a1803d0e5f30457b38
[ "MIT" ]
13
2019-03-05T05:29:40.000Z
2022-03-17T22:27:49.000Z
Chapter05/gdp/src/main/java/com/nilangpatel/web/rest/GenericRestResource.java
hocyadav/Spring-5.0-Projects
3ae4f71c060eb56241cfa1a1803d0e5f30457b38
[ "MIT" ]
63
2019-02-27T06:20:48.000Z
2022-03-29T04:22:24.000Z
39.912281
112
0.781099
995,344
package com.nilangpatel.web.rest; import java.util.List; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; 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 com.codahale.metrics.annotation.Timed; import com.nilangpatel.service.CountryQueryService; import com.nilangpatel.service.CountryService; import com.nilangpatel.service.dto.CountryCriteria; import com.nilangpatel.service.dto.CountryDTO; import com.nilangpatel.web.rest.util.PaginationUtil; @RestController @RequestMapping("/api/open") public class GenericRestResource { private final Logger log = LoggerFactory.getLogger(GenericRestResource.class); private final CountryQueryService countryQueryService; private final CountryService countryService; public GenericRestResource(CountryService countryService, CountryQueryService countryQueryService) { this.countryQueryService = countryQueryService; this.countryService = countryService; } @GetMapping("/search-countries") @Timed public ResponseEntity<List<CountryDTO>> getAllCountriesForGdp(CountryCriteria criteria, Pageable pageable) { log.debug("REST request to get a page of Countries"); Page<CountryDTO> page = countryQueryService.findByCriteria(criteria, pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/open/search-countries"); return ResponseEntity.ok().headers(headers).body(page.getContent()); } @GetMapping("/show-gdp/{id}") @Timed public ResponseEntity<CountryDTO> getCountryDetails(@PathVariable Long id) { log.debug("Get Country Details to show GDP information"); CountryDTO countryDto = new CountryDTO(); Optional<CountryDTO> countryData = countryService.findOne(id); return ResponseEntity.ok().body(countryData.orElse(countryDto)); } }
9230077abb9bf8d6c34e4dac6d8f05bfc6b5beba
355
java
Java
java/numJewelsInStones.java
abhibratasarkar/CodingInterview
ceb399aa50f161dea0daeb238d9e8c1c699fa6a0
[ "Xnet", "RSA-MD", "X11", "CNRI-Python" ]
68
2017-08-15T04:34:25.000Z
2022-01-29T15:50:16.000Z
java/numJewelsInStones.java
abhibratasarkar/CodingInterview
ceb399aa50f161dea0daeb238d9e8c1c699fa6a0
[ "Xnet", "RSA-MD", "X11", "CNRI-Python" ]
null
null
null
java/numJewelsInStones.java
abhibratasarkar/CodingInterview
ceb399aa50f161dea0daeb238d9e8c1c699fa6a0
[ "Xnet", "RSA-MD", "X11", "CNRI-Python" ]
35
2018-01-13T15:20:05.000Z
2022-02-02T10:29:59.000Z
22.1875
54
0.473239
995,345
class Solution { public int numJewelsInStones(String J, String S) { HashSet<Character> set = new HashSet<>(); for(char c:J.toCharArray()) set.add(c); int count = 0; for(char c:S.toCharArray()) if(set.contains(c)) count++; return count; } }
923007b415a03ceedcdd6f6a28d9682fe4e79cf6
6,362
java
Java
dnnl/src/gen/java/org/bytedeco/dnnl/eltwise_forward.java
deinhofer/javacpp-presets
fe5e75d91d10572ab64bf902555d8938891569bd
[ "Apache-2.0" ]
1
2020-02-17T20:55:26.000Z
2020-02-17T20:55:26.000Z
dnnl/src/gen/java/org/bytedeco/dnnl/eltwise_forward.java
deinhofer/javacpp-presets
fe5e75d91d10572ab64bf902555d8938891569bd
[ "Apache-2.0" ]
null
null
null
dnnl/src/gen/java/org/bytedeco/dnnl/eltwise_forward.java
deinhofer/javacpp-presets
fe5e75d91d10572ab64bf902555d8938891569bd
[ "Apache-2.0" ]
null
null
null
53.915254
179
0.668186
995,346
// Targeted by JavaCPP version 1.5.2: DO NOT EDIT THIS FILE package org.bytedeco.dnnl; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.dnnl.global.dnnl.*; /** \} <p> * \addtogroup cpp_api_eltwise Eltwise * A primitive to compute element-wise operations such as rectified linear * unit (ReLU). * * Both forward and backward passes support in-place operation; that is, src * and dst point to the same memory for forward pass, and diff_dst and * diff_src point to the same memory for backward pass. * * \warning Because the original src is required for backward pass, in-place * forward pass in general cannot be applied during training. However, for * some kinds of element-wise operations (namely ReLU with alpha parameter * equals 0), dst and src can be interchangeable for the backward pass, which * enables performance of in-place forward even for training. * * @see \ref dev_guide_eltwise in developer guide * @see \ref c_api_eltwise in \ref c_api * \{ <p> * Element-wise operations for forward propagation. Implements descriptor, * primitive descriptor, and primitive. */ @Namespace("dnnl") @Properties(inherit = org.bytedeco.dnnl.presets.dnnl.class) public class eltwise_forward extends primitive { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public eltwise_forward(Pointer p) { super(p); } /** Native array allocator. Access with {@link Pointer#position(long)}. */ public eltwise_forward(long size) { super((Pointer)null); allocateArray(size); } private native void allocateArray(long size); @Override public eltwise_forward position(long position) { return (eltwise_forward)super.position(position); } /** Initializes an eltwise descriptor for forward propagation using \p * prop_kind (possible values are #dnnl::forward_training and * #dnnl::forward_inference), \p aalgorithm algorithm, memory * descriptor \p data_desc, \p alpha, and \p beta parameters. */ @NoOffset public static class desc extends Pointer { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public desc(Pointer p) { super(p); } public native @ByRef dnnl_eltwise_desc_t data(); public native desc data(dnnl_eltwise_desc_t setter); public desc(prop_kind aprop_kind, algorithm aalgorithm, @Const @ByRef memory.desc src_desc, float alpha/*=0*/, float beta/*=0*/) { super((Pointer)null); allocate(aprop_kind, aalgorithm, src_desc, alpha, beta); } private native void allocate(prop_kind aprop_kind, algorithm aalgorithm, @Const @ByRef memory.desc src_desc, float alpha/*=0*/, float beta/*=0*/); public desc(@Cast("dnnl::prop_kind") int aprop_kind, @Cast("dnnl::algorithm") int aalgorithm, @Const @ByRef memory.desc src_desc, float alpha/*=0*/, float beta/*=0*/) { super((Pointer)null); allocate(aprop_kind, aalgorithm, src_desc, alpha, beta); } private native void allocate(@Cast("dnnl::prop_kind") int aprop_kind, @Cast("dnnl::algorithm") int aalgorithm, @Const @ByRef memory.desc src_desc, float alpha/*=0*/, float beta/*=0*/); } /** Primitive descriptor for eltwise forward propagation. */ public static class primitive_desc extends org.bytedeco.dnnl.primitive_desc { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public primitive_desc(Pointer p) { super(p); } /** Native array allocator. Access with {@link Pointer#position(long)}. */ public primitive_desc(long size) { super((Pointer)null); allocateArray(size); } private native void allocateArray(long size); @Override public primitive_desc position(long position) { return (primitive_desc)super.position(position); } public primitive_desc() { super((Pointer)null); allocate(); } private native void allocate(); public primitive_desc( @Const @ByRef desc desc, @Const @ByRef engine e, @Cast("bool") boolean allow_empty/*=false*/) { super((Pointer)null); allocate(desc, e, allow_empty); } private native void allocate( @Const @ByRef desc desc, @Const @ByRef engine e, @Cast("bool") boolean allow_empty/*=false*/); public primitive_desc( @Const @ByRef desc desc, @Const @ByRef engine e) { super((Pointer)null); allocate(desc, e); } private native void allocate( @Const @ByRef desc desc, @Const @ByRef engine e); public primitive_desc(@Const @ByRef desc desc, @Const @ByRef primitive_attr attr, @Const @ByRef engine e, @Cast("bool") boolean allow_empty/*=false*/) { super((Pointer)null); allocate(desc, attr, e, allow_empty); } private native void allocate(@Const @ByRef desc desc, @Const @ByRef primitive_attr attr, @Const @ByRef engine e, @Cast("bool") boolean allow_empty/*=false*/); public primitive_desc(@Const @ByRef desc desc, @Const @ByRef primitive_attr attr, @Const @ByRef engine e) { super((Pointer)null); allocate(desc, attr, e); } private native void allocate(@Const @ByRef desc desc, @Const @ByRef primitive_attr attr, @Const @ByRef engine e); /** Initializes a primitive descriptor for element-wise operations for * forward propagation from a C primitive descriptor \p pd. */ public primitive_desc(dnnl_primitive_desc pd) { super((Pointer)null); allocate(pd); } private native void allocate(dnnl_primitive_desc pd); /** Queries source memory descriptor. */ public native @ByVal memory.desc src_desc(); /** Queries destination memory descriptor. */ public native @ByVal memory.desc dst_desc(); } public eltwise_forward() { super((Pointer)null); allocate(); } private native void allocate(); public eltwise_forward(@Const @ByRef primitive_desc pd) { super((Pointer)null); allocate(pd); } private native void allocate(@Const @ByRef primitive_desc pd); }
92300842383ae56e1160630935344299e5c115af
315
java
Java
multi-thread/src/main/java/com/futao/basic/learn/thread/imooc/_2JDK的线程池/_2Single.java
FutaoSmile/thread
2fdba3eb6c06a2965b403a7967e4bb7a3fee4f6a
[ "Apache-2.0" ]
null
null
null
multi-thread/src/main/java/com/futao/basic/learn/thread/imooc/_2JDK的线程池/_2Single.java
FutaoSmile/thread
2fdba3eb6c06a2965b403a7967e4bb7a3fee4f6a
[ "Apache-2.0" ]
7
2020-12-21T17:01:23.000Z
2022-02-01T01:01:58.000Z
multi-thread/src/main/java/com/futao/basic/learn/thread/imooc/_2JDK的线程池/_2Single.java
FutaoSmile/java-basic-learn
2fdba3eb6c06a2965b403a7967e4bb7a3fee4f6a
[ "Apache-2.0" ]
null
null
null
18.529412
62
0.698413
995,347
package com.futao.basic.learn.thread.imooc._2JDK的线程池; import java.util.concurrent.Executors; /** * 单个线程的线程池 * 可以保证线程的执行顺序 * * @author dark * Created on 2019/11/12. */ public class _2Single { public static void main(String[] args) { _0TestClass.test(Executors.newSingleThreadExecutor()); } }
92300a2fbc5b4e49690d77568085cb3aea8b3fe4
1,613
java
Java
src/main/java/cz/wake/lobby/listeners/ChatListener.java
RstYcz/craftlobby
5f208da2308b139b1f9b58b6b9b3e14618f64442
[ "MIT" ]
null
null
null
src/main/java/cz/wake/lobby/listeners/ChatListener.java
RstYcz/craftlobby
5f208da2308b139b1f9b58b6b9b3e14618f64442
[ "MIT" ]
2
2020-08-01T21:42:34.000Z
2020-10-19T14:14:42.000Z
src/main/java/cz/wake/lobby/listeners/ChatListener.java
RstYcz/craftlobby
5f208da2308b139b1f9b58b6b9b3e14618f64442
[ "MIT" ]
6
2020-08-01T21:29:36.000Z
2021-10-01T13:36:46.000Z
38.404762
135
0.579665
995,348
package cz.wake.lobby.listeners; import cz.wake.lobby.Main; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.scheduler.BukkitRunnable; import java.util.HashMap; public class ChatListener implements Listener { private HashMap<Player, Double> _time = new HashMap(); HashMap<Player, BukkitRunnable> _cdRunnable = new HashMap(); @EventHandler public void onChat(AsyncPlayerChatEvent e) { final Player p = e.getPlayer(); if (Main.getInstance().at_list.contains(p)) { if (!this._time.containsKey(p)) { this._time.put(p, 60D + 0.1D); Main.getInstance().getSQL().updateAtLastActive(p, System.currentTimeMillis()); Main.getInstance().getSQL().updateAtPoints(p); this._cdRunnable.put(p, new BukkitRunnable() { @Override public void run() { ChatListener.this._time.put(p, Double.valueOf(((Double) ChatListener.this._time.get(p)).doubleValue() - 0.1D)); if (((Double) ChatListener.this._time.get(p)).doubleValue() < 0.01D) { ChatListener.this._time.remove(p); ChatListener.this._cdRunnable.remove(p); cancel(); } } }); ((BukkitRunnable) this._cdRunnable.get(p)).runTaskTimer(Main.getInstance(), 2L, 2L); } } } }